code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
import Vue from 'vue'; import VueForm from 'vue-form'; Vue.use(VueForm, { validators: { 'step': function(value, stepValue) { return stepValue === `any` || Number(value) % Number(stepValue) === 0; }, 'data-exclusive-minimum': function(value, exclusiveMinimum) { return Number(value) > Number(exclusiveMinimum); }, 'data-exclusive-maximum': function(value, exclusiveMaximum) { return Number(value) < Number(exclusiveMaximum); }, 'complete-range': function(range) { return range === null || (range[0] !== null && range[1] !== null); }, 'valid-range': function(range) { if (range === null) { // allowed range return true; } if (range[0] === null || range[1] === null) { // let complete-range validator handle this return true; } if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { // let number validator handle this return true; } return range[0] <= range[1]; }, 'categories-not-empty': function(categories) { return categories.length > 0; }, 'complete-dimensions': function(dimensions) { return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null); }, 'start-with-uppercase-or-number': function(value) { return /^[\dA-Z]/.test(value); }, 'no-mode-name': function(value) { return !/\bmode\b/i.test(value); }, 'no-fine-channel-name': function(value) { if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) { return false; } return !/\bLSB\b|\bMSB\b/.test(value); }, 'entity-complete': function(value, attributeValue, vnode) { const component = vnode.componentInstance; if (component.hasNumber) { return component.selectedNumber !== `` && component.selectedNumber !== null; } return true; }, 'entities-have-same-units': function(value, attributeValue, vnode) { return vnode.componentInstance.hasSameUnit; }, 'valid-color-hex-list': function(value) { return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value); }, 'max-file-size': function(file, attributeValue) { if (typeof file === `object`) { let maxSize = Number.parseInt(attributeValue, 10); if (attributeValue.includes(`M`)) { maxSize *= 1000 * 1000; } else if (attributeValue.includes(`k`)) { maxSize *= 1000; } return file.size <= maxSize; } return true; }, }, });
FloEdelmann/open-fixture-library
ui/plugins/vue-form.js
JavaScript
mit
2,583
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Post extends Application { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->data['pagetitle'] = 'News title - Zerotype Website Template'; $this->data['pagebody'] = 'post'; $this->render(); } } /* End of file welcome.php */ /* Location: ./application/controllers/welcome.php */
ericytsang/comp4711.lab2.partB.local
application/controllers/Post.php
PHP
mit
939
--- layout: post title: How To Order Bitcoin Debit Card With SpectroCoin? description: How To Order Bitcoin Debit Card With SpectroCoin? author: Melvin Draupnir authorurl: /melvin-draupnir/ published: true --- <p><a href="/spectrocoin/">SpectroCoin</a> now offers Bitcoin prepaid cards which could be a virtual one or a plastic one. You can.This card can be immediately funded All you need to do is click “Order card” on your <a href="http://geni.us/spectrocoin">SpectroCoin account</a>.</p> <center><iframe width="700" height="394" src="https://www.youtube.com/embed/iuweq3hHesk" frameborder="0" allowfullscreen></iframe></center> <h2>TRANSCRIPT</h2>
sunnankar/wucorg
_posts/2016-08-27-how-to-order-bitcoin-debit-card-with-spectrocoin.md
Markdown
mit
660
var resources = require('jest'), util = require('util'), models = require('../../models'), async = require('async'), common = require('./../common'), calc_thresh = require('../../tools/calc_thresh.js'), GradeActionSuggestion = require('./grade_action_suggestion_resource.js'), ActionSuggestion = require('./ActionSuggestionResource.js'), og_action = require('../../og/og.js').doAction; //Authorization var Authoriztion = function() {}; util.inherits(Authoriztion,resources.Authorization); //Authorization.prototype.edit_object = function(req,object,callback){ // //check if user already grade this action // var flag = false; // // models.GradeAction.find({"action_id": object.action_id}, function(err, objects){ // if (err){ // callback(err, null); // }else{ // for (var i = 0; i < objects.length; i++){ // if(req.session.user_id == objects[i].user_id){ // flag = true; // break; // } // } // if (flag){ // callback({message:"user already grade this action",code:401}, null); // }else{ // callback(null, object); // } // } // }) //}; var GradeActionResource = module.exports = common.GamificationMongooseResource.extend({ init:function(){ this._super(models.GradeAction,'grade_action', null); // GradeResource.super_.call(this,models.Grade); this.allowed_methods = ["get", "put", "post"]; this.authorization = new Authoriztion(); this.authentication = new common.SessionAuthentication(); this.filtering = {action_id: { exact:null, in:null }}; }, create_obj:function(req,fields,callback) { var self = this; var g_grade_obj; var new_grade = null; var counter = 0; var threshold; var admin_threshold; var action_thresh; var action_obj; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var base = self._super; fields.proxy_power = proxy_power; fields.user_id = req.user._id; async.waterfall([ function(cbk){ base.call(self, req, fields, cbk); }, //find actions function(grade_obj, cbk){ g_grade_obj = grade_obj; models.Action.findById(grade_obj.action_id, cbk); }, // 2) calculate action grade + set notifications for all users of proxy function(action, cbk){ action_obj = action; async.parallel([ //2.1 set notifications for all users of proxy function(cbk1){ cbk1(null, null); }, // 2.2 calculate action grade function(cbk1){ //cant grade your own action action_thresh = Number(action.admin_threshold_for_accepting_change_suggestions) || action.threshold_for_accepting_change_suggestions admin_threshold = action.admin_threshold_for_accepting_change_suggestions; calculateActionGrade(g_grade_obj.action_id, function(err, _new_grade, evaluate_counter, _threshold){ new_grade = _new_grade; counter = evaluate_counter; threshold = _threshold cbk1(err, threshold); }); }, //2.3 add user to be part of the action function(cbk1){ if (! _.any(action.users, function(user){ return user.user_id + "" == req.user.id})){ var new_user = {user_id: req.user._id, join_date: Date.now()}; models.Action.update({_id: action._id}, {$addToSet:{users: new_user}}, function(err, num){cbk1(err, num)}); }else{ cbk1(null, null); } } ],function(err, args){ cbk(err, args[1]); }) }, // 3) find suggestion object //calculate all change suggestion all over again and check if they approved function(threshold, cbk){ models.ActionSuggestion.find({action_id: g_grade_obj.action_id}, {"_id":1}, function(err, results) { cbk(err, results); }); }, // 4) calculate suggestion grades function(suggestions, cbk){ var real_threshold async.forEach(suggestions, function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, g_grade_obj.action_id, null, null, action_thresh, null, null,function(err, obj){ //check if suggestion is over the threshold real_threshold = Number(suggestion.admin_threshold_for_accepting_the_suggestion) || suggestion.threshold_for_accepting_the_suggestion; if(suggestion.agrees && suggestion.agrees.length > real_threshold){ //approveSuggestion.exec() ActionSuggestion.approveSuggestion(suggestion._id, function(err, obj1){ itr_cbk(err, obj1); }) }else itr_cbk(err, obj); });} , function(err){ cbk(err); }); }, // 5) publish to facebook function (cbk) { og_action({ action: 'rank', object_name:'action', object_url : '/actions/' + action_obj.id, fid : req.user.facebook_id, access_token:req.user.access_token, user:req.user }); cbk(); }, // update actions done by user function(cbk){ models.User.update({_id:user._id},{$set: {"actions_done_by_user.grade_object": true}}, function(err){ cbk(err); }); } ], // Final) set gamification details, return object function(err, args){ req.gamification_type = "grade_action"; req.token_price = common.getGamificationTokenPrice('grade_action') > -1 ? common.getGamificationTokenPrice('grade_action') : 0; callback(err, {new_grade: new_grade, evaluate_counter: counter, grade_id: g_grade_obj._id || 0}); }) }, update_obj: function(req, object, callback){ var g_grade; var self = this; var suggestions = []; var action_thresh; var proxy_power = req.user.num_of_given_mandates ? 1 + req.user.num_of_given_mandates * 1/9 : 1; var iterator = function(suggestion, itr_cbk){ GradeActionSuggestion.calculateActionSuggestionGrade(suggestion._id, object.action_id, null, null, action_thresh, null, null,function(err, sugg_new_grade, sugg_total_counter){ if(!err){ suggestions.push({ _id: suggestion._id, grade: sugg_new_grade, evaluators_counter: sugg_total_counter }) } itr_cbk(err, 0); }); } object.proxy_power = proxy_power; self._super(req, object, function(err, grade_object){ if(err){ callback(err, null); }else{ var new_grade, evaluate_counter; async.waterfall([ function(cbk){ g_grade = grade_object; calculateActionGrade(object.action_id, function(err, _new_grade, _evaluate_counter){ new_grade = _new_grade; evaluate_counter = _evaluate_counter; cbk(err, 0); }); }, //get action threshold so i can update every suggestion threshold function(obj, cbk){ models.Action.findById(object.action_id, function(err, result){ cbk(err, result) }); }, function(action_obj,cbk){ async.parallel([ //set notifications for all users of proxy function(cbk1){ //Todo - set notifications // models.User.find({"proxy.user_id": req.user._id}, function(err, slaves_users){ // async.forEach(slaves_users, function(slave, itr_cbk){ // notifications.create_user_proxy_vote_or_grade_notification("proxy_graded_discussion", // discussion_obj._id, slave._id, req.user._id, // null, null, g_grade.evaluation_grade, // function(err){ // itr_cbk(err); // }) // }, function(err){ // cbk1(err); // }) // }) cbk1(null); }, //calculate all change suggestion all over again function(cbk1){ action_thresh = Number(action_obj.admin_threshold_for_accepting_change_suggestions) || action_obj.threshold_for_accepting_change_suggestions; models.ActionSuggestion.find({action_id: grade_object.action_id}, {"_id":1}, function(err, results) { cbk1(err, results); }); } ], function(err, args){ cbk(err, args[1]); } ) }, function(suggestions, cbk){ async.forEach(suggestions, iterator, cbk); } ], function(err){ callback(err, {new_grade: new_grade, evaluate_counter: evaluate_counter, suggestions: suggestions,grade_id: g_grade._id || 0}) }) } }); } }); function calculateActionGrade(action_id, callback){ var count; var grade_sum; var new_grade; var threshold; async.waterfall([ function(cbk){ models.GradeAction.find({action_id: action_id}, {"evaluation_grade":1, "proxy_power":1}, cbk); }, function(grades, cbk){ count = grades.length; if(count){ //calculate grade_sum with take proxy power in consideration grade_sum = _.reduce(grades, function(memo, grade){return memo + Number(grade.evaluation_grade * (grade.proxy_power || 1)); }, 0); //calculate count with take proxy power in consideration count = _.reduce(grades, function(memo, grade){return memo + Number(grade.proxy_power || 1)}, 0); new_grade = grade_sum / count; //calculate threshhold here threshold = calc_thresh.calculating_thresh(count, new_grade) || 50; models.Action.update({_id: action_id}, {$set: {grade: new_grade, evaluate_counter: count, threshold_for_accepting_change_suggestions: threshold}}, cbk); }else{ cbk({message: "you have to grade before changing the grade" , code: 401}); } } ],function(err, args){ callback(err, new_grade, count, threshold); }) }
saarsta/sheatufim
api/actions/GradeActionResource.js
JavaScript
mit
12,565
module Sample VERSION = '1.2' end
pavolzbell/bump
spec/fixtures/inputs/gem-2-version-numbers.rb
Ruby
mit
36
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace CameraModifications { public class LookButton : MonoBehaviour { public bool isHead; public H_Scene h_scene; public H_EditsUIControl controls; private GameObject buttonPrefab; public KocchiMitePlugin watchDog; private Toggle m_toggle; private UI_ShowCanvasGroup group; private int currentValue = -1; private Dictionary<LookAtRotator.TYPE, Toggle> toggles; private bool initialShutup = true; private void Start() { // Make buttons m_toggle = GetComponent<Toggle>(); m_toggle.onValueChanged.AddListener(HandleClick); controls.GetComponent<ToggleGroup>().RegisterToggle(m_toggle); try { MakeGroup(); } catch (Exception e) { Console.WriteLine(e); } } public int CurrentMode { get { return isHead ? watchDog.currentHeadType : watchDog.currentType; } } private void Update() { if (CurrentMode != currentValue) { currentValue = CurrentMode; toggles[(LookAtRotator.TYPE)currentValue].isOn = true; } initialShutup = false; } private void HandleClick(bool isOn) { try { if (isOn) { m_toggle.image.color = Color.blue; // Show h_scene.GC.SystemSE.Play_Click(); } else { m_toggle.image.color = Color.white; // Hide h_scene.GC.SystemSE.Play_Cancel(); } group.Show(isOn); Console.WriteLine(isOn); } catch (Exception e) { Console.WriteLine(e); } } private void MakeGroup() { var container = controls.transform.FindChild("EditStep2"); Console.WriteLine("C {0}", container); var exampleGroup = container.GetChild(0); Console.WriteLine("E {0}", exampleGroup); buttonPrefab = GameObject.Instantiate(container.GetComponentInChildren<Toggle>().gameObject) as GameObject; buttonPrefab.SetActive(false); group = new GameObject().AddComponent<CanvasGroup>().gameObject.AddComponent<UI_ShowCanvasGroup>(); group.gameObject.layer = LayerMask.NameToLayer("UI"); group.gameObject.AddComponent<ToggleGroup>().allowSwitchOff = false; group.gameObject.AddComponent<RectTransform>(exampleGroup.GetComponent<RectTransform>()); group.gameObject.AddComponent<VerticalLayoutGroup>(exampleGroup.GetComponent<VerticalLayoutGroup>()).childForceExpandHeight = false; group.transform.SetParent(container, false); //group.GetComponent<RectTransform>().GetCopyOf(exampleGroup.GetComponent<RectTransform>()); // Make buttons toggles = new Dictionary<LookAtRotator.TYPE, Toggle>() { { LookAtRotator.TYPE.NO, MakeButton(watchDog.useEnglish ? "None" : "無設定", LookAtRotator.TYPE.NO) }, { LookAtRotator.TYPE.AWAY, MakeButton(watchDog.useEnglish ? "Away" : "あっち向け", LookAtRotator.TYPE.AWAY)}, { LookAtRotator.TYPE.FORWARD, MakeButton(watchDog.useEnglish ? "Forward" : "正面向け", LookAtRotator.TYPE.FORWARD)}, { LookAtRotator.TYPE.TARGET, MakeButton(watchDog.useEnglish ? "Camera" : "こっち向け", LookAtRotator.TYPE.TARGET)} }; foreach (var button in toggles.Values) { button.transform.SetParent(group.transform, false); } //group.gameObject.AddComponent<Image>().color = Color.red; } private Toggle MakeButton(string text, LookAtRotator.TYPE type) { var buttonObj = Instantiate(buttonPrefab) as GameObject; buttonObj.SetActive(true); GameObject.DestroyImmediate(buttonObj.GetComponent<global::UI_ShowCanvasGroup>()); buttonObj.AddComponent<UI_ShowCanvasGroup>(); var buttonEl = buttonObj.GetComponent<Toggle>(); Console.WriteLine(buttonEl.group); buttonEl.onValueChanged = new Toggle.ToggleEvent(); buttonEl.group = group.GetComponent<ToggleGroup>(); // set text Console.WriteLine(buttonPrefab.name); buttonEl.GetComponentInChildren<Text>().text = text; //buttonEl.GetComponentInChildren<Text>().resizeTextForBestFit = true; //buttonEl.GetComponentInChildren<Text>().resizeTextMinSize = 1; buttonEl.onValueChanged.AddListener((state) => { if (state) { if(!initialShutup) h_scene.GC.SystemSE.Play_Click(); if (isHead) { watchDog.currentHeadType = (int)type; if(!initialShutup) watchDog.oldHeadLook.IsChecked = false; } else { watchDog.currentType = (int)type; if (!initialShutup) watchDog.oldEyeLook.IsChecked = false; } currentValue = (int)type; buttonEl.image.color = Color.blue; } else { buttonEl.image.color = Color.white; } }); return buttonEl; } } }
Eusth/Illusion-Plugins
CameraModifications/LookButton.cs
C#
mit
6,055
/** * This Control enables to render a Scene with a Screen Space Ambient Occlusion (SSAO) effect. * * @namespace GIScene * @class Control.SSAO * @constructor * @extends GIScene.Control */ GIScene.Control.SSAO = function() { //inherit GIScene.Control.call(this); var scenePass; var ssaoEffect; var fxaaEffect; var depthTarget; var depthShader; var depthUniforms; var depthMaterial; var depthCam; var activeCam; var updateDepthCam = function() { // if(depthCam !== undefined && depthCam.parent !== undefined){ // this.scene.camera.remove(depthCam); // } //depthCam activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) : this.scene.camera; depthCam = activeCam.clone(); this.scene.camera.add(depthCam); // depthCam = new THREE.PerspectiveCamera(); // //POSITION // depthCam.fov = activeCam.fov; // depthCam.aspect = activeCam.aspect; depthCam.near = 0.1; depthCam.far = 1000; depthCam.updateProjectionMatrix(); //console.log(depthCam); //updateSsaoUniforms();//mca }.bind(this); var updateSsaoUniforms = function() { ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = depthCam.near; ssaoEffect.uniforms[ 'cameraFar' ].value = depthCam.far; }.bind(this); var onBeforeRender = function() { // activeCam = (this.scene.camera instanceof THREE.CombinedCamera)? // ( (this.scene.camera.inPerspectiveMode)? this.scene.camera.cameraP : this.scene.camera.cameraO ) // : // this.scene.camera; // activeCam = this.scene.camera.cameraP.clone(); // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // activeCam.near = 0.1; // activeCam.far = 1500; // activeCam.updateProjectionMatrix(); this.scene.renderer.clearTarget(depthTarget,true, true, false); //color, depth, stencil this.scene.renderer.render(this.scene.root, depthCam, depthTarget); // activeCam.near = this.scene.config.near; // activeCam.far = this.scene.config.far; // activeCam.updateProjectionMatrix(); this.scene.root.overrideMaterial = null; // // this.scene.root.overrideMaterial = null; }.bind(this); var onChangedProjection = function(event) { console.log("chPrj2",activeCam); updateDepthCam(); }; var onResize = function() { updateDepthCam(); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); updateSsaoUniforms(); fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); }.bind(this); this.activate_ = function() { if(!this.isActive){ scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; this.scene.addEventListener('beforeRender', onBeforeRender); // function(){ // // this.scene.root.overrideMaterial = depthMaterial;//new THREE.MeshDepthMaterial({blending: THREE.NoBlending}); // this.scene.camera.cameraP.near = 0.1; // this.scene.camera.cameraP.far = 1500; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.renderer.clearTarget(depthTarget,true, true, true); // this.scene.renderer.render(this.scene.root, this.scene.camera, depthTarget); // // this.scene.camera.cameraP.near = this.scene.config.near; // this.scene.camera.cameraP.far = this.scene.config.far; // this.scene.camera.cameraP.updateProjectionMatrix(); // this.scene.root.overrideMaterial = null; // // }.bind(this) // ); ssaoEffect.uniforms[ 'tDepth' ].value = depthTarget; ssaoEffect.uniforms[ 'size' ].value.x = this.scene.canvas.width; ssaoEffect.uniforms[ 'size' ].value.y = this.scene.canvas.height; ssaoEffect.uniforms[ 'cameraNear' ].value = this.scene.camera.near; ssaoEffect.uniforms[ 'cameraFar' ].value = this.scene.camera.far; ssaoEffect.uniforms[ 'onlyAO' ].value = 1; ssaoEffect.renderToScreen = true; this.scene.effectComposer.addPass(scenePass); this.scene.effectComposer.addPass(ssaoEffect); } //call super class method GIScene.Control.prototype.activate.call(this); }; this.activate = function() { if(!this.isActive){ //depth map depthTarget = new THREE.WebGLRenderTarget( this.scene.canvas.width, this.scene.canvas.height, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } ); depthShader = THREE.ShaderLib[ "depthRGBA" ]; depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); depthMaterial.blending = THREE.NoBlending; //depthCam updateDepthCam(); //define passes scenePass = new THREE.RenderPass( this.scene.root, this.scene.camera ); ssaoEffect = new THREE.ShaderPass( THREE.SSAOShader ); fxaaEffect = new THREE.ShaderPass( THREE.FXAAShader ); updateSsaoUniforms(); ssaoEffect.renderToScreen = true; fxaaEffect.uniforms[ 'resolution' ].value.set( 1 / this.scene.canvas.width, 1 / this.scene.canvas.height ); fxaaEffect.renderToScreen = false; //add beforeRender Event this.scene.addEventListener('beforeRender2', onBeforeRender); //be sure, there are no other passes active //add passes this.scene.effectComposer.passes = [scenePass, fxaaEffect, ssaoEffect]; // this.scene.effectComposer.addPass(scenePass); // this.scene.effectComposer.addPass(ssaoEffect); //add other events window.addEventListener('resize', onResize, false); this.scene.camera.addEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.activate.call(this); } }; this.deactivate = function() { if(this.isActive){ //remove passes this.scene.effectComposer.passes = []; //remove depthCam this.scene.camera.remove(depthCam); //remove Events this.scene.removeEventListener('beforeRender2', onBeforeRender); window.removeEventListener('resize', onResize, false); this.scene.camera.removeEventListener('changedProjection', onChangedProjection); //call super class method GIScene.Control.prototype.deactivate.call(this); } }; }; GIScene.Control.SSAO.prototype = Object.create(GIScene.Control.prototype);
GIScience/GIScene.js
lib/GIScene/Control/SSAO.js
JavaScript
mit
7,334
div.CodeMirror-wrapping { float:left; width:275px; height:303px; border-width:2px; border-style:solid; background:#fff; } #canvas { width:470px; height:303px; }
chrispiech/cs106a-winter-2017
karel/css/advanced.css
CSS
mit
170
package com.cnpc.framework.utils; import com.cnpc.framework.base.pojo.GenerateSetting; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.*; public class FreeMarkerUtil { /** * 获取模板路径 * * @param templateName * 模板名称(含后缀名) * @return * @throws IOException */ public static String getTemplatePath(String templateName) throws IOException { Resource res = FreeMarkerUtil.getResource(templateName); return res.getFile().getPath(); } /** * 获取模板资源 * * @param templateName * 模板名称(含后缀名) * @return Resource */ public static Resource getResource(String templateName) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource res = resolver.getResource("/template/" + templateName); return res; } /** * 获取模板 * * @param templateName * 模板名称(含后缀名) * @return Template * @throws IOException */ public static Template getTemplate(String templateName) throws IOException { Configuration cfg = new Configuration(); Template temp = null; File tmpRootFile = getResource(templateName).getFile().getParentFile(); if (tmpRootFile == null) { throw new RuntimeException("无法取得模板根路径!"); } try { cfg.setDefaultEncoding("utf-8"); cfg.setOutputEncoding("utf-8"); cfg.setDirectoryForTemplateLoading(tmpRootFile); /* cfg.setDirectoryForTemplateLoading(getResourceURL()); */ cfg.setObjectWrapper(new DefaultObjectWrapper()); temp = cfg.getTemplate(templateName); } catch (IOException e) { e.printStackTrace(); } return temp; } /** * 根据freemark模板生成文件 * * @param templateName * 模板名称(含后缀名) * @param filePath * 生成文件路径 * @param setting * 参数 */ public static void generateFile(String templateName, String filePath, GenerateSetting setting) throws TemplateException, IOException { Writer writer = null; Template template = getTemplate(templateName); // Windows/Linux // String dir = filePath.substring(0, filePath.lastIndexOf("\\")); String dir = filePath.substring(0, filePath.lastIndexOf("/")); File fdir = new File(dir); if (!fdir.exists()) { if (!fdir.mkdirs()) { System.out.println("创建目录" + fdir.getAbsolutePath() + "失败"); return; } } File file = new File(filePath); if(file.exists()) file.delete(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); template.setEncoding("utf-8"); template.process(setting, writer); writer.flush(); writer.close(); } }
XilongPei/Openparts
Openparts-framework/src/main/java/com/cnpc/framework/utils/FreeMarkerUtil.java
Java
mit
3,038
<?php /* @SRVDVServer/Registration/checkEmail.html.twig */ class __TwigTemplate_b7388a253fe83dce0c06be9794c45a140b6b7d51b0d7f4393b8bb6ea03bbb2f5 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("FOSUserBundle::layout.html.twig", "@SRVDVServer/Registration/checkEmail.html.twig", 1); $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 6 public function block_fos_user_content($context, array $blocks = array()) { // line 7 echo " <p>"; echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->trans("registration.check_email", array("%email%" => $this->getAttribute((isset($context["user"]) ? $context["user"] : null), "email", array())), "FOSUserBundle"), "html", null, true); echo "</p> "; } public function getTemplateName() { return "@SRVDVServer/Registration/checkEmail.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 7, 28 => 6, 11 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("", "@SRVDVServer/Registration/checkEmail.html.twig", "C:\\wamp64\\www\\serveurDeVoeuxOmar\\src\\SRVDV\\ServerBundle\\Resources\\views\\Registration\\checkEmail.html.twig"); } }
youcefboukersi/serveurdevoeux
app/cache/prod/twig/26/2661d52b18638f3c0557a97abe21ab4f663d0577907552ec42ba9fb1790acde1.php
PHP
mit
2,198
import * as b from "bobril"; import { IRouteWithNavDefinition } from "../../../../common/routing"; import { Anchor } from "../../../../common/Anchor"; import { Example } from "../../../../common/Example"; import { Col, Form, margin, Row } from "../../../../../index"; import { Code } from "../../../../common/Code"; import { Lead } from "../../../../common/Lead"; export const formControlsRoute: IRouteWithNavDefinition = { url: "form-controls", name: "form-controls", label: "Form controls", handler: () => <FormsDoc />, subs: [ { url: "example", name: "form-controls-example", label: "Example", subs: [], }, { url: "sizing", name: "form-controls-sizing", label: "Sizing", subs: [], }, { url: "readonly", name: "form-controls-readonly", label: "Readonly", subs: [], }, { url: "readonly-plain-text", name: "form-controls-readonly-plain-text", label: "Readonly plain text", subs: [], }, { url: "file-input", name: "form-controls-file-input", label: "File input", subs: [], }, { url: "color", name: "form-controls-color", label: "Color", subs: [], }, { url: "datalist", name: "form-controls-datalist", label: "Datalist", subs: [], }, ], }; export function FormsDoc(): b.IBobrilNode { return ( <> <Anchor name="form-controls"> <h1>Form controls</h1> </Anchor> <Lead> Give textual form controls like <code>{`<Form.Input>`}</code>s, <code>{`<Form.Select>`}</code>s, and{" "} <code>{`<Form.Textarea>`}</code>s an upgrade with custom styles, sizing, focus states, and more. </Lead> <Anchor name="form-controls-example"> <h2>Form controls</h2> </Anchor> <Example> <Form> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlInput1">Email address</Form.Label> <Form.Input type="email" id="exampleFormControlInput1" placeholder="[email protected]" /> </div> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlTextarea1">Example textarea</Form.Label> <Form.Textarea id="exampleFormControlTextarea1" rows="3" /> </div> </Form> </Example> <Code language="tsx">{` <Form> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlInput1">Email address</Form.Label> <Form.Input type="email" id="exampleFormControlInput1" placeholder="[email protected]" /> </div> <div style={margin("b", 3)}> <Form.Label for="exampleFormControlTextarea1">Example textarea</Form.Label> <Form.Textarea id="exampleFormControlTextarea1" rows="3" /> </div> </Form>`}</Code> <Anchor name="form-controls-sizing"> <h3>Sizing</h3> </Anchor> <p> Set <code>size</code> prop. </p> <Example> <Form.Input type="text" size="lg" placeholder="lg" /> <Form.Input type="text" placeholder="Default input" /> <Form.Input type="text" size="sm" placeholder="sm" /> </Example> <Code language="tsx">{`<Form.Input type="text" size="lg" placeholder="lg" /> <Form.Input type="text" placeholder="Default input" /> <Form.Input type="text" size="sm" placeholder="sm" />`}</Code> <Anchor name="form-controls-readonly"> <h3>Readonly</h3> </Anchor> <p> Add the <code>readonly</code> boolean prop on an input to prevent modification of the input’s value. Read-only inputs appear lighter (just like disabled inputs), but retain the standard cursor. </p> <Example> <Form.Input type="text" placeholder="Readonly input here..." readonly /> </Example> <Code language="tsx">{`<Form.Input type="text" placeholder="Readonly input here..." readonly />`}</Code> <Anchor name="form-controls-readonly-plain-text"> <h3>Readonly plain text</h3> </Anchor> <p> If you want to have <code>readonly</code> elements in your form styled as plain text, use the <code>plain-text</code> prop to remove the default form field styling and preserve the correct margin and padding. </p> <Example> <Form> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="staticEmail"> Email </Form.Label> <Col sm={10}> <Form.Input type="text" readonly plain-text id="staticEmail" value="[email protected]" /> </Col> </Row> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="inputPassword"> Password </Form.Label> <Col sm={10}> <Form.Input type="password" id="inputPassword" /> </Col> </Row> </Form> </Example> <Code language="tsx">{`<Form> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="staticEmail"> Email </Form.Label> <Col sm={10}> <Form.Input type="text" readonly plain-text id="staticEmail" value="[email protected]" /> </Col> </Row> <Row style={margin("b", 3)}> <Form.Label col sm={2} for="inputPassword"> Password </Form.Label> <Col sm={10}> <Form.Input type="password" id="inputPassword" /> </Col> </Row> </Form>`}</Code> <Anchor name="form-controls-file-input"> <h3>File input</h3> </Anchor> <Example> <div style={margin("b", 3)}> <Form.Label for="formFile">Default file input example</Form.Label> <Form.Input type="file" id="formFile" /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileMultiple">Multiple files input example</Form.Label> <Form.Input type="file" id="formFileMultiple" multiple /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileDisabled">Disabled file input example</Form.Label> <Form.Input type="file" id="formFileDisabled" disabled /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileSm">Small file input example</Form.Label> <Form.Input size="sm" id="formFileSm" type="file" /> </div> <div> <Form.Label for="formFileLg">Large file input example</Form.Label> <Form.Input size="lg" id="formFileLg" type="file" /> </div> </Example> <Code language="tsx">{`<div style={margin("b", 3)}> <Form.Label for="formFile">Default file input example</Form.Label> <Form.Input type="file" id="formFile" /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileMultiple">Multiple files input example</Form.Label> <Form.Input type="file" id="formFileMultiple" multiple /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileDisabled">Disabled file input example</Form.Label> <Form.Input type="file" id="formFileDisabled" disabled /> </div> <div style={margin("b", 3)}> <Form.Label for="formFileSm"> Small file input example </Form.Label> <Form.Input size="sm" id="formFileSm" type="file" /> </div> <div> <Form.Label for="formFileLg">Large file input example</Form.Label> <Form.Input size="lg" id="formFileLg" type="file" /> </div>`}</Code> <Anchor name="form-controls-color"> <h3>Color</h3> </Anchor> <Example> <Form.Label for="exampleColorInput">Color picker</Form.Label> <Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" /> </Example> <Code language="tsx">{`<Form.Label for="exampleColorInput">Color picker</Form.Label> <Form.Input type="color" id="exampleColorInput" value="#563d7c" title="Choose your color" />`}</Code> <Anchor name="form-controls-datalist"> <h3>Datalist</h3> </Anchor> <p> Datalists allow you to create a group of <code>{`<Form.Option>`}</code>s that can be accessed (and autocompleted) from within an <code>{`<Form.Input>`}</code>. These are similar to <code>{`<Form.Select>`}</code>s, but come with more menu styling limitations and differences. While most browsers and operating systems include some support for{" "} <code>{`<Form.Datalist>`}</code>s, their styling is inconsistent at best. </p> <Example> <Form.Label for="exampleDataList">Datalist example</Form.Label> <Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." /> <Form.Datalist id="datalistOptions"> <Form.Option value="San Francisco" /> <Form.Option value="New York" /> <Form.Option value="Seattle" /> <Form.Option value="Los Angeles" /> <Form.Option value="Chicago" /> </Form.Datalist> </Example> <Code language="tsx">{`<Form.Label for="exampleDataList">Datalist example</Form.Label> <Form.Input type="datalist" list="datalistOptions" id="exampleDataList" placeholder="Type to search..." /> <Form.Datalist id="datalistOptions"> <Form.Option value="San Francisco" /> <Form.Option value="New York" /> <Form.Option value="Seattle" /> <Form.Option value="Los Angeles" /> <Form.Option value="Chicago" /> </Form.Datalist>`}</Code> </> ); }
keeema/bobrilstrap
example/documentation/content/forms/parts/FormsControls.tsx
TypeScript
mit
10,921
package easyauth import ( "context" "crypto/rand" "encoding/base64" "fmt" "html/template" "log" "net/http" "strings" "time" "github.com/gorilla/mux" ) //Role is a number representing a permission level. //Specific roles will be defined by the host application. //It is intended to be a bitmask. //Each user will have a certain permission level associated, as can any endpoint or content. //If the user permissions and the content requirement have any common bits (user & content != 0), then access will be granted. type Role uint32 type User struct { Username string Access Role Method string Data interface{} } //AuthProvider is any source of user authentication. These core methods must be implemented by all providers. type AuthProvider interface { //Retreive a user from the current http request if present. GetUser(r *http.Request) (*User, error) } //FormProvider is a provider that accepts login info from an html form. type FormProvider interface { AuthProvider GetRequiredFields() []string HandlePost(http.ResponseWriter, *http.Request) } //HTTPProvider is a provider that provides an http handler form managing its own login endpoints, for example oauth. //Will receive all calls to /{providerName}/* type HTTPProvider interface { AuthProvider http.Handler } type Logoutable interface { //Logout allows the provider to delete any relevant cookies or session data in order to log the user out. //The provider should not otherwise write to the response, or redirect Logout(w http.ResponseWriter, r *http.Request) } type AuthManager interface { AddProvider(string, AuthProvider) LoginHandler() http.Handler Wrapper(required Role) func(http.Handler) http.Handler Wrap(next http.Handler, required Role) http.Handler WrapFunc(next http.HandlerFunc, required Role) http.Handler } type namedProvider struct { Name string Provider AuthProvider } type namedFormProvider struct { Name string Provider FormProvider } type namedHTTPProvider struct { Name string Provider HTTPProvider } type authManager struct { Providers []namedProvider FormProviders []namedFormProvider HTTPProviders []namedHTTPProvider names map[string]bool cookie *CookieManager loginTemplate *template.Template } func New(opts ...Option) (AuthManager, error) { var mgr = &authManager{ names: map[string]bool{}, cookie: &CookieManager{ duration: int(time.Hour * 24 * 30), }, } for _, opt := range opts { if err := opt(mgr); err != nil { return nil, err } } if mgr.loginTemplate == nil { mgr.loginTemplate = template.Must(template.New("login").Parse(loginTemplate)) } return mgr, nil } func (m *authManager) AddProvider(name string, p AuthProvider) { if _, ok := m.names[name]; ok { panic(fmt.Errorf("Auth provider %s registered multiple times", name)) } m.names[name] = true m.Providers = append(m.Providers, namedProvider{name, p}) if form, ok := p.(FormProvider); ok { m.FormProviders = append(m.FormProviders, namedFormProvider{name, form}) } if httpp, ok := p.(HTTPProvider); ok { m.HTTPProviders = append(m.HTTPProviders, namedHTTPProvider{name, httpp}) } } func (m *authManager) LoginHandler() http.Handler { mx := mux.NewRouter() mx.Path("/").Methods("GET").HandlerFunc(m.loginPage) mx.Path("/out").Methods("GET").HandlerFunc(m.logout) mx.Path("/deny").Methods("GET").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<html><body><h1>Access denied</h1>You do not have access to the requested content.")) }) for _, form := range m.FormProviders { mx.Path(fmt.Sprintf("/%s", form.Name)).Methods("POST").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m.postForm(w, r, form.Provider) }) } for _, httpp := range m.HTTPProviders { mx.PathPrefix(fmt.Sprintf("/%s/", httpp.Name)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m.delegateHTTP(w, r, httpp.Provider) }) } return mx } func (m *authManager) buildContext(w http.ResponseWriter, r *http.Request) *http.Request { ctx := context.WithValue(r.Context(), cookieContextKey, m.cookie) ctx = context.WithValue(ctx, redirectContextKey, func() { m.redirect(w, r) }) return r.WithContext(ctx) } //Wrapper returns a middleware constructor for the given auth level. This function can be used with middleware chains //or by itself to create new handlers in the future func (m *authManager) Wrapper(required Role) func(http.Handler) http.Handler { return func(h http.Handler) http.Handler { return m.Wrap(h, required) } } func (m *authManager) Wrap(next http.Handler, required Role) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { orig := r r = m.buildContext(w, r) var u *User var err error for _, p := range m.Providers { u, err = p.Provider.GetUser(r) if err != nil { log.Println(err) continue } if u != nil { r = orig //don't send intenral context to real handler r = r.WithContext(context.WithValue(r.Context(), userContextKey, u)) break } } if required == 0 { //no permission needed next.ServeHTTP(w, r) } else if u == nil { //logged out. redir to login if strings.Contains(r.Header.Get("Accept"), "html") { m.cookie.SetCookiePlain(w, redirCookirName, 10*60, r.URL.String()) http.Redirect(w, r, "/login/", http.StatusFound) //todo: configure this } else { http.Error(w, "Access Denied", http.StatusForbidden) } } else if u.Access&required == 0 { //denied for permissions if strings.Contains(r.Header.Get("Accept"), "html") { m.cookie.SetCookiePlain(w, redirCookirName, 10*60, r.URL.String()) http.Redirect(w, r, "/login/deny", http.StatusFound) } else { http.Error(w, "Access Denied", http.StatusForbidden) } } else { //has permission next.ServeHTTP(w, r) } }) } func (m *authManager) WrapFunc(next http.HandlerFunc, required Role) http.Handler { return m.Wrap(next, required) } const ( errMsgCookieName = "errMsg" redirCookirName = "redirTo" ) func (m *authManager) loginPage(w http.ResponseWriter, r *http.Request) { msg, err := m.cookie.ReadCookiePlain(r, errMsgCookieName) if err == nil { m.cookie.ClearCookie(w, errMsgCookieName) } var ctx = map[string]interface{}{ "Auth": m, "Message": msg, } if err := m.loginTemplate.Execute(w, ctx); err != nil { log.Printf("Error executing login template: %s", err) } } func (m *authManager) logout(w http.ResponseWriter, r *http.Request) { r = m.buildContext(w, r) for _, p := range m.Providers { if lo, ok := p.Provider.(Logoutable); ok { lo.Logout(w, r) } } http.Redirect(w, r, "/", 302) } type contextKeyType int const ( cookieContextKey contextKeyType = iota redirectContextKey userContextKey ) func (m *authManager) delegateHTTP(w http.ResponseWriter, r *http.Request, h HTTPProvider) { r = m.buildContext(w, r) h.ServeHTTP(w, r) } func (m *authManager) redirect(w http.ResponseWriter, r *http.Request) { path := "/" stored, err := m.cookie.ReadCookiePlain(r, redirCookirName) if err == nil { path = stored m.cookie.ClearCookie(w, redirCookirName) } http.Redirect(w, r, path, http.StatusFound) } func (m *authManager) postForm(w http.ResponseWriter, r *http.Request, p FormProvider) { defer func() { if rc := recover(); rc != nil { //set short-lived cookie with message and redirect to login page m.cookie.SetCookiePlain(w, errMsgCookieName, 60, fmt.Sprint(rc)) http.Redirect(w, r, r.Header.Get("Referer"), http.StatusFound) } }() r = m.buildContext(w, r) p.HandlePost(w, r) } func GetCookieManager(r *http.Request) *CookieManager { return r.Context().Value(cookieContextKey).(*CookieManager) } func GetRedirector(r *http.Request) func() { return r.Context().Value(redirectContextKey).(func()) } func GetUser(r *http.Request) *User { u := r.Context().Value(userContextKey) if u == nil { return nil } return u.(*User) } //RandomString returns a random string of bytes length long, base64 encoded. func RandomString(length int) string { var dat = make([]byte, length) rand.Read(dat) return base64.StdEncoding.EncodeToString(dat) }
alienth/bosun
vendor/github.com/captncraig/easyauth/auth.go
GO
mit
8,164
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M20 15H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zm0-5H4c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-1c0-.55-.45-1-1-1zm0-6H4c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm.5 15h-17c-.28 0-.5.22-.5.5s.22.5.5.5h17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z" }), 'LineWeightRounded');
AlloyTeam/Nuclear
components/icon/esm/line-weight-rounded.js
JavaScript
mit
447
FROM python:3 WORKDIR /root # install any Python packages this app depends on COPY requirements.txt /root/requirements.txt RUN pip install -r requirements.txt ENV FLASK_APP /root/main.py # copy sources COPY main.py /root/main.py COPY templates /root/templates CMD ["flask", "run", "--host=0.0.0.0", "--port=80"]
anoop901/facebook-clone
Dockerfile
Dockerfile
mit
317
package test.unit.hu.interconnect.hr.module.personaldata.vacations; import static com.google.common.collect.Lists.newArrayList; import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.MUNKANAP; import static hu.interconnect.hr.backend.api.enumeration.KivetelnapTipus.PIHENONAP; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.junit.Test; import hu.interconnect.hr.backend.api.dto.SzabadsagFelhasznalasResponseDTO; import hu.interconnect.hr.domain.Kivetelnap; import hu.interconnect.hr.domain.Szabadsag; import hu.interconnect.hr.module.exceptiondays.KivetelnapokHelper; import hu.interconnect.hr.module.personaldata.vacations.SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo; import test.builder.KivetelnapBuilder; import test.builder.SzabadsagBuilder; import test.builder.SzemelyitorzsBuilder; import test.matcher.SzabadsagFelhasznalasResponseDTOMatcher; import test.unit.AbstractBackendUnitTest; public class SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertaloTest extends AbstractBackendUnitTest { private SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(new KivetelnapokHelper(new ArrayList<Kivetelnap>())); @Test public void nullIllegalArgumentExceptiontDob() { try { konvertalo.konvertal(null); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getLocalizedMessage(), "A bemeno parameter null!"); } } @Test public void uresListaUresetAdVissza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(new ArrayList<Szabadsag>()); assertThat(kapottReszletek, hasSize(0)); } @Test public void egyElemuListaEgyelemetAdVissza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.03") .munkanapokSzama(1); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void ketEgymasMellettiElemOsszevonodikHaAKetNapKetEgymastKovetkoHetkoznapok() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.04").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.04") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void ketEgymasMellettiElemOsszevonodikHaAKetNapKozottHetvegeVan() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.10").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.10") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void csutortokEsPentekOsszevonodikDeAHetvegeNemAdodikHozza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.06") .veg("2012.12.07") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void hetfotolPentekigOsszevonodikDeAHetvegeNemAdodikHozza() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.03").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.04").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.03") .veg("2012.12.07") .munkanapokSzama(5); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void pentekEsKovetkezoHetKedd() { List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.11").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.07") .munkanapokSzama(1); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.11") .veg("2012.12.11") .munkanapokSzama(1); assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void pentekEsKovetkezoHetKeddEsAHetvegeNormalisAHetfoPedigPihenonap() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.12.10") .tipus(PIHENONAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.11").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.07") .veg("2012.12.11") .munkanapokSzama(2); assertThat(kapottReszletek, contains(elvartReszletek)); } @Test public void bugfix() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.03.16") .tipus(PIHENONAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.20").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.01") .veg("2012.03.08") .munkanapokSzama(6); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.15") .veg("2012.03.20") .munkanapokSzama(3); assertThat(kapottReszletek, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void vasarnapMunkanappaTeveEsErreSzabadsagKiveve() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.12.23") .tipus(MUNKANAP) .letrehoz())); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> kapottReszletek = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.12.23").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.12.23") .veg("2012.12.23") .munkanapokSzama(1); assertThat(kapottReszletek, contains(asList(elvartReszletek))); } @Test public void bugfix2() { List<SzabadsagFelhasznalasResponseDTO> eredmeny = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.16").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.17").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.18").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.21").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.22").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.23").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.28").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.29").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.30").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2013.01.31").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek1 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2013.01.15") .veg("2013.01.23") .munkanapokSzama(7); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek2 = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2013.01.28") .veg("2013.01.31") .munkanapokSzama(4); assertThat(eredmeny, contains(asList(elvartReszletek1, elvartReszletek2))); } @Test public void bugfix3() { KivetelnapokHelper kivetelnapok = new KivetelnapokHelper(newArrayList(new KivetelnapBuilder() .datum("2012.03.16") .tipus(PIHENONAP) .letrehoz(), new KivetelnapBuilder() .datum("2012.03.24") .tipus(MUNKANAP) .letrehoz()) ); konvertalo = new SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertalo(kivetelnapok); List<SzabadsagFelhasznalasResponseDTO> eredmeny = konvertalo.konvertal(newArrayList( new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.01").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.02").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.05").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.06").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.07").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.08").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.09").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.12").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.13").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.14").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.15").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.19").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.20").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.21").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.22").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.23").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.24").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.26").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.27").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.28").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.29").letrehoz(), new SzabadsagBuilder().szemelyitorzs(new SzemelyitorzsBuilder().tsz(1).letrehoz()).nap("2012.03.30").letrehoz())); SzabadsagFelhasznalasResponseDTOMatcher elvartReszletek = new SzabadsagFelhasznalasResponseDTOMatcher() .tsz(1) .kezdet("2012.03.01") .veg("2012.03.30") .munkanapokSzama(22); assertThat(eredmeny, contains(elvartReszletek)); } }
tornaia/hr2
hr2-java-parent/hr2-backend-impl/src/test/java/test/unit/hu/interconnect/hr/module/personaldata/vacations/SzabadsagokatOsszefuggoFelhasznaltSzabadnapReszletekkeKonvertaloTest.java
Java
mit
21,192
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>JsDoc Reference - Index</title> <meta name="generator" content="JsDoc Toolkit" /> <link href="css/default.css" type="text/css" rel="stylesheet" media="all" /> </head> <body> <div id="header"> </div> <div class="index"> <div class="menu"> <div align="center"><a href="index.html">Class Index</a> | <a href="files.html">File Index</a></div> <h2 class="heading1">Classes</h2> <ul class="classList"> <li><a href="symbols/_global_.html">_global_</a></li> <li><a href="symbols/dom.html">dom</a></li> <li><a href="symbols/dom.clone.html">dom.clone</a></li> <li><a href="symbols/s.html">s</a></li> </ul> </div> <div class="fineprint" style="clear:both"> Generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blank">JsDoc Toolkit</a> 2.4.0 on Wed Dec 15 2010 21:56:33 GMT-0000 (GMT)<br /> HTML template: <a href="http://www.thebrightlines.com/2010/05/06/new-template-for-jsdoctoolkit-codeview/" target="_blank">Codeview</a> </div> </div> <div class="content"> <div class="innerContent"> <h1 class="classTitle">Class Index</h1> <ul> <li> <h2 class="classname"><a href="symbols/_global_.html">_global_</a></h2> <p></p> </li> <li> <h2 class="classname"><a href="symbols/dom.html">dom</a></h2> <p>Common and useful DOM elements for the class instance</p> </li> <li> <h2 class="classname"><a href="symbols/dom.clone.html">dom.clone</a></h2> <p>Cloned table nodes</p> </li> <li> <h2 class="classname"><a href="symbols/s.html">s</a></h2> <p>Settings object which contains customisable information for FixedColumns instance</p> </li> </ul> </div> </div> </body> </html>
linkworks/linkigniter
public/js/dataTables-1.7/extras/FixedColumns/media/docs/index.html
HTML
mit
2,085
using ENode.EQueue; using ENode.Eventing; namespace ENode.Tests { public class EventTopicProvider : AbstractTopicProvider<IDomainEvent> { public override string GetTopic(IDomainEvent source) { return "EventTopic"; } } }
ouraspnet/ENode.Standard
test/ENode.Test/Providers/EventTopicProvider.cs
C#
mit
272
#!/usr/bin/env python # coding: utf-8 import os,sys import ctypes import numpy as np from .hmatrix import _C_HMatrix, HMatrix class _C_MultiHMatrix(ctypes.Structure): """Holder for the raw data from the C++ code.""" pass class AbstractMultiHMatrix: """Common code for the two actual MultiHMatrix classes below.""" ndim = 2 # To mimic a numpy 2D array def __init__(self, c_data: _C_MultiHMatrix, **params): # Users should use one of the two constructors below. self.c_data = c_data self.shape = (self.lib.multi_nbrows(c_data), self.lib.multi_nbcols(c_data)) self.size = self.lib.nbhmats(c_data) self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] self.hmatrices = [] for l in range(0,self.size): c_data_hmatrix = self.lib.getHMatrix(self.c_data,l) self.hmatrices.append(HMatrix(c_data_hmatrix,**params)) self.params = params.copy() @classmethod def from_coefs(cls, getcoefs, nm, points_target, points_source=None, **params): """Construct an instance of the class from a evaluation function. Parameters ---------- getcoefs: Callable A function evaluating an array of matrices at given coordinates. points_target: np.ndarray of shape (N, 3) The coordinates of the target points. If points_source=None, also the coordinates of the target points points_source: np.ndarray of shape (N, 3) If not None; the coordinates of the source points. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- MultiHMatrix or ComplexMultiHMatrix """ # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getcoefs_func_type = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)) if points_source is None: cls.lib.MultiHMatrixCreateSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreateSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreateSym(points_target, points_target.shape[0], _getcoefs_func_type(getcoefs),nm) else: cls.lib.MultiHMatrixCreate.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreate.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreate(points_target,points_target.shape[0],points_source, points_source.shape[0], _getcoefs_func_type(getcoefs),nm) return cls(c_data, **params) @classmethod def from_submatrices(cls, getsubmatrix, nm, points_target, points_source=None, **params): """Construct an instance of the class from a evaluation function. Parameters ---------- points: np.ndarray of shape (N, 3) The coordinates of the points. getsubmatrix: Callable A function evaluating the matrix in a given range. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- HMatrix or ComplexHMatrix """ # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getsumatrix_func_type = ctypes.CFUNCTYPE( None, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double) ) if points_source is None: cls.lib.MultiHMatrixCreatewithsubmatSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmatSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmatSym(points_target, points_target.shape[0], _getsumatrix_func_type(getsubmatrix),nm) else: cls.lib.MultiHMatrixCreatewithsubmat.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmat.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmat(points_target,points_target.shape[0],points_source, points_source.shape[0], _getsumatrix_func_type(getsubmatrix),nm) return cls(c_data, **params) @classmethod def _set_building_params(cls, *, eta=None, minclustersize=None, epsilon=None, maxblocksize=None): """Put the parameters in the C++ backend.""" if epsilon is not None: cls.lib.setepsilon.restype = None cls.lib.setepsilon.argtypes = [ ctypes.c_double ] cls.lib.setepsilon(epsilon) if eta is not None: cls.lib.seteta.restype = None cls.lib.seteta.argtypes = [ ctypes.c_double ] cls.lib.seteta(eta) if minclustersize is not None: cls.lib.setminclustersize.restype = None cls.lib.setminclustersize.argtypes = [ ctypes.c_int ] cls.lib.setminclustersize(minclustersize) if maxblocksize is not None: cls.lib.setmaxblocksize.restype = None cls.lib.setmaxblocksize.argtypes = [ ctypes.c_int ] cls.lib.setmaxblocksize(maxblocksize) def __str__(self): return f"{self.__class__.__name__}(shape={self.shape})" def __getitem__(self, key): # self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) # self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] # c_data_hmatrix = self.lib.getHMatrix(self.c_data,key) # return HMatrix(c_data_hmatrix,**self.params) return self.hmatrices[key] def matvec(self, l , vector): """Matrix-vector product (interface for scipy iterative solvers).""" assert self.shape[1] == vector.shape[0], "Matrix-vector product of matrices of wrong shapes." # Boilerplate for Python/C++ interface self.lib.MultiHMatrixVecProd.argtypes = [ ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int, np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS'), np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS') ] # Initialize vector result = np.zeros((self.shape[0],), dtype=self.dtype) # Call C++ backend self.lib.MultiHMatrixVecProd(self.c_data,l , vector, result) return result class MultiHMatrix(AbstractMultiHMatrix): """A real-valued hierarchical matrix based on htool C++ library. Create with HMatrix.from_coefs or HMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """ libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = ctypes.c_double class ComplexMultiHMatrix(AbstractMultiHMatrix): """A complex-valued hierarchical matrix based on htool C++ library. Create with ComplexHMatrix.from_coefs or ComplexHMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """ libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared_complex') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = np.complex128
PierreMarchand20/htool
interface/htool/multihmatrix.py
Python
mit
10,354
public class Grid { public Tile array[][] = new Tile[10][8]; public Grid() { // for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { array[x][y] = new Tile(); } } } public int getWidth() { return 9; } public int getHeight() { return 7; } public Tile getTile(int x, int y) { Tile mytile = new Tile(); try { //System.out.println("Actual tile returned"); mytile = array[x][y]; } catch(ArrayIndexOutOfBoundsException e) { //System.out.println("Out of bounds tile"); } finally { //System.out.println("Returning false tile"); return mytile; } } public void makeHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if(((y == 1) || (y == 5)) && (x>=3) && (x<=6)) { array[x][y].visible = false; } if(((y == 2) || (y == 4)) && (x>=2) && (x<=6)) { array[x][y].visible = false; } if((y == 3) && (x>=2) && (x<=7)) { array[x][y].visible = false; } } } } public void makeHolierHole() { for(int y = 0; y < getHeight(); y++) { for(int x = 0; x < getWidth(); x++) { if((x >= 1+y%2) && (x <= 5+y%2)) { array[x][y].visible = false; } } } } }
Caaz/danmaku-class-project
Grid.java
Java
mit
1,391
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { FootComponent } from './foot.component'; describe('FootComponent', () => { let component: FootComponent; let fixture: ComponentFixture<FootComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ FootComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(FootComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
tme321/uat-datatable
src/app/data-table/foot/foot.component.spec.ts
TypeScript
mit
614
# path Create a 2d path using SVG syntax. * `d` is the path descriptor {% craftml %} <!-- rectangle --> <path d="M10 10 h 10 v 10 h -10 z"/> <!-- triangle --> <path d="M30 10 l 10 10 l 10 -10 z"/> {% endcraftml %} Typically, you would use another drawing program to draw a path and export it as an SVG tag to use in CraftML, because it is quite difficult to write out a path descriptor manually. {% craftml %} <path d="M425.714,298.795c-3.315-25.56-31.224-50.174-59.725-52.675c-1.32-0.116-2.678-0.175-4.035-0.175 c-7.841,0-15.145,1.899-22.876,3.909c-8.474,2.204-17.236,4.482-27.593,4.482c-24.627,0-51.939-13.673-85.951-43.03 c-15.99-13.803-37.649-30.563-60.579-48.309c-35.625-27.57-72.464-56.078-92.513-76.923c-0.966-1.005-2.134-2.422-3.485-4.063 c-5.524-6.71-13.871-16.849-23.975-16.849c-7.007,0-13.556,4.88-19.463,14.506c-17.969,29.272-40.64,92.412-11.632,143.381 c22.454,39.516,27.952,104.224,29.102,123.114c0.583,9.583,7.556,12.261,11.214,12.338h33.836c6.576,0,10.445-4.408,10.615-12.095 c0.141-6.393,0.801-30.128,3.351-67.172c2.102-30.806,8.488-34.369,13.109-34.369c10.056,0,27.157,16.668,50.825,39.738 c15.363,14.975,34.483,33.61,56.618,52.296c19.095,16.12,42.025,23.956,70.1,23.956c36.682,0,74.746-13.709,105.331-24.725 l2.09-0.752C418.524,328.739,427.869,315.404,425.714,298.795z"/> {% endcraftml %}
craftml/docs
language/primitives/2d/path.md
Markdown
mit
1,313
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResolutionHost = createModuleResolutionHost(); const files = {}; // normalized filename => {version, snap, text} filenames.forEach(filename => files[normalizePath(filename)] = null); return { getDirectories: sys.getDirectories, directoryExists: sys.directoryExists, readDirectory: sys.readDirectory, getDefaultLibFileName: getDefaultLibFilePath, fileExists(filename) { filename = normalizePath(filename); return filename in files || sys.fileExists(filename); }, readFile(filename) { return readFileSync(normalizePath(filename), "utf-8"); }, getCompilationSettings() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { let f = files[normalizePath(filename)]; if(!f) { f = this.addFile(filename, this.readFile(filename)); } return f.snap; }, resolveModuleNames(moduleNames, containingFile) { return moduleNames.map(name => this.resolveModuleName(name, containingFile)); }, getNewLine() { return options.newLine || sys.newLine; }, // additional methods containsFile(filename) { return normalizePath(filename) in files; }, resolveModuleName(moduleName, containingFile) { const {resolvedModule} = resolveModuleName(moduleName, containingFile, options, moduleResolutionHost); if(resolvedModule) { resolvedModule.resolvedFileName = normalizePath(resolvedModule.resolvedFileName); resolvedModule.originalFileName = resolvedModule.resolvedFileName; } return resolvedModule; }, addFile(filename, text) { filename = normalizePath(filename); const snap = ScriptSnapshot.fromString(text); snap.getChangeRange = () => {}; let file = files[filename]; if(!file) { file = {version: 0}; files[filename] = file; } ++file.version; file.snap = snap; file.text = text; return file; }, }; } function createModuleResolutionHost() { return { fileExists(filename) { return existsSync(filename); }, readFile(filename) { return readFileSync(filename, "utf-8") }, }; }
tsne/rollup-plugin-tsc
src/servicehost.js
JavaScript
mit
2,558
--- layout: sidebar-right title: "Piglettes by Clémentine Beauvais" date: 2019-03-26 author: emma-maguire category: young-adult excerpt: "<cite>Piglettes</cite> is funny, uplifting and inspiring." featured-image: /images/featured/featured-piglettes.jpg featured-alt: "Piglettes" breadcrumb: young-adult genre: literary-fiction genre-image: /images/featured/featured-piglettes-genre.jpg genre-alt: "Piglettes" --- ![Piglettes](/images/featured/featured-piglettes.jpg) **[See <cite>Piglettes</cite> in our catalogue](https://suffolk.spydus.co.uk/cgi-bin/spydus.exe/ENQ/OPAC/BIBENQ?BRN=2168761)** > "Awarded the Gold, Silver and Bronze trotters after a vote by their classmates on Facebook, Mireille, Astrid and Hakima are officially the three ugliest girls in their school, but does that mean they're going to sit around crying about it? Well, yes, a bit, but not for long! Climbing aboard their bikes, the trio set off on a summer road trip to Paris, their goal: a garden party with the French president. > "As news of their trip spreads they become stars of social media and television. With the eyes of the nation upon them, the girls find fame, friendship and happiness, and still have time to consume an enormous amount of food along the way." I discovered Clémentine Beauvais when I read [<cite>In Paris with You</cite>](/new-suggestions/young-adult/in-paris-with-you-by-clementine-beauvais/). <cite>Piglettes</cite> is her other novel for young adults, and it did not disappoint. I laughed out loud at times and was inspired and uplifted at others. If ever we needed a book about the power of friendship and sausages against the need for fame and beauty, this is the novel to read. I loved this book, and will be keeping a keen eye on what Clémentine does next and grabbing for it with arms open wide!
suffolklibraries/sljekyll
new-suggestions/young-adult/_posts/2019-03-26-piglettes-by-clementine-beauvais.md
Markdown
mit
1,816
package main import ( "fmt" "log" ) type ListCommand struct { All bool `short:"a" long:"available" description:"also prints all available version for installation"` } type InitCommand struct{} type InstallCommand struct { Use bool `short:"u" long:"use" description:"force use of this new version after installation"` } type UseCommand struct{} type Interactor struct { archive WebotsArchive manager WebotsInstanceManager templates TemplateManager } func NewInteractor() (*Interactor, error) { res := &Interactor{} var err error res.archive, err = NewWebotsHttpArchive("http://www.cyberbotics.com/archive/") if err != nil { return nil, err } manager, err := NewSymlinkManager(res.archive) if err != nil { return nil, err } res.manager = manager res.templates = manager.templates return res, nil } func (x *ListCommand) Execute(args []string) error { xx, err := NewInteractor() if err != nil { return err } installed := xx.manager.Installed() if len(installed) == 0 { fmt.Printf("No webots version installed.\n") } else { for _, v := range installed { if xx.manager.IsUsed(v) == true { fmt.Printf(" -* %s\n", v) } else { fmt.Printf(" - %s\n", v) } } } if x.All { fmt.Println("List of all available versions:") for _, v := range xx.archive.AvailableVersions() { fmt.Printf(" - %s\n", v) } } else { vers := xx.archive.AvailableVersions() if len(vers) == 0 { return fmt.Errorf("No version are available") } fmt.Printf("Last available version is %s\n", vers[len(vers)-1]) } return nil } func (x *InitCommand) Execute(args []string) error { return SymlinkManagerSystemInit() } func (x *InstallCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Missing version to install") } v, err := ParseWebotsVersion(args[0]) if err != nil { return err } xx, err := NewInteractor() if err != nil { return err } err = xx.manager.Install(v) if err != nil { return err } notUsed := true for _, vv := range xx.manager.Installed() { if xx.manager.IsUsed(vv) { notUsed = false break } } if notUsed || x.Use { err = xx.manager.Use(v) if err != nil { return err } log.Printf("Using now version %s", v) } return nil } func (x *UseCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Missing version to use") } v, err := ParseWebotsVersion(args[0]) if err != nil { return err } xx, err := NewInteractor() if err != nil { return err } return xx.manager.Use(v) } type AddTemplateCommand struct { Only []string `short:"o" long:"only" description:"apply template only for these versions"` Except []string `short:"e" long:"except" description:"do not apply template on these versions"` } func (x *AddTemplateCommand) Execute(args []string) error { if len(args) != 2 { return fmt.Errorf("Need file to read and where to install") } var white, black []WebotsVersion for _, w := range x.Only { v, err := ParseWebotsVersion(w) if err != nil { return err } white = append(white, v) } for _, w := range x.Except { v, err := ParseWebotsVersion(w) if err != nil { return err } black = append(black, v) } xx, err := NewInteractor() if err != nil { return err } err = xx.templates.RegisterTemplate(args[0], args[1]) if err != nil { return err } err = xx.templates.WhiteList(args[1], white) if err != nil { return err } err = xx.templates.BlackList(args[1], black) if err != nil { return err } return xx.manager.ApplyAllTemplates() } type RemoveTemplateCommand struct{} func (x *RemoveTemplateCommand) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("Need install path to remove template from") } xx, err := NewInteractor() if err != nil { return err } err = xx.templates.RemoveTemplate(args[0]) if err != nil { return err } return xx.manager.ApplyAllTemplates() } func init() { parser.AddCommand("list", "Prints all the available version of webots", "Prints all installed version, and current version in use. Can also prinst all available version for installation", &ListCommand{}) parser.AddCommand("init", "Initialiaze the system for webots_manager", "Initialiaze the system with all requirement for webots_manager", &InitCommand{}) parser.AddCommand("install", "Install a new webots version on the system", "Installs a new webots version on the system", &InstallCommand{}) parser.AddCommand("use", "Use a webots version on the system", "Use a webots version on the system. If it is not installed, it will first install it", &UseCommand{}) parser.AddCommand("add-template", "Adds a template file to all version", "Install a file to all version of webots. -o and -e can be used to explicitely whitelist or blacklist a version", &AddTemplateCommand{}) parser.AddCommand("remove-template", "Removes a template file from all version", "Removes a previously installed template from all version of webots.", &RemoveTemplateCommand{}) }
biorob/webots-manager
commands.go
GO
mit
5,064
/* * $Id: Perl5Matcher.java,v 1.27 2003/11/07 20:16:25 dfs Exp $ * * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation", "Jakarta-Oro" * must not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * or "Jakarta-Oro", nor may "Apache" or "Jakarta-Oro" appear in their * name, without prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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 on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.oro.text.regex; import java.util.Stack; /** * The Perl5Matcher class is used to match regular expressions (conforming to * the Perl5 regular expression syntax) generated by Perl5Compiler. * <p> * Perl5Compiler and Perl5Matcher are designed with the intent that you use a * separate instance of each per thread to avoid the overhead of both * synchronization and concurrent access (e.g., a match that takes a long time * in one thread will block the progress of another thread with a shorter * match). If you want to use a single instance of each in a concurrent program, * you must appropriately protect access to the instances with critical * sections. If you want to share Perl5Pattern instances between concurrently * executing instances of Perl5Matcher, you must compile the patterns with * {@link Perl5Compiler#READ_ONLY_MASK}. * * @since 1.0 * @see PatternMatcher * @see Perl5Compiler */ public final class Perl5Matcher implements PatternMatcher { private static final char __EOS = Character.MAX_VALUE; private static final int __INITIAL_NUM_OFFSETS = 20; private final boolean __multiline = false; private boolean __lastSuccess = false; private boolean __caseInsensitive = false; private char __previousChar, __input[], __originalInput[]; private Perl5Repetition __currentRep; private int __numParentheses, __bol, __eol, __currentOffset, __endOffset; private char[] __program; private int __expSize, __inputOffset, __lastParen; private int[] __beginMatchOffsets, __endMatchOffsets; private final Stack<int[]> __stack = new Stack<int[]>(); private Perl5MatchResult __lastMatchResult = null; private static boolean __compare(final char[] s1, final int s1off, final char[] s2, final int s2off, final int n) { int s2Offs = s2off; int s1Offs = s1off; int cnt; for (cnt = 0; cnt < n; cnt++, s1Offs++, s2Offs++) { if (s1Offs >= s1.length) { return false; } if (s2Offs >= s2.length) { return false; } if (s1[s1Offs] != s2[s2Offs]) { return false; } } return true; } private static int __findFirst(final char[] input, final int curr, final int endOffset, final char[] mustString) { int current = curr; int count, saveCurrent; char ch; if (input.length == 0) { return endOffset; } ch = mustString[0]; // Find the offset of the first character of the must string while (current < endOffset) { if (ch == input[current]) { saveCurrent = current; count = 0; while (current < endOffset && count < mustString.length) { if (mustString[count] != input[current]) { break; } ++count; ++current; } current = saveCurrent; if (count >= mustString.length) { break; } } ++current; } return current; } private void __pushState(final int parenFloor) { int[] state; int stateEntries, paren; stateEntries = 3 * (this.__expSize - parenFloor); if (stateEntries <= 0) { state = new int[3]; } else { state = new int[stateEntries + 3]; } state[0] = this.__expSize; state[1] = this.__lastParen; state[2] = this.__inputOffset; for (paren = this.__expSize; paren > parenFloor; --paren, stateEntries -= 3) { state[stateEntries] = this.__endMatchOffsets[paren]; state[stateEntries + 1] = this.__beginMatchOffsets[paren]; state[stateEntries + 2] = paren; } this.__stack.push(state); } private void __popState() { int[] state; int entry, paren; state = this.__stack.pop(); this.__expSize = state[0]; this.__lastParen = state[1]; this.__inputOffset = state[2]; for (entry = 3; entry < state.length; entry += 3) { paren = state[entry + 2]; this.__beginMatchOffsets[paren] = state[entry + 1]; if (paren <= this.__lastParen) { this.__endMatchOffsets[paren] = state[entry]; } } for (paren = this.__lastParen + 1; paren <= this.__numParentheses; paren++) { if (paren > this.__expSize) { this.__beginMatchOffsets[paren] = OpCode._NULL_OFFSET; } this.__endMatchOffsets[paren] = OpCode._NULL_OFFSET; } } // Initialize globals needed before calling __tryExpression for first time private void __initInterpreterGlobals(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; // Remove this hack after more efficient case-folding and unicode // character classes are implemented this.__caseInsensitive = expression._isCaseInsensitive; this.__input = input; this.__endOffset = endOffset; this.__currentRep = new Perl5Repetition(); this.__currentRep._numInstances = 0; this.__currentRep._lastRepetition = null; this.__program = expression._program; this.__stack.setSize(0); // currentOffset should always be >= beginOffset and should // always be equal to zero when beginOffset equals 0, but we // make a weak attempt to protect against a violation of this // precondition if (currentOffset == beginOffset || currentOffset <= 0) { this.__previousChar = '\n'; } else { this.__previousChar = input[currentOffset - 1]; if (!this.__multiline && this.__previousChar == '\n') { this.__previousChar = '\0'; } } this.__numParentheses = expression._numParentheses; this.__currentOffset = currentOffset; this.__bol = beginOffset; this.__eol = endOffset; // Ok, here we're using endOffset as a temporary variable. endOffset = this.__numParentheses + 1; if (this.__beginMatchOffsets == null || endOffset > this.__beginMatchOffsets.length) { if (endOffset < __INITIAL_NUM_OFFSETS) { endOffset = __INITIAL_NUM_OFFSETS; } this.__beginMatchOffsets = new int[endOffset]; this.__endMatchOffsets = new int[endOffset]; } } // Set the match result information. Only call this if we successfully // matched. private void __setLastMatchResult() { int offs, maxEndOffs = 0; // endOffset+=dontTry; this.__lastMatchResult = new Perl5MatchResult(this.__numParentheses + 1); // This can happen when using Perl5StreamInput if (this.__endMatchOffsets[0] > this.__originalInput.length) { throw new ArrayIndexOutOfBoundsException(); } this.__lastMatchResult._matchBeginOffset = this.__beginMatchOffsets[0]; while (this.__numParentheses >= 0) { offs = this.__beginMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; } else { this.__lastMatchResult._beginGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } offs = this.__endMatchOffsets[this.__numParentheses]; if (offs >= 0) { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = offs - this.__lastMatchResult._matchBeginOffset; if (offs > maxEndOffs && offs <= this.__originalInput.length) { maxEndOffs = offs; } } else { this.__lastMatchResult._endGroupOffset[this.__numParentheses] = OpCode._NULL_OFFSET; } --this.__numParentheses; } this.__lastMatchResult._match = new String(this.__originalInput, this.__beginMatchOffsets[0], maxEndOffs - this.__beginMatchOffsets[0]); // Free up for garbage collection this.__originalInput = null; } // Expects to receive a valid regular expression program. No checking // is done to ensure validity. // __originalInput must be set before calling this method for // __lastMatchResult to be set correctly. // beginOffset marks the beginning of the string // currentOffset marks where to start the pattern search private boolean __interpret(final Perl5Pattern expression, final char[] input, final int beginOffset, final int endOff, final int currentOffset) { int endOffset = endOff; boolean success; int minLength = 0, dontTry = 0, offset; char ch, mustString[]; __initInterpreterGlobals(expression, input, beginOffset, endOffset, currentOffset); success = false; mustString = expression._mustString; _mainLoop: while (true) { if (mustString != null && ((expression._anchor & Perl5Pattern._OPT_ANCH) == 0 || (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0) && expression._back >= 0)) { this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString); if (this.__currentOffset >= endOffset) { if ((expression._options & Perl5Compiler.READ_ONLY_MASK) == 0) { expression._mustUtility++; } success = false; break _mainLoop; } else if (expression._back >= 0) { this.__currentOffset -= expression._back; if (this.__currentOffset < currentOffset) { this.__currentOffset = currentOffset; } minLength = expression._back + mustString.length; } else if (!expression._isExpensive && (expression._options & Perl5Compiler.READ_ONLY_MASK) == 0 && --expression._mustUtility < 0) { // Be careful! The preceding logical expression is // constructed // so that mustUtility is only decremented if the expression // is // compiled without READ_ONLY_MASK. mustString = expression._mustString = null; this.__currentOffset = currentOffset; } else { this.__currentOffset = currentOffset; minLength = mustString.length; } } if ((expression._anchor & Perl5Pattern._OPT_ANCH) != 0) { if (this.__currentOffset == beginOffset && __tryExpression(beginOffset)) { success = true; break _mainLoop; } else if (this.__multiline || (expression._anchor & Perl5Pattern._OPT_ANCH_MBOL) != 0 || (expression._anchor & Perl5Pattern._OPT_IMPLICIT) != 0) { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; if (this.__currentOffset > currentOffset) { --this.__currentOffset; } while (this.__currentOffset < endOffset) { if (this.__input[this.__currentOffset++] == '\n') { if (this.__currentOffset < endOffset && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } } } break _mainLoop; } if (expression._startString != null) { mustString = expression._startString; if ((expression._anchor & Perl5Pattern._OPT_SKIP) != 0) { ch = mustString[0]; while (this.__currentOffset < endOffset) { if (ch == this.__input[this.__currentOffset]) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; while (this.__currentOffset < endOffset && this.__input[this.__currentOffset] == ch) { ++this.__currentOffset; } } ++this.__currentOffset; } } else { while ((this.__currentOffset = __findFirst(this.__input, this.__currentOffset, endOffset, mustString)) < endOffset) { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } } break _mainLoop; } if ((offset = expression._startClassOffset) != OpCode._NULL_OFFSET) { boolean doEvery, tmp; char op; doEvery = (expression._anchor & Perl5Pattern._OPT_SKIP) == 0; if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; tmp = true; switch (op = this.__program[offset]) { case OpCode._ANYOF: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (ch < 256 && (this.__program[offset + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: offset = OpCode._getOperand(offset); while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (__matchUnicodeClass(ch, this.__program, offset, op)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._BOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } ++this.__currentOffset; } if ((minLength > 0 || tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._NBOUND: if (minLength > 0) { ++dontTry; --endOffset; } if (this.__currentOffset != beginOffset) { ch = this.__input[this.__currentOffset - 1]; tmp = OpCode._isWordCharacter(ch); } else { tmp = OpCode._isWordCharacter(this.__previousChar); } while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (tmp != OpCode._isWordCharacter(ch)) { tmp = !tmp; } else if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } ++this.__currentOffset; } if ((minLength > 0 || !tmp) && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } break; case OpCode._ALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NALNUM: while (this.__currentOffset < endOffset) { ch = this.__input[this.__currentOffset]; if (!OpCode._isWordCharacter(ch)) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._SPACE: while (this.__currentOffset < endOffset) { if (Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NSPACE: while (this.__currentOffset < endOffset) { if (!Character .isWhitespace(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._DIGIT: while (this.__currentOffset < endOffset) { if (Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; case OpCode._NDIGIT: while (this.__currentOffset < endOffset) { if (!Character .isDigit(this.__input[this.__currentOffset])) { if (tmp && __tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } tmp = doEvery; } else { tmp = true; } ++this.__currentOffset; } break; default: break; } // end switch } else { if (minLength > 0) { dontTry = minLength - 1; } endOffset -= dontTry; do { if (__tryExpression(this.__currentOffset)) { success = true; break _mainLoop; } } while (this.__currentOffset++ < endOffset); } break _mainLoop; } // end while this.__lastSuccess = success; this.__lastMatchResult = null; return success; } private boolean __matchUnicodeClass(final char code, final char __program1[], final int off, final char opcode) { int offset = off; boolean isANYOF = opcode == OpCode._ANYOFUN; while (__program1[offset] != OpCode._END) { if (__program1[offset] == OpCode._RANGE) { offset++; if (code >= __program1[offset] && code <= __program1[offset + 1]) { return isANYOF; } offset += 2; } else if (__program1[offset] == OpCode._ONECHAR) { offset++; if (__program1[offset++] == code) { return isANYOF; } } else { isANYOF = __program1[offset] == OpCode._OPCODE ? isANYOF : !isANYOF; offset++; switch (__program1[offset++]) { case OpCode._ALNUM: if (OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._NALNUM: if (!OpCode._isWordCharacter(code)) { return isANYOF; } break; case OpCode._SPACE: if (Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._NSPACE: if (!Character.isWhitespace(code)) { return isANYOF; } break; case OpCode._DIGIT: if (Character.isDigit(code)) { return isANYOF; } break; case OpCode._NDIGIT: if (!Character.isDigit(code)) { return isANYOF; } break; case OpCode._ALNUMC: if (Character.isLetterOrDigit(code)) { return isANYOF; } break; case OpCode._ALPHA: if (Character.isLetter(code)) { return isANYOF; } break; case OpCode._BLANK: if (Character.isSpaceChar(code)) { return isANYOF; } break; case OpCode._CNTRL: if (Character.isISOControl(code)) { return isANYOF; } break; case OpCode._LOWER: if (Character.isLowerCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isUpperCase(code)) { return isANYOF; } break; case OpCode._UPPER: if (Character.isUpperCase(code)) { return isANYOF; } // Remove this hack after more efficient case-folding and // unicode // character classes are implemented if (this.__caseInsensitive && Character.isLowerCase(code)) { return isANYOF; } break; case OpCode._PRINT: if (Character.isSpaceChar(code)) { return isANYOF; } // Fall through to check if the character is alphanumeric, // or a punctuation mark. Printable characters are either // alphanumeric, punctuation marks, or spaces. //$FALL-THROUGH$ case OpCode._GRAPH: if (Character.isLetterOrDigit(code)) { return isANYOF; } // Fall through to check if the character is a punctuation // mark. // Graph characters are either alphanumeric or punctuation. //$FALL-THROUGH$ case OpCode._PUNCT: switch (Character.getType(code)) { case Character.DASH_PUNCTUATION: case Character.START_PUNCTUATION: case Character.END_PUNCTUATION: case Character.CONNECTOR_PUNCTUATION: case Character.OTHER_PUNCTUATION: case Character.MATH_SYMBOL: case Character.CURRENCY_SYMBOL: case Character.MODIFIER_SYMBOL: return isANYOF; default: break; } break; case OpCode._XDIGIT: if (code >= '0' && code <= '9' || code >= 'a' && code <= 'f' || code >= 'A' && code <= 'F') { return isANYOF; } break; case OpCode._ASCII: if (code < 0x80) { return isANYOF; } break; default: return !isANYOF; } } } return !isANYOF; } private boolean __tryExpression(final int offset) { int count; this.__inputOffset = offset; this.__lastParen = 0; this.__expSize = 0; if (this.__numParentheses > 0) { for (count = 0; count <= this.__numParentheses; count++) { this.__beginMatchOffsets[count] = OpCode._NULL_OFFSET; this.__endMatchOffsets[count] = OpCode._NULL_OFFSET; } } if (__match(1)) { this.__beginMatchOffsets[0] = offset; this.__endMatchOffsets[0] = this.__inputOffset; return true; } return false; } private int __repeat(final int offset, final int max) { int scan, eol, operand, ret; char ch; char op; scan = this.__inputOffset; eol = this.__eol; if (max != Character.MAX_VALUE && max < eol - scan) { eol = scan + max; } operand = OpCode._getOperand(offset); switch (op = this.__program[offset]) { case OpCode._ANY: while (scan < eol && this.__input[scan] != '\n') { ++scan; } break; case OpCode._SANY: scan = eol; break; case OpCode._EXACTLY: ++operand; while (scan < eol && this.__program[operand] == this.__input[scan]) { ++scan; } break; case OpCode._ANYOF: if (scan < eol && (ch = this.__input[scan]) < 256) { while (ch < 256 && (this.__program[operand + (ch >> 4)] & 1 << (ch & 0xf)) == 0) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: if (scan < eol) { ch = this.__input[scan]; while (__matchUnicodeClass(ch, this.__program, operand, op)) { if (++scan < eol) { ch = this.__input[scan]; } else { break; } } } break; case OpCode._ALNUM: while (scan < eol && OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._NALNUM: while (scan < eol && !OpCode._isWordCharacter(this.__input[scan])) { ++scan; } break; case OpCode._SPACE: while (scan < eol && Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._NSPACE: while (scan < eol && !Character.isWhitespace(this.__input[scan])) { ++scan; } break; case OpCode._DIGIT: while (scan < eol && Character.isDigit(this.__input[scan])) { ++scan; } break; case OpCode._NDIGIT: while (scan < eol && !Character.isDigit(this.__input[scan])) { ++scan; } break; default: break; } ret = scan - this.__inputOffset; this.__inputOffset = scan; return ret; } private boolean __match(final int offset) { char nextChar, op; int scan, next, input, maxScan, current, line, arg; boolean inputRemains = true, minMod = false; Perl5Repetition rep; input = this.__inputOffset; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; scan = offset; maxScan = this.__program.length; while (scan < maxScan /* && scan > 0 */) { next = OpCode._getNext(this.__program, scan); switch (op = this.__program[scan]) { case OpCode._BOL: if (input == this.__bol ? this.__previousChar == '\n' : this.__multiline) { break; } return false; case OpCode._MBOL: if (input == this.__bol ? this.__previousChar == '\n' : (inputRemains || input < this.__eol) && this.__input[input - 1] == '\n') { break; } return false; case OpCode._SBOL: if (input == this.__bol && this.__previousChar == '\n') { break; } return false; case OpCode._GBOL: if (input == this.__bol) { break; } return true; case OpCode._EOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (!this.__multiline && this.__eol - input > 1) { return false; } break; case OpCode._MEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } break; case OpCode._SEOL: if ((inputRemains || input < this.__eol) && nextChar != '\n') { return false; } if (this.__eol - input > 1) { return false; } break; case OpCode._SANY: if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANY: if (!inputRemains && input >= this.__eol || nextChar == '\n') { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._EXACTLY: current = OpCode._getOperand(scan); line = this.__program[current++]; if (this.__program[current] != nextChar) { return false; } if (this.__eol - input < line) { return false; } if (line > 1 && !__compare(this.__program, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOF: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (nextChar >= 256 || (this.__program[current + (nextChar >> 4)] & 1 << (nextChar & 0xf)) != 0) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ANYOFUN: case OpCode._NANYOFUN: current = OpCode._getOperand(scan); if (nextChar == __EOS && inputRemains) { nextChar = this.__input[input]; } if (!__matchUnicodeClass(nextChar, this.__program, current, op)) { return false; } if (!inputRemains && input >= this.__eol) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._ALNUM: if (!inputRemains) { return false; } if (!OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NALNUM: if (!inputRemains && input >= this.__eol) { return false; } if (OpCode._isWordCharacter(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NBOUND: case OpCode._BOUND: boolean a, b; if (input == this.__bol) { a = OpCode._isWordCharacter(this.__previousChar); } else { a = OpCode._isWordCharacter(this.__input[input - 1]); } b = OpCode._isWordCharacter(nextChar); if (a == b == (this.__program[scan] == OpCode._BOUND)) { return false; } break; case OpCode._SPACE: if (!inputRemains && input >= this.__eol) { return false; } if (!Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NSPACE: if (!inputRemains) { return false; } if (Character.isWhitespace(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._DIGIT: if (!Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NDIGIT: if (!inputRemains && input >= this.__eol) { return false; } if (Character.isDigit(nextChar)) { return false; } inputRemains = ++input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._REF: arg = OpCode._getArg1(this.__program, scan); current = this.__beginMatchOffsets[arg]; if (current == OpCode._NULL_OFFSET) { return false; } if (this.__endMatchOffsets[arg] == OpCode._NULL_OFFSET) { return false; } if (current == this.__endMatchOffsets[arg]) { break; } if (this.__input[current] != nextChar) { return false; } line = this.__endMatchOffsets[arg] - current; if (input + line > this.__eol) { return false; } if (line > 1 && !__compare(this.__input, current, this.__input, input, line)) { return false; } input += line; inputRemains = input < this.__endOffset; nextChar = inputRemains ? this.__input[input] : __EOS; break; case OpCode._NOTHING: break; case OpCode._BACK: break; case OpCode._OPEN: arg = OpCode._getArg1(this.__program, scan); this.__beginMatchOffsets[arg] = input; if (arg > this.__expSize) { this.__expSize = arg; } break; case OpCode._CLOSE: arg = OpCode._getArg1(this.__program, scan); this.__endMatchOffsets[arg] = input; if (arg > this.__lastParen) { this.__lastParen = arg; } break; case OpCode._CURLYX: rep = new Perl5Repetition(); rep._lastRepetition = this.__currentRep; this.__currentRep = rep; rep._parenFloor = this.__lastParen; rep._numInstances = -1; rep._min = OpCode._getArg1(this.__program, scan); rep._max = OpCode._getArg2(this.__program, scan); rep._scan = OpCode._getNextOperator(scan) + 2; rep._next = next; rep._minMod = minMod; // Must initialize to -1 because if we initialize to 0 and are // at the beginning of the input the OpCode._WHILEM case will // not work right. rep._lastLocation = -1; this.__inputOffset = input; // use minMod as temporary minMod = __match(OpCode._getPrevOperator(next)); // leave scope call not pertinent? this.__currentRep = rep._lastRepetition; return minMod; case OpCode._WHILEM: rep = this.__currentRep; arg = rep._numInstances + 1; this.__inputOffset = input; if (input == rep._lastLocation) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; return false; } if (arg < rep._min) { rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (rep._minMod) { this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } this.__currentRep._numInstances = line; this.__currentRep = rep; if (arg >= rep._max) { return false; } this.__inputOffset = input; rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } rep._numInstances = arg - 1; return false; } if (arg < rep._max) { __pushState(rep._parenFloor); rep._numInstances = arg; rep._lastLocation = input; if (__match(rep._scan)) { return true; } __popState(); this.__inputOffset = input; } this.__currentRep = rep._lastRepetition; line = this.__currentRep._numInstances; if (__match(rep._next)) { return true; } rep._numInstances = line; this.__currentRep = rep; rep._numInstances = arg - 1; return false; case OpCode._BRANCH: if (this.__program[next] != OpCode._BRANCH) { next = OpCode._getNextOperator(scan); } else { int lastParen; lastParen = this.__lastParen; do { this.__inputOffset = input; if (__match(OpCode._getNextOperator(scan))) { return true; } for (arg = this.__lastParen; arg > lastParen; --arg) { // __endMatchOffsets[arg] = 0; this.__endMatchOffsets[arg] = OpCode._NULL_OFFSET; } this.__lastParen = arg; scan = OpCode._getNext(this.__program, scan); } while (scan != OpCode._NULL_OFFSET && this.__program[scan] == OpCode._BRANCH); return false; } break; case OpCode._MINMOD: minMod = true; break; case OpCode._CURLY: case OpCode._STAR: case OpCode._PLUS: if (op == OpCode._CURLY) { line = OpCode._getArg1(this.__program, scan); arg = OpCode._getArg2(this.__program, scan); scan = OpCode._getNextOperator(scan) + 2; } else if (op == OpCode._STAR) { line = 0; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } else { line = 1; arg = Character.MAX_VALUE; scan = OpCode._getNextOperator(scan); } if (this.__program[next] == OpCode._EXACTLY) { nextChar = this.__program[OpCode._getOperand(next) + 1]; current = 0; } else { nextChar = __EOS; current = -1000; } this.__inputOffset = input; if (minMod) { minMod = false; if (line > 0 && __repeat(scan, line) < line) { return false; } while (arg >= line || arg == Character.MAX_VALUE && line > 0) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } this.__inputOffset = input + line; if (__repeat(scan, 1) != 0) { ++line; this.__inputOffset = input + line; } else { return false; } } } else { arg = __repeat(scan, arg); if (line < arg && OpCode._opType[this.__program[next]] == OpCode._EOL && (!this.__multiline && this.__program[next] != OpCode._MEOL || this.__program[next] == OpCode._SEOL)) { line = arg; } while (arg >= line) { // there may be a bug here with respect to // __inputOffset >= __endOffset, but it seems to be // right for // now. the issue is with __inputOffset being reset // later. // is this test really supposed to happen here? if (current == -1000 || this.__inputOffset >= this.__endOffset || this.__input[this.__inputOffset] == nextChar) { if (__match(next)) { return true; } } --arg; this.__inputOffset = input + arg; } } return false; case OpCode._SUCCEED: case OpCode._END: this.__inputOffset = input; // This enforces the rule that two consecutive matches cannot // have // the same end offset. if (this.__inputOffset == this.__lastMatchInputEndOffset) { return false; } return true; case OpCode._IFMATCH: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (!__match(scan)) { return false; } break; case OpCode._UNLESSM: this.__inputOffset = input; scan = OpCode._getNextOperator(scan); if (__match(scan)) { return false; } break; default: // todo: Need to throw an exception here. } // end switch // scan = (next > 0 ? next : 0); scan = next; } // end while scan return false; } static char[] _toLower(final char[] in) { char[] input = in.clone(); int current; char[] inp; // todo: // Certainly not the best way to do case insensitive matching. // Must definitely change this in some way, but for now we // do what Perl does and make a copy of the input, converting // it all to lowercase. This is truly better handled in the // compilation phase. inp = new char[input.length]; System.arraycopy(input, 0, inp, 0, input.length); input = inp; // todo: Need to inline toLowerCase() for (current = 0; current < input.length; current++) { if (Character.isUpperCase(input[current])) { input[current] = Character.toLowerCase(input[current]); } } return input; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern, starting from a given offset into the string. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param in * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @param offset * The offset at which to start searching for the prefix. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] in, final Pattern pattern, final int offset) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, offset); this.__lastSuccess = __tryExpression(offset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a prefix of a string (represented as a char[]) matches a * given pattern. If a prefix of the string matches the pattern, a * MatchResult instance representing the match is made accesible via * {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The char[] to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final char[] input, final Pattern pattern) { return matchesPrefix(input, pattern, 0); } /** * Determines if a prefix of a string matches a given pattern. If a prefix * of the string matches the pattern, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The String to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final String input, final Pattern pattern) { return matchesPrefix(input.toCharArray(), pattern, 0); } /** * Determines if a prefix of a PatternMatcherInput instance matches a given * pattern. If there is a match, a MatchResult instance representing the * match is made accesible via {@link #getMatch()}. Unlike the * {@link #contains(PatternMatcherInput, Pattern)} method, the current * offset of the PatternMatcherInput argument is not updated. However, * unlike the {@link #matches matches(PatternMatcherInput, Pattern)} method, * matchesPrefix() will start its search from the current offset rather than * the begin offset of the PatternMatcherInput. * <p> * This method is useful for certain common token identification tasks that * are made more difficult without this functionality. * <p> * * @param input * The PatternMatcherInput to test for a prefix match. * @param pattern * The Pattern to be matched. * @return True if input matches pattern, false otherwise. */ @Override public boolean matchesPrefix(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); this.__lastSuccess = __tryExpression(input._currentOffset); this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string (represented as a char[]) exactly matches a given * pattern. If there is an exact match, a MatchResult instance representing * the match is made accesible via {@link #getMatch()}. The pattern must be * a Perl5Pattern instance, otherwise a ClassCastException will be thrown. * You are not required to, and indeed should NOT try to (for performance * reasons), catch a ClassCastException because it will never be thrown as * long as you use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param in * The char[] to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } __initInterpreterGlobals(expression, input, 0, input.length, 0); this.__lastSuccess = __tryExpression(0) && this.__endMatchOffsets[0] == input.length; this.__lastMatchResult = null; return this.__lastSuccess; } /** * Determines if a string exactly matches a given pattern. If there is an * exact match, a MatchResult instance representing the match is made * accesible via {@link #getMatch()}. The pattern must be a Perl5Pattern * instance, otherwise a ClassCastException will be thrown. You are not * required to, and indeed should NOT try to (for performance reasons), * catch a ClassCastException because it will never be thrown as long as you * use a Perl5Pattern as the pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The String to test for an exact match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final String input, final Pattern pattern) { return matches(input.toCharArray(), pattern); } /** * Determines if the contents of a PatternMatcherInput instance exactly * matches a given pattern. If there is an exact match, a MatchResult * instance representing the match is made accesible via {@link #getMatch()} * . Unlike the {@link #contains(PatternMatcherInput, Pattern)} method, the * current offset of the PatternMatcherInput argument is not updated. You * should remember that the region between the begin (NOT the current) and * end offsets of the PatternMatcherInput will be tested for an exact match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * <b>Note:</b> matches() is not the same as sticking a ^ in front of your * expression and a $ at the end of your expression in Perl5 and using the * =~ operator, even though in many cases it will be equivalent. matches() * literally looks for an exact match according to the rules of Perl5 * expression matching. Therefore, if you have a pattern <em>foo|foot</em> * and are matching the input <em>foot</em> it will not produce an exact * match. But <em>foot|foo</em> will produce an exact match for either * <em>foot</em> or <em>foo</em>. Remember, Perl5 regular expressions do not * match the longest possible match. From the perlre manpage: <blockquote> * Alternatives are tried from left to right, so the first alternative found * for which the entire expression matches, is the one that is chosen. This * means that alternatives are not necessarily greedy. For example: when * matching foo|foot against "barefoot", only the "foo" part will match, as * that is the first alternative tried, and it successfully matches the * target string. </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if input matches pattern, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean matches(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } __initInterpreterGlobals(expression, inp, input._beginOffset, input._endOffset, input._beginOffset); this.__lastMatchResult = null; if (__tryExpression(input._beginOffset)) { if (this.__endMatchOffsets[0] == input._endOffset || input.length() == 0 || input._beginOffset == input._endOffset) { this.__lastSuccess = true; return true; } } this.__lastSuccess = false; return false; } /** * Determines if a string contains a pattern. If the pattern is matched by * some substring of the input, a MatchResult instance representing the <b> * first </b> such match is made acessible via {@link #getMatch()}. If you * want to access subsequent matches you should either use a * PatternMatcherInput object or use the offset information in the * MatchResult to create a substring representing the remaining input. Using * the MatchResult offset information is the recommended method of obtaining * the parts of the string preceeding the match and following the match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param input * The String to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final String input, final Pattern pattern) { return contains(input.toCharArray(), pattern); } /** * Determines if a string (represented as a char[]) contains a pattern. If * the pattern is matched by some substring of the input, a MatchResult * instance representing the <b> first </b> such match is made acessible via * {@link #getMatch()}. If you want to access subsequent matches you should * either use a PatternMatcherInput object or use the offset information in * the MatchResult to create a substring representing the remaining input. * Using the MatchResult offset information is the recommended method of * obtaining the parts of the string preceeding the match and following the * match. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * * @param in * The char[] to test for a match. * @param pattern * The Perl5Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final char[] in, final Pattern pattern) { char[] input = in.clone(); final Perl5Pattern expression = (Perl5Pattern) pattern; this.__originalInput = input; if (expression._isCaseInsensitive) { input = _toLower(input); } return __interpret(expression, input, 0, input.length, 0); } private static final int __DEFAULT_LAST_MATCH_END_OFFSET = -100; private int __lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; /** * Determines if the contents of a PatternMatcherInput, starting from the * current offset of the input contains a pattern. If a pattern match is * found, a MatchResult instance representing the <b>first</b> such match is * made acessible via {@link #getMatch()}. The current offset of the * PatternMatcherInput is set to the offset corresponding to the end of the * match, so that a subsequent call to this method will continue searching * where the last call left off. You should remember that the region between * the begin and end offsets of the PatternMatcherInput are considered the * input to be searched, and that the current offset of the * PatternMatcherInput reflects where a search will start from. Matches * extending beyond the end offset of the PatternMatcherInput will not be * matched. In other words, a match must occur entirely between the begin * and end offsets of the input. See <code>PatternMatcherInput</code> for * more details. * <p> * As a side effect, if a match is found, the PatternMatcherInput match * offset information is updated. See the * <code>PatternMatcherInput.setMatchOffsets(int, int)</code> method for * more details. * <p> * The pattern must be a Perl5Pattern instance, otherwise a * ClassCastException will be thrown. You are not required to, and indeed * should NOT try to (for performance reasons), catch a ClassCastException * because it will never be thrown as long as you use a Perl5Pattern as the * pattern parameter. * <p> * This method is usually used in a loop as follows: <blockquote> * * <pre> * PatternMatcher matcher; * PatternCompiler compiler; * Pattern pattern; * PatternMatcherInput input; * MatchResult result; * * compiler = new Perl5Compiler(); * matcher = new Perl5Matcher(); * * try { * pattern = compiler.compile(somePatternString); * } catch (MalformedPatternException e) { * System.err.println(&quot;Bad pattern.&quot;); * System.err.println(e.getMessage()); * return; * } * * input = new PatternMatcherInput(someStringInput); * * while (matcher.contains(input, pattern)) { * result = matcher.getMatch(); * // Perform whatever processing on the result you want. * } * * </pre> * * </blockquote> * <p> * * @param input * The PatternMatcherInput to test for a match. * @param pattern * The Pattern to be matched. * @return True if the input contains a pattern match, false otherwise. * @exception ClassCastException * If a Pattern instance other than a Perl5Pattern is passed * as the pattern parameter. */ @Override public boolean contains(final PatternMatcherInput input, final Pattern pattern) { char[] inp; Perl5Pattern expression; boolean matchFound; // if(input.length() > 0) { // We want to allow a null string to match at the end of the input // which is why we don't check endOfInput. Not sure if this is a // safe thing to do or not. if (input._currentOffset > input._endOffset) { return false; } // } /* * else if(input._endOfInput()) return false; */ expression = (Perl5Pattern) pattern; this.__originalInput = input._originalBuffer; // Todo: // Really should only reduce to lowercase that part of the // input that is necessary, instead of the whole thing. // Adjust MatchResult offsets accordingly. Actually, pass an adjustment // value to __interpret. this.__originalInput = input._originalBuffer; if (expression._isCaseInsensitive) { if (input._toLowerBuffer == null) { input._toLowerBuffer = _toLower(this.__originalInput); } inp = input._toLowerBuffer; } else { inp = this.__originalInput; } this.__lastMatchInputEndOffset = input.getMatchEndOffset(); matchFound = __interpret(expression, inp, input._beginOffset, input._endOffset, input._currentOffset); if (matchFound) { input.setCurrentOffset(this.__endMatchOffsets[0]); input.setMatchOffsets(this.__beginMatchOffsets[0], this.__endMatchOffsets[0]); } else { input.setCurrentOffset(input._endOffset + 1); } // Restore so it doesn't interfere with other unrelated matches. this.__lastMatchInputEndOffset = __DEFAULT_LAST_MATCH_END_OFFSET; return matchFound; } /** * Fetches the last match found by a call to a matches() or contains() * method. If you plan on modifying the original search input, you must call * this method BEFORE you modify the original search input, as a lazy * evaluation technique is used to create the MatchResult. This reduces the * cost of pattern matching when you don't care about the actual match and * only care if the pattern occurs in the input. Otherwise, a MatchResult * would be created for every match found, whether or not the MatchResult * was later used by a call to getMatch(). * <p> * * @return A MatchResult instance containing the pattern match found by the * last call to any one of the matches() or contains() methods. If * no match was found by the last call, returns null. */ @Override public MatchResult getMatch() { if (!this.__lastSuccess) { return null; } if (this.__lastMatchResult == null) { __setLastMatchResult(); } return this.__lastMatchResult; } }
venanciolm/afirma-ui-miniapplet_x_x
afirma_ui_miniapplet/src/main/java/org/apache/oro/text/regex/Perl5Matcher.java
Java
mit
62,090
--- layout: post title: "Sourdough Cinnamon Rolls" date: 2014-07-21 07:30:37 -0600 comments: true categories: - buddy image: http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg alt-image: http%3A%2F%2Fanthonyrotio.com%2Frotiofood%2F2014-07-21%2Frolls_1.jpg author: rotio keywords: sourdough, cinnamon rolls, buns, cinnamon, budweiser, breakfast description: Sourdough cinnamon rolls made with Budweiser sourdough starter external-url: http%3A%2F%2Frotiofood.com%2Fblog%2F2014%2F07%2F21%2Fsourdough-cinnamon-rolls%2F twitter-text: Sourdough%20cinnamon%20rolls%20made%20with%20Budweiser%20sourdough%20starter buddy: 1 --- <!-- more --> <img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" /> <a href="https://plus.google.com/107103100819027957630?rel=author" style="display:none">{{page.author }}</a> <h4>Story</b> </h4> <div> <p> <img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_baked.jpg"/><br/>The smell of cinnamon rolls in the morning is nearly as powerful as the smell of bacon in the morning. It's that magic spell that seems to automatically levitate you out of bed. My mom used to make these when my siblings and I were little as an occasional treat. Katie and I decided to take a crack at making them homemade with our <a target="_blank" href="http://www.rotiofood.com/buddy/">Buddy Sourdough.</a> The smell of cinnamon wafting through the apartment brought us right back to when we were kids. The simple answer to your question is, "Yes, Budweiser can make cinnamon buns even better." </p> </div> <h4>Recipe</b> </h4> <div itemscope itemtype="http://schema.org/Recipe" > <h4 itemprop="name">Sourdough Cinnamon Rolls</h4> <br /> July 21, 2014 <center> <img itemprop="image" width="200px" src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" /> <br /><span itemprop="description">{{page.description }}</span><br /> <br />Prep time: <time datetime="PT2H10M" itemprop="prepTime">2h10m</time> <br />Cook time: <time datetime="PT0H25M" itemprop="cookTime">25m</time> <br />Total time: <time datetime="PT2H35M" itemprop="totalTime">2h35m</time> <br />Yield: <span itemprop="recipeYield">about 12 rolls</span> <br/> <h5>Ingredients:</h5> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name"><a href="http://www.rotiofood.com/blog/2014/07/15/sourdough-hamburger-buns/">Sourdough Hamburger Bun Dough</a></span>: <span itemprop="amount">1/2 batch</span>, prepared through the first rise </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Butter</span>: <span itemprop="amount">6 tbl</span>, softened </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Sugar</span>: <span itemprop="amount">1/2 c</span> </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Cinnamon</span>: <span itemprop="amount">1/4 c</span> </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Powdered Sugar</span>: <span itemprop="amount">1/4 c</span> </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Milk</span>: <span itemprop="amount">splash</span> </span><br /> <span itemprop="ingredients" itemscope itemtype="http://schema.org/ingredients"> <span itemprop="name">Vanilla</span>: <span itemprop="amount">1 tsp</span> </span><br /> <br /><h5>Directions:</h5> <div itemprop="recipeInstructions"> 1. Roll out dough to a rectangular shape between 1/2 and 1 inch thick.<br/> 2. Spread butter all over dough.<br/> 3. Sprinkle with sugar and cinnamon.<br/> 4. Roll dough as shown in photo. Cut into 1" slices. Place in greased pan with 1/4 inch in between each roll.<br/> 5. Allow to rise until doubled, about an hour. Tip: Heat a bowl of water in the microwave for 2 minutes. Remove bowl from microwave. Place dough in microwave and shut door to rise in warm humid environment.<br/> 6. Preheat oven to 350 F. <br/> 7. Toss a few ice cubes into bottom of oven. Bake rolls for 25 minutes or until risen and golden brown. Remove from oven.<br/> 8. Mix last three ingredients, adding milk a splash at a time to achieve an icing consistency.<br/> 9. Top hot rolls with icing, serve immediately.<br/></div> <br/> <br /> <center><div><img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_rolling.jpg" /> <em style="text-align:center;font-size:.8em">Dough being rolled up with butter, cinnamon, and sugar already added.</em> <br/><br/><br/> <img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_raw.jpg" /> <em style="text-align:center;font-size:.8em">Rolls cut and spaced, before the rise.</em> <br/><br/><br/> <img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_baked.jpg"/> <em style="text-align:center;font-size:.8em">Rolls baked and ready to be iced.</em> <br/><br/><br/> <img src="http://anthonyrotio.com/rotiofood/2014-07-21/rolls_1.jpg" /> <em style="text-align:center;font-size:.8em">The final product - Budweiser Sourdough Cinnamon Rolls.</em> <br/><br/><br/> </div></center> </div>
arotio/arotio.github.io
_posts/2014-07-21-sourdough-cinnamon-rolls.markdown
Markdown
mit
5,348
rfstats ====== statistics for random fields ---------------------------- Several different methods for estimating correlation functions for random fields are included.
aluchies/rfstats
README.md
Markdown
mit
169
import path from 'path'; import {runScheduler} from './scheduler'; import logger from '../util/logger'; import dotenv from 'dotenv'; import {loadConfig} from '../../config'; import {initQueue} from './pipeline.queue'; logger.info(" _____ _ _ _ _ _ _ _ _ "); logger.info("| | |_|___| | | |_| |_|_|"); logger.info("| --| | | | | | | | '_| |"); logger.info("|_____|_|_|_|_|_____|_|_,_|_|"); logger.info('ClinWiki data pipeline starting...'); const envPath = path.resolve(process.cwd()+'/../', '.env'); logger.info('Loading .env from '+envPath); dotenv.config({ path: envPath }); loadConfig(); logger.info('Initializing pipeline queue'); initQueue(); logger.info('Running...'); runScheduler();
clinwiki-org/clinwiki
api/src/pipeline/worker.js
JavaScript
mit
747
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>org.robolectric.util.reflector Class Hierarchy</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.robolectric.util.reflector Class Hierarchy"; } } catch(err) { } //--> var pathtoroot = "../../../../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.4 | <a href="/" target="_top"><img src="http://robolectric.org/images/logo-with-bubbles-down.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/robolectric/util/inject/package-tree.html">Prev</a></li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/robolectric/util/reflector/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><span>SEARCH:&nbsp;</span> <input type="text" id="search" value=" " disabled="disabled"> <input type="reset" id="reset" value=" " disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> <div class="header"> <h1 class="title">Hierarchy For Package org.robolectric.util.reflector</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li class="circle">java.lang.<a href="https://developer.android.com/reference/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Reflector.html" title="class in org.robolectric.util.reflector"><span class="typeNameLink">Reflector</span></a></li> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/UnsafeAccess.html" title="class in org.robolectric.util.reflector"><span class="typeNameLink">UnsafeAccess</span></a></li> </ul> </li> </ul> <h2 title="Annotation Type Hierarchy">Annotation Type Hierarchy</h2> <ul> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Accessor.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">Accessor</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/ForType.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">ForType</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/Static.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">Static</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li> <li class="circle">org.robolectric.util.reflector.<a href="../../../../org/robolectric/util/reflector/WithType.html" title="annotation in org.robolectric.util.reflector"><span class="typeNameLink">WithType</span></a> (implements java.lang.annotation.<a href="https://developer.android.com/reference/java/lang/annotation/Annotation.html?is-external=true" title="class or interface in java.lang.annotation">Annotation</a>)</li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.4 | <a href="/" target="_top"><img src="http://robolectric.org/images/logo-with-bubbles-down.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/robolectric/util/inject/package-tree.html">Prev</a></li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/robolectric/util/reflector/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
robolectric/robolectric.github.io
javadoc/4.4/org/robolectric/util/reflector/package-tree.html
HTML
mit
8,345
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; 384c21a2-fb1a-4ecb-afc2-c2ac93c6b43f </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#iso-relax">iso-relax</a></strong></td> <td class="text-center">99.48 %</td> <td class="text-center">99.48 %</td> <td class="text-center">100.00 %</td> <td class="text-center">99.48 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="iso-relax"><h3>iso-relax</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Diagnostics.DebuggableAttribute</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Boolean,System.Boolean)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.SerializationInfo</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Remove serialization constructors on custom Exception types</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
kuhlenh/port-to-core
Reports/wo/woodstox.4.1.4/iso-relax-net.html
HTML
mit
12,502
<?php /* Unsafe sample input : get the field userData from the variable $_GET via an object Uses a special_chars_filter via filter_var function construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS); $tainted = $sanitized ; $query = sprintf("cat '%s'", $tainted); //flaw $ret = system($query); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_78/unsafe/CWE_78__object-classicGet__func_FILTER-CLEANING-special_chars_filter__cat-sprintf_%s_simple_quote.php
PHP
mit
1,514
describe VagrantHyperV do it 'should have a version number' do VagrantHyperV::VERSION.should_not be_nil end it 'should do something useful' do false.should be_true end end
tehgeekmeister/VagrantHyperV
spec/VagrantHyperV_spec.rb
Ruby
mit
189
import primes as py def lcm(a, b): return a * b / gcd(a, b) def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a # Returns two integers x, y such that gcd(a, b) = ax + by def egcd(a, b): if a == 0: return (0, 1) else: y, x = egcd(b % a, a) return (x - (b // a) * y, y) # Returns an integer x such that ax = 1(mod m) def modInverse(a, m): x, y = egcd(a, m) if gcd(a, m) == 1: return x % m # Reduces linear congruence to form x = b(mod m) def reduceCongr(a, b, m): gcdAB = gcd(a, b) a /= gcdAB b /= gcdAB m /= gcd(gcdAB, m) modinv = modInverse(a, m) b *= modinv return (1, b, m) # Returns the incongruent solutions to the linear congruence ax = b(mod m) def linCongr(a, b, m): solutions = set() if (b % gcd(a, m) == 0): numSols = gcd(a, m) sol = (b * egcd(a, m)[0] / numSols) % m for i in xrange(0, numSols): solutions.add((sol + m * i / numSols) % m) return solutions # Uses the Chinese Remainder Theorem to solve a system of linear congruences def crt(congruences): x = 0 M = 1 for i in xrange(len(congruences)): M *= congruences[i][2] congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2]) for j in xrange(len(congruences)): m = congruences[j][2] if gcd(m, M/m) != 1: return None x += congruences[j][1] * modInverse(M/m, m) * M / m return x % M # Returns the incongruent solution to any system of linear congruences def linCongrSystem(congruences): newCongruences = [] for i in xrange(len(congruences)): congruences[i] = reduceCongr(congruences[i][0], congruences[i][1], congruences[i][2]) # Tests to see whether the system is solvable for j in xrange(len(congruences)): if congruences[i] != congruences[j]: if (congruences[i][1] - congruences[j][1]) % gcd(congruences[i][2], congruences[j][2]) != 0: return None # Splits moduli into prime powers pFactor = py.primeFactorization(congruences[i][2]) for term in pFactor: newCongruences.append((1, congruences[i][1], term[0] ** term[1])) # Discards redundant congruences newCongruences = sorted(newCongruences, key=lambda x: x[2], reverse = True) finalCongruences = [] for k in xrange(len(newCongruences)): isRedundant = False for l in xrange(0, k): if newCongruences[l][2] % newCongruences[k][2] == 0: isRedundant = True if not isRedundant: finalCongruences.append(newCongruences[k]) return crt(finalCongruences) # Returns incongruents solutions to a polynomial congruence def polyCongr(coefficients, m): solutions = [] for i in xrange(m): value = 0 for degree in xrange(len(coefficients)): value += coefficients[degree] * (i ** (len(coefficients) - degree - 1)) if value % m == 0: solutions.append(i) return solutions
ioguntol/NumTy
numty/congruences.py
Python
mit
3,551
package com.aokyu.service; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
aoq/resident-background-service
app/src/androidTest/java/com/aokyu/service/ApplicationTest.java
Java
mit
348
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using PowerLib.System; using PowerLib.System.Collections; using PowerLib.System.IO; using PowerLib.System.IO.Streamed.Typed; using PowerLib.System.Numerics; using PowerLib.System.Data.SqlTypes.Numerics; namespace PowerLib.System.Data.SqlTypes.Collections { [SqlUserDefinedType(Format.UserDefined, Name = "GradAngleCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)] public sealed class SqlGradAngleCollection : INullable, IBinarySerialize { private List<GradAngle?> _list; #region Contructors public SqlGradAngleCollection() { _list = null; } public SqlGradAngleCollection(IEnumerable<GradAngle?> coll) { _list = coll != null ? new List<GradAngle?>(coll) : null; } private SqlGradAngleCollection(List<GradAngle?> list) { _list = list; } #endregion #region Properties public List<GradAngle?> List { get { return _list; } set { _list = value; } } public static SqlGradAngleCollection Null { get { return new SqlGradAngleCollection(); } } public bool IsNull { get { return _list == null; } } public SqlInt32 Count { get { return _list != null ? _list.Count : SqlInt32.Null; } } #endregion #region Methods public static SqlGradAngleCollection Parse(SqlString s) { if (s.IsNull) return Null; return new SqlGradAngleCollection(SqlFormatting.ParseCollection<GradAngle?>(s.Value, t => !t.Equals(SqlFormatting.NullText, StringComparison.InvariantCultureIgnoreCase) ? SqlGradAngle.Parse(t).Value : default(GradAngle?))); } public override String ToString() { return SqlFormatting.Format(_list, t => (t.HasValue ? new SqlGradAngle(t.Value) : SqlGradAngle.Null).ToString()); } [SqlMethod(IsMutator = true)] public void Clear() { _list.Clear(); } [SqlMethod(IsMutator = true)] public void AddItem(SqlGradAngle value) { _list.Add(value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void InsertItem(SqlInt32 index, SqlGradAngle value) { _list.Insert(index.IsNull ? _list.Count : index.Value, value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void RemoveItem(SqlGradAngle value) { _list.Remove(value.IsNull ? default(GradAngle?) : value.Value); } [SqlMethod(IsMutator = true)] public void RemoveAt(SqlInt32 index) { if (index.IsNull) return; _list.RemoveAt(index.Value); } [SqlMethod(IsMutator = true)] public void SetItem(SqlInt32 index, SqlGradAngle value) { if (index.IsNull) return; _list[index.Value] = value.IsNull ? default(GradAngle?) : value.Value; } [SqlMethod(IsMutator = true)] public void AddRange(SqlGradAngleCollection coll) { if (coll.IsNull) return; _list.AddRange(coll._list); } [SqlMethod(IsMutator = true)] public void AddRepeat(SqlGradAngle value, SqlInt32 count) { if (count.IsNull) return; _list.AddRepeat(value.IsNull ? default(GradAngle?) : value.Value, count.Value); } [SqlMethod(IsMutator = true)] public void InsertRange(SqlInt32 index, SqlGradAngleCollection coll) { if (coll.IsNull) return; int indexValue = !index.IsNull ? index.Value : _list.Count; _list.InsertRange(indexValue, coll._list); } [SqlMethod(IsMutator = true)] public void InsertRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count) { if (count.IsNull) return; int indexValue = !index.IsNull ? index.Value : _list.Count; _list.InsertRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, count.Value); } [SqlMethod(IsMutator = true)] public void SetRange(SqlInt32 index, SqlGradAngleCollection range) { if (range.IsNull) return; int indexValue = index.IsNull ? _list.Count - Comparable.Min(_list.Count, range._list.Count) : index.Value; _list.SetRange(indexValue, range.List); } [SqlMethod(IsMutator = true)] public void SetRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; _list.SetRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, countValue); } [SqlMethod(IsMutator = true)] public void RemoveRange(SqlInt32 index, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; _list.RemoveRange(indexValue, countValue); } [SqlMethod] public SqlGradAngle GetItem(SqlInt32 index) { return !index.IsNull && _list[index.Value].HasValue ? _list[index.Value].Value : SqlGradAngle.Null; } [SqlMethod] public SqlGradAngleCollection GetRange(SqlInt32 index, SqlInt32 count) { int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value; int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value; return new SqlGradAngleCollection(_list.GetRange(indexValue, countValue)); } [SqlMethod] public SqlGradAngleArray ToArray() { return new SqlGradAngleArray(_list); } #endregion #region Operators public static implicit operator byte[] (SqlGradAngleCollection coll) { using (var ms = new MemoryStream()) using (new NulInt32StreamedCollection(ms, SizeEncoding.B4, true, coll._list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(coll._list.Count), true, false)) return ms.ToArray(); } public static explicit operator SqlGradAngleCollection(byte[] buffer) { using (var ms = new MemoryStream(buffer)) using (var sa = new NulInt32StreamedArray(ms, true, false)) return new SqlGradAngleCollection(sa.Select(t => t.HasValue ? new GradAngle(t.Value) : default(GradAngle?)).ToList()); } #endregion #region IBinarySerialize implementation public void Read(BinaryReader rd) { using (var sa = new NulInt32StreamedArray(rd.BaseStream, true, false)) _list = sa.Select(t => !t.HasValue ? default(GradAngle?) : new GradAngle(t.Value)).ToList(); } public void Write(BinaryWriter wr) { using (var ms = new MemoryStream()) using (var sa = new NulInt32StreamedArray(ms, SizeEncoding.B4, true, _list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(_list.Count), true, false)) wr.Write(ms.GetBuffer(), 0, (int)ms.Length); } #endregion } }
vaseug/PowerLib
PowerLib.System.Data.SqlTypes/Collections/SqlGradAngleCollection.cs
C#
mit
7,128
require 'spec_helper' describe Pagerage::IncidentsParser do before(:each) do Pagerage::Incident.delete end let(:incidents_json) { File.read(File.dirname(__FILE__) + '/incidents_sample.json') } let(:incidents_data) { JSON.parse(incidents_json) } let(:parser) { Pagerage::IncidentsParser.new(incidents_json) } it 'should set data attr when created' do parser.data.should eq(incidents_data) end it 'should generate two incidents from the sample data' do parser.run! Pagerage::Incident.count.should eq(2) end end
gorsuch/pagerage
spec/pagerage/incidents_parser_spec.rb
Ruby
mit
546
a = a # e 4 a = 1 # 0 int l = [a] # 0 [int] d = {a:l} # 0 {int:[int]} s = "abc" c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int l2 = [range(i) for i in d] # 0 [[int]] y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)] b = 1 # 0 int if 0: b = '' # 4 str else: b = str(b) # 4 str # 12 int r = 0 # 0 int if r: # 3 int r = str(r) # 4 str # 12 int r # 0 <int|str> l = range(5) # 0 [int] l2 = l[2:3] # 0 [int] x = l2[1] # 0 int k = 1() # 0 <unknown> # e 4 del k k # e 0 l = [] # 0 [int] x = 1 # 0 int while x: # 6 int l = [] # 4 [int] l.append(1) # 0 [int] # 2 (int) -> None l = [1, 2] # 0 [int] l2 = [x for x in l] # 0 [<int|str>] l2.append('') # 0 [<int|str>] s = str() # 0 str s2 = str(s) # 0 str s3 = repr() # e 5 # 0 str s4 = repr(s) # 0 str x = 1 if [] else '' # 0 <int|str> l = [1] # 0 [<int|str>] l2 = [''] # 0 [str] l[:] = l2 # 0 [<int|str>] b = 1 < 2 < 3 # 0 bool l = sorted(range(5), key=lambda x:-x) # 0 [int] d = {} # 0 {<bool|int>:<int|str>} d1 = {1:''} # 0 {int:str} d.update(d1) d[True] = 1 d # 0 {<bool|int>:<int|str>} l = [] # 0 [int] l1 = [] # 0 [<unknown>] l.extend(l1) l.append(2) l = [] # 0 [<[str]|int>] l1 = [[]] # 0 [[str]] l.extend(l1) l[0].append('') # e 0 l.append(1) l = [] # 0 [[<int|str>]] l2 = [1] # 0 [int] l3 = [''] # 0 [str] l.append(l2) l.append(l3) for i, s in enumerate("aoeu"): # 4 int # 7 str pass x = 1 # 0 int y = x + 1.0 # 0 float y << 1 # e 0 l = [1, 1.0] # 0 [float] 1.0 in [1] # e 0 x = `1` # 0 str def f(): x = `1` # 4 str d = dict(a=1) # 0 {str:int} l = list() # 0 [<unknown>] i = int(1) # 0 int i = int(1.2) # 0 int i = abs(1) # 0 int i = abs(1.0) # 0 float d = dict() # 0 {int:int} d[1] = 2 d2 = dict(d) # 0 {<int|str>:<int|str>} d2[''] = '' d3 = dict([(1,2)]) # 0 {int:int} d4 = dict(a=1) # 0 {str:int}
kmod/icbd
icbd/type_analyzer/tests/basic.py
Python
mit
1,818
Java-essais =========== JAVA : essais de programmation 1. Déclarations de variables
mikeleyeti/Java-essais
README.md
Markdown
mit
87
<?php //var_dump($games) ?> <?php $this->load->view('includes/tables-head') ?> <body class="fixed-header" ng-app="app" ng-controller="gameCtrl"> <?php $this->load->view('admin/admin-nav') ?> <div class="page-container"> <?php $this->load->view('admin/admin-header') ?> <div class="page-content-wrapper "> <div class="content "> <div class="jumbotron" data-pages="parallax"> <div class="container-fluid container-fixed-lg sm-p-l-20 sm-p-r-20"> <div class="inner"> <ul class="breadcrumb"> <li><p>Dashboard</p></li> <li><a href="#" class="active">Game</a></li> <li><a href="#" class="active">New</a></li> </ul> </div> </div> </div> <div class="container-fluid container-fixed-lg"> <div class="panel"> <ul class="nav nav-tabs nav-tabs-linetriangle" data-init-reponsive-tabs="dropdownfx"> <li class="active"> <a data-toggle="tab" href="#new"><span>New Game</span></a> </li> <li> <a data-toggle="tab" href="#game"><span>This Week Game</span></a> </li> </ul> <div class="tab-content"> <div class="tab-pane slide-left active" id="new"> <!-- View Branches Table start --> <div class="conatiner"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="clearfix"></div> <?php echo validation_errors(); ?> <table class="table"> <thead> <tr> <td>NUMBER</td> <td>HOME</td> <td>AWAY</td> <td>DEADLINE <small>format: (2016-04-18 11:24:00)</small></td> </tr> </thead> <tbody> <form role="form" method="post" action="<?=site_url('admin/game/create') ?>"> <?php for($i = 1; $i<=49; $i++){ ?> <tr> <td> <?=$i; ?> <input type="hidden" name="data[<?=$i; ?>][number]" value="<?=$i; ?>" /> </td> <td> <input id="home" type="text" name="data[<?=$i ?>][home]" class="form-control" required /> </td> <td> <input id="away" type="text" name="data[<?=$i ?>][away]" class="form-control" required /> </td> <td> <input type="date" class="input-sm form-control" name="data[<?=$i ?>][deadline]" placeholder="2016-04-18 11:24:00" required/> </td> </tr> <?php } ?> <?php $csrf = array( 'name' => $this->security->get_csrf_token_name(), 'hash' => $this->security->get_csrf_hash()); ?> <input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> <tr> <td> <label for="number">Week Number <small>e.g. 34</small></label> <input type="number" name="week_number" class="form-control" required placeholder="0"> </td> <td> <label for="week_start_date">Week Start Date (<small>format: 2016-04-18</small>)</label> <input type="date" name="week_start_date" class="form-control" required placeholder="2016-04-18"> </td> <td> <label for="week_start_date">Week End Date (<small>format: 2016-04-18</small>)</label> <input type="date" name="week_end_date" class="form-control" required placeholder="2016-04-18"> </td> <td> <label for="submit">Submit All Entries</label><br /> <input id="sumbit" type="submit" name="submit" value="Submit" class="btn btn-sm btn-primary"> </td> </tr> </form> </tbody> </table> <br /> </div> </div> </div> <!-- Veiw Branches Table end --> </div> <div class="tab-pane slide-left" id="game"> <!-- View Branches Table start --> <div class="conatiner"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="clearfix"></div> <table class="table table-responsive"> <thead> <tr> <td>NUMBER</td> <td >DEADLINE</td> <td>TOGGLE</td> </tr> </thead> <?php if($games): ?> <tbody> <?php foreach ($games as $row): ?> <tr> <td><?=$row->number; ?></td> <td><?=$row->deadline ?></td> <td> <?php if ($row->status == 'active'){ ?> <input type="checkbox" ng-click="toggleGame(<?=$row->number; ?>, <?=$row->week_number ?>)" id="<?=$row->number ?>"checked/> <?php }else{ ?> <input type="checkbox" disabled id="<?=$row->number ?>" /> <?php } ?> </td> </tr> <?php endforeach; ?> </tbody> <?php endif; ?> </table> </div> </div> </div> <!-- Veiw Branches Table end --> </div> </div> </div> </div> <?php $this->load->view('includes/footer-note') ?> </div> </div> <?php $this->load->view('includes/tables-footer') ?>
massivebrains/poolapp
application/views/admin/admin-game-new.php
PHP
mit
5,597
define(['js/util'], function (util) { "use strict"; var sf2 = {}; sf2.createFromArrayBuffer = function(ab) { var that = { riffHeader: null, sfbk: {} }; var ar = util.ArrayReader(ab); var sfGenerator = [ "startAddrsOffset", // 0 "endAddrsOffset", // 1 "startloopAddrsOffset", // 2 "endloopAddrsOffset", // 3 "startAddrsCoarseOffset", // 4 "modLfoToPitch", // 5 "vibLfoToPitch", // 6 "modEnvToPitch", // 7 "initialFilterFc", // 8 "initialFilterQ", // 9 "modLfoToFilterFc", // 10 "modEnvToFilterFc", // 11 "endAddrsCoarseOffset", // 12 "modLfoToVolume", // 13 "unused1", "chorusEffectsSend", // 15 "reverbEffectsSend", // 16 "pan", // 17 "unused2", "unused3", "unused4", "delayModLFO", // 21 "freqModLFO", // 22 "delayVibLFO", // 23 "freqVibLFO", // 24 "delayModEnv", // 25 "attackModEnv", // 26 "holdModEnv", // 27 "decayModEnv", // 28 "sustainModEnv", // 29 "releaseModEnv", // 30 "keynumToModEnvHold", // 31 "keynumToModEnvDecay", // 32 "delayVolEnv", // 33 "attackVolEnv", // 34 "holdVolEnv", // 35 "decayVolEnv", // 36 "sustainVolEnv", // 37 "releaseVolEnv", // 38 "keynumToVolEnvHold", // 39 "keynumToVolEnvDecay", // 40 "instrument", // 41: PGEN Terminator "reserved1", "keyRange", // 43 "velRange", // 44 "startloopAddrsCoarseOffset", // 45 "keynum", // 46 "velocity", // 47 "initialAttenuation", // 48 "reserved2", "endloopAddrsCoarseOffset", // 50 "coarseTune", // 51 "fineTune", // 52 "sampleID", // 53: IGEN Terminator "sampleModes", // 54 "reserved3", "scaleTuning", // 56 "exclusiveClass", // 57 "overridingRootKey", // 58 "unused5", "endOper" ]; that.parseHeader = function () { // read RIFF header that.riffHeader = parseHeader(); that.size = that.riffHeader.length + 8; // read level1 header ar.seek(that.riffHeader.headPosition); that.sfbk = {}; that.sfbk.ID = ar.readStringF(4); // read level2 header that.sfbk.INFO = parseHeader(); // read level3 header // 3.1 INFO ar.seek(that.sfbk.INFO.headPosition); that.sfbk.INFO.ID = ar.readStringF(4); that.sfbk.INFO.child = {}; while(ar.position() < that.sfbk.INFO.headPosition + that.sfbk.INFO.length) { var head = parseHeader(); that.sfbk.INFO.child[head.ID] = head; } // 3.2 sdta ar.seek(that.sfbk.INFO.headPosition + that.sfbk.INFO.padLength); that.sfbk.sdta = parseHeader(); ar.seek(that.sfbk.sdta.headPosition); that.sfbk.sdta.ID = ar.readStringF(4); that.sfbk.sdta.child = {}; while(ar.position() < that.sfbk.sdta.headPosition + that.sfbk.sdta.length) { head = parseHeader(); that.sfbk.sdta.child[head.ID] = head; } // 3.3 pdta ar.seek(that.sfbk.sdta.headPosition + that.sfbk.sdta.padLength); that.sfbk.pdta = parseHeader(); ar.seek(that.sfbk.pdta.headPosition); that.sfbk.pdta.ID = ar.readStringF(4); that.sfbk.pdta.child = {}; while(ar.position() < that.sfbk.pdta.headPosition + that.sfbk.pdta.length) { head = parseHeader(); that.sfbk.pdta.child[head.ID] = head; } // read level4 data // 4.1 PHDR data var phdr = that.sfbk.pdta.child.phdr; phdr.data = []; ar.seek(phdr.headPosition); while(ar.position() < phdr.headPosition + phdr.length) { var data = {}; data.presetName = ar.readStringF(20); data.preset = ar.readUInt16(); data.bank = ar.readUInt16(); data.presetBagNdx = ar.readUInt16(); data.library = ar.readUInt32(); data.genre = ar.readUInt32(); data.morphology = ar.readUInt32(); phdr.data.push(data); } // set placeholder that.sfbk.pdta.child.pbag.data = []; that.sfbk.pdta.child.pgen.data = []; that.sfbk.pdta.child.pmod.data = []; that.sfbk.pdta.child.inst.data = []; that.sfbk.pdta.child.ibag.data = []; that.sfbk.pdta.child.igen.data = []; that.sfbk.pdta.child.imod.data = []; that.sfbk.pdta.child.shdr.data = []; }; that.readPreset = function(n) { var phdr = that.sfbk.pdta.child.phdr; var pbag = that.sfbk.pdta.child.pbag; var r = { presetName: phdr.data[n].presetName, preset: phdr.data[n].preset, bank: phdr.data[n].bank, gen: [], mod: [] } // PBAGs var pgen_global = { keyRange: { lo: 0, hi: 127 }, velRange: { lo: 1, hi: 127 } }; var pmod_global = []; for(var i = phdr.data[n].presetBagNdx; i < phdr.data[n + 1].presetBagNdx; i++) { var pbag0 = parsePBAG1(ar, pbag, i); var pbag1 = parsePBAG1(ar, pbag, i + 1); var pmod = readPMOD1(pbag0.modNdx, pbag1.modNdx, pmod_global); var pmod_local = Array.prototype.concat(pmod_global, pmod); var pgen = readPGEN1(pbag0.genNdx, pbag1.genNdx, pgen_global, pmod_local); if(pgen["instrument"] === undefined) { pgen_global = pgen; pmod_global = pmod; } else { r.gen = Array.prototype.concat(r.gen, pgen.instrument.ibag.igen); r.mod = Array.prototype.concat(r.mod, pgen.instrument.ibag.imod); } // r.mod.push(readPMOD1(pbag0.modNdx, pbag1.modNdx)); } return r; }; that.enumPresets = function() { var p = []; var phdr = that.sfbk.pdta.child.phdr; phdr.data.forEach(function(ph) { p.push(ph.presetName); }); return p; }; that.readSDTA = function(pos) { ar.seek(that.sfbk.sdta.child.smpl.headPosition + pos * 2); return ar.readInt16() / 32768; } that.readSDTAChunk = function(b, e) { return new Int16Array(new Uint8Array(ar.subarray( that.sfbk.sdta.child.smpl.headPosition + b * 2, that.sfbk.sdta.child.smpl.headPosition + e * 2 )).buffer); } var readPGEN1 = function(b, e, g, gm) { var pgen = that.sfbk.pdta.child.pgen; var global = _.O(g, true); var global_m = _.O(gm, true); var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { var r = parsePGEN1(ar, pgen, i); if(r.inst == "instrument") { global = _.O(result, true); result[r.inst] = readINST1(r.genAmount, global, global_m); } else { result[r.inst] = r.genAmount; } } } return result; }; var readPMOD1 = function(b, e, g) { var pmod = that.sfbk.pdta.child.pmod; var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { result.push(parseMOD1(ar, pmod, i)); } } return result; }; var readINST1 = function(i, g, gm) { var inst = that.sfbk.pdta.child.inst; var ibag = that.sfbk.pdta.child.ibag; var inst0 = parseINST1(ar, inst, i); var inst1 = parseINST1(ar, inst, i + 1); var r = { "instName": inst0.instName }; var global = _.O(g, true); var global_m = _.O(gm, true); // IBAGs r.ibag = { igen: [], imod: [] }; for(var i = inst0.instBagNdx; i < inst1.instBagNdx; i++) { var ibag0 = parseIBAG1(ar, ibag, i); var ibag1 = parseIBAG1(ar, ibag, i + 1); var igen = readIGEN1(ibag0.instGenNdx, ibag1.instGenNdx, global); var imod = readIMOD1(ibag0.instModNdx, ibag1.instModNdx, global_m); if(igen["sampleID"] === undefined) { // global parameter global = igen; global_m = imod; } else { r.ibag.igen.push(igen); r.ibag.imod.push(imod); } } return r; } var readIGEN1 = function(b, e, g) { var igen = that.sfbk.pdta.child.igen; var result = _.O(g, true); for(var i = b; i < e; i++) { var r = parseIGEN1(ar, igen, i); result[r.inst] = r.genAmount; if(r.inst == "sampleID") { result.shdr = readSHDR1(r.genAmount); } } return result; }; var readIMOD1 = function(b, e, g) { var imod = that.sfbk.pdta.child.imod; var result = _.O(g, true); if(b != e) { for(var i = b; i < e; i++) { result.push(parseMOD1(ar, imod, i)); } } return result; }; var readSHDR1 = function(i) { var shdr = that.sfbk.pdta.child.shdr; var r = parseSHDR1(ar, shdr, i); r.end -= r.start; r.startloop -= r.start; r.endloop -= r.start; r.sample = new Float32Array(r.end); ar.seek(that.sfbk.sdta.child.smpl.headPosition + r.start * 2) for(var j = 0; j < r.end; j++) { r.sample[j] = ar.readInt16() / 32768; } r.start = 0; return r; }; var parseHeader = function(){ var h = {}; h.ID = ar.readStringF(4); h.length = ar.readUInt32(); h.padLength = h.length % 2 == 1 ? h.length + 1 : h.length; h.headPosition = ar.position(); ar.seek(ar.position() + h.padLength); return h; }; var parsePBAG1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genNdx = ar.readUInt16(); data.modNdx = ar.readUInt16(); root.data[i] = data; return data; }; var parsePGEN1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genOper = ar.readUInt16(); data.inst = sfGenerator[data.genOper]; if(data.inst == 'keyRange' || data.inst == 'velRange' || data.inst == 'keynum' || data.inst == 'velocity') { data.genAmount = {}; data.genAmount.lo = ar.readUInt8(); data.genAmount.hi = ar.readUInt8(); } else { data.genAmount = ar.readInt16(); } root.data[i] = data; return data; }; var parseMOD1 = function(ar, root, i) { ar.seek(root.headPosition + i * 10); var data = {}; data.modSrcOper = { }; data.modSrcOper.index = ar.readUInt8(); data.modSrcOper.type = ar.readUInt8(); data.modDestOper = ar.readUInt16(); data.modDestInst = sfGenerator[data.modDestOper]; data.modAmount = ar.readInt16(); data.modAmtSrcOper = {}; data.modAmtSrcOper.index = ar.readUInt8(); data.modAmtSrcOper.type = ar.readUInt8(); data.modTransOper = ar.readUInt16(); root.data[i] = data; return data; }; var parseINST1 = function(ar, root, i) { ar.seek(root.headPosition + i * 22); var data = {}; data.instName = ar.readStringF(20); data.instBagNdx = ar.readUInt16(); root.data.push(data); return data; }; var parseIBAG1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.instGenNdx = ar.readUInt16(); data.instModNdx = ar.readUInt16(); root.data.push(data); return data; }; var parseIGEN1 = function(ar, root, i) { ar.seek(root.headPosition + i * 4); var data = {}; data.genOper = ar.readUInt16(); data.inst = sfGenerator[data.genOper]; if(data.inst == 'keyRange' || data.inst == 'velRange' || data.inst == 'keynum' || data.inst == 'velocity') { data.genAmount = {}; data.genAmount.lo = ar.readUInt8(); data.genAmount.hi = ar.readUInt8(); } else { data.genAmount = ar.readInt16(); } root.data.push(data); return data; }; var parseSHDR1 = function(ar, root, i) { ar.seek(root.headPosition + i * 46); var data = {}; data.sampleName = ar.readStringF(20); data.start = ar.readUInt32(); data.end = ar.readUInt32(); data.startloop = ar.readUInt32(); data.endloop = ar.readUInt32(); data.sampleRate = ar.readUInt32(); data.originalPitch = ar.readUInt8(); data.pitchCorrection = ar.readInt8(); data.sampleLink = ar.readUInt16(); data.sampleType = ar.readUInt16(); root.data.push(data); return data; }; return that; } return sf2; });
ruly-rudel/tipsound
js/sf2.js
JavaScript
mit
16,386
=begin <recording pid="" cookie="" stamp="" agent=""> <record id="" stamp="" status="" method="" url="" request-time=""> <header name="" value=""/> <body><![CDATA[HTML OR WHATEVER HERE]]></body> <param name="" value=""/> <multipart-reference name="" file-path=""/> </record> </recording> =end module DejaVuNS class Recording def self.find_by_identifier(ident) DejaVuNS.root.recording.each do |rec| return rec if rec.cookie == ident end nil end def self.find_by_pid(pid) rec = nil DejaVuNS.transaction do rec = DejaVuNS.root.recording[pid] end rec end def self.all_recordings recordings = [] DejaVuNS.transaction do DejaVuNS.root.recording.each do |rec| recordings << rec end end recordings end end end
kuccello/deja-vu
lib/deja-vu/model/recording.rb
Ruby
mit
982
import static org.junit.Assert.*; import java.util.List; import org.junit.Test; public class IdParserTest { @Test public void testListParser() { String testMedList = "{1;3;9}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(3, ids.size()); assertEquals(new Integer(1), ids.get(0)); assertEquals(new Integer(3), ids.get(1)); assertEquals(new Integer(9), ids.get(2)); } @Test public void testEmptyListParser() { String testMedList = "{}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(0, ids.size()); } @Test public void testSingletonListParser() { String testMedList = "{1}"; List<Integer> ids = IdParser.parse(testMedList); assertEquals(1, ids.size()); assertEquals(new Integer(1), ids.get(0)); } }
UMM-CSci/Coding-dojos
PatientRecordsKata/IdParserTest.java
Java
mit
807
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Archos</td><td>A101C</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 [family] => Archos A101C [brand] => Archos [model] => A101C ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Android 4.0</td><td>WebKit </td><td>Android 1.1</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.023</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.1\.1.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?1.1* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 1.1 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.005</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-42bb56ba-b834-47c5-bea0-c0270e9ab371">Detail</a> <!-- Modal Structure --> <div id="modal-42bb56ba-b834-47c5-bea0-c0270e9ab371" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapLite result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => unknown [browser_modus] => unknown [version] => 4.0 [majorver] => 0 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => false [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.021</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td>AndroidOS 1.1.20</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => Safari [browserVersion] => 4.0 [osName] => AndroidOS [osVersion] => 1.1.20 [deviceModel] => WebKit [isMobile] => 1 [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555">Archos</td><td>Arnova 10 G2</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.27401</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 320 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Archos [mobile_model] => Arnova 10 G2 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 1.1.20 [is_ios] => [producer] => Google Inc. [operating_system] => Android [mobile_screen_width] => 240 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Android Browser </td><td>WebKit </td><td>Android 1.1</td><td style="border-left: 1px solid #555">Arnova</td><td>10 G2</td><td>tablet</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.002</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 1.1 [platform] => ) [device] => Array ( [brand] => AN [brandName] => Arnova [model] => 10 G2 [device] => 2 [deviceName] => tablet ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => 1 [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a> <!-- Modal Structure --> <div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => [isFacebookWebView:Sinergi\BrowserDetector\Browser:private] => [isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 1.1.20 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Android 1.1.20</td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555">Archos</td><td>A101C</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 1 [minor] => 1 [patch] => 20 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 1 [minor] => 1 [patch] => 20 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Archos [model] => A101C [family] => Archos A101C ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Safari 530.17</td><td>WebKit 530.17</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => Android [platform_version] => 1.1.20 [platform_type] => Mobile [browser_name] => Safari [browser_version] => 530.17 [engine_name] => WebKit [engine_version] => 530.17 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.068</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a> <!-- Modal Structure --> <div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 1.1.20 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => English - Australia [agent_languageTag] => En-au ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Android Browser 4.0</td><td>WebKit 530.17</td><td>Android 1.1.20</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.24601</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android 1.1 [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => Array ( ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => 1.1 [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 530.17 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android 1.1 [operating_system_version_full] => 1.1.20 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 1.1.20; En-au; A101C Build/ECLAIR) AppleWebKit/530.17 (KHTML, Like Gecko) Version/4.0 Mobile Safari/530.17 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Android Browser </td><td>Webkit 530.17</td><td>Android 1.1.20</td><td style="border-left: 1px solid #555">Archos</td><td>Arnova 10 G2</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 530.17 ) [os] => Array ( [name] => Android [version] => 1.1.20 ) [device] => Array ( [type] => tablet [manufacturer] => Archos [model] => Arnova 10 G2 ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a> <!-- Modal Structure --> <div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 1.1.20 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Android Webkit 1.1.20</td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555"></td><td></td><td>Feature Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.016</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => false [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 1.1.20 [advertised_browser] => Android Webkit [advertised_browser_version] => 1.1.20 [complete_device_name] => Generic Android 2.0 [device_name] => Generic Android 2.0 [form_factor] => Feature Phone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 2.0 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 2.0 [pointing_method] => touchscreen [release_date] => 2009_october [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => not_supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => play_and_stop [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 320 [resolution_height] => 480 [columns] => 60 [max_image_width] => 320 [max_image_height] => 400 [rows] => 40 [physical_screen_width] => 34 [physical_screen_height] => 50 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 200 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 1000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => progressive_download [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => false [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => -1 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => C [is_sencha_touch_ok] => false ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 1.1.20</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://developer.android.com/reference/android/webkit/package-summary.html [title] => Android Webkit 4.0 [name] => Android Webkit [version] => 4.0 [code] => android-webkit [image] => img/16/browser/android-webkit.png ) [os] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 1.1.20 [code] => android [x64] => [title] => Android 1.1.20 [type] => os [dir] => os [image] => img/16/os/android.png ) [device] => Array ( [link] => [title] => [model] => [brand] => [code] => null [dir] => device [type] => device [image] => img/16/device/null.png ) [platform] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 1.1.20 [code] => android [x64] => [title] => Android 1.1.20 [type] => os [dir] => os [image] => img/16/os/android.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 08:03:09</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v5/user-agent-detail/96/27/96276c33-b0ab-4717-9c39-a66682ccba33.html
HTML
mit
56,424
```javascript /** * @param {string} s * @return {boolean} * * Maximum length is 50000 * s is not empty * s only contains a-z */ var validPalindrome = function(s) { return validHelper(s, 0, s.length - 1, 0); }; var validHelper = function(s, startIndex, endIndex, deleteCount) { let left = startIndex, right = endIndex, lc, rc; while (left < right) { lc = s[left], rc = s[right]; if (lc === rc) { left++; right--; } else { if (deleteCount > 0) { return false; } else { // we got two choices, (1) delete left character, (2) delete right charecter return validHelper(s, left + 1, right, 1) || validHelper(s, left, right - 1, 1); } } } return true; }; ```
ddki/my_study_project
algorithm/topic/facebook/680/solution.md
Markdown
mit
748
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // @ignoreDep @angular/compiler-cli const ts = require("typescript"); const path = require("path"); const fs = require("fs"); const { __NGTOOLS_PRIVATE_API_2, VERSION } = require('@angular/compiler-cli'); const resource_loader_1 = require("./resource_loader"); class ExtractI18nPlugin { constructor(options) { this._compiler = null; this._compilation = null; this._compilerOptions = null; this._angularCompilerOptions = null; this._setupOptions(options); } _setupOptions(options) { if (!options.hasOwnProperty('tsConfigPath')) { throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.'); } // TS represents paths internally with '/' and expects the tsconfig path to be in this format this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/'); // Check the base path. const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath); let basePath = maybeBasePath; if (fs.statSync(maybeBasePath).isFile()) { basePath = path.dirname(basePath); } if (options.hasOwnProperty('basePath')) { basePath = path.resolve(process.cwd(), options.basePath); } let tsConfigJson = null; try { tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8')); } catch (err) { throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`); } const tsConfig = ts.parseJsonConfigFileContent(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath); let fileNames = tsConfig.fileNames; if (options.hasOwnProperty('exclude')) { let exclude = typeof options.exclude == 'string' ? [options.exclude] : options.exclude; exclude.forEach((pattern) => { const basePathPattern = '(' + basePath.replace(/\\/g, '/') .replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?'; pattern = pattern .replace(/\\/g, '/') .replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&') .replace(/\*\*/g, '(?:.*)') .replace(/\*/g, '(?:[^/]*)') .replace(/^/, basePathPattern); const re = new RegExp('^' + pattern + '$'); fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re)); }); } else { fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName)); } this._rootFilePath = fileNames; // By default messages will be generated in basePath let genDir = basePath; if (options.hasOwnProperty('genDir')) { genDir = path.resolve(process.cwd(), options.genDir); } this._compilerOptions = tsConfig.options; this._angularCompilerOptions = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['angularCompilerOptions'], { basePath }); this._basePath = basePath; this._genDir = genDir; // this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath); this._compilerHost = ts.createCompilerHost(this._compilerOptions, true); this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost); if (options.hasOwnProperty('i18nFormat')) { this._i18nFormat = options.i18nFormat; } if (options.hasOwnProperty('locale')) { if (VERSION.major === '2') { console.warn("The option '--locale' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._locale = options.locale; } if (options.hasOwnProperty('outFile')) { if (VERSION.major === '2') { console.warn("The option '--out-file' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._outFile = options.outFile; } } apply(compiler) { this._compiler = compiler; compiler.plugin('make', (compilation, cb) => this._make(compilation, cb)); compiler.plugin('after-emit', (compilation, cb) => { this._donePromise = null; this._compilation = null; compilation._ngToolsWebpackXi18nPluginInstance = null; cb(); }); } _make(compilation, cb) { this._compilation = compilation; if (this._compilation._ngToolsWebpackXi18nPluginInstance) { return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' + 'this compilation.')); } if (!this._compilation._ngToolsWebpackPluginInstance) { return cb(new Error('An @ngtools/webpack aot plugin does not exists ' + 'for this compilation')); } this._compilation._ngToolsWebpackXi18nPluginInstance = this; this._resourceLoader = new resource_loader_1.WebpackResourceLoader(compilation); this._donePromise = Promise.resolve() .then(() => { return __NGTOOLS_PRIVATE_API_2.extractI18n({ basePath: this._basePath, compilerOptions: this._compilerOptions, program: this._program, host: this._compilerHost, angularCompilerOptions: this._angularCompilerOptions, i18nFormat: this._i18nFormat, locale: this._locale, outFile: this._outFile, readResource: (path) => this._resourceLoader.get(path) }); }) .then(() => cb(), (err) => { this._compilation.errors.push(err); cb(err); }); } } exports.ExtractI18nPlugin = ExtractI18nPlugin; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
mikkeldamm/angular-cli
dist/@ngtools/webpack/src/extract_i18n_plugin.js
JavaScript
mit
6,184
package org.softlang.service.company; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * A department has a name, a manager, employees, and subdepartments. */ public class Department implements Serializable { private static final long serialVersionUID = -2008895922177165250L; private String name; private Employee manager; private List<Department> subdepts = new LinkedList<Department>(); private List<Employee> employees = new LinkedList<Employee>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee getManager() { return manager; } public void setManager(Employee manager) { this.manager = manager; } public List<Department> getSubdepts() { return subdepts; } public List<Employee> getEmployees() { return employees; } public double total() { double total = 0; total += getManager().getSalary(); for (Department s : getSubdepts()) total += s.total(); for (Employee e : getEmployees()) total += e.getSalary(); return total; } public void cut() { getManager().cut(); for (Department s : getSubdepts()) s.cut(); for (Employee e : getEmployees()) e.cut(); } }
amritbhat786/DocIT
101repo/contributions/javawsServer/OneOhOneCompanies/src/org/softlang/service/company/Department.java
Java
mit
1,240
/** * Contains methods for extracting/selecting final multiword candidates. * @author Valeria Quochi @author Francesca Frontini @author Francesco Rubino * Istituto di linguistica Computazionale "A. Zampolli" - CNR Pisa - Italy * */ package multiword;
francescafrontini/MWExtractor
src/multiword/package-info.java
Java
mit
262
[![Build Status](https://travis-ci.org/mircoc/cordova-plugin-settings-hook.svg?branch=master)](https://travis-ci.org/mircoc/cordova-plugin-settings-hook) [![npm version](https://badge.fury.io/js/cordova-plugin-settings-hook.svg)](https://badge.fury.io/js/cordova-plugin-settings-hook) [![npm](https://img.shields.io/npm/dm/cordova-plugin-settings-hook.svg)](https://www.npmjs.com/package/cordova-plugin-settings-hook) # cordova-plugin-settings-hook Cordova plugin helpful to modify Android and iOS settings with config.xml parameters. Based on the work of [Devin Jett](https://github.com/djett) and [Diego Netto](https://github.com/diegonetto) on [generator-ionic](https://github.com/diegonetto/generator-ionic) with hook [update_platform_config.js](https://github.com/diegonetto/generator-ionic/blob/master/templates/hooks/after_prepare/update_platform_config.js) Removed dependency to other npm packages, so it can be installed as a Cordova plugin adding it to your config.xml: ``` <plugin name="cordova-plugin-settings-hook" spec="~0" /> ``` This hook updates platform configuration files based on preferences and config-file data defined in config.xml. Currently only the AndroidManifest.xml and IOS *-Info.plist file are supported. ## Preferences: 1. Preferences defined outside of the platform element will apply to all platforms 2. Preferences defined inside a platform element will apply only to the specified platform 3. Platform preferences take precedence over common preferences 4. The preferenceMappingData object contains all of the possible custom preferences to date including the target file they belong to, parent element, and destination element or attribute Config Files 1. config-file elements MUST be defined inside a platform element, otherwise they will be ignored. 2. config-file target attributes specify the target file to update. (AndroidManifest.xml or *-Info.plist) 3. config-file parent attributes specify the parent element (AndroidManifest.xml) or parent key (*-Info.plist) that the child data will replace or be appended to. 4. config-file elements are uniquely indexed by target AND parent for each platform. 5. If there are multiple config-file's defined with the same target AND parent, the last config-file will be used 6. Elements defined WITHIN a config-file will replace or be appended to the same elements relative to the parent element 7. If a unique config-file contains multiples of the same elements (other than uses-permssion elements which are selected by by the uses-permission name attribute), the last defined element will be retrieved. ## Examples of config.xml: You have to add some of the following configuration options inside your Cordova project _config.xml_ in the <platform> tag for Android or iOS. ### Android These configuration will update the generated AndroidManifest.xml for Android platform. NOTE: For possible manifest values see (http://developer.android.com/guide/topics/manifest/manifest-intro.html) ``` <platform name="android"> //These preferences are actually available in Cordova by default although not currently documented <preference name="android-minSdkVersion" value="8" /> <preference name="android-maxSdkVersion" value="19" /> <preference name="android-targetSdkVersion" value="19" /> //custom preferences examples <preference name="android-windowSoftInputMode" value="stateVisible" /> <preference name="android-installLocation" value="auto" /> <preference name="android-launchMode" value="singleTop" /> <preference name="android-activity-hardwareAccelerated" value="false" /> <preference name="android-manifest-hardwareAccelerated" value="false" /> <preference name="android-configChanges" value="orientation" /> <preference name="android-applicationName" value="MyApplication" /> <preference name="android-theme" value="@android:style/Theme.Black.NoTitleBar" /> <config-file target="AndroidManifest.xml" parent="/*"> <supports-screens android:xlargeScreens="false" android:largeScreens="false" android:smallScreens="false" /> <uses-permission android:name="android.permission.READ_CONTACTS" android:maxSdkVersion="15" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> </config-file> </platform> ``` #### Android config-file requirements If you specify something in the ```<config-file target="AndroidManifest.xml"...```, you need to add android namespace to the xml root, like this: ``` <widget xmlns:android="http://schemas.android.com/apk/res/android" ... > ``` If don't do this you'll get a build error: ```error: Error parsing XML: unbound prefix```. ### iOS These configuration will update the generated *-Info.plist for iOS platform. ``` <platform name="ios"> <config-file platform="ios" target="*-Info.plist" parent="UISupportedInterfaceOrientations"> <array> <string>UIInterfaceOrientationLandscapeOmg</string> </array> </config-file> <config-file platform="ios" target="*-Info.plist" parent="SomeOtherPlistKey"> <string>someValue</string> </config-file> </platform> ``` ## Execution After you added the plugin you can execute `cordova prepare` to change the platform config. ``` $ cordova prepare Processing settings for platform: android Wrote AndroidManifest.xml: ../platforms/android/AndroidManifest.xml Processing settings for platform: ios Wrote iOS Plist: ../platforms/ios/GamifiveBrazil/MyApp-Info.plist ``` ## Note NOTE: Currently, items aren't removed from the platform config files if you remove them from config.xml. For example, if you add a custom permission, build the remove it, it will still be in the manifest. If you make a mistake, for example adding an element to the wrong parent, you may need to remove and add your platform, or revert to your previous manifest/plist file. ## Todo TODO: We may need to capture all default manifest/plist elements/keys created by Cordova along with any plugin elements/keys to compare against custom elements to remove.
mircoc/cordova-plugin-settings-hook
README.md
Markdown
mit
6,123
--- layout: post title: "计算机网络IO模型原理性解析" category: Linux tags: [net] --- &emsp;&emsp;本文旨在原理性的揭示计算机网络IO模型以及select、epoll的区别,而并不探讨实现细节,另外,讨论阻塞与非阻塞、同步和异步时往往是上下文相关的,本文的上下文就是Linux IO,下文中IO操作就以read为例。 首先明确一点,一次IO操作分为两个阶段: 1. 等待数据准备就绪 2. 将数据从内核拷贝到用户进程空间 * **阻塞IO:** &emsp;&emsp;首先用户进程发起read系统调用,内核开始准备数据,一般的,对于网络IO来说,大部分情况下当用户进程发起read系统调用的时候数据尚未到达,这个时候内核一直等待数据到达,在用户进程这一侧,整个进程会被阻塞。当数据到达后,内核就把准备妥当的数据从内核空间拷贝用户进程空间,然后内核返回,用户进程被唤醒,因此,阻塞IO在一次IO操作的两个阶段均被阻塞了。 * **非阻塞IO:** &emsp;&emsp;当用户进程发起read系统调用时,如果内核还没收到数据,则此次系统调用立即返回一个错误而不是阻塞整个进程,用户进程需要通过此次调用的返回值判断是否读到了数据,如果没有则隔一段时间再次发起read调用,如此不断轮询,在用户进程轮询期间,内核一直在等待数据到达,当数据准备妥当后,当用户进程发起当read系统调用时,内核负责将数据拷贝到用户进程空间,直到拷贝完成,read操作返回,也就是在这一阶段(第二阶段),非阻塞IO表现出的其实是一个同步操作,因此,从内核拷贝数据到用户进程空间的这段时间内read调用是一直等待直到完成的,所以,非阻塞IO是属于同步IO,也就是说非阻塞IO操作在第一阶段是不阻塞的,在第二阶段是阻塞的。 * **同步IO:** &emsp;&emsp;一个同步IO操作会导致进程阻塞直到IO操作完成,所以,阻塞IO、非阻塞IO以及本文未提及到的IO多路复用都属于同步IO。 * **异步IO:** &emsp;&emsp;一个异步IO操作不会引起进程的阻塞。 > &emsp;&emsp;这里面大家可能分不清阻塞和非阻塞IO,甚至会认为非阻塞就是同步了,其实不是的,回到本文开头,我们说一次IO操作分两个阶段,第一阶段是等待数据,第二阶段拷贝数据(内核到用户空间),非阻塞IO操作在数据还没有到达时是立即返回到,这一点表现的跟异步一样,但是,在第二阶段,当数据准备妥当的时候,非阻塞IO是阻塞的,直到数据拷贝完成,这一点表现的与同步IO完全不一样,异步操作根本不关心你的数据是否到达以及你的数据是否拷贝完成,异步发起一次操作后就去干别的事儿了,直到内核发出一个信号通知这一事件,它才会转回来继续处理。 * **select与epoll** &emsp;&emsp;select与epoll都是IO多路复用模型,它们都是监视一组文件描述符(在本文就是socket)上是否有数据准备就绪,select和epoll会一直阻塞直到它们监视的一个或多个套接字描述符上数据准备就绪,当在某个或某几个套接字描述符上有数据到达时,对select而言,它需要遍历这组描述符以确定到底是哪一个描述符上面有数据到达了,所以时间复杂度是O(n),而对于epoll而言,它不是通过遍历或者叫轮询的方式来确定数据准备妥当的描述符,而是通过事件的方式,以事件的方式通知epoll是哪个描述符上数据到达来,因此,时间复杂度是O(1)。 > &emsp;&emsp;可能说的很啰嗦,只是想尽量的把原理讲清楚,原理清楚来再看实现细节才能做到游刃有余。 * **参考文章:** &emsp;&emsp;[http://blog.csdn.net/historyasamirror/article/details/5778378](http://blog.csdn.net/historyasamirror/article/details/5778378) &emsp;&emsp;[http://yaocoder.blog.51cto.com/2668309/888374](http://yaocoder.blog.51cto.com/2668309/888374)
chunleiyang/chunleiyang.github.io
_posts/2014-05-21-computer-net-io.markdown
Markdown
mit
4,212
## Bookmarks tagged [[ngrx]](https://www.codever.land/search?q=[ngrx]) _<sup><sup>[www.codever.land/bookmarks/t/ngrx](https://www.codever.land/bookmarks/t/ngrx)</sup></sup>_ --- #### [Managing State in Angular 2 - Kyle Cordes - Oct 2016 - 46min](https://www.youtube.com/watch?v=eBLTz8QRg4Q) _<sup>https://www.youtube.com/watch?v=eBLTz8QRg4Q</sup>_ This month at the St. Lewis Angular Lunch, Kyle spoke about managing state in Angular 2 applications. The crying baby thumbnail accurately reflects how many developers have come to experience state ma... * :calendar: **published on**: 2016-10-20 * **tags**: [angular](../tagged/angular.md), [state-management](../tagged/state-management.md), [ngrx](../tagged/ngrx.md), [redux](../tagged/redux.md) --- #### [Ngrx Store - An Architecture Guide](https://blog.angular-university.io/angular-ngrx-store-and-effects-crash-course/) _<sup>https://blog.angular-university.io/angular-ngrx-store-and-effects-crash-course/</sup>_ Using a store architecture represents a big architectural shift: with the arrival of single page applications, we moved the Model to View transformation from the server to the client. Store architect... * **tags**: [angular](../tagged/angular.md), [flux](../tagged/flux.md), [ngrx](../tagged/ngrx.md), [architecture](../tagged/architecture.md) --- #### [Communication Patterns in Angular - BB Tutorials & Thoughts - Medium](https://medium.com/bb-tutorials-and-thoughts/communication-patterns-in-angular-9b0a829aa916) _<sup>https://medium.com/bb-tutorials-and-thoughts/communication-patterns-in-angular-9b0a829aa916</sup>_ Angular follows a two-way data flow pattern, meaning you can send data up and down the component tree. As everything in the Angular is a component, understanding communication between components is cr... * :calendar: **published on**: 2019-05-30 * **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md) * :octocat: **[source code](https://github.com/bbachi/angular-communication)** --- #### [NGXS Home Page](https://www.ngxs.io/) _<sup>https://www.ngxs.io/</sup>_ NGXS is a state management pattern + library for Angular. It acts as a single source of truth for your application's state, providing simple rules for predictable state mutations. NGXS is modeled aft... * **tags**: [angular](../tagged/angular.md), [rxjs](../tagged/rxjs.md), [redux](../tagged/redux.md), [ngrx](../tagged/ngrx.md), [cqrs](../tagged/cqrs.md) * :octocat: **[source code](https://github.com/ngxs/store)** --- #### [GitHub - johnpapa/angular-ngrx-data: Angular with ngRx and experimental ngrx-data helperAsset 1Asset 1](https://github.com/johnpapa/angular-ngrx-data) _<sup>https://github.com/johnpapa/angular-ngrx-data</sup>_ Angular with ngRx and experimental ngrx-data helper * **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md) * :octocat: **[source code](https://github.com/johnpapa/angular-ngrx-data)** --- #### [GitHub - ngrx/platform: Monorepo for ngrx codebase](https://github.com/ngrx/platform) _<sup>https://github.com/ngrx/platform</sup>_ Monorepo for ngrx codebase * **tags**: [angular](../tagged/angular.md), [ngrx](../tagged/ngrx.md), [redux](../tagged/redux.md) * :octocat: **[source code](https://github.com/ngrx/platform)** ---
Codingpedia/bookmarks
tagged/ngrx.md
Markdown
mit
3,249
#include "PerformanceSpriteTest.h" enum { kMaxNodes = 50000, kNodesIncrease = 250, TEST_COUNT = 7, }; enum { kTagInfoLayer = 1, kTagMainLayer = 2, kTagMenuLayer = (kMaxNodes + 1000), }; static int s_nSpriteCurCase = 0; //////////////////////////////////////////////////////// // // SubTest // //////////////////////////////////////////////////////// SubTest::~SubTest() { if (batchNode) { batchNode->release(); batchNode = NULL; } } void SubTest::initWithSubTest(int nSubTest, CCNode* p) { subtestNumber = nSubTest; parent = p; batchNode = NULL; /* * Tests: * 1: 1 (32-bit) PNG sprite of 52 x 139 * 2: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 * 3: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 * 4: 1 (4-bit) PVRTC Batch Node using 1 sprite of 52 x 139 * 5: 14 (32-bit) PNG sprites of 85 x 121 each * 6: 14 (32-bit) PNG Batch Node of 85 x 121 each * 7: 14 (16-bit) PNG Batch Node of 85 x 121 each * 8: 14 (4-bit) PVRTC Batch Node of 85 x 121 each * 9: 64 (32-bit) sprites of 32 x 32 each *10: 64 (32-bit) PNG Batch Node of 32 x 32 each *11: 64 (16-bit) PNG Batch Node of 32 x 32 each *12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each */ // purge textures CCTextureCache *mgr = CCTextureCache::sharedTextureCache(); // [mgr removeAllTextures]; mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png")); mgr->removeTexture(mgr->addImage("Images/grossini_dance_atlas.png")); mgr->removeTexture(mgr->addImage("Images/spritesheet1.png")); switch ( subtestNumber) { case 1: case 4: case 7: break; /// case 2: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888); batchNode = CCSpriteBatchNode::create("Images/grossinis_sister1.png", 100); p->addChild(batchNode, 0); break; case 3: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444); batchNode = CCSpriteBatchNode::create("Images/grossinis_sister1.png", 100); p->addChild(batchNode, 0); break; /// case 5: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888); batchNode = CCSpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); p->addChild(batchNode, 0); break; case 6: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444); batchNode = CCSpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); p->addChild(batchNode, 0); break; /// case 8: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888); batchNode = CCSpriteBatchNode::create("Images/spritesheet1.png", 100); p->addChild(batchNode, 0); break; case 9: CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444); batchNode = CCSpriteBatchNode::create("Images/spritesheet1.png", 100); p->addChild(batchNode, 0); break; default: break; } if (batchNode) { batchNode->retain(); } CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default); } CCSprite* SubTest::createSpriteWithTag(int tag) { // create CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888); CCSprite* sprite = NULL; switch (subtestNumber) { case 1: { sprite = CCSprite::create("Images/grossinis_sister1.png"); parent->addChild(sprite, 0, tag+100); break; } case 2: case 3: { sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(0, 0, 52, 139)); batchNode->addChild(sprite, 0, tag+100); break; } case 4: { int idx = (CCRAScutOM_0_1() * 1400 / 100) + 1; char str[32] = {0}; sprintf(str, "Images/grossini_dance_%02d.png", idx); sprite = CCSprite::create(str); parent->addChild(sprite, 0, tag+100); break; } case 5: case 6: { int y,x; int r = (CCRAScutOM_0_1() * 1400 / 100); y = r / 5; x = r % 5; x *= 85; y *= 121; sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(x,y,85,121)); batchNode->addChild(sprite, 0, tag+100); break; } case 7: { int y,x; int r = (CCRAScutOM_0_1() * 6400 / 100); y = r / 8; x = r % 8; char str[40] = {0}; sprintf(str, "Images/sprites_test/sprite-%d-%d.png", x, y); sprite = CCSprite::create(str); parent->addChild(sprite, 0, tag+100); break; } case 8: case 9: { int y,x; int r = (CCRAScutOM_0_1() * 6400 / 100); y = r / 8; x = r % 8; x *= 32; y *= 32; sprite = CCSprite::createWithTexture(batchNode->getTexture(), CCRectMake(x,y,32,32)); batchNode->addChild(sprite, 0, tag+100); break; } default: break; } CCTexture2D::setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default); return sprite; } void SubTest::removeByTag(int tag) { switch (subtestNumber) { case 1: case 4: case 7: parent->removeChildByTag(tag+100, true); break; case 2: case 3: case 5: case 6: case 8: case 9: batchNode->removeChildAtIScutex(tag, true); // [batchNode removeChildByTag:tag+100 cleanup:YES]; break; default: break; } } //////////////////////////////////////////////////////// // // SpriteMenuLayer // //////////////////////////////////////////////////////// void SpriteMenuLayer::showCurrentTest() { SpriteMainScene* pScene = NULL; SpriteMainScene* pPreScene = (SpriteMainScene*) getParent(); int nSubTest = pPreScene->getSubTestNum(); int nNodes = pPreScene->getNodesNum(); switch (m_nCurCase) { case 0: pScene = new SpritePerformTest1; break; case 1: pScene = new SpritePerformTest2; break; case 2: pScene = new SpritePerformTest3; break; case 3: pScene = new SpritePerformTest4; break; case 4: pScene = new SpritePerformTest5; break; case 5: pScene = new SpritePerformTest6; break; case 6: pScene = new SpritePerformTest7; break; } s_nSpriteCurCase = m_nCurCase; if (pScene) { pScene->initWithSubTest(nSubTest, nNodes); CCDirector::sharedDirector()->replaceScene(pScene); pScene->release(); } } //////////////////////////////////////////////////////// // // SpriteMainScene // //////////////////////////////////////////////////////// void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) { //sraScutom(0); subtestNumber = asubtest; m_pSubTest = new SubTest; m_pSubTest->initWithSubTest(asubtest, this); CCSize s = CCDirector::sharedDirector()->getWinSize(); lastRenderedCount = 0; quantityNodes = 0; CCMenuItemFont::setFontSize(65); CCMenuItemFont *decrease = CCMenuItemFont::create(" - ", this, menu_selector(SpriteMainScene::oScutecrease)); decrease->setColor(ccc3(0,200,20)); CCMenuItemFont *increase = CCMenuItemFont::create(" + ", this, menu_selector(SpriteMainScene::onIncrease)); increase->setColor(ccc3(0,200,20)); CCMenu *menu = CCMenu::create(decrease, increase, NULL); menu->alignItemsHorizontally(); menu->setPosition(ccp(s.width/2, s.height-65)); addChild(menu, 1); CCLabelTTF *infoLabel = CCLabelTTF::create("0 nodes", "Marker Felt", 30); infoLabel->setColor(ccc3(0,200,20)); infoLabel->setPosition(ccp(s.width/2, s.height-90)); addChild(infoLabel, 1, kTagInfoLayer); // add menu SpriteMenuLayer* pMenu = new SpriteMenuLayer(true, TEST_COUNT, s_nSpriteCurCase); addChild(pMenu, 1, kTagMenuLayer); pMenu->release(); // Sub Tests CCMenuItemFont::setFontSize(32); CCMenu* pSubMenu = CCMenu::create(); for (int i = 1; i <= 9; ++i) { char str[10] = {0}; sprintf(str, "%d ", i); CCMenuItemFont* itemFont = CCMenuItemFont::create(str, this, menu_selector(SpriteMainScene::testNCallback)); itemFont->setTag(i); pSubMenu->addChild(itemFont, 10); if( i<= 3) itemFont->setColor(ccc3(200,20,20)); else if(i <= 6) itemFont->setColor(ccc3(0,200,20)); else itemFont->setColor(ccc3(0,20,200)); } pSubMenu->alignItemsHorizontally(); pSubMenu->setPosition(ccp(s.width/2, 80)); addChild(pSubMenu, 2); // add title label CCLabelTTF *label = CCLabelTTF::create(title().c_str(), "Arial", 40); addChild(label, 1); label->setPosition(ccp(s.width/2, s.height-32)); label->setColor(ccc3(255,255,40)); while(quantityNodes < nNodes) onIncrease(this); } std::string SpriteMainScene::title() { return "No title"; } SpriteMainScene::~SpriteMainScene() { if (m_pSubTest) { delete m_pSubTest; m_pSubTest = NULL; } } void SpriteMainScene::testNCallback(CCObject* pSender) { subtestNumber = ((CCMenuItemFont*) pSender)->getTag(); SpriteMenuLayer* pMenu = (SpriteMenuLayer*)getChildByTag(kTagMenuLayer); pMenu->restartCallback(pSender); } void SpriteMainScene::updateNodes() { if( quantityNodes != lastRenderedCount ) { CCLabelTTF *infoLabel = (CCLabelTTF *) getChildByTag(kTagInfoLayer); char str[16] = {0}; sprintf(str, "%u nodes", quantityNodes); infoLabel->setString(str); lastRenderedCount = quantityNodes; } } void SpriteMainScene::onIncrease(CCObject* pSender) { if( quantityNodes >= kMaxNodes) return; for( int i=0;i< kNodesIncrease;i++) { CCSprite *sprite = m_pSubTest->createSpriteWithTag(quantityNodes); doTest(sprite); quantityNodes++; } updateNodes(); } void SpriteMainScene::oScutecrease(CCObject* pSender) { if( quantityNodes <= 0 ) return; for( int i=0;i < kNodesIncrease;i++) { quantityNodes--; m_pSubTest->removeByTag(quantityNodes); } updateNodes(); } //////////////////////////////////////////////////////// // // For test functions // //////////////////////////////////////////////////////// void performanceActions(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); float period = 0.5f + (raScut() % 1000) / 500.0f; CCRotateBy* rot = CCRotateBy::create(period, 360.0f * CCRAScutOM_0_1()); CCActionInterval* rot_back = rot->reverse(); CCAction *permanentRotation = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL)); pSprite->runAction(permanentRotation); float growDuration = 0.5f + (raScut() % 1000) / 500.0f; CCActionInterval *grow = CCScaleBy::create(growDuration, 0.5f, 0.5f); CCAction *permanentScaleLoop = CCRepeatForever::create(CCSequence::create(grow, grow->reverse(), NULL)); pSprite->runAction(permanentScaleLoop); } void performanceActions20(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); if( CCRAScutOM_0_1() < 0.2f ) pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); else pSprite->setPosition(ccp( -1000, -1000)); float period = 0.5f + (raScut() % 1000) / 500.0f; CCRotateBy* rot = CCRotateBy::create(period, 360.0f * CCRAScutOM_0_1()); CCActionInterval* rot_back = rot->reverse(); CCAction *permanentRotation = CCRepeatForever::create(CCSequence::create(rot, rot_back, NULL)); pSprite->runAction(permanentRotation); float growDuration = 0.5f + (raScut() % 1000) / 500.0f; CCActionInterval *grow = CCScaleBy::create(growDuration, 0.5f, 0.5f); CCAction *permanentScaleLoop = CCRepeatForever::create(CCSequence::createWithTwoActions(grow, grow->reverse())); pSprite->runAction(permanentScaleLoop); } void performanceRotationScale(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); pSprite->setRotation(CCRAScutOM_0_1() * 360); pSprite->setScale(CCRAScutOM_0_1() * 2); } void performancePosition(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); } void performanceout20(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); if( CCRAScutOM_0_1() < 0.2f ) pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); else pSprite->setPosition(ccp( -1000, -1000)); } void performanceOut100(CCSprite* pSprite) { pSprite->setPosition(ccp( -1000, -1000)); } void performanceScale(CCSprite* pSprite) { CCSize size = CCDirector::sharedDirector()->getWinSize(); pSprite->setPosition(ccp((raScut() % (int)size.width), (raScut() % (int)size.height))); pSprite->setScale(CCRAScutOM_0_1() * 100 / 50); } //////////////////////////////////////////////////////// // // SpritePerformTest1 // //////////////////////////////////////////////////////// std::string SpritePerformTest1::title() { char str[32] = {0}; sprintf(str, "A (%d) position", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest1::doTest(CCSprite* sprite) { performancePosition(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest2 // //////////////////////////////////////////////////////// std::string SpritePerformTest2::title() { char str[32] = {0}; sprintf(str, "B (%d) scale", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest2::doTest(CCSprite* sprite) { performanceScale(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest3 // //////////////////////////////////////////////////////// std::string SpritePerformTest3::title() { char str[32] = {0}; sprintf(str, "C (%d) scale + rot", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest3::doTest(CCSprite* sprite) { performanceRotationScale(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest4 // //////////////////////////////////////////////////////// std::string SpritePerformTest4::title() { char str[32] = {0}; sprintf(str, "D (%d) 100%% out", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest4::doTest(CCSprite* sprite) { performanceOut100(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest5 // //////////////////////////////////////////////////////// std::string SpritePerformTest5::title() { char str[32] = {0}; sprintf(str, "E (%d) 80%% out", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest5::doTest(CCSprite* sprite) { performanceout20(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest6 // //////////////////////////////////////////////////////// std::string SpritePerformTest6::title() { char str[32] = {0}; sprintf(str, "F (%d) actions", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest6::doTest(CCSprite* sprite) { performanceActions(sprite); } //////////////////////////////////////////////////////// // // SpritePerformTest7 // //////////////////////////////////////////////////////// std::string SpritePerformTest7::title() { char str[32] = {0}; sprintf(str, "G (%d) actions 80%% out", subtestNumber); std::string strRet = str; return strRet; } void SpritePerformTest7::doTest(CCSprite* sprite) { performanceActions20(sprite); } void runSpriteTest() { SpriteMainScene* pScene = new SpritePerformTest1; pScene->initWithSubTest(1, 50); CCDirector::sharedDirector()->replaceScene(pScene); pScene->release(); }
wenhulove333/ScutServer
Sample/ClientSource/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp
C++
mit
17,742
class SparseVector { unordered_map<int, int> repr; int size = 0; public: SparseVector(vector<int> &nums) { size = nums.size(); for (int i=0; i<nums.size(); i++) { if (nums[i] == 0) { continue; } repr[i] = nums[i]; } } // Return the dotProduct of two sparse vectors int dotProduct(SparseVector& vec) { if (size != vec.size) {return 0;} // incompatible int dp=0; for (const auto& kv : vec.repr) { if (repr.find(kv.first) == repr.end()) continue; dp += kv.second * repr[kv.first]; } return dp; } }; // Your SparseVector object will be instantiated and called as such: // SparseVector v1(nums1); // SparseVector v2(nums2); // int ans = v1.dotProduct(v2);
cbrghostrider/Hacking
leetcode/_001570_dotProdSparseVectors.cpp
C++
mit
807
# Copyright (c) 2016 nVentiveUX # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """Application configuration""" from django.apps import AppConfig class ShowcaseConfig(AppConfig): name = 'mystartupmanager.showcase'
nVentiveUX/mystartupmanager
mystartupmanager/showcase/apps.py
Python
mit
1,233
--- author: viviworld comments: true date: 2014-06-01 10:07:00+00:00 layout: post link: http://www.labazhou.net/2014/06/the-makings-of-a-great-logo/ slug: the-makings-of-a-great-logo title: 伟大Logo的要素 wordpress_id: 724 categories: - 设计 tags: - Amazon - Disney - logo - Path - Pinterest - 字体 --- ## 在设计品牌时要问自己的6个问题 公司logo是业务品牌的重要基础。它很可能是你和客户之间的首次互动。一个有效的logo能够建立合适的基调、设定正确的气质。我为不同的项目设计了数年的logo之后,在交付一个新logo之前我经常问自己一系列问题。 ### 1.logo要唤起什么情感? 所有设计指导方针之上,最重要的准则是logo能否反映公司的性格。logo唤起的情感应该体现出公司价值。比如,迪斯尼logo唤起幸福和乐观的感觉。曲线优美、充满趣味的字体与为儿童制作卡通和动画片的公司相得益彰。然而,相似logo样式出现在销售平台上就不太合适了。 设计师应该理解颜色心理学以及字体在伟大logo设计上的效果。例如,绿色通常体现了成长、健康和环境。它促进了放松和精神焕发的情感。另一方面,红色或许引起危险和激烈的情感。对于字体也是一样,Garamond,Helvetica,和 Comic Sans都会带来非常不同的柔情。Garamond 之类的Serif字体促进了尊重和传统的想法,因此更加适合对于正直有要求的环境,比如大学或新闻机构。像Helvetica之类的Sans Serif字体简洁、现代,非常适合高科技企业,比如计算机或媒体公司。像Comic Sans之类的Casual Script字体很可能最适合娱乐或动画公司了,比如玩具公司。较好地理解颜色心理学、字体和形状是创作伟大logo的重要组成部分。 [![disney logo的分析](http://www.labazhou.net/wp-content/uploads/2014/06/disney-logo.png)](http://www.labazhou.net/wp-content/uploads/2014/06/disney-logo.png) ### 2.logo背后的意义 <blockquote>每个伟大logo的背后都有一个故事。</blockquote> 一个伟大的logo不是把你的业务名字拍在通用形状上,这就是为什么选择现成logo是糟糕的想法。确保一个logo不是一般的极好方式就是logo背后有一个富有意义的故事。好的设计师在开始把想法应用在logo之前,首先要非常理解公司文化、产品基调和业务愿景。高质量logo的最终结果就是公司哲学和价值的体现。 [![amazon-logo](http://www.labazhou.net/wp-content/uploads/2014/06/amazon-logo.png)](http://www.labazhou.net/wp-content/uploads/2014/06/amazon-logo.png) ### 3.logo能够经得起时间的考验吗? logo在未来2年、10年、20年内看起来如何?设计师应该避免引入红极一时的趋势。像极细字体和扁平阴影就是那些经不起未来时间考验的设计样式。简单远胜复杂。一个简单且容易记住的logo能够在未来20年内使用,而不用担心过期。 考验logo的一个好方法就是在发布之前让它和你‘待’一会儿。一些logo随着你成长------你看它越多,你就越喜欢它。一些logo在一段时间后开始感到厌烦------你看它越多,你就越讨厌它。在你和logo共处了数周之后,如果你发现它是厌烦的,那么这个logo很可能不够好,或不是永恒的。 [![apple的logo变迁](http://www.labazhou.net/wp-content/uploads/2014/06/apple-logo.png)](http://www.labazhou.net/wp-content/uploads/2014/06/apple-logo.png) ### 4.它是独一无二的?可以瞬间被识别吗? 伟大的logo是有特色的、容易记住的和可识别的。甚至你只看了一次,在很长时间之后你仍然应当能够记住它的样子。测试的好方法是向你的朋友展示logo,然后合上,在一周后让你朋友描述这个logo。一双毫无经验的眼睛在描述logo最容易记住的部分上面是非常有效的。 另外,如果logo让你想起了你曾经见过的其它logo,那么它就不是足够有特色的,很可能是要让这个logo更加易识别的信号。 [![pinterest](http://www.labazhou.net/wp-content/uploads/2014/06/pinterest.png)](http://www.labazhou.net/wp-content/uploads/2014/06/pinterest.png) ### 5.黑白的logo效果如何? 当我开始设计logo时,我总是从黑白开始。这个限制下的设计首先要求你确保logo纯粹靠其形状和轮廓被识别出来、而不是其颜色。一个健壮logo仅仅通过其轮廓仍然是易于记住的。 单色logo还有个好处,让你的品牌轻松应用在有不同背景和材质的多个媒体上。 [![国家地理的logo](http://www.labazhou.net/wp-content/uploads/2014/06/National-Geography-logo.png)](http://www.labazhou.net/wp-content/uploads/2014/06/National-Geography-logo.png) ### 6.小尺寸下的logo是清晰的、明显的? 确保logo简单、可识别的另一个方法就是大幅缩小尺寸。甚至在低分辨率下,健壮的logo应该还是一眼就能看出来的。这也是确保logo没有因为不必要的设计装饰而过度复杂的一种较好测试。 [![小logo集合](http://www.labazhou.net/wp-content/uploads/2014/06/tiny-logo.png)](http://www.labazhou.net/wp-content/uploads/2014/06/tiny-logo.png) 这些不是一成不变的规则,而是制作一个有效果logo的优秀指导方针。即使它是复杂的,但是理解这样决定的权衡对于设计一个健壮的logo,仍然是有可能的。因此,下次你发现自己设计或挑选一个新logo时,问自己这些问题。它们有助于你选定正确的logo。 原文地址:[https://bold.pixelapse.com/minming/the-makings-of-a-great-logo](https://bold.pixelapse.com/minming/the-makings-of-a-great-logo)
365zph/365zph.github.io
_posts/2014-06-01-the-makings-of-a-great-logo.markdown
Markdown
mit
5,794
<?php namespace Algolia\SearchBundle; use Algolia\SearchBundle\TestApp\Entity\Comment; use Algolia\SearchBundle\TestApp\Entity\Image; use Algolia\SearchBundle\TestApp\Entity\Post; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\ConsoleOutput; class BaseTest extends KernelTestCase { public function setUp(): void { self::bootKernel(); } protected function createPost($id = null): Post { $post = new Post(); $post->setTitle('Test'); $post->setContent('Test content'); if (!is_null($id)) { $post->setId($id); } return $post; } protected function createSearchablePost(): SearchableEntity { $post = $this->createPost(random_int(100, 300)); return new SearchableEntity( $this->getPrefix() . 'posts', $post, $this->get('doctrine')->getManager()->getClassMetadata(Post::class), $this->get('serializer') ); } protected function createComment($id = null): Comment { $comment = new Comment(); $comment->setContent('Comment content'); $comment->setPost(new Post(['title' => 'What a post!', 'content' => 'my content'])); if (!is_null($id)) { $comment->setId($id); } return $comment; } protected function createImage($id = null): Image { $image = new Image(); if (!is_null($id)) { $image->setId($id); } return $image; } protected function createSearchableImage(): SearchableEntity { $image = $this->createImage(random_int(100, 300)); return new SearchableEntity( $this->getPrefix() . 'image', $image, $this->get('doctrine')->getManager()->getClassMetadata(Image::class), null ); } protected function getPrefix(): ?string { return $this->get('search.service')->getConfiguration()['prefix']; } protected function get($id): ?object { return self::$kernel->getContainer()->get($id); } protected function refreshDb($application): void { $inputs = [ new ArrayInput([ 'command' => 'doctrine:schema:drop', '--full-database' => true, '--force' => true, '--quiet' => true, ]), new ArrayInput([ 'command' => 'doctrine:schema:create', '--quiet' => true, ]), ]; $application->setAutoExit(false); foreach ($inputs as $input) { $application->run($input, new ConsoleOutput()); } } protected function getFileName($indexName, $type): string { return sprintf( '%s/%s-%s.json', $this->get('search.service')->getConfiguration()['settingsDirectory'], $indexName, $type ); } protected function getDefaultConfig(): array { return [ 'hitsPerPage' => 20, 'maxValuesPerFacet' => 100, ]; } }
algolia/AlgoliaSearchBundle
tests/BaseTest.php
PHP
mit
3,259
module PrintSquare class CommandRunner class << self def run(args) validate_args(args) print_square(args[0].to_i) end def print_square(number) size = Math.sqrt(number).to_i n = number x = PrintSquare::Vector.new size.even? ? 1 : -1, size, size.even? ? 1 : 0 y = PrintSquare::Vector.new 0, size print = PrintSquare::Printer.new size x.turn = proc do y.offset += 1 if x.direction == 1 y.direction = x.direction x.direction = 0 end y.turn = proc do if y.direction == -1 x.size -= 1 y.size -= 1 x.offset += 1 end x.direction = y.direction * -1 y.direction = 0 end until n == 0 print.set x, y, n y.direction == 0 ? x.next : y.next n -= 1 end print.out end def validate_args(args) usage(:no_args) if args.count == 0 usage(:too_many_args) if args.count > 1 usage(:invalid_arg) unless (Integer(args[0]) rescue false) usage(:not_square) unless is_square?(args[0].to_i) end def is_square?(number) return true if number == 1 position = 2 spread = 1 until spread == 0 current_square = position*position return true if current_square == number if number < current_square spread >>= 1 position -= spread else spread <<= 1 position += spread end end false end def usage(error_type) error = case error_type when :no_args then 'Missing argument' when :invalid_arg then 'Argument must be a number' when :too_many_args then 'Too many arguments' when :not_square then "Argument is not a square number" end puts <<-USAGE #{error} print_square [square_number] USAGE exit(-1) end end end end
AktionLab/print_square
lib/print_square/command_runner.rb
Ruby
mit
2,057
package com.ripplargames.meshio.meshformats.ply; import com.ripplargames.meshio.vertices.VertexType; public class PlyVertexDataType { private final VertexType vertexType; private final PlyDataType plyDataType; public PlyVertexDataType(VertexType vertexType, PlyDataType plyDataType) { this.vertexType = vertexType; this.plyDataType = plyDataType; } public VertexType vertexType() { return vertexType; } public PlyDataType plyDataType() { return plyDataType; } }
NathanJAdams/MeshIO
src/com/ripplargames/meshio/meshformats/ply/PlyVertexDataType.java
Java
mit
531
<!DOCTYPE html> <html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Begin Jekyll SEO tag v2.5.0 --> <title>Jalil Butrón | Shanghai-based cinematographer</title> <meta name="generator" content="Jekyll v3.7.4" /> <meta property="og:title" content="Jalil Butrón" /> <meta property="og:locale" content="en_US" /> <meta name="description" content="Shanghai-based cinematographer" /> <meta property="og:description" content="Shanghai-based cinematographer" /> <link rel="canonical" href="http://localhost:4000/404.html" /> <meta property="og:url" content="http://localhost:4000/404.html" /> <meta property="og:site_name" content="Jalil Butrón" /> <script type="application/ld+json"> {"description":"Shanghai-based cinematographer","@type":"WebPage","url":"http://localhost:4000/404.html","headline":"Jalil Butrón","@context":"http://schema.org"}</script> <!-- End Jekyll SEO tag --> <link rel="stylesheet" href="/assets/main.css"><link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="Jalil Butrón" /><!-- Favicon --> <link rel="shortcut icon" type="image/png" href="/assets/favicon.png"> <link rel="shortcut icon" sizes="196x196" href="/assets/favicon.png"> <link rel="apple-touch-icon" href="/assets/favicon.png"> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous"> </head> <body> <div class="body-container"><header class="site-header" role="banner"> <div class="wrapper"><div class="site-title"> <a rel="author" href="/"> <strong>Jalil Butrón</strong> <span>Cinematographer</span> </a> </div><nav class="site-nav"> <input type="checkbox" id="nav-trigger" class="nav-trigger" /> <label for="nav-trigger"> <span class="menu-icon"> <svg viewBox="0 0 18 15" width="18px" height="15px"> <path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/> </svg> </span> </label> <div class="trigger"><a class="page-link" href="/stills/">Stills</a><a class="page-link" href="/contact">Contact</a></div> </nav></div> </header> <main class="page-wrapper" aria-label="Content"> <div class="wrapper"> <style type="text/css" media="screen"> .container { margin: 10px auto; max-width: 600px; text-align: center; } h1 { margin: 30px 0; font-size: 4em; line-height: 1; letter-spacing: -1px; } </style> <div class="container"> <h1>404</h1> <p><strong>Page not found :(</strong></p> <p>The requested page could not be found.</p> </div> </div> </main><footer class="site-footer h-card"> <data class="u-url" href="/"></data> <div class="wrapper"><div class="footer-social"> <a class="no-underline" href="https://instagram.com/jalilbutron" target="_blank"><i class="fab fa-instagram fa-lg"></i></a> <a class="no-underline" href="https://vimeo.com/jalilbutron" target="_blank"><i class="fab fa-vimeo-v fa-lg"></i></a> </div><h5> &copy Jalil Butrón. All rights reserved. 2020 </h5> </div> </footer> </div> <script> </script> </body> </html>
jalilmdx1/jalilmdx1.github.io
_site/404.html
HTML
mit
3,826
require 'multi_xml' require 'ostruct' require 'roxml' module WxHelper module XmlHelper class Message def initialize(xml) hash = parse_xml xml @source = OpenStruct.new(hash['xml']) end def method_missing(method, *args, &block) @source.send(method.to_s.classify, *args, &block) end def parse_xml xml MultiXml.parse(xml) end end # <xml> # <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> # <Package><![CDATA[a=1&url=http%3A%2F%2Fwww.qq.com]]></Package> # <TimeStamp> 1369745073</TimeStamp> # <NonceStr><![CDATA[iuytxA0cH6PyTAVISB28]]></NonceStr> # <RetCode>0</RetCode> # <RetErrMsg><![CDATA[ok]]></ RetErrMsg> # <AppSignature><![CDATA[53cca9d47b883bd4a5c85a9300df3da0cb48565c]]> # </AppSignature> # <SignMethod><![CDATA[sha1]]></ SignMethod > # </xml> PackageMessage = Class.new(Message) # <xml> # <OpenId><![CDATA[111222]]></OpenId> # <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> # <IsSubscribe>1</IsSubscribe> # <TimeStamp> 1369743511</TimeStamp> # <NonceStr><![CDATA[jALldRTHAFd5Tgs5]]></NonceStr> # <AppSignature><![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]> # </AppSignature> # <SignMethod><![CDATA[sha1]]></ SignMethod > # </xml> NotifyMessage = Class.new(Message) # <xml> # <OpenId><![CDATA[111222]]></OpenId> # <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> # <TimeStamp> 1369743511</TimeStamp> # <MsgType><![CDATA[request]]></MsgType> # <FeedBackId><![CDATA[5883726847655944563]]></FeedBackId> # <TransId><![CDATA[10123312412321435345]]></TransId> # <Reason><![CDATA[商品质量有问题]]></Reason> # <Solution><![CDATA[补发货给我]]></Solution> # <ExtInfo><![CDATA[明天六点前联系我 18610847266]]></ExtInfo> # <AppSignature><![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]> # </AppSignature> # <SignMethod><![CDATA[sha1]]></ SignMethod > # </xml> # <xml> # <OpenId><![CDATA[111222]]></OpenId> # <AppId><![CDATA[wwwwb4f85f3a797777]]></AppId> # <TimeStamp> 1369743511</TimeStamp> # <MsgType><![CDATA[confirm/reject]]></MsgType> # <FeedBackId><![CDATA[5883726847655944563]]></FeedBackId> # <Reason><![CDATA[商品质量有问题]]></Reason> # <AppSignature><![CDATA[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]> # </AppSignature> # <SignMethod><![CDATA[sha1]]></ SignMethod > # </xml> PayFeedbackMessage = Class.new(Message) # <xml> # <AppId><![CDATA[wxf8b4f85f3a794e77]]></AppId> # <ErrorType>1001</ErrorType> # <Description><![CDATA[错识描述]]></Description> # <AlarmContent><![CDATA[错误详情]]></AlarmContent> # <TimeStamp>1393860740</TimeStamp> # <AppSignature><![CDATA[f8164781a303f4d5a944a2dfc68411a8c7e4fbea]]></AppSignature> # <SignMethod><![CDATA[sha1]]></SignMethod> # </xml> WarningMessage = Class.new(Message) class ResponseMessage include ROXML xml_name :xml xml_convention :camelcase xml_accessor :app_id, :cdata => true xml_accessor :package, :cdata => true xml_accessor :nonce_str, :cdata => true xml_accessor :ret_err_msg, :cdata => true xml_accessor :app_signature, :cdata => true xml_accessor :sign_method, :cdata => true xml_accessor :time_stamp, :as => Integer xml_accessor :ret_code, :as => Integer def initialize @sign_method = "sha1" end def to_xml super.to_xml(:encoding => 'UTF-8', :indent => 0, :save_with => 0) end end end end
sforce100/wxpay
lib/wxpay/helpers/xml_helper.rb
Ruby
mit
3,671
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>qarith: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0 / qarith - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> qarith <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-13 20:16:59 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-13 20:16:59 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.5.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/qarith&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/QArith&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: Q&quot; &quot;keyword: arithmetic&quot; &quot;keyword: rational numbers&quot; &quot;keyword: setoid&quot; &quot;keyword: ring&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Rational numbers&quot; &quot;category: Miscellaneous/Extracted Programs/Arithmetic&quot; ] authors: [ &quot;Pierre Letouzey&quot; ] bug-reports: &quot;https://github.com/coq-contribs/qarith/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/qarith.git&quot; synopsis: &quot;A Library for Rational Numbers (QArith)&quot; description: &quot;&quot;&quot; This contribution is a proposition of a library formalizing rational number in Coq.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/qarith/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=dbb5eb51a29032589cd351ea9eaf49a0&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-qarith.8.9.0 coq.8.5.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0). The following dependencies couldn&#39;t be met: - coq-qarith -&gt; coq &gt;= 8.9 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-qarith.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.5.0/qarith/8.9.0.html
HTML
mit
7,079
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-finmap: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / mathcomp-finmap - 1.3.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-finmap <small> 1.3.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-20 06:05:22 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-20 06:05:22 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Cyril Cohen &lt;[email protected]&gt;&quot; homepage: &quot;https://github.com/math-comp/finmap&quot; bug-reports: &quot;https://github.com/math-comp/finmap/issues&quot; dev-repo: &quot;git+https://github.com/math-comp/finmap.git&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;install&quot; ] depends: [ &quot;coq&quot; { (&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.11~&quot;) } &quot;coq-mathcomp-ssreflect&quot; { (&gt;= &quot;1.8.0&quot; &amp; &lt; &quot;1.10~&quot;) } &quot;coq-mathcomp-bigenough&quot; { (&gt;= &quot;1.0.0&quot; &amp; &lt; &quot;1.1~&quot;) } ] tags: [ &quot;keyword:finmap&quot; &quot;keyword:finset&quot; &quot;keyword:multiset&quot; &quot;keyword:order&quot; &quot;date:2019-06-13&quot; &quot;logpath:mathcomp.finmap&quot;] authors: [ &quot;Cyril Cohen &lt;[email protected]&gt;&quot; &quot;Kazuhiko Sakaguchi &lt;[email protected]&gt;&quot; ] synopsis: &quot;Finite sets, finite maps, finitely supported functions, orders&quot; description: &quot;&quot;&quot; This library is an extension of mathematical component in order to support finite sets and finite maps on choicetypes (rather that finite types). This includes support for functions with finite support and multisets. The library also contains a generic order and set libary, which will be used to subsume notations for finite sets, eventually.&quot;&quot;&quot; url { src: &quot;https://github.com/math-comp/finmap/archive/1.3.1.tar.gz&quot; checksum: &quot;sha256=5b90b4dbb1c851be7a835493ef81471238260580e2d1b340dc4cf40668c6a15b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-finmap.1.3.1 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-mathcomp-finmap -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-finmap.1.3.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.10.2-2.0.6/extra-dev/dev/mathcomp-finmap/1.3.1.html
HTML
mit
7,511
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using P03_FootballBetting.Data.Models; using System; using System.Collections.Generic; using System.Text; namespace P03_FootballBetting.Data.EntitiesConfiguration { public class PositionConfig : IEntityTypeConfiguration<Position> { public void Configure(EntityTypeBuilder<Position> builder) { builder.Property(x => x.Name) .IsRequired() .IsUnicode(); builder.HasMany(x => x.Players) .WithOne(x => x.Position) .HasForeignKey(x => x.PositionId); } } }
radoikoff/SoftUni
DB Advanced/EntityRelations/FootballBettingDatabase/P03_FootballBetting.Data/EntitiesConfiguration/PositionConfig.cs
C#
mit
687
/** * @file * @author Mamadou Babaei <[email protected]> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2016 - 2021 Mamadou Babaei * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @section DESCRIPTION * * Provides zlib, gzip and bzip2 comprission / decompression algorithms. */ #ifndef CORELIB_COMPRESSION_HPP #define CORELIB_COMPRESSION_HPP #include <string> #include <vector> namespace CoreLib { class Compression; } class CoreLib::Compression { public: typedef std::vector<char> Buffer; public: enum class Algorithm : unsigned char { Zlib, Gzip, Bzip2 }; public: static void Compress(const char *data, const size_t size, Buffer &out_compressedBuffer, const Algorithm &algorithm); static void Compress(const std::string &dataString, Buffer &out_compressedBuffer, const Algorithm &algorithm); static void Compress(const Buffer &dataBuffer, Buffer &out_compressedBuffer, const Algorithm &algorithm); static void Decompress(const Buffer &dataBuffer, std::string &out_uncompressedString, const Algorithm &algorithm); static void Decompress(const Buffer &dataBuffer, Buffer &out_uncompressedBuffer, const Algorithm &algorithm); }; #endif /* CORELIB_COMPRESSION_HPP */
NuLL3rr0r/blog-subscription-service
CoreLib/Compression.hpp
C++
mit
2,563
# v0.6.10 * Original: [Release atom-shell v0.6.10 - electron/electron](https://github.com/electron/electron/releases/tag/v0.6.10) Changelog: * Build binary for Mac on OS X 10.8.5. * OS X 10.8.5 Mac 向けバイナリーをビルドしました * Mountain Lion 向け * Fix a possible dead lock when quitting. * アプリ終了時にデッド ロックする可能性のある問題を修正しました * 安定性の向上 * Enable setting window icons when creating window. * ウィンドウ生成時にウィンドウ アイコン設定を有効にしました * Electron v0.6.9 のウィンドウ アイコン設定を受けての対応
akabekobeko/electron-release-notes-ja-private-edition
v0.x/v0.6/v0.6.10.ja.md
Markdown
mit
656
import asyncio import email.utils import json import sys from cgi import parse_header from collections import namedtuple from http.cookies import SimpleCookie from urllib.parse import parse_qs, unquote, urlunparse from httptools import parse_url from sanic.exceptions import InvalidUsage from sanic.log import error_logger, logger try: from ujson import loads as json_loads except ImportError: if sys.version_info[:2] == (3, 5): def json_loads(data): # on Python 3.5 json.loads only supports str not bytes return json.loads(data.decode()) else: json_loads = json.loads DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream" # HTTP/1.1: https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1 # > If the media type remains unknown, the recipient SHOULD treat it # > as type "application/octet-stream" class RequestParameters(dict): """Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang """ def get(self, name, default=None): """Return the first value, either the default or actual""" return super().get(name, [default])[0] def getlist(self, name, default=None): """Return the entire list""" return super().get(name, default) class StreamBuffer: def __init__(self, buffer_size=100): self._queue = asyncio.Queue(buffer_size) async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload async def put(self, payload): await self._queue.put(payload) def is_full(self): return self._queue.full() class Request(dict): """Properties of an HTTP request such as URL, headers, etc.""" __slots__ = ( "__weakref__", "_cookies", "_ip", "_parsed_url", "_port", "_remote_addr", "_socket", "app", "body", "endpoint", "headers", "method", "parsed_args", "parsed_files", "parsed_form", "parsed_json", "raw_url", "stream", "transport", "uri_template", "version", ) def __init__(self, url_bytes, headers, version, method, transport): self.raw_url = url_bytes # TODO: Content-Encoding detection self._parsed_url = parse_url(url_bytes) self.app = None self.headers = headers self.version = version self.method = method self.transport = transport # Init but do not inhale self.body_init() self.parsed_json = None self.parsed_form = None self.parsed_files = None self.parsed_args = None self.uri_template = None self._cookies = None self.stream = None self.endpoint = None def __repr__(self): return "<{0}: {1} {2}>".format( self.__class__.__name__, self.method, self.path ) def __bool__(self): if self.transport: return True return False def body_init(self): self.body = [] def body_push(self, data): self.body.append(data) def body_finish(self): self.body = b"".join(self.body) @property def json(self): if self.parsed_json is None: self.load_json() return self.parsed_json def load_json(self, loads=json_loads): try: self.parsed_json = loads(self.body) except Exception: if not self.body: return None raise InvalidUsage("Failed when parsing body as json") return self.parsed_json @property def token(self): """Attempt to return the auth header token. :return: token related to request """ prefixes = ("Bearer", "Token") auth_header = self.headers.get("Authorization") if auth_header is not None: for prefix in prefixes: if prefix in auth_header: return auth_header.partition(prefix)[-1].strip() return auth_header @property def form(self): if self.parsed_form is None: self.parsed_form = RequestParameters() self.parsed_files = RequestParameters() content_type = self.headers.get( "Content-Type", DEFAULT_HTTP_CONTENT_TYPE ) content_type, parameters = parse_header(content_type) try: if content_type == "application/x-www-form-urlencoded": self.parsed_form = RequestParameters( parse_qs(self.body.decode("utf-8")) ) elif content_type == "multipart/form-data": # TODO: Stream this instead of reading to/from memory boundary = parameters["boundary"].encode("utf-8") self.parsed_form, self.parsed_files = parse_multipart_form( self.body, boundary ) except Exception: error_logger.exception("Failed when parsing form") return self.parsed_form @property def files(self): if self.parsed_files is None: self.form # compute form to get files return self.parsed_files @property def args(self): if self.parsed_args is None: if self.query_string: self.parsed_args = RequestParameters( parse_qs(self.query_string) ) else: self.parsed_args = RequestParameters() return self.parsed_args @property def raw_args(self): return {k: v[0] for k, v in self.args.items()} @property def cookies(self): if self._cookies is None: cookie = self.headers.get("Cookie") if cookie is not None: cookies = SimpleCookie() cookies.load(cookie) self._cookies = { name: cookie.value for name, cookie in cookies.items() } else: self._cookies = {} return self._cookies @property def ip(self): if not hasattr(self, "_socket"): self._get_address() return self._ip @property def port(self): if not hasattr(self, "_socket"): self._get_address() return self._port @property def socket(self): if not hasattr(self, "_socket"): self._get_address() return self._socket def _get_address(self): self._socket = self.transport.get_extra_info("peername") or ( None, None, ) self._ip = self._socket[0] self._port = self._socket[1] @property def remote_addr(self): """Attempt to return the original client ip based on X-Forwarded-For. :return: original client ip. """ if not hasattr(self, "_remote_addr"): forwarded_for = self.headers.get("X-Forwarded-For", "").split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if len(remote_addrs) > 0: self._remote_addr = remote_addrs[0] else: self._remote_addr = "" return self._remote_addr @property def scheme(self): if ( self.app.websocket_enabled and self.headers.get("upgrade") == "websocket" ): scheme = "ws" else: scheme = "http" if self.transport.get_extra_info("sslcontext"): scheme += "s" return scheme @property def host(self): # it appears that httptools doesn't return the host # so pull it from the headers return self.headers.get("Host", "") @property def content_type(self): return self.headers.get("Content-Type", DEFAULT_HTTP_CONTENT_TYPE) @property def match_info(self): """return matched info after resolving route""" return self.app.router.get(self)[2] @property def path(self): return self._parsed_url.path.decode("utf-8") @property def query_string(self): if self._parsed_url.query: return self._parsed_url.query.decode("utf-8") else: return "" @property def url(self): return urlunparse( (self.scheme, self.host, self.path, None, self.query_string, None) ) File = namedtuple("File", ["type", "body", "name"]) def parse_multipart_form(body, boundary): """Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters) """ files = RequestParameters() fields = RequestParameters() form_parts = body.split(boundary) for form_part in form_parts[1:-1]: file_name = None content_type = "text/plain" content_charset = "utf-8" field_name = None line_index = 2 line_end_index = 0 while not line_end_index == -1: line_end_index = form_part.find(b"\r\n", line_index) form_line = form_part[line_index:line_end_index].decode("utf-8") line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(":") form_header_field = form_line[0:colon_index].lower() form_header_value, form_parameters = parse_header( form_line[colon_index + 2 :] ) if form_header_field == "content-disposition": field_name = form_parameters.get("name") file_name = form_parameters.get("filename") # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get("filename*"): encoding, _, value = email.utils.decode_rfc2231( form_parameters["filename*"] ) file_name = unquote(value, encoding=encoding) elif form_header_field == "content-type": content_type = form_header_value content_charset = form_parameters.get("charset", "utf-8") if field_name: post_data = form_part[line_index:-4] if file_name is None: value = post_data.decode(content_charset) if field_name in fields: fields[field_name].append(value) else: fields[field_name] = [value] else: form_file = File( type=content_type, name=file_name, body=post_data ) if field_name in files: files[field_name].append(form_file) else: files[field_name] = [form_file] else: logger.debug( "Form-data field does not have a 'name' parameter " "in the Content-Disposition header" ) return fields, files
lixxu/sanic
sanic/request.py
Python
mit
11,420
require 'stringio' require 'highline/import' module RailsZen class ChosenAttr attr_accessor :name, :type, :validator, :type_based_validators, :scope_attr def initialize(name, type) @name = name @type = type @scope_attr = [] end def get_user_inputs get_presence_req get_type_based_validations end def get_presence_req say "\n\nShould :#{name} be present always in your record?\n" say"--------------------------------------------------------------" inp = agree("Reply with y or n") if inp @validator = "validates_presence_of" #say "What should be the default value? If there is no default value enter n" #val = $stdin.gets.strip #if val != 'n' #@default_value = val #end get_uniqueness_req else @validator = nil end end def get_uniqueness_req say "Should :#{name} be an unique column?\n" say "-------------------------------------\n\n" say "Reply with \n 0 if it is not unique \n 1 if it is just unique \n 2 if it is unique with respect to another attr \n\n" inp = ask("Please enter", Integer) { |q| q.in = 0..2 } if inp == 2 #say "Setting presence true in your models and migrations" say "\n#{name} is unique along with ?\n Reply with attr name\n " if is_relation? @scope_attr << "#{name}_id" unless name.end_with? "_id" end say("if it is a relation reply along with id: eg: user_id \n\n $->") @scope_attr << ask("Enter (comma sep list) ", lambda { |str| str.split(/,\s*/) }) @scope_attr = @scope_attr.flatten.map(&:to_sym) @validator = "validates_uniqueness_scoped_to" elsif inp == 1 @validator = "validates_uniqueness_of" end end def get_type_based_validations if(type == "integer" || type == "decimal") @validator_line = "#@validator_line, numericality: true" say "#{name} is an integer do you want to check \n 1 just the numericality? \n 2 check if it is only integer\n\n $-> " input = ask("Please enter", Integer) { |q| q.in = 1..2} map_input = { 1 => "validate_numericality", 2 => "validate_integer" #"3" => "validate_greater_than", "4" => "validate_lesser_than" } @type_based_validators = map_input[input] elsif(is_relation?) @type_based_validators = "validate_belongs_to" end end def is_relation? type =="belongs_to" || type == "references" || (type.end_with? "_id") end end end
vysakh0/rails_zen
lib/rails_zen/chosen_attr.rb
Ruby
mit
2,712
# frozen_string_literal: true RSpec::Matchers.define :enforce_authorization_api do expected_error = { 'error' => 'User is not authorized to access this resource.' } match do |actual| expect(actual).to have_http_status(403) expect(JSON.parse(actual.body)).to eq(expected_error) end failure_message do |actual| "expected to receive 403 status code (forbidden) and '#{expected_error}' " \ "as the response body. Received #{actual.status} status and "\ "'#{JSON.parse(actual.body)}' response body instead." end failure_message_when_negated do "expected not to receive 403 status (forbidden) or '#{expected_error}' "\ 'in the response body, but it did.' end description do 'enforce authorization policies when accessing API resources.' end end
brunofacca/zen-rails-base-app
spec/support/matchers/enforce_authorization_api.rb
Ruby
mit
804
from .tile import Split, Stack, TileStack class Tile(Split): class left(Stack): weight = 3 priority = 0 limit = 1 class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324
tailhook/tilenol
tilenol/layout/examples.py
Python
mit
657
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /** * @overview */ /** * Creates a folder properties dialog. * @class * This class represents a folder properties dialog. * * @param {DwtControl} parent the parent * @param {String} className the class name * * @extends DwtDialog */ ZmFolderPropsDialog = function(parent, className) { className = className || "ZmFolderPropsDialog"; var extraButtons; if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { extraButtons = [ new DwtDialog_ButtonDescriptor(ZmFolderPropsDialog.ADD_SHARE_BUTTON, ZmMsg.addShare, DwtDialog.ALIGN_LEFT) ]; } DwtDialog.call(this, {parent:parent, className:className, title:ZmMsg.folderProperties, extraButtons:extraButtons, id:"FolderProperties"}); this._tabViews = []; this._tabKeys = []; this._tabInUse = []; this._tabKeyMap = {}; if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this.registerCallback(ZmFolderPropsDialog.ADD_SHARE_BUTTON, this._handleAddShareButton, this); } this.setButtonListener(DwtDialog.OK_BUTTON, new AjxListener(this, this._handleOkButton)); this.setButtonListener(DwtDialog.CANCEL_BUTTON, new AjxListener(this, this._handleCancelButton)); this._folderChangeListener = new AjxListener(this, this._handleFolderChange); this._createView(); }; ZmFolderPropsDialog.prototype = new DwtDialog; ZmFolderPropsDialog.prototype.constructor = ZmFolderPropsDialog; // Constants ZmFolderPropsDialog.ADD_SHARE_BUTTON = ++DwtDialog.LAST_BUTTON; ZmFolderPropsDialog.SHARES_HEIGHT = "9em"; // Tab identifiers ZmFolderPropsDialog.TABKEY_PROPERTIES = "PROPERTIES_TAB"; ZmFolderPropsDialog.TABKEY_RETENTION = "RETENTION_TAB"; // Public methods ZmFolderPropsDialog.prototype.toString = function() { return "ZmFolderPropsDialog"; }; ZmFolderPropsDialog.prototype.getTabKey = function(id) { var index = this._tabKeyMap[id]; return this._tabKeys[index]; }; /** * Pops-up the properties dialog. * * @param {ZmOrganizer} organizer the organizer */ ZmFolderPropsDialog.prototype.popup = function(organizer) { this._organizer = organizer; for (var i = 0; i < this._tabViews.length; i++) { this._tabViews[i].setOrganizer(organizer); } // On popup, make the property view visible var tabKey = this.getTabKey(ZmFolderPropsDialog.TABKEY_PROPERTIES); this._tabContainer.switchToTab(tabKey, true); organizer.addChangeListener(this._folderChangeListener); this._handleFolderChange(); if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { var isShareable = ZmOrganizer.SHAREABLE[organizer.type]; var isVisible = (!organizer.link || organizer.isAdmin()); this.setButtonVisible(ZmFolderPropsDialog.ADD_SHARE_BUTTON, isVisible && isShareable); } DwtDialog.prototype.popup.call(this); }; ZmFolderPropsDialog.prototype.popdown = function() { if (this._organizer) { this._organizer.removeChangeListener(this._folderChangeListener); this._organizer = null; } DwtDialog.prototype.popdown.call(this); }; // Protected methods ZmFolderPropsDialog.prototype._getSeparatorTemplate = function() { return ""; }; ZmFolderPropsDialog.prototype._handleEditShare = function(event, share) { share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); var sharePropsDialog = appCtxt.getSharePropsDialog(); sharePropsDialog.popup(ZmSharePropsDialog.EDIT, share.object, share); return false; }; ZmFolderPropsDialog.prototype._handleRevokeShare = function(event, share) { share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); var revokeShareDialog = appCtxt.getRevokeShareDialog(); revokeShareDialog.popup(share); return false; }; ZmFolderPropsDialog.prototype._handleResendShare = function(event, share) { AjxDispatcher.require("Share"); share = share || Dwt.getObjectFromElement(DwtUiEvent.getTarget(event)); // create share info var tmpShare = new ZmShare({object:share.object}); tmpShare.grantee.id = share.grantee.id; tmpShare.grantee.email = (share.grantee.type == "guest") ? share.grantee.id : share.grantee.name; tmpShare.grantee.name = share.grantee.name; if (tmpShare.object.isRemote()) { tmpShare.grantor.id = tmpShare.object.zid; tmpShare.grantor.email = tmpShare.object.owner; tmpShare.grantor.name = tmpShare.grantor.email; tmpShare.link.id = tmpShare.object.rid; } else { tmpShare.grantor.id = appCtxt.get(ZmSetting.USERID); tmpShare.grantor.email = appCtxt.get(ZmSetting.USERNAME); tmpShare.grantor.name = appCtxt.get(ZmSetting.DISPLAY_NAME) || tmpShare.grantor.email; tmpShare.link.id = tmpShare.object.id; } tmpShare.link.name = share.object.name; tmpShare.link.view = ZmOrganizer.getViewName(share.object.type); tmpShare.link.perm = share.link.perm; if (share.grantee.type == "guest") { // Pass action as ZmShare.NEW even for resend for external user tmpShare._sendShareNotification(tmpShare.grantee.email, tmpShare.link.id, "", ZmShare.NEW); } else { tmpShare.sendMessage(ZmShare.NEW); } appCtxt.setStatusMsg(ZmMsg.resentShareMessage); return false; }; ZmFolderPropsDialog.prototype._handleAddShareButton = function(event) { var sharePropsDialog = appCtxt.getSharePropsDialog(); sharePropsDialog.popup(ZmSharePropsDialog.NEW, this._organizer, null); }; ZmFolderPropsDialog.prototype._handleOkButton = function(event) { // New batch command, stop on error var batchCommand = new ZmBatchCommand(null, null, true); var saveState = { commandCount: 0, errorMessage: [] }; for (var i = 0; i < this._tabViews.length; i++) { if (this._tabInUse[i]) { // Save all in use tabs this._tabViews[i].doSave(batchCommand, saveState); } } if (saveState.errorMessage.length > 0) { var msg = saveState.errorMessage.join("<br>"); var dialog = appCtxt.getMsgDialog(); dialog.reset(); dialog.setMessage(msg, DwtMessageDialog.WARNING_STYLE); dialog.popup(); } else if (saveState.commandCount > 0) { var callback = new AjxCallback(this, this.popdown); batchCommand.run(callback); } else { this.popdown(); } }; ZmFolderPropsDialog.prototype._handleError = function(response) { // Returned 'not handled' so that the batch command will preform the default // ZmController._handleException return false; }; ZmFolderPropsDialog.prototype._handleCancelButton = function(event) { this.popdown(); }; ZmFolderPropsDialog.prototype._handleFolderChange = function(event) { var organizer = this._organizer; // Get the components that will be hidden or displayed var tabBar = this._tabContainer.getTabBar(); var tabKey = this.getTabKey(ZmFolderPropsDialog.TABKEY_RETENTION); var retentionTabButton = this._tabContainer.getTabButton(tabKey); var retentionIndex = this._tabKeyMap[ZmFolderPropsDialog.TABKEY_RETENTION]; if ((organizer.type != ZmOrganizer.FOLDER) || organizer.link) { // Not a folder, or shared - hide the retention view (and possibly the toolbar) this._tabInUse[retentionIndex] = false; if (this._tabViews.length > 2) { // More than two tabs, hide the retention tab, leave the toolbar intact tabBar.setVisible(true); retentionTabButton.setVisible(false); } else { // Two or fewer tabs. Hide the toolbar, just let the properties view display standalone // (On popup, the display defaults to the property view) tabBar.setVisible(false); } } else { // Using the retention tab view - show the toolbar and all tabs this._tabInUse[retentionIndex] = true; retentionTabButton.setVisible(true); tabBar.setVisible(true); } for (var i = 0; i < this._tabViews.length; i++) { if (this._tabInUse[i]) { // Update all in use tabs to use the specified folder this._tabViews[i]._handleFolderChange(event); } } if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this._populateShares(organizer); } }; ZmFolderPropsDialog.prototype._populateShares = function(organizer) { this._sharesGroup.setContent(""); var displayShares = this._getDisplayShares(organizer); var getFolder = false; if (displayShares.length) { for (var i = 0; i < displayShares.length; i++) { var share = displayShares[i]; if (!(share.grantee && share.grantee.name)) { getFolder = true; } } } if (getFolder) { var respCallback = new AjxCallback(this, this._handleResponseGetFolder, [displayShares]); organizer.getFolder(respCallback); } else { this._handleResponseGetFolder(displayShares); } this._sharesGroup.setVisible(displayShares.length > 0); }; ZmFolderPropsDialog.prototype._getDisplayShares = function(organizer) { var shares = organizer.shares; var displayShares = []; if ((!organizer.link || organizer.isAdmin()) && shares && shares.length > 0) { AjxDispatcher.require("Share"); var userZid = appCtxt.accountList.mainAccount.id; // if a folder was shared with us with admin rights, a share is created since we could share it; // don't show any share that's for us in the list for (var i = 0; i < shares.length; i++) { var share = shares[i]; if (share.grantee) { var granteeId = share.grantee.id; if ((share.grantee.type != ZmShare.TYPE_USER) || (share.grantee.id != userZid)) { displayShares.push(share); } } } } return displayShares; }; ZmFolderPropsDialog.prototype._handleResponseGetFolder = function(displayShares, organizer) { if (organizer) { displayShares = this._getDisplayShares(organizer); } if (displayShares.length) { var table = document.createElement("TABLE"); table.className = "ZPropertySheet"; table.cellSpacing = "6"; for (var i = 0; i < displayShares.length; i++) { var share = displayShares[i]; var row = table.insertRow(-1); var nameEl = row.insertCell(-1); nameEl.style.paddingRight = "15px"; var nameText = share.grantee && share.grantee.name; if (share.isAll()) { nameText = ZmMsg.shareWithAll; } else if (share.isPublic()) { nameText = ZmMsg.shareWithPublic; } else if (share.isGuest()){ nameText = nameText || (share.grantee && share.grantee.id); } nameEl.innerHTML = AjxStringUtil.htmlEncode(nameText); var roleEl = row.insertCell(-1); roleEl.style.paddingRight = "15px"; roleEl.innerHTML = ZmShare.getRoleName(share.link.role); this.__createCmdCells(row, share); } this._sharesGroup.setElement(table); var width = Dwt.DEFAULT; var height = displayShares.length > 5 ? ZmFolderPropsDialog.SHARES_HEIGHT : Dwt.CLEAR; var insetElement = this._sharesGroup.getInsetHtmlElement(); Dwt.setScrollStyle(insetElement, Dwt.SCROLL); Dwt.setSize(insetElement, width, height); } this._sharesGroup.setVisible(displayShares.length > 0); }; ZmFolderPropsDialog.prototype.__createCmdCells = function(row, share) { var type = share.grantee.type; if (type == ZmShare.TYPE_DOMAIN || !share.link.role) { var cell = row.insertCell(-1); cell.colSpan = 3; cell.innerHTML = ZmMsg.configureWithAdmin; return; } var actions = [ZmShare.EDIT, ZmShare.REVOKE, ZmShare.RESEND]; var handlers = [this._handleEditShare, this._handleRevokeShare, this._handleResendShare]; for (var i = 0; i < actions.length; i++) { var action = actions[i]; var cell = row.insertCell(-1); // public shares have no editable fields, and sent no mail var isAllShare = share.grantee && (share.grantee.type == ZmShare.TYPE_ALL); if (((isAllShare || share.isPublic() || share.isGuest()) && (action == ZmShare.EDIT)) || ((isAllShare || share.isPublic()) && action == ZmShare.RESEND)) { continue; } var link = document.createElement("A"); link.href = "#"; link.innerHTML = ZmShare.ACTION_LABEL[action]; Dwt.setHandler(link, DwtEvent.ONCLICK, handlers[i]); Dwt.associateElementWithObject(link, share); cell.appendChild(link); } }; ZmFolderPropsDialog.prototype.addTab = function(index, id, tabViewPage) { if (!this._tabContainer || !tabViewPage) { return null; } this._tabViews[index] = tabViewPage; this._tabKeys[index] = this._tabContainer.addTab(tabViewPage.getTitle(), tabViewPage); this._tabInUse[index] = true; this._tabKeyMap[id] = index; return this._tabKeys[index]; }; ZmFolderPropsDialog.prototype._initializeTabView = function(view) { this._tabContainer = new DwtTabView(view, null, Dwt.STATIC_STYLE); //ZmFolderPropertyView handle things such as color and type. (in case you're searching for "color" and can't find in this file. I know I did) this.addTab(0, ZmFolderPropsDialog.TABKEY_PROPERTIES, new ZmFolderPropertyView(this, this._tabContainer)); this.addTab(1, ZmFolderPropsDialog.TABKEY_RETENTION, new ZmFolderRetentionView(this, this._tabContainer)); // setup shares group if (appCtxt.get(ZmSetting.SHARING_ENABLED)) { this._sharesGroup = new DwtGrouper(view, "DwtGrouper ZmFolderPropSharing"); this._sharesGroup.setLabel(ZmMsg.folderSharing); this._sharesGroup.setVisible(false); this._sharesGroup.setScrollStyle(Dwt.SCROLL); view.getHtmlElement().appendChild(this._sharesGroup.getHtmlElement()); } }; // This creates the tab views managed by this dialog, the tabToolbar, and // the share buttons and view components ZmFolderPropsDialog.prototype._createView = function() { this._baseContainerView = new DwtComposite({parent:this, className:"ZmFolderPropertiesDialog-container "}); this._initializeTabView(this._baseContainerView); this.setView(this._baseContainerView); };
nico01f/z-pec
ZimbraWebClient/WebRoot/js/zimbraMail/share/view/dialog/ZmFolderPropsDialog.js
JavaScript
mit
14,081
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.Part; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import com.zimbra.common.account.Key.AccountBy; import com.zimbra.common.httpclient.HttpClientUtil; import com.zimbra.common.localconfig.LC; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.AdminConstants; import com.zimbra.common.soap.Element; import com.zimbra.common.soap.MailConstants; import com.zimbra.common.soap.SoapFaultException; import com.zimbra.common.soap.SoapHttpTransport; import com.zimbra.common.util.BufferStream; import com.zimbra.common.util.ByteUtil; import com.zimbra.common.util.CliUtil; import com.zimbra.common.util.Log; import com.zimbra.common.util.LogFactory; import com.zimbra.common.util.ZimbraCookie; import com.zimbra.common.zmime.ZMimeMessage; import com.zimbra.common.zmime.ZSharedFileInputStream; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.Config; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.account.Server; import com.zimbra.cs.service.mail.ItemAction; public class SpamExtract { private static Log mLog = LogFactory.getLog(SpamExtract.class); private static Options mOptions = new Options(); static { mOptions.addOption("s", "spam", false, "extract messages from configured spam mailbox"); mOptions.addOption("n", "notspam", false, "extract messages from configured notspam mailbox"); mOptions.addOption("m", "mailbox", true, "extract messages from specified mailbox"); mOptions.addOption("d", "delete", false, "delete extracted messages (default is to keep)"); mOptions.addOption("o", "outdir", true, "directory to store extracted messages"); mOptions.addOption("a", "admin", true, "admin user name for auth (default is zimbra_ldap_userdn)"); mOptions.addOption("p", "password", true, "admin password for auth (default is zimbra_ldap_password)"); mOptions.addOption("u", "url", true, "admin SOAP service url (default is target mailbox's server's admin service port)"); mOptions.addOption("q", "query", true, "search query whose results should be extracted (default is in:inbox)"); mOptions.addOption("r", "raw", false, "extract raw message (default: gets message/rfc822 attachments)"); mOptions.addOption("h", "help", false, "show this usage text"); mOptions.addOption("D", "debug", false, "enable debug level logging"); mOptions.addOption("v", "verbose", false, "be verbose while running"); } private static void usage(String errmsg) { if (errmsg != null) { mLog.error(errmsg); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("zmspamextract [options] ", "where [options] are one of:", mOptions, "SpamExtract retrieve messages that may have been marked as spam or not spam in the Zimbra Web Client."); System.exit((errmsg == null) ? 0 : 1); } private static CommandLine parseArgs(String args[]) { CommandLineParser parser = new GnuParser(); CommandLine cl = null; try { cl = parser.parse(mOptions, args); } catch (ParseException pe) { usage(pe.getMessage()); } if (cl.hasOption("h")) { usage(null); } return cl; } private static boolean mVerbose = false; public static void main(String[] args) throws ServiceException, HttpException, SoapFaultException, IOException { CommandLine cl = parseArgs(args); if (cl.hasOption('D')) { CliUtil.toolSetup("DEBUG"); } else { CliUtil.toolSetup("INFO"); } if (cl.hasOption('v')) { mVerbose = true; } boolean optDelete = cl.hasOption('d'); if (!cl.hasOption('o')) { usage("must specify directory to extract messages to"); } String optDirectory = cl.getOptionValue('o'); File outputDirectory = new File(optDirectory); if (!outputDirectory.exists()) { mLog.info("Creating directory: " + optDirectory); outputDirectory.mkdirs(); if (!outputDirectory.exists()) { mLog.error("could not create directory " + optDirectory); System.exit(2); } } String optAdminUser; if (cl.hasOption('a')) { optAdminUser = cl.getOptionValue('a'); } else { optAdminUser = LC.zimbra_ldap_user.value(); } String optAdminPassword; if (cl.hasOption('p')) { optAdminPassword = cl.getOptionValue('p'); } else { optAdminPassword = LC.zimbra_ldap_password.value(); } String optQuery = "in:inbox"; if (cl.hasOption('q')) { optQuery = cl.getOptionValue('q'); } Account account = getAccount(cl); if (account == null) { System.exit(1); } boolean optRaw = cl.hasOption('r'); if (mVerbose) mLog.info("Extracting from account " + account.getName()); Server server = Provisioning.getInstance().getServer(account); String optAdminURL; if (cl.hasOption('u')) { optAdminURL = cl.getOptionValue('u'); } else { optAdminURL = getSoapURL(server, true); } String adminAuthToken = getAdminAuthToken(optAdminURL, optAdminUser, optAdminPassword); String authToken = getDelegateAuthToken(optAdminURL, account, adminAuthToken); extract(authToken, account, server, optQuery, outputDirectory, optDelete, optRaw); } public static final String TYPE_MESSAGE = "message"; private static void extract(String authToken, Account account, Server server, String query, File outdir, boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException { String soapURL = getSoapURL(server, false); URL restURL = getServerURL(server, false); HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr HttpState state = new HttpState(); GetMethod gm = new GetMethod(); gm.setFollowRedirects(true); Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1, false); state.addCookie(authCookie); hc.setState(state); hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(), Protocol.getProtocol(restURL.getProtocol())); gm.getParams().setSoTimeout(60000); if (mVerbose) mLog.info("Mailbox requests to: " + restURL); SoapHttpTransport transport = new SoapHttpTransport(soapURL); transport.setRetryCount(1); transport.setTimeout(0); transport.setAuthToken(authToken); int totalProcessed = 0; boolean haveMore = true; int offset = 0; while (haveMore) { Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST); searchReq.addElement(MailConstants.A_QUERY).setText(query); searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, TYPE_MESSAGE); searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset); try { if (mLog.isDebugEnabled()) mLog.debug(searchReq.prettyPrint()); Element searchResp = transport.invoke(searchReq, false, true, account.getId()); if (mLog.isDebugEnabled()) mLog.debug(searchResp.prettyPrint()); StringBuilder deleteList = new StringBuilder(); for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) { offset++; Element e = iter.next(); String mid = e.getAttribute(MailConstants.A_ID); if (mid == null) { mLog.warn("null message id SOAP response"); continue; } String path = "/service/user/" + account.getName() + "/?id=" + mid; if (extractMessage(hc, gm, path, outdir, raw)) { deleteList.append(mid).append(','); } totalProcessed++; } haveMore = false; String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE); if (more != null && more.length() > 0) { try { int m = Integer.parseInt(more); if (m > 0) { haveMore = true; } } catch (NumberFormatException nfe) { mLog.warn("more flag from server not a number: " + more, nfe); } } if (delete && deleteList.length() > 0) { deleteList.deleteCharAt(deleteList.length()-1); // -1 removes trailing comma Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST); Element action = msgActionReq.addElement(MailConstants.E_ACTION); action.addAttribute(MailConstants.A_ID, deleteList.toString()); action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE); if (mLog.isDebugEnabled()) mLog.debug(msgActionReq.prettyPrint()); Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId()); if (mLog.isDebugEnabled()) mLog.debug(msgActionResp.prettyPrint()); } } finally { gm.releaseConnection(); } } mLog.info("Total messages processed: " + totalProcessed); } private static Session mJMSession; private static String mOutputPrefix; static { Properties props = new Properties(); props.setProperty("mail.mime.address.strict", "false"); mJMSession = Session.getInstance(props); mOutputPrefix = Long.toHexString(System.currentTimeMillis()); } private static boolean extractMessage(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) { try { extractMessage0(hc, gm, path, outdir, raw); return true; } catch (MessagingException me) { mLog.warn("exception occurred fetching message", me); } catch (IOException ioe) { mLog.warn("exception occurred fetching message", ioe); } return false; } private static int mExtractIndex; private static final int MAX_BUFFER_SIZE = 10 * 1024 * 1024; private static void extractMessage0(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) throws IOException, MessagingException { gm.setPath(path); if (mLog.isDebugEnabled()) mLog.debug("Fetching " + path); HttpClientUtil.executeMethod(hc, gm); if (gm.getStatusCode() != HttpStatus.SC_OK) { throw new IOException("HTTP GET failed: " + gm.getPath() + ": " + gm.getStatusCode() + ": " + gm.getStatusText()); } if (raw) { // Write the message as-is. File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); ByteUtil.copy(gm.getResponseBodyAsStream(), true, os, false); if (mVerbose) mLog.info("Wrote: " + file); } catch (java.io.IOException e) { String fileName = outdir + "/" + mOutputPrefix + "-" + mExtractIndex; mLog.error("Cannot write to " + fileName, e); } finally { if (os != null) os.close(); } return; } // Write the attached message to the output directory. BufferStream buffer = new BufferStream(gm.getResponseContentLength(), MAX_BUFFER_SIZE); buffer.setSequenced(false); MimeMessage mm = null; InputStream fis = null; try { ByteUtil.copy(gm.getResponseBodyAsStream(), true, buffer, false); if (buffer.isSpooled()) { fis = new ZSharedFileInputStream(buffer.getFile()); mm = new ZMimeMessage(mJMSession, fis); } else { mm = new ZMimeMessage(mJMSession, buffer.getInputStream()); } writeAttachedMessages(mm, outdir, gm.getPath()); } finally { ByteUtil.closeStream(fis); } } private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri) throws IOException, MessagingException { // Not raw - ignore the spam report and extract messages that are in attachments... if (!(mm.getContent() instanceof MimeMultipart)) { mLog.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")"); return; } MimeMultipart mmp = (MimeMultipart)mm.getContent(); int nAttachments = mmp.getCount(); boolean foundAtleastOneAttachedMessage = false; for (int i = 0; i < nAttachments; i++) { BodyPart bp = mmp.getBodyPart(i); if (!bp.isMimeType("message/rfc822")) { // Let's ignore all parts that are not messages. continue; } foundAtleastOneAttachedMessage = true; Part msg = (Part) bp.getContent(); // the actual message File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); msg.writeTo(os); } finally { os.close(); } if (mVerbose) mLog.info("Wrote: " + file); } if (!foundAtleastOneAttachedMessage) { String msgid = mm.getHeader("Message-ID", " "); mLog.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments"); } } public static URL getServerURL(Server server, boolean admin) throws ServiceException { String host = server.getAttr(Provisioning.A_zimbraServiceHostname); if (host == null) { throw ServiceException.FAILURE("invalid " + Provisioning.A_zimbraServiceHostname + " in server " + server.getName(), null); } String protocol = "http"; String portAttr = Provisioning.A_zimbraMailPort; if (admin) { protocol = "https"; portAttr = Provisioning.A_zimbraAdminPort; } else { String mode = server.getAttr(Provisioning.A_zimbraMailMode); if (mode == null) { throw ServiceException.FAILURE("null " + Provisioning.A_zimbraMailMode + " in server " + server.getName(), null); } if (mode.equalsIgnoreCase("https")) { protocol = "https"; portAttr = Provisioning.A_zimbraMailSSLPort; } if (mode.equalsIgnoreCase("redirect")) { protocol = "https"; portAttr = Provisioning.A_zimbraMailSSLPort; } } int port = server.getIntAttr(portAttr, -1); if (port < 1) { throw ServiceException.FAILURE("invalid " + portAttr + " in server " + server.getName(), null); } try { return new URL(protocol, host, port, ""); } catch (MalformedURLException mue) { throw ServiceException.FAILURE("exception creating url (protocol=" + protocol + " host=" + host + " port=" + port + ")", mue); } } public static String getSoapURL(Server server, boolean admin) throws ServiceException { String url = getServerURL(server, admin).toString(); String file = admin ? AdminConstants.ADMIN_SERVICE_URI : AccountConstants.USER_SERVICE_URI; return url + file; } public static String getAdminAuthToken(String adminURL, String adminUser, String adminPassword) throws ServiceException { SoapHttpTransport transport = new SoapHttpTransport(adminURL); transport.setRetryCount(1); transport.setTimeout(0); Element authReq = new Element.XMLElement(AdminConstants.AUTH_REQUEST); authReq.addAttribute(AdminConstants.E_NAME, adminUser, Element.Disposition.CONTENT); authReq.addAttribute(AdminConstants.E_PASSWORD, adminPassword, Element.Disposition.CONTENT); try { if (mVerbose) mLog.info("Auth request to: " + adminURL); if (mLog.isDebugEnabled()) mLog.debug(authReq.prettyPrint()); Element authResp = transport.invokeWithoutSession(authReq); if (mLog.isDebugEnabled()) mLog.debug(authResp.prettyPrint()); String authToken = authResp.getAttribute(AdminConstants.E_AUTH_TOKEN); return authToken; } catch (Exception e) { throw ServiceException.FAILURE("admin auth failed url=" + adminURL, e); } } public static String getDelegateAuthToken(String adminURL, Account account, String adminAuthToken) throws ServiceException { SoapHttpTransport transport = new SoapHttpTransport(adminURL); transport.setRetryCount(1); transport.setTimeout(0); transport.setAuthToken(adminAuthToken); Element daReq = new Element.XMLElement(AdminConstants.DELEGATE_AUTH_REQUEST); Element acctElem = daReq.addElement(AdminConstants.E_ACCOUNT); acctElem.addAttribute(AdminConstants.A_BY, AdminConstants.BY_ID); acctElem.setText(account.getId()); try { if (mVerbose) mLog.info("Delegate auth request to: " + adminURL); if (mLog.isDebugEnabled()) mLog.debug(daReq.prettyPrint()); Element daResp = transport.invokeWithoutSession(daReq); if (mLog.isDebugEnabled()) mLog.debug(daResp.prettyPrint()); String authToken = daResp.getAttribute(AdminConstants.E_AUTH_TOKEN); return authToken; } catch (Exception e) { throw ServiceException.FAILURE("Delegate auth failed url=" + adminURL, e); } } private static Account getAccount(CommandLine cl) throws ServiceException { Provisioning prov = Provisioning.getInstance(); Config conf; try { conf = prov.getConfig(); } catch (ServiceException e) { throw ServiceException.FAILURE("Unable to connect to LDAP directory", e); } String name = null; if (cl.hasOption('s')) { if (cl.hasOption('n') || cl.hasOption('m')) { mLog.error("only one of s, n or m options can be specified"); return null; } name = conf.getAttr(Provisioning.A_zimbraSpamIsSpamAccount); if (name == null || name.length() == 0) { mLog.error("no account configured for spam"); return null; } } else if (cl.hasOption('n')) { if (cl.hasOption('m')) { mLog.error("only one of s, n, or m options can be specified"); return null; } name = conf.getAttr(Provisioning.A_zimbraSpamIsNotSpamAccount); if (name == null || name.length() == 0) { mLog.error("no account configured for ham"); return null; } } else if (cl.hasOption('m')) { name = cl.getOptionValue('m'); if (name.length() == 0) { mLog.error("illegal argument to m option"); return null; } } else { mLog.error("one of s, n or m options must be specified"); return null; } Account account = prov.get(AccountBy.name, name); if (account == null) { mLog.error("can not find account " + name); return null; } return account; } }
nico01f/z-pec
ZimbraServer/src/java/com/zimbra/cs/util/SpamExtract.java
Java
mit
21,891
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BookReviews.UI.Saga { public class OrderDetailsRequestSaga : SagaStateMachine<OrderDetailsRequestSaga>, ISaga { static OrderDetailsRequestSaga() { Define(Saga); } private static void Saga() { Correlate(RequestReceived) .By((saga, message) => saga.CustomerId == message.CustomerId && saga.OrderId == message.OrderId && saga.CurrentState == WaitingForResponse); Correlate(ResponseReceived) .By((saga, message) => saga.CustomerId == message.CustomerId && saga.OrderId == message.OrderId && saga.CurrentState == WaitingForResponse); public static State Initial { get; set; } public static State WaitingForResponse { get; set; } public static State Completed { get; set; } public static Event<RetrieveOrderDetails> RequestReceived { get; set; } public static Event<OrderDetailsResponse> ResponseReceived { get; set; } public static Event<OrderDetailsRequestFailed> RequestFailed { get; set; } Initially( When(RequestReceived) .Then((saga, request) => { saga.OrderId = request.OrderId; saga.CustomerId = request.CustomerId; }) .Publish((saga, request) => new SendOrderDetailsRequest { RequestId = saga.CorrelationId, CustomerId = saga.CustomerId, OrderId = saga.OrderId, }) .TransitionTo(WaitingForResponse)); During(WaitingForResponse, When(ResponseReceived) .Then((saga, response) => { saga.OrderCreated = response.Created; saga.OrderStatus = response.Status; }) .Publish((saga, request) => new OrderDetails { CustomerId = saga.CustomerId, OrderId = saga.OrderId, Created = saga.OrderCreated.Value, Status = saga.OrderStatus, }) .TransitionTo(Completed)); } public OrderDetailsRequestSaga(Guid correlationId) { CorrelationId = correlationId; } protected OrderDetailsRequestSaga() { } public virtual string CustomerId { get; set; } public virtual string OrderId { get; set; } public virtual OrderStatus OrderStatus { get; set; } public virtual DateTime? OrderCreated { get; set; } public virtual Guid CorrelationId { get; set; } public virtual IServiceBus Bus { get; set; } } //The rest of the saga class is shown above for completeness. //The properties are part of the saga and get saved when the saga is persisted //(using the NHibernate saga persister, or in the case of the sample the in-memory implementation). //The constructor with the Guid is used to initialize the saga when a new one is created, //the protected one is there for NHibernate to be able to persist the saga. } }
bob2000/BookReviews
BookReviews.UI/Saga/OrderDetailsRequestSaga.cs
C#
mit
3,007
ActiveRecord::Schema.define(:version => 1) do create_table :notes, :force => true do |t| t.string :title t.text :body end end
relax4u/jpvalidator
spec/schema.rb
Ruby
mit
139
var coords; var directionsDisplay; var map; var travelMode; var travelModeElement = $('#mode_travel'); // Order of operations for the trip planner (each function will have detailed notes): // 1) Calculate a user's route, with directions. // 2) Run a query using the route's max and min bounds to narrow potential results. // 3) Just because a marker is in the area of the route, it doesn't mean that it's on the route. // Use RouteBoxer to map sections of the route to markers, if applicable. Display only those markers on the map. // 4) The directions panel also isn't linked to a section of the route. // Use RouteBoxer to map a direction (turn left, right, etc) to part of the route. // 5) Build the custom directions panel by looping though each leg of the trip, finding the corresponding RouteBoxer // section, and use that to get markers for that section only. $(document).ready(function () { $('.active').toggleClass('active'); $('#trip-planner').toggleClass('active'); }); // Run these functions after setting geolocation. All except setFormDateTime() are dependent on geolocation to run. initGeolocation().then(function (coords) { map = mapGenerator(coords); setDirectionsDisplay(map); formListener(); }); // Instantiate directions methods on map. function setDirectionsDisplay(map) { directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); } // Listener for if the mode of travel is changed from an empty default to either bicycling or walking. function formListener() { travelModeElement.change(function(){ // Launch route calculation, markers, and directions panel. calcRoute(); }); } // Once the mode of travel is selected, start calculating routes and get marker data. function calcRoute() { var directionsService = new google.maps.DirectionsService(); var start = $('#start').val(); var end = $('#end').val(); travelMode = travelModeElement.val(); var request = { origin: start, destination: end, travelMode: google.maps.TravelMode[travelMode] }; directionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); // Remove existing markers from the map and map object. removeMarkers(true); queryResults = getMarkers(response); // Check if results are along the route. if (queryResults.objects.length > 0) { // Filter the query results further by comparing coords with each route section. narrowResults(queryResults.objects, response); // If no query results, set the marker count to 0 and generate the directions panel. } else { response.routes[0].legs[0]['marker_count'] = 0; generateDirectionsPanel(response); } } }); } // Get markers near a route. This is done by getting the boundaries for the route as a whole and using those // as query params. function getMarkers(response){ var userType; if (travelMode == "BICYCLING") { userType = 1; } else { userType = 2; } // Build the query string, limiting the results for cyclists and pedestrians. var queryString = '/api/v1/hazard/?format=json&?user_type=' + userType; // Get the maximum and minimum lat/lon bounds for the route. // This will narrow the query to a box around the route as a whole. var routeBounds = getBounds(response.routes[0].bounds); // TODO(zemadi): Look up alternatives for building the querystring. //Build the querystring. Negative numbers require different greater/less than logic, // so testing for that here. if (routeBounds.lat1 >= 0 && routeBounds.lat2 >= 0) { queryString += '&lat__gte=' + routeBounds.lat1 + '&lat__lte=' + routeBounds.lat2; } else { queryString += '&lat__gte=' + routeBounds.lat2 + '&lat__lte=' + routeBounds.lat1; } if (routeBounds.lon1 >= 0 && routeBounds.lon2 >= 0) { queryString += '&lon__gte=' + routeBounds.lon1 + '&lon__lte=' + routeBounds.lon2; } else { queryString += '&lon__gte=' + routeBounds.lon2 + '&lon__lte=' + routeBounds.lon1; } return httpGet(queryString); } // Function to get coordinate boundaries from the Directions route callback. function getBounds(data) { var coordinateBounds = {}; var keyByIndex = Object.keys(data); coordinateBounds['lat1'] = data[keyByIndex[0]]['k']; coordinateBounds['lat2'] = data[keyByIndex[0]]['j']; coordinateBounds['lon1'] = data[keyByIndex[1]]['k']; coordinateBounds['lon2'] = data[keyByIndex[1]]['j']; return coordinateBounds; } // Reduce the query results further by checking if they're actually along a route. // In order for a data point to be on the route, the coordinates need to be between the values of a box in routeBoxer. // RouteBoxer chops up a route into sections and returns the upper and lower boundaries for that section of the route. // Refer to: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/routeboxer/docs/examples.html function narrowResults(queryResults, directionsResponse) { // Variables needed for routeBoxer. var path = directionsResponse.routes[0].overview_path; var rboxer = new RouteBoxer(); var boxes = rboxer.box(path, .03); // Second param is a boundary in km from the route path. //Variables to hold mapData and match a marker to a specific section of the route. var mapData = {'objects': []}; // Object to hold routeBoxer index to markers map. var mapBoxesAndMarkers = {}; // For each section of the route, look through markers to see if any fit in the section's boundaries. // Using a for loop here because routeBoxer returns an array. for (var j = 0, b=boxes.length; j < b; j++) { // For each section of the route, record the index as a key and create an empty array to hold marker values. mapBoxesAndMarkers[j] = []; queryResults.forEach(function(result) { // If a marker is between the latitude and longitude bounds of the route, add it to the map and // the route-marker dict. var currentResult = new google.maps.LatLng(result.lat, result.lon); if (boxes[j].contains(currentResult)) { mapData.objects.push(result); mapBoxesAndMarkers[j].push(result); } }); } if (mapData.objects.length > 0) { // Add new markers to the map. markerGenerator(map, mapData); // Add the count of valid markers to the directionsResponse object, which is used to generate // the directions panel. If there are no markers, add 'None'. directionsResponse.routes[0].legs[0]['marker_count'] = mapData.objects.length; } else { directionsResponse.routes[0].legs[0]['marker_count'] = 'None'; } mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers); } // Directions information also needs to be mapped to a section of the route. function mapDirectionsToBoxes(boxes, directionsResponse, mapBoxesAndMarkers){ var directions = directionsResponse.routes[0].legs[0].steps; // go through each step and set of lat lngs per step. directions.forEach(function(direction) { var routeBoxesinDirection = []; for (var l = 0, b=boxes.length; l < b; l++) { direction.lat_lngs.forEach(function(lat_lng) { // If the index isn't already in the array and the box contains the current route's lat and long, add the // index. if (routeBoxesinDirection.indexOf(l) === -1 && boxes[l].contains(lat_lng)) { routeBoxesinDirection.push(l); } }); } // Once we're done looping over route boxes for the current direction, lookup markers that have the same bounds. // A direction can have multiple route boxes so a list is being used here. direction['markers'] = []; routeBoxesinDirection.forEach(function(box) { if (mapBoxesAndMarkers[box].length > 0) { // Use the route box to look up arrays of markers to add to the directions object. direction['markers'].push.apply(direction['markers'], mapBoxesAndMarkers[box]); } }); }); generateDirectionsPanel(directionsResponse); } function generateDirectionsPanel(directionsResponse) { var directionsPanel = $('#directions-panel'); var directionsPanelHtml = $('#directions-panel-template').html(); var newSearchTrigger = $('#new-search-trigger'); var template = Handlebars.compile(directionsPanelHtml); var compiledDirectionsPanel = template(directionsResponse.routes[0].legs[0]); if (directionsPanel[0].children.length > 0) { directionsPanel[0].innerHTML = compiledDirectionsPanel; } else { directionsPanel.append(compiledDirectionsPanel); } // Close the trip planner form and display the directions panel. $('#trip-planner-form').addClass('closed'); directionsPanel.removeClass('closed'); newSearchTrigger.removeClass('hidden'); // Listen for a new search event, which shows the form and closes the directions panel. newSearchTrigger.click(function(){ directionsPanel.addClass('closed'); newSearchTrigger.addClass('hidden'); $('#trip-planner-form').removeClass('closed'); }); }
codeforsanjose/CycleSafe
app/static/js/trip_planner.js
JavaScript
mit
9,596
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({ initialize: function(options) { if (!options.icon_name) { options.icon_name = 'bird'; } this.model = new Backbone.Model( options ); this.render(); }, template: function(serialized_model) { return Mustache.render(template, serialized_model); }, ui: { 'ok': '.btn-ok', 'cancel': '.btn-cancel', 'dialog': '.dialog', 'close': '.dialog-close' }, events: { 'tap @ui.ok': 'onOk', 'tap @ui.cancel': 'onCancel', 'tap @ui.close': 'onCancel' }, onOk: function(ev) { this.trigger('ok'); this.destroy(); }, onCancel: function(ev) { this.trigger('cancel'); this.destroy(); }, onRender: function() { $('body').append(this.$el); this.ui.dialog.css({ 'marginTop': 0 - this.ui.dialog.height()/2 }); this.ui.dialog.addClass('bounceInDown animated'); }, onDestory: function() { this.$el.remove(); this.model.destroy(); }, className: 'dialogContainer' }); });
yoniji/ApeRulerDemo
app/modules/ctrls/CtrlDialogView.js
JavaScript
mit
1,645
export * from './alert.service'; export * from './authentication.service'; export * from './user.service'; export * from './serviceRequest.service';
JacksonLee2019/CS341-VolunteerSchedule
app/_services/index.ts
TypeScript
mit
151
--- title: play on playa (part deux) date: 2007-01-14 00:00:00 Z permalink: "/2007/01/14/20070114play-on-playa-part-deux/" categories: - Baby E - Uncategorized author: Jennifer layout: post --- Yes, we had a fun filled [play date](http://www.flickr.com/photos/jenniferandJennifers_photos/?saved=1 "play date")! Oliver and Noah were reacquainted under the tantalizing play mat and enjoyed every minute of it! <img id="image115" alt="pod_011207.jpg" src="http://static.squarespace.com/static/50db6bb3e4b015296cd43789/50dfa5b1e4b0dc6320e0b5ea/50dfa5b1e4b0dc6320e0b652/1168806613000/?format=original" />
jaythanelam/teamelam
_posts/2007-01-14-20070114play-on-playa-part-deux.md
Markdown
mit
602
import { InvalidArgumentError } from '../errors/InvalidArgumentError'; import { NotImplementedError } from '../errors/NotImplementedError'; import mustache from 'mustache'; import '../utils/Function'; // The base class for a control export class Control { // The constructor of a control // id: The id of the control // template: The template used for rendering the control // localCSS: An object whose properties are CSS class names and whose values are the localized CSS class names // The control will change the matching CSS class names in the templates. constructor(id, template, localCSS) { if (typeof id !== 'string' || !isNaN(id)) { throw new InvalidArgumentError('Cannot create the control because the id is not a string'); } if (id.length < 1) { throw new InvalidArgumentError('Cannot create the control because the id is not a non-empty string'); } if (null === template || undefined === template) { throw new InvalidArgumentError('Cannot create the control because the template cannot be null or undefined'); } if (typeof template !== 'string') { throw new InvalidArgumentError('Cannot create the control because the template is not a string'); } this.id = id; this.template = template; if (template && localCSS) { // localize the CSS class names in the templates for (const oCN in localCSS) { const nCN = localCSS[oCN]; this.template = this.template .replace(new RegExp(`class="${oCN}"`, 'gi'), `class="${nCN}"`) .replace(new RegExp(`class='${oCN}'`, 'gi'), `class='${nCN}'`); } } this.controls = {}; } // Adds a child control to the control // control: The Control instance addControl(control) { if (!(control instanceof Control)) { throw new InvalidArgumentError('Cannot add sub-control because it is invalid'); } this.controls[control.id] = control; } // Removes a child control from the control // val: Either a controlId or a Control instance removeControl(val) { if (val instanceof Control) { delete this.controls[val.id]; } else { delete this.controls[val]; } } // Renders the control (and all its contained controls) // data: The object that contains the data to substitute into the template // eventObj: Event related data for the event that caused the control to render render(data, eventObj) { if (this.controls) { const controlData = {}; for (let controlId in this.controls) { const control = this.controls[controlId]; controlData[control.constructor.getConstructorName()] = {}; controlData[control.constructor.getConstructorName()][control.id] = control.render(data, eventObj); } for (let key in controlData) { data[key] = controlData[key]; } } return mustache.render(this.template, data); } // This method is invoked so the control can bind events after the DOM has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdated(domContainerElement, eventObj) { if (this.onDOMUpdatedNotification) { this.onDOMUpdatedNotification(domContainerElement, eventObj); } if (this.controls) { for (let controlId in this.controls) { const control = this.controls[controlId]; control.onDOMUpdated(domContainerElement, eventObj); } } } // The Control classes that extend this type can add custom logic here to be executed after the domContainerElement // has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdatedNotification(domContainerElement, eventObj) { } };
kmati/affront
lib/Control/index.js
JavaScript
mit
3,736
<html><img border=0 src=70786-65-1.txt alt=70786-65-1.txt></img><body> "x" "1" "KAZIUS, J, MCGUIRE, R AND BURSI, R. DERIVATION AND VALIDATION OF TOXICOPHORES FOR MUTAGENICITY PREDICTION. J. MED. CHEM. 48: 312-320, 2005" </body></html>
andrewdefries/Ames_ToxBenchmark
70786-65-1.txt.html
HTML
mit
235
// // MultibandBank.c // FxDSP // // Created by Hamilton Kibbe on 11/24/13. // Copyright (c) 2013 Hamilton Kibbe. All rights reserved. // #include "MultibandBank.h" #include "LinkwitzRileyFilter.h" #include "RBJFilter.h" #include "FilterTypes.h" #include <stdlib.h> // Sqrt(2)/2 #define FILT_Q (0.70710681186548) /******************************************************************************* MultibandFilter */ struct MultibandFilter { LRFilter* LPA; LRFilter* HPA; LRFilter* LPB; LRFilter* HPB; RBJFilter* APF; float lowCutoff; float highCutoff; float sampleRate; }; struct MultibandFilterD { LRFilterD* LPA; LRFilterD* HPA; LRFilterD* LPB; LRFilterD* HPB; RBJFilterD* APF; double lowCutoff; double highCutoff; double sampleRate; }; /******************************************************************************* MultibandFilterInit */ MultibandFilter* MultibandFilterInit(float lowCutoff, float highCutoff, float sampleRate) { MultibandFilter* filter = (MultibandFilter*) malloc(sizeof(MultibandFilter)); filter->lowCutoff = lowCutoff; filter->highCutoff = highCutoff; filter->sampleRate = sampleRate; filter->LPA = LRFilterInit(LOWPASS, filter->lowCutoff, FILT_Q, filter->sampleRate); filter->HPA = LRFilterInit(HIGHPASS, filter->lowCutoff, FILT_Q, filter->sampleRate); filter->LPB = LRFilterInit(LOWPASS, filter->highCutoff, FILT_Q, filter->sampleRate); filter->HPB = LRFilterInit(HIGHPASS, filter->highCutoff, FILT_Q, filter->sampleRate); filter->APF = RBJFilterInit(ALLPASS, filter->sampleRate/2.0, filter->sampleRate); RBJFilterSetQ(filter->APF, 0.5); return filter; } MultibandFilterD* MultibandFilterInitD(double lowCutoff, double highCutoff, double sampleRate) { MultibandFilterD* filter = (MultibandFilterD*) malloc(sizeof(MultibandFilterD)); filter->lowCutoff = lowCutoff; filter->highCutoff = highCutoff; filter->sampleRate = sampleRate; filter->LPA = LRFilterInitD(LOWPASS, filter->lowCutoff, FILT_Q, filter->sampleRate); filter->HPA = LRFilterInitD(HIGHPASS, filter->lowCutoff, FILT_Q, filter->sampleRate); filter->LPB = LRFilterInitD(LOWPASS, filter->highCutoff, FILT_Q, filter->sampleRate); filter->HPB = LRFilterInitD(HIGHPASS, filter->highCutoff, FILT_Q, filter->sampleRate); filter->APF = RBJFilterInitD(ALLPASS, filter->sampleRate/2.0, filter->sampleRate); RBJFilterSetQD(filter->APF, 0.5); return filter; } /******************************************************************************* MultibandFilterFree */ Error_t MultibandFilterFree(MultibandFilter* filter) { LRFilterFree(filter->LPA); LRFilterFree(filter->LPB); LRFilterFree(filter->HPA); LRFilterFree(filter->HPB); RBJFilterFree(filter->APF); if (filter) { free(filter); filter = NULL; } return NOERR; } Error_t MultibandFilterFreeD(MultibandFilterD* filter) { LRFilterFreeD(filter->LPA); LRFilterFreeD(filter->LPB); LRFilterFreeD(filter->HPA); LRFilterFreeD(filter->HPB); RBJFilterFreeD(filter->APF); if (filter) { free(filter); filter = NULL; } return NOERR; } /******************************************************************************* MultibandFilterFlush */ Error_t MultibandFilterFlush(MultibandFilter* filter) { LRFilterFlush(filter->LPA); LRFilterFlush(filter->LPB); LRFilterFlush(filter->HPA); LRFilterFlush(filter->HPB); RBJFilterFlush(filter->APF); return NOERR; } Error_t MultibandFilterFlushD(MultibandFilterD* filter) { LRFilterFlushD(filter->LPA); LRFilterFlushD(filter->LPB); LRFilterFlushD(filter->HPA); LRFilterFlushD(filter->HPB); RBJFilterFlushD(filter->APF); return NOERR; } /******************************************************************************* MultibandFilterSetLowCutoff */ Error_t MultibandFilterSetLowCutoff(MultibandFilter* filter, float lowCutoff) { filter->lowCutoff = lowCutoff; LRFilterSetParams(filter->LPA, LOWPASS, lowCutoff, FILT_Q); LRFilterSetParams(filter->HPA, HIGHPASS, lowCutoff, FILT_Q); return NOERR; } Error_t MultibandFilterSetLowCutoffD(MultibandFilterD* filter, double lowCutoff) { filter->lowCutoff = lowCutoff; LRFilterSetParamsD(filter->LPA, LOWPASS, lowCutoff, FILT_Q); LRFilterSetParamsD(filter->HPA, HIGHPASS, lowCutoff, FILT_Q); return NOERR; } /******************************************************************************* MultibandFilterSetHighCutoff */ Error_t MultibandFilterSetHighCutoff(MultibandFilter* filter, float highCutoff) { filter->highCutoff = highCutoff; LRFilterSetParams(filter->LPB, LOWPASS, highCutoff, FILT_Q); LRFilterSetParams(filter->HPB, HIGHPASS, highCutoff, FILT_Q); return NOERR; } Error_t MultibandFilterSetHighCutoffD(MultibandFilterD* filter, double highCutoff) { filter->highCutoff = highCutoff; LRFilterSetParamsD(filter->LPB, LOWPASS, highCutoff, FILT_Q); LRFilterSetParamsD(filter->HPB, HIGHPASS, highCutoff, FILT_Q); return NOERR; } /******************************************************************************* MultibandFilterUpdate */ Error_t MultibandFilterUpdate(MultibandFilter* filter, float lowCutoff, float highCutoff) { filter->lowCutoff = lowCutoff; filter->highCutoff = highCutoff; LRFilterSetParams(filter->LPA, LOWPASS, lowCutoff, FILT_Q); LRFilterSetParams(filter->HPA, HIGHPASS, lowCutoff, FILT_Q); LRFilterSetParams(filter->LPB, LOWPASS, highCutoff, FILT_Q); LRFilterSetParams(filter->HPB, HIGHPASS, highCutoff, FILT_Q); return NOERR; } Error_t MultibandFilterUpdateD(MultibandFilterD* filter, double lowCutoff, double highCutoff) { filter->lowCutoff = lowCutoff; filter->highCutoff = highCutoff; LRFilterSetParamsD(filter->LPA, LOWPASS, lowCutoff, FILT_Q); LRFilterSetParamsD(filter->HPA, HIGHPASS, lowCutoff, FILT_Q); LRFilterSetParamsD(filter->LPB, LOWPASS, highCutoff, FILT_Q); LRFilterSetParamsD(filter->HPB, HIGHPASS, highCutoff, FILT_Q); return NOERR; } /******************************************************************************* MultibandFilterProcess */ Error_t MultibandFilterProcess(MultibandFilter* filter, float* lowOut, float* midOut, float* highOut, const float* inBuffer, unsigned n_samples) { float tempLow[n_samples]; float tempHi[n_samples]; LRFilterProcess(filter->LPA, tempLow, inBuffer, n_samples); LRFilterProcess(filter->HPA, tempHi, inBuffer, n_samples); RBJFilterProcess(filter->APF, lowOut, tempLow, n_samples); LRFilterProcess(filter->LPB, midOut, tempHi, n_samples); LRFilterProcess(filter->HPB, highOut, tempHi, n_samples); return NOERR; } Error_t MultibandFilterProcessD(MultibandFilterD* filter, double* lowOut, double* midOut, double* highOut, const double* inBuffer, unsigned n_samples) { double tempLow[n_samples]; double tempHi[n_samples]; LRFilterProcessD(filter->LPA, tempLow, inBuffer, n_samples); LRFilterProcessD(filter->HPA, tempHi, inBuffer, n_samples); RBJFilterProcessD(filter->APF, lowOut, tempLow, n_samples); LRFilterProcessD(filter->LPB, midOut, tempHi, n_samples); LRFilterProcessD(filter->HPB, highOut, tempHi, n_samples); return NOERR; }
hamiltonkibbe/FxDSP
FxDSP/src/MultibandBank.c
C
mit
8,273
using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; namespace AutoHelp.domain.Models { [DebuggerDisplay("{Fullname}")] [DataContract] public class Method : CodeCommentBase { [DataMember] public string ReturnType { get; set; } [DataMember] public string ReturnTypeFullName { get; set; } public Method() { Parameters = new List<Parameter>(); } } }
RaynaldM/autohelp
AutoHelp.domain/Models/Method.cs
C#
mit
482
'use strict'; /* jasmine specs for filters go here */ describe('filter', function() { });
LeoAref/angular-seed
test/unit/filtersSpec.js
JavaScript
mit
93
<div id="contenido"> <div class="bloque"> <h2 class="titulo"><strong>Contacto</strong></h2> <p>Rellene el siguiente formulario si desea ponerse en contacto.</p> <?php if(!empty($estado)){ echo $estado; } ?> <form action="contacto/" method="post"> <fieldset> <legend>Datos</legend> <p> <label for="nombre" title="Nombre"><strong>Nombre </strong></label> <input id="nombre" name="nombre" type="text" value="<?php echo $nombre; ?>" size="50" maxlength="40" /> <em>Ejemplo: Pepe</em> </p> <p> <label for="email" title="Email"><strong>Email </strong></label> <input id="email" name="email" type="text" value="<?php echo $email; ?>" size="50" maxlength="320" /> <em>Ejemplo: [email protected]</em> </p> <p> <label for="asunto" title="Asunto"><strong>Asunto </strong></label> <input id="asunto" name="asunto" type="text" value="<?php echo $asunto; ?>" size="50" maxlength="50" /> </p> <p> <label for="mensaje" title="Mensaje"><strong>Mensaje </strong></label> <textarea id="mensaje" name="mensaje" rows="7" cols="40"><?php echo $mensaje; ?></textarea> </p> <p> <label for="humano" title="Humano ó Maquina"><strong>¿Eres humano? </strong></label> <input id="humano" name="humano" type="text" value="0" size="5" maxlength="5" /> <?php echo $captcha["pregunta"]; ?> </p> <p><input id="enviar" name="enviar" type="submit" value="Enviar" /></p> </fieldset> </form> </div> </div>
jh2odo/mfp5-mvc
demo/app/vistas/inicio/contacto.php
PHP
mit
1,496
!function(n){}(jQuery); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5iYWRyYWZ0LnNjcmlwdC5qcyJdLCJuYW1lcyI6WyIkIiwialF1ZXJ5Il0sIm1hcHBpbmdzIjoiQ0FJQSxTQUFBQSxLQUVBQyIsImZpbGUiOiJuYmFkcmFmdC5zY3JpcHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBmaWxlXG4gKiBDdXN0b20gc2NyaXB0cyBmb3IgdGhlbWUuXG4gKi9cbihmdW5jdGlvbiAoJCkge1xuICBcbn0pKGpRdWVyeSk7XG4iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
eganr/nba-draft-lookup
themes/nbadraft/assets/js/nbadraft.script.js
JavaScript
mit
419
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/chain/account_object.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/market_object.hpp> #include <graphene/chain/market_evaluator.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/is_authorized_asset.hpp> #include <graphene/chain/protocol/market.hpp> #include <fc/uint128.hpp> namespace graphene { namespace chain { void_result limit_order_create_evaluator::do_evaluate(const limit_order_create_operation& op) { try { // Disable Operation Temporary FC_ASSERT( false, "Limit order create operation is not supported for now."); const database& d = db(); FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME ); FC_ASSERT( op.expiration >= d.head_block_time() ); _seller = this->fee_paying_account; _sell_asset = &op.amount_to_sell.asset_id(d); _receive_asset = &op.min_to_receive.asset_id(d); if( _sell_asset->options.whitelist_markets.size() ) FC_ASSERT( _sell_asset->options.whitelist_markets.find(_receive_asset->id) != _sell_asset->options.whitelist_markets.end() ); if( _sell_asset->options.blacklist_markets.size() ) FC_ASSERT( _sell_asset->options.blacklist_markets.find(_receive_asset->id) == _sell_asset->options.blacklist_markets.end() ); FC_ASSERT( is_authorized_asset( d, *_seller, *_sell_asset ) ); FC_ASSERT( is_authorized_asset( d, *_seller, *_receive_asset ) ); FC_ASSERT( d.get_balance( *_seller, *_sell_asset ) >= op.amount_to_sell, "insufficient balance", ("balance",d.get_balance(*_seller,*_sell_asset))("amount_to_sell",op.amount_to_sell) ); return void_result(); } FC_CAPTURE_AND_RETHROW( (op) ) } void limit_order_create_evaluator::pay_fee() { _deferred_fee = core_fee_paid; } object_id_type limit_order_create_evaluator::do_apply(const limit_order_create_operation& op) { try { const auto& seller_stats = _seller->statistics(db()); db().modify(seller_stats, [&](account_statistics_object& bal) { if( op.amount_to_sell.asset_id == asset_id_type() ) { bal.total_core_in_orders += op.amount_to_sell.amount; } }); db().adjust_balance(op.seller, -op.amount_to_sell); const auto& new_order_object = db().create<limit_order_object>([&](limit_order_object& obj){ obj.seller = _seller->id; obj.for_sale = op.amount_to_sell.amount; obj.sell_price = op.get_price(); obj.expiration = op.expiration; obj.deferred_fee = _deferred_fee; }); limit_order_id_type order_id = new_order_object.id; // save this because we may remove the object by filling it bool filled = db().apply_order(new_order_object); FC_ASSERT( !op.fill_or_kill || filled ); return order_id; } FC_CAPTURE_AND_RETHROW( (op) ) } void_result limit_order_cancel_evaluator::do_evaluate(const limit_order_cancel_operation& o) { try { database& d = db(); FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME ); _order = &o.order(d); FC_ASSERT( _order->seller == o.fee_paying_account ); return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } asset limit_order_cancel_evaluator::do_apply(const limit_order_cancel_operation& o) { try { database& d = db(); auto base_asset = _order->sell_price.base.asset_id; auto quote_asset = _order->sell_price.quote.asset_id; auto refunded = _order->amount_for_sale(); d.cancel_order(*_order, false /* don't create a virtual op*/); // Possible optimization: order can be called by canceling a limit order iff the canceled order was at the top of the book. // Do I need to check calls in both assets? d.check_call_orders(base_asset(d)); d.check_call_orders(quote_asset(d)); return refunded; } FC_CAPTURE_AND_RETHROW( (o) ) } void_result call_order_update_evaluator::do_evaluate(const call_order_update_operation& o) { try { database& d = db(); FC_ASSERT( d.head_block_time() < HARDFORK_1_TIME ); _paying_account = &o.funding_account(d); _debt_asset = &o.delta_debt.asset_id(d); FC_ASSERT( _debt_asset->is_market_issued(), "Unable to cover ${sym} as it is not a collateralized asset.", ("sym", _debt_asset->symbol) ); _bitasset_data = &_debt_asset->bitasset_data(d); /// if there is a settlement for this asset, then no further margin positions may be taken and /// all existing margin positions should have been closed va database::globally_settle_asset FC_ASSERT( !_bitasset_data->has_settlement() ); FC_ASSERT( o.delta_collateral.asset_id == _bitasset_data->options.short_backing_asset ); if( _bitasset_data->is_prediction_market ) FC_ASSERT( o.delta_collateral.amount == o.delta_debt.amount ); else if( _bitasset_data->current_feed.settlement_price.is_null() ) FC_THROW_EXCEPTION(insufficient_feeds, "Cannot borrow asset with no price feed."); if( o.delta_debt.amount < 0 ) { FC_ASSERT( d.get_balance(*_paying_account, *_debt_asset) >= o.delta_debt, "Cannot cover by ${c} when payer only has ${b}", ("c", o.delta_debt.amount)("b", d.get_balance(*_paying_account, *_debt_asset).amount) ); } if( o.delta_collateral.amount > 0 ) { FC_ASSERT( d.get_balance(*_paying_account, _bitasset_data->options.short_backing_asset(d)) >= o.delta_collateral, "Cannot increase collateral by ${c} when payer only has ${b}", ("c", o.delta_collateral.amount) ("b", d.get_balance(*_paying_account, o.delta_collateral.asset_id(d)).amount) ); } return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } void_result call_order_update_evaluator::do_apply(const call_order_update_operation& o) { try { FC_ASSERT( false, "Call order update operation is not supported for now."); database& d = db(); if( o.delta_debt.amount != 0 ) { d.adjust_balance( o.funding_account, o.delta_debt ); // Deduct the debt paid from the total supply of the debt asset. d.modify(_debt_asset->dynamic_asset_data_id(d), [&](asset_dynamic_data_object& dynamic_asset) { dynamic_asset.current_supply += o.delta_debt.amount; assert(dynamic_asset.current_supply >= 0); }); } if( o.delta_collateral.amount != 0 ) { d.adjust_balance( o.funding_account, -o.delta_collateral ); // Adjust the total core in orders accodingly if( o.delta_collateral.asset_id == asset_id_type() ) { d.modify(_paying_account->statistics(d), [&](account_statistics_object& stats) { stats.total_core_in_orders += o.delta_collateral.amount; }); } } auto& call_idx = d.get_index_type<call_order_index>().indices().get<by_account>(); auto itr = call_idx.find( boost::make_tuple(o.funding_account, o.delta_debt.asset_id) ); const call_order_object* call_obj = nullptr; if( itr == call_idx.end() ) { FC_ASSERT( o.delta_collateral.amount > 0 ); FC_ASSERT( o.delta_debt.amount > 0 ); call_obj = &d.create<call_order_object>( [&](call_order_object& call ){ call.borrower = o.funding_account; call.collateral = o.delta_collateral.amount; call.debt = o.delta_debt.amount; call.call_price = price::call_price(o.delta_debt, o.delta_collateral, _bitasset_data->current_feed.maintenance_collateral_ratio); }); } else { call_obj = &*itr; d.modify( *call_obj, [&]( call_order_object& call ){ call.collateral += o.delta_collateral.amount; call.debt += o.delta_debt.amount; if( call.debt > 0 ) { call.call_price = price::call_price(call.get_debt(), call.get_collateral(), _bitasset_data->current_feed.maintenance_collateral_ratio); } }); } auto debt = call_obj->get_debt(); if( debt.amount == 0 ) { FC_ASSERT( call_obj->collateral == 0 ); d.remove( *call_obj ); return void_result(); } FC_ASSERT(call_obj->collateral > 0 && call_obj->debt > 0); // then we must check for margin calls and other issues if( !_bitasset_data->is_prediction_market ) { call_order_id_type call_order_id = call_obj->id; // check to see if the order needs to be margin called now, but don't allow black swans and require there to be // limit orders available that could be used to fill the order. if( d.check_call_orders( *_debt_asset, false ) ) { const auto call_obj = d.find(call_order_id); // if we filled at least one call order, we are OK if we totally filled. GRAPHENE_ASSERT( !call_obj, call_order_update_unfilled_margin_call, "Updating call order would trigger a margin call that cannot be fully filled", ("a", ~call_obj->call_price )("b", _bitasset_data->current_feed.settlement_price) ); } else { const auto call_obj = d.find(call_order_id); FC_ASSERT( call_obj, "no margin call was executed and yet the call object was deleted" ); //edump( (~call_obj->call_price) ("<")( _bitasset_data->current_feed.settlement_price) ); // We didn't fill any call orders. This may be because we // aren't in margin call territory, or it may be because there // were no matching orders. In the latter case, we throw. GRAPHENE_ASSERT( ~call_obj->call_price < _bitasset_data->current_feed.settlement_price, call_order_update_unfilled_margin_call, "Updating call order would trigger a margin call that cannot be fully filled", ("a", ~call_obj->call_price )("b", _bitasset_data->current_feed.settlement_price) ); } } return void_result(); } FC_CAPTURE_AND_RETHROW( (o) ) } } } // graphene::chain
bitsuperlab/cpp-play2
libraries/chain/market_evaluator.cpp
C++
mit
11,139
require "fog" module RedmineObjectStorage module AttachmentPatch def self.included(base) # :nodoc: base.extend(ClassMethods) base.send(:include, InstanceMethods) base.class_eval do unloadable cattr_accessor :context_obj, :objectstorage_bucket_instance, :__objectstorage_config after_validation :save_to_objectstorage before_destroy :delete_from_objectstorage def readable? !!Attachment.objectstorage_bucket.get(self.objectstorage_path) rescue false end end end module ClassMethods def set_context(context) @@context_obj = context end def get_context @@context_obj end def objectstorage_config unless Attachment.__objectstorage_config yaml = ERB.new(File.read(Rails.root.join("config", "objectstorage.yml"))).result @@__objectstorage_config = YAML.load(yaml).fetch(Rails.env) end return @@__objectstorage_config end def objectstorage_bucket unless Attachment.objectstorage_bucket_instance config = Attachment.objectstorage_config @@objectstorage_bucket_instance = Fog::Storage.new( provider: :aws, aws_access_key_id: config["access_key_id"], aws_secret_access_key: config["secret_access_key"], host: config["endpoint"], aws_signature_version: config["signature_version"] ).directories.get(config["bucket"]) end @@objectstorage_bucket_instance end def objectstorage_absolute_path(filename, project_id) ts = DateTime.now.strftime("%y%m%d%H%M%S") [project_id, ts, filename].compact.join("/") end end module InstanceMethods def objectstorage_filename if self.new_record? timestamp = DateTime.now.strftime("%y%m%d%H%M%S") self.disk_filename = [timestamp, filename].join("/") end self.disk_filename.blank? ? filename : self.disk_filename end # path on objectstorage to the file, defaulting the instance's disk_filename def objectstorage_path(fn = objectstorage_filename)#, ctx = nil, pid = nil) context = self.container || self.class.get_context project = context.is_a?(Hash) ? Project.find(context[:project]) : context.project ctx = context.is_a?(Hash) ? context[:class] : context.class.name # XXX s/WikiPage/Wiki ctx = "Wiki" if ctx == "WikiPage" pid = project.identifier [pid, fn].compact.join("/") end def save_to_objectstorage if @temp_file && !@temp_file.empty? logger.debug "[redmine_objectstorage_attachments] Uploading #{objectstorage_filename}" file = Attachment.objectstorage_bucket.files.create( key: objectstorage_path, body: @temp_file.is_a?(String) ? @temp_file : @temp_file.read ) self.digest = file.etag end # set the temp file to nil so the model's original after_save block # skips writing to the filesystem @temp_file = nil end def delete_from_objectstorage logger.debug "[redmine_objectstorage_attachments] Deleting #{objectstorage_filename}" Attachment.objectstorage_bucket.files.get(objectstorage_path(objectstorage_filename)).destroy end end end end
nttcom/redmine_objectstorage
lib/redmine_objectstorage/attachment_patch.rb
Ruby
mit
3,467
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; using Chromamboo.Contracts; using Newtonsoft.Json.Linq; namespace Chromamboo.Providers.Notification { public class AtlassianCiSuiteBuildStatusNotificationProvider : INotificationProvider<string> { private readonly IBitbucketApi bitbucketApi; private readonly IBambooApi bambooApi; private readonly IPresentationService presentationService; public AtlassianCiSuiteBuildStatusNotificationProvider(IBitbucketApi bitbucketApi, IBambooApi bambooApi, IPresentationService presentationService) { this.bitbucketApi = bitbucketApi; this.bambooApi = bambooApi; this.presentationService = presentationService; } public enum NotificationType { Build, PullRequest } public void Register(string planKey) { Observable .Timer(DateTimeOffset.MinValue, TimeSpan.FromSeconds(5)) .Subscribe(async l => { await this.PerformPollingAction(planKey); }); } private async Task PerformPollingAction(string planKey) { List<BuildDetail> buildsDetails; try { var latestHistoryBuild = this.bambooApi.GetLatestBuildResultsInHistoryAsync(planKey); var branchesListing = this.bambooApi.GetLastBuildResultsWithBranchesAsync(planKey); var isDevelopSuccessful = JObject.Parse(latestHistoryBuild.Result)["results"]["result"].First()["state"].Value<string>() == "Successful"; var lastBuiltBranches = JObject.Parse(branchesListing.Result); buildsDetails = lastBuiltBranches["branches"]["branch"].Where(b => b["enabled"].Value<bool>()).Select(this.GetBuildDetails).ToList(); if (!isDevelopSuccessful) { var developDetails = this.bambooApi.GetBuildResultsAsync(JObject.Parse(latestHistoryBuild.Result)["results"]["result"].First()["planResultKey"]["key"].Value<string>()); var developBuildDetails = this.ConstructBuildDetails(developDetails.Result); buildsDetails.Add(developBuildDetails); } } catch (Exception e) { this.presentationService.MarkAsInconclusive(NotificationType.Build); Console.WriteLine(e.GetType() + ": " + e.Message); return; } this.presentationService.Update(buildsDetails); } private BuildDetail GetBuildDetails(JToken jsonToken) { var key = jsonToken["key"].Value<string>(); var latestBuildKeyInPlan = JObject.Parse(this.bambooApi.GetLastBuildFromBranchPlan(key).Result)["results"]["result"].First()["buildResultKey"].Value<string>(); var buildDetailsString = this.bambooApi.GetBuildDetailsAsync(latestBuildKeyInPlan).Result; var buildDetails = this.ConstructBuildDetails(buildDetailsString); buildDetails.BranchName = jsonToken["shortName"].Value<string>(); return buildDetails; } private BuildDetail ConstructBuildDetails(string buildDetailsString) { var details = JObject.Parse(buildDetailsString); var buildDetails = new BuildDetail(); buildDetails.CommitHash = details["vcsRevisionKey"].Value<string>(); buildDetails.Successful = details["successful"].Value<bool>(); buildDetails.BuildResultKey = details["buildResultKey"].Value<string>(); buildDetails.PlanResultKey = details["planResultKey"]["key"].Value<string>(); var commitDetails = JObject.Parse(this.bitbucketApi.GetCommitDetails(buildDetails.CommitHash).Result); buildDetails.JiraIssue = commitDetails["properties"]?["jira-key"].Values<string>().Aggregate((s1, s2) => s1 + ", " + s2); buildDetails.AuthorEmailAddress = commitDetails["author"]["emailAddress"].Value<string>(); buildDetails.AuthorName = commitDetails["author"]["name"].Value<string>(); buildDetails.AuthorDisplayName = commitDetails["author"]["displayName"]?.Value<string>() ?? buildDetails.AuthorName; return buildDetails; } } }
duvaneljulien/chromamboo
src/Chromamboo/Providers/Notification/AtlassianCiSuiteBuildStatusNotificationProvider.cs
C#
mit
4,569
namespace SupermarketsChainDB.Data.Migrations { using System; using System.Collections.Generic; using System.Linq; using Oracle.DataAccess.Client; using SupermarketsChainDB.Data; using SupermarketsChainDB.Models; public static class OracleToSqlDb { private static string ConnectionString = Connection.GetOracleConnectionString(); private static OracleConnection con; public static void MigrateToSql() { MigrateMeasures(); MigrateVendors(); MigrateProducts(); } private static void Connect() { var con = new OracleConnection(); if (OracleConnection.IsAvailable) { con.ConnectionString = "context connection=true"; } else { con = new OracleConnection { ConnectionString = ConnectionString }; con.Open(); Console.WriteLine("Connected to Oracle" + con.ServerVersion); } } private static void MigrateMeasures() { SupermarketSystemData data = new SupermarketSystemData(); con = new OracleConnection { ConnectionString = ConnectionString }; con.Open(); OracleCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT M_ID, MEASURE_NAME FROM MEASURE_UNITS"; using (OracleDataReader reader = cmd.ExecuteReader()) { var lastMeasure = data.Measures.All().OrderByDescending(v => v.Id).FirstOrDefault(); int dataId = 0; if (lastMeasure != null) { dataId = lastMeasure.Id; } while (reader.Read()) { int measureId = int.Parse(reader["M_ID"].ToString()); if (dataId < measureId) { Measure measure = new Measure(); measure.Id = measureId; measure.MeasureName = (string)reader["MEASURE_NAME"]; data.Measures.Add(measure); } } data.SaveChanges(); } Close(); } private static void MigrateVendors() { SupermarketSystemData data = new SupermarketSystemData(); con = new OracleConnection { ConnectionString = ConnectionString }; con.Open(); OracleCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT V_ID,VENDOR_NAME FROM VENDORS"; using (OracleDataReader reader = cmd.ExecuteReader()) { var lastVendor = data.Vendors.All().OrderByDescending(v => v.Id).FirstOrDefault(); int dataId = 0; if (lastVendor != null) { dataId = lastVendor.Id; } while (reader.Read()) { int vendorId = int.Parse(reader["V_ID"].ToString()); if (dataId < vendorId) { Vendor vendor = new Vendor(); vendor.Id = vendorId; vendor.VendorName = (string)reader["VENDOR_NAME"]; data.Vendors.Add(vendor); } } data.SaveChanges(); } Close(); } private static void MigrateProducts() { SupermarketSystemData data = new SupermarketSystemData(); con = new OracleConnection { ConnectionString = ConnectionString }; con.Open(); OracleCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT P_ID, " + "VENDOR_ID," + "PRODUCT_NAME, " + "MEASURE_ID, " + "PRICE, " + "PRODUCT_TYPE " + "FROM PRODUCTS"; using (OracleDataReader reader = cmd.ExecuteReader()) { var lastProduct = data.Products.All().OrderByDescending(p => p.Id).FirstOrDefault(); int dataId = 0; if (lastProduct != null) { dataId = lastProduct.Id; } while (reader.Read()) { int productId = int.Parse(reader["P_ID"].ToString()); if (dataId < productId) { Product product = new Product(); // for debugging product.Id = productId; product.VendorId = int.Parse(reader["VENDOR_ID"].ToString()); product.ProductName = reader["PRODUCT_NAME"].ToString(); product.MeasureId = int.Parse(reader["MEASURE_ID"].ToString()); product.Price = decimal.Parse(reader["PRICE"].ToString()); product.ProductType = (ProductType)Enum.Parse(typeof(ProductType), reader["PRODUCT_TYPE"].ToString()); data.Products.Add(product); } } data.SaveChanges(); } Close(); } private static void Close() { con.Close(); con.Dispose(); } } }
ttittoOrg/SupermarketsChainDB
SupermarketsChainDB/SupermarketsChainDB.Data/Migrations/OracleToSqlDb.cs
C#
mit
5,619
# ts3 TeamSpeak 3 ServerQuery API implementation for Node.js
VeltroGaming/ts3
README.md
Markdown
mit
61
^^^^^^^^^^^^^CS171 2015 Homework Assignments === Homework assignments for Harvard's [CS171](http://www.cs171.org/2015/index.html) 2015. To receive homework updates on your local machine run: ``` git pull homework master ``` For details on how to submit your work, take a look at [Section 1](https://github.com/CS171/2015-cs171-homework/tree/master/section1). --- **Name**:Yi Mao **Email**:[email protected]
yim833/cs171-hw-mao-yi
README.md
Markdown
mit
421
class ApplicationController < ActionController::Base protect_from_forgery with: :exception helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def require_login render_404 unless current_user end private def render_404 raise ActionController::RoutingError.new('Not Found') end end
mk12/great-reads
app/controllers/application_controller.rb
Ruby
mit
380
import { Injectable } from '@angular/core'; import { SyncResult } from 'app/model/syncResult' import { Log } from 'app/model/log' import { LogItem } from 'app/model/logItem' @Injectable() export class SyncResultService { syncResultService : any; constructor() { this.syncResultService = (window as any).syncResultService; } // TODO cache // TODO should be ab // TODO shouldnt be needed, drop isSuccess() : boolean { var success; var syncResults = this.syncResultService.getResults(); if (syncResults.length > 0) { success = true; for (var i = 0; i < syncResults.length; i++) { var syncResult = syncResults[i]; success &= syncResult.success; } } else { success = false; } return success; } // TODO cache // TODO move translation into shared service getResults() : SyncResult[] { var results = []; var syncResults = this.syncResultService.getResults(); // Translate each result for (var i = 0; i < syncResults.length; i++) { var syncResult = syncResults[i]; var result = new SyncResult(); result.profileId = syncResult.getProfileId(); result.hostName = syncResult.getHostName(); // Translate merge log var log = syncResult.getLog(); if (log != null) { var logItems = log.getLogItems(); // Translate log items of each result var jsonLog = new Log(); var items = []; for (var j = 0; j < logItems.length; j++) { var logItem = logItems[j]; var item = new LogItem(); item.level = logItem.getLevel().toString(); item.local = logItem.isLocal(); item.text = logItem.getText(); items.push(item); } jsonLog.items = items; result.log = jsonLog; } results.push(result); } return results; } clear() { this.syncResultService.clear(); } getResultsAsText() { return this.syncResultService.getResultsAsText(); } }
limpygnome/parrot-manager
parrot-manager-frontend/src/app/service/syncResult.service.ts
TypeScript
mit
2,422
import * as React from 'react'; import { StandardProps } from '..'; export interface TableProps extends StandardProps<TableBaseProps, TableClassKey> { component?: React.ReactType<TableBaseProps>; } export type TableBaseProps = React.TableHTMLAttributes<HTMLTableElement>; export type TableClassKey = 'root'; declare const Table: React.ComponentType<TableProps>; export default Table;
cherniavskii/material-ui
packages/material-ui/src/Table/Table.d.ts
TypeScript
mit
391
hmm = [ "https://media3.giphy.com/media/TPl5N4Ci49ZQY/giphy.gif", "https://media0.giphy.com/media/l14qxlCgJ0zUk/giphy.gif", "https://media4.giphy.com/media/MsWnkCVSXz73i/giphy.gif", "https://media1.giphy.com/media/l2JJEIMLgrXPEbDGM/giphy.gif", "https://media0.giphy.com/media/dgK22exekwOLm/giphy.gif" ]
garr741/mr_meeseeks
rtmbot/plugins/hmm.py
Python
mit
322
/** * Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog */ import React from 'react'; import ReactDOM from 'react-dom'; import EventStack from './EventStack'; import PropTypes from 'prop-types'; const ESCAPE = 27; /** * Get the keycode from an event * @param {Event} event The browser event from which we want the keycode from * @returns {Number} The number of the keycode */ const getKeyCodeFromEvent = event => event.which || event.keyCode || event.charCode; // Render into subtree is necessary for parent contexts to transfer over // For example, for react-router const renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer; export class ModalContent extends React.Component { constructor(props) { super(props); this.handleGlobalClick = this.handleGlobalClick.bind(this); this.handleGlobalKeydown = this.handleGlobalKeydown.bind(this); } componentWillMount() { /** * This is done in the componentWillMount instead of the componentDidMount * because this way, a modal that is a child of another will have register * for events after its parent */ this.eventToken = EventStack.addListenable([ ['click', this.handleGlobalClick], ['keydown', this.handleGlobalKeydown] ]); } componentWillUnmount() { EventStack.removeListenable(this.eventToken); } shouldClickDismiss(event) { const { target } = event; // This piece of code isolates targets which are fake clicked by things // like file-drop handlers if (target.tagName === 'INPUT' && target.type === 'file') { return false; } if (!this.props.dismissOnBackgroundClick) { if (target !== this.refs.self || this.refs.self.contains(target)) { return false; } } else { if (target === this.refs.self || this.refs.self.contains(target)) { return false; } } return true; } handleGlobalClick(event) { if (this.shouldClickDismiss(event)) { if (typeof this.props.onClose === 'function') { this.props.onClose(event); } } } handleGlobalKeydown(event) { if (getKeyCodeFromEvent(event) === ESCAPE) { if (typeof this.props.onClose === 'function') { this.props.onClose(event); } } } render() { return ( <div ref="self" className={'liq_modal-content'}> {this.props.showButton && this.props.onClose ? ( <button onClick={this.props.onClose} className={'liq_modal-close'} data-test="close_modal_button"> <span aria-hidden="true">{'×'}</span> </button> ) : null} {this.props.children} </div> ); } } ModalContent.propTypes = { showButton: PropTypes.bool, onClose: PropTypes.func, // required for the close button className: PropTypes.string, children: PropTypes.node, dismissOnBackgroundClick: PropTypes.bool }; ModalContent.defaultProps = { dismissOnBackgroundClick: true, showButton: true }; export class ModalPortal extends React.Component { componentDidMount() { // disable scrolling on body document.body.classList.add('liq_modal-open'); // Create a div and append it to the body this._target = document.body.appendChild(document.createElement('div')); // Mount a component on that div this._component = renderSubtreeIntoContainer( this, this.props.children, this._target ); // A handler call in case you want to do something when a modal opens, like add a class to the body or something if (typeof this.props.onModalDidMount === 'function') { this.props.onModalDidMount(); } } componentDidUpdate() { // When the child component updates, we have to make sure the content rendered to the DOM is updated to this._component = renderSubtreeIntoContainer( this, this.props.children, this._target ); } componentWillUnmount() { /** * Let this be some discussion about fading out the components on unmount. * Right now, there is the issue that if a stack of components are layered * on top of each other, and you programmatically dismiss the bottom one, * it actually takes some time for the animation to catch up to the top one, * because each modal doesn't send a dismiss signal to its children until * it itself is totally gone... */ // TODO: REMOVE THIS - THINK OUT OF THE BOX const done = () => { // Modal will unmount now // Call a handler, like onModalDidMount if (typeof this.props.onModalWillUnmount === 'function') { this.props.onModalWillUnmount(); } // Remove the node and clean up after the target ReactDOM.unmountComponentAtNode(this._target); document.body.removeChild(this._target); document.body.classList.remove('liq_modal-open'); }; // A similar API to react-transition-group if ( this._component && typeof this._component.componentWillLeave === 'function' ) { // Pass the callback to be called on completion this._component.componentWillLeave(done); } else { // Call completion immediately done(); } } render() { return null; } // This doesn't actually return anything to render } ModalPortal.propTypes = { onClose: PropTypes.func, // This is called when the dialog should close children: PropTypes.node, onModalDidMount: PropTypes.func, // optional, called on mount onModalWillUnmount: PropTypes.func // optional, called on unmount }; export class ModalBackground extends React.Component { constructor(props) { super(props); this.state = { // This is set to false as soon as the component has mounted // This allows the component to change its css and animate in transparent: true }; } componentDidMount() { // Create a delay so CSS will animate requestAnimationFrame(() => this.setState({ transparent: false })); } componentWillLeave(callback) { this.setState({ transparent: true, componentIsLeaving: true }); // There isn't a good way to figure out what the duration is exactly, // because parts of the animation are carried out in CSS... setTimeout(() => { callback(); }, this.props.duration); } render() { const { transparent } = this.state; const overlayStyle = { opacity: transparent ? 0 : 0.6 }; const containerStyle = { opacity: transparent ? 0 : 1 }; return ( <div className={'liq_modal-background'} style={{ zIndex: this.props.zIndex }}> <div style={overlayStyle} className={'liq_modal-background__overlay'} /> <div style={containerStyle} className={'liq_modal-background__container'}> {this.props.children} </div> </div> ); } } ModalBackground.defaultProps = { duration: 300, zIndex: 1100 // to lay above tooltips and the website header }; ModalBackground.propTypes = { onClose: PropTypes.func, duration: PropTypes.number.isRequired, zIndex: PropTypes.number.isRequired, children: PropTypes.node }; export default { ModalPortal, ModalBackground, ModalContent };
LIQIDTechnology/liqid-react-components
src/components/Modal/Components.js
JavaScript
mit
8,193
#include "pch.h" #include "ActalogicApp.h" TCHAR ActalogicApp::m_szWindowClass[] = _T("Actalogic"); TCHAR ActalogicApp::m_szTitle[] = _T("Actalogic"); ActalogicApp::ActalogicApp(): m_hWnd(NULL), m_hInstance(NULL), m_d2d1Manager(), m_entityFPS(), m_entityDebugInfoLayer(), m_entitySceneContainer(this), m_inputHelper() { m_entityDebugInfoLayer.SetApp(this); } ActalogicApp::~ActalogicApp() { } HRESULT ActalogicApp::Initialize(HINSTANCE hInstance, int nCmdShow) { HRESULT hresult; hresult = m_d2d1Manager.CreateDeviceIndependentResources(); if (FAILED(hresult)) {return hresult;} //TODO:‚±‚±‚ÉEntity‚̃fƒoƒCƒX”ñˆË‘¶‚̏‰Šú‰»ˆ—‚ð’ljÁ hresult = m_entityDebugInfoLayer.OnCreateDeviceIndependentResources(&m_d2d1Manager); if (FAILED(hresult)) { return hresult; } hresult = m_entityFPS.OnCreateDeviceIndependentResources(&m_d2d1Manager); if (FAILED(hresult)) { return hresult; } hresult = m_entitySceneContainer.OnCreateDeviceIndependentResources(&m_d2d1Manager); if (FAILED(hresult)) { return hresult; } m_hInstance = hInstance; m_hWnd = InitializeWindow(hInstance, nCmdShow, 800.0F, 600.0F); return m_hWnd==NULL ? E_FAIL : S_OK; } HWND ActalogicApp::InitializeWindow(HINSTANCE hInstance, int nCmdShow, FLOAT width, FLOAT height) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ActalogicApp::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = m_szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION)); if (!RegisterClassEx(&wcex)) { MessageBox(NULL, _T("Call to RegisterClassEx failed!"), m_szTitle, NULL); return NULL; } FLOAT dpiX, dpiY; m_d2d1Manager.GetDesktopDpi(&dpiX, &dpiY); UINT desktopWidth = static_cast<UINT>(ceil(width * dpiX / 96.f)); UINT desktopHeight = static_cast<UINT>(ceil(height * dpiY / 96.f)); HWND hWnd = CreateWindow( m_szWindowClass, m_szTitle, WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, desktopWidth, desktopHeight, NULL, NULL, hInstance, this ); if (!hWnd) { MessageBox(NULL, _T("Call to CreateWindow failed!"), m_szTitle, NULL); return NULL; } SetClientSize(hWnd, desktopWidth, desktopHeight); if (nCmdShow == SW_MAXIMIZE) { ShowWindow(hWnd, SW_RESTORE); } else { ShowWindow(hWnd, nCmdShow); } UpdateWindow(hWnd); return hWnd; } int ActalogicApp::Run() { MSG msg; for (;;) { if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!GetMessage(&msg, NULL, 0, 0)) { return msg.wParam; } TranslateMessage(&msg); DispatchMessage(&msg); } else { if (m_isActive) { OnTick(); } else { Sleep(1); } } } } void ActalogicApp::Dispose() { //TODO:‚±‚±‚ÉEntity‚ÌƒŠƒ\[ƒX‚ÌŠJ•úˆ—‚ð’ljÁ m_entityDebugInfoLayer.OnDiscardAllResources(); m_entitySceneContainer.OnDiscardAllResources(); m_d2d1Manager.DiscardAllResources(); } void ActalogicApp::Exit() { PostMessage(m_hWnd, WM_DESTROY, 0, 0); } /////////////////////////////////////////////////////////////////////////////// void ActalogicApp::OnTick() { m_inputHelper.OnTick(); OnPreRender(); OnRender(); OnPostRender(); } void ActalogicApp::OnPreRender() { //TODO:‚±‚±‚É•`‰æ‘O‚̏ˆ—‚ð’ljÁ m_entityDebugInfoLayer.OnPreRender(&m_inputHelper); m_entityFPS.OnPreRender(&m_inputHelper); m_entitySceneContainer.OnPreRender(&m_inputHelper); } void ActalogicApp::OnRender() { HRESULT hresult = S_OK; hresult = m_d2d1Manager.CreateDeviceResources(m_hWnd); //TODO:‚±‚±‚ɃfƒoƒCƒXˆË‘¶ƒŠƒ\[ƒX‰Šú‰»ˆ—‚ð’ljÁ if (SUCCEEDED(hresult)){ m_entityDebugInfoLayer.OnCreateDeviceResources(&m_d2d1Manager); } if (SUCCEEDED(hresult)){ m_entitySceneContainer.OnCreateDeviceResources(&m_d2d1Manager); } if (SUCCEEDED(hresult)) { m_d2d1Manager.BeginDraw(); //TODO:‚±‚±‚É•`‰æˆ—‚ð’ljÁ m_entitySceneContainer.OnRender(&m_d2d1Manager); m_entityDebugInfoLayer.OnRender(&m_d2d1Manager); hresult = m_d2d1Manager.EndDraw(); } if (FAILED(hresult)) { //TODO:‚±‚±‚ÉƒŠƒ\[ƒX‚̉ð•úˆ—‚ð’ljÁ m_entityDebugInfoLayer.OnDiscardDeviceResources(); m_entitySceneContainer.OnDiscardDeviceResources(); m_d2d1Manager.DiscardDeviceResources(); } } void ActalogicApp::OnPostRender() { //TODO:‚±‚±‚É•`‰æ‘O‚̏ˆ—‚ð’ljÁ m_entityDebugInfoLayer.OnPostRender(); m_entitySceneContainer.OnPostRender(); } void ActalogicApp::OnResize(WORD width, WORD height, BOOL isActive) { m_isActive = isActive; } /////////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK ActalogicApp::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_CREATE) { LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam; ActalogicApp *pApp = (ActalogicApp *)pcs->lpCreateParams; SetWindowLongPtrW(hWnd, GWLP_USERDATA, PtrToUlong(pApp)); } else { ActalogicApp *pApp = reinterpret_cast<ActalogicApp *>(static_cast<LONG_PTR>( ::GetWindowLongPtrW(hWnd, GWLP_USERDATA))); switch (message) { case WM_DISPLAYCHANGE: InvalidateRect(hWnd, NULL, FALSE); case WM_PAINT: pApp->OnRender(); ValidateRect(hWnd, NULL); break; case WM_SIZE: { BOOL isActive = wParam == SIZE_MINIMIZED ? FALSE : TRUE; WORD width = lParam & 0xFFFF; WORD height = (lParam >> 16) & 0xFFFF; pApp->OnResize(width, height, isActive); break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); break; } } return S_OK; } VOID ActalogicApp::SetClientSize(HWND hWnd, LONG sx, LONG sy) { RECT rc1; RECT rc2; GetWindowRect(hWnd, &rc1); GetClientRect(hWnd, &rc2); sx += ((rc1.right - rc1.left) - (rc2.right - rc2.left)); sy += ((rc1.bottom - rc1.top) - (rc2.bottom - rc2.top)); SetWindowPos(hWnd, NULL, 0, 0, sx, sy, (SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE)); }
iwa-yuki/Actalogic
Actalogic/Actalogic/ActalogicApp.cpp
C++
mit
6,115
import * as React from 'react'; import * as ReactDom from 'react-dom'; import * as strings from 'BarChartDemoWebPartStrings'; import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, } from '@microsoft/sp-webpart-base'; import { PropertyPaneWebPartInformation } from '@pnp/spfx-property-controls/lib/PropertyPaneWebPartInformation'; import BarChartDemo from './components/BarChartDemo'; import { IBarChartDemoProps } from './components/IBarChartDemo.types'; export interface IBarChartDemoWebPartProps { description: string; } /** * This web part retrieves data asynchronously and renders a bar chart once loaded * It mimics a "real-life" scenario by loading (random) data asynchronously * and rendering the chart once the data has been retrieved. * To keep the demo simple, we don't specify custom colors. */ export default class BarChartDemoWebPart extends BaseClientSideWebPart<IBarChartDemoWebPartProps> { public render(): void { const element: React.ReactElement<IBarChartDemoProps > = React.createElement( BarChartDemo, { // there are no properties to pass for this demo } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { groupFields: [ PropertyPaneWebPartInformation({ description: strings.WebPartDescription, moreInfoLink: strings.MoreInfoLinkUrl, key: 'webPartInfoId' }) ] } ] } ] }; } }
rgarita/sp-dev-fx-webparts
samples/react-chartcontrol/src/webparts/barChartDemo/BarChartDemoWebPart.ts
TypeScript
mit
1,881
package ca.wescook.wateringcans.events; import ca.wescook.wateringcans.potions.ModPotions; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.client.event.FOVUpdateEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class EventFOV { @SubscribeEvent public void fovUpdates(FOVUpdateEvent event) { // Get player object EntityPlayer player = event.getEntity(); if (player.getActivePotionEffect(ModPotions.inhibitFOV) != null) { // Get player data double playerSpeed = player.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getAttributeValue(); float capableSpeed = player.capabilities.getWalkSpeed(); float fov = event.getFov(); // Disable FOV change event.setNewfov((float) (fov / ((playerSpeed / capableSpeed + 1.0) / 2.0))); } } }
WesCook/WateringCans
src/main/java/ca/wescook/wateringcans/events/EventFOV.java
Java
mit
1,001
<html><body> <h4>Windows 10 x64 (18362.449)</h4><br> <h2>FEATURE_CHANGE_TIME</h2> <font face="arial"> FEATURE_CHANGE_TIME_READ = 0n0<br> FEATURE_CHANGE_TIME_MODULE_RELOAD = 0n1<br> FEATURE_CHANGE_TIME_SESSION = 0n2<br> FEATURE_CHANGE_TIME_REBOOT = 0n3<br> FEATURE_CHANGE_TIME_USER_FLAG = 0n128<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18362.449)/FEATURE_CHANGE_TIME.html
HTML
mit
341
module Rake class << self def verbose? ENV.include? "VERBOSE" and ["1", "true", "yes"].include? ENV["VERBOSE"] end end end
chetan/test_guard
lib/test_guard/rake.rb
Ruby
mit
142
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/favicon.ico" /> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/iosicon.png" /> <!-- DEVELOPMENT LESS --> <!-- <link rel="stylesheet/less" href="css/photon.less" media="all" /> <link rel="stylesheet/less" href="css/photon-responsive.less" media="all" /> --> <!-- PRODUCTION CSS --> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all" /> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all" /> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all" /> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/images/photon/[email protected]" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="raphael.2.1.0.min.js.html#">Sign Up &#187;</a> <a href="raphael.2.1.0.min.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="raphael.2.1.0.min.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
user-tony/photon-rails
lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/css/css_compiled/js/js/plugins/prettify/js/plugins/raphael.2.1.0.min.js.html
HTML
mit
16,656