repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
10045125/KJFrameForAndroid
KJFrame/src/org/kymjs/kjframe/ui/ViewInject.java
6172
/* * Copyright (c) 2014,KJFrameForAndroid Open Source Project,张涛. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kymjs.kjframe.ui; import org.kymjs.kjframe.utils.DensityUtils; import org.kymjs.kjframe.utils.StringUtils; import org.kymjs.kjframe.utils.SystemTool; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.drawable.ColorDrawable; import android.view.View; import android.widget.DatePicker; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; /** * 侵入式View的调用工具类 * * @author kymjs(kymjs123@gmail.com) */ public class ViewInject { private ViewInject() { } private static class ClassHolder { private static final ViewInject instance = new ViewInject(); } /** * 类对象创建方法 * * @return 本类的对象 */ public static ViewInject create() { return ClassHolder.instance; } /** * 显示一个toast * * @param msg */ public static void toast(String msg) { try { toast(KJActivityStack.create().topActivity(), msg); } catch (Exception e) { } } /** * 长时间显示一个toast * * @param msg */ public static void longToast(String msg) { try { longToast(KJActivityStack.create().topActivity(), msg); } catch (Exception e) { } } /** * 长时间显示一个toast * * @param msg */ public static void longToast(Context context, String msg) { Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); } /** * 显示一个toast * * @param msg */ public static void toast(Context context, String msg) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } /** * 返回一个退出确认对话框 */ public void getExitDialog(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("确定退出吗?"); builder.setCancelable(false); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); KJActivityStack.create().AppExit(context); } }); builder.create(); builder.show(); builder = null; } /** * 返回一个自定义View对话框 */ public AlertDialog getDialogView(Context cxt, String title, View view) { AlertDialog dialog = new AlertDialog.Builder(cxt).create(); dialog.setMessage(title); dialog.setView(view); dialog.show(); return dialog; } /** * 用于创建PopupWindow封装一些公用属性 */ private PopupWindow createWindow(View view, int w, int h, int argb) { PopupWindow popupView = new PopupWindow(view, w, h); popupView.setFocusable(true); popupView.setBackgroundDrawable(new ColorDrawable(argb)); popupView.setOutsideTouchable(true); return popupView; } /** * 返回一个日期对话框 */ public void getDateDialog(String title, final TextView textView) { final String[] time = SystemTool.getDataTime("yyyy-MM-dd").split("-"); final int year = StringUtils.toInt(time[0], 0); final int month = StringUtils.toInt(time[1], 1); final int day = StringUtils.toInt(time[2], 0); DatePickerDialog dialog = new DatePickerDialog(textView.getContext(), new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { textView.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth); } }, year, month - 1, day); dialog.setTitle(title); dialog.show(); } /** * 返回一个等待信息弹窗 * * @param aty * 要显示弹出窗的Activity * @param msg * 弹出窗上要显示的文字 * @param cancel * dialog是否可以被取消 */ public static ProgressDialog getprogress(Activity aty, String msg, boolean cancel) { // 实例化一个ProgressBarDialog ProgressDialog progressDialog = new ProgressDialog(aty); progressDialog.setMessage(msg); progressDialog.getWindow().setLayout(DensityUtils.getScreenW(aty), DensityUtils.getScreenH(aty)); progressDialog.setCancelable(cancel); // 设置ProgressBarDialog的显示样式 progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.show(); return progressDialog; } }
apache-2.0
pashchuk/Hospital-app
HospitalLibrary/Class1.cs
186
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HospitalLibrary { public class Class1 { } }
apache-2.0
brianrandell/rgroup
src/Before/Rg.Web/Controllers/Api/UserImagesController.cs
2521
using System.Data.Entity; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Web.Http; using Rg.ServiceCore.DbModel; using Rg.ServiceCore.Operations; using Rg.ApiTypes; namespace Rg.Web.Controllers.Api { [Authorize] public class UserImagesController : ApiControllerBase { [Route("api/userimages/{id}.{extension}")] public async Task<HttpResponseMessage> Get(int id, string extension) { if (string.IsNullOrEmpty(extension)) { return new HttpResponseMessage(HttpStatusCode.NotFound); } UserMedia entity = await DbContext.UserMedias .Include(um => um.Data) .SingleOrDefaultAsync(um => um.UserMediaId == id); if (entity == null || entity.Extension != extension) { return new HttpResponseMessage(HttpStatusCode.NotFound); } var content = new ByteArrayContent(entity.Data.ImageData); content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping("x." + extension)); return new HttpResponseMessage { Content = content }; } [Route("api/userimages/{id}.{extension}/Like")] public async Task PostLike(int id, string extension, LikeRequest likeRequest) { HttpStatusCode result = await UserMediaOperations.AddOrRemoveMediaLikeAsync( DbContext, UserId, id, likeRequest); result.ThrowHttpResponseExceptionIfNotSuccessful(); } /// <summary> /// Adds a comment to an album. /// </summary> /// <param name="mediaId"> /// The item to comment on. /// </param> /// <param name="extension"> /// File extension. (Media items are identified as, e.g. 1.jpg, 2.png, etc.) /// </param> /// <param name="commentRequest"> /// Details of the comment to add. /// </param> /// <returns></returns> [Route("api/userimages/{mediaId}.{extension}/Comment")] public async Task PostComment(int mediaId, string extension, CommentRequest commentRequest) { HttpStatusCode result = await UserMediaOperations.AddMediaCommentAsync( DbContext, UserId, mediaId, commentRequest); result.ThrowHttpResponseExceptionIfNotSuccessful(); } } }
apache-2.0
lijinfengworm/ant-design-reactjs
src/schema/faultData.dataSchema.js
3040
import React from 'react'; import {Icon} from 'antd'; import {Link} from 'react-router'; // 定义某个表的dataSchema, 结构跟querySchema很相似, 见下面的例子 // 注意: 所有的key不能重复 // 这个配置不只决定了table的schema, 也包括用于新增/删除的表单的schema module.exports = [ { key: 'id', // 传递给后端的key title: 'ID', // 前端显示的名字 // 其实dataType对前端的意义不大, 更重要的是生成后端接口时要用到, 所以要和DB中的类型一致 // 对java而言, int/float/varchar/datetime会映射为Long/Double/String/Date dataType: 'int', // 数据类型, 目前可用的: int/float/varchar/datetime // 这一列是否是主键? // 如果不指定主键, 不能update/delete, 但可以insert // 如果指定了主键, insert/update时不能填写主键的值; // 只有int/varchar可以作为主键, 但是实际上主键一般都是自增id primary: true, // 可用的showType: normal/radio/select/checkbox/multiSelect/textarea/image/file/cascader showType: 'normal', // 默认是normal, 就是最普通的输入框 showInTable: true, // 这一列是否要在table中展示, 默认true disabled: false, // 表单中这一列是否禁止编辑, 默认false // 扩展接口, 决定了这一列渲染成什么样子 render: (text, record) => text, }, { key: 'province', title: '省份', dataType: 'varchar', // 对于普通的input框, 可以设置addonBefore/addonAfter placeholder: '请输入用户名', addonBefore: (<Icon type="user"/>), addonAfter: '切克闹', defaultValue: 'foolbear', // 默认值, 只在insert时生效, update时不生效 }, { key: 'machine', title: '设备编号', dataType: 'varchar', }, { key: 'machine_type', title: '设备类型', dataType: 'varchar', }, { key: 'machine_count', title: '纱支', dataType: 'varchar', }, { key: 'fault_point', title: '点位', dataType: 'varchar', }, { key: 'fault_code', title: '故障码', dataType: 'varchar', }, { key: 'fault_msg', title: '故障描述', dataType: 'varchar', showType: 'image', // 后端必须提供图片上传接口 showInTable: false, }, { key: 'fault_type', title: '故障类型', dataType: 'varchar', defaultValue: '个人简介个人简介个人简介', }, { key: 'fault_level', title: '级别', dataType: 'varchar', max: 99, min: 9, }, { key: 'fault_print', title: '是否生成工单', dataType: 'float', max: 9.9, placeholder: '哈哈', width: 50, }, { // 这个key是我预先定义好的, 注意不要冲突 key: 'singleRecordActions', title: '操作', // 列名 actions: [ { // 这样写似乎和Link组件是一样的效果 render: (record) => <a href={`/#/fault_detail?id=${record.id}`}>{'查看详情'}</a>, }, ], }, ];
apache-2.0
wvanderdeijl/oracle-cci-sonarqube
src/main/java/org/jdev/emg/sonar/cci/CCIXmlMetricsDecorator.java
4597
/* * Sonar CCI Plugin * Copyright (C) 2015 Whitehorses * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.jdev.emg.sonar.cci; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.Decorator; import org.sonar.api.batch.DecoratorContext; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.resources.Project; import org.sonar.api.resources.ProjectFileSystem; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Resource; import org.sonar.api.utils.SonarException; /** * Class based on the JavaMetricsDecorator. For handling * @see org.adf.emg.sonar.ojaudit.XmlMetricsDecorator */ public class CCIXmlMetricsDecorator implements Decorator { private static final Logger LOG = LoggerFactory.getLogger(CCIXmlMetricsDecorator.class); @Override public void decorate(Resource resource, DecoratorContext context) { if (!Qualifiers.isFile(resource)) { return; } ProjectFileSystem fileSystem = context.getProject().getFileSystem(); File file = lookup(resource, fileSystem); try { if (readFirstByte(file) != '<') { return; } } catch (IOException e) { throw new SonarException(e); } int numCommentLines; CCICountCommentParser commentCounter = new CCICountCommentParser(); try { numCommentLines = commentCounter.countLinesOfComment(FileUtils.openInputStream(file)); if (numCommentLines == -1) { return; } } catch (IOException e) { throw new SonarException(e); } LineIterator iterator = null; int numLines = 0; int numBlankLines = 0; try { Charset charset = fileSystem.getSourceCharset(); iterator = charset == null ? FileUtils.lineIterator(file) : FileUtils.lineIterator(file, charset.name()); while (iterator.hasNext()) { String line = iterator.nextLine(); numLines++; if (line.trim().isEmpty()) { numBlankLines++; } } } catch (IOException e) { LOG.warn("error reading " + file + " to collect metrics", e); } finally { LineIterator.closeQuietly(iterator); } context.saveMeasure(CoreMetrics.LINES, (double) numLines); // Lines context.saveMeasure(CoreMetrics.COMMENT_LINES, (double) numCommentLines); // Non Commenting Lines of Code context.saveMeasure(CoreMetrics.NCLOC, (double) numLines - numBlankLines - numCommentLines); // Comment Lines } private File lookup(Resource resource, ProjectFileSystem filesys) { return filesys.resolvePath(resource.getLongName()); } private byte readFirstByte(File file) throws IOException { byte[] buffer = new byte[1]; int len = IOUtils.read(FileUtils.openInputStream(file), buffer); return len == 1 ? buffer[0] : null; } /** * Determines if this Sensor should run for a given project. * @param project Project * @return <code>true</code> if the supplied project uses cci as language, otherwise <code>false</code> * @see CCIPlugin#LANGUAGE_KEY */ @Override public boolean shouldExecuteOnProject(Project project) { boolean retval = CCIPlugin.LANGUAGE_KEY.equals(project.getLanguageKey()); if (!retval) { LOG.debug(this.getClass().getName() + " not executing on project with language " + project.getLanguageKey()); } return retval; } }
apache-2.0
daileyet/openlibs.binder
src/main/java/com/openthinks/libs/binder/support/SupportUtilities.java
457
package com.openthinks.libs.binder.support; public class SupportUtilities { public static String convertToString(Object object) { String val = null; if (object == null) val = ""; else val = object.toString(); return val; } public static boolean equals(Object oldVal, Object newVal) { if (oldVal == newVal) return true; if (oldVal != null && oldVal.equals(newVal)) return true; return false; } }
apache-2.0
shivangi1015/incubator-carbondata
processing/src/main/java/org/apache/carbondata/processing/newflow/steps/DummyClassForTest.java
3291
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.processing.newflow.steps; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.carbondata.core.datastore.row.CarbonRow; import org.apache.carbondata.processing.newflow.AbstractDataLoadProcessorStep; import org.apache.carbondata.processing.newflow.CarbonDataLoadConfiguration; import org.apache.carbondata.processing.newflow.DataField; import org.apache.carbondata.processing.newflow.exception.CarbonDataLoadingException; import org.apache.carbondata.processing.newflow.row.CarbonRowBatch; /** * DummyClassForTest */ public class DummyClassForTest extends AbstractDataLoadProcessorStep { private ExecutorService executorService; public DummyClassForTest(CarbonDataLoadConfiguration configuration, AbstractDataLoadProcessorStep child) { super(configuration, child); } @Override public DataField[] getOutput() { return child.getOutput(); } @Override public void initialize() throws CarbonDataLoadingException { } @Override protected String getStepName() { return "Dummy"; } @Override public Iterator<CarbonRowBatch>[] execute() throws CarbonDataLoadingException { Iterator<CarbonRowBatch>[] iterators = child.execute(); this.executorService = Executors.newFixedThreadPool(iterators.length); try { for (int i = 0; i < iterators.length; i++) { executorService.submit(new DummyThread(iterators[i])); } executorService.shutdown(); executorService.awaitTermination(2, TimeUnit.DAYS); } catch (Exception e) { throw new CarbonDataLoadingException("Problem while shutdown the server ", e); } return null; } @Override protected CarbonRow processRow(CarbonRow row) { return null; } } /** * This thread iterates the iterator */ class DummyThread implements Callable<Void> { private Iterator<CarbonRowBatch> iterator; public DummyThread(Iterator<CarbonRowBatch> iterator) { this.iterator = iterator; } @Override public Void call() throws CarbonDataLoadingException { try { while (iterator.hasNext()) { CarbonRowBatch batch = iterator.next(); while (batch.hasNext()) { CarbonRow row = batch.next(); // do nothing } } } catch (Exception e) { throw new CarbonDataLoadingException(e); } return null; } }
apache-2.0
hailongren/AndroidTraining
app/src/test/java/com/bearapp/androidtraining/ExampleUnitTest.java
405
package com.bearapp.androidtraining; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
googleapis/nodejs-translate
samples/test/quickstart.test.js
1125
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const {assert} = require('chai'); const {describe, it} = require('mocha'); const cp = require('child_process'); const path = require('path'); const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'}); const cwd = path.join(__dirname, '..'); const projectId = process.env.GCLOUD_PROJECT; describe('quickstart sample tests', () => { it('should translate a string', async () => { const stdout = execSync(`node quickstart ${projectId}`, {cwd}); assert.include(stdout, 'Translation: Привет'); }); });
apache-2.0
armandosrz/UdacityNanoMachine
capstone_project/Conniption/src/mergeq.py
677
import resource from itertools import chain, product import pickle ''' This file takes all the pickle objects created during the simulations and puts them all together for a better extraction. ''' letters = {'h', 'c', 's', 'r' ,'f'} q_letters = {'q', 'm'} letters = map(''.join, chain(product(letters, q_letters), product(q_letters, letters))) comb = map(lambda p: '../log_reinforce/' + ''.join(p) + '.pkl', letters) #print (len(list(comb))) data = [] for f in comb: try: data += pickle.load(open(f, 'rb')) print(f) except: continue out = open('../log_reinforce/merged_qlearn_5evals.pkl', 'wb') pickle.dump(data, out) print (list(comb))
apache-2.0
EmeraldSequoia/JNI-gen
jni/ESJNI.cpp
5573
// // ESJNI.cpp // // Copyright Emerald Sequoia LLC 2011. // #include "ESJNI.hpp" #include "ESJNIDefs.hpp" #include "ESErrorReporter.hpp" ESJNIBase::ESJNIBase() : _retained(false), _javaObject(NULL) {} ESJNIBase::ESJNIBase(jobject jobj) : _retained(false), _javaObject(jobj) { } ESJNIBase::ESJNIBase(jobject jobj, bool retained) : _retained(retained), _javaObject(jobj) { } ESJNIBase::ESJNIBase(const ESJNIBase &other) : _retained(other._retained), _javaObject(other._javaObject) { } void ESJNIBase::release(JNIEnv *jniEnv) { ESAssert(_retained); if (_retained) { ESAssert(_javaObject); jniEnv->DeleteGlobalRef(_javaObject); _javaObject = NULL; _retained = false; // Note that this does nothing to other glue-handle objects which might be pointed at the retained ptr } } void ESJNIBase::DeleteLocalRef(JNIEnv *jniEnv) { ESAssert(!_retained); ESAssert(_javaObject); jniEnv->DeleteLocalRef(_javaObject); _javaObject = NULL; } ESJNI_java_lang_String::ESJNI_java_lang_String() : _esStringInitialized(false), _javaStringRetained(false), _javaString(NULL) { } ESJNI_java_lang_String::ESJNI_java_lang_String(jobject js) : _esStringInitialized(false), _javaStringRetained(false), _javaString((jstring)js) { } ESJNI_java_lang_String::ESJNI_java_lang_String(jstring js) : _esStringInitialized(false), _javaStringRetained(false), _javaString(js) { } ESJNI_java_lang_String::ESJNI_java_lang_String(const std::string &str) : _esStringInitialized(true), _esString(str), _javaStringRetained(false), _javaString(NULL) { } ESJNI_java_lang_String::ESJNI_java_lang_String(const char *str) : _esStringInitialized(true), _esString(str), _javaStringRetained(false), _javaString(NULL) { } ESJNI_java_lang_String::ESJNI_java_lang_String(const ESJNI_java_lang_String &other) : _esStringInitialized(other._esStringInitialized), _esString(other._esString), _javaStringRetained(false), _javaString(other._javaString) { ESAssert(!other._javaStringRetained); } ESJNI_java_lang_String::~ESJNI_java_lang_String() { ESAssert(!_javaStringRetained); // Can't release without jniEnv } jobject ESJNI_java_lang_String::toJObject(JNIEnv *jniEnv) { if (_javaString) { return _javaString; } if (_esStringInitialized) { return (jobject)jniEnv->NewStringUTF(_esString.c_str()); } return NULL; } jstring ESJNI_java_lang_String::toJString(JNIEnv *jniEnv) { if (_javaString) { return _javaString; } if (_esStringInitialized) { return jniEnv->NewStringUTF(_esString.c_str()); } return NULL; } void ESJNI_java_lang_String::retainJString(JNIEnv *jniEnv) { ESAssert(!_javaStringRetained); if (_javaString) { _javaString = (jstring)jniEnv->NewGlobalRef(_javaString); _javaStringRetained = true; } else if (_esStringInitialized) { _javaString = (jstring)jniEnv->NewGlobalRef((jobject)jniEnv->NewStringUTF(_esString.c_str())); _javaStringRetained = true; } else { ESAssert(false); // Nothing to retain } } void ESJNI_java_lang_String::releaseJString(JNIEnv *jniEnv) { ESAssert(_javaStringRetained); ESAssert(_javaString); jniEnv->DeleteGlobalRef(_javaString); _javaString = NULL; } std::string ESJNI_java_lang_String::toESString(JNIEnv *jniEnv) { if (!_esStringInitialized) { if (_javaString) { const char *utf = jniEnv->GetStringUTFChars(_javaString, NULL); _esString = utf; _esStringInitialized = true; jniEnv->ReleaseStringUTFChars(_javaString, utf); } else { return ""; } } ESAssert(_esStringInitialized); return _esString; } ESJNI_java_lang_String & ESJNI_java_lang_String::operator=(ESJNI_java_lang_String &other) { ESAssert(!_javaString); // One-time use for now _javaString = other._javaString; _javaStringRetained = other._javaStringRetained; _esString = other._esString; _esStringInitialized = other._esStringInitialized; return *this; } ESJNI_java_lang_String & ESJNI_java_lang_String::operator=(const std::string &str) { ESAssert(!_javaString); // One-time use for now _esStringInitialized = true; _esString = str; _javaString = NULL; _javaStringRetained = false; return *this; } ESJNI_java_lang_String & ESJNI_java_lang_String::operator=(const char *str) { ESAssert(!_javaString); // One-time use for now _esStringInitialized = true; _esString = str; _javaString = NULL; _javaStringRetained = false; return *this; } ESJNI_java_lang_String & ESJNI_java_lang_String::operator=(jstring js) { ESAssert(!_javaString); // One-time use for now _esStringInitialized = false; _javaString = js; _javaStringRetained = false; return *this; } ESJNI_java_lang_String & ESJNI_java_lang_String::operator=(jobject js) { ESAssert(!_javaString); // One-time use for now _esStringInitialized = false; _javaString = (jstring)js; _javaStringRetained = false; return *this; } ESJNI_java_lang_CharSequence ESJNI_java_lang_String::toCharSequence(JNIEnv *jniEnv) { if (_javaString) { return ESJNI_java_lang_CharSequence(_javaString, _javaStringRetained); // a String isa CharSequence } else { return ESJNI_java_lang_CharSequence(toJString(jniEnv), _javaStringRetained); // a String isa CharSequence } }
apache-2.0
sllexa/junior
chapter_003/src/main/java/ru/job4j/lite/user/SortUser.java
1396
package ru.job4j.lite.user; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Class SortUser. * * @author Aleksey Slivko * @version $1.0$ * @since 22.06.2018 */ public class SortUser { /** * Convert List of users to TreeSet and sort users by age. * @param list of users. * @return TreeSet of users. */ public Set<User> sort(List<User> list) { return new TreeSet<>(list); } /** * Sort List by name length. * @param list of users. * @return - sorted list of users. */ public List<User> sortNameLength(List<User> list) { list.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return Integer.compare(o1.getName().length(), o2.getName().length()); } }); return list; } /** * Sort List by all fields. * @param list of user. * @return - sorted list of user. */ public List<User> sortByAllFields(List<User> list) { list.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { int rsl = o1.getName().compareTo(o2.getName()); return rsl != 0 ? rsl : Integer.compare(o1.getAge(), o2.getAge()); } }); return list; } }
apache-2.0
SocialFarm/camarilla
src/main/java/org/socialfarm/camarilla/CamarillaServer.java
1571
package org.socialfarm.camarilla; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.http.server.NetworkListener; import org.glassfish.grizzly.threadpool.ThreadPoolConfig; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import java.net.URI; /** * Hello world! * */ public class CamarillaServer { public static void main( String[] args ) { System.out.println( "Starting " + args ); // TODO : parse args or config to get port etc final URI restEndPoint = URI.create( String.format("http://0.0.0.0:%d/", 3242) ) ; final ResourceConfig resourceConfig = new ResourceConfig( CamarillaEndPoints.class ) ; final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(restEndPoint, resourceConfig); ThreadPoolConfig threadPoolConfig = ThreadPoolConfig.defaultConfig() .setPoolName( "camarilla-service-threads") .setCorePoolSize(256) .setMaxPoolSize(65535) ; NetworkListener listener = httpServer.getListeners().iterator().next(); listener.getTransport().setWorkerThreadPoolConfig(threadPoolConfig); try { System.out.println( "Serving requests, press any key to exit" ); System.in.read() ; } catch (Exception ex) { ex.printStackTrace(); } finally { httpServer.shutdownNow(); } System.out.println( "Done " + args ); } }
apache-2.0
bh1xuw/rust-rocks
rocks-sys/rocks/util.cc
1571
#include <string> #include <vector> #include "rocksdb/slice.h" #include "rocksdb/version.h" #include "rocks/ctypes.hpp" using namespace ROCKSDB_NAMESPACE; extern "C" { /* version */ int rocks_version_major() { return ROCKSDB_MAJOR; } int rocks_version_minor() { return ROCKSDB_MINOR; } int rocks_version_patch() { return ROCKSDB_PATCH; } size_t cxx_vector_slice_size(const void* list) { auto p = reinterpret_cast<const std::vector<Slice>*>(list); return p->size(); } const void* cxx_vector_slice_nth(const void* list, size_t n) { auto p = reinterpret_cast<const std::vector<Slice>*>(list); return (void*)&p->at(n); } void cxx_string_assign(cxx_string_t* s, const char* p, size_t len) { auto str = reinterpret_cast<std::string*>(s); str->assign(p, len); } const char* cxx_string_data(const cxx_string_t* s) { auto str = reinterpret_cast<const std::string*>(s); return str->data(); } size_t cxx_string_size(const cxx_string_t* s) { auto str = reinterpret_cast<const std::string*>(s); return str->size(); } void cxx_string_destroy(cxx_string_t* s) { delete reinterpret_cast<std::string*>(s); } cxx_string_vector_t* cxx_string_vector_create() { return new cxx_string_vector_t; } void cxx_string_vector_destory(cxx_string_vector_t* v) { delete v; } size_t cxx_string_vector_size(cxx_string_vector_t* v) { return v->rep.size(); } const char* cxx_string_vector_nth(cxx_string_vector_t* v, size_t index) { return v->rep[index].data(); } size_t cxx_string_vector_nth_size(cxx_string_vector_t* v, size_t index) { return v->rep[index].size(); } }
apache-2.0
esp/esp-net
src/Esp.Net/Meta/IEventObservationRegistrar.cs
809
#region copyright // Copyright 2015 Dev Shop Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace Esp.Net.Meta { internal interface IEventObservationRegistrar { void IncrementRegistration<TEvent>(); void DecrementRegistration<TEvent>(); } }
apache-2.0
OleksandrKulchytskyi/Agile
Server/WebSignalR/WebSignalR.DataAccess/Migrations/201403170824102_VoteItem_Opened.Designer.cs
838
// <auto-generated /> namespace WebSignalR.DataAccess.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.0.2-21211")] public sealed partial class VoteItem_Opened : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(VoteItem_Opened)); string IMigrationMetadata.Id { get { return "201403170824102_VoteItem_Opened"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
apache-2.0
sdw2330976/Research-jetty-9.2.5
jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/generator/DataFrameGeneratorTest.java
3722
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.spdy.generator; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.nio.ByteBuffer; import java.util.concurrent.ThreadLocalRandom; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.spdy.api.ByteBufferDataInfo; import org.eclipse.jetty.spdy.api.DataInfo; import org.eclipse.jetty.spdy.frames.DataFrame; import org.eclipse.jetty.util.BufferUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DataFrameGeneratorTest { private int increment = 1024; private int streamId = 1; private ArrayByteBufferPool bufferPool; private DataFrameGenerator dataFrameGenerator; private ByteBuffer headerBuffer = ByteBuffer.allocate(DataFrame.HEADER_LENGTH); @Before public void setUp() { bufferPool = new ArrayByteBufferPool(64, increment, 8192); dataFrameGenerator = new DataFrameGenerator(bufferPool); headerBuffer.putInt(0, streamId & 0x7F_FF_FF_FF); } @Test public void testGenerateSmallFrame() { int bufferSize = 256; generateFrame(bufferSize); } @Test public void testGenerateFrameWithBufferThatEqualsBucketSize() { int bufferSize = increment; generateFrame(bufferSize); } @Test public void testGenerateFrameWithBufferThatEqualsBucketSizeMinusHeaderLength() { int bufferSize = increment - DataFrame.HEADER_LENGTH; generateFrame(bufferSize); } private void generateFrame(int bufferSize) { ByteBuffer byteBuffer = createByteBuffer(bufferSize); ByteBufferDataInfo dataInfo = new ByteBufferDataInfo(byteBuffer, true); fillHeaderBuffer(bufferSize); ByteBuffer dataFrameBuffer = dataFrameGenerator.generate(streamId, bufferSize, dataInfo); assertThat("The content size in dataFrameBuffer matches the buffersize + header length", dataFrameBuffer.limit(), is(bufferSize + DataFrame.HEADER_LENGTH)); byte[] headerBytes = new byte[DataFrame.HEADER_LENGTH]; dataFrameBuffer.get(headerBytes, 0, DataFrame.HEADER_LENGTH); assertThat("Header bytes are prepended", headerBytes, is(headerBuffer.array())); } private ByteBuffer createByteBuffer(int bufferSize) { byte[] bytes = new byte[bufferSize]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer byteBuffer = bufferPool.acquire(bufferSize, false); BufferUtil.flipToFill(byteBuffer); byteBuffer.put(bytes); BufferUtil.flipToFlush(byteBuffer, 0); return byteBuffer; } private void fillHeaderBuffer(int bufferSize) { headerBuffer.putInt(4, bufferSize & 0x00_FF_FF_FF); headerBuffer.put(4, DataInfo.FLAG_CLOSE); } }
apache-2.0
mikeb01/Aeron
aeron-client/src/main/java/io/aeron/exceptions/ClientTimeoutException.java
1227
/* * Copyright 2014-2022 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.exceptions; /** * Client timeout event received from the driver for this client. * <p> * This is likely to happen as a result of a GC pause that is longer than the {@code aeron.client.liveness.timeout} * setting. */ public class ClientTimeoutException extends TimeoutException { private static final long serialVersionUID = 4085394356371474876L; /** * Construct the client timeout exception with detail message. * * @param message detail for the exception. */ public ClientTimeoutException(final String message) { super(message, Category.FATAL); } }
apache-2.0
wolabs/womano
main/java/com/culabs/unicomportal/model/db/DBNats.java
15306
package com.culabs.unicomportal.model.db; import java.util.Date; public class DBNats { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.created_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Date created_at; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.updated_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Date updated_at; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.name * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.admin_state_up * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Boolean admin_state_up; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.publicip_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer publicip_id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.type * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String type; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.internet_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String internet_id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.protocol * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String protocol; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.fixed_ip * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String fixed_ip; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.source_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer source_port; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.destination_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer destination_port; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.nat_uuid * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String nat_uuid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.status * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private String status; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.job_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer job_id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.owner_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer owner_id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column nats.creator_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ private Integer creator_id; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.id * * @return the value of nats.id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.id * * @param id the value for nats.id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.created_at * * @return the value of nats.created_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Date getCreated_at() { return created_at; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.created_at * * @param created_at the value for nats.created_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setCreated_at(Date created_at) { this.created_at = created_at; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.updated_at * * @return the value of nats.updated_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Date getUpdated_at() { return updated_at; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.updated_at * * @param updated_at the value for nats.updated_at * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.name * * @return the value of nats.name * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.name * * @param name the value for nats.name * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setName(String name) { this.name = name; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.admin_state_up * * @return the value of nats.admin_state_up * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Boolean getAdmin_state_up() { return admin_state_up; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.admin_state_up * * @param admin_state_up the value for nats.admin_state_up * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setAdmin_state_up(Boolean admin_state_up) { this.admin_state_up = admin_state_up; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.publicip_id * * @return the value of nats.publicip_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getPublicip_id() { return publicip_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.publicip_id * * @param publicip_id the value for nats.publicip_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setPublicip_id(Integer publicip_id) { this.publicip_id = publicip_id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.type * * @return the value of nats.type * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getType() { return type; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.type * * @param type the value for nats.type * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setType(String type) { this.type = type; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.internet_id * * @return the value of nats.internet_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getInternet_id() { return internet_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.internet_id * * @param internet_id the value for nats.internet_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setInternet_id(String internet_id) { this.internet_id = internet_id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.protocol * * @return the value of nats.protocol * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getProtocol() { return protocol; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.protocol * * @param protocol the value for nats.protocol * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.fixed_ip * * @return the value of nats.fixed_ip * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getFixed_ip() { return fixed_ip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.fixed_ip * * @param fixed_ip the value for nats.fixed_ip * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setFixed_ip(String fixed_ip) { this.fixed_ip = fixed_ip; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.source_port * * @return the value of nats.source_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getSource_port() { return source_port; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.source_port * * @param source_port the value for nats.source_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setSource_port(Integer source_port) { this.source_port = source_port; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.destination_port * * @return the value of nats.destination_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getDestination_port() { return destination_port; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.destination_port * * @param destination_port the value for nats.destination_port * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setDestination_port(Integer destination_port) { this.destination_port = destination_port; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.nat_uuid * * @return the value of nats.nat_uuid * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getNat_uuid() { return nat_uuid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.nat_uuid * * @param nat_uuid the value for nats.nat_uuid * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setNat_uuid(String nat_uuid) { this.nat_uuid = nat_uuid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.status * * @return the value of nats.status * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public String getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.status * * @param status the value for nats.status * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setStatus(String status) { this.status = status; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.job_id * * @return the value of nats.job_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getJob_id() { return job_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.job_id * * @param job_id the value for nats.job_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setJob_id(Integer job_id) { this.job_id = job_id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.owner_id * * @return the value of nats.owner_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getOwner_id() { return owner_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.owner_id * * @param owner_id the value for nats.owner_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setOwner_id(Integer owner_id) { this.owner_id = owner_id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column nats.creator_id * * @return the value of nats.creator_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public Integer getCreator_id() { return creator_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column nats.creator_id * * @param creator_id the value for nats.creator_id * * @mbggenerated Tue May 26 15:53:09 CST 2015 */ public void setCreator_id(Integer creator_id) { this.creator_id = creator_id; } }
apache-2.0
JotaAlava/Sputnik
Sputnik/Commands/NotExistCommand.cs
1721
using System; using OpenQA.Selenium; using Sputnik.Selenium; using NUnit.Framework; namespace Sputnik.Commands { public class NotExistCommand { /// <summary> /// Will check if the specified CssPath returns an element that currently does not exist on the page /// </summary> /// <param name="cssPath">The csspath of the element we want to check for</param> /// <returns>False if the element was found, true if the element was not found</returns> public void ByCssPath(string cssPath) { var element = Driver.Instance.FindElements(By.CssSelector(cssPath)); Assert.True(element.Count == 0, "Element exists!"); } /// <summary> /// Will check if the specified Id returns an element that currently does not exist on the page /// </summary> /// <param name="chosenSelectorById"></param> /// <param name="valueToCompareWith"></param> public void ById(string chosenSelectorById) { var element = Driver.Instance.FindElements(By.Id(chosenSelectorById)); Assert.True(element.Count == 0, "Element exists!"); } /// <summary> /// Will check if the specified jQuery selector returns an element that currently does not exist on the page /// </summary> /// <param name="chosenSelectorByJquery"></param> /// <returns></returns> public bool ByJQuery(string chosenSelectorByJquery) { var jsExecutor = Driver.Instance as IJavaScriptExecutor; var elem = jsExecutor.ExecuteScript(chosenSelectorByJquery); return elem.ToString() != string.Empty; } } }
apache-2.0
hambroz/Orleans.Bus
Source/Bus/Properties/AssemblyInfo.cs
223
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Orleans.Bus")] [assembly: InternalsVisibleTo("Orleans.Bus.Observables")] [assembly: InternalsVisibleTo("Orleans.Bus.Tests")]
apache-2.0
bitExpert/adrenaline
tests/bitExpert/Adrenaline/Responder/Resolver/NegotiatingResponderResolverMiddlewareUnitTest.php
5609
<?php /** * This file is part of the Adrenaline framework. * * (c) bitExpert AG * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types = 1); namespace bitExpert\Adrenaline\Responder\Resolver; use bitExpert\Adrenaline\Accept\ContentNegotiationManager; use bitExpert\Adrenaline\Domain\DomainPayload; use bitExpert\Adroit\Responder\Responder; use bitExpert\Adroit\Responder\Resolver\ResponderResolver; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response; use Zend\Diactoros\ServerRequest; use Psr\Http\Message\ResponseInterface; /** * Unit test for {@link \bitExpert\Adrenaline\Responder\Resolver\NegotiatingResponderResolverMiddleware}. */ class NegotiatingResponderResolverMiddlewareUnitTest extends \PHPUnit_Framework_TestCase { /** * @var ServerRequestInterface */ protected $request; /** * @var \bitExpert\Adrenaline\Domain\DomainPayload */ protected $domainPayload; /** * @var ContentNegotiationManager */ protected $manager; /** * @var ResponderResolver */ protected $resolver1; /** * @var ResponderResolver */ protected $resolver2; /** * @var Responder */ protected $notAcceptedResponder; /** * @var NegotiatingResponderResolverMiddleware */ protected $middleware; /** * @see PHPUnit_Framework_TestCase::setUp() */ protected function setUp() { parent::setUp(); $this->request = $this->createMock(ServerRequestInterface::class); $this->response = new Response(); $this->domainPayload = new DomainPayload(''); $this->manager = $this->getMockBuilder(ContentNegotiationManager::class) ->disableOriginalConstructor() ->getMock(); $this->resolver1 = $this->createMock(ResponderResolver::class); $this->resolver2 = $this->createMock(ResponderResolver::class); $mockedResolver = $this->getMockBuilder(ResponderResolver::class) ->disableOriginalConstructor() ->setMethods(['resolve']) ->getMock(); $mockedResolver->expects($this->any()) ->method('resolve') ->will($this->returnValue(null)); $this->middleware = new NegotiatingResponderResolverMiddleware( [ 'text/html' => $this->resolver1, 'text/vcard' => [ new \stdClass(), new \stdClass() ], 'application/json' => [ $mockedResolver, $this->resolver2, $this->resolver2 ] ], 'domainPayload', Responder::class, $this->manager ); } /** * @test * @expectedException \bitExpert\Adroit\Resolver\ResolveException */ public function noBestMatchWillThrowResolveException() { $this->manager->expects($this->once()) ->method('getBestMatch') ->will($this->returnValue(null)); $request = (new ServerRequest())->withHeader('Accept', 'text/xml'); $this->middleware->__invoke($request, new Response()); } /** * @test * @expectedException \bitExpert\Adroit\Resolver\ResolveException */ public function whenNoRespondersExistForBestMatchWillThrowResolveException() { $this->manager->expects($this->once()) ->method('getBestMatch') ->will($this->returnValue('application/custom')); $this->middleware->__invoke($this->request, $this->response); } /** * @test */ public function oneConfiguredResponderForContentTypeWillBeUsed() { $setResponder = null; $responder = $this->createMock(Responder::class); $this->manager->expects($this->once()) ->method('getBestMatch') ->will($this->returnValue('text/html')); $this->resolver1->expects($this->once()) ->method('resolve') ->will($this->returnValue($responder)); $request = (new ServerRequest())->withAttribute('domainPayload', new DomainPayload('')); $next = function (ServerRequestInterface $request, ResponseInterface $response) use (&$setResponder) { $setResponder = $request->getAttribute(Responder::class); return $response; }; $this->middleware->__invoke($request, $this->response, $next); $this->assertSame($responder, $setResponder); } /** * @test */ public function firstMatchingResponderForContentTypeWillBeUsed() { $setResponder = null; $responder = $this->createMock(Responder::class); $this->manager->expects($this->once()) ->method('getBestMatch') ->will($this->returnValue('application/json')); $this->resolver2->expects($this->once()) ->method('resolve') ->will($this->returnValue($responder)); $request = (new ServerRequest())->withAttribute('domainPayload', new DomainPayload('')); $next = function (ServerRequestInterface $request, ResponseInterface $response) use (&$setResponder) { $setResponder = $request->getAttribute(Responder::class); return $response; }; $this->middleware->__invoke($request, $this->response, $next); $this->assertSame($responder, $setResponder); } }
apache-2.0
cfg4j/cfg4j
cfg4j-core/src/test/java/org/cfg4j/source/context/propertiesprovider/JsonBasedPropertiesProviderTest.java
3475
/* * Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cfg4j.source.context.propertiesprovider; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.InputStream; class JsonBasedPropertiesProviderTest { private JsonBasedPropertiesProvider provider; @BeforeEach void setUp() { provider = new JsonBasedPropertiesProvider(); } @Test void readsSingleValues() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsSingleValues.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("setting", "masterValue"), MapEntry.entry("integerSetting", 42)); } } @Test void readsNestedValues() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsNestedValues.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("some.setting", "masterValue"), MapEntry.entry("some.integerSetting", 42)); } } @Test void readsLists() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsLists.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("whitelist", "a,b,33"), MapEntry.entry("blacklist", "x,y,z")); } } @Test void readsTextBlock() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsTextBlock.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsExactly(MapEntry.entry("content", "I'm just a text block document")); } } @Test void throwsForNonJsonFile() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_throwsForNonJsonFile.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThatThrownBy(() -> provider.getProperties(input)).isExactlyInstanceOf(IllegalStateException.class); } } @Test void throwsOnNullInput() throws Exception { String path = "org/cfg4j/source/propertiesprovider/nonexistent.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThatThrownBy(() -> provider.getProperties(input)).isExactlyInstanceOf(NullPointerException.class); } } }
apache-2.0
cppforlife/bosh-warden-cpi-release
src/bosh-warden-cpi/vm/iptables_ports.go
2842
package vm import ( "net" "strconv" "strings" "time" "github.com/cloudfoundry/bosh-cpi-go/apiv1" bosherr "github.com/cloudfoundry/bosh-utils/errors" boshsys "github.com/cloudfoundry/bosh-utils/system" bwcutil "bosh-warden-cpi/util" ) type IPTablesPorts struct { sleeper bwcutil.Sleeper cmdRunner boshsys.CmdRunner } func NewIPTablesPorts(sleeper bwcutil.Sleeper, cmdRunner boshsys.CmdRunner) IPTablesPorts { return IPTablesPorts{sleeper, cmdRunner} } func (p IPTablesPorts) Forward(id apiv1.VMCID, containerIP string, mappings []PortMapping) error { for _, mapping := range mappings { forwardArgs := []string{ "PREROUTING", "-p", mapping.Protocol(), "!", "-i", "w+", // non-warden interfaces // todo wont work if cpi is nested "--dport", p.fmtPortRange(mapping.Host(), ":"), "-j", "DNAT", "--to", net.JoinHostPort(containerIP, p.fmtPortRange(mapping.Container(), "-")), "-m", "comment", "--comment", p.comment(id), } _, _, _, err := p.runCmd("-A", forwardArgs) if err != nil { p.removeRulesWithID(id) return bosherr.WrapErrorf(err, "Forwarding host port(s) '%v'", mapping.Host()) } } return nil } func (p IPTablesPorts) RemoveForwarded(id apiv1.VMCID) error { return p.removeRulesWithID(id) } func (p IPTablesPorts) removeRulesWithID(id apiv1.VMCID) error { stdout, _, _, err := p.cmdRunner.RunCommand("iptables-save", "-t", "nat") if err != nil { return bosherr.WrapErrorf(err, "Listing nat table rules to remove rules") } var lastErr error for _, line := range strings.Split(stdout, "\n") { if !strings.Contains(line, p.comment(id)) { continue } forwardArgs := strings.Split(line, " ")[1:] // skip -A _, stderr, _, err := p.runCmd("-D", forwardArgs) if err != nil { // Ignore missing rule errors as there may be race conditions (though unlikely) if !strings.Contains(stderr, "No chain/target/match by that name") { lastErr = err } } } return lastErr } func (IPTablesPorts) comment(id apiv1.VMCID) string { return "bosh-warden-cpi-" + id.AsString() } func (IPTablesPorts) fmtPortRange(portRange PortRange, delim string) string { if portRange.Len() > 1 { return strconv.Itoa(portRange.Start()) + delim + strconv.Itoa(portRange.End()) } return strconv.Itoa(portRange.Start()) } func (p IPTablesPorts) runCmd(action string, args []string) (string, string, int, error) { globalArgs := []string{"-w", "-t", "nat", action} globalArgs = append(globalArgs, args...) for i := 0; i < 60; i++ { stdout, stderr, code, err := p.cmdRunner.RunCommand("iptables", globalArgs...) if err != nil { if strings.Contains(stderr, "Resource temporarily unavailable") { p.sleeper.Sleep(500 * time.Millisecond) continue } } return stdout, stderr, code, err } return "", "", 0, bosherr.Errorf("Failed to add iptables rule") }
apache-2.0
0359xiaodong/Renderers
sample/src/main/java/com/pedrogomez/renderers/ui/renderers/FavoriteVideoRenderer.java
1536
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedrogomez.renderers.ui.renderers; import android.content.Context; import com.pedrogomez.renderers.R; import com.pedrogomez.renderers.model.Video; import com.squareup.picasso.Picasso; /** * Favorite video renderer created to implement the presentation logic for videos. This * VideoRenderer subtype only * override renderLabel and renderMarker methods. * * @author Pedro Vicente Gómez Sánchez. */ public class FavoriteVideoRenderer extends VideoRenderer { /* * Constructor */ public FavoriteVideoRenderer(Context context) { super(context); } /* * Implemented methods */ @Override protected void renderLabel() { String label = getContext().getString(R.string.favorite_label); getLabel().setText(label); } @Override protected void renderMarker(Video video) { Picasso.with(getContext()).load(R.drawable.fav_active).into(getMarker()); } }
apache-2.0
AndroidWJC/UnversityFinance
app/src/main/java/com/hqj/universityfinance/LoginActivity.java
7722
package com.hqj.universityfinance; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.hqj.universityfinance.customview.ClearEditText; import com.hqj.universityfinance.utils.ConfigUtils; import com.hqj.universityfinance.utils.DatabaseUtils; import com.hqj.universityfinance.utils.HttpCallbackListener; import com.hqj.universityfinance.utils.HttpConnectUtils; import com.hqj.universityfinance.utils.Utils; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by wang on 17-9-20. */ public class LoginActivity extends BaseActivity implements View.OnClickListener{ private static final String TAG = "LoginActivity"; private ClearEditText mAccountEt; private ClearEditText mPasswordEt; private TextView mForgetPasswordTv; private Button mLoginBtn; private DatabaseUtils mdbHelper; private SQLiteDatabase mDB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); mdbHelper = new DatabaseUtils(this, ConfigUtils.DATABASE_NAME, ConfigUtils.DATABASE_VERSION); mDB = mdbHelper.getWritableDatabase(); } private void initView() { mAccountEt = (ClearEditText) findViewById(R.id.login_account); mPasswordEt = (ClearEditText) findViewById(R.id.login_password); mForgetPasswordTv = (TextView) findViewById(R.id.forget_password); mForgetPasswordTv.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); mActionBarTitle.setText(R.string.title_action_bar_login); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.login_btn: Utils.showLoadingDialog(this, 0, R.string.loading_text_login); HashMap<String, String> params = new HashMap<String, String>(); params.put("type", ConfigUtils.TYPE_POST_LOGIN); params.put("account", mAccountEt.getText().toString()); params.put("password", mPasswordEt.getText().toString()); try { String urlWithInfo = HttpConnectUtils.getURLWithParams(ConfigUtils.SERVER_URL, params); HttpConnectUtils.sendRequestByOKHttp(urlWithInfo, new HttpCallbackListener() { @Override public void onLoadSuccess(final String response) { Log.d(TAG, "onLoadSuccess: response = "+response); if (response == null) { Utils.showToast(LoginActivity.this, R.string.login_failed_net_error); } else if (response.equals(ConfigUtils.ERROR)) { Utils.showToast(LoginActivity.this, R.string.toast_login_account_error); } else if (response.startsWith(ConfigUtils.SUCCESSFUL)) { Utils.writeToSharedPreferences(LoginActivity.this, "account", mAccountEt.getText().toString()); Utils.writeToSharedPreferences(LoginActivity.this, "password", mPasswordEt.getText().toString()); saveDataToDatabase(response); succeedToLogin(); } Utils.dismissLoadingDialog(); Log.d(TAG, "onLoadSuccess: end "); } @Override public void onLoadFailed(int reason) { Log.d(TAG, "onLoadSuccess: error"); if (reason == ConfigUtils.TYPE_LOGIN_NET_ERROR) { Utils.showToast(LoginActivity.this, R.string.login_failed_net_error); } else if (reason == ConfigUtils.TYPE_LOGIN_ACCOUNT_ERROR){ Utils.showToast(LoginActivity.this, R.string.toast_login_account_error); } Utils.dismissLoadingDialog(); } }); } catch (Exception e) { } break; case R.id.forget_password: break; } } private boolean saveDataToDatabase(String jsonData) { Cursor cursor = mDB.rawQuery("select s_password from "+ConfigUtils.TABLE_STUDENT+" "+"where s_id=?", new String[]{mAccountEt.getText().toString()}); if (cursor.moveToFirst()) { cursor.close(); return true; } try { JSONObject jsonObject = new JSONObject(jsonData); ContentValues values = new ContentValues(); values.put("s_id", jsonObject.getInt("s_id")); values.put("s_password", jsonObject.getString("s_password")); values.put("s_status", jsonObject.getInt("s_status")); values.put("s_id_card", jsonObject.getString("s_id_card")); values.put("s_name", jsonObject.getString("s_name")); values.put("s_sex", jsonObject.getString("s_sex")); values.put("s_political_status", jsonObject.getString("s_political_status")); values.put("s_college", jsonObject.getString("s_college")); values.put("s_start_year", jsonObject.getInt("s_start_year")); values.put("s_continue_years", jsonObject.getInt("s_continue_years")); values.put("s_class", jsonObject.getString("s_class")); values.put("s_phone", jsonObject.getString("s_phone")); values.put("s_photo", jsonObject.getString("s_photo")); values.put("s_photo_bytes", getPhotoBytes(jsonObject.getString("s_photo"))); mDB.insert(ConfigUtils.TABLE_STUDENT, null, values); Log.d(TAG, "onLoadSuccess: s_id = "+jsonObject.getInt("s_id") +", s_password = "+jsonObject.getString("s_password")); } catch (JSONException e) { e.printStackTrace(); } return true; } private byte[] getPhotoBytes(String url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { Response response = client.newCall(request).execute(); InputStream inputStream = response.body().byteStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } return outStream.toByteArray(); } private void succeedToLogin() { runOnUiThread(new Runnable() { @Override public void run() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); LoginActivity.this.startActivity(intent); finish(); } }); } }
apache-2.0
abego/j2slib
src/main/j2slib/org/eclipse/swt/widgets/FileDialog.js
3434
$_L(["$wt.widgets.Dialog"],"$wt.widgets.FileDialog",["$wt.events.SelectionAdapter","$wt.internal.ResizeSystem","$wt.layout.GridData","$.GridLayout","$wt.widgets.Button","$.Composite","$.Label","$.Listener","$.Shell"],function(){ c$=$_C(function(){ this.filterNames=null; this.filterExtensions=null; this.fileNames=null; this.filterPath=""; this.fileName=""; $_Z(this,arguments); },$wt.widgets,"FileDialog",$wt.widgets.Dialog); $_Y(c$,function(){ this.filterNames=new Array(0); this.filterExtensions=new Array(0); this.fileNames=new Array(0); }); $_K(c$, function(parent){ this.construct(parent,32768); },"$wt.widgets.Shell"); $_K(c$, function(parent,style){ $_R(this,$wt.widgets.FileDialog,[parent,style]); },"$wt.widgets.Shell,~N"); $_M(c$,"getFileName", function(){ return this.fileName; }); $_M(c$,"getFileNames", function(){ return this.fileNames; }); $_M(c$,"getFilterExtensions", function(){ return this.filterExtensions; }); $_M(c$,"getFilterNames", function(){ return this.filterNames; }); $_M(c$,"getFilterPath", function(){ return this.filterPath; }); $_M(c$,"open", function(){ this.dialogShell=new $wt.widgets.Shell(this.parent.display,this.style|64|65536); this.dialogShell.addListener(21,(($_D("$wt.widgets.FileDialog$1")?0:org.eclipse.swt.widgets.FileDialog.$FileDialog$1$()),$_N($wt.widgets.FileDialog$1,this,null))); this.dialogShell.setText(this.title); this.dialogShell.setLayout(new $wt.layout.GridLayout(2,false)); var icon=new $wt.widgets.Label(this.dialogShell,0); icon.setImage(this.parent.display.getSystemImage(8)); var gridData=new $wt.layout.GridData(32,32); icon.setLayoutData(gridData); var label=new $wt.widgets.Label(this.dialogShell,0); label.setText("Not implemented yet."); var buttonPanel=new $wt.widgets.Composite(this.dialogShell,0); var gd=new $wt.layout.GridData(3,2,false,false); gd.horizontalSpan=2; buttonPanel.setLayoutData(gd); buttonPanel.setLayout(new $wt.layout.GridLayout()); var btn=new $wt.widgets.Button(buttonPanel,8); btn.setText("&OK"); btn.setLayoutData(new $wt.layout.GridData(75,24)); btn.addSelectionListener((($_D("$wt.widgets.FileDialog$2")?0:org.eclipse.swt.widgets.FileDialog.$FileDialog$2$()),$_N($wt.widgets.FileDialog$2,this,null))); this.dialogShell.pack(); this.dialogShell.open(); var size=this.dialogShell.getSize(); var y=$_dI((this.dialogShell.getMonitor().clientHeight-size.y)/2)-20; if(y<0){ y=0; }this.dialogShell.setLocation($_dI((this.dialogShell.getMonitor().clientWidth-size.x)/2),y); $wt.internal.ResizeSystem.register(this.dialogShell,16777216); return null; }); $_M(c$,"setFileName", function(string){ this.fileName=string; },"~S"); $_M(c$,"setFilterExtensions", function(extensions){ this.filterExtensions=extensions; },"~A"); $_M(c$,"setFilterNames", function(names){ this.filterNames=names; },"~A"); $_M(c$,"setFilterPath", function(string){ this.filterPath=string; },"~S"); c$.$FileDialog$1$=function(){ $_H(); c$=$_W($wt.widgets,"FileDialog$1",null,$wt.widgets.Listener); $_V(c$,"handleEvent", function(event){ },"$wt.widgets.Event"); c$=$_P(); }; c$.$FileDialog$2$=function(){ $_H(); c$=$_W($wt.widgets,"FileDialog$2",$wt.events.SelectionAdapter); $_V(c$,"widgetSelected", function(e){ this.b$["$wt.widgets.FileDialog"].dialogShell.close(); },"$wt.events.SelectionEvent"); c$=$_P(); }; $_S(c$, "FILTER","*.*", "BUFFER_SIZE",32768); });
apache-2.0
JiangFeng07/myapp-demo
poi-myapp-core/src/test/java/com/myapp/pattern/proxyPattern/AdjKey.java
1408
package com.myapp.pattern.proxyPattern; /** * Created by lionel on 16/12/2. */ public class AdjKey { private Integer level; private Integer cate; private String subject; private String adj; public AdjKey() { } public AdjKey(Integer level, Integer cate, String subject, String adj) { this.level = level; this.cate = cate; this.subject = subject; this.adj = adj; } public Integer getLevel() { return level; } public Integer getCate() { return cate; } public String getSubject() { return subject; } public String getAdj() { return adj; } @Override public int hashCode() { return getCate().hashCode() + getLevel().hashCode() * 16 + getSubject().hashCode() * 32 + getAdj().hashCode() * 64; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof AdjKey)) { return false; } final AdjKey adjKey = (AdjKey) object; return this.getAdj().equals(adjKey.getAdj()) && this.getSubject().equals(adjKey.getSubject()) && this.getCate().equals(adjKey.getCate()) && this.getLevel().equals(adjKey.getLevel()); } }
apache-2.0
mengmoya/onos
apps/l3vpn/nel3vpn/nemgr/src/main/java/org/onosproject/yang/gen/v1/ne/l3vpn/api/rev20141225/NeL3VpnApiManager.java
1776
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.yang.gen.v1.ne.l3vpn.api.rev20141225; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Service; import org.onosproject.yang.gen.v1.ne.l3vpn.api.rev20141225.nel3vpnapi.L3VpnInstances; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; /** * Represents the implementation of neL3VpnApiManager. */ @Component (immediate = true) @Service public class NeL3VpnApiManager implements NeL3VpnApiService { private final Logger log = getLogger(getClass()); @Activate public void activate() { //TODO: YANG utils generated code log.info("Started"); } @Deactivate public void deactivate() { //TODO: YANG utils generated code log.info("Stopped"); } @Override public L3VpnInstances getL3VpnInstances() { //TODO: YANG utils generated code return null; } @Override public void setL3VpnInstances(L3VpnInstances l3VpnInstances) { //TODO: YANG utils generated code } }
apache-2.0
sidorovis/stsc.general
src/main/java/stsc/general/simulator/multistarter/AlgorithmConfigurationSet.java
632
package stsc.general.simulator.multistarter; import java.util.Iterator; public interface AlgorithmConfigurationSet { long size(); int parametersSize(); String toString(); AlgorithmConfigurationSet clone(); // public void reset(); public ParameterList<Integer, MpNumberIterator<Integer>> getIntegers(); public ParameterList<Double, MpNumberIterator<Double>> getDoubles(); public ParameterList<String, MpTextIterator<String>> getStrings(); public ParameterList<String, MpTextIterator<String>> getSubExecutions(); public Iterator<MpTextIterator<String>> getSubExecutionIterator(); }
apache-2.0
martincmartin/MathematiciansAssistant
DeductionApril2018.py
3354
from Expression import Expression, CompositeExpression, has_head, Equal from MatchAndSubstitute import Direction from ProofSystem import ExprAndParent, Exprs, BruteForceProofState from typing import Sequence from typing import cast def try_rules( context: Sequence[Expression], goal: Expression, general_rules: Sequence[Expression], verbosity: int = 0, ) -> Sequence[Expression]: """context and context_rules are disjoint, all in context_rules satisfy is_rule(), whereas none of those in context do.""" assert verbosity >= 0 general = BruteForceProofState( [ExprAndParent(r, None) for r in general_rules], [], None, verbosity ) state = BruteForceProofState( [ExprAndParent(e, None) for e in context], [ExprAndParent(goal, None)], general, verbosity, ) while True: made_progress = False # Step 1: work forward from premises to goal. found = state.try_all_rules( state.context.immediate_non_rules(), state.context.immediate_rules(), Direction.FORWARD, ) if isinstance(found, bool): made_progress = made_progress or found else: return found # Step 2: simplification / transformations from the goal. found = state.try_all_rules( cast(Exprs, state.goals).immediate_non_rules(), state.context.immediate_rules(), Direction.BACKWARD, ) if isinstance(found, bool): made_progress = made_progress or found else: return found if not made_progress: break print( "Using just the problem specific premises & rules hasn't let us " "prove the goal. Switching to general purpose premises / rules." ) for current_goal in cast(Exprs, state.goals).equalities(): assert has_head(current_goal.expr, Equal) goal_expr = cast(CompositeExpression, current_goal.expr) lhs = ExprAndParent(goal_expr[1], None) rhs = ExprAndParent(goal_expr[2], current_goal) if verbosity > 0: print( "*** goal: " + str(current_goal.expr) + ", LHS: " + str(lhs.expr) + ", target: " + str(rhs.expr) ) temp_state = BruteForceProofState([lhs], [rhs], state, verbosity) while True: print("######## Starting pass!") print("************************ context:") print("\n".join([str(v) for v in temp_state.context])) print("************************ goals:") print("\n".join([str(v) for v in temp_state.goals])) # We need something smarter than try_all_rules(). found = temp_state.try_all_rules( temp_state.context.all_exprs(), temp_state.context.all_rules(), Direction.FORWARD, ) if not isinstance(found, bool): return found if not found: break print("************************ Final context:") print("\n".join([str(v) for v in state.context])) print("************************ Final goals:") print("\n".join([str(v) for v in state.goals])) return []
apache-2.0
nlalevee/ant-http
src/java/org/missinglink/http/exception/InvalidUriException.java
1143
/* * Copyright 2012 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.missinglink.http.exception; public class InvalidUriException extends HttpClientException { private static final long serialVersionUID = -7009763989380593388L; public InvalidUriException() { super(); } public InvalidUriException(final String message, final Throwable cause) { super(message, cause); } public InvalidUriException(final String message) { super(message); } public InvalidUriException(final Throwable cause) { super(cause); } }
apache-2.0
KodrAus/cirrus
src/cirrus.core.workflow/processes/PartialResult.cs
529
namespace Cirrus.Core.Workflow.Processes { //Represents a partially completed Process public class PartialResult { public object Result; public Process Process; public object Execute() { //Execute the Process if it is not null, or return the result return Process != null ? Process.Execute(Result) : Result; } public PartialResult ExecuteStep() { //Execute a step in the Process if it is not null, or return this return Process != null ? Process.ExecuteStep(Result) : this; } } }
apache-2.0
alexflav23/exercises
rps/app/model/domain/DomainJsonFormats.scala
703
package model.domain import play.api.libs.json._ /** * A list of implicit formats generated using the [[Json]] macro implementation. * We are keeping the implicits grouped here. We could also store the implicits * nested under the companion objects of their respective target case classes, * but in this instance we will store them here for simplicity. */ trait DomainJsonFormats { implicit val categoryFormat = Json.format[Category] implicit val categoriesFormat = Json.format[Categories] implicit val categoryDistributionFormat = Json.format[CategoryDistribution] implicit val attributesFormat = Json.format[Attributes] implicit val productFormat = Json.format[StoreProduct] }
apache-2.0
chrisGerken/sofa
stackoverflow/src/main/java/com/gerkenip/stackoverflow/model/AbstractModelObject.java
4816
package com.gerkenip.stackoverflow.model; import java.util.ArrayList; import java.util.StringTokenizer; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.gerkenip.stackoverflow.SofAccess; import com.gerkenip.stackoverflow.SofIterator; import com.gerkenip.stackoverflow.elasticsearch.EsClient; public abstract class AbstractModelObject { protected static EsClient esClient = EsClient.localClient(); protected static SofAccess sofAccess = new SofAccess("stackoverflow"); protected static String baseUrl = "https://api.stackexchange.com/2.1"; public static long DURATION_DAYS_0007 = 7 * 24 * 60 * 60 * 1000; public static long DURATION_DAYS_1000 = 1000 * 24 * 60 * 60 * 1000; private JSONObject _data = null; public AbstractModelObject(JSONObject jobj) { this._data = jobj; } protected JSONObject getDataObject() { return _data; } protected boolean hasValue(String key) { try { JSONObject jobj = getDataObject(path(key)); if (jobj == null) { return false; } if (jobj.get(property(key)) == null) { return false; } } catch (Exception e) { return false; } return true; } protected String getStringValue(String key) { try { return getDataObject(path(key)).getString(property(key)); } catch (Exception e) { return null; } } protected int getIntValue(String key) { try { return getDataObject(path(key)).getInt(property(key)); } catch (Exception e) { return 0; } } protected long getLongValue(String key) { try { return getDataObject(path(key)).getLong(property(key)); } catch (Exception e) { return 0; } } protected boolean getBooleanValue(String key) { try { return getDataObject(path(key)).getBoolean(property(key)); } catch (Exception e) { return false; } } protected String[] getStringArrayValue(String key) { try { JSONArray jarr = getDataObject(path(key)).getJSONArray(property(key)); String result[] = new String[jarr.length()]; for (int i = 0; i < jarr.length(); i++) { result[i] = jarr.get(i).toString(); } return result; } catch (Exception e) { return new String[0]; } } private JSONObject getDataObject(String path) { if (path == null) { return getDataObject(); } JSONObject jobj = getDataObject(); try { StringTokenizer st = new StringTokenizer(path, "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); jobj = jobj.getJSONObject(token); } return jobj; } catch (Exception e) { return null; } } private String path(String key) { int index = key.lastIndexOf("/"); if (index < 0) { return null; } String result = key.substring(0,index); return result; } private String property(String key) { int index = key.lastIndexOf("/"); if (index < 0) { return key; } String result = key.substring(index+1); return result; } public abstract String asHtmlLink(); protected void cache(String type, String id, long shelfLife) { sofAccess.cacheDocument(type, id, _data, shelfLife); } protected static JSONObject[] getMultipleUnderlyingData(String type, String idAttribute, String getUrl, long shelfLife) { ArrayList<JSONObject> jsons = new ArrayList<JSONObject>(); SofIterator iter = sofAccess.getMany(getUrl); while (iter.hasNext()) { JSONObject jobj = iter.next(); jsons.add(jobj); try { sofAccess.cacheDocument(type, jobj.getString(idAttribute), jobj, shelfLife); } catch (JSONException e) { e.printStackTrace(); } } JSONObject[] jobj = new JSONObject[jsons.size()]; jsons.toArray(jobj); return jobj; } protected static JSONObject getUnderlyingData(String type, String id, String getUrl, long shelfLife) { JSONObject jobj = sofAccess.getDocument(type, id); if ((jobj == null) || (sofAccess.isExpired(jobj))) { jobj = sofAccess.getSingle(getUrl); sofAccess.cacheDocument(type, id, jobj, shelfLife); } if (jobj == null) { return null; } return jobj; } protected static JSONObject[] getUnderlyingData(String type, String id[], String url1, String url2, long shelfLife) { ArrayList<JSONObject> jsons = new ArrayList<JSONObject>(); for (int i = 0; i < id.length; i=i+100 ) { String delim = ""; StringBuffer sb = new StringBuffer(); sb.append(url1); for (int j = 0; ((j < 100) && ((i+j)<id.length)); j++) { int offset = i + j; sb.append(delim); sb.append(id[offset]); delim = ";"; } sb.append(url2); String url = sb.toString(); SofIterator iter = sofAccess.getMany(url); while (iter.hasNext()) { jsons.add(iter.next()); } } JSONObject[] jobj = new JSONObject[jsons.size()]; jsons.toArray(jobj); return jobj; } }
apache-2.0
cloudant/java-cloudant
cloudant-client/src/test/resources/design-files/query_design_doc.js
241
{ "_id": "_design/testQuery", "language": "query", "views": { "testView": { "map": {"fields": {"Person_dob": "asc"}}, "reduce": "_count", "options": { "def": { "fields": [ "Person_dob" ] } } } } }
apache-2.0
Rikkola/guvnor
droolsjbpm-ide-common/src/test/java/org/drools/testframework/MockWorkingMemory.java
16650
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.testframework; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import org.drools.Agenda; import org.drools.FactException; import org.drools.FactHandle; import org.drools.QueryResults; import org.drools.RuleBase; import org.drools.SessionConfiguration; import org.drools.WorkingMemoryEntryPoint; import org.drools.common.InternalFactHandle; import org.drools.common.InternalKnowledgeRuntime; import org.drools.common.InternalRuleBase; import org.drools.common.InternalWorkingMemory; import org.drools.common.NodeMemory; import org.drools.common.ObjectStore; import org.drools.common.ObjectTypeConfigurationRegistry; import org.drools.common.RuleBasePartitionId; import org.drools.common.TruthMaintenanceSystem; import org.drools.common.WorkingMemoryAction; import org.drools.concurrent.ExecutorService; import org.drools.event.AgendaEventListener; import org.drools.event.AgendaEventSupport; import org.drools.event.RuleBaseEventListener; import org.drools.event.WorkingMemoryEventListener; import org.drools.event.WorkingMemoryEventSupport; import org.drools.process.instance.WorkItemManager; import org.drools.reteoo.LIANodePropagation; import org.drools.reteoo.ObjectTypeConf; import org.drools.reteoo.PartitionTaskManager; import org.drools.rule.EntryPoint; import org.drools.rule.Rule; import org.drools.runtime.Calendars; import org.drools.runtime.Channel; import org.drools.runtime.Environment; import org.drools.runtime.ExitPoint; import org.drools.runtime.ObjectFilter; import org.drools.runtime.impl.ExecutionResultImpl; import org.drools.runtime.process.InternalProcessRuntime; import org.drools.runtime.process.ProcessInstance; import org.drools.spi.Activation; import org.drools.spi.AgendaFilter; import org.drools.spi.AsyncExceptionHandler; import org.drools.spi.FactHandleFactory; import org.drools.spi.GlobalResolver; import org.drools.time.SessionClock; import org.drools.time.TimerService; import org.drools.time.impl.JDKTimerService; import org.drools.type.DateFormats; public class MockWorkingMemory implements InternalWorkingMemory { List<Object> facts = new ArrayList<Object>(); AgendaEventListener agendaEventListener; Map<String, Object> globals = new HashMap<String, Object>(); private SessionClock clock = new JDKTimerService(); public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { facts = (List<Object>)in.readObject(); agendaEventListener = (AgendaEventListener)in.readObject(); globals = (Map<String, Object>)in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(facts); out.writeObject(agendaEventListener); out.writeObject(globals); } public Calendars getCalendars() { return null; } public Iterator iterateObjects() { return this.facts.iterator(); } public void setGlobal(String identifier, Object value) { this.globals.put(identifier, value); } public void addEventListener(AgendaEventListener listener) { this.agendaEventListener = listener; } public void addLIANodePropagation(LIANodePropagation liaNodePropagation) { // TODO Auto-generated method stub } public void clearNodeMemory(NodeMemory node) { // TODO Auto-generated method stub } public void executeQueuedActions() { // TODO Auto-generated method stub } public ExecutorService getExecutorService() { // TODO Auto-generated method stub return null; } public FactHandle getFactHandleByIdentity(Object object) { // TODO Auto-generated method stub return null; } public FactHandleFactory getFactHandleFactory() { // TODO Auto-generated method stub return null; } public int getId() { // TODO Auto-generated method stub return 0; } public InternalFactHandle getInitialFactHandle() { // TODO Auto-generated method stub return null; } public Lock getLock() { // TODO Auto-generated method stub return null; } public long getNextPropagationIdCounter() { // TODO Auto-generated method stub return 0; } public Object getNodeMemory(NodeMemory node) { // TODO Auto-generated method stub return null; } public ObjectStore getObjectStore() { // TODO Auto-generated method stub return null; } public ObjectTypeConfigurationRegistry getObjectTypeConfigurationRegistry() { // TODO Auto-generated method stub return null; } public PartitionTaskManager getPartitionTaskManager(RuleBasePartitionId partitionId) { // TODO Auto-generated method stub return null; } public TimerService getTimerService() { // TODO Auto-generated method stub return null; } public TruthMaintenanceSystem getTruthMaintenanceSystem() { // TODO Auto-generated method stub return null; } public boolean isSequential() { // TODO Auto-generated method stub return false; } public void queueWorkingMemoryAction(WorkingMemoryAction action) { // TODO Auto-generated method stub } public void removeProcessInstance(ProcessInstance processInstance) { // TODO Auto-generated method stub } public void retract(FactHandle factHandle, boolean removeLogical, boolean updateEqualsMap, Rule rule, Activation activation) throws FactException { // TODO Auto-generated method stub } public void setAgendaEventSupport(AgendaEventSupport agendaEventSupport) { // TODO Auto-generated method stub } public void setExecutorService(ExecutorService executor) { // TODO Auto-generated method stub } public void setId(int id) { // TODO Auto-generated method stub } public void setRuleBase(InternalRuleBase ruleBase) { // TODO Auto-generated method stub } public void setWorkingMemoryEventSupport(WorkingMemoryEventSupport workingMemoryEventSupport) { // TODO Auto-generated method stub } public void clearActivationGroup(String group) { // TODO Auto-generated method stub } public void clearAgenda() { // TODO Auto-generated method stub } public void clearAgendaGroup(String group) { // TODO Auto-generated method stub } public void clearRuleFlowGroup(String group) { // TODO Auto-generated method stub } public int fireAllRules() throws FactException { // TODO Auto-generated method stub return 0; } public int fireAllRules(AgendaFilter agendaFilter) throws FactException { // TODO Auto-generated method stub return 0; } public int fireAllRules(int fireLimit) throws FactException { // TODO Auto-generated method stub return 0; } public int fireAllRules(AgendaFilter agendaFilter, int fireLimit) throws FactException { // TODO Auto-generated method stub return 0; } public Agenda getAgenda() { // TODO Auto-generated method stub return null; } public FactHandle getFactHandle(Object object) { // TODO Auto-generated method stub return null; } public Object getGlobal(String identifier) { // TODO Auto-generated method stub return null; } public GlobalResolver getGlobalResolver() { // TODO Auto-generated method stub return null; } public Object getObject(org.drools.runtime.rule.FactHandle handle) { // TODO Auto-generated method stub return null; } public ProcessInstance getProcessInstance(long id) { // TODO Auto-generated method stub return null; } public Collection<ProcessInstance> getProcessInstances() { // TODO Auto-generated method stub return null; } public QueryResults getQueryResults(String query) { // TODO Auto-generated method stub return null; } public QueryResults getQueryResults(String query, Object[] arguments) { // TODO Auto-generated method stub return null; } public RuleBase getRuleBase() { // TODO Auto-generated method stub return null; } public SessionClock getSessionClock() { return this.clock; } public void setSessionClock(SessionClock clock) { this.clock = clock; } public WorkItemManager getWorkItemManager() { // TODO Auto-generated method stub return null; } public WorkingMemoryEntryPoint getWorkingMemoryEntryPoint(String id) { // TODO Auto-generated method stub return null; } public void halt() { // TODO Auto-generated method stub } public Iterator< ? > iterateFactHandles() { // TODO Auto-generated method stub return null; } public Iterator< ? > iterateFactHandles(org.drools.runtime.ObjectFilter filter) { // TODO Auto-generated method stub return null; } public Iterator< ? > iterateObjects(org.drools.runtime.ObjectFilter filter) { // TODO Auto-generated method stub return null; } public void setAsyncExceptionHandler(AsyncExceptionHandler handler) { // TODO Auto-generated method stub } public void setFocus(String focus) { // TODO Auto-generated method stub } public void setGlobalResolver(GlobalResolver globalResolver) { // TODO Auto-generated method stub } public ProcessInstance startProcess(String processId) { // TODO Auto-generated method stub return null; } public ProcessInstance startProcess(String processId, Map<String, Object> parameters) { // TODO Auto-generated method stub return null; } public void addEventListener(WorkingMemoryEventListener listener) { // TODO Auto-generated method stub } public List getAgendaEventListeners() { // TODO Auto-generated method stub return null; } public List getWorkingMemoryEventListeners() { // TODO Auto-generated method stub return null; } public void removeEventListener(WorkingMemoryEventListener listener) { // TODO Auto-generated method stub } public void removeEventListener(AgendaEventListener listener) { // TODO Auto-generated method stub } public void addEventListener(RuleBaseEventListener listener) { // TODO Auto-generated method stub } public List<RuleBaseEventListener> getRuleBaseEventListeners() { // TODO Auto-generated method stub return null; } public void removeEventListener(RuleBaseEventListener listener) { // TODO Auto-generated method stub } public FactHandle insert(Object object) throws FactException { this.facts .add(object); return new MockFactHandle(object.hashCode()); } public FactHandle insert(Object object, boolean dynamic) throws FactException { // TODO Auto-generated method stub return null; } public void modifyInsert(FactHandle factHandle, Object object) { // TODO Auto-generated method stub } public void modifyRetract(FactHandle factHandle) { // TODO Auto-generated method stub } public void retract(org.drools.runtime.rule.FactHandle handle) throws FactException { // TODO Auto-generated method stub } public void update(org.drools.runtime.rule.FactHandle handle, Object object) throws FactException { // TODO Auto-generated method stub } public InternalKnowledgeRuntime getKnowledgeRuntime() { // TODO Auto-generated method stub return null; } public void setKnowledgeRuntime(InternalKnowledgeRuntime kruntime) { // TODO Auto-generated method stub } public Map<String, ExitPoint> getExitPoints() { // TODO Auto-generated method stub return null; } public Environment getEnvironment() { // TODO Auto-generated method stub return null; } public SessionConfiguration getSessionConfiguration() { // TODO Auto-generated method stub return null; } public Map<String, WorkingMemoryEntryPoint> getEntryPoints() { // TODO Auto-generated method stub return null; } public void endBatchExecution() { // TODO Auto-generated method stub } public ExecutionResultImpl getExecutionResult() { // TODO Auto-generated method stub return null; } public void startBatchExecution(ExecutionResultImpl results) { // TODO Auto-generated method stub } public Collection< Object > getObjects() { // TODO Auto-generated method stub return null; } public Collection< Object > getObjects(ObjectFilter filter) { // TODO Auto-generated method stub return null; } public void endOperation() { // TODO Auto-generated method stub } public long getIdleTime() { // TODO Auto-generated method stub return 0; } public void startOperation() { // TODO Auto-generated method stub } public long getTimeToNextJob() { // TODO Auto-generated method stub return 0; } public void updateEntryPointsCache() { // TODO Auto-generated method stub } public void activationFired() { // TODO Auto-generated method stub } public void prepareToFireActivation() { // TODO Auto-generated method stub } public String getEntryPointId() { // TODO Auto-generated method stub return null; } public long getFactCount() { // TODO Auto-generated method stub return 0; } public long getTotalFactCount() { // TODO Auto-generated method stub return 0; } public DateFormats getDateFormats() { // TODO Auto-generated method stub return null; } public <T extends org.drools.runtime.rule.FactHandle> Collection<T> getFactHandles() { // TODO Auto-generated method stub return null; } public <T extends org.drools.runtime.rule.FactHandle> Collection<T> getFactHandles(ObjectFilter filter) { // TODO Auto-generated method stub return null; } public EntryPoint getEntryPoint() { // TODO Auto-generated method stub return null; } public void insert(InternalFactHandle handle, Object object, Rule rule, Activation activation, ObjectTypeConf typeConf) { // TODO Auto-generated method stub } public Map<String, Channel> getChannels() { // TODO Auto-generated method stub return null; } public InternalProcessRuntime getProcessRuntime() { // TODO Auto-generated method stub return null; } }
apache-2.0
HoanNguyenIM/ATD
project/packages/foostart/mail/src/Controllers/Admin/MailSendController.php
9390
<?php namespace Foostart\Mail\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use URL; use Route, Redirect; use Foostart\Mail\Models\Mails; use Foostart\Mail\Models\MailsContacts; use Foostart\Mail\Models\MailsHistories; use Mail; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Http\File; /** * Validators */ use Foostart\Mail\Validators\MailAdminValidator; class MailSendController extends Controller { public $data_view = array(); private $obj_mail = NULL; private $obj_mail_contact = NULL; private $obj_mail_history = NULL; private $obj_validator = NULL; private $file_extension_temp = NULL; public function __construct() { $this->obj_mail = new Mails(); $this->obj_mail_contact = new MailsContacts(); $this->obj_mail_history = new MailsHistories(); } /** * * @return type */ /* Wrong when send. Go to https://www.google.com/settings/security/lesssecureapps and active it. */ public function mailSend(Request $request){ $this->obj_validator = new MailAdminValidator(); $mail = NULL; $mail_contact = NULL; $mail_history = NULL; $mail_id = (int) $request->get('id'); $mail_name = (string) $request->get('mail_name'); $count_mail = 0; // Check connect internet /*if(!$this->pingAddress('8.8.8.8')){ $request->request->add(['internet_interrupt' => 'Not internet']); }*/ //With cmd will not run in real website if(!$this->internet_checker()){ $request->request->add(['internet_interrupt' => 'Not internet']); } $input = $request->all(); // var_dump($input); // die(); if (!$this->obj_validator->validate($input)) { $data['errors'] = $this->obj_validator->getErrors(); if (!empty($mail_id) && is_int($mail_id)) { $mail = $this->obj_mail->find($mail_id); $mail_contact = $this->obj_mail_contact->find($mail_id); $mail_history = $this->obj_mail_history->find($mail_id); } $this->data_view = array_merge($this->data_view, array( 'mail' => $mail, 'mail_contact' => $mail_contact, 'mail_history' => $mail_history, 'request' => $request ), $data); if ($request->has('prepare')){ return view('mail::mail_send.admin.mail_send', $this->data_view); } elseif ($request->has('compose')) { return view('mail::mail_send.admin.mail_compose', $this->data_view); } elseif ($request->has('reply')) { return view('mail::mail_contact.admin.mail_contact_reply', $this->data_view); } else { return view('mail::mail_history.admin.mail_history_forward', $this->data_view); } } else{ // $photos = $input['fileToUpload']; // $this->storageFile($photos); // var_dump($photos); // die(); $arr_mail = explode(' ', $mail_name); $count_mail = count($arr_mail); $file = Input::file('fileToUpload'); $file_path = null; if($file != null){ $file_path = $this->storageFile($file);//.$this->file_extension_temp;// $this->attachFile($file); } elseif(!empty($input['mail_attach'])) { $file_path = $input['mail_attach']; } $data = [ 'confirm' => 'confirm', 'author' => 'ADMIN PACKAGE', 'subject' => $input['mail_subject'], 'contents' => $input['mail_content'], 'file_path' => $file_path ]; // var_dump($data); // die(); if($request->has('prepare') || $request->has('reply')){ if (!empty($mail_id) && (is_int($mail_id))) { if($request->has('prepare')) $mail = $this->obj_mail->find($mail_id); else $mail_contact = $this->obj_mail_contact->find($mail_id); } $data['address'] = $mail != null ? $mail->mail_name : $mail_contact->mail_contact_name; // Sendding mail function $this->sendding($data); $request->request->add([ 'mail_history_name' => $data['address'], 'mail_history_subject' => $input['mail_subject'], 'mail_history_content' => $input['mail_content'], 'mail_history_attach' => $file_path ]); $input = $request->all(); $mail_history = $this->obj_mail_history->add_mail_history($input); //Message \Session::flash('message', trans('mail::mail_admin.message_send_mail_successfully')); return Redirect::route("admin_mail"); } else { if($count_mail == 1){ $data['address'] = $input['mail_name']; $this->sendding($data); } else{ foreach ($arr_mail as $key => $value) { if($value != null){ $data['address'] = trim($value); $this->sendding($data); sleep(5); } } } $request->request->add([ 'mail_history_name' => $input['mail_name'], 'mail_history_subject' => $input['mail_subject'], 'mail_history_content' => $input['mail_content'], 'mail_history_attach' => $file_path ]); $input = $request->all(); $mail_history = $this->obj_mail_history->add_mail_history($input); //Message \Session::flash('message', trans('mail::mail_admin.message_send_mail_successfully')); return Redirect::route("admin_mail"); } } } /** * Check internet connection * @return true or false */ public function pingAddress($ip) { $max = 200; $avg = 100; $getAvg = 200; $getMax = 100; $pingresult = exec("ping -n 3 $ip", $outcome, $status); $arr = explode(',', $pingresult); foreach ($arr as $key => $value) { // Has internet if(strpos($value, 'Minimum')){} elseif (strpos($value, 'Maximum')){ $getMax = preg_replace('/[^0-9]+/', '', $value); } elseif (strpos($value, 'Average')){ $getAvg = preg_replace('/[^0-9]+/', '', $value); } // Not internet else { return false; } } if ($getMax > $max || $getAvg > $avg) return false; else return true; } /** * * @return type */ function internet_checker() { $connected = @fsockopen("www.example.com", 80); //website, port (try 80 or 443) if ($connected){ $is_conn = true; //action when connected fclose($connected); }else{ $is_conn = false; //action in connection failure } return $is_conn; } /** * * @return type */ public function sendding($data){ // var_dump($data); // die(); Mail::send(['view' => 'mail'], $data, function($message) use ($data){ $message->to($data['address']) ->cc($data['address']) ->subject($data['subject']) ->setBody($data['contents']); if($data['file_path'] != null){ // $message->attach(public_path().'/'.$data['file_path']); $message->attach(storage_path('app').'/'.$data['file_path']); } $message->from('rootpowercontrol@gmail.com', 'ADMIN'); }); } /** * * @return location file have been save */ public function attachFile($file) { if ($file != null && $file->isValid()){ $location_file = public_path(); $file_name = null; $destinationPath = 'upload/'; $extension = $file->getClientOriginalExtension(); $file_name = rand(111,999).$file->getClientOriginalName(); $file->move($destinationPath, $file_name); return $destinationPath.$file_name; } } public function storageFile($file){ $path = Storage::putFile('files', $file); return $path; // var_dump($path); // die(); // $file_name = $file->store('files'); // $this->file_extension_temp = $file->getClientOriginalExtension(); // return $file_name; } }
apache-2.0
entoj/entoj-system
test/export/ConfigurationShared.js
13876
'use strict'; /** * Requirements * @ignore */ const Site = require(ES_SOURCE + '/model/site/Site.js').Site; const EntityAspect = require(ES_SOURCE + '/model/entity/EntityAspect.js').EntityAspect; const DocumentationCallable = require(ES_SOURCE + '/model/documentation/DocumentationCallable.js').DocumentationCallable; const ContentType = require(ES_SOURCE + '/model/ContentType.js').ContentType; const ContentKind = require(ES_SOURCE + '/model/ContentKind.js').ContentKind; const baseSpec = require(ES_TEST + '/BaseShared.js').spec; const projectFixture = require(ES_FIXTURES + '/project/index.js'); const co = require('co'); /** * Shared Renderer spec */ function spec(type, className, prepareParameters, options) { /** * Base Test */ baseSpec(type, className, prepareParameters); /** * Configuration Test */ const opts = options || {}; beforeEach(function() { global.fixtures = projectFixture.createStatic({ skipEntities: true }); }); function createTestee(entity, macro, settings) { let params = [entity, macro, settings, undefined, undefined, undefined, global.fixtures.globalRepository, global.fixtures.buildConfiguration]; if (prepareParameters) { params = prepareParameters(params); } return new type(...params); } spec.createTestee = createTestee; /** * Create a new entity and registers it */ function createEntity(idPath, macros, properties) { const entity = global.fixtures.createEntity(idPath); entity.properties.load(properties || {}); const macroNames = []; if (!macros) { macroNames.push(entity.idString.replace('-', '_')); } else { macroNames.push(...macros); } for (const macroName of macroNames) { const macro = new DocumentationCallable( { name: macroName, contentType: ContentType.JINJA, contentKind: ContentKind.MACRO, site: global.fixtures.siteBase }); entity.documentation.push(macro); } } spec.createEntity = createEntity; describe('#getMacroConfiguration()', function() { it('should yield a configuration containing the macro, entity and site of the exported artefact', function() { const promise = co(function *() { createEntity('base/elements/e-headline'); const settings = {}; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getMacroConfiguration(); expect(config.macro).to.be.instanceof(DocumentationCallable); expect(config.macro.name).to.be.equal('e_headline'); expect(config.entity).to.be.instanceof(EntityAspect); expect(config.entity.idString).to.be.equal('e-headline'); expect(config.site).to.be.instanceof(Site); expect(config.site.name).to.be.equal('Base'); }); return promise; }); it('should allow to change configuration via export settings', function() { const promise = co(function *() { createEntity('base/elements/e-headline'); const settings = { view: 'local.html' }; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getMacroConfiguration(); expect(config.view).to.be.equal('local.html'); }); return promise; }); it('should allow to change configuration for specific macros via export settings', function() { const promise = co(function *() { createEntity('base/elements/e-headline', ['e_headline']); const settings = { settings: { e_headline: { view: 'specific.html' } } }; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getMacroConfiguration(); expect(config.view).to.be.equal('specific.html'); }); return promise; }); it('should allow to change configuration via global export settings', function() { const promise = co(function *() { const identifier = opts.identifier || 'default'; const globalSettings = { base: { export: { settings: { [identifier]: { view: 'global.html' } } } } }; createEntity('base/elements/e-headline', ['e_headline'], globalSettings); const settings = {}; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getMacroConfiguration(); expect(config.view).to.be.equal('global.html'); }); return promise; }); it('should allow to change configuration for a specific macro via global export settings', function() { const promise = co(function *() { const identifier = opts.identifier || 'default'; const globalSettings = { base: { export: { settings: { [identifier]: { macros: { '*': { view: 'specific.html' } } } } } } }; createEntity('base/elements/e-headline', ['e_headline'], globalSettings); const settings = {}; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getMacroConfiguration(); expect(config.view).to.be.equal('specific.html'); }); return promise; }); it('should prefer local over global export settings', function() { const promise = co(function *() { const identifier = opts.identifier || 'default'; const globalSettings = { base: { export: { settings: { [identifier]: { view: 'global.html' } } } } }; createEntity('base/elements/e-headline', ['e_headline'], globalSettings); const settings = { view: 'view.html' }; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const macro = yield global.fixtures.globalRepository.resolveMacro(global.fixtures.siteBase, 'e_headline'); const testee = createTestee(entity, macro, settings); const config = yield testee.getExportConfiguration(); expect(config.view).to.be.equal('view.html'); }); return promise; }); }); describe('#getExportConfiguration()', function() { it('should yield a configuration containing the entity and site of the export artefact', function() { const promise = co(function *() { createEntity('base/elements/e-headline'); const settings = {}; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const testee = createTestee(entity, false, settings); const config = yield testee.getExportConfiguration(); expect(config.entity).to.be.instanceof(EntityAspect); expect(config.entity.idString).to.be.equal('e-headline'); expect(config.site).to.be.instanceof(Site); expect(config.site.name).to.be.equal('Base'); }); return promise; }); it('should allow to change configuration via export settings', function() { const promise = co(function *() { createEntity('base/elements/e-headline'); const settings = { view: 'view.html' }; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const testee = createTestee(entity, false, settings); const config = yield testee.getExportConfiguration(); expect(config.view).to.be.equal('view.html'); }); return promise; }); it('should allow to change configuration via global export settings', function() { const promise = co(function *() { const identifier = opts.identifier || 'default'; const globalSettings = { base: { export: { settings: { [identifier]: { view: 'global.html' } } } } }; createEntity('base/elements/e-headline', [], globalSettings); const settings = {}; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const testee = createTestee(entity, false, settings); const config = yield testee.getExportConfiguration(); expect(config.view).to.be.equal('global.html'); }); return promise; }); it('should prefer local over global export settings', function() { const promise = co(function *() { const identifier = opts.identifier || 'default'; const globalSettings = { base: { export: { settings: { [identifier]: { view: 'global.html' } } } } }; createEntity('base/elements/e-headline', [], globalSettings); const settings = { view: 'view.html' }; const entity = yield global.fixtures.entitiesRepository.getById('e-headline', global.fixtures.siteBase); const testee = createTestee(entity, false, settings); const config = yield testee.getExportConfiguration(); expect(config.view).to.be.equal('view.html'); }); return promise; }); }); } /** * Exports */ module.exports.spec = spec;
apache-2.0
jacobluber/ScalaSpider
FinancialSpider/src/application/Mapper.scala
488
//code from http://debasishg.blogspot.com/2008/06/playing-around-with-parallel-maps-in.html; I merely used this to inspire my actor based parallel map package application class Mapper[A, B:Manifest](l: List[A], f: A => B) { def pmap = { val buffer = new Array[B](l.length) val mappers = for(idx <- (0 until l.length).toList) yield { scala.actors.Futures.future { buffer(idx) = f(l(idx)) } } for(mapper <- mappers) mapper() buffer } }
apache-2.0
jrh3k5/inventory-webapp
src/main/java/com/github/jrh3k5/inventory/application/data/CountableEntity.java
139
package com.github.jrh3k5.inventory.application.data; public interface CountableEntity extends IdentifiableEntity { int getCount(); }
apache-2.0
rullionsolutions/lazuli-ui
sections_core/ItemSet.js
24483
"use strict"; var UI = require("lazuli-ui/index.js"); var Data = require("lazuli-data/index.js"); module.exports = UI.Section.clone({ id: "ItemSet", items: null, // array of item objects query_mode: null, // "preload" to load items in setup, "dynamic" to reload in eachItem() query: null, // query object for dynamic use INSTEAD of items OR to populate items allow_add_items: true, allow_delete_items: true, add_item_icon: "<i class='glyphicon glyphicon-plus'></i>", // ordinary plus ; "&#x2795;" heavy plus sign delete_item_icon: "<i class='glyphicon glyphicon-remove'></i>", // ordinary cross; "&#x274C;" heavy cross mark add_item_label: "Add a new item", delete_item_label: "Remove this item", text_no_items: "no items", text_one_items: "1 item", text_many_items: "items", itemset_size: 10, itemset_size_ext: 20, itemset_size_long_lists: 1000, itemset: null, itemset_last: null, frst_itemset_icon: "<i class='glyphicon glyphicon-fast-backward'></i>", prev_itemset_icon: "<i class='glyphicon glyphicon-backward'></i>", next_itemset_icon: "<i class='glyphicon glyphicon-forward'></i>", last_itemset_icon: "<i class='glyphicon glyphicon-fast-forward'></i>", extd_itemset_icon: "<i class='glyphicon glyphicon-arrow-down'></i>", }); module.exports.register("addItem"); module.exports.register("deleteItem"); module.exports.register("renderBeforeItems"); module.exports.register("renderAfterItems"); module.exports.defbind("initializeItemSet", "cloneInstance", function () { this.items = []; // deleted items remain in array but eachItem() ignores them this.item_count = 0; this.itemset = 1; this.itemset_last = 1; }); /** * To setup this grid, by setting 'entity' to the entity specified by 'entity', then calling */ module.exports.define("setupRecord", function (entity_id) { var spec = { id: entity_id, skip_registration: true, }; if (this.query_mode === "dynamic") { spec.page = this.owner.page; spec.instance = true; spec.id_prefix = "list_" + this.id; } // this.record = Data.entities.getThrowIfUnrecognized(entity_id).clone({ // id: entity_id, // skip_registration: true, // }); // if query_mode === "dynamic" then record object is used to store actual field values, // so is an instance, otherwise it is used as the template for transaction records this.record = Data.entities.getThrowIfUnrecognized(entity_id).clone(spec); }); module.exports.defbind("initializeEntity", "setup", function () { if (typeof this.entity_id === "string") { this.setupRecord(this.entity_id); } else if (typeof this.entity === "string") { // 'entity' as a string property is deprecated this.setupRecord(this.entity); } }); module.exports.define("setupParentRecord", function (parent_record) { this.parent_record = parent_record; }); module.exports.defbind("initializeParentRecord", "setup", function () { if (!this.parent_record && this.record && this.link_field) { if (this.owner.page.page_key_entity && this.record.getField(this.link_field).ref_entity === this.owner.page.page_key_entity.id) { this.setupParentRecord(this.owner.page.page_key_entity .getRow(this.owner.page.page_key)); } else if (this.record.getField(this.link_field).ref_entity === this.owner.page.entity.id) { this.setupParentRecord(this.owner.page.getPrimaryRow()); } } }); /** * To setup this section to use an 'item adder field', i.e. a field in entity * (usually of Option type) * @return the field in entity specified by 'add_item_field' */ module.exports.define("setupItemAdder", function (spec) { var type = Data.fields.getThrowIfUnrecognized(spec.type); spec.id = "list_" + this.id + "_item_adder"; spec.label = this.add_item_label; spec.instance = true; spec.btn_label = this.add_item_icon; this.add_item_field = type.clone(spec); this.add_item_field.override("getFormGroupCSSClass", function (form_type, editable) { return type.getFormGroupCSSClass.call(this, form_type, editable) + " css_list_add"; }); }); module.exports.define("copyItemAdderFromExistingField", function (add_item_field_id, add_item_unique) { var orig_add_item_field = this.record.getField(add_item_field_id); var spec = { type: orig_add_item_field.type, // tb_input: "input-sm", skip_full_load: false, // make sure we have full lov here.. input_group_size: "input-group-sm", editable: true, css_reload: true, render_radio: false, input_group_addon_before: this.add_item_label, list: orig_add_item_field.list, ref_entity: orig_add_item_field.ref_entity, selection_filter: this.selection_filter, collection_id: orig_add_item_field.collection_id, config_item: orig_add_item_field.config_item, label_prop: orig_add_item_field.label_prop, active_prop: orig_add_item_field.active_prop, }; if (spec.type === "Reference") { spec.type = "Option"; // Autocompleter doesn't work here yet } this.setupItemAdder(spec); this.add_item_unique = (typeof add_item_unique === "boolean") ? add_item_unique : this.record.isKey(add_item_field_id); this.debug("setupItemAdder(): " + this.add_item_field.lov); // prevent original field from being shown as a column - assumes entity is a private copy... orig_add_item_field.list_column = false; // this.columns.get(this.add_item_field_id).editable = false; return orig_add_item_field; }); module.exports.define("getAdderItem", function (val) { var item; if (!this.add_item_field) { this.throwError("no add_item_field defined"); } this.debug("getAdderItem(): " + val + ", from " + this.add_item_field.lov); item = this.add_item_field.lov.getItem(val); if (!item) { this.throwError("unrecognized item: " + val); } return item; }); module.exports.defbind("initializeItemAdder", "setup", function () { if (this.add_item_field_id && this.record) { this.copyItemAdderFromExistingField(this.add_item_field_id, this.add_item_unique); } else if (this.add_item_field && this.record) { // deprecated and replaced... this.add_item_field_id = this.add_item_field; this.copyItemAdderFromExistingField(this.add_item_field, this.add_item_unique); } else { this.setupItemAdder({ type: "ContextButton", css_cmd: true, }); } }); // this.setupColumns(); module.exports.define("setupItemDeleterField", function () { this.delete_item_field = this.record.addField({ id: "_item_deleter", type: "ContextButton", // label: " ", btn_label: this.delete_item_label, visible: this.allow_delete_items, list_column: this.allow_delete_items, btn_css_class: "css_col_control", css_cmd: true, }); this.record.moveTo("_item_deleter", 0); }); module.exports.defbind("initializeItemDeleter", "setup", function () { if (this.allow_delete_items) { this.setupItemDeleterField(); } }); /** * To add a row control columns as the first column in the table, which is based on a Reference * field to the entity, which is set * @param entity_id as string */ module.exports.define("setupItemControlField", function () { var that = this; var visible = !!this.entity.getDisplayPage(); this.item_control_field = this.record.addField({ id: "_item_control", type: "Reference", label: "", ref_entity: this.entity.id, sql_function: "A._key", visible: visible, list_column: visible, dynamic_only: true, sortable: false, sticky_column: true, css_class_col_header: "css_row_control", dropdown_label: "Action", dropdown_button: true, dropdown_css_class: "btn-default btn-xs", dropdown_right_align: true, }); this.item_control_field.override("renderCell", function (row_elem, render_opts) { if (this.dynamic_only && render_opts.dynamic_page === false) { return; } if (this.visible) { // this.field.set(row_obj.getKey()); this.renderNavOptions(row_elem.makeElement("td"), render_opts, that.record); } }); }); module.exports.defbind("initializeItemControl", "setup", function () { if (this.show_item_control) { this.setupItemControlField(); } }); /** * To create a new x.sql.Query object, stored to 'query' to be used to load initial items * into the grid; */ module.exports.define("setupQuery", function (entity) { this.query = entity.getQuery(true); // getQuery(true) - default sort if (this.load_link_field && this.load_link_value) { this.setLinkCondition(this.query, this.load_link_field, this.load_link_value); } else if (this.link_field && this.parent_record) { this.setLinkCondition(this.query, this.link_field, this.parent_record.getKey()); } }); /** * Set up link field relationship (requires this.query to be present) * @param link_field: string column id, value: string value to use in filter condition, condition * is false if not supplied */ module.exports.define("setLinkField", function (link_field, value) { this.setLinkCondition(this.query, link_field, value); }); module.exports.define("setLinkCondition", function (query, link_field, value) { if (this.key_condition) { this.key_condition.remove(); } if (value) { this.key_condition = query.addCondition({ column: "A." + link_field, operator: "=", value: value, }); } else { this.key_condition = query.addCondition({ full_condition: "false", }); // prevent load if no value supplied } // prevent link field from being shown as a column - assumes entity is a private copy... this.record.getField(link_field).list_column = false; this.record.getField(link_field).visible = false; // if (this.columns.get(link_field)) { // this.columns.get(link_field).visible = false; // } }); /** * To load initial items into this grid by looping over this.query, calling addExistingRow() * on each item's key */ module.exports.define("load", function () { while (this.query.next()) { this.addItemInternal({ key: this.query.getColumn("A._key").get(), }); } this.query.reset(); }); module.exports.defbind("initializeLoad", "setup", function () { if (this.query_mode === "preload" || this.query_mode === "manual" || this.query_mode === "dynamic") { if (!this.query) { if (this.load_entity_id) { this.setupQuery(Data.entities.get(this.load_entity_id)); } else { this.setupQuery(this.record); } } } if (this.query_mode === "preload") { this.load(); } }); module.exports.define("addItem", function (spec) { if (!this.allow_add_items || this.query_mode === "dynamic") { this.throwError("items cannot be added to this ItemSet"); } return this.addItemInternal(spec); }); module.exports.define("addItemInternal", function (spec) { var item = this.makeItemFromSpec(spec); this.items.push(item); this.item_count += 1; this.happen("addItem", item); return item; }); module.exports.define("deleteItem", function (item) { var i = this.items.indexOf(item); if (i < 0) { this.throwError("item not in this ItemSet: " + item.id); } if (!this.allow_delete_items || this.query_mode === "dynamic") { this.throwError("items cannot be deleted from this ItemSet"); } if (item.allow_delete === false) { this.throwError("this item cannot be deleted"); } item.setDelete(true); // this.items.splice(i, 1); this.item_count -= 1; this.happen("deleteItem", item); }); module.exports.define("getItemCount", function () { return this.item_count; }); module.exports.define("resetToStart", function () { this.itemset = 1; }); module.exports.define("eachItem", function (funct) { if (this.query_mode === "dynamic") { while (this.query.next()) { this.populateRecordFromQuery(); funct(this.record); } this.query.reset(); } else { this.items.forEach(function (item) { if (!item.deleting) { funct(item); } }); } }); module.exports.define("populateRecordFromQuery", function () { this.record.populate(this.query.resultset); }); module.exports.override("isValid", function () { var valid = true; this.eachItem(function (item) { valid = valid && item.isValid(); }); return valid; }); module.exports.define("makeItemFromSpec", function (spec) { var record; if (spec.key) { record = this.createNewOrExistingRecordWithKey(spec.key); } else if (spec.field_id && spec.field_val) { record = this.createNewRecordWithField(spec.field_id, spec.field_val); } else if (spec.add_blank_item) { record = this.createNewRecord(); } else { this.throwError("invalid spec: " + this.view.call(spec)); } return record; }); module.exports.define("createNewOrExistingRecordWithKey", function (key) { return this.owner.page.getTrans().getRow(this.record, key); }); module.exports.define("createNewRecordWithField", function (field_id, field_val) { var row; if (this.add_item_field_id === field_id && this.add_item_unique && !this.getAddRowItem(field_val).active) { this.throwError("createNewRecordWithField() row already exists: " + field_val); } this.getParentRecord(); // ensure this.parent_record populated if can be if (this.record.getField(field_id).isKey() && this.parent_record && this.parent_record.isKeyComplete()) { row = this.getDeletedRecordIfExists(field_id, field_val); } if (!row) { row = this.owner.page.getTrans().createNewRow(this.record); row.getField(field_id).set(field_val); } return row; }); module.exports.define("createNewRecord", function () { return this.owner.page.getTrans().createNewRow(this.record); }); module.exports.define("getDeletedRecordIfExists", function (field_id, field_val) { var row; var key_values = {}; key_values[this.link_field] = this.getParentRecord().getKey(); key_values[field_id] = field_val; this.debug("getDeletedRowIfExists() " + this.view.call(key_values)); row = this.record.getCachedRecordFromKeyValues(key_values, this.owner.page.getTrans()); this.debug("getDeletedRowIfExists() got: " + row); if (row) { if (!row.deleting) { this.throwError("new record is already in cache and not being deleted"); } row.setDelete(false); } return row; }); module.exports.defbind("afterAddItem", "addItem", function (item) { var id; if (this.add_item_unique && this.add_item_field) { id = item.getField(this.add_item_field_id).get(); this.debug("removing item from LoV: " + id); if (id) { this.getAddRowItem(id).active = false; } } item.id_prefix = this.id + "_" + this.items.length; if (this.parent_record) { item.linkToParent(this.parent_record, this.link_field); } if (item.page !== this.owner.page) { item.addToPage(this.owner.page); } }); module.exports.defbind("afterDeleteItem", "deleteItem", function (item) { var id; if (this.add_item_unique && this.add_item_field) { id = item.getField(this.add_item_field_id).get(); if (id) { this.getAddRowItem(id).active = true; } } item.removeFromPage(this.owner.page); }); module.exports.defbind("updateAddDeleteItems", "update", function (params) { var match; var that = this; if (params.page_button === "list_" + this.id + "_item_adder") { this.addItem({ add_blank_item: true, }); } else if (params.page_button === "list_set_extend_" + this.id) { this.extendItemSet(); } else if (params.page_button === "add_item_field_" + this.id) { this.addItem({ field_id: this.add_item_field_id, field_val: params["add_item_field_" + this.id], }); } else if (typeof params.page_button === "string" && params.page_button.indexOf("list_" + this.id)) { match = params.page_button.match(new RegExp(this.id + "_([0-9]+)__item_deleter")); if (match && match.length > 1) { this.eachItem(function (item) { if (item.getField("_item_deleter").getControl() === match[0]) { that.deleteItem(item); } }); } } }); module.exports.defbind("renderItemSet", "render", function (render_opts) { var that = this; this.happen("renderBeforeItems", render_opts); this.item_elmt = this.getItemSetElement(render_opts); this.foot_elmt = null; this.item_count = 0; this.eachItem(function (item) { if (render_opts.test === true) { that.setTestValues(item); } that.trace("renderItemSet(): " + item); that.renderItem(that.item_elmt, render_opts, item); that.item_count += 1; }); this.happen("renderAfterItems", render_opts); }); module.exports.define("getItemSetElement", function (render_opts) { return this.getSectionElement().makeElement(this.main_tag); }); module.exports.define("getFootElement", function (render_opts) { if (!this.foot_elmt) { this.foot_elmt = this.getSectionElement().makeElement("div"); } return this.foot_elmt; }); module.exports.define("renderItem", function (parent_elmt, render_opts, item) { this.throwError("this function must be overridden"); }); module.exports.defbind("setQueryLimitsIfDynamic", "renderBeforeItems", function (render_opts) { if (this.query_mode === "dynamic") { this.setQueryLimits(render_opts); } }); module.exports.define("setQueryLimits", function (render_opts) { var itemset_size = this.itemset_size; if (!this.query) { this.throwError("no query object"); } if (render_opts.long_lists && itemset_size < this.itemset_size_long_lists) { itemset_size = this.itemset_size_long_lists; } if (this.hide_detail_rows) { this.itemset = 1; this.query.limit_offset = 0; this.query.limit_row_count = 0; } else if (render_opts && render_opts.long_lists) { this.recordset = 1; this.query.limit_offset = 0; this.query.limit_row_count = itemset_size; } else { this.query.limit_offset = ((this.itemset - 1) * itemset_size); this.query.limit_row_count = itemset_size; if (this.include_query_row_before_itemset && (this.itemset > 1)) { this.query.limit_offset -= 1; this.query.limit_row_count += 1; } if (this.include_query_row_after_itemset) { this.query.limit_row_count += 1; } } }); module.exports.define("setTestValues", function (item) { var obj = {}; // this capture of values for test will be REMOVED!! item.each(function (f) { obj[f.id] = f.get(); }); if (!this.test_values) { this.test_values = []; } this.test_values.push(obj); }); /** * To render elements displayed in the event that the list thas no items. By default this will * be the text_no_items but can be overridden to display addition elements. */ module.exports.define("renderNoItems", function () { this.getSectionElement().text(this.text_no_items); }); module.exports.define("extendItemSet", function () { this.resetToStart(); this.itemset_size += this.itemset_size_ext; }); module.exports.defbind("renderItemAdder", "renderAfterItems", function (render_opts) { var foot_elmt = this.getFootElement(); if (render_opts.dynamic_page === false || !this.allow_add_items) { return; } if (this.add_item_field) { this.debug("renderItemAdder(): " + this.add_item_field.lov); this.add_item_field.renderFormGroup(foot_elmt, render_opts, "table-cell"); // } else { // foot_elmt.makeElement("span", "css_list_add") // .makeElement("a", "css_cmd btn btn-default btn-xs", "list_add_" + this.id) // .attr("title", this.add_item_label) // .text(this.add_item_icon, true); } }); /** * To render the player-style control for pages back and forth through itemsets of data, if * appropriate * @param foot_elmt (xmlstream) */ module.exports.defbind("renderListPager", "renderAfterItems", function (render_opts) { var foot_elmt = this.getFootElement(); var ctrl_elem; if (render_opts.dynamic_page === false) { return; } ctrl_elem = foot_elmt.makeElement("span", "btn-group css_item_pager"); if (this.itemset > 1) { ctrl_elem.makeElement("a", "css_cmd btn btn-default btn-xs", "list_set_frst_" + this.id) .attr("title", "first itemset") .text(this.frst_itemset_icon, true); ctrl_elem.makeElement("a", "css_cmd btn btn-default btn-xs", "list_set_prev_" + this.id) .attr("title", "previous itemset") .text(this.prev_itemset_icon, true); } ctrl_elem.text(this.getItemCountText()); // if (this.open_ended_itemset || (this.itemset_last > 1 && // this.itemset < this.itemset_last)) { if (this.subsequent_itemset || this.itemset > 1) { ctrl_elem .makeElement("span", "css_list_itemcount") .makeElement("a", "css_cmd btn btn-default btn-xs", "list_set_extend_" + this.id) .attr("title", "expand this itemset by " + this.itemset_size_ext + " items") .text(this.extd_itemset_icon, true); } if (this.subsequent_itemset) { ctrl_elem .makeElement("a", "css_cmd btn btn-default btn-xs", "list_set_next_" + this.id) .attr("title", "next itemset") .text(this.next_itemset_icon, true); } if (this.subsequent_itemset && !this.open_ended_itemset) { ctrl_elem .makeElement("a", "css_cmd btn btn-default btn-xs", "list_set_last_" + this.id) .attr("title", "last itemset") .text(this.last_itemset_icon, true); } }); module.exports.define("getItemCountText", function () { var text; var item_count = this.getItemCount(); if (this.itemset === 1 && !this.subsequent_itemset) { if (item_count === 0) { text = this.text_no_items; } else if (item_count === 1) { text = this.text_one_items; } else { text = item_count + " " + this.text_many_items; } } else if (this.frst_item_in_set && this.last_item_in_set) { text = "items " + this.frst_item_in_set + " - " + this.last_item_in_set; if (!this.open_ended_itemset && this.found_items && this.itemset_size < this.found_items) { text += " of " + this.found_items; } } else { text = item_count + " " + this.text_many_items; } return text; }); module.exports.define("outputNavLinks", function (page_key, details_elmt) { var found_key = false; var prev_key; var next_key; this.trace("outputNavLinks() with page_key: " + page_key); this.items.forEach(function (item) { if (item.deleting || typeof item.getKey !== "function") { return; } if (!found_key) { prev_key = item.getKey(); } if (found_key && !next_key) { next_key = item.getKey(); } if (item.getKey() === page_key) { found_key = true; } }); this.debug("outputNavLinks(): " + page_key + ", " + found_key + ", " + prev_key + ", " + next_key); if (found_key && prev_key) { details_elmt.attr("data-prev-key", prev_key); } if (found_key && next_key) { details_elmt.attr("data-next-key", next_key); } });
apache-2.0
tiffanytse/nya
js/scripts.js
605
jQuery(function($) { $('div.toc-content').TableOfContents(); $('.toc-container').waypoint('sticky', { offset: 32 // Apply "stuck" when element 30px from top }); $('.footer').waypoint({ offset: $('.sticky-wrapper').height()+64, //calculate menu's height and margin before footer handler: function(direction) { $('.toc-container').toggleClass('sticky-bottom'); //change position to absolute for the wrapper } }); // Disable zoom scroll on maps $(document).bind('em_maps_location_hook', function( e, map, infowindow, marker ){ map.scrollwheel = false; }); });
apache-2.0
tomoto/GlassNjslyr
src/com/tomoto/glass/njslyr/MainActivity.java
7912
package com.tomoto.glass.njslyr; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import com.google.android.glass.app.Card; import com.google.android.glass.widget.CardScrollView; import com.tomoto.glass.njslyr.model.StoryModel; import com.tomoto.glass.njslyr.model.TextLineModel; public class MainActivity extends Activity { // private SensorManager sensorManager; // private Sensor gravitySensor; private StoryModel storyModel; private CardScrollView cardScrollView; private GourangaCardScrollAdapter cardScrollAdapter; private TextToSpeech tts; // private UtteranceProgressListener ttsListener; // Doesn't work... // Workaround for TTS listener private TTSWatcher ttsw; private TTSWatcher.Listener ttswListener = new TTSWatcher.Listener() { @Override public void onStart() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @Override public void onStop(boolean force) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (!force) { goToNextPage(); } } }; // private SensorEventListener sensorEventListener = new SensorEventListener() { // private static final float THRESHOLD = 0.5f; // long lastSensedTime = 0; // // @Override // public void onSensorChanged(SensorEvent event) { // if (event.values[2] < -THRESHOLD) { // long currentTime = System.currentTimeMillis(); // if (currentTime - lastSensedTime > 1000) { // int position = cardScrollView.getSelectedItemPosition(); // if (position < cardScrollAdapter.getCount() - 1) { // cardScrollView.setSelection(position + 1); // } // } // lastSensedTime = currentTime; // } // } // // @Override // public void onAccuracyChanged(Sensor sensor, int accuracy) { // // Nothing to do // } // }; private class GourangaCardScrollAdapter extends AbstractCardScrollAdapter<TextLineModel> { public GourangaCardScrollAdapter(Context context, List<TextLineModel> textLineModels) { this.items = textLineModels; cards = new ArrayList<Card>(); for (TextLineModel tlm : textLineModels) { String text = MessageFormat.format("{0} ({1}/{2})", tlm.getText(), tlm.getIndex()+1, textLineModels.size()); Card card = new Card(context); card.setText(text); cards.add(card); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); Intent intent = getIntent(); storyModel = (StoryModel) intent.getSerializableExtra(RootActivity.EXTRA_STORY); List<TextLineModel> textLineModels = Arrays.asList(storyModel.getLines()); cardScrollView = new CardScrollView(this); cardScrollAdapter = new GourangaCardScrollAdapter(this, textLineModels); cardScrollView.setAdapter(cardScrollAdapter); cardScrollView.activate(); cardScrollView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { readCurrentCardAloud(); } @Override public void onNothingSelected(AdapterView<?> arg0) { stopCurrentSpeech(); } }); cardScrollView.setSelection(intent.getIntExtra(RootActivity.EXTRA_LINE, 0)); setContentView(cardScrollView); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // nothing to do // } // handler.post(new Runnable() { // @Override // public void run() { // speak(); // } // }); // } // }).start(); } private void activateTTS() { tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { tts.setLanguage(Locale.JAPANESE); readCurrentCardAloud(); } }); // tts.setOnUtteranceProgressListener(ttsListener); // does not work sadly // Workaround for listener ttsw = new TTSWatcher(tts, ttswListener); } private void deactivateTTS() { ttsw.shutdown(); } private void goToNextPage() { int position = cardScrollView.getSelectedItemPosition(); if (position < cardScrollAdapter.getCount() - 1) { cardScrollView.setSelection(position + 1); } else { cardScrollView.setSelection(0); finish(); // reached to the end } } private void readCurrentCardAloud() { if (ttsw != null) { int position = cardScrollView.getSelectedItemPosition(); // String text = "Card " + (position + 1) + "is selected"; String text = ((TextLineModel) cardScrollAdapter.getItem(position)).getSpeakingText(); ttsw.speak(text, TextToSpeech.QUEUE_FLUSH, null); } } private void stopCurrentSpeech() { ttsw.stop(); } @Override protected void onResume() { super.onResume(); activateTTS(); activateSensors(); } @Override protected void onPause() { super.onPause(); deactivateSensors(); deactivateTTS(); saveState(); } @Override protected void onDestroy() { cardScrollView.deactivate(); super.onDestroy(); } private void activateSensors() { // sensorManager.registerListener(sensorEventListener, gravitySensor , SensorManager.SENSOR_DELAY_NORMAL); } private void deactivateSensors() { // sensorManager.unregisterListener(sensorEventListener); } private void saveState() { SharedPreferences pref = getSharedPreferences(SavedStateConstants.NAME, MODE_PRIVATE); SharedPreferences.Editor prefEditor = pref.edit(); int currentLineIndex = cardScrollView.getSelectedItemPosition(); prefEditor.putInt(SavedStateConstants.CURRENT_STORY_INDEX, storyModel.getIndex()); prefEditor.putInt(SavedStateConstants.CURRENT_LINE_INDEX, currentLineIndex); prefEditor.commit(); } // private void restoreState() { // SharedPreferences pref = getPreferences(MODE_PRIVATE); // // String savedStoryTitle = pref.getString(SAVED_STATE_CURRENT_STORY_TITLE, ""); // Log.i("Gouranga", "savedStoryTitle: " + savedStoryTitle); // Log.i("Gouranga", "currentStoryTitle: " + storyModel.getTitle()); // if (savedStoryTitle.equals(storyModel.getTitle())) { // int currentLineIndex = pref.getInt(SAVED_STATE_CURRENT_LINE_INDEX, 0); // cardScrollView.setSelection(currentLineIndex); // } // } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { // openOptionsMenu(); // return true; // } // // return super.onKeyDown(keyCode, event); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.main, menu); // return true; // } // // @Override // public void onOptionsMenuClosed(Menu menu) { // finish(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.next: // Log.i("Gouranga", "Next"); // return true; // default: // return super.onOptionsItemSelected(item); // } // } }
apache-2.0
FirebaseExtended/crashlytics-migration-android
Firebase/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/fragment/R.java
12397
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.fragment; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f030027; public static final int coordinatorLayoutStyle = 0x7f0300a7; public static final int font = 0x7f0300da; public static final int fontProviderAuthority = 0x7f0300dc; public static final int fontProviderCerts = 0x7f0300dd; public static final int fontProviderFetchStrategy = 0x7f0300de; public static final int fontProviderFetchTimeout = 0x7f0300df; public static final int fontProviderPackage = 0x7f0300e0; public static final int fontProviderQuery = 0x7f0300e1; public static final int fontStyle = 0x7f0300e2; public static final int fontVariationSettings = 0x7f0300e3; public static final int fontWeight = 0x7f0300e4; public static final int keylines = 0x7f030112; public static final int layout_anchor = 0x7f030117; public static final int layout_anchorGravity = 0x7f030118; public static final int layout_behavior = 0x7f030119; public static final int layout_dodgeInsetEdges = 0x7f030145; public static final int layout_insetEdge = 0x7f03014e; public static final int layout_keyline = 0x7f03014f; public static final int statusBarBackground = 0x7f0301ac; public static final int ttcIndex = 0x7f03020e; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050079; public static final int notification_icon_bg_color = 0x7f05007a; public static final int ripple_material_light = 0x7f050087; public static final int secondary_text_default_material_light = 0x7f050089; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06004e; public static final int compat_button_inset_vertical_material = 0x7f06004f; public static final int compat_button_padding_horizontal_material = 0x7f060050; public static final int compat_button_padding_vertical_material = 0x7f060051; public static final int compat_control_corner_material = 0x7f060052; public static final int compat_notification_large_icon_max_height = 0x7f060053; public static final int compat_notification_large_icon_max_width = 0x7f060054; public static final int notification_action_icon_size = 0x7f0600c0; public static final int notification_action_text_size = 0x7f0600c1; public static final int notification_big_circle_margin = 0x7f0600c2; public static final int notification_content_margin_start = 0x7f0600c3; public static final int notification_large_icon_height = 0x7f0600c4; public static final int notification_large_icon_width = 0x7f0600c5; public static final int notification_main_column_padding_top = 0x7f0600c6; public static final int notification_media_narrow_margin = 0x7f0600c7; public static final int notification_right_icon_size = 0x7f0600c8; public static final int notification_right_side_padding_top = 0x7f0600c9; public static final int notification_small_icon_background_padding = 0x7f0600ca; public static final int notification_small_icon_size_as_large = 0x7f0600cb; public static final int notification_subtext_size = 0x7f0600cc; public static final int notification_top_pad = 0x7f0600cd; public static final int notification_top_pad_large_text = 0x7f0600ce; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070080; public static final int notification_bg = 0x7f070081; public static final int notification_bg_low = 0x7f070082; public static final int notification_bg_low_normal = 0x7f070083; public static final int notification_bg_low_pressed = 0x7f070084; public static final int notification_bg_normal = 0x7f070085; public static final int notification_bg_normal_pressed = 0x7f070086; public static final int notification_icon_background = 0x7f070087; public static final int notification_template_icon_bg = 0x7f070088; public static final int notification_template_icon_low_bg = 0x7f070089; public static final int notification_tile_bg = 0x7f07008a; public static final int notify_panel_notification_icon_bg = 0x7f07008b; } public static final class id { private id() {} public static final int action_container = 0x7f08000e; public static final int action_divider = 0x7f080010; public static final int action_image = 0x7f080011; public static final int action_text = 0x7f080017; public static final int actions = 0x7f080018; public static final int async = 0x7f080023; public static final int blocking = 0x7f080027; public static final int bottom = 0x7f080028; public static final int chronometer = 0x7f080032; public static final int end = 0x7f08004c; public static final int forever = 0x7f080059; public static final int icon = 0x7f080060; public static final int icon_group = 0x7f080061; public static final int info = 0x7f080065; public static final int italic = 0x7f080067; public static final int left = 0x7f08006b; public static final int line1 = 0x7f08006d; public static final int line3 = 0x7f08006e; public static final int none = 0x7f08007f; public static final int normal = 0x7f080080; public static final int notification_background = 0x7f080081; public static final int notification_main_column = 0x7f080082; public static final int notification_main_column_container = 0x7f080083; public static final int right = 0x7f080090; public static final int right_icon = 0x7f080091; public static final int right_side = 0x7f080092; public static final int start = 0x7f0800bc; public static final int tag_transition_group = 0x7f0800c2; public static final int tag_unhandled_key_event_manager = 0x7f0800c3; public static final int tag_unhandled_key_listeners = 0x7f0800c4; public static final int text = 0x7f0800c5; public static final int text2 = 0x7f0800c6; public static final int time = 0x7f0800d1; public static final int title = 0x7f0800d2; public static final int top = 0x7f0800d5; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f09000f; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b002d; public static final int notification_action_tombstone = 0x7f0b002e; public static final int notification_template_custom_big = 0x7f0b0035; public static final int notification_template_icon_group = 0x7f0b0036; public static final int notification_template_part_chronometer = 0x7f0b003a; public static final int notification_template_part_time = 0x7f0b003b; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e0064; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f0115; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0116; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0118; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f011b; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f011d; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01c5; public static final int Widget_Compat_NotificationActionText = 0x7f0f01c6; public static final int Widget_Support_CoordinatorLayout = 0x7f0f01f5; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] CoordinatorLayout = { 0x7f030112, 0x7f0301ac }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f030117, 0x7f030118, 0x7f030119, 0x7f030145, 0x7f03014e, 0x7f03014f }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0300dc, 0x7f0300dd, 0x7f0300de, 0x7f0300df, 0x7f0300e0, 0x7f0300e1 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300da, 0x7f0300e2, 0x7f0300e3, 0x7f0300e4, 0x7f03020e }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
apache-2.0
shawnsky/RantApp
app/src/main/java/com/xt/android/rant/fragment/NotifyCmtFragment.java
4859
package com.xt.android.rant.fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.xt.android.rant.R; import com.xt.android.rant.adapter.NewAdapter; import com.xt.android.rant.adapter.NotifyCmtAdapter; import com.xt.android.rant.utils.SpaceItemDecoration; import com.xt.android.rant.utils.TokenUtil; import com.xt.android.rant.wrapper.CmtNotifyItem; import com.xt.android.rant.wrapper.RantItem; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * A simple {@link Fragment} subclass. */ public class NotifyCmtFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private static final String TAG = "NotifyCmtFragment"; private static final int MSG_GET_NOTIFY_LIST = 1; private RecyclerView mRecyclerView; private SwipeRefreshLayout mSwipeRefreshLayout; private OkHttpClient mClient; private String mJson; private Handler mHandler; public NotifyCmtFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_notify_cmt, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_notify_cmt_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mRecyclerView.setAdapter(new NotifyCmtAdapter(new ArrayList<CmtNotifyItem>())); mRecyclerView.addItemDecoration(new SpaceItemDecoration(5)); mSwipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.fragment_notify_cmt_swipe_refresh_layout); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary)); List<CmtNotifyItem> cmtNotifyItemsFromDatabase = DataSupport.findAll(CmtNotifyItem.class); if(cmtNotifyItemsFromDatabase==null){ Log.i(TAG, "onCreateView: cmtNotifyItemsFromDatabase==null"); getData(); } else{ Log.i(TAG, "onCreateView: load cmt from database"); NotifyCmtAdapter adapter = new NotifyCmtAdapter(cmtNotifyItemsFromDatabase); mRecyclerView.setAdapter(adapter); } mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case MSG_GET_NOTIFY_LIST: Gson gson = new Gson(); List<CmtNotifyItem> cmtNotifyItems = gson.fromJson(mJson, new TypeToken<List<CmtNotifyItem>>(){}.getType()); DataSupport.deleteAll(CmtNotifyItem.class); DataSupport.saveAll(cmtNotifyItems); mRecyclerView.setAdapter(new NotifyCmtAdapter(cmtNotifyItems)); mSwipeRefreshLayout.setRefreshing(false); break; default: break; } } }; return view; } private void getData(){ String ip = getActivity().getResources().getString(R.string.ip_server); mClient = new OkHttpClient(); Request request = new Request.Builder() .url(ip+"api/getCmtNotify.action?token="+ TokenUtil.getToken(getActivity())) .build(); Call call = mClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { mJson = response.body().string(); mHandler.sendEmptyMessage(MSG_GET_NOTIFY_LIST); } }); } @Override public void onRefresh() { getData(); } @Override public void onResume() { super.onResume(); getData(); } }
apache-2.0
tumblr/colossus
colossus/src/main/scala/colossus/service/Callback.scala
19004
package colossus.service import akka.actor._ import colossus.metrics.logging.ColossusLogging import scala.util.{Failure, Success, Try} import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future, Promise} /** * This exception is only thrown when there's a uncaught exception in the execution block of a Callback. For example, {{{ val c: Callback[Foo] = getCallback() c.execute{ case Success(foo) => throw new Exception("exception") } }}} * will result in a `CallbackExecutionException` being thrown, however {{{ c.map{_ => throw new Exception("exception")}.execute() }}} * will not because the exception can still be recovered */ class CallbackExecutionException(cause: Throwable) extends Exception("Uncaught exception in callback Execution block", cause) /** * A Callback is a Monad for doing in-thread non-blocking operations. It is * essentially a "function builder" that uses function composition to chain * together a callback function that is eventually passed to another function. * * Normally if you have a function that requires a callback, the function looks something like:{{{ def doSomething(param, param, callBack: result => Unit) }}} * and then you'd call it like {{{ doSomething(arg1, arg2, result => println("got the result")) }}} * This is the well-known continuation pattern, and it something we'd like to avoid due to the common occurrance of deeply nested "callback hell". Instead, the `Callback` allows us to define out function as{{{ def doSomething(param1, param2): Callback[Result] }}} * and call it like {{{ val c = doSomething(arg1, arg2) c.map{ result => println("got the result") }.execute() }}} * * Thus, in practice working with Callbacks is very similar to working with Futures. The big differences from a future are: * * 1. Callbacks are not thread safe at all. They are entirely intended to stay inside a single worker. Otherwise just use Futures. * * 2. The execute() method needs to be called once the callback has been * fully built, which unlike futures requires some part of the code to know when a callback is ready to be invoked * * == Using Callbacks in Services == * * When building services, particularly when working with service clients, you * will usually be getting Callbacks back from clients when requests are sent. * *Do not call `execute` yourself!* on these Callbacks. They must be returned * as part of request processing, and Colossus will invoke the callback itself. * * == Using Callbacks elsewhere == * * If you are using Callbacks in some custom situation outside of services, be * aware that exceptions thrown inside a `map` or `flatMap` are properly caught * and can be recovered using `recover` and `recoverWith`, however exceptions * thrown in the "final" handler passed to `execute` are not caught. This is * because the final block cannot be mapped on (since it is only passed when * the callback is executed) and throwing the exception is preferrable to * suppressing it. * * Any exception that is thrown in this block is however rethrown as a * `CallbackExecutionException`. Therefore, any "trigger" function you wrap * inside a callback should properly catch this exception. * */ sealed trait Callback[+O] { def map[U](f: O => U): Callback[U] def flatMap[U](f: O => Callback[U]): Callback[U] def mapTry[U](f: Try[O] => Try[U]): Callback[U] def recover[U >: O](p: PartialFunction[Throwable, U]): Callback[U] def recoverWith[U >: O](p: PartialFunction[Throwable, Callback[U]]): Callback[U] final def withFilter(f: O => Boolean): Callback[O] = this.mapTry { _.filter(f) } def execute(onComplete: Try[O] => Unit = _ => ()) /** * Hook a future into the callback and execute the caller. Use this if you * need to hand a callback to something out-of-thread */ def toFuture(implicit ex: ExecutionContext): Future[O] = { val p = Promise[O]() this .map { o => p.success(o) } .recover { case o => p.failure(o) } .execute() p.future } //TODO: take a wild guess def zip[B](b: Callback[B]): Callback[(O, B)] = Callback.zip(this, b) def zip[B, C](b: Callback[B], c: Callback[C]): Callback[(O, B, C)] = { zip(b.zip(c)).map { case (x, (y, z)) => (x, y, z) } } } /** * A mapped callback is the most generalized implementation of a callback and is usually created when a callback has * been mapped on (i.e. map/mapTry/recover). An unmapped callback and constant callback are specialized versions, * that exist to improve performance. For example: * * {{{ MappedCallback[Int, Int](_ => Success(5), identity[Try[Int]]) <==> ConstantCallback[Int](Success(5)) }}} * * See the docs for [[Callback]] for more information. */ case class MappedCallback[I, O](trigger: (Try[I] => Unit) => Unit, handler: Try[I] => Try[O]) extends Callback[O] { def execute(onComplete: Try[O] => Unit = _ => ()) { try { trigger({ i => onComplete(handler(i)) }) } catch { case err: Throwable => throw new CallbackExecutionException(err) } } //since we're getting a new callback, we must rebuild the trigger so that the //new callback takes in the built handler function and not this one //notice the order of execution is handler(this callback) => f(the mapping) => cb (the handler function built after this call) def flatMap[U](f: O => Callback[U]): Callback[U] = { val newTrigger: (Try[U] => Unit) => Unit = cb => trigger(i => handler(i) match { case Success(value) => { Try(f(value)) match { case Success(callback) => callback.execute(cb) case Failure(err) => cb(Failure(err)) } } case Failure(err) => cb(Failure(err)) }) UnmappedCallback(newTrigger) } def map[U](f: O => U): Callback[U] = MappedCallback(trigger, { i: Try[I] => handler(i).flatMap(v => Try(f(v))) }) def mapTry[U](f: Try[O] => Try[U]): Callback[U] = MappedCallback(trigger, { i: Try[I] => try { f(handler(i)) } catch { case t: Throwable => Failure(t) } }) def recover[U >: O](p: PartialFunction[Throwable, U]): Callback[U] = MappedCallback( trigger, { i: Try[I] => handler(i) match { case Success(o) => Success(o) case Failure(err) => try { p.andThen(s => Success(s)) .applyOrElse(err, { e: Throwable => Failure[U](e) }) } catch { case t: Throwable => Failure(t) } } } ) def recoverWith[U >: O](p: PartialFunction[Throwable, Callback[U]]): Callback[U] = { val newtrigger: (Try[U] => Unit) => Unit = cb => trigger(i => handler(i) match { case Success(o) => cb(Success(o)) case Failure(err) => try { p.applyOrElse(err, (e: Throwable) => Callback.failed(e)).execute(cb) } catch { case t: Throwable => cb(Failure(t)) } }) UnmappedCallback(newtrigger) } } /** * A Callback that has not been mapped (i.e. map/mapTry/recover). Unmapped callback is the same as a mapped callback * that uses the identity function as the handler: * * {{{ UnmappedCallback[I](func) <==> MappedCallback[I, I](func, identity[Try[I]]) }}} * * An unmapped callback is 30% faster to execute than the mapped version. See the docs for [[Callback]] for more * information. */ case class UnmappedCallback[I](trigger: (Try[I] => Unit) => Unit) extends Callback[I] { def map[O](f: I => O): Callback[O] = MappedCallback(trigger, (i: Try[I]) => i.map(f)) def flatMap[O](f: I => Callback[O]): Callback[O] = { val newTrigger: (Try[O] => Unit) => Unit = cb => trigger { case Success(value) => { Try(f(value)) match { case Success(callback) => callback.execute(cb) case Failure(err) => cb(Failure(err)) } } case Failure(err) => cb(Failure(err)) } UnmappedCallback(newTrigger) } def mapTry[O](f: Try[I] => Try[O]): Callback[O] = MappedCallback(trigger, (i: Try[I]) => try { f(i) } catch { case t: Throwable => Failure(t) }) def execute(onComplete: Try[I] => Unit = _ => ()) { try { trigger({ i => onComplete(i) }) } catch { case err: Throwable => throw new CallbackExecutionException(err) } } def recover[U >: I](p: PartialFunction[Throwable, U]): Callback[U] = MappedCallback( trigger, (i: Try[I]) => i match { case Success(o) => Success(o) case Failure(err) => try { p.andThen(s => Success(s)) .applyOrElse(err, { e: Throwable => Failure[U](e) }) } catch { case t: Throwable => Failure(t) } } ) def recoverWith[U >: I](p: PartialFunction[Throwable, Callback[U]]): Callback[U] = { val newTrigger: (Try[U] => Unit) => Unit = cb => trigger { case Success(o) => cb(Success(o)) case Failure(err) => try { p.applyOrElse(err, (e: Throwable) => Callback.failed(e)).execute(cb) } catch { case t: Throwable => cb(Failure(t)) } } UnmappedCallback(newTrigger) } } /** * A Callback containing a constant value, usually created as the result of calling `Callback.success` or * `Callback.failure`. A constant callback is slightly faster than an unmapped callback, but only by a small margin. * See the docs for [[Callback]] for more information. */ case class ConstantCallback[O](value: Try[O]) extends Callback[O] { def map[U](f: O => U): Callback[U] = ConstantCallback(value.map(f)) def flatMap[U](f: O => Callback[U]): Callback[U] = value match { case Success(v) => try { f(v) } catch { case t: Throwable => ConstantCallback(Failure(t)) } case Failure(err) => ConstantCallback(Failure(err)) } def mapTry[U](f: Try[O] => Try[U]): Callback[U] = try { ConstantCallback(f(value)) } catch { case t: Throwable => ConstantCallback(Failure(t)) } def recover[U >: O](p: PartialFunction[Throwable, U]): Callback[U] = ConstantCallback(value.recover(p)) def recoverWith[U >: O](p: PartialFunction[Throwable, Callback[U]]): Callback[U] = value match { case Success(_) => this case Failure(err) => p.applyOrElse(err, (x: Throwable) => ConstantCallback(Failure(err))) } def execute(onComplete: Try[O] => Unit = _ => ()) { try { onComplete(value) } catch { case err: Throwable => throw new CallbackExecutionException(err) } } } /** * A `CallbackExecutor` represents a scheduler and execution environment for * [[Callback]]s and is required when either converting a `Future` to a * `Callback` or scheduling delayed execution of a `Callback`. Every * `Worker` provides an `CallbackExecutor` that can be * imported when doing such operations. * */ case class CallbackExecutor(context: ExecutionContext, executor: ActorRef) object CallbackExecutor { def apply(executor: ActorRef)(implicit ex: ExecutionContext): CallbackExecutor = CallbackExecutor(ex, executor) } object Callback { import scala.reflect.ClassTag def identity[A]: Function1[A, A] = (a: A) => a /** * The class tag is only needed to construct the array */ private class SequencedCallback[A: ClassTag](callback: Try[Seq[Try[A]]] => Unit, callbacks: Seq[Callback[A]]) { private val results = new Array[Try[A]](callbacks.size) private var numComplete = 0 def finish(index: Int, value: Try[A]) { results(index) = value numComplete += 1 if (numComplete == callbacks.size) { callback(Success(results.toList)) } } def execute() { if (callbacks.isEmpty) { callback(Success(Nil)) } else { callbacks.zipWithIndex.foreach { case (cb, index) => cb.execute(result => finish(index, result)) } } } } private class TupledCallback[A, B](a: Callback[A], b: Callback[B], completion: Try[(A, B)] => Unit) { private var aresult: Option[Try[A]] = None private var bresult: Option[Try[B]] = None def checkDone() { if (aresult.isDefined && bresult.isDefined) { val ab = for { va <- aresult.get vb <- bresult.get } yield (va, vb) completion(ab) } } def execute() { a.execute { a => aresult = Some(a); checkDone() } b.execute { b => bresult = Some(b); checkDone() } } } /** * Convert a function into a [[Callback]]. The function's parameter is a * continuation that will be the fully built mappings on the result * `Callback`. */ def apply[I](f: (Try[I] => Unit) => Unit): Callback[I] = UnmappedCallback(f) /** * Zip two [[Callback Callbacks]] together into a single `Callback` containing * a tuple of the results. */ def zip[A, B](a: Callback[A], b: Callback[B]): Callback[(A, B)] = { UnmappedCallback((f: Try[(A, B)] => Unit) => new TupledCallback[A, B](a, b, f).execute()) } /** * Convert a sequence of [[Callback Callbacks]] into a single `Callback` * contains a sequence of all the results. The result type is `Try[A]` so * that the success/failure of each individual `Callback` can be determined. */ def sequence[A: ClassTag](callbacks: Seq[Callback[A]]): Callback[Seq[Try[A]]] = { UnmappedCallback((f: Function1[Try[Seq[Try[A]]], Unit]) => new SequencedCallback(f, callbacks).execute()) } /** Create a callback that immediately returns the value * * @param value the successful value or error to complete with */ def complete[I](value: Try[I]): Callback[I] = ConstantCallback[I](value) /** returns a callback that will immediately succeed with the value as soon as its executed * * @param value the value to complete with */ def successful[I](value: I): Callback[I] = complete(Success(value)) /** returns a callback that will immediately fail with the given error * * @param err the error to return */ def failed[I](err: Throwable): Callback[I] = complete(Failure(err)) /** Convert a Future to a Callback * * Because Callbacks are expected to be handled entirely in a single thread, * you must provide an executor actor which will finish processing the * callback after the future is complete (eg if someone maps or flatMaps this * callback * * IMPORTANT - the executor actor must be able to handle the CallbackExec * message. All it has to do is call the execute() method. Or you can mixin * the CallbackExecutor trait and compose handleCallback with your receives!! * * @param future The future to convert * @param executor The executor actor to complete the callback * @return Callback linked to the Future */ def fromFuture[I](future: Future[I])(implicit executor: CallbackExecutor): Callback[I] = { implicit val ex = executor.context val trigger: (Try[I] => Unit) => Unit = cb => future.onComplete { res => executor.executor ! CallbackExec(() => cb(res)) } UnmappedCallback(trigger) } /** * Schedule a callback to be executed after a delay * * This method requires an implicit executor actor, which must be able to * handle CallbackExec messages * * @param in how long to wait before executing the callback * @param cb the callback to execute */ def schedule[I](in: FiniteDuration)(cb: Callback[I])(implicit executor: CallbackExecutor): Callback[I] = { implicit val ex = executor.context val trigger: (Try[I] => Unit) => Unit = x => executor.executor ! CallbackExec(() => cb.execute(x), Some(in)) UnmappedCallback(trigger) } object Implicits { implicit def objectToSuccessfulCallback[T](obj: T): Callback[T] = Callback.successful(obj) } object FutureImplicits { implicit def futureToCallback[T](f: Future[T])(implicit cbe: CallbackExecutor): Callback[T] = Callback.fromFuture(f) } } class PromiseException(message: String) extends Exception(message) /** * A CallbackPromise creates a callback which can be eventually filled in with * a value. This works similarly to a scala Promise. CallbackPromises are not * thread-safe. For thread-safety, simply use a scala Promise and use * Callback.fromFuture on it's corresponding Future. */ class CallbackPromise[T] { private var value: Option[Try[T]] = None private var completion: Option[Try[T] => Unit] = None val callback: Callback[T] = UnmappedCallback(trigger => { value match { case Some(v) => trigger(v) case None => { completion = Some(trigger) } } }) def success(t: T) { complete(Success(t)) } def failure(reason: Throwable) { complete(Failure(reason)) } def complete(v: Try[T]) { value match { case Some(f) => throw new CallbackExecutionException(new PromiseException("Promise already filled with value")) case None => completion match { case Some(c) => c(v) case None => value = Some(v) } } } } /* Message used to finish executing a callback after work was done in a future * * When using `Callback.fromFuture`, we need a way to bring execution back into * the thread executing the callback. So any entity executing a callback must * be an Actor implementing the `CallbackExecution` trait. This message is * sent to that trait on the completion of the converted Future, containing the * code for any `map` or `flatMap` that occurs on the callback. */ private[colossus] case class CallbackExec(cb: () => Unit, in: Option[FiniteDuration] = None) { def execute() { cb() } } /** * This little actor is needed because apparently actors that are running in a * pinned dispatcher AND are sending messages to themselves (like workers) * cannot use the scheduler...the messages never get sent. So we get around * this by sending a message to this actor living in the default dispatcher * which then does the proper scheduling */ private[colossus] class Delayer extends Actor with ColossusLogging { import context.dispatcher def receive = { case c: CallbackExec => { context.system.scheduler.scheduleOnce(c.in.get, sender(), CallbackExec(c.cb)) } } } private[colossus] trait CallbackExecution extends Actor with ColossusLogging { val delayer = context.actorOf(Props[Delayer]) val handleCallback: Receive = { case c: CallbackExec => c.in match { case None => c.execute() case Some(wait) => { delayer ! c } } } }
apache-2.0
hach-que/LevelEditor
LevelEditorCore/DesignViews/DesignView.cs
10546
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Sce.Atf; using Sce.Atf.Adaptation; using Sce.Atf.Controls; using MayaControlScheme = Sce.Atf.Rendering.MayaControlScheme; using MayaLaptopControlScheme = Sce.Atf.Rendering.MayaLaptopControlScheme; using MaxControlScheme = Sce.Atf.Rendering.MaxControlScheme; using ControlSchemes = Sce.Atf.Rendering.ControlSchemes; namespace LevelEditorCore { /// <summary> /// Base designview class /// </summary> public abstract class DesignView : IDesignView, ISnapSettings { public DesignView() { QuadView = new QuadPanelControl(); CameraController.LockOrthographic = true; m_frequency = Stopwatch.Frequency; m_baseTicks = Stopwatch.GetTimestamp(); m_lastTicks = m_baseTicks; } #region IDesignView Members public Control HostControl { get { return QuadView; } } public DesignViewControl ActiveView { get { return (DesignViewControl)QuadView.ActiveControl; } } /// <summary> /// Gets all the DesignViewControls</summary> public IEnumerable<DesignViewControl> AllViews { get { foreach (Control ctrl in QuadView.Controls) { DesignViewControl view = ctrl as DesignViewControl; if (view != null) yield return view; } } } /// <summary> /// Gets only DesigViewControls /// for the current ViewMode</summary> public IEnumerable<DesignViewControl> Views { get {return AllViews.Where(view => view.Width > 1 && view.Height > 1); } } private ViewModes m_viewMode = ViewModes.Quad; public ViewModes ViewMode { get { return m_viewMode; } set { m_viewMode = value; switch (m_viewMode) { case ViewModes.Single: QuadView.EnableX = false; QuadView.EnableY = false; QuadView.SplitterThickness = 0; QuadView.SplitX = 1.0f; QuadView.SplitY = 1.0f; break; case ViewModes.DualHorizontal: if (QuadView.ActiveControl == QuadView.TopLeft || QuadView.ActiveControl == QuadView.TopRight) QuadView.SplitX = 1.0f; else QuadView.SplitX = 0.0f; QuadView.SplitY = 0.5f; QuadView.EnableX = false; QuadView.EnableY = true; QuadView.SplitterThickness = DefaultSplitterThickness; break; case ViewModes.DualVertical: if (QuadView.ActiveControl == QuadView.TopLeft || QuadView.ActiveControl == QuadView.BottomLeft) QuadView.SplitY = 1.0f; else QuadView.SplitY = 0.0f; QuadView.SplitterThickness = DefaultSplitterThickness; QuadView.EnableX = true; QuadView.EnableY = false; QuadView.SplitX = 0.5f; break; case ViewModes.Quad: QuadView.EnableX = true; QuadView.EnableY = true; QuadView.SplitterThickness = DefaultSplitterThickness; QuadView.SplitX = 0.5f; QuadView.SplitY = 0.5f; break; } QuadView.Refresh(); } } public object Context { get { return m_context; } set { ContextChanging(this, EventArgs.Empty); if (m_validationContext != null) { m_validationContext.Cancelled -= validationContext_Refresh; m_validationContext.Ended -= validationContext_Refresh; } m_context = value; m_validationContext = m_context.As<IValidationContext>(); if (m_validationContext != null) { m_validationContext.Cancelled += validationContext_Refresh; m_validationContext.Ended += validationContext_Refresh; } ContextChanged(this, EventArgs.Empty); } } public event EventHandler ContextChanging = delegate { }; public event EventHandler ContextChanged = delegate { }; private void validationContext_Refresh(object sender, EventArgs e) { InvalidateViews(); } private object m_context = null; public IManipulator Manipulator { get { return m_manipulator; } set { m_manipulator = value; if (m_manipulator != null) { Point pt = ActiveView.PointToClient(Control.MousePosition); bool picked = m_manipulator.Pick(ActiveView, pt); ActiveView.Cursor = picked ? Cursors.SizeAll : Cursors.Default; } else { ActiveView.Cursor = Cursors.Default; } InvalidateViews(); } } public IPickFilter PickFilter { get; set; } [DefaultValue(typeof(Color), "0xFF606060")] public Color BackColor { get { return m_backColor; } set { m_backColor = value; InvalidateViews(); } } private Color m_backColor = Color.FromArgb(96, 96, 96); public void InvalidateViews() { foreach (DesignViewControl view in Views) view.Invalidate(); } /// <summary> /// Advances update/render by the given frame time.</summary> /// <param name="ft"></param> public abstract void Tick(FrameTime ft); /// <summary> /// Computes frame time and calls /// Tick(FrameTime ft) to advance /// update/rendering by on tick. /// </summary> public void Tick() { FrameTime ft = GetFrameTime(); Tick(ft); } /// <summary> /// Gets next frame time /// Used by Tick() and OnPaint</summary> public FrameTime GetFrameTime() { long curTick = Stopwatch.GetTimestamp(); double dt = (double)(curTick - m_lastTicks) / m_frequency; m_lastTicks = curTick; double TotalTime = (double)(m_lastTicks - m_baseTicks) / m_frequency; return new FrameTime(TotalTime, (float)dt); } #endregion #region ISnapSettings Members [DefaultValue(false)] public bool SnapVertex { get; set; } [DefaultValue(false)] public bool RotateOnSnap { get; set; } [DefaultValue(SnapFromMode.Pivot)] public SnapFromMode SnapFrom { get; set; } [DefaultValue(false)] public bool ManipulateLocalAxis { get; set; } [DefaultValue((float)(5.0f * (Math.PI / 180.0f)))] public float SnapAngle { get{return m_SnapAngle;} set { m_SnapAngle = MathUtil.Clamp(value,0, (float) (2.0 * Math.PI)); } } #endregion /// <summary> /// Distance to the camera's far clipping plane.</summary> [DefaultValue(2048.0f)] public float CameraFarZ { get { return m_cameraFarZ; } set { m_cameraFarZ = value; foreach (DesignViewControl view in QuadView.Controls) { view.Camera.FarZ = m_cameraFarZ; } } } /// <summary> /// Gets/sets input scheme.</summary> [DefaultValue(ControlSchemes.Maya)] public ControlSchemes ControlScheme { get { return m_controlScheme; } set { switch (value) { case ControlSchemes.Maya: InputScheme.ActiveControlScheme = new MayaControlScheme(); break; case ControlSchemes.MayaLaptop: InputScheme.ActiveControlScheme = new MayaLaptopControlScheme(); break; case ControlSchemes.Max: InputScheme.ActiveControlScheme = new MaxControlScheme(); break; } m_controlScheme = value; } } protected const int DefaultSplitterThickness = 8; protected readonly QuadPanelControl QuadView; #region private members private float m_cameraFarZ = 2048; private ControlSchemes m_controlScheme = ControlSchemes.Maya; private float m_SnapAngle = (float)(5.0 * (Math.PI / 180.0f)); private IManipulator m_manipulator; private IValidationContext m_validationContext; // update and render variables. private double m_frequency; private readonly long m_baseTicks; private long m_lastTicks; #endregion } }
apache-2.0
Talend/components
components/components-googledrive/components-googledrive-definition/src/main/java/org/talend/components/google/drive/copy/GoogleDriveCopyProperties.java
4697
//============================================================================ // // Copyright (C) 2006-2022 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // //============================================================================ package org.talend.components.google.drive.copy; import static org.talend.daikon.properties.property.PropertyFactory.newBoolean; import static org.talend.daikon.properties.property.PropertyFactory.newEnum; import static org.talend.daikon.properties.property.PropertyFactory.newString; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.talend.components.google.drive.GoogleDriveComponentProperties; import org.talend.daikon.avro.SchemaConstants; import org.talend.daikon.properties.presentation.Form; import org.talend.daikon.properties.presentation.Widget; import org.talend.daikon.properties.property.Property; public class GoogleDriveCopyProperties extends GoogleDriveComponentProperties { public enum CopyMode { File, Folder } public Property<CopyMode> copyMode = newEnum("copyMode", CopyMode.class); public Property<AccessMethod> sourceAccessMethod = newEnum("sourceAccessMethod", AccessMethod.class); public Property<String> source = newString("source"); public Property<AccessMethod> destinationFolderAccessMethod = newEnum("destinationFolderAccessMethod", AccessMethod.class); public Property<String> destinationFolder = newString("destinationFolder"); public Property<Boolean> rename = newBoolean("rename"); public Property<String> newName = newString("newName"); public Property<Boolean> deleteSourceFile = newBoolean("deleteSourceFile"); public GoogleDriveCopyProperties(String name) { super(name); } @Override public void setupProperties() { super.setupProperties(); sourceAccessMethod.setPossibleValues(AccessMethod.values()); sourceAccessMethod.setValue(AccessMethod.Name); source.setValue(""); destinationFolderAccessMethod.setPossibleValues(AccessMethod.values()); destinationFolderAccessMethod.setValue(AccessMethod.Name); destinationFolder.setValue(""); copyMode.setPossibleValues(CopyMode.values()); copyMode.setValue(CopyMode.File); rename.setValue(false); deleteSourceFile.setValue(false); Schema s = SchemaBuilder.builder().record(GoogleDriveCopyDefinition.COMPONENT_NAME).fields()// .name(GoogleDriveCopyDefinition.RETURN_SOURCE_ID).type().nullable().stringType().noDefault()// .name(GoogleDriveCopyDefinition.RETURN_DESTINATION_ID).type().nullable().stringType().noDefault()// .endRecord(); s.addProp(SchemaConstants.TALEND_IS_LOCKED, "true"); schemaMain.schema.setValue(s); } @Override public void setupLayout() { super.setupLayout(); Form mainForm = getForm(Form.MAIN); mainForm.addRow(copyMode); mainForm.addRow(source); mainForm.addColumn(sourceAccessMethod); mainForm.addRow(destinationFolder); mainForm.addColumn(destinationFolderAccessMethod); mainForm.addRow(rename); mainForm.addRow(newName); mainForm.addRow(deleteSourceFile); mainForm.addRow(schemaMain.getForm(Form.REFERENCE)); } @Override public void refreshLayout(Form form) { super.refreshLayout(form); if (Form.MAIN.equals(form.getName())) { if (CopyMode.File.equals(copyMode.getValue())) { form.getWidget(deleteSourceFile.getName()).setVisible(true); } else { form.getWidget(deleteSourceFile.getName()).setVisible(false); } form.getWidget(newName.getName()).setVisible(rename.getValue()); } else if (Form.ADVANCED.equals(form.getName())) { form .getWidget(includeSharedItems.getName()) .setHidden(checkIdAccessMethod(destinationFolderAccessMethod.getValue()) && checkIdAccessMethod(sourceAccessMethod.getValue())); } } public void afterSourceAccessMethod() { refreshLayout(getForm(Form.ADVANCED)); } public void afterCopyMode() { refreshLayout(getForm(Form.MAIN)); } public void afterRename() { refreshLayout(getForm(Form.MAIN)); } }
apache-2.0
linuxska/repoVJP
plugins/sfGuardPlugin/lib/model/map/sfGuardPermissionTableMap.php
2308
<?php /** * This class defines the structure of the 'sf_guard_permission' table. * * * This class was autogenerated by Propel 1.4.2 on: * * Mon Jul 15 20:06:25 2013 * * * This map class is used by Propel to do runtime db structure discovery. * For example, the createSelectSql() method checks the type of a given column used in an * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive * (i.e. if it's a text column type). * * @package plugins.sfGuardPlugin.lib.model.map */ class sfGuardPermissionTableMap extends TableMap { /** * The (dot-path) name of this class */ const CLASS_NAME = 'plugins.sfGuardPlugin.lib.model.map.sfGuardPermissionTableMap'; /** * Initialize the table attributes, columns and validators * Relations are not initialized by this method since they are lazy loaded * * @return void * @throws PropelException */ public function initialize() { // attributes $this->setName('sf_guard_permission'); $this->setPhpName('sfGuardPermission'); $this->setClassname('sfGuardPermission'); $this->setPackage('plugins.sfGuardPlugin.lib.model'); $this->setUseIdGenerator(true); $this->setPrimaryKeyMethodInfo('sf_guard_permission_id_seq'); // columns $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); $this->addColumn('NAME', 'Name', 'VARCHAR', true, 255, null); $this->addColumn('DESCRIPTION', 'Description', 'LONGVARCHAR', false, null, null); // validators } // initialize() /** * Build the RelationMap objects for this table relationships */ public function buildRelations() { $this->addRelation('sfGuardGroupPermission', 'sfGuardGroupPermission', RelationMap::ONE_TO_MANY, array('id' => 'permission_id', ), 'CASCADE', null); $this->addRelation('sfGuardUserPermission', 'sfGuardUserPermission', RelationMap::ONE_TO_MANY, array('id' => 'permission_id', ), 'CASCADE', null); } // buildRelations() /** * * Gets the list of behaviors registered for this table * * @return array Associative array (name => parameters) of behaviors */ public function getBehaviors() { return array( 'symfony' => array('form' => 'true', 'filter' => 'true', ), 'symfony_behaviors' => array(), ); } // getBehaviors() } // sfGuardPermissionTableMap
apache-2.0
vimaier/conqat
org.conqat.engine.sourcecode/src/org/conqat/engine/sourcecode/analysis/shallowparsed/ShallowParsingSuccessAssessor.java
4026
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.sourcecode.analysis.shallowparsed; import java.util.List; import org.conqat.engine.core.core.AConQATFieldParameter; import org.conqat.engine.core.core.AConQATKey; import org.conqat.engine.core.core.AConQATProcessor; import org.conqat.engine.core.core.ConQATException; import org.conqat.engine.sourcecode.analysis.AnalysisProblemsProcessorBase; import org.conqat.engine.sourcecode.resource.ITokenElement; import org.conqat.engine.sourcecode.shallowparser.ShallowParserFactory; import org.conqat.engine.sourcecode.shallowparser.framework.ShallowEntity; import org.conqat.engine.sourcecode.shallowparser.framework.ShallowEntityTraversalUtils; /** * {@ConQAT.Doc} * * @author $Author: heinemann $ * @version $Rev: 44267 $ * @ConQAT.Rating GREEN Hash: 54B5DE21FC5F12C7A1842D1B670641A5 */ @AConQATProcessor(description = "Annotates each element with an assessment of whether it could be shallow parsed or not. " + "Optionally, findings can be created for parser problems.") public class ShallowParsingSuccessAssessor extends AnalysisProblemsProcessorBase { /** Finding group name used. */ private static final String FINDING_GROUP_NAME = "Parser Problems"; /** {ConQAT.Doc} */ @AConQATKey(description = "Green if the element could be parsed successfully, red otherwise.", type = "org.conqat.lib.commons.assessment.Assessment") public static final String PARSING_ASSESSMENT_KEY = "parseable"; /** {ConQAT.Doc} */ @AConQATKey(description = "Textual description of the parse problem.", type = "java.lang.String") public static final String PARSING_ERROR_KEY = "parse error"; /** {ConQAT.Doc} */ @AConQATFieldParameter(parameter = "missing-parser", attribute = "report", optional = true, description = "" + "Determines whether to also report if an element is found for which no parser is available. Default is true.") public boolean reportMissingParser = true; /** Constructor. */ public ShallowParsingSuccessAssessor() { super(PARSING_ASSESSMENT_KEY, PARSING_ERROR_KEY, FINDING_GROUP_NAME); } /** * {@inheritDoc} * * @throws ConQATException * in case of underlying I/O problems. */ @Override protected String getAnalysisErrorMessage(ITokenElement element) throws ConQATException { if (!ShallowParserFactory.supportsLanguage(element.getLanguage())) { if (reportMissingParser) { return "No parser available for language " + element.getLanguage(); } return null; } List<ShallowEntity> entities = ShallowParserFactory.parse(element, getLogger()); ShallowEntity incomplete = ShallowEntityTraversalUtils .findIncompleteEntity(entities); if (incomplete != null) { return "Incompletely parsed node: " + incomplete.toLocalStringUnfiltered(element); } return null; } }
apache-2.0
gustavovaliati/training_Symfony2.8_Angular1.5_AdminLTE
front-root/src/js/app.js
1070
import angular from 'angular'; // Import our app config files import constants from './config/app.constants'; import appConfig from './config/app.config'; import appRun from './config/app.run'; import 'angular-ui-router'; // Import our templates file (generated by Gulp) import './config/app.templates'; // Import our app functionaity import './layout'; import './components'; import './home'; import './profile'; import './article'; import './services'; import './auth'; import './settings'; import './editor'; import './ticket'; // Create and bootstrap application const requires = [ 'ui.router', 'templates', 'app.layout', 'app.components', 'app.home', 'app.profile', 'app.article', 'app.services', 'app.auth', 'app.settings', 'app.editor', 'app.ticket' ]; // Mount on window for testing window.app = angular.module('app', requires); angular.module('app').constant('AppConstants', constants); angular.module('app').config(appConfig); angular.module('app').run(appRun); angular.bootstrap(document, ['app'], { strictDi: true });
apache-2.0
vivantech/kc_fixes
src/main/java/org/kuali/kra/proposaldevelopment/document/ProposalDevelopmentDocument.java
26130
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.proposaldevelopment.document; import org.apache.commons.lang.StringUtils; import org.kuali.kra.authorization.KraAuthorizationConstants; import org.kuali.kra.authorization.Task; import org.kuali.kra.bo.CustomAttributeDocValue; import org.kuali.kra.bo.DocumentCustomData; import org.kuali.kra.budget.core.Budget; import org.kuali.kra.budget.document.BudgetDocument; import org.kuali.kra.budget.document.BudgetParentDocument; import org.kuali.kra.budget.versions.BudgetDocumentVersion; import org.kuali.kra.common.permissions.Permissionable; import org.kuali.kra.infrastructure.*; import org.kuali.kra.institutionalproposal.service.InstitutionalProposalService; import org.kuali.kra.kew.KraDocumentRejectionService; import org.kuali.kra.krms.KcKrmsConstants; import org.kuali.kra.krms.KrmsRulesContext; import org.kuali.kra.krms.service.impl.KcKrmsFactBuilderServiceHelper; import org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal; import org.kuali.kra.proposaldevelopment.document.authorization.ProposalTask; import org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyException; import org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService; import org.kuali.kra.proposaldevelopment.service.ProposalStateService; import org.kuali.kra.proposaldevelopment.service.ProposalStatusService; import org.kuali.kra.workflow.KraDocumentXMLMaterializer; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants.COMPONENT; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants.NAMESPACE; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kew.api.KewApiServiceLocator; import org.kuali.rice.kew.api.action.ActionTaken; import org.kuali.rice.kew.api.action.WorkflowDocumentActionsService; import org.kuali.rice.kew.framework.postprocessor.ActionTakenEvent; import org.kuali.rice.kew.framework.postprocessor.DocumentRouteStatusChange; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kns.service.KNSServiceLocator; import org.kuali.rice.kns.web.ui.ExtraButton; import org.kuali.rice.krad.datadictionary.DataDictionary; import org.kuali.rice.krad.datadictionary.DocumentEntry; import org.kuali.rice.krad.document.Copyable; import org.kuali.rice.krad.document.SessionDocument; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.workflow.KualiDocumentXmlMaterializer; import org.kuali.rice.krms.api.engine.Facts; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; @NAMESPACE(namespace=Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT) @COMPONENT(component=ParameterConstants.DOCUMENT_COMPONENT) public class ProposalDevelopmentDocument extends BudgetParentDocument<DevelopmentProposal> implements Copyable, SessionDocument, Permissionable, KrmsRulesContext { private static org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(ProposalDevelopmentDocument.class); public static final String DOCUMENT_TYPE_CODE = "PRDV"; private static final String KRA_EXTERNALIZABLE_IMAGES_URI_KEY = "kra.externalizable.images.url"; private static final String RETURN_TO_PROPOSAL_ALT_TEXT = "return to proposal"; private static final String RETURN_TO_PROPOSAL_METHOD_TO_CALL = "methodToCall.returnToProposal"; private static final String HIERARCHY_CHILD_SPLITNODE_QUESTION = "isHierarchyChild"; private static final long serialVersionUID = 2958631745964610527L; private List<DevelopmentProposal> developmentProposalList; private List<BudgetDocumentVersion> budgetDocumentVersions; private transient Boolean allowsNoteAttachments; //used to indicate if the proposal has been deleted private boolean proposalDeleted; /* Currently this property is just used for UI display. * If it becomes part of the domain, it should probably move to DevelopmentProposal.java */ private String institutionalProposalNumber; private String saveXmlFolderName; private List<CustomAttributeDocValue> customDataList; public ProposalDevelopmentDocument() { super(); developmentProposalList = new ArrayList<DevelopmentProposal>(); DevelopmentProposal newProposal = new DevelopmentProposal(); newProposal.setProposalDocument(this); developmentProposalList.add(newProposal); budgetDocumentVersions = new ArrayList<BudgetDocumentVersion>(); customDataList = new ArrayList<CustomAttributeDocValue>(); } public List<DevelopmentProposal> getDevelopmentProposalList() { return developmentProposalList; } public void setDevelopmentProposalList(List<DevelopmentProposal> proposalList) { this.developmentProposalList = proposalList; } public DevelopmentProposal getDevelopmentProposal() { if (!developmentProposalList.isEmpty()) { return developmentProposalList.get(0); } else { //return new and empty development proposal to avoid NPEs when proposal has been deleted return new DevelopmentProposal(); } } public void setDevelopmentProposal(DevelopmentProposal proposal) { developmentProposalList.set(0, proposal); } public String getInstitutionalProposalNumber() { return institutionalProposalNumber; } public void setInstitutionalProposalNumber(String institutionalProposalNumber) { this.institutionalProposalNumber = institutionalProposalNumber; } @Override public void initialize() { super.initialize(); getDevelopmentProposal().initializeOwnedByUnitNumber(); } @Override public void doRouteStatusChange(DocumentRouteStatusChange dto) { super.doRouteStatusChange(dto); String newStatus = dto.getNewRouteStatus(); String oldStatus = dto.getOldRouteStatus(); if( LOG.isDebugEnabled() ) { LOG.debug(String.format( "Route Status change for document %s from %s to %s" , this.getDocumentNumber(), oldStatus, newStatus ) ); } if (!isProposalDeleted()) { DevelopmentProposal bp = this.getDevelopmentProposal(); ProposalHierarchyService hierarchyService = KraServiceLocator.getService(ProposalHierarchyService.class); LOG.info(String.format("Route status change for document %s - proposal number %s is moving from %s to %s", bp .getProposalDocument().getDocumentHeader().getDocumentNumber(), bp.getProposalNumber(), oldStatus, newStatus)); if (bp.isParent()) { try { hierarchyService.routeHierarchyChildren( this, dto ); } catch (ProposalHierarchyException e) { throw new RuntimeException( "ProposalHierarchyException thrown while routing children.", e ); } } else if ( !bp.isInHierarchy() ) { try { hierarchyService.calculateAndSetProposalAppDocStatus(this, dto ); } catch ( ProposalHierarchyException pe ) { throw new RuntimeException( String.format( "ProposalHierarchyException thrown while updating app doc status for document %s", getDocumentNumber() )); } } bp.setProposalStateTypeCode( KraServiceLocator.getService(ProposalStateService.class).getProposalStateTypeCode( this, true, false ) ); } } /** * @see org.kuali.rice.krad.document.Document#doActionTaken(org.kuali.rice.kew.framework.postprocessor.ActionTakenEvent) */ @Override public void doActionTaken(ActionTakenEvent event) { super.doActionTaken(event); ActionTaken actionTaken = event.getActionTaken(); if( LOG.isDebugEnabled() ) { LOG.debug( String.format( "Action taken on document %s: event code %s, action taken is %s" , getDocumentNumber(), event.getDocumentEventCode(), actionTaken.getActionTaken().getCode()) ); } if (!isProposalDeleted()) { ProposalHierarchyService hService = KraServiceLocator.getService(ProposalHierarchyService.class); KraDocumentRejectionService documentRejectionService = KraServiceLocator.getService(KraDocumentRejectionService.class); if( StringUtils.equals( KewApiConstants.ACTION_TAKEN_APPROVED_CD, actionTaken.getActionTaken().getCode()) ) { try { if( documentRejectionService.isDocumentOnInitialNode(this) ) { DocumentRouteStatusChange dto = new DocumentRouteStatusChange(getDocumentHeader().getWorkflowDocument().getDocumentId(), getDocumentNumber(), KewApiConstants.ROUTE_HEADER_ENROUTE_CD, KewApiConstants.ROUTE_HEADER_ENROUTE_CD); //DocumentRouteStatusChange.documentEventCode is always returned as rt_status_change //dto.setDocumentEventCode("REJECTED_APPROVED"); if( getDevelopmentProposal().isParent() ) { hService.routeHierarchyChildren(this, dto ); hService.calculateAndSetProposalAppDocStatus(this, dto); } if( !getDevelopmentProposal().isInHierarchy() ) hService.calculateAndSetProposalAppDocStatus(this, dto); } } catch( ProposalHierarchyException pe ) { throw new RuntimeException( String.format("ProposalHeierachyException encountered trying to re-submit rejected parent document:%s",getDocumentNumber()), pe ); } catch( Exception we) { throw new RuntimeException( String.format( "Exception trying to re-submit rejected parent:%s", getDocumentNumber() ),we); } } String pCode = getDevelopmentProposal().getProposalStateTypeCode(); getDevelopmentProposal().setProposalStateTypeCode(KraServiceLocator.getService(ProposalStateService.class).getProposalStateTypeCode(this, false, documentRejectionService.isDocumentOnInitialNode(this))); if( !StringUtils.equals(pCode, getDevelopmentProposal().getProposalStateTypeCode() )) { getDevelopmentProposal().refresh(); KraServiceLocator.getService(BusinessObjectService.class).save(getDevelopmentProposal()); } if( getDevelopmentProposal().isChild() && StringUtils.equals(KewApiConstants.ACTION_TAKEN_CANCELED_CD, actionTaken.getActionTaken().getCode())) { try { hService.removeFromHierarchy(this.getDevelopmentProposal() ); } catch (ProposalHierarchyException e) { throw new RuntimeException( String.format( "COULD NOT REMOVE CHILD:%s", this.getDevelopmentProposal().getProposalNumber() ) ); } } if (isLastSubmitterApprovalAction(event.getActionTaken()) && shouldAutogenerateInstitutionalProposal()) { InstitutionalProposalService institutionalProposalService = KraServiceLocator.getService(InstitutionalProposalService.class); String proposalNumber = institutionalProposalService.createInstitutionalProposal(this.getDevelopmentProposal(), this.getFinalBudgetForThisProposal()); this.setInstitutionalProposalNumber(proposalNumber); } } } private boolean isLastSubmitterApprovalAction(ActionTaken actionTaken) { WorkflowDocumentActionsService workflowInfo = KewApiServiceLocator.getWorkflowDocumentActionsService(); return actionTaken.getActionTaken().getCode().equals(KewApiConstants.ACTION_TAKEN_APPROVED_CD) && workflowInfo.isFinalApprover(actionTaken.getDocumentId(), actionTaken.getPrincipalId()); // also check person is last submitter. Need KIM for this. } private boolean shouldAutogenerateInstitutionalProposal() { return getParameterService().getParameterValueAsBoolean( Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT, ParameterConstants.DOCUMENT_COMPONENT, KeyConstants.AUTOGENERATE_INSTITUTIONAL_PROPOSAL_PARAM); } protected ConfigurationService getKualiConfigurationService() { return CoreApiServiceLocator.getKualiConfigurationService(); } protected ParameterService getParameterService() { return KraServiceLocator.getService(ParameterService.class); } protected DateTimeService getDateTimeService() { return KraServiceLocator.getService(DateTimeService.class); } public Budget getFinalBudgetForThisProposal() { BudgetDocumentVersion budgetDocumentVersion = this.getFinalBudgetVersion(); if (budgetDocumentVersion != null) { return budgetDocumentVersion.getFinalBudget(); } return null; } public String getFinalrateClassCode() { String retVal = ""; Budget finalBudget = getFinalBudgetForThisProposal(); if (finalBudget != null && finalBudget.getRateClass().getRateClassCode() != null) { retVal = finalBudget.getRateClass().getRateClassCode(); } return retVal; } public String getDocumentTypeCode() { return DOCUMENT_TYPE_CODE; } /** * Wraps a document in an instance of KualiDocumentXmlMaterializer, that provides additional metadata for serialization * * @see org.kuali.core.document.Document#wrapDocumentWithMetadataForXmlSerialization() */ @Override // This method should go away in favor of using DD workflowProperties bean to serialize properties public KualiDocumentXmlMaterializer wrapDocumentWithMetadataForXmlSerialization() { KraDocumentXMLMaterializer xmlWrapper = (KraDocumentXMLMaterializer) super.wrapDocumentWithMetadataForXmlSerialization(); xmlWrapper.setRolepersons(getAllRolePersons()); return xmlWrapper; } @Override public void prepareForSave() { super.prepareForSave(); if (!isProposalDeleted()) { getDevelopmentProposal().updateS2sOpportunity(); KraServiceLocator.getService(ProposalStatusService.class).saveBudgetFinalVersionStatus(this); if (getBudgetDocumentVersions() != null) { updateDocumentDescriptions(getBudgetDocumentVersions()); } } } @Override public void processAfterRetrieve() { super.processAfterRetrieve(); if (!isProposalDeleted()) { KraServiceLocator.getService(ProposalStatusService.class).loadBudgetStatus(this.getDevelopmentProposal()); getDevelopmentProposal().updateProposalChangeHistory(); } } public Boolean getAllowsNoteAttachments() { if (allowsNoteAttachments == null) { DataDictionary dataDictionary = KNSServiceLocator.getDataDictionaryService().getDataDictionary(); DocumentEntry entry = (DocumentEntry) dataDictionary.getDocumentEntry(getClass().getName()); allowsNoteAttachments = entry.getAllowsNoteAttachments(); } return allowsNoteAttachments; } public void setAllowsNoteAttachments(boolean allowsNoteAttachments) { this.allowsNoteAttachments = allowsNoteAttachments; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getRoleNames() */ public List<String> getRoleNames() { List<String> roleNames = new ArrayList<String>(); roleNames.add(RoleConstants.AGGREGATOR); roleNames.add(RoleConstants.BUDGET_CREATOR); roleNames.add(RoleConstants.NARRATIVE_WRITER); roleNames.add(RoleConstants.VIEWER); roleNames.add("approver"); return roleNames; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentNumberForPermission() */ public String getDocumentNumberForPermission() { return getDevelopmentProposal().getProposalNumber(); } /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentKey() */ public String getDocumentKey() { return Permissionable.PROPOSAL_KEY; } /** * @see org.kuali.core.bo.PersistableBusinessObjectBase#buildListOfDeletionAwareLists() */ @SuppressWarnings("unchecked") @Override public List buildListOfDeletionAwareLists() { List managedLists = super.buildListOfDeletionAwareLists(); managedLists.addAll(getDevelopmentProposal().buildListOfDeletionAwareLists()); managedLists.add(developmentProposalList); return managedLists; } /** * Sets the budgetDocumentVersions attribute value. * @param budgetDocumentVersions The budgetDocumentVersions to set. */ public void setBudgetDocumentVersions(List<BudgetDocumentVersion> budgetDocumentVersions) { this.budgetDocumentVersions = budgetDocumentVersions; } /** * Gets the budgetDocumentVersions attribute. * @return Returns the budgetDocumentVersions. */ public List<BudgetDocumentVersion> getBudgetDocumentVersions() { return budgetDocumentVersions; } @Override public Task getParentAuthZTask(String taskName) { return new ProposalTask(taskName,this); } @Override public boolean isComplete() { return getDevelopmentProposal().isProposalComplete(); } @Override public void saveBudgetFinalVersionStatus(BudgetDocument budgetDocument) { getService(ProposalStatusService.class).saveBudgetFinalVersionStatus(this); } @Override public void processAfterRetrieveForBudget(BudgetDocument budgetDocument) { getService(ProposalStatusService.class).loadBudgetStatusByProposalDocumentNumber(budgetDocument.getParentDocumentKey()); } @Override public String getTaskGroupName() { return TaskGroupName.PROPOSAL_BUDGET; } @Override public ExtraButton configureReturnToParentTopButton() { ExtraButton returnToProposalButton = new ExtraButton(); returnToProposalButton.setExtraButtonProperty(RETURN_TO_PROPOSAL_METHOD_TO_CALL); returnToProposalButton.setExtraButtonSource(buildExtraButtonSourceURI("tinybutton-retprop.gif")); returnToProposalButton.setExtraButtonAltText(RETURN_TO_PROPOSAL_ALT_TEXT); return returnToProposalButton; } /** * This method does what its name says * @param buttonFileName * @return */ private String buildExtraButtonSourceURI(String buttonFileName) { return getKualiConfigurationService().getPropertyValueAsString(KRA_EXTERNALIZABLE_IMAGES_URI_KEY) + buttonFileName; } @Override public DevelopmentProposal getBudgetParent() { return getDevelopmentProposal(); } /** {@inheritDoc} */ public String getDocumentBoNumber() { return getDevelopmentProposal().getProposalNumber(); } @Override public Permissionable getBudgetPermissionable() { return new Permissionable(){ public String getDocumentKey() { return Permissionable.PROPOSAL_BUDGET_KEY; } public String getDocumentNumberForPermission() { return getDevelopmentProposal().getProposalNumber(); } public List<String> getRoleNames() { List<String> roleNames = new ArrayList<String>(); return roleNames; } public String getNamespace() { return Constants.MODULE_NAMESPACE_BUDGET; } public String getLeadUnitNumber() { return getDevelopmentProposal().getOwnedByUnitNumber(); } public String getDocumentRoleTypeCode() { return RoleConstants.PROPOSAL_ROLE_TYPE; } public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) { } }; } /** * @see org.kuali.kra.document.ResearchDocumentBase#answerSplitNodeQuestion(java.lang.String) */ @Override public boolean answerSplitNodeQuestion( String routeNodeName ) throws Exception { LOG.debug("Processing answerSplitNodeQuestion:"+routeNodeName ); if( StringUtils.equals(HIERARCHY_CHILD_SPLITNODE_QUESTION, routeNodeName )) { return getDevelopmentProposal().isChild(); } //defer to the super class. ResearchDocumentBase will throw the UnsupportedOperationException //if no super class answers the question. return super.answerSplitNodeQuestion(routeNodeName); } public String getNamespace() { return Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT; } public String getLeadUnitNumber() { return getDevelopmentProposal().getOwnedByUnitNumber(); } public String getDocumentRoleTypeCode() { return RoleConstants.PROPOSAL_ROLE_TYPE; } public String getProposalBudgetFlag() { return "true"; } /** * This method is to check whether rice async routing is ok now. * Close to hack. called by holdingpageaction * Different document type may have different routing set up, so each document type * can implement its own isProcessComplete * @return */ public boolean isProcessComplete() { boolean isComplete = false; if (getDocumentHeader().hasWorkflowDocument()) { String docRouteStatus = getDocumentHeader().getWorkflowDocument().getStatus().getCode(); if (KewApiConstants.ROUTE_HEADER_ENROUTE_CD.equals(docRouteStatus) || KewApiConstants.ROUTE_HEADER_PROCESSED_CD.equals(docRouteStatus) || KewApiConstants.ROUTE_HEADER_FINAL_CD.equals(docRouteStatus)) { isComplete = true; } } return isComplete; } public boolean isProposalDeleted() { return proposalDeleted; } public void setProposalDeleted(boolean proposalDeleted) { this.proposalDeleted = proposalDeleted; } public void refreshBudgetDocumentVersions() { this.refreshReferenceObject("budgetDocumentVersions"); } public void populateContextQualifiers(Map<String, String> qualifiers) { qualifiers.put("namespaceCode", Constants.MODULE_NAMESPACE_PROPOSAL_DEVELOPMENT); qualifiers.put("name", KcKrmsConstants.ProposalDevelopment.PROPOSAL_DEVELOPMENT_CONTEXT); } public void addFacts(Facts.Builder factsBuilder) { KcKrmsFactBuilderServiceHelper fbService = KraServiceLocator.getService("proposalDevelopmentFactBuilderService"); fbService.addFacts(factsBuilder, this); } public void populateAgendaQualifiers(Map<String, String> qualifiers) { qualifiers.put(KcKrmsConstants.UNIT_NUMBER, getLeadUnitNumber()); } public void defaultDocumentDescription() { DevelopmentProposal proposal = getDevelopmentProposal(); String desc = String.format("%s; Proposal No: %s; PI: %s; Sponsor: %s; Due Date: %s", proposal.getTitle() != null ? proposal.getTitle().substring(0, Math.min(proposal.getTitle().length(), 19)) : "null", proposal.getProposalNumber(), proposal.getPrincipalInvestigatorName(), proposal.getSponsorName(), proposal.getDeadlineDate() != null ? getDateTimeService().toDateString(proposal.getDeadlineDate()) : "null"); getDocumentHeader().setDocumentDescription(desc); } @Override public List<? extends DocumentCustomData> getDocumentCustomData() { return getCustomDataList(); } public List<CustomAttributeDocValue> getCustomDataList() { return customDataList; } public void setCustomDataList(List<CustomAttributeDocValue> customDataList) { this.customDataList = customDataList; } public String getSaveXmlFolderName() { return saveXmlFolderName; } public void setSaveXmlFolderName(String saveXmlFolderName) { this.saveXmlFolderName = saveXmlFolderName; } public boolean isDefaultDocumentDescription() { return getParameterService().getParameterValueAsBoolean(ProposalDevelopmentDocument.class, Constants.HIDE_AND_DEFAULT_PROP_DEV_DOC_DESC_PARAM); } @Override public String getDocumentTitle() { if (isDefaultDocumentDescription()) { return this.getDocumentHeader().getDocumentDescription(); } else { return super.getDocumentTitle(); } } }
apache-2.0
cloudbase/lis-tempest
tempest/api/network/admin/test_load_balancer_admin_actions.py
5056
# Copyright 2014 Mirantis.inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.api.network import base from tempest.common.utils import data_utils from tempest import test class LoadBalancerAdminTestJSON(base.BaseAdminNetworkTest): _interface = 'json' """ Test admin actions for load balancer. Create VIP for another tenant Create health monitor for another tenant """ @classmethod @test.safe_setup def setUpClass(cls): super(LoadBalancerAdminTestJSON, cls).setUpClass() if not test.is_extension_enabled('lbaas', 'network'): msg = "lbaas extension not enabled." raise cls.skipException(msg) cls.force_tenant_isolation = True manager = cls.get_client_manager() cls.client = manager.network_client cls.tenant_id = cls.isolated_creds.get_primary_creds().tenant_id cls.network = cls.create_network() cls.subnet = cls.create_subnet(cls.network) cls.pool = cls.create_pool(data_utils.rand_name('pool-'), "ROUND_ROBIN", "HTTP", cls.subnet) @test.attr(type='smoke') def test_create_vip_as_admin_for_another_tenant(self): name = data_utils.rand_name('vip-') _, body = self.admin_client.create_pool( name=data_utils.rand_name('pool-'), lb_method="ROUND_ROBIN", protocol="HTTP", subnet_id=self.subnet['id'], tenant_id=self.tenant_id) pool = body['pool'] self.addCleanup(self.admin_client.delete_pool, pool['id']) _, body = self.admin_client.create_vip(name=name, protocol="HTTP", protocol_port=80, subnet_id=self.subnet['id'], pool_id=pool['id'], tenant_id=self.tenant_id) vip = body['vip'] self.addCleanup(self.admin_client.delete_vip, vip['id']) self.assertIsNotNone(vip['id']) self.assertEqual(self.tenant_id, vip['tenant_id']) _, body = self.client.show_vip(vip['id']) show_vip = body['vip'] self.assertEqual(vip['id'], show_vip['id']) self.assertEqual(vip['name'], show_vip['name']) @test.attr(type='smoke') def test_create_health_monitor_as_admin_for_another_tenant(self): _, body = ( self.admin_client.create_health_monitor(delay=4, max_retries=3, type="TCP", timeout=1, tenant_id=self.tenant_id)) health_monitor = body['health_monitor'] self.addCleanup(self.admin_client.delete_health_monitor, health_monitor['id']) self.assertIsNotNone(health_monitor['id']) self.assertEqual(self.tenant_id, health_monitor['tenant_id']) _, body = self.client.show_health_monitor(health_monitor['id']) show_health_monitor = body['health_monitor'] self.assertEqual(health_monitor['id'], show_health_monitor['id']) @test.attr(type='smoke') def test_create_pool_from_admin_user_other_tenant(self): _, body = self.admin_client.create_pool( name=data_utils.rand_name('pool-'), lb_method="ROUND_ROBIN", protocol="HTTP", subnet_id=self.subnet['id'], tenant_id=self.tenant_id) pool = body['pool'] self.addCleanup(self.admin_client.delete_pool, pool['id']) self.assertIsNotNone(pool['id']) self.assertEqual(self.tenant_id, pool['tenant_id']) @test.attr(type='smoke') def test_create_member_from_admin_user_other_tenant(self): _, body = self.admin_client.create_member(address="10.0.9.47", protocol_port=80, pool_id=self.pool['id'], tenant_id=self.tenant_id) member = body['member'] self.addCleanup(self.admin_client.delete_member, member['id']) self.assertIsNotNone(member['id']) self.assertEqual(self.tenant_id, member['tenant_id']) class LoadBalancerAdminTestXML(LoadBalancerAdminTestJSON): _interface = 'xml'
apache-2.0
tuxmonteiro/ATSForge-FIX
atsforgefix.server/src/main/java/org/atsforge/fix/server/MainServer.java
1101
package org.atsforge.fix.server; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; public class MainServer { public static void main( String[] args ) { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new FixServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } }
apache-2.0
canerbasaran/criticalmaps-android
app/src/main/java/de/stephanlindauer/criticalmaps/adapter/ChatMessageAdapter.java
2906
package de.stephanlindauer.criticalmaps.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.text.DateFormat; import java.util.ArrayList; import java.util.Locale; import java.util.TimeZone; import butterknife.Bind; import butterknife.ButterKnife; import de.stephanlindauer.criticalmaps.R; import de.stephanlindauer.criticalmaps.interfaces.IChatMessage; import de.stephanlindauer.criticalmaps.utils.TimeToWordStringConverter; import de.stephanlindauer.criticalmaps.vo.chat.ReceivedChatMessage; public class ChatMessageAdapter extends RecyclerView.Adapter<ChatMessageAdapter.ChatMessageViewHolder> { private final ArrayList<IChatMessage> chatMessages; public ChatMessageAdapter(ArrayList<IChatMessage> chatMessages) { this.chatMessages = chatMessages; } public class ChatMessageViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.firstLine) TextView labelView; @Bind(R.id.secondLine) TextView valueView; private final DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.getDefault()); private final Context context; public ChatMessageViewHolder(View itemView) { super(itemView); context = itemView.getContext(); ButterKnife.bind(this, itemView); } public void bind(IChatMessage message) { valueView.setText(message.getMessage()); if (message instanceof ReceivedChatMessage) { dateFormatter.setTimeZone(TimeZone.getDefault()); labelView.setText(TimeToWordStringConverter.getTimeAgo(((ReceivedChatMessage) message).getTimestamp(), context)); } else { labelView.setText(R.string.chat_sending); } } } @Override public ChatMessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final LayoutInflater inflater = LayoutInflater.from(parent.getContext()); final View res; if (viewType == 0) { res = inflater.inflate(R.layout.view_chatmessage, parent, false); } else { res = inflater.inflate(R.layout.view_outgoing_chatmessage, parent, false); } return new ChatMessageViewHolder(res); } @Override public void onBindViewHolder(ChatMessageViewHolder holder, int position) { holder.bind(chatMessages.get(position)); } @Override public int getItemViewType(int position) { if (chatMessages.get(position) instanceof ReceivedChatMessage) { return 0; } else { return 1; } } @Override public int getItemCount() { return chatMessages.size(); } }
apache-2.0
ldp4j/ldp4j
framework/server/core/src/main/java/org/ldp4j/server/controller/UnknownConstraintReportException.java
1831
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the LDP4j Project: * http://www.ldp4j.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2014-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.ldp4j.framework:ldp4j-server-core:0.2.2 * Bundle : ldp4j-server-core-0.2.2.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.ldp4j.server.controller; import javax.ws.rs.core.Response.Status; public class UnknownConstraintReportException extends DiagnosedException { private static final long serialVersionUID = -1884871976187812914L; public UnknownConstraintReportException(OperationContext context, String constraintReportId, boolean includeEntity) { super(context,null,Diagnosis. create(). statusCode(Status.NOT_FOUND). diagnostic("Unknown constraint report '%s'",constraintReportId). mandatory(includeEntity)); } }
apache-2.0
stevetcm/quickremind
app/src/main/java/com/orangemuffin/quickremind/utils/DateAndTimeUtil.java
2857
package com.orangemuffin.quickremind.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; /* Created by OrangeMuffin on 7/3/2017 */ public class DateAndTimeUtil { public static int getDueDate(String reminder_date) { String pattern = "EEE, dd MMM yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); Calendar calendar = Calendar.getInstance(); String today = dateFormat.format(calendar.getTime()); try { Date one = dateFormat.parse(today); Date two = dateFormat.parse(reminder_date); long diff = two.getTime() - one.getTime(); return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); } catch (ParseException e) { e.printStackTrace(); } return 0; } public static String convertDate(String pattern, String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy"); Date temp = dateFormat.parse(date); dateFormat = new SimpleDateFormat(pattern); return dateFormat.format(temp); } catch (Exception e) { } return null; } public static String convertTime(String pattern, String time) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); Date temp = dateFormat.parse(time); dateFormat = new SimpleDateFormat(pattern); return dateFormat.format(temp); } catch (Exception e) { } return null; } public static String dateToDay(String date) { String day = ""; String pattern = "EEE, dd MMM yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(dateFormat.parse(date)); int result = calendar.get(Calendar.DAY_OF_WEEK); switch (result) { case Calendar.MONDAY: day = "Monday"; break; case Calendar.TUESDAY: day = "Tuesday"; break; case Calendar.WEDNESDAY: day = "Wednesday"; break; case Calendar.THURSDAY: day = "Thursday"; break; case Calendar.FRIDAY: day = "Friday"; break; case Calendar.SATURDAY: day = "Saturday"; break; case Calendar.SUNDAY: day = "Sunday"; break; } } catch (Exception e) { } return day; } }
apache-2.0
nimble-platform/frontend-service
src/app/user-mgmt/model/user-registration.ts
1034
/* * Copyright 2020 * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Credentials } from './credentials'; import { User } from './user'; export class UserRegistration { public user: User; public credentials: Credentials; public static initEmpty() { let ur = new UserRegistration(); ur.user = new User('', '', '', '', '', '', '', '', ''); ur.credentials = new Credentials('', ''); return ur; } }
apache-2.0
cmaere/lwb
templates/protostar/indexda83.php
759
<?xml version="1.0" encoding="utf-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&amp;view=article&amp;id=223&amp;Itemid=267&amp;lang=ta&amp;format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&amp;searchword={searchTerms}&amp;Itemid=188"/></OpenSearchDescription>
apache-2.0
IntuitionEngineeringTeam/chars2vec
setup.py
2190
import sys import subprocess PY_VER = sys.version[0] subprocess.call(["pip{:} install -r requirements.txt".format(PY_VER)], shell=True) from setuptools import setup setup( name='chars2vec', version='0.1.7', author='Vladimir Chikin', author_email='v4@intuition.engineering', packages=['chars2vec'], include_package_data=True, package_data={'chars2vec': ['trained_models/*']}, description='Character-based word embeddings model based on RNN', maintainer='Intuition', maintainer_email='dev@intuition.engineering', url='https://github.com/IntuitionEngineeringTeam/chars2vec', download_url='https://github.com/IntuitionEngineeringTeam/chars2vec/archive/master.zip', license='Apache License 2.0', long_description='Chars2vec library could be very useful if you are dealing with the texts \ containing abbreviations, slang, typos, or some other specific textual dataset. \ Chars2vec language model is based on the symbolic representation of words – \ the model maps each word to a vector of a fixed length. \ These vector representations are obtained with a custom neural netowrk while \ the latter is being trained on pairs of similar and non-similar words. \ This custom neural net includes LSTM, reading sequences of characters in words, as its part. \ The model maps similarly written words to proximal vectors. \ This approach enables creation of an embedding in vector space for any sequence of characters.\ Chars2vec models does not keep any dictionary of embeddings, \ but generates embedding vectors inplace using pretrained model. \ There are pretrained models of dimensions 50, 100, 150, 200 and 300 for the English language.\ The library provides convenient user API to train a model for an arbitrary set of characters.', classifiers=['Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3'] )
apache-2.0
orioncode/orionplatform
orion_math/orion_math_core/src/main/java/com/orionplatform/math/graph/vertex/point/PointVertex.java
1841
package com.orionplatform.math.graph.vertex.point; import com.orionplatform.core.object.CloningService; import com.orionplatform.math.geometry.point.Point; import com.orionplatform.math.graph.vertex.Vertex; import com.orionplatform.math.graph.vertex.VertexRules; public class PointVertex extends Vertex { private Point point; public PointVertex() { setEmpty(true); } public PointVertex(Point point) { PointVertexRules.isValid(point); this.point = point; setVertexPoint(point); } public static synchronized PointVertex of() { return new PointVertex(); } public static synchronized PointVertex of(Point point) { return new PointVertex(point); } @Override public void setNewPoint(Vertex vertex) { VertexRules.haveSameType(this, vertex); this.point = ((PointVertex)vertex).getPoint(); setVertexPoint(vertex.getVertexPoint()); } @Override public int hashCode() { return PointVertexInternalService.hashCode(this); } @Override public boolean equals(Object object) { return PointVertexInternalService.equals(this, object); } public boolean notEquals(Object object) { return !equals(object); } @Override public PointVertex clone() throws CloneNotSupportedException { return (PointVertex)CloningService.clone(this); } public PointVertex getCopy() { try { return this.clone(); } catch(CloneNotSupportedException e) { e.printStackTrace(); } return null; } public Point getPoint() { return this.point; } }
apache-2.0
scudre/alarm-central-station-receiver
alarm_central_station_receiver/contact_id/dsc.py
5963
""" DSC Contact ID Codes to Descriptions """ from alarm_central_station_receiver.config import AlarmConfig EVENTS = { '100000': {'1': ('A', 'Aux Key Alarm')}, '100ZZZ': {'1': ('A', '24 Hr Medical')}, '101ZZZ': {'1': ('A', '24 Hr Emergency (non-medical)')}, '102000': {'1': ('A', 'Fail to Report In')}, '110000': {'1': ('A', '[F] Key Alarm')}, '110ZZZ': {'1': ('A', '24 Hr Fire')}, '120000': {'1': ('A', 'Panic Key Alarm')}, '120ZZZ': {'1': ('A', '24 Hr Panic')}, '121000': {'1': ('A', 'Duress Alarm')}, '130ZZZ': {'1': ('A', 'Zone Alarm')}, '139000': {'1': ('A', 'Cross Zone Alarm')}, '140ZZZ': {'1': ('A', '24 Hr Supervisory Buzzer')}, '145000': {'1': ('T', 'General System Tamper (Case/Cover Tamper Alarm)')}, '150ZZZ': {'1': ('A', '24 Hr Supervisory')}, '151ZZZ': {'1': ('A', '24 Hr Gas')}, '154ZZZ': {'1': ('A', '24 Hr Water')}, '159ZZZ': {'1': ('A', '24 Hr Freeze')}, '162ZZZ': {'1': ('A', '24 Hr CO Alarm')}, '300000': {'1': ('MA', 'General System Trouble')}, '300001': {'1': ('MA', 'General Alternate Communicator Trouble')}, '301000': {'1': ('MA', 'AC Line Trouble')}, '302000': {'1': ('MA', 'Battery Trouble')}, '312000': {'1': ('MA', 'Auxiliary Power Trouble')}, '330000': {'1': ('MA', 'Alternate Communicator Fault')}, '350001': {'1': ('MA', 'Alternate Communicator Receiver 1 Trouble')}, '350002': {'1': ('MA', 'Alternate Communicator Receiver 2 Trouble')}, '350003': {'1': ('MA', 'Alternate Communicator Receiver 3 Trouble')}, '350004': {'1': ('MA', 'Alternate Communicator Receiver 4 Trouble')}, '351000': {'1': ('MA', 'Phone Line Failure')}, '354000': {'1': ('MA', 'Phone #1-4 FTC')}, '373000': {'1': ('MA', 'Fire Trouble')}, '374ZZZ': {'1': ('C', 'Exit Fault')}, '378000': {'1': ('A', 'Burglary Not Verified')}, '380070': {'1': ('MA', 'Keypad 1 Fault')}, '380071': {'1': ('MA', 'Keypad 2 Fault')}, '380072': {'1': ('MA', 'Keypad 3 Fault')}, '380073': {'1': ('MA', 'Keypad 4 Fault')}, '380080': {'1': ('MA', 'Siren 1 Fault')}, '380081': {'1': ('MA', 'Siren 2 Fault')}, '380082': {'1': ('MA', 'Siren 3 Fault')}, '380083': {'1': ('MA', 'Siren 4 Fault')}, '380ZZZ': {'1': ('MA', 'Zone Fault')}, '383070': {'1': ('T', 'Keypad 1 Tamper')}, '383071': {'1': ('T', 'Keypad 2 Tamper')}, '383072': {'1': ('T', 'Keypad 3 Tamper')}, '383073': {'1': ('T', 'Keypad 4 Tamper')}, '383080': {'1': ('T', 'Siren 1 Tamper')}, '383081': {'1': ('T', 'Siren 2 Tamper')}, '383082': {'1': ('T', 'Siren 3 Tamper')}, '383083': {'1': ('T', 'Siren 4 Tamper')}, '383ZZZ': {'1': ('T', 'Zone Tamper')}, '384000': {'1': ('MA', 'Wireless Device Low Battery Trouble')}, '384ZZZ': {'1': ('MA', 'Wireless Zone Low Battery Trouble')}, '400000': {'1': ('O', 'Special Disarming'), '3': ('C', 'Special Arming')}, '401UUU': {'1': ('O', 'System Disarmed'), '3': ('C', 'System Armed')}, '406UUU': {'1': ('A', 'Alarm Cleared')}, '411000': {'1': ('MA', 'DLS Lead In')}, '412000': {'1': ('MA', 'DLS Lead Out')}, '453000': {'1': ('O', 'Late to Open')}, '456000': {'1': ('C', 'Partial Arming')}, '458000': {'1': ('E', 'Disarm After Alarm')}, '459UUU': {'1': ('A', 'Alarm Within 2 min of Arming')}, '461000': {'1': ('T', 'Keypad Lockout')}, '570ZZZ': {'1': ('C', 'Zone Bypass')}, '601000': {'1': ('E', 'System Test')}, '602000': {'1': ('E', 'Periodic Test')}, '607UUU': {'1': ('E', 'Walk Test Begin'), '3': ('R', 'Walk Test End')}, '627000': {'1': ('MA', 'Installer Lead In')}, '628000': {'1': ('MA', 'Installer Lead Out')}, '654000': {'1': ('MA', 'Delinquency')} } def create_event_description(event_type, event): """ Create the alarm description by using the '1' event type description and appending the appropriate event type name to it for the passed in `event_type` """ _, description = event.get('1') if event_type == '1': event_type_name = 'E' elif event_type == '3': event_type_name = 'R' description += ' Restoral' elif event_type == '6': event_type_name = 'S' description += ' Status' else: event_type_name = 'U' description += 'Unknown Event Type (%s)' % event_type return event_type_name, description def get_zone_name(sensor_code): zone_name = AlarmConfig.config.get('ZoneMapping', sensor_code, fallback=None) if not zone_name: zone_name = 'Zone %s' % sensor_code return zone_name def digits_to_alarmreport(code): """ Given a raw contact id DTMF string from a DSC alarm, return the alarm description and event type. 4567 18 1 570 00 016 4 ACCT MT Q CCC GG ZZZ S NNNN 18 1 = new event 3 = restore or closing 6 = still present (status report) """ event_type = code[6] event_code = code[7:10] sensor_code = code[12:15] event_type_name = 'U' description = 'Unknown Event - %s' % code extra_desc = '' event = EVENTS.get(event_code + sensor_code) if not event: zone_event = EVENTS.get(event_code + 'ZZZ') user_event = EVENTS.get(event_code + 'UUU') if zone_event: event = zone_event zone_name = get_zone_name(sensor_code) extra_desc = ' %s (%s)' % (zone_name, sensor_code) elif user_event: event = user_event extra_desc = ' User %s' % sensor_code if event: if event_type in event: event_type_name, description = event.get(event_type) else: event_type_name, description = \ create_event_description(event_type, event) description += extra_desc return event_type_name, event_code + sensor_code, description
apache-2.0
teecube/t3
t3-common/src/main/java/t3/xml/RootElementNamespaceFilter.java
3704
/** * (C) Copyright 2016-2019 teecube * (https://teecu.be) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package t3.xml; import org.apache.commons.lang3.builder.EqualsBuilder; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; import java.util.ArrayList; import java.util.List; /** * * @author Mathieu Debove &lt;mad@teecu.be&gt; * */ public class RootElementNamespaceFilter extends XMLFilterImpl { private String rootElementLocalName; private List<NamespaceDeclaration> namespaceDeclarationsToRemove; public static class NamespaceDeclaration { private String prefix; private String uri; /** * * @param prefix, prefix in the form xmlns:prefix * @param uri, the namespace URI */ public NamespaceDeclaration(String prefix, String uri) { this.prefix = prefix; this.uri = uri; } @Override public boolean equals(Object obj) { if (!(obj instanceof NamespaceDeclaration)) return false; if (obj == this) return true; NamespaceDeclaration rhs = (NamespaceDeclaration) obj; return new EqualsBuilder(). append(prefix, rhs.prefix). append(uri, rhs.uri). isEquals(); } } /** * * @param rootElementLocalName, the document root element local name * @param namespaceDeclarationsToRemove, list of prefix in the form "xmlns:prefix" */ public RootElementNamespaceFilter(String rootElementLocalName, List<NamespaceDeclaration> namespaceDeclarationsToRemove) { super(); if (rootElementLocalName == null) { this.rootElementLocalName = ""; } this.rootElementLocalName = rootElementLocalName; if (namespaceDeclarationsToRemove == null) { namespaceDeclarationsToRemove = new ArrayList<NamespaceDeclaration>(); } this.namespaceDeclarationsToRemove = namespaceDeclarationsToRemove; } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals(rootElementLocalName)) { AttributesImpl result = new AttributesImpl(); if (atts.getLength() > 0) { for (int i = 0; i < atts.getLength(); i++) { String _uri = atts.getURI(i); String _localName = atts.getLocalName(i); String _qName = atts.getQName(i); String _type = atts.getType(i); String _value = atts.getValue(i); if (!namespaceDeclarationsToRemove.contains(new NamespaceDeclaration(_qName, _value))) { result.addAttribute(_uri, _localName, _qName, _type, _value); } } } super.startElement(uri, localName, qName, result); } else { super.startElement(uri, localName, qName, atts); } } }
apache-2.0
jmochel/code-samples
src/test/java/org/saltations/samples/BasicTimerTest.java
784
package org.saltations.samples; import java.util.Timer; import java.util.TimerTask; public class BasicTimerTest { private static class EggTimer { private final Timer timer = new Timer(); private final int seconds; public EggTimer(int seconds) { this.seconds = seconds; } public void start() { timer.schedule(new TimerTask() { public void run() { System.out.println("Your egg is ready!"); timer.cancel(); } }, seconds * 1000); } public static void main(String[] args) { EggTimer eggTimer = new EggTimer(2); eggTimer.start(); } } }
apache-2.0
dnephin/cli
cli/command/config/remove.go
1064
package config import ( "fmt" "strings" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/pkg/errors" "github.com/spf13/cobra" "golang.org/x/net/context" ) type removeOptions struct { names []string } func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command { return &cobra.Command{ Use: "rm CONFIG [CONFIG...]", Aliases: []string{"remove"}, Short: "Remove one or more configs", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts := removeOptions{ names: args, } return runConfigRemove(dockerCli, opts) }, } } func runConfigRemove(dockerCli command.Cli, opts removeOptions) error { client := dockerCli.Client() ctx := context.Background() var errs []string for _, name := range opts.names { if err := client.ConfigRemove(ctx, name); err != nil { errs = append(errs, err.Error()) continue } fmt.Fprintln(dockerCli.Out(), name) } if len(errs) > 0 { return errors.Errorf("%s", strings.Join(errs, "\n")) } return nil }
apache-2.0
ceph/ceph-csi
internal/rbd/clone.go
8923
/* Copyright 2020 The Ceph-CSI Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package rbd import ( "context" "errors" "fmt" "github.com/ceph/ceph-csi/internal/util/log" librbd "github.com/ceph/go-ceph/rbd" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // checkCloneImage check the cloned image exists, if the cloned image is not // found it will check the temporary cloned snapshot exists, and again it will // check the snapshot exists on the temporary cloned image, if yes it will // create a new cloned and delete the temporary snapshot and adds a task to // flatten the temp cloned image and return success. // // if the temporary snapshot does not exists it creates a temporary snapshot on // temporary cloned image and creates a new cloned with user-provided image // features and delete the temporary snapshot and adds a task to flatten the // temp cloned image and return success // // if the temporary clone does not exist and if there is a temporary snapshot // present on the parent image it will delete the temporary snapshot and // returns. func (rv *rbdVolume) checkCloneImage(ctx context.Context, parentVol *rbdVolume) (bool, error) { // generate temp cloned volume tempClone := rv.generateTempClone() defer tempClone.Destroy() snap := &rbdSnapshot{} defer snap.Destroy() snap.RbdSnapName = rv.RbdImageName snap.Pool = rv.Pool err := tempClone.checkSnapExists(snap) if err != nil { switch { case errors.Is(err, ErrSnapNotFound): // check temporary image needs flatten, if yes add task to flatten the // temporary clone err = tempClone.flattenRbdImage(ctx, false, rbdHardMaxCloneDepth, rbdSoftMaxCloneDepth) if err != nil { return false, err } // as the snapshot is not present, create new snapshot,clone and // delete the temporary snapshot err = createRBDClone(ctx, tempClone, rv, snap) if err != nil { return false, err } // check image needs flatten, if yes add task to flatten the clone err = rv.flattenRbdImage(ctx, false, rbdHardMaxCloneDepth, rbdSoftMaxCloneDepth) if err != nil { return false, err } return true, nil case errors.Is(err, ErrImageNotFound): // as the temp clone does not exist,check snapshot exists on parent volume // snapshot name is same as temporary clone image snap.RbdImageName = tempClone.RbdImageName err = parentVol.checkSnapExists(snap) if err == nil { // the temp clone exists, delete it lets reserve a new ID and // create new resources for a cleaner approach err = parentVol.deleteSnapshot(ctx, snap) } if errors.Is(err, ErrSnapNotFound) { return false, nil } return false, err default: // any error other than the above return error return false, err } } // snap will be created after we flatten the temporary cloned image,no // need to check for flatten here. // as the snap exists,create clone image and delete temporary snapshot // and add task to flatten temporary cloned image err = rv.cloneRbdImageFromSnapshot(ctx, snap, parentVol) if err != nil { log.ErrorLog(ctx, "failed to clone rbd image %s from snapshot %s: %v", rv.RbdImageName, snap.RbdSnapName, err) err = fmt.Errorf("failed to clone rbd image %s from snapshot %s: %w", rv.RbdImageName, snap.RbdSnapName, err) return false, err } err = tempClone.deleteSnapshot(ctx, snap) if err != nil { log.ErrorLog(ctx, "failed to delete snapshot: %v", err) return false, err } // check image needs flatten, if yes add task to flatten the clone err = rv.flattenRbdImage(ctx, false, rbdHardMaxCloneDepth, rbdSoftMaxCloneDepth) if err != nil { return false, err } return true, nil } func (rv *rbdVolume) generateTempClone() *rbdVolume { tempClone := rbdVolume{} tempClone.conn = rv.conn.Copy() // The temp clone image need to have deep flatten feature f := []string{librbd.FeatureNameLayering, librbd.FeatureNameDeepFlatten} tempClone.ImageFeatureSet = librbd.FeatureSetFromNames(f) tempClone.ClusterID = rv.ClusterID tempClone.Monitors = rv.Monitors tempClone.Pool = rv.Pool tempClone.RadosNamespace = rv.RadosNamespace // The temp cloned image name will be always (rbd image name + "-temp") // this name will be always unique, as cephcsi never creates an image with // this format for new rbd images tempClone.RbdImageName = rv.RbdImageName + "-temp" return &tempClone } func (rv *rbdVolume) createCloneFromImage(ctx context.Context, parentVol *rbdVolume) error { j, err := volJournal.Connect(rv.Monitors, rv.RadosNamespace, rv.conn.Creds) if err != nil { return status.Error(codes.Internal, err.Error()) } defer j.Destroy() err = rv.doSnapClone(ctx, parentVol) if err != nil { return err } err = rv.getImageID() if err != nil { log.ErrorLog(ctx, "failed to get volume id %s: %v", rv, err) return err } if parentVol.isEncrypted() { err = parentVol.copyEncryptionConfig(&rv.rbdImage, false) if err != nil { return fmt.Errorf("failed to copy encryption config for %q: %w", rv, err) } } err = j.StoreImageID(ctx, rv.JournalPool, rv.ReservedID, rv.ImageID) if err != nil { log.ErrorLog(ctx, "failed to store volume %s: %v", rv, err) return err } // expand the image if the requested size is greater than the current size err = rv.expand() if err != nil { log.ErrorLog(ctx, "failed to resize volume %s: %v", rv, err) return err } return nil } func (rv *rbdVolume) doSnapClone(ctx context.Context, parentVol *rbdVolume) error { var ( errClone error errFlatten error ) // generate temp cloned volume tempClone := rv.generateTempClone() // snapshot name is same as temporary cloned image, This helps to // flatten the temporary cloned images as we cannot have more than 510 // snapshots on an rbd image tempSnap := &rbdSnapshot{} tempSnap.RbdSnapName = tempClone.RbdImageName tempSnap.Pool = rv.Pool cloneSnap := &rbdSnapshot{} cloneSnap.RbdSnapName = rv.RbdImageName cloneSnap.Pool = rv.Pool // create snapshot and temporary clone and delete snapshot err := createRBDClone(ctx, parentVol, tempClone, tempSnap) if err != nil { return err } defer func() { if err != nil || errClone != nil { cErr := cleanUpSnapshot(ctx, tempClone, cloneSnap, rv) if cErr != nil { log.ErrorLog(ctx, "failed to cleanup image %s or snapshot %s: %v", cloneSnap, tempClone, cErr) } } if err != nil || errFlatten != nil { if !errors.Is(errFlatten, ErrFlattenInProgress) { // cleanup snapshot cErr := cleanUpSnapshot(ctx, parentVol, tempSnap, tempClone) if cErr != nil { log.ErrorLog(ctx, "failed to cleanup image %s or snapshot %s: %v", tempSnap, tempClone, cErr) } } } }() // flatten clone errFlatten = tempClone.flattenRbdImage(ctx, false, rbdHardMaxCloneDepth, rbdSoftMaxCloneDepth) if errFlatten != nil { return errFlatten } // create snap of temp clone from temporary cloned image // create final clone // delete snap of temp clone errClone = createRBDClone(ctx, tempClone, rv, cloneSnap) if errClone != nil { // set errFlatten error to cleanup temporary snapshot and temporary clone errFlatten = errors.New("failed to create user requested cloned image") return errClone } return nil } func (rv *rbdVolume) flattenCloneImage(ctx context.Context) error { tempClone := rv.generateTempClone() // reducing the limit for cloned images to make sure the limit is in range, // If the intermediate clone reaches the depth we may need to return ABORT // error message as it need to be flatten before continuing, this may leak // omap entries and stale temporary snapshots in corner cases, if we reduce // the limit and check for the depth of the parent image clain itself we // can flatten the parent images before used to avoid the stale omap entries. hardLimit := rbdHardMaxCloneDepth softLimit := rbdSoftMaxCloneDepth // choosing 2 so that we don't need to flatten the image in the request. const depthToAvoidFlatten = 2 if rbdHardMaxCloneDepth > depthToAvoidFlatten { hardLimit = rbdHardMaxCloneDepth - depthToAvoidFlatten } if rbdSoftMaxCloneDepth > depthToAvoidFlatten { softLimit = rbdSoftMaxCloneDepth - depthToAvoidFlatten } err := tempClone.getImageInfo() if err == nil { return tempClone.flattenRbdImage(ctx, false, hardLimit, softLimit) } if !errors.Is(err, ErrImageNotFound) { return err } return rv.flattenRbdImage(ctx, false, hardLimit, softLimit) }
apache-2.0
pieces029/RxNetty
rx-netty/src/main/java/io/reactivex/netty/channel/ObservableConnectionFactory.java
969
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.netty.channel; import io.netty.channel.ChannelHandlerContext; import io.reactivex.netty.metrics.MetricEventsSubject; /** * @author Nitesh Kant */ public interface ObservableConnectionFactory<I, O> { ObservableConnection<I, O> newConnection(ChannelHandlerContext ctx); void useMetricEventsSubject(MetricEventsSubject<?> eventsSubject); }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/it/ksb/src/test/java/org/kuali/rice/ksb/messaging/remotedservices/SOAPService.java
816
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.ksb.messaging.remotedservices; /** * * @author Kuali Rice Team (rice.collab@kuali.org) */ public interface SOAPService { public String doTheThing(String param); }
apache-2.0
kissge/shinchoku
app/models/Goal.scala
232
package models import org.joda.time.DateTime /** * The goal object. */ case class Goal( goalID: Int, name: String, description: String, timeLimit: DateTime, maxProgress: Int, createdBy: User, createdAt: DateTime )
apache-2.0
manoa-tckts/manoa-tckts
app/imports/ui/layouts/if-is-admin.js
405
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { Members, MembersSchema } from '../../api/schema/members.js'; /* eslint-disable object-shorthand */ Template.If_Is_Admin.helpers({ /** * @returns {*} True if Meteor is in the process of logging in. */ isAdmin: function isAdmin() { return Members.findOne({'uid':Meteor.userId()}).admin; }, });
apache-2.0
DuGuQiuBai/Android-Basics-Codes
day11_新特性(第九剑)/code/03_Fragment和Activity的数据传递/src/cn/itcast/transmit/Fragment01.java
1106
package cn.itcast.transmit; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.Button; import android.widget.EditText; public class Fragment01 extends Fragment { //ϵͳµ÷Ó㬷µ»ØÒ»¸öView¶ÔÏó£¬×÷ΪFragmentµÄÏÔʾÄÚÈÝ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //°Ñ²¼¾ÖÎļþÌî³ä³ÉView¶ÔÏó£¬return³öÈ¥ final View v = inflater.inflate(R.layout.fragment01, null); Button bt_fragment01 = (Button) v.findViewById(R.id.bt_fragment01); //ÉèÖð´Å¥µã»÷ÕìÌý bt_fragment01.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //»ñÈ¡Óû§ÊäÈëÊý¾Ý EditText et = (EditText) v.findViewById(R.id.et_fragment01); String text = et.getText().toString(); //´«µÝ¸øActivity //»ñÈ¡MainActivityµÄ¶ÔÏó ((MainActivity)getActivity()).setText(text); } }); return v; } }
artistic-2.0
Frhack11/gnak
Alus/src/Stuff/Arma.java
61
package Stuff; public interface Arma extends ArmaScudo { }
artistic-2.0
aifeiasdf/Template-tookit
t/config_test.py
3854
from template.config import Config from template.test import TestCase, main from template.util import Literal class ConfigTest(TestCase): def testConfig(self): factory = Config # Parser: parser = factory.parser({ 'PRE_CHOMP': 1, 'INTERPOLATE': True }) self.failUnless(parser) self.assertEquals(1, parser.pre_chomp) self.failUnless(parser.interpolate) parser = factory.parser({ 'POST_CHOMP': 1 }) self.failUnless(parser) self.assertEquals(1, parser.post_chomp) # Provider: provider = factory.provider({ 'INCLUDE_PATH': 'here:there', 'PARSER': parser }) self.failUnless(provider) self.assertEquals(['here', 'there'], provider.include_path()) self.assertEquals(1, provider.parser().post_chomp) provider = factory.provider({ 'INCLUDE_PATH': 'cat:mat', 'ANYCASE': True, 'INTERPOLATE': True }) self.failUnless(provider) self.assertEquals(['cat', 'mat'], provider.include_path()) # Force the provider to instantiate a parser and check it uses the # correct parameters. text = 'The cat sat on the mat' self.failUnless(provider.fetch(Literal(text))) self.failUnless(provider.parser().anycase) self.failUnless(provider.parser().interpolate) # Plugins: plugins = factory.plugins({ 'PLUGIN_BASE': ('my.plugins', 'MyPlugins') }) self.failUnless(plugins) self.assertEquals([('my.plugins', 'MyPlugins'), 'template.plugin'], plugins.plugin_base()) plugins = factory.plugins({ 'LOAD_PYTHON': True, 'PLUGIN_BASE': ('my.plugins', 'NewPlugins') }) self.failUnless(plugins) self.failUnless(plugins.load_python()) self.assertEquals([('my.plugins', 'NewPlugins'), 'template.plugin'], plugins.plugin_base()) # Filters: filters = factory.filters({ 'TOLERANT': True }) self.failUnless(filters) self.failUnless(filters.tolerant()) filters = factory.filters({ 'TOLERANT': True }) self.failUnless(filters) self.failUnless(filters.tolerant()) # Stash: stash = factory.stash({ 'foo': 10, 'bar': 20 }) self.failUnless(stash) self.assertEquals(10, stash.get('foo').value()) self.assertEquals(20, stash.get('bar').value()) stash = factory.stash({ 'foo': 30, 'bar': lambda *_: 'forty' }) self.failUnless(stash) self.assertEquals(30, stash.get('foo').value()) self.assertEquals('forty', stash.get('bar').value()) # Context: context = factory.context({}) self.failUnless(context) context = factory.context({ 'INCLUDE_PATH': 'anywhere' }) self.failUnless(context) self.assertEquals('anywhere', context.load_templates()[0].include_path()[0]) context = factory.context({ 'LOAD_TEMPLATES': [ provider ], 'LOAD_PLUGINS': [ plugins ], 'LOAD_FILTERS': [ filters ], 'STASH': stash }) self.failUnless(context) self.assertEquals(30, context.stash().get('foo').value()) self.failUnless(context.load_templates()[0].parser().interpolate) self.failUnless(context.load_plugins()[0].load_python()) self.failUnless(context.load_filters()[0].tolerant()) # Service: service = factory.service({ 'INCLUDE_PATH': 'amsterdam' }) self.failUnless(service) self.assertEquals(['amsterdam'], service.context().load_templates()[0].include_path()) # Iterator: iterator = factory.iterator(['foo', 'bar', 'baz']) self.failUnless(iterator) self.assertEquals('foo', iterator.get_first()) self.assertEquals('bar', iterator.get_next()) self.assertEquals('baz', iterator.get_next()) # Instdir: # (later) main()
artistic-2.0
xyzstick/Yiiartist
protected/views/site/login.php
1316
<?php /** * @var $this SiteController * @var $model LoginForm * @var $form CActiveForm */ $this->pageTitle=Yii::app()->name.' - Login'; $this->breadcrumbs=array('Login',); ?> <h1>Login</h1> <p>Please fill out the following form with your login credentials:</p> <div class="form"> <?php $form=$this->beginWidget('CActiveForm',array( 'id'=>'login-form', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> <?php //echo CHtml::errorSummary($model); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <div class="row"> <?php echo $form->labelEx($model,'username'); ?> <?php echo $form->textField($model,'username'); ?> <?php echo $form->error($model,'username'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'password'); ?> <?php echo $form->passwordField($model,'password'); ?> <?php echo $form->error($model,'password'); ?> </div> <div class="row"> <?php echo $form->error($model,'status'); ?> </div> <div class="row rememberMe"> <?php echo $form->checkBox($model,'rememberMe'); ?> <?php echo $form->label($model,'rememberMe'); ?> <?php echo $form->error($model,'rememberMe'); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton('Login'); ?> </div> <?php $this->endWidget(); ?> </div><!-- form -->
artistic-2.0
hdijkema/TaskGnome
src/net/oesterholt/taskgnome/TaskGnome.java
4431
package net.oesterholt.taskgnome; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.net.URL; import java.util.Vector; import java.util.prefs.Preferences; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import net.oesterholt.taskgnome.sync.Synchronizer; import net.oesterholt.taskgnome.utils.TgLogger; import org.apache.log4j.Appender; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; public class TaskGnome { static Logger logger=TgLogger.getLogger(TaskGnome.class); public static void setIconImage(Window w) { URL url=TaskGnome.class.getResource("/net/oesterholt/taskgnome/resources/icon.png"); ImageIcon icon = new ImageIcon(url); w.setIconImage(icon.getImage()); } public static ImageIcon toolBarIcon(String name) { URL url=TaskGnome.class.getResource( String.format("/net/oesterholt/taskgnome/resources/%s.png",name) ); return new ImageIcon( new ImageIcon(url).getImage().getScaledInstance(48, 48, Image.SCALE_SMOOTH) ); } @SuppressWarnings("serial") public static JButton toolBarAction(final String action,final ActionListener l) { JButton b=new JButton(new AbstractAction(action,TaskGnome.toolBarIcon(action)) { public void actionPerformed(ActionEvent e) { ActionEvent E=new ActionEvent(e.getSource(), e.getID(), action); l.actionPerformed(E); } }); b.setFocusable(false); b.setHideActionText(true); return b; } public static JMenuItem menu(final String action, final String txt,ActionListener l) { JMenuItem mnu=new JMenuItem(txt); mnu.addActionListener(l); mnu.setActionCommand(action); return mnu; } public static void setWindowPosition(Point where,Dimension size) { Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class); prefs.putInt("wx", where.x); prefs.putInt("wy", where.y); prefs.putInt("width", size.width); prefs.putInt("height", size.height); } public static Point getPrevWindowLocation() { Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class); int x=prefs.getInt("wx", -1); int y=prefs.getInt("wy", -1); if (x<0 || y<0) { return null; } else { return new Point(x,y); } } public static Dimension getPrevWindowSize() { Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class); int w=prefs.getInt("width", -1); int h=prefs.getInt("height", -1); if (w<0 || h<0) { return null; } else { return new Dimension(w,h); } } public static void setLastPath(String f) { Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class); prefs.put("lastpath",f); } public static Vector<String> getRecentlyUsed() { Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class); Integer i; Vector<String> r=new Vector<String>(); for(i=0;i<5;i++) { String key="recently_"+i; String f=prefs.get(key, null); if (f!=null) { r.add(f); } } return r; } public static void main(String argv[]) { if (argv.length > 0) { //int i; /*for(i = 0; i < argv.length; ++i) { System.out.println(argv[i]);; }*/ if (argv[0].equals("--version")) { System.out.println("1.0"); System.exit(0);; } } File td = new File(System.getProperty("user.home"), ".taskgnome"); if (!td.exists()) { td.mkdirs(); } BasicConfigurator.configure(); //Logger.getRootLogger().getLoggerRepository().resetConfiguration(); File logfile = new File(td.getAbsolutePath(), "taskgnome.log"); logfile.delete(); FileAppender fa = new FileAppender(); fa.setName("TaskGnomeLogger"); fa.setFile(logfile.getAbsolutePath()); fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n")); fa.setThreshold(Level.DEBUG); fa.setAppend(true); fa.activateOptions(); Logger.getRootLogger().addAppender(fa); logger.debug("TaskGnome started"); TaskWindow u; try { u = new TaskWindow(td.getAbsolutePath()); SwingUtilities.invokeLater(u); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
artistic-2.0
graslevy/ptesfinder_v1
src/bio/igm/utils/discovery/ResolvePTESExonCoordinates.java
5347
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bio.igm.utils.discovery; import bio.igm.entities.Exons; import bio.igm.entities.MappedAnchors; import bio.igm.entities.Transcript; import bio.igm.utils.init.Logging; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; /** * * @author osagie izuogu - 05/2013 */ public class ResolvePTESExonCoordinates { Map<String, Transcript> refseq = new HashMap(); Map<String, String> to_print = new HashMap<String, String>(); String eid; String path; private static Logger LOG; public ResolvePTESExonCoordinates(String _path, String _eid) throws IOException { this.path = _path; File f = new File(_path); try { if (f.isDirectory()) { LOG = new Logging(_path, ResolvePTESExonCoordinates.class.getName()).setup(); } else { LOG = new Logging(f.getParent(), ResolvePTESExonCoordinates.class.getName()).setup(); } } catch (IOException ex) { Logger.getLogger(ResolvePTESExonCoordinates.class.getName()).log(Level.SEVERE, null, ex); } this.eid = _eid; getRefSeqCoord(); read_processed_sam(); LOG.info("Finished resolving shuffled coordinates to exons.."); writeToFile(); } private void getRefSeqCoord() throws IOException { BufferedReader br = new BufferedReader(new FileReader(eid)); String line = ""; while ((line = br.readLine()) != null) { String[] contents = line.trim().split("\t"); Transcript transcript = new Transcript(contents[0].toUpperCase()); if (contents.length > 3) { String[] start = StringUtils.split(contents[2]); String[] end = StringUtils.split(contents[3]); for (int i = 0; i < start.length; i++) { Exons exon = new Exons(transcript, Integer.parseInt(start[i]), Integer.parseInt(end[i])); exon.setOrder(i + 1); transcript.addExon(exon); } this.refseq.put(transcript.getRefseq(), transcript); } contents = null; } LOG.info("Transcripts: " + refseq.size()); br.close(); } private void read_processed_sam() throws IOException { BufferedReader br = new BufferedReader(new FileReader(path + "processedSAM.txt")); String line = ""; while ((line = br.readLine()) != null) { try { String locus = line.split("\t")[1].contains("ref") ? processID(line.split("\t")[1]) : line.split("\t")[1]; int left = Integer.parseInt(line.split("\t")[2]); int right = Integer.parseInt(line.split("\t")[3]); int o = Integer.parseInt(line.split("\t")[4]); checkAnchorEquality(left, right, locus); } catch (Exception e) { LOG.info("Error processing this read: " + line); } } br.close(); } private static String processID(String string) { String id = ""; String[] target = string.split("ref"); id = target[1].split("\\.")[0].replaceAll("\\..*|[^a-zA-Z0-9_]", ""); return id; } private void checkAnchorEquality(int left, int right, String locus) { Transcript transcript = null; MappedAnchors anchors = null; if (this.refseq.containsKey(locus)) { transcript = (Transcript) this.refseq.get(locus); int x = Math.max(left, right); int y = Math.min(left, right); anchors = new MappedAnchors(x, y, transcript); if (anchors.checkJunction()) { this.to_print.put(anchors.getId(), anchors.getTo_print()); } } } private void writeToFile() throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(this.path + "TestTargets.txt")); for (String s : to_print.values()) { bw.write(s + "\n"); } bw.close(); } public Map<String, Transcript> getRefseq() { return refseq; } public void setRefseq(Map<String, Transcript> refseq) { this.refseq = refseq; } public String getEid() { return eid; } public void setEid(String eid) { this.eid = eid; } public static void main(String[] args) { try { /* input files: Working directory and Coordinates file */ String path = args[0]; String eid = args[1]; ResolvePTESExonCoordinates r = new ResolvePTESExonCoordinates(path, eid); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } }
artistic-2.0
rec/DMXIS
Macros/Colours/Adjust Colour/Blue +.py
505
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #=============================================================== for ch in GetAllSelCh(False): nm = GetChName(ch).lower() if nm=="b" or nm=="blue": v = GetChVal(ch) + 5 if (v>255): v=255 SetChVal(ch, v) elif nm=="g" or nm=="green" or nm=="r" or nm=="red": v = GetChVal(ch) - 5 if (v>255): v=255 SetChVal(ch, v)
artistic-2.0
maxrevilo/Mazzaroth
Assets/Plugins/BehaviourMachine/Source/Nodes/Composites/Selector.cs
2069
//---------------------------------------------- // Behaviour Machine // Copyright © 2014 Anderson Campos Cardoso //---------------------------------------------- using UnityEngine; using System.Collections; namespace BehaviourMachine { /// <summary> /// Think "or" logic. If one child does not fails, then the execution is stopped and the selector returns the status of this child. /// If a child fails then sequantially runs the next child. /// If all child fails, returns Failure. /// <seealso cref="BehaviourMachine.Sequence" /> /// <summary> [NodeInfo ( category = "Composite/", icon = "Selector", description = "Has an \"or\" logic. If one child succeed, then the execution is stopped and the selector returns Success. If a child fails then sequantially runs the next child. If all child fails, returns Failure")] public class Selector : CompositeNode { [System.NonSerialized] int m_CurrentChildIndex = 0; public override Status Update () { // Returns to the first child when finished if (m_CurrentChildIndex >= children.Length) m_CurrentChildIndex = 0; var childStatus = Status.Error; while (m_CurrentChildIndex < children.Length) { // Tick current child children[m_CurrentChildIndex].OnTick(); childStatus = children[m_CurrentChildIndex].status; // The child failed? if (childStatus == Status.Failure) { // Go to the next child ++m_CurrentChildIndex; } else { // Break the loop break; } } return childStatus; } public override void End () { m_CurrentChildIndex = 0; } public override void OnValidate () { base.OnValidate(); m_CurrentChildIndex = 0; } } }
artistic-2.0
UltrosBot/Ultros3K
tests/storage/config/test_json.py
5947
# coding=utf-8 import os import secrets import shutil import tempfile from nose.tools import assert_equal, assert_true from unittest import TestCase from ultros.core.storage.config.json import JSONConfig from ultros.core.storage.manager import StorageManager __author__ = "Gareth Coles" class TestJSON(TestCase): def setUp(self): self.directory = os.path.join(tempfile.gettempdir(), secrets.token_urlsafe(10)) if not os.path.exists(self.directory): os.mkdir(self.directory) self.config_dir = os.path.join(self.directory, "config") self.data_dir = os.path.join(self.directory, "data") if not os.path.exists(self.config_dir): os.mkdir(self.config_dir) if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) current_dir = os.path.dirname(__file__) tests_dir = os.path.join(current_dir, "../../") shutil.copy(os.path.join(tests_dir, "files/test.json"), os.path.join(self.config_dir, "test.json")) self.manager = StorageManager( ultros=None, config_location=self.config_dir, data_location=self.data_dir ) def tearDown(self): self.manager.shutdown() del self.manager if os.path.exists(self.directory): shutil.rmtree(self.directory) def test_dict_functionality(self): """ JSON config testing: Dict functionality """ def _config_object() -> JSONConfig: return self.manager.get_config( "test.json", None ) config_obj = _config_object() config_obj.clear() assert_equal( len(config_obj), 0 ) config_obj.reload() assert_equal( len(config_obj), 6 ) assert_equal( config_obj.copy(), config_obj.data ) assert_equal( config_obj.get("test"), "test" ) assert_equal( list(config_obj.items()), [ ("test", "test"), ("herp", "derp"), ("int", 1), ("float", 1.1), ("boolean", True), ("other_boolean", False) ] ) assert_equal( list(config_obj.keys()), ["test", "herp", "int", "float", "boolean", "other_boolean"] ) assert_equal( config_obj.pop("test"), "test" ) assert_equal( list(config_obj.keys()), ["herp", "int", "float", "boolean", "other_boolean"] ) config_obj.reload() config_obj.popitem() assert_equal( len(config_obj), 5 ) config_obj.reload() assert_equal( config_obj.setdefault("berp", "lerp"), "lerp" ) assert_equal( config_obj.get("berp"), "lerp" ) config_obj.reload() config_obj.update({"berp": "lerp"}) assert_equal( config_obj.get("berp"), "lerp" ) config_obj.reload() assert_equal( list(config_obj.values()), ["test", "derp", 1, 1.1, True, False] ) assert_true( "test" in config_obj ) del config_obj["test"] assert_true( "test" not in config_obj ) config_obj.reload() assert_equal( config_obj["test"], "test" ) assert_equal( list(config_obj), ["test", "herp", "int", "float", "boolean", "other_boolean"] ) assert_equal( len(config_obj), 6 ) config_obj["x"] = "y" assert_equal( config_obj["x"], "y" ) def test_read(self): """ JSON config testing: Reading """ def _config_object() -> JSONConfig: return self.manager.get_config( "test.json", None ) config_obj = _config_object() assert_equal( config_obj["test"], "test" ) assert_equal( config_obj["herp"], "derp" ) assert_equal( config_obj["int"], 1 ) assert_equal( config_obj["float"], 1.1 ) assert_equal( config_obj["boolean"], True ) assert_equal( config_obj["other_boolean"], False ) def test_write(self): """ JSON config testing: Writing """ def _config_object() -> JSONConfig: return self.manager.get_config( "test.json", None ) config_obj = _config_object() with config_obj: config_obj["test"] = "test2" config_obj["int"] = 2 config_obj["float"] = 2.2 config_obj["boolean"] = False config_obj["other_boolean"] = True config_obj["list"] = ["herp"] config_obj["dict"] = {"herp": "derp"} config_obj.reload() assert_equal( config_obj["test"], "test2" ) assert_equal( config_obj["int"], 2 ) assert_equal( config_obj["float"], 2.2 ) assert_equal( config_obj["boolean"], False ) assert_equal( config_obj["other_boolean"], True ) assert_equal( config_obj["list"], ["herp"] ) assert_equal( config_obj["dict"], {"herp": "derp"} )
artistic-2.0
tzachshabtay/MonoAGS
Source/AGS.API/Misc/Drawing/WrapMode.cs
110
namespace AGS.API { public enum WrapMode { Tile, TileFlipX, TileFlipY, TileFlipXY, Clamp } }
artistic-2.0
brunolauze/MonoNative
MonoNative.Tests/mscorlib/System/Diagnostics/mscorlib_System_Diagnostics_StackFrame_Fixture.cpp
3529
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Diagnostics // Name: StackFrame // C++ Typed Name: mscorlib::System::Diagnostics::StackFrame #include <gtest/gtest.h> #include <mscorlib/System/Diagnostics/mscorlib_System_Diagnostics_StackFrame.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodBase.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Diagnostics { //Constructors Tests //StackFrame() TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,DefaultConstructor) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //StackFrame(mscorlib::System::Boolean fNeedFileInfo) TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,Constructor_2) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //StackFrame(mscorlib::System::Int32 skipFrames) TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,Constructor_3) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //StackFrame(mscorlib::System::Int32 skipFrames, mscorlib::System::Boolean fNeedFileInfo) TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,Constructor_4) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //StackFrame(mscorlib::System::String fileName, mscorlib::System::Int32 lineNumber) TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,Constructor_5) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //StackFrame(mscorlib::System::String fileName, mscorlib::System::Int32 lineNumber, mscorlib::System::Int32 colNumber) TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,Constructor_6) { mscorlib::System::Diagnostics::StackFrame *value = new mscorlib::System::Diagnostics::StackFrame(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests // Method GetFileLineNumber // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetFileLineNumber_Test) { } // Method GetFileColumnNumber // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetFileColumnNumber_Test) { } // Method GetFileName // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetFileName_Test) { } // Method GetILOffset // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetILOffset_Test) { } // Method GetMethod // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetMethod_Test) { } // Method GetNativeOffset // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,GetNativeOffset_Test) { } // Method ToString // Signature: TEST(mscorlib_System_Diagnostics_StackFrame_Fixture,ToString_Test) { } } } }
bsd-2-clause
stapler/stapler
core/src/main/java/org/kohsuke/stapler/lang/Klass.java
4015
package org.kohsuke.stapler.lang; import org.kohsuke.stapler.Function; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import edu.umd.cs.findbugs.annotations.NonNull; /** * Abstraction of class-like object, agnostic to languages. * * <p> * To support other JVM languages that use their own specific types to represent a class * (such as JRuby and Jython), we now use this object instead of {@link Class}. This allows * us to reuse much of the logic of class traversal/resource lookup across different languages. * * This is a convenient tuple so that we can pass around a single argument instead of two. * * @param <C> * Variable that represents the type of {@code Class} like object in this language. * * @author Kohsuke Kawaguchi */ public final class Klass<C> { public final C clazz; public final KlassNavigator<C> navigator; public Klass(C clazz, KlassNavigator<C> navigator) { this.clazz = clazz; this.navigator = navigator; } public URL getResource(String resourceName) { return navigator.getResource(clazz,resourceName); } public Iterable<Klass<?>> getAncestors() { return navigator.getAncestors(clazz); } public Klass<?> getSuperClass() { return navigator.getSuperClass(clazz); } public Class toJavaClass() { return navigator.toJavaClass(clazz); } /** * @since 1.220 */ public List<MethodRef> getDeclaredMethods() { return navigator.getDeclaredMethods(clazz); } /** * Gets list of fields declared by the class. * @return List of fields. * May return empty list in the case of obsolete {@link #navigator}, which does not offer the method. * @since 1.246 */ @NonNull public List<FieldRef> getDeclaredFields() { return navigator.getDeclaredFields(clazz); } /** * Gets all the public fields defined in this type, including super types. * * @see Class#getFields() */ public List<FieldRef> getFields() { Map<String,FieldRef> fields = new LinkedHashMap<>(); for (Klass<?> k = this; k!=null; k=k.getSuperClass()) { for (FieldRef f : k.getDeclaredFields()) { String name = f.getName(); if (!fields.containsKey(name) && f.isRoutable()) { fields.put(name,f); } } } return new ArrayList<>(fields.values()); } /** * Reports all the methods that can be used for routing requests on this class. * @return List of functions. * May return empty list in the case of obsolete {@link #navigator}, which does not offer the method. * @since 1.246 */ @NonNull public List<Function> getFunctions() { return navigator.getFunctions(clazz); } public boolean isArray() { return navigator.isArray(clazz); } public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException { return navigator.getArrayElement(o,index); } public boolean isMap() { return navigator.isMap(clazz); } public Object getMapElement(Object o, String key) { return navigator.getMapElement(o,key); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Klass that = (Klass) o; return clazz.equals(that.clazz) && navigator.equals(that.navigator); } @Override public int hashCode() { return 31 * clazz.hashCode() + navigator.hashCode(); } @Override public String toString() { return clazz.toString(); } /** * Creates {@link Klass} from a Java {@link Class}. */ public static Klass<Class> java(Class c) { return c == null ? null : new Klass<>(c, KlassNavigator.JAVA); } }
bsd-2-clause
eslint/espree
tests/fixtures/ecma-version/9/rest-property/invalid-parenthesized-2.src.js
20
let {...(a,b)} = foo
bsd-2-clause
TheTypoMaster/SPHERE-Framework
Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/0.3.9/vendor/phing/phing/classes/phing/tasks/system/condition/IsSetCondition.php
1905
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. */ require_once 'phing/ProjectComponent.php'; require_once 'phing/tasks/system/condition/Condition.php'; /** * Condition that tests whether a given property has been set. * * @author Hans Lellelid <hans@xmpl.org> (Phing) * @author Stefan Bodewig <stefan.bodewig@epost.de> (Ant) * @version $Id$ * @package phing.tasks.system.condition */ class IsSetCondition extends ProjectComponent implements Condition { private $property; /** * @param $p */ public function setProperty( $p ) { $this->property = $p; } /** * Check whether property is set. * * @throws BuildException */ public function evaluate() { if ($this->property === null) { throw new BuildException( "No property specified for isset " ."condition" ); } return $this->project->getProperty( $this->property ) !== null; } }
bsd-2-clause
dimddev/NetCatKS
NetCatKS/Components/api/interfaces/__init__.py
1405
""" A module container for our Components interfaces """ from NetCatKS.Components.api.interfaces.adapters import IJSONResourceAPI, IJSONResourceRootAPI, IRequestSubscriber from NetCatKS.Components.api.interfaces.loaders import IBaseLoader from NetCatKS.Components.api.interfaces.registration.adapters import IRegisterAdapters from NetCatKS.Components.api.interfaces.registration.factories import IRegisterFactories from NetCatKS.Components.api.interfaces.registration.protocols import IRegisterProtocols from NetCatKS.Components.api.interfaces.registration.wamp import IWAMPResource, IRegisterWamp, IWAMPComponent from NetCatKS.Components.api.interfaces.registration.wamp import IWAMPLoadOnRunTime from NetCatKS.Components.api.interfaces.storages import IStorageRegister from NetCatKS.Components.api.interfaces.loaders import IUserFactory, IUserStorage, IUserWampComponent from NetCatKS.Components.api.interfaces.loaders import IUserGlobalSubscriber, IJSONResource __author__ = 'dimd' __all__ = [ 'IBaseLoader', 'IRegisterAdapters', 'IRegisterFactories', 'IRegisterProtocols', 'IStorageRegister', 'IWAMPResource', 'IRegisterWamp', 'IWAMPComponent', 'IUserFactory', 'IUserStorage', 'IUserWampComponent', 'IUserGlobalSubscriber', 'IJSONResource', 'IJSONResourceAPI', 'IJSONResourceRootAPI', 'IRequestSubscriber', 'IWAMPLoadOnRunTime' ]
bsd-2-clause
claui/homebrew-cask
Casks/telegram.rb
944
cask 'telegram' do version '5.2.2-171178' sha256 '2ca57e9dbd861765db5f1f38189c6bb09d4300e2bc41bd170c1539c94f1f9094' url "https://osx.telegram.org/updates/Telegram-#{version}.app.zip" appcast 'https://osx.telegram.org/updates/versions.xml' name 'Telegram for macOS' homepage 'https://macos.telegram.org/' auto_updates true depends_on macos: '>= :el_capitan' app 'Telegram.app' zap trash: [ '~/Library/Application Scripts/ru.keepcoder.Telegram', '~/Library/Application Scripts/ru.keepcoder.Telegram.TelegramShare', '~/Library/Containers/ru.keepcoder.Telegram', '~/Library/Containers/ru.keepcoder.Telegram.TelegramShare', '~/Library/Group Containers/*.ru.keepcoder.Telegram', '~/Library/Preferences/ru.keepcoder.Telegram.plist', '~/Library/Saved Application State/ru.keepcoder.Telegram.savedState', ] end
bsd-2-clause
epiqc/ScaffCC
clang/test/OpenMP/teams_distribute_parallel_for_ast_print.cpp
7433
// RUN: %clang_cc1 -verify -fopenmp -ast-print %s -Wno-openmp-mapping | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print -Wno-openmp-mapping | FileCheck %s // RUN: %clang_cc1 -verify -fopenmp-simd -ast-print %s -Wno-openmp-mapping | FileCheck %s // RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print -Wno-openmp-mapping | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER void foo() {} int x; #pragma omp threadprivate(x) struct S { S(): a(0) {} S(int v) : a(v) {} int a; typedef int type; }; template <typename T> class S7 : public T { protected: T a; S7() : a(0) {} public: S7(typename T::type v) : a(v) { #pragma omp target #pragma omp teams distribute parallel for private(a) private(this->a) private(T::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S7 &operator=(S7 &s) { #pragma omp target #pragma omp teams distribute parallel for private(a) private(this->a) for (int k = 0; k < s.a.a; ++k) ++s.a.a; foo(); return *this; } void foo() { int b, argv, d, c, e, f; #pragma omp target #pragma omp teams distribute parallel for default(none), private(b) firstprivate(argv) shared(d) reduction(+:c) reduction(max:e) num_teams(f) thread_limit(d) copyin(x) for (int k = 0; k < a.a; ++k) ++a.a; } }; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(this->a) private(this->a) private(T::a) // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(this->a) private(this->a) // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for default(none) private(b) firstprivate(argv) shared(d) reduction(+: c) reduction(max: e) num_teams(f) thread_limit(d) copyin(x) class S8 : public S7<S> { S8() {} public: S8(int v) : S7<S>(v){ #pragma omp target #pragma omp teams distribute parallel for private(a) private(this->a) private(S7<S>::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S8 &operator=(S8 &s) { #pragma omp target #pragma omp teams distribute parallel for private(a) private(this->a) for (int k = 0; k < s.a.a; ++k) ++s.a.a; bar(); return *this; } void bar() { int b, argv, d, c, e, f8; #pragma omp target #pragma omp teams distribute parallel for allocate(b) default(none), private(b) firstprivate(argv) shared(d) reduction(+:c) reduction(max:e) num_teams(f8) thread_limit(d) copyin(x) allocate(argv) for (int k = 0; k < a.a; ++k) ++a.a; } }; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(this->a) private(this->a) private(this->S::a) // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(this->a) private(this->a) private(this->S7<S>::a) // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(this->a) private(this->a) // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for allocate(b) default(none) private(b) firstprivate(argv) shared(d) reduction(+: c) reduction(max: e) num_teams(f8) thread_limit(d) copyin(x) allocate(argv) template <class T, int N> T tmain(T argc) { T b = argc, c, d, e, f, g; static T a; // CHECK: static T a; const T clen = 5; const T alen = 16; int arr[10]; #pragma omp target #pragma omp teams distribute parallel for for (int i=0; i < 2; ++i) a = 2; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for{{$}} // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: a = 2; #pragma omp target #pragma omp teams distribute parallel for private(argc, b), firstprivate(c, d), collapse(2) for (int i = 0; i < 10; ++i) for (int j = 0; j < 10; ++j) foo(); // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(argc,b) firstprivate(c,d) collapse(2) // CHECK-NEXT: for (int i = 0; i < 10; ++i) // CHECK-NEXT: for (int j = 0; j < 10; ++j) // CHECK-NEXT: foo(); for (int i = 0; i < 10; ++i) foo(); // CHECK: for (int i = 0; i < 10; ++i) // CHECK-NEXT: foo(); #pragma omp target #pragma omp teams distribute parallel for for (int i = 0; i < 10; ++i) foo(); // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for // CHECK-NEXT: for (int i = 0; i < 10; ++i) // CHECK-NEXT: foo(); #pragma omp target #pragma omp teams distribute parallel for default(none), private(b) firstprivate(argc) shared(d) reduction(+:c) reduction(max:e) num_teams(f) thread_limit(d) copyin(x) for (int k = 0; k < 10; ++k) e += d + argc; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for default(none) private(b) firstprivate(argc) shared(d) reduction(+: c) reduction(max: e) num_teams(f) thread_limit(d) copyin(x) // CHECK-NEXT: for (int k = 0; k < 10; ++k) // CHECK-NEXT: e += d + argc; #pragma omp target #pragma omp teams distribute parallel for for (int k = 0; k < 10; ++k) e += d + argc; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for // CHECK-NEXT: for (int k = 0; k < 10; ++k) // CHECK-NEXT: e += d + argc; return T(); } int main (int argc, char **argv) { int b = argc, c, d, e, f, g; static int a; // CHECK: static int a; const int clen = 5; const int N = 10; int arr[10]; #pragma omp target #pragma omp teams distribute parallel for for (int i=0; i < 2; ++i) a = 2; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: a = 2; #pragma omp target #pragma omp teams distribute parallel for private(argc,b),firstprivate(argv, c), collapse(2) for (int i = 0; i < 10; ++i) for (int j = 0; j < 10; ++j) foo(); // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for private(argc,b) firstprivate(argv,c) collapse(2) // CHECK-NEXT: for (int i = 0; i < 10; ++i) // CHECK-NEXT: for (int j = 0; j < 10; ++j) // CHECK-NEXT: foo(); for (int i = 0; i < 10; ++i) foo(); // CHECK: for (int i = 0; i < 10; ++i) // CHECK-NEXT: foo(); #pragma omp target #pragma omp teams distribute parallel for for (int i = 0; i < 10; ++i)foo(); // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for // CHECK-NEXT: for (int i = 0; i < 10; ++i) // CHECK-NEXT: foo(); #pragma omp target #pragma omp teams distribute parallel for default(none), private(b) firstprivate(argc) shared(d) reduction(+:c) reduction(max:e) num_teams(f) thread_limit(d) copyin(x) for (int k = 0; k < 10; ++k) e += d + argc; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for default(none) private(b) firstprivate(argc) shared(d) reduction(+: c) reduction(max: e) num_teams(f) thread_limit(d) copyin(x) // CHECK-NEXT: for (int k = 0; k < 10; ++k) // CHECK-NEXT: e += d + argc; #pragma omp target #pragma omp teams distribute parallel for for (int k = 0; k < 10; ++k) e += d + argc; // CHECK: #pragma omp target // CHECK-NEXT: #pragma omp teams distribute parallel for // CHECK-NEXT: for (int k = 0; k < 10; ++k) // CHECK-NEXT: e += d + argc; return (0); } #endif
bsd-2-clause
liberborn/extapp
app/portal/store/AboutStore.js
413
/*global Ext*/ /*jslint browser: true*/ /*jshint strict: false*/ Ext.define('Demo.store.AboutStore', { extend: 'Ext.data.Store', alias: 'widget.aboutWindow', model: 'Demo.model.AboutModel', proxy : { type : 'memory', reader : { type : 'json' } } autoLoad : false, sorters : [{ property : 'name', direction : 'ASC' }] });
bsd-2-clause
vividos/OldStuff
C64/src/d64view/source/document.hpp
913
/* d64view - a d64 disk image viewer Copyright (c) 2002,2003,2016 Michael Fink */ /*! \file document.hpp \brief wxWindows document disk document class for doc/view model */ // import guard #ifndef d64view_document_hpp_ #define d64view_document_hpp_ // needed includes #include "imagebase.hpp" // classes //! d64 disk document class class disk_document: public wxDocument { public: //! ctor disk_document(); //! dtor virtual ~disk_document(); //! assign operator const disk_document& operator=(const disk_document& doc); //! returns current disk image disk_image_base* get_disk_image(){ return image; } protected: //! called on opening a document virtual bool OnOpenDocument(const wxString& filename); protected: //! generic disk image pointer disk_image_base* image; private: DECLARE_DYNAMIC_CLASS(disk_document) }; #endif //d64view_document_hpp_
bsd-2-clause
angelsbaytech/AVnode.net
lib/routes/crews/show.js
692
const router = require('../router')(); const User = require('../../models/User'); //const Crew = require('../../models/Crew'); router.get('/', (req, res, next) => { //Crew User.findOne({slug: req.params.slug}) .populate([{ path: 'image', model: 'Asset' }, { path: 'teaserImage', model: 'Asset' }, { path: 'members', model: 'User', populate: [{ path: 'image', model: 'Asset' }] }]) .exec((err, crew) => { if (err || crew === null) { console.log('routes/crews/show err:' + err); return next(err); } res.render('crews/show', { title: crew.name, crew: crew }); }); }); module.exports = router;
bsd-2-clause
mlcit/pakiti3
lib/model/CveDef.php
2600
<?php # Copyright (c) 2017, CESNET. All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # o Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # o Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. /** * @author Vadym Yanovskyy */ class CveDef { private $_id; private $_definitionId; private $_title; private $_refUrl; private $_vdsSubSourceDefId; private $_cves = array(); public function getCves() { return $this->_cves; } public function setCves($cves) { $this->_cves = $cves; } public function getId() { return $this->_id; } public function setId($id) { $this->_id = $id; } public function getDefinitionId() { return $this->_definitionId; } public function setDefinitionId($definitionId) { $this->_definitionId = $definitionId; } public function getTitle() { return $this->_title; } public function setTitle($title) { $this->_title = $title; } public function getRefUrl() { return $this->_refUrl; } public function setRefUrl($refUrl) { $this->_refUrl = $refUrl; } public function getVdsSubSourceDefId() { return $this->_vdsSubSourceDefId; } public function setVdsSubSourceDefId($vdsSubSourceDefId) { $this->_vdsSubSourceDefId = $vdsSubSourceDefId; } }
bsd-2-clause
nihospr01/OpenSpeechPlatform-UCSD
Sources/liblsl/lslboost/boost/concept_check.hpp
32052
// // (C) Copyright Jeremy Siek 2000. // Copyright 2002 The Trustees of Indiana University. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Revision History: // 05 May 2001: Workarounds for HP aCC from Thomas Matelich. (Jeremy Siek) // 02 April 2001: Removed limits header altogether. (Jeremy Siek) // 01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock) // // See http://www.boost.org/libs/concept_check for documentation. #ifndef BOOST_CONCEPT_CHECKS_HPP # define BOOST_CONCEPT_CHECKS_HPP # include <boost/concept/assert.hpp> # include <iterator> # include <boost/type_traits/conversion_traits.hpp> # include <utility> # include <boost/type_traits/is_same.hpp> # include <boost/type_traits/is_void.hpp> # include <boost/static_assert.hpp> # include <boost/type_traits/integral_constant.hpp> # include <boost/config/workaround.hpp> # include <boost/concept/usage.hpp> # include <boost/concept/detail/concept_def.hpp> #if (defined _MSC_VER) # pragma warning( push ) # pragma warning( disable : 4510 ) // default constructor could not be generated # pragma warning( disable : 4610 ) // object 'class' can never be instantiated - user-defined constructor required #endif namespace lslboost { // // Backward compatibility // template <class Model> inline void function_requires(Model* = 0) { BOOST_CONCEPT_ASSERT((Model)); } template <class T> inline void ignore_unused_variable_warning(T const&) {} # define BOOST_CLASS_REQUIRE(type_var, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept<type_var>)) # define BOOST_CLASS_REQUIRE2(type_var1, type_var2, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept<type_var1,type_var2>)) # define BOOST_CLASS_REQUIRE3(tv1, tv2, tv3, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept<tv1,tv2,tv3>)) # define BOOST_CLASS_REQUIRE4(tv1, tv2, tv3, tv4, ns, concept) \ BOOST_CONCEPT_ASSERT((ns::concept<tv1,tv2,tv3,tv4>)) // // Begin concept definitions // BOOST_concept(Integer, (T)) { BOOST_CONCEPT_USAGE(Integer) { x.error_type_must_be_an_integer_type(); } private: T x; }; template <> struct Integer<char> {}; template <> struct Integer<signed char> {}; template <> struct Integer<unsigned char> {}; template <> struct Integer<short> {}; template <> struct Integer<unsigned short> {}; template <> struct Integer<int> {}; template <> struct Integer<unsigned int> {}; template <> struct Integer<long> {}; template <> struct Integer<unsigned long> {}; # if defined(BOOST_HAS_LONG_LONG) template <> struct Integer< ::lslboost::long_long_type> {}; template <> struct Integer< ::lslboost::ulong_long_type> {}; # elif defined(BOOST_HAS_MS_INT64) template <> struct Integer<__int64> {}; template <> struct Integer<unsigned __int64> {}; # endif BOOST_concept(SignedInteger,(T)) { BOOST_CONCEPT_USAGE(SignedInteger) { x.error_type_must_be_a_signed_integer_type(); } private: T x; }; template <> struct SignedInteger<signed char> { }; template <> struct SignedInteger<short> {}; template <> struct SignedInteger<int> {}; template <> struct SignedInteger<long> {}; # if defined(BOOST_HAS_LONG_LONG) template <> struct SignedInteger< ::lslboost::long_long_type> {}; # elif defined(BOOST_HAS_MS_INT64) template <> struct SignedInteger<__int64> {}; # endif BOOST_concept(UnsignedInteger,(T)) { BOOST_CONCEPT_USAGE(UnsignedInteger) { x.error_type_must_be_an_unsigned_integer_type(); } private: T x; }; template <> struct UnsignedInteger<unsigned char> {}; template <> struct UnsignedInteger<unsigned short> {}; template <> struct UnsignedInteger<unsigned int> {}; template <> struct UnsignedInteger<unsigned long> {}; # if defined(BOOST_HAS_LONG_LONG) template <> struct UnsignedInteger< ::lslboost::ulong_long_type> {}; # elif defined(BOOST_HAS_MS_INT64) template <> struct UnsignedInteger<unsigned __int64> {}; # endif //=========================================================================== // Basic Concepts BOOST_concept(DefaultConstructible,(TT)) { BOOST_CONCEPT_USAGE(DefaultConstructible) { TT a; // require default constructor ignore_unused_variable_warning(a); } }; BOOST_concept(Assignable,(TT)) { BOOST_CONCEPT_USAGE(Assignable) { #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL a = b; // require assignment operator #endif const_constraints(b); } private: void const_constraints(const TT& x) { #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL a = x; // const required for argument to assignment #else ignore_unused_variable_warning(x); #endif } private: TT a; TT b; }; BOOST_concept(CopyConstructible,(TT)) { BOOST_CONCEPT_USAGE(CopyConstructible) { TT a(b); // require copy constructor TT* ptr = &a; // require address of operator const_constraints(a); ignore_unused_variable_warning(ptr); } private: void const_constraints(const TT& a) { TT c(a); // require const copy constructor const TT* ptr = &a; // require const address of operator ignore_unused_variable_warning(c); ignore_unused_variable_warning(ptr); } TT b; }; // The SGI STL version of Assignable requires copy constructor and operator= BOOST_concept(SGIAssignable,(TT)) { BOOST_CONCEPT_USAGE(SGIAssignable) { TT c(a); #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL a = b; // require assignment operator #endif const_constraints(b); ignore_unused_variable_warning(c); } private: void const_constraints(const TT& x) { TT c(x); #if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL a = x; // const required for argument to assignment #endif ignore_unused_variable_warning(c); } TT a; TT b; }; BOOST_concept(Convertible,(X)(Y)) { BOOST_CONCEPT_USAGE(Convertible) { Y y = x; ignore_unused_variable_warning(y); } private: X x; }; // The C++ standard requirements for many concepts talk about return // types that must be "convertible to bool". The problem with this // requirement is that it leaves the door open for evil proxies that // define things like operator|| with strange return types. Two // possible solutions are: // 1) require the return type to be exactly bool // 2) stay with convertible to bool, and also // specify stuff about all the logical operators. // For now we just test for convertible to bool. template <class TT> void require_boolean_expr(const TT& t) { bool x = t; ignore_unused_variable_warning(x); } BOOST_concept(EqualityComparable,(TT)) { BOOST_CONCEPT_USAGE(EqualityComparable) { require_boolean_expr(a == b); require_boolean_expr(a != b); } private: TT a, b; }; BOOST_concept(LessThanComparable,(TT)) { BOOST_CONCEPT_USAGE(LessThanComparable) { require_boolean_expr(a < b); } private: TT a, b; }; // This is equivalent to SGI STL's LessThanComparable. BOOST_concept(Comparable,(TT)) { BOOST_CONCEPT_USAGE(Comparable) { require_boolean_expr(a < b); require_boolean_expr(a > b); require_boolean_expr(a <= b); require_boolean_expr(a >= b); } private: TT a, b; }; #define BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(OP,NAME) \ BOOST_concept(NAME, (First)(Second)) \ { \ BOOST_CONCEPT_USAGE(NAME) { (void)constraints_(); } \ private: \ bool constraints_() { return a OP b; } \ First a; \ Second b; \ } #define BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(OP,NAME) \ BOOST_concept(NAME, (Ret)(First)(Second)) \ { \ BOOST_CONCEPT_USAGE(NAME) { (void)constraints_(); } \ private: \ Ret constraints_() { return a OP b; } \ First a; \ Second b; \ } BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(==, EqualOp); BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(!=, NotEqualOp); BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<, LessThanOp); BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<=, LessEqualOp); BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>, GreaterThanOp); BOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>=, GreaterEqualOp); BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(+, PlusOp); BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(*, TimesOp); BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(/, DivideOp); BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(-, SubtractOp); BOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(%, ModOp); //=========================================================================== // Function Object Concepts BOOST_concept(Generator,(Func)(Return)) { BOOST_CONCEPT_USAGE(Generator) { test(is_void<Return>()); } private: void test(lslboost::false_type) { // Do we really want a reference here? const Return& r = f(); ignore_unused_variable_warning(r); } void test(lslboost::true_type) { f(); } Func f; }; BOOST_concept(UnaryFunction,(Func)(Return)(Arg)) { BOOST_CONCEPT_USAGE(UnaryFunction) { test(is_void<Return>()); } private: void test(lslboost::false_type) { f(arg); // "priming the pump" this way keeps msvc6 happy (ICE) Return r = f(arg); ignore_unused_variable_warning(r); } void test(lslboost::true_type) { f(arg); } #if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ && BOOST_WORKAROUND(__GNUC__, > 3))) // Declare a dummy constructor to make gcc happy. // It seems the compiler can not generate a sensible constructor when this is instantiated with a reference type. // (warning: non-static reference "const double& lslboost::UnaryFunction<YourClassHere>::arg" // in class without a constructor [-Wuninitialized]) UnaryFunction(); #endif Func f; Arg arg; }; BOOST_concept(BinaryFunction,(Func)(Return)(First)(Second)) { BOOST_CONCEPT_USAGE(BinaryFunction) { test(is_void<Return>()); } private: void test(lslboost::false_type) { f(first,second); Return r = f(first, second); // require operator() (void)r; } void test(lslboost::true_type) { f(first,second); } #if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ && BOOST_WORKAROUND(__GNUC__, > 3))) // Declare a dummy constructor to make gcc happy. // It seems the compiler can not generate a sensible constructor when this is instantiated with a reference type. // (warning: non-static reference "const double& lslboost::BinaryFunction<YourClassHere>::arg" // in class without a constructor [-Wuninitialized]) BinaryFunction(); #endif Func f; First first; Second second; }; BOOST_concept(UnaryPredicate,(Func)(Arg)) { BOOST_CONCEPT_USAGE(UnaryPredicate) { require_boolean_expr(f(arg)); // require operator() returning bool } private: #if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ && BOOST_WORKAROUND(__GNUC__, > 3))) // Declare a dummy constructor to make gcc happy. // It seems the compiler can not generate a sensible constructor when this is instantiated with a reference type. // (warning: non-static reference "const double& lslboost::UnaryPredicate<YourClassHere>::arg" // in class without a constructor [-Wuninitialized]) UnaryPredicate(); #endif Func f; Arg arg; }; BOOST_concept(BinaryPredicate,(Func)(First)(Second)) { BOOST_CONCEPT_USAGE(BinaryPredicate) { require_boolean_expr(f(a, b)); // require operator() returning bool } private: #if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ && BOOST_WORKAROUND(__GNUC__, > 3))) // Declare a dummy constructor to make gcc happy. // It seems the compiler can not generate a sensible constructor when this is instantiated with a reference type. // (warning: non-static reference "const double& lslboost::BinaryPredicate<YourClassHere>::arg" // in class without a constructor [-Wuninitialized]) BinaryPredicate(); #endif Func f; First a; Second b; }; // use this when functor is used inside a container class like std::set BOOST_concept(Const_BinaryPredicate,(Func)(First)(Second)) : BinaryPredicate<Func, First, Second> { BOOST_CONCEPT_USAGE(Const_BinaryPredicate) { const_constraints(f); } private: void const_constraints(const Func& fun) { // operator() must be a const member function require_boolean_expr(fun(a, b)); } #if (BOOST_WORKAROUND(__GNUC__, BOOST_TESTED_AT(4) \ && BOOST_WORKAROUND(__GNUC__, > 3))) // Declare a dummy constructor to make gcc happy. // It seems the compiler can not generate a sensible constructor when this is instantiated with a reference type. // (warning: non-static reference "const double& lslboost::Const_BinaryPredicate<YourClassHere>::arg" // in class without a constructor [-Wuninitialized]) Const_BinaryPredicate(); #endif Func f; First a; Second b; }; BOOST_concept(AdaptableGenerator,(Func)(Return)) : Generator<Func, typename Func::result_type> { typedef typename Func::result_type result_type; BOOST_CONCEPT_USAGE(AdaptableGenerator) { BOOST_CONCEPT_ASSERT((Convertible<result_type, Return>)); } }; BOOST_concept(AdaptableUnaryFunction,(Func)(Return)(Arg)) : UnaryFunction<Func, typename Func::result_type, typename Func::argument_type> { typedef typename Func::argument_type argument_type; typedef typename Func::result_type result_type; ~AdaptableUnaryFunction() { BOOST_CONCEPT_ASSERT((Convertible<result_type, Return>)); BOOST_CONCEPT_ASSERT((Convertible<Arg, argument_type>)); } }; BOOST_concept(AdaptableBinaryFunction,(Func)(Return)(First)(Second)) : BinaryFunction< Func , typename Func::result_type , typename Func::first_argument_type , typename Func::second_argument_type > { typedef typename Func::first_argument_type first_argument_type; typedef typename Func::second_argument_type second_argument_type; typedef typename Func::result_type result_type; ~AdaptableBinaryFunction() { BOOST_CONCEPT_ASSERT((Convertible<result_type, Return>)); BOOST_CONCEPT_ASSERT((Convertible<First, first_argument_type>)); BOOST_CONCEPT_ASSERT((Convertible<Second, second_argument_type>)); } }; BOOST_concept(AdaptablePredicate,(Func)(Arg)) : UnaryPredicate<Func, Arg> , AdaptableUnaryFunction<Func, bool, Arg> { }; BOOST_concept(AdaptableBinaryPredicate,(Func)(First)(Second)) : BinaryPredicate<Func, First, Second> , AdaptableBinaryFunction<Func, bool, First, Second> { }; //=========================================================================== // Iterator Concepts BOOST_concept(InputIterator,(TT)) : Assignable<TT> , EqualityComparable<TT> { typedef typename std::iterator_traits<TT>::value_type value_type; typedef typename std::iterator_traits<TT>::difference_type difference_type; typedef typename std::iterator_traits<TT>::reference reference; typedef typename std::iterator_traits<TT>::pointer pointer; typedef typename std::iterator_traits<TT>::iterator_category iterator_category; BOOST_CONCEPT_USAGE(InputIterator) { BOOST_CONCEPT_ASSERT((SignedInteger<difference_type>)); BOOST_CONCEPT_ASSERT((Convertible<iterator_category, std::input_iterator_tag>)); TT j(i); (void)*i; // require dereference operator ++j; // require preincrement operator i++; // require postincrement operator } private: TT i; }; BOOST_concept(OutputIterator,(TT)(ValueT)) : Assignable<TT> { BOOST_CONCEPT_USAGE(OutputIterator) { ++i; // require preincrement operator i++; // require postincrement operator *i++ = t; // require postincrement and assignment } private: TT i, j; ValueT t; }; BOOST_concept(ForwardIterator,(TT)) : InputIterator<TT> { BOOST_CONCEPT_USAGE(ForwardIterator) { BOOST_CONCEPT_ASSERT((Convertible< BOOST_DEDUCED_TYPENAME ForwardIterator::iterator_category , std::forward_iterator_tag >)); typename InputIterator<TT>::reference r = *i; ignore_unused_variable_warning(r); } private: TT i; }; BOOST_concept(Mutable_ForwardIterator,(TT)) : ForwardIterator<TT> { BOOST_CONCEPT_USAGE(Mutable_ForwardIterator) { *i++ = *j; // require postincrement and assignment } private: TT i, j; }; BOOST_concept(BidirectionalIterator,(TT)) : ForwardIterator<TT> { BOOST_CONCEPT_USAGE(BidirectionalIterator) { BOOST_CONCEPT_ASSERT((Convertible< BOOST_DEDUCED_TYPENAME BidirectionalIterator::iterator_category , std::bidirectional_iterator_tag >)); --i; // require predecrement operator i--; // require postdecrement operator } private: TT i; }; BOOST_concept(Mutable_BidirectionalIterator,(TT)) : BidirectionalIterator<TT> , Mutable_ForwardIterator<TT> { BOOST_CONCEPT_USAGE(Mutable_BidirectionalIterator) { *i-- = *j; // require postdecrement and assignment } private: TT i, j; }; BOOST_concept(RandomAccessIterator,(TT)) : BidirectionalIterator<TT> , Comparable<TT> { BOOST_CONCEPT_USAGE(RandomAccessIterator) { BOOST_CONCEPT_ASSERT((Convertible< BOOST_DEDUCED_TYPENAME BidirectionalIterator<TT>::iterator_category , std::random_access_iterator_tag >)); i += n; // require assignment addition operator i = i + n; i = n + i; // require addition with difference type i -= n; // require assignment subtraction operator i = i - n; // require subtraction with difference type n = i - j; // require difference operator (void)i[n]; // require element access operator } private: TT a, b; TT i, j; typename std::iterator_traits<TT>::difference_type n; }; BOOST_concept(Mutable_RandomAccessIterator,(TT)) : RandomAccessIterator<TT> , Mutable_BidirectionalIterator<TT> { BOOST_CONCEPT_USAGE(Mutable_RandomAccessIterator) { i[n] = *i; // require element access and assignment } private: TT i; typename std::iterator_traits<TT>::difference_type n; }; //=========================================================================== // Container s BOOST_concept(Container,(C)) : Assignable<C> { typedef typename C::value_type value_type; typedef typename C::difference_type difference_type; typedef typename C::size_type size_type; typedef typename C::const_reference const_reference; typedef typename C::const_pointer const_pointer; typedef typename C::const_iterator const_iterator; BOOST_CONCEPT_USAGE(Container) { BOOST_CONCEPT_ASSERT((InputIterator<const_iterator>)); const_constraints(c); } private: void const_constraints(const C& cc) { i = cc.begin(); i = cc.end(); n = cc.size(); n = cc.max_size(); b = cc.empty(); } C c; bool b; const_iterator i; size_type n; }; BOOST_concept(Mutable_Container,(C)) : Container<C> { typedef typename C::reference reference; typedef typename C::iterator iterator; typedef typename C::pointer pointer; BOOST_CONCEPT_USAGE(Mutable_Container) { BOOST_CONCEPT_ASSERT(( Assignable<typename Mutable_Container::value_type>)); BOOST_CONCEPT_ASSERT((InputIterator<iterator>)); i = c.begin(); i = c.end(); c.swap(c2); } private: iterator i; C c, c2; }; BOOST_concept(ForwardContainer,(C)) : Container<C> { BOOST_CONCEPT_USAGE(ForwardContainer) { BOOST_CONCEPT_ASSERT(( ForwardIterator< typename ForwardContainer::const_iterator >)); } }; BOOST_concept(Mutable_ForwardContainer,(C)) : ForwardContainer<C> , Mutable_Container<C> { BOOST_CONCEPT_USAGE(Mutable_ForwardContainer) { BOOST_CONCEPT_ASSERT(( Mutable_ForwardIterator< typename Mutable_ForwardContainer::iterator >)); } }; BOOST_concept(ReversibleContainer,(C)) : ForwardContainer<C> { typedef typename C::const_reverse_iterator const_reverse_iterator; BOOST_CONCEPT_USAGE(ReversibleContainer) { BOOST_CONCEPT_ASSERT(( BidirectionalIterator< typename ReversibleContainer::const_iterator>)); BOOST_CONCEPT_ASSERT((BidirectionalIterator<const_reverse_iterator>)); const_constraints(c); } private: void const_constraints(const C& cc) { const_reverse_iterator _i = cc.rbegin(); _i = cc.rend(); } C c; }; BOOST_concept(Mutable_ReversibleContainer,(C)) : Mutable_ForwardContainer<C> , ReversibleContainer<C> { typedef typename C::reverse_iterator reverse_iterator; BOOST_CONCEPT_USAGE(Mutable_ReversibleContainer) { typedef typename Mutable_ForwardContainer<C>::iterator iterator; BOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator<iterator>)); BOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator<reverse_iterator>)); reverse_iterator i = c.rbegin(); i = c.rend(); } private: C c; }; BOOST_concept(RandomAccessContainer,(C)) : ReversibleContainer<C> { typedef typename C::size_type size_type; typedef typename C::const_reference const_reference; BOOST_CONCEPT_USAGE(RandomAccessContainer) { BOOST_CONCEPT_ASSERT(( RandomAccessIterator< typename RandomAccessContainer::const_iterator >)); const_constraints(c); } private: void const_constraints(const C& cc) { const_reference r = cc[n]; ignore_unused_variable_warning(r); } C c; size_type n; }; BOOST_concept(Mutable_RandomAccessContainer,(C)) : Mutable_ReversibleContainer<C> , RandomAccessContainer<C> { private: typedef Mutable_RandomAccessContainer self; public: BOOST_CONCEPT_USAGE(Mutable_RandomAccessContainer) { BOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator<typename self::iterator>)); BOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator<typename self::reverse_iterator>)); typename self::reference r = c[i]; ignore_unused_variable_warning(r); } private: typename Mutable_ReversibleContainer<C>::size_type i; C c; }; // A Sequence is inherently mutable BOOST_concept(Sequence,(S)) : Mutable_ForwardContainer<S> // Matt Austern's book puts DefaultConstructible here, the C++ // standard places it in Container --JGS // ... so why aren't we following the standard? --DWA , DefaultConstructible<S> { BOOST_CONCEPT_USAGE(Sequence) { S c(n, t), c2(first, last); c.insert(p, t); c.insert(p, n, t); c.insert(p, first, last); c.erase(p); c.erase(p, q); typename Sequence::reference r = c.front(); ignore_unused_variable_warning(c); ignore_unused_variable_warning(c2); ignore_unused_variable_warning(r); const_constraints(c); } private: void const_constraints(const S& c) { typename Sequence::const_reference r = c.front(); ignore_unused_variable_warning(r); } typename S::value_type t; typename S::size_type n; typename S::value_type* first, *last; typename S::iterator p, q; }; BOOST_concept(FrontInsertionSequence,(S)) : Sequence<S> { BOOST_CONCEPT_USAGE(FrontInsertionSequence) { c.push_front(t); c.pop_front(); } private: S c; typename S::value_type t; }; BOOST_concept(BackInsertionSequence,(S)) : Sequence<S> { BOOST_CONCEPT_USAGE(BackInsertionSequence) { c.push_back(t); c.pop_back(); typename BackInsertionSequence::reference r = c.back(); ignore_unused_variable_warning(r); const_constraints(c); } private: void const_constraints(const S& cc) { typename BackInsertionSequence::const_reference r = cc.back(); ignore_unused_variable_warning(r); } S c; typename S::value_type t; }; BOOST_concept(AssociativeContainer,(C)) : ForwardContainer<C> , DefaultConstructible<C> { typedef typename C::key_type key_type; typedef typename C::key_compare key_compare; typedef typename C::value_compare value_compare; typedef typename C::iterator iterator; BOOST_CONCEPT_USAGE(AssociativeContainer) { i = c.find(k); r = c.equal_range(k); c.erase(k); c.erase(i); c.erase(r.first, r.second); const_constraints(c); BOOST_CONCEPT_ASSERT((BinaryPredicate<key_compare,key_type,key_type>)); typedef typename AssociativeContainer::value_type value_type_; BOOST_CONCEPT_ASSERT((BinaryPredicate<value_compare,value_type_,value_type_>)); } // Redundant with the base concept, but it helps below. typedef typename C::const_iterator const_iterator; private: void const_constraints(const C& cc) { ci = cc.find(k); n = cc.count(k); cr = cc.equal_range(k); } C c; iterator i; std::pair<iterator,iterator> r; const_iterator ci; std::pair<const_iterator,const_iterator> cr; typename C::key_type k; typename C::size_type n; }; BOOST_concept(UniqueAssociativeContainer,(C)) : AssociativeContainer<C> { BOOST_CONCEPT_USAGE(UniqueAssociativeContainer) { C c(first, last); pos_flag = c.insert(t); c.insert(first, last); ignore_unused_variable_warning(c); } private: std::pair<typename C::iterator, bool> pos_flag; typename C::value_type t; typename C::value_type* first, *last; }; BOOST_concept(MultipleAssociativeContainer,(C)) : AssociativeContainer<C> { BOOST_CONCEPT_USAGE(MultipleAssociativeContainer) { C c(first, last); pos = c.insert(t); c.insert(first, last); ignore_unused_variable_warning(c); ignore_unused_variable_warning(pos); } private: typename C::iterator pos; typename C::value_type t; typename C::value_type* first, *last; }; BOOST_concept(SimpleAssociativeContainer,(C)) : AssociativeContainer<C> { BOOST_CONCEPT_USAGE(SimpleAssociativeContainer) { typedef typename C::key_type key_type; typedef typename C::value_type value_type; BOOST_STATIC_ASSERT((lslboost::is_same<key_type,value_type>::value)); } }; BOOST_concept(PairAssociativeContainer,(C)) : AssociativeContainer<C> { BOOST_CONCEPT_USAGE(PairAssociativeContainer) { typedef typename C::key_type key_type; typedef typename C::value_type value_type; typedef typename C::mapped_type mapped_type; typedef std::pair<const key_type, mapped_type> required_value_type; BOOST_STATIC_ASSERT((lslboost::is_same<value_type,required_value_type>::value)); } }; BOOST_concept(SortedAssociativeContainer,(C)) : AssociativeContainer<C> , ReversibleContainer<C> { BOOST_CONCEPT_USAGE(SortedAssociativeContainer) { C c(kc), c2(first, last), c3(first, last, kc); p = c.upper_bound(k); p = c.lower_bound(k); r = c.equal_range(k); c.insert(p, t); ignore_unused_variable_warning(c); ignore_unused_variable_warning(c2); ignore_unused_variable_warning(c3); const_constraints(c); } void const_constraints(const C& c) { kc = c.key_comp(); vc = c.value_comp(); cp = c.upper_bound(k); cp = c.lower_bound(k); cr = c.equal_range(k); } private: typename C::key_compare kc; typename C::value_compare vc; typename C::value_type t; typename C::key_type k; typedef typename C::iterator iterator; typedef typename C::const_iterator const_iterator; typedef SortedAssociativeContainer self; iterator p; const_iterator cp; std::pair<typename self::iterator,typename self::iterator> r; std::pair<typename self::const_iterator,typename self::const_iterator> cr; typename C::value_type* first, *last; }; // HashedAssociativeContainer BOOST_concept(Collection,(C)) { BOOST_CONCEPT_USAGE(Collection) { lslboost::function_requires<lslboost::InputIteratorConcept<iterator> >(); lslboost::function_requires<lslboost::InputIteratorConcept<const_iterator> >(); lslboost::function_requires<lslboost::CopyConstructibleConcept<value_type> >(); const_constraints(c); i = c.begin(); i = c.end(); c.swap(c); } void const_constraints(const C& cc) { ci = cc.begin(); ci = cc.end(); n = cc.size(); b = cc.empty(); } private: typedef typename C::value_type value_type; typedef typename C::iterator iterator; typedef typename C::const_iterator const_iterator; typedef typename C::reference reference; typedef typename C::const_reference const_reference; // typedef typename C::pointer pointer; typedef typename C::difference_type difference_type; typedef typename C::size_type size_type; C c; bool b; iterator i; const_iterator ci; size_type n; }; } // namespace lslboost #if (defined _MSC_VER) # pragma warning( pop ) #endif # include <boost/concept/detail/concept_undef.hpp> #endif // BOOST_CONCEPT_CHECKS_HPP
bsd-2-clause
sebastienros/jint
Jint.Tests.Test262/test/language/statements/for-of/dstr-const-obj-ptrn-prop-obj.js
1935
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-prop-obj.case // - src/dstr-binding/default/for-of-const.template /*--- description: Object binding pattern with "nested" object binding pattern not using initializer (for-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation es6id: 13.7.5.11 features: [destructuring-binding] flags: [generated] info: | IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement [...] 3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 3. Let destructuring be IsDestructuring of lhs. [...] 5. Repeat [...] h. If destructuring is false, then [...] i. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization [...] 3. If Initializer is present and v is undefined, then [...] 4. Return the result of performing BindingInitialization for BindingPattern passing v and environment as arguments. ---*/ var iterCount = 0; for (const { w: { x, y, z } = { x: 4, y: 5, z: 6 } } of [{ w: { x: undefined, z: 7 } }]) { assert.sameValue(x, undefined); assert.sameValue(y, undefined); assert.sameValue(z, 7); assert.throws(ReferenceError, function() { w; }); iterCount += 1; } assert.sameValue(iterCount, 1, 'iteration occurred as expected');
bsd-2-clause
klupek/pdf2epl
pdf2epl.rb
15539
#!/usr/bin/env ruby require 'pdf/reader' require 'pp' class MyReceiver def initialize @lines = [] @texts = [] @images = [] @stack = [] @rectangles = [] @state = { :matrix => identity_matrix } @current_text = {} end def stats { :lines => @lines, :texts => @texts, :rectangles => @rectangles, :images => @images } end def page=(c) @page = c @page_height = @page.attributes[:MediaBox][3] end def set_line_cap_style(style) @current_line = {} unless @current_line @current_line[:style] = style end def set_line_width(width) @current_line = {} unless @current_line @current_line[:width] = width end def begin_text_object @current_text = {} if @current_text.nil? end def set_text_font_and_size(font_id, size) @current_text[:font] = font_id @current_text[:size] = size end def set_text_matrix_and_text_line_matrix(scale_x,shear_x,shear_y,scale_y,x,y) if scale_x == 1.0 and shear_x == 0 and shear_y == 0 and scale_y == 1 @current_text[:rotate] = :rotate0 elsif scale_x == 0 and shear_x == -1.0 and shear_y == 1.0 and scale_y == 0 @current_text[:rotate] = :rotate90 elsif scale_x == -1 and shear_x == 0 and shear_y == 0 and scale_y == -1 @current_text[:rotate] = :rotate180 elsif scale_x == 0 and shear_x == 1.0 and shear_y == -1.0 and scale_y == 0 @current_text[:rotate] = :rotate270 else raise RuntimeError,'EPL supports only (0,90,180,270) text rotation' end move_text_position(x,y) end def move_text_position(x,y) @current_text[:position] = [x, @page_height - y] end def show_text(text) @current_text[:text] = text end def set_horizontal_text_scaling(scale) @current_text[:hscale] = scale.to_f/100 end def end_text_object @texts << make_text(@current_text.clone) if @current_text[:text] and @current_text[:text].length > 0 @current_text[:text] = nil @current_text[:rotate] = :rotate0 end def make_text(obj) font = PDF::Reader::Font.new(@page.objects, @page.fonts[obj[:font]]) width = font.unpack(obj[:text]).map { |c| font.glyph_width(c)/1000*obj[:size] }.reduce(:+) obj[:text] = font.to_utf8(obj[:text]) obj[:width] = width if obj[:rotate] == :rotate0 obj[:end] = [ obj[:position][0] + obj[:width], obj[:position][1] + obj[:size] ] elsif obj[:rotate] == :rotate90 obj[:end] = [ obj[:position][0] + obj[:size], obj[:position][1] + obj[:width] ] elsif obj[:rotate] == :rotate180 obj[:end] = [ obj[:position][0] - obj[:width], obj[:position][1] - obj[:size] ] elsif obj[:rotate] == :rotate270 obj[:end] = [ obj[:position][0] - obj[:size], obj[:position][1] - obj[:width] ] end obj end def begin_new_subpath(x, y) @position = [ x, @page_height - y ] end def append_line(x, y) @lines << @current_line.merge({ :from => @position, :to => [ x, @page_height - y ] }) end def stroke_path # WTF? end def save_graphics_state @stack.push({ :matrix => @state[:matrix].clone }) end def restore_graphics_state @state = @stack.pop end def invoke_xobject(object_id) obj = @page.xobjects[object_id] raise RuntimeError, 'XObject not found: ' + object_id.to_s unless obj raise RuntimeError, 'Only image XObjects are supported: ' + obj.hash[:Subtype].to_s unless obj.hash[:Subtype] == :Image matrix = @state[:matrix].clone matrix = matrix.multiply!(*obj.hash[:Matrix].to_a) if obj.hash[:Matrix] @images << make_image({ :matrix => matrix.to_a, :image => obj }) end def make_image(obj) m = obj[:matrix] obj[:width] = m[0] obj[:height] = m[4] obj[:position] = [ m[6], @page_height - m[7] - obj[:height] ] raise RuntimeError, 'Only FlateDecode is currently supported' if obj[:image].hash[:Filter] != :FlateDecode cs = obj[:image].hash[:ColorSpace] # TODO: someone should make *real* image support, but i only need 1 bit bw images. raise RuntimeError, 'Only 1 bit indexed image is currently supported' unless cs[0] == :Indexed and cs[1] == :DeviceRGB and cs[2] == 1 and cs[3].unfiltered_data == "\x00\x00\x00\xFF\xFF\xFF".b bytes = Zlib::Inflate.new.inflate(obj[:image].data).b # img.hash[:Width] is few bits smaller then real image row ("scan line") in stream pixels_height = obj[:image].hash[:Height] pixels_width = (bytes.length*8 / pixels_height).to_i raise RuntimeError, 'Image row bit count should be integer value' if pixels_width*pixels_height != bytes.length*8 raise RuntimeError, 'Image row bit count should be rounded to 8 bits' if (pixels_width.to_f/8).to_i*8 != pixels_width obj[:data] = { :bytes => bytes, :width => pixels_width, :height => pixels_height } obj end def identity_matrix PDF::Reader::TransformationMatrix.new(1,0, 0,1, 0,0) end def concatenate_matrix(a,b,c,d,e,f) @state[:matrix].multiply!(a,b,c,d,e,f) end def append_rectangle(x,y, width, height) @rectangles << { :pos => [x,@page_height - y], :size => [width,-height], :print => false } end def fill_path_with_nonzero @rectangles.last[:print] = true end def method_missing(method, *args, &block) raise 'Unsupported pdf method: ' + [ method, *args ].inspect unless [ :r ].index(method) end def calculate_area minx = [] maxx = [] miny = [] maxy = [] minx << @lines.map { |line| [ line[:from][0], line[:to][0] ].min }.min maxx << @lines.map { |line| [ line[:from][0], line[:to][0] ].max }.max minx << @rectangles.map { |r| [ r[:pos][0], r[:pos][0] + r[:size][0] ].min }.min maxx << @rectangles.map { |r| [ r[:pos][0], r[:pos][0] + r[:size][0] ].max }.max minx << @texts.map { |text| [ text[:position][0], text[:end][0] ].min }.min maxx << @texts.map { |text| [ text[:position][0], text[:end][0] ].max }.max [ 'Lines', 'Rectangles', 'Texts' ].zip( minx.zip(maxx) ).each { |title, a| left, right = a STDERR.puts "#{title} from #{left} to #{right}" } miny << @lines.map { |line| [ line[:from][1], line[:to][1] ].min }.min maxy << @lines.map { |line| [ line[:from][1], line[:to][1] ].max }.max miny << @rectangles.map { |r| [ r[:pos][1], r[:pos][1] + r[:size][1] ].min }.min maxy << @rectangles.map { |r| [ r[:pos][1], r[:pos][1] + r[:size][1] ].max }.max miny << @texts.map { |text| [ text[:position][1], text[:end][1] ].min }.min maxy << @texts.map { |text| [ text[:position][1], text[:end][1] ].max }.max { :top => miny.min, :bottom => maxy.max, :left => minx.min, :right => maxx.max, :width => maxx.max - minx.min, :height => maxy.max - miny.min } end def scale_to(width, height) area = calculate_area STDERR.puts("Scaling #{area[:width]}x#{area[:height]} to #{width}x#{height}") offset = { :x => area[:left], :y => area[:top] } scale = { :x => area[:width]/width, :y => area[:height]/height } @texts.map! { |text| text[:realpos] = { :position => [ (text[:position][0] - offset[:x])/scale[:x], (text[:position][1] - offset[:y])/scale[:y] ], :width => text[:width]/scale[:x], :size => text[:size]/scale[:y], :hscale => text[:hscale] } if text[:rotate] == nil or text[:rotate] == :rotate0 text[:realpos][:position][1] -= text[:size]/scale[:y] elsif text[:rotate] == :rotate90 text[:realpos][:position][0] -= text[:size]/scale[:x] end # TODO: elsifs text } @rectangles.map! { |r| r[:realpos] = { :p0 => [ (r[:pos][0] - offset[:x])/scale[:x], (r[:pos][1] - offset[:y])/scale[:y] ], :p1 => [ (r[:pos][0] + r[:size][0] - offset[:x])/scale[:x], (r[:pos][1] + r[:size][1] - offset[:y])/scale[:y] ], } r[:realpos][:start] = [ [ r[:realpos][:p0][0], r[:realpos][:p1][0] ].min, [ r[:realpos][:p0][1], r[:realpos][:p1][1] ].min ] r[:realpos][:end] = [ [ r[:realpos][:p0][0], r[:realpos][:p1][0] ].max, [ r[:realpos][:p0][1], r[:realpos][:p1][1] ].max ] r[:realpos][:width] = r[:realpos][:end][0] - r[:realpos][:start][0] r[:realpos][:height] = r[:realpos][:end][1] - r[:realpos][:start][1] r } @lines.map! { |line| line[:realpos] = { :from => [ (line[:from][0] - offset[:x])/scale[:x], (line[:from][1] - offset[:y])/scale[:y] ], :to => [ (line[:to][0] - offset[:x])/scale[:x], (line[:to][1] - offset[:y])/scale[:y] ], } line[:realpos][:start] = [ [ line[:realpos][:from][0], line[:realpos][:to][0] ].min, [ line[:realpos][:from][1], line[:realpos][:to][1] ].min ] line[:realpos][:width] = [ line[:realpos][:from][0], line[:realpos][:to][0] ].max - line[:realpos][:start][0] line[:realpos][:height] = [ line[:realpos][:from][1], line[:realpos][:to][1] ].max - line[:realpos][:start][1] if line[:realpos][:width] == 0.0 line[:realpos][:width] = line[:width]/scale[:x] line[:realpos][:start][0] -= line[:realpos][:width] end if line[:realpos][:height] == 0.0 line[:realpos][:height] = line[:width]/scale[:y] line[:realpos][:start][1] -= line[:realpos][:height] end line } @images.map! { |image| image[:realpos] = { :position => [ (image[:position][0]-offset[:x])/scale[:x], (image[:position][1]-offset[:y])/scale[:y] ], :width => image[:width]/scale[:x], :height => image[:height]/scale[:y] } image } end def select_best_font_for_text(text, startfrom = 5) expected_height = text[:realpos][:size] expected_text_width = text[:realpos][:width] fonts = [ [ 1, 10, 12 ], # font id, width, height, in dots [ 2, 12, 16 ], [ 3, 14, 20 ], [ 4, 16, 24 ], [ 5, 36, 48 ] ] if startfrom <= 0 STDERR.puts("No good candidate for #{text[:text]}/#{expected_height}/#{expected_text_width/text[:text].length}, choosing font 1 and upscaling") f = fonts.first fid, vscale, hscale = [ f[0], (expected_height/f[2]).round, (expected_text_width.to_f/text[:text].length/f[1]).round ] #T text[:realpos][:position][1] -= vscale*f[2] STDERR.puts("Expected: width = #{expected_text_width}; height = #{expected_height}") STDERR.puts("Actual: width = #{hscale*f[1]*text[:text].length}; height = #{vscale*f[2]}") STDERR.puts("Upscale results: hscale x vscale = #{hscale}x#{vscale}, height error #{expected_height - vscale*f[2]}, width error #{expected_text_width - text[:text].length*f[1]*hscale}}(#{(expected_text_width-f[1]*hscale*text[:text].length).to_f/text[:text].length} per char)") error = text[:text].length*f[1]*hscale - expected_text_width if error > 0 # puts "Moving text left because of error(#{error} dots, #{text[:rotate].to_s})" if (text[:rotate] == :rotate0 or text[:rotate] == nil) and text[:realpos][:position][0] > error.to_i/2 text[:realpos][:position][0] -= error.to_i/2 elsif text[:rotate] == :rotate90 and text[:realpos][:position][1] > error.to_i/2 text[:realpos][:position][1] -= error.to_i/2 end # TODO: elsifs end return [ fid, vscale, hscale ] else diff, fid, vscale = (1..9).map { |i| fonts[0..startfrom].map { |fid, w, h| [ (h*i-expected_height).abs, fid, i ] }.min }.min diff, hscale = (1..6).map { |i| [ (fonts[fid-1][1]*text[:text].length*i - expected_text_width).abs, i ] }.min if text[:text].match(/^\d+$/) current_width = fonts[fid-1][1]*text[:text].length #T text[:realpos][:position][1] -= vscale*fonts[fid-1][2] STDERR.puts([ 'selected ', fid, vscale, ' for ', expected_height, text[:text]].inspect) STDERR.puts([ 'widths expected', expected_text_width, 'actual', current_width, 'hscale', hscale ].inspect) vscale = hscale = [ vscale, hscale ].max [ fid, vscale, hscale ] elsif hscale * fonts[fid-1][1]*text[:text].length > 1.35 * expected_text_width return select_best_font_for_text(text, fid-2) else current_width = fonts[fid-1][1]*text[:text].length #T text[:realpos][:position][1] -= vscale*fonts[fid-1][2] STDERR.puts([ 'selected ', fid, vscale, ' for ', expected_height, text[:text]].inspect) error = current_width - expected_text_width if error > 0 if text[:rotate] == :rotate0 or text[:rotate] == nil and text[:realpos][:position][0] > error.to_i/2 text[:realpos][:position][0] -= error.to_i/2 elsif text[:rotate] == :rotate90 text[:realpos][:position][1] -= error.to_i/2 and text[:realpos][:position][1] > error.to_i/2 end # TODO: elsifs end STDERR.puts([ 'widths expected', expected_text_width, 'actual', current_width, 'hscale', hscale ].inspect) [ fid, vscale, hscale ] end end end def fix_text_object_position(text, fid, vscale, hscale, boxwidth, boxheight, lastchance = false) fonts = [ [ 1, 10, 12 ], # font id, width, height, in dots [ 2, 12, 16 ], [ 3, 14, 20 ], [ 4, 16, 24 ], [ 5, 36, 48 ] ] font_width = fonts[fid-1][1] font_height = fonts[fid-1][2] l = text[:text].length # we do not want text objects to overflow # so move them left if they overflow # p [ :fix, text[:realpos][:position][0], font_width*l*hscale, text[:realpos][:position][0] + font_width*l*hscale, boxwidth ] if (text[:rotate] == :rotate0 or text[:rotate] == nil) and text[:realpos][:position][0] + font_width*l*hscale > boxwidth error = text[:realpos][:position][0] + font_width*l - boxwidth if text[:realpos][:position][0] - error <= 0 raise RuntimeError, "I am sorry, this text if too long to fit on label: #{text[:text].inspect}" if lastchance really_fix_text_object(text) return fix_text_object_position(text, fid, vscale, hscale, boxwidth, boxheight, true) else STDERR.puts("Fixing text box, #{error} dots overflow") text[:realpos][:position][0] -= (error+20) # 20 dots for margin end end # TODO elsifs for other rotates end def really_fix_text_object(text) STDERR.puts("Text too long, trying to fix by removing spaces") text[:text] = text[:text].gsub(/([.,]) /,'\1') end def generate_epl rotates = { nil => 0, :rotate0 => 0, :rotate90 => 1, :rotate180 => 2, :rotate270 => 3 } dpi = 203 # dots/inch labelheight = 150.0 # mm labelwidth = 100.0 # mm inch = 25.4 # mm labelheight_dots = labelheight/inch*dpi labelwidth_dots = labelwidth/inch*dpi scale_to(labelwidth_dots, labelheight_dots) header = [] header << "N" # new label header << "S3" # speed 3 header << "D11" # density 11 (0-15) header << "q#{labelwidth_dots.to_i}" # width in dots header << "Q#{labelheight_dots.to_i},26" # label height in dots header << "I8,B,001" # 8 bit character encoding (8), windows 1250 (B), 001 (country code) footer = [] footer << "P1,1\n" (header + # @texts.map { |text| # pos = text[:realpos] # font, font_vscale, font_hscale = select_best_font_for_text(text) # fix_text_object_position(text, font, font_vscale, font_hscale, labelwidth_dots, labelheight_dots) #font_hscale = font_vscale # 1-6, 8 # font_vscale = 1 # 1-9 # escaped_text = text[:text].gsub(/\\/,'\\\\').gsub(/([^\\])"/,'\1\\"').encode('cp1250') # sprintf 'A%d,%d,%d,%d,%d,%d,N,"%s"', pos[:position][0], pos[:position][1], rotates[text[:rotate]], font, font_hscale, font_vscale, escaped_text # } + @rectangles.map { |r| rp = r[:realpos] sprintf 'LO%d,%d,%d,%d', rp[:start][0], rp[:start][1], rp[:width], rp[:height] } + @lines.map { |line| rp = line[:realpos] sprintf 'LO%d,%d,%d,%d', rp[:start][0], rp[:start][1], rp[:width], rp[:height] } + footer).join("\n") end end #receiver = PDF::Reader::RegisterReceiver.new receiver = MyReceiver.new PDF::Reader.open(ARGV[0]) do |reader| reader.pages.each do |page| page.walk(receiver) puts(receiver.generate_epl) PP.pp(receiver.calculate_area, STDERR) PP.pp(receiver.stats, STDERR) end end
bsd-2-clause
npat-efault/gohacks
cirq/cirq_test.go
5014
package cirq import ( "strings" "testing" ) type pushFn func(interface{}) bool type popFn func() (interface{}, bool) func testLIFO(t *testing.T, q *CQ, maxSz int, push pushFn, pop popFn) { if !q.Empty() || q.Full() || q.Len() != 0 || q.MaxCap() != maxSz { t.Fatalf("Initially: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } for i := 0; i < maxSz; i++ { ok := push(i) if !ok { t.Fatalf("Cannot push %d", i) } if q.Empty() || q.Len() != i+1 || q.MaxCap() != maxSz { t.Fatalf("After %d Pushes: E=%v, F=%v, L=%d, C=%d", i+1, q.Empty(), q.Full(), q.Len(), q.MaxCap()) } if i < maxSz-1 && q.Full() { t.Fatal("Bad queue-full inication") } } if !q.Full() { t.Fatal("Bad queue-not-full inication") } for i := 0; i < maxSz; i++ { ei, ok := pop() if !ok { t.Fatalf("Cannot pop %d", maxSz-i-1) } if q.Full() || q.Len() != maxSz-i-1 || q.MaxCap() != maxSz { t.Fatalf("Bad queue after %d Pops", i) } if i < maxSz-1 && q.Empty() { t.Fatal("Bad queue-empty inication") } if ei.(int) != maxSz-i-1 { t.Fatalf("Bad element %d: %d", i, ei.(int)) } } if !q.Empty() || q.Full() || q.Len() != 0 || q.MaxCap() != maxSz { t.Fatalf("Finally: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } } func testFIFO(t *testing.T, q *CQ, maxSz int, push pushFn, pop popFn) { if q.Full() || !q.Empty() || q.Len() != 0 || q.MaxCap() != maxSz { t.Fatalf("Initially: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } for i := 0; i < maxSz; i++ { ok := push(i) if !ok { t.Fatalf("Cannot push %d", i) } } for i := 0; i < maxSz*5; i++ { ei, ok := pop() if !ok { t.Fatalf("Cannot pop %d", i) } if ei.(int) != i%maxSz { t.Fatalf("Bad element: %d != %d", ei.(int), i%maxSz) } ok = push(i % maxSz) if !ok { t.Fatalf("Cannot push %d", i) } if !q.Full() || q.Empty() || q.Len() != maxSz || q.MaxCap() != maxSz { t.Fatalf("After %d ops: E=%v, F=%v, L=%d, C=%d", i+1, q.Empty(), q.Full(), q.Len(), q.MaxCap()) } } for i := 0; i < maxSz; i++ { ei, ok := pop() if !ok { t.Fatalf("Cannot pop %d", i) } if ei.(int) != i { t.Fatalf("Bad element: %d != %d", ei.(int), i) } } if q.Full() || !q.Empty() || q.Len() != 0 || q.MaxCap() != maxSz { t.Fatalf("Finally: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } } func testResize(t *testing.T, q *CQ, maxSz int) { if q.Full() || !q.Empty() || q.Len() != 0 || q.MaxCap() != maxSz { t.Fatalf("Initially: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } q.Compact(1) for i := 1; i <= maxSz; i <<= 1 { for j := i >> 1; j < i; j++ { ok := q.PushBack(j) if !ok { t.Fatalf("Cannot push %d", j) } if q.Cap() != i { t.Fatalf("Queue cap %d != %d", q.Cap(), i) } } } for i := maxSz; i > 1; i >>= 1 { for j := i; j > i>>1; j-- { _, ok := q.PopFront() if !ok { t.Fatalf("Cannot pop %d", j) } } q.Compact(1) if q.Cap() != i>>1 { t.Fatalf("Queue cap %d != %d", q.Cap(), i>>1) } } if q.Full() || q.Empty() || q.Len() != 1 || q.MaxCap() != maxSz { t.Fatalf("Finally: E=%v, F=%v, L=%d, C=%d", q.Empty(), q.Full(), q.Len(), q.MaxCap()) } } func TestLIFO(t *testing.T) { maxSz := 2048 q := New(1, maxSz) testLIFO(t, q, maxSz, q.PushFront, q.PopFront) testLIFO(t, q, maxSz, q.PushBack, q.PopBack) } func TestFIFO(t *testing.T) { maxSz := 2048 q := New(1, maxSz) testFIFO(t, q, maxSz, q.PushBack, q.PopFront) testFIFO(t, q, maxSz, q.PushFront, q.PopBack) } func TestResize(t *testing.T) { maxSz := 2048 q := New(1, maxSz) testResize(t, q, maxSz) } func TestPeek(t *testing.T) { maxSz := 2048 q := New(1, maxSz) for i := 0; i < maxSz; i++ { q.PushBack(i) } for i := 0; i < maxSz; i++ { e, ok := q.PeekFront() if !ok { t.Fatalf("Failed to PeekFront %d", i) } if e.(int) != i { t.Fatalf("PeekFront %d != %d", e.(int), i) } q.PopFront() } for i := 0; i < maxSz; i++ { q.PushFront(i) } for i := 0; i < maxSz; i++ { e, ok := q.PeekBack() if !ok { t.Fatalf("Failed to PeekBack %d", i) } if e.(int) != i { t.Fatalf("PeekBack %d != %d", e.(int), i) } q.PopBack() } } func TestMustPeek(t *testing.T) { maxSz := 2048 q := New(1, maxSz) for i := 0; i < maxSz; i++ { q.PushBack(i) } for i := 0; i < maxSz; i++ { e := q.MustPeekFront() if e.(int) != i { t.Fatalf("PeekFront %d != %d", e.(int), i) } q.PopFront() } for i := 0; i < maxSz; i++ { q.PushFront(i) } for i := 0; i < maxSz; i++ { e := q.MustPeekBack() if e.(int) != i { t.Fatalf("PeekBack %d != %d", e.(int), i) } q.PopBack() } func() { defer func() { x := recover() if x == nil { t.Fatal("No panic when peeking empty Q") } if !strings.HasPrefix(x.(string), "MustPeek") { panic(x) } }() // q is empty, so these should panic. The panic will // be caught by the recover, above. q.MustPeekBack() q.MustPeekFront() }() }
bsd-2-clause
bborbe/assert
hamcrest_util_test.go
1884
package assert import ( "testing" ) func TestBuildError(t *testing.T) { { err := buildError("expected type '%s' but got '%s'", "", "foo", "bar") if err == nil { t.Fatal("err is nil") } if err.Error() != "expected type 'foo' but got 'bar'" { t.Fatal("errormessage is incorrect") } } { err := buildError("expected type '%s' but got '%s'", "message", "foo", "bar") if err == nil { t.Fatal("err is nil") } if err.Error() != "message, expected type 'foo' but got 'bar'" { t.Fatal("errormessage is incorrect") } } } func TestIsByteArray(t *testing.T) { { err := AssertThat(isByteArray(nil), Is(false)) if err != nil { t.Fatal(err) } } { err := AssertThat(isByteArray([]string{"a", "b"}), Is(false)) if err != nil { t.Fatal(err) } } { err := AssertThat(isByteArray([]byte("hello")), Is(true)) if err != nil { t.Fatal(err) } } } func TestLessTypeNotEqualAlwaysReturnFalse(t *testing.T) { if less(int32(1), int64(2)) { t.Fatal("invalid") } } func TestLessNotSupportTypePanics(t *testing.T) { defer func() { if r := recover(); r != nil { } else { t.Fatal("panic should be called") } }() less("1", "1") } func TestLess(t *testing.T) { if less(int(1), int(1)) { t.Fatal("invalid") } if less(int8(1), int8(1)) { t.Fatal("invalid") } if less(int16(1), int16(1)) { t.Fatal("invalid") } if less(int32(1), int32(1)) { t.Fatal("invalid") } if less(int64(1), int64(1)) { t.Fatal("invalid") } if less(uint(1), uint(1)) { t.Fatal("invalid") } if less(uint8(1), uint8(1)) { t.Fatal("invalid") } if less(uint16(1), uint16(1)) { t.Fatal("invalid") } if less(uint32(1), uint32(1)) { t.Fatal("invalid") } if less(uint64(1), uint64(1)) { t.Fatal("invalid") } if less(float32(1), float32(1)) { t.Fatal("invalid") } if less(float64(1), float64(1)) { t.Fatal("invalid") } }
bsd-2-clause
cameronjacobson/SimpleSQS
examples/deletequeue.php
272
<?php require_once(dirname(__DIR__).'/vendor/autoload.php'); use SimpleSQS\SimpleSQS; $sqs = new SimpleSQS(array( 'profile'=>'default', 'region'=>'us-west-2', 'error'=>function($result){ var_dump($result->__toString()); } )); $sqs->deleteQueue('mysamplequeue');
bsd-2-clause
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/prototype/filter/15.4.4.20-1-10.js
509
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.filter es5id: 15.4.4.20-1-10 description: Array.prototype.filter applied to the Math object ---*/ function callbackfn(val, idx, obj) { return '[object Math]' === Object.prototype.toString.call(obj); } Math.length = 1; Math[0] = 1; var newArr = Array.prototype.filter.call(Math, callbackfn); assert.sameValue(newArr[0], 1, 'newArr[0]');
bsd-2-clause
mapfish/mapfish-print
core/src/test/java/org/mapfish/print/processor/map/CreateMapProcessorCenterGeoJsonZoomToExtentFlexibleScaleTest.java
2415
package org.mapfish.print.processor.map; import org.junit.Test; import org.mapfish.print.AbstractMapfishSpringTest; import org.mapfish.print.TestHttpClientFactory; import org.mapfish.print.config.Configuration; import org.mapfish.print.config.ConfigurationFactory; import org.mapfish.print.config.Template; import org.mapfish.print.output.Values; import org.mapfish.print.test.util.ImageSimilarity; import org.mapfish.print.wrapper.json.PJsonObject; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import static org.junit.Assert.assertEquals; /** * Basic test of the Map processor. * * Created by Jesse on 3/26/14. */ public class CreateMapProcessorCenterGeoJsonZoomToExtentFlexibleScaleTest extends AbstractMapfishSpringTest { private static final String BASE_DIR = "center_geojson_zoomToExtent_flexiblescale/"; @Autowired private ConfigurationFactory configurationFactory; @Autowired private TestHttpClientFactory httpRequestFactory; @Autowired private ForkJoinPool forkJoinPool; public static PJsonObject loadJsonRequestData() throws IOException { return parseJSONObjectFromFile(CreateMapProcessorCenterGeoJsonZoomToExtentFlexibleScaleTest.class, BASE_DIR + "requestData.json"); } @Test public void testExecute() throws Exception { final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml")); final Template template = config.getTemplate("main"); PJsonObject requestData = loadJsonRequestData(); Values values = new Values("test", requestData, template, getTaskDirectory(), this.httpRequestFactory, new File(".")); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit( template.getProcessorGraph().createTask(values)); taskFuture.get(); @SuppressWarnings("unchecked") List<URI> layerGraphics = (List<URI>) values.getObject("layerGraphics", List.class); assertEquals(1, layerGraphics.size()); new ImageSimilarity(getFile(BASE_DIR + "expectedSimpleImage.png")) .assertSimilarity(layerGraphics.get(0), 500, 400, 1); } }
bsd-2-clause