repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
duncanteege/nemo_application
app/components/province.component.ts
5364
import { Component} from '@angular/core'; import { ProvinceService } from '../services/activities/activities.service'; import { LocationService } from '../services/location/location.service'; import { Observable } from 'rxjs/Observable'; @Component({ moduleId: module.id, selector: 'provinces', templateUrl: 'province.component.html', styleUrls: ['province.component.css'], providers: [ ProvinceService, LocationService ] }) export class ProvinceComponent { provinces: Array<any>; audience: Array<any>; activities: Array<any>; location: Array<any>; results: Array<any>; active_audience_id: number; active_audience_name: string; page_number: number; loc: string; activitiesLoading: boolean; constructor(private provinceService: ProvinceService, private locationService: LocationService) { this.page_number = 0; this.provinces = [ { id: '101', name: 'Zuid-Holland', user_in_province: false }, { id: '71', name: 'Noord-Holland', user_in_province: false }, { id: '31', name: 'Gelderland', user_in_province: false }, { id: '41', name: 'Groningen', user_in_province: false }, { id: '11', name: 'Flevoland', user_in_province: false }, { id: '1', name: 'Drenthe', user_in_province: false }, { id: '61', name: 'Noord-Brabant', user_in_province: false }, { id: '8', name: 'Limburg', user_in_province: false }, { id: '91', name: 'Zeeland', user_in_province: false }, { id: '21', name: 'Friesland', user_in_province: false }, { id: '81', name: 'Utrecht', user_in_province: false }, { id: '111', name:'Overijssel', user_in_province: false } ]; this.audience = [ { id: '0', name: 'Jonge kinderen' }, { id: '1', name: 'Kinderen' }, { id: '11', name: 'Jongeren' }, { id: '21', name: 'Volwassenen' }, { id: '31', name: 'Familie' }, { id: '51', name: 'Educatief programma BO' }, { id: '61', name: 'Educatief programma VO' } ]; this.active_audience_id = 1; this.active_audience_name = 'Kinderen' this.activitiesLoading = true; } ngOnInit() { this.selectAudienceChanged(this.active_audience_id); this.getLocation(); } getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(this.showPosition.bind(this)); } } showPosition(position:any) { var lat = position.coords.latitude; var lng = position.coords.longitude; console.log(lat + ' ' + lng); this.locationService.locationUser(lat, lng).subscribe((data:any)=> { console.log(data.results[0].address_components[4].long_name); this.toggleProvinceBasedOnUserLocation(data.results[0].address_components[4].long_name); this.loc = data; }); } toggleProvinceBasedOnUserLocation(province_name:any) { for (let i = 0; i < this.provinces.length; i++) { this.provinces[i].user_in_province = false; if (province_name == this.provinces[i].name) { this.provinces[i].user_in_province = true; } } } toggleProvince(prov_id:any) { for (let i = 0; i <this.provinces.length; i++) { this.provinces[i].user_in_province = false; if (prov_id == this.provinces[i].id ) { this.provinces[i].user_in_province = true; } } } selectAudienceChanged(val:any) { this.activitiesLoading = true; console.log(this.activitiesLoading); for (let i = 0; i < this.audience.length; i++) { if (val == this.audience[i].name) { this.active_audience_id = this.audience[i].id; this.active_audience_name = val; } } console.log(this.active_audience_id); // updated value this.getPACount(this.active_audience_id); this.getAmountActivitiesAndSuchFromProvinceInfo(this.provinces); } getPACount(audience_id: any) { console.log(audience_id); for (let i = 0; i < this.provinces.length; i++) { this.provinceService.getProvinceInfo(this.provinces[i].id, audience_id).subscribe((activitiesCount:any) => { this.provinces[i].count = activitiesCount.count; }); } } // ** THIS FUNCTION RETRIEVES EVERY SINGLE ITEM FROM EVERY PAGE AT ONCE, THIS MIGHT NOT BE WHAT WE WANT ** // // ** THIS FUNCTION RETRIEVES EVERY SINGLE ITEM FROM EVERY PAGE AT ONCE, THIS MIGHT NOT BE WHAT WE WANT ** // // ** THIS FUNCTION RETRIEVES EVERY SINGLE ITEM FROM EVERY PAGE AT ONCE, THIS MIGHT NOT BE WHAT WE WANT ** // getAmountActivitiesAndSuchFromProvinceInfo(provArray: any) { for (let c = 0; c < provArray.length; c++) { this.provinceService.getProvinceInfo(provArray[c].id, this.active_audience_id).subscribe((info: any) => { let arr:any = []; for (let i = 1; i < info.totalPages+1; i++) { // console.log(i); this.provinceService.getActivityFromPage(provArray[c].id, i, this.active_audience_id).subscribe((activity:any) => { // console.log(activity); for (let l = 0; l < activity.results.length; l++) { arr.push(activity.results[l]); } }); } provArray[c].activities = arr; }); } this.activitiesLoading = false; } toggleProvinceAnchor(province:any) { // console.log(window.location.hash.substr(1)); console.log(province); for (let i = 0; i < this.provinces.length; i++) { this.provinces[i].user_in_province = false; } province.user_in_province = true; //if name achor == name province open that province } }
mit
peim/money-transfer-service
src/main/scala/com/peim/model/table/Transfers.scala
729
package com.peim.model.table import java.time.OffsetDateTime import com.peim.model.{Transfer, TransferStatus} import slick.driver.H2Driver.api._ import slick.lifted.Tag class Transfers(tag: Tag) extends Table[Transfer](tag, "transfers") { import Transfer._ def id = column[Int]("id", O.PrimaryKey, O.AutoInc) def sourceAccountId = column[Int]("source_account_id") def destAccountId = column[Int]("dest_account_id") def currencyId = column[Int]("currency_id") def sum = column[Double]("sum") def created = column[OffsetDateTime]("created") def status = column[TransferStatus]("status") def * = (id, sourceAccountId, destAccountId, currencyId, sum, created, status) <> (Transfer.tupled, Transfer.unapply) }
mit
ekov1/TelerikAcademy-Exercises
regular/C#/C# - 1/01. Introduction-to-Programming/demos/01. Console Manipulation/01. Console Manipulation.cs
636
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.Console_Manipulation { class Program { static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Cyan; Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WindowHeight = 30; Console.WindowWidth = 100; Console.WriteLine("Hello"); Console.WriteLine("WorkShop!"); int result = 3 / 1; Console.WriteLine(result); //Console.Clear(); } } }
mit
Uniandes-isis2603/company_back
company-api/src/main/java/co/edu/uniandes/csw/company/mappers/BusinessLogicExceptionMapper.java
1020
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.company.mappers; import co.edu.uniandes.csw.company.exceptions.BusinessLogicException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Convertidor de Excepciones BookLogicException a mensajes REST. */ @Provider public class BusinessLogicExceptionMapper implements ExceptionMapper<BusinessLogicException> { /** * Generador de una respuesta a partir de una excepción * @param ex excecpión a convertir a una respuesta REST */ @Override public Response toResponse(BusinessLogicException ex) { // retorna una respuesta return Response .status(Response.Status.NOT_FOUND) // estado HTTP 404 .entity(ex.getMessage()) // mensaje adicional .type("text/plain") .build(); } }
mit
thomasnilsson/thomasnilsson.github.io
ionic/capacitorDemo/src/app/home/home.module.ts
552
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { IonicModule } from '@ionic/angular'; import { FormsModule } from '@angular/forms'; import { HomePage } from './home.page'; import { HomePageRoutingModule } from './home-routing.module'; import { MessageComponentModule } from '../message/message.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, MessageComponentModule, HomePageRoutingModule ], declarations: [HomePage] }) export class HomePageModule {}
mit
greezybacon/phlite
src/Db/Exception/NotUnique.php
75
<?php namespace Phlite\Db\Exception; class NotUnique extends OrmError {}
mit
Dhonisaputra/Akar
index.js
1602
'use strict'; /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. * */ var system_path = 'system'; /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. * */ /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder then the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * http://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! * */ var application_folder = 'application'; global.SELFDIR = __dirname+'/'; global.SELF = global.SELFDIR+'index.js'; global.EXT = '.js'; global.BASEPATH = global.SELFDIR+system_path+'/'; global.FCPATH = global.SELFDIR+system_path; global.SYSDIR = global.BASEPATH; global.APPPATH = global.SELFDIR+application_folder+'/'; global.PORT = 3000; require(global.BASEPATH+'core/Akar.js')
mit
Addepar/ember-data
packages/ember-data/tests/integration/adapter/store_adapter_test.js
17484
/** This is an integration test that tests the communication between a store and its adapter. Typically, when a method is invoked on the store, it calls a related method on its adapter. The adapter notifies the store that it has completed the assigned task, either synchronously or asynchronously, by calling a method on the store. These tests ensure that the proper methods get called, and, if applicable, the given record or record array changes state appropriately. */ var get = Ember.get, set = Ember.set; var Person, Dog, env, store, adapter; module("integration/adapter/store_adapter - DS.Store and DS.Adapter integration test", { setup: function() { Person = DS.Model.extend({ updatedAt: DS.attr('string'), name: DS.attr('string'), firstName: DS.attr('string'), lastName: DS.attr('string') }); Dog = DS.Model.extend({ name: DS.attr('string') }); env = setupStore({ person: Person, dog: Dog }); store = env.store; adapter = env.adapter; }, teardown: function() { env.container.destroy(); } }); test("Records loaded multiple times and retrieved in recordArray are ready to send state events", function() { adapter.findQuery = function(store, type, query, recordArray) { return Ember.RSVP.resolve([{ id: 1, name: "Mickael Ramírez" }, { id: 2, name: "Johny Fontana" }]); }; store.findQuery('person', {q: 'bla'}).then(async(function(people) { var people2 = store.findQuery('person', { q: 'bla2' }); return Ember.RSVP.hash({ people: people, people2: people2 }); })).then(async(function(results) { equal(results.people2.get('length'), 2, 'return the elements' ); ok( results.people2.get('isLoaded'), 'array is loaded' ); var person = results.people.objectAt(0); ok(person.get('isLoaded'), 'record is loaded'); // delete record will not throw exception person.deleteRecord(); })); }); test("by default, createRecords calls createRecord once per record", function() { var count = 1; adapter.createRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (count === 1) { equal(get(record, 'name'), "Tom Dale"); } else if (count === 2) { equal(get(record, 'name'), "Yehuda Katz"); } else { ok(false, "should not have invoked more than 2 times"); } var hash = get(record, 'data'); hash.id = count; hash.updatedAt = "now"; count++; return Ember.RSVP.resolve(hash); }; var tom = store.createRecord('person', { name: "Tom Dale" }); var yehuda = store.createRecord('person', { name: "Yehuda Katz" }); Ember.RSVP.hash({ tom: tom.save(), yehuda: yehuda.save() }).then(async(function(records) { tom = records.tom; yehuda = records.yehuda; asyncEqual(tom, store.find('person', 1), "Once an ID is in, find returns the same object"); asyncEqual(yehuda, store.find('person', 2), "Once an ID is in, find returns the same object"); equal(get(tom, 'updatedAt'), "now", "The new information is received"); equal(get(yehuda, 'updatedAt'), "now", "The new information is received"); })); }); test("by default, updateRecords calls updateRecord once per record", function() { var count = 0; adapter.updateRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (count === 0) { equal(get(record, 'name'), "Tom Dale"); } else if (count === 1) { equal(get(record, 'name'), "Yehuda Katz"); } else { ok(false, "should not get here"); } count++; equal(record.get('isSaving'), true, "record is saving"); return Ember.RSVP.resolve(); }; store.push('person', { id: 1, name: "Braaaahm Dale" }); store.push('person', { id: 2, name: "Brohuda Katz" }); Ember.RSVP.hash({ tom: store.find('person', 1), yehuda: store.find('person', 2) }).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; set(tom, "name", "Tom Dale"); set(yehuda, "name", "Yehuda Katz"); return Ember.RSVP.hash({ tom: tom.save(), yehuda: yehuda.save() }); })).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; equal(tom.get('isSaving'), false, "record is no longer saving"); equal(tom.get('isLoaded'), true, "record is loaded"); equal(yehuda.get('isSaving'), false, "record is no longer saving"); equal(yehuda.get('isLoaded'), true, "record is loaded"); })); }); test("calling store.didSaveRecord can provide an optional hash", function() { var count = 0; adapter.updateRecord = function(store, type, record) { equal(type, Person, "the type is correct"); count++; if (count === 1) { equal(get(record, 'name'), "Tom Dale"); return Ember.RSVP.resolve({ id: 1, name: "Tom Dale", updatedAt: "now" }); } else if (count === 2) { equal(get(record, 'name'), "Yehuda Katz"); return Ember.RSVP.resolve({ id: 2, name: "Yehuda Katz", updatedAt: "now!" }); } else { ok(false, "should not get here"); } }; store.push('person', { id: 1, name: "Braaaahm Dale" }); store.push('person', { id: 2, name: "Brohuda Katz" }); Ember.RSVP.hash({ tom: store.find('person', 1), yehuda: store.find('person', 2) }).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; set(tom, "name", "Tom Dale"); set(yehuda, "name", "Yehuda Katz"); return Ember.RSVP.hash({ tom: tom.save(), yehuda: yehuda.save() }); })).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; equal(get(tom, 'isDirty'), false, "the record should not be dirty"); equal(get(tom, 'updatedAt'), "now", "the hash was updated"); equal(get(yehuda, 'isDirty'), false, "the record should not be dirty"); equal(get(yehuda, 'updatedAt'), "now!", "the hash was updated"); })); }); test("by default, deleteRecord calls deleteRecord once per record", function() { expect(4); var count = 0; adapter.deleteRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (count === 0) { equal(get(record, 'name'), "Tom Dale"); } else if (count === 1) { equal(get(record, 'name'), "Yehuda Katz"); } else { ok(false, "should not get here"); } count++; return Ember.RSVP.resolve(); }; store.push('person', { id: 1, name: "Tom Dale" }); store.push('person', { id: 2, name: "Yehuda Katz" }); Ember.RSVP.hash({ tom: store.find('person', 1), yehuda: store.find('person', 2) }).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; tom.deleteRecord(); yehuda.deleteRecord(); tom.save(); yehuda.save(); })); }); test("by default, destroyRecord calls deleteRecord once per record without requiring .save", function() { expect(4); var count = 0; adapter.deleteRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (count === 0) { equal(get(record, 'name'), "Tom Dale"); } else if (count === 1) { equal(get(record, 'name'), "Yehuda Katz"); } else { ok(false, "should not get here"); } count++; return Ember.RSVP.resolve(); }; store.push('person', { id: 1, name: "Tom Dale" }); store.push('person', { id: 2, name: "Yehuda Katz" }); Ember.RSVP.hash({ tom: store.find('person', 1), yehuda: store.find('person', 2) }).then(async(function(records) { var tom = records.tom, yehuda = records.yehuda; tom.destroyRecord(); yehuda.destroyRecord(); })); }); test("if an existing model is edited then deleted, deleteRecord is called on the adapter", function() { expect(5); var count = 0; adapter.deleteRecord = function(store, type, record) { count++; equal(get(record, 'id'), 'deleted-record', "should pass correct record to deleteRecord"); equal(count, 1, "should only call deleteRecord method of adapter once"); return Ember.RSVP.resolve(); }; adapter.updateRecord = function() { ok(false, "should not have called updateRecord method of adapter"); }; // Load data for a record into the store. store.push('person', { id: 'deleted-record', name: "Tom Dale" }); // Retrieve that loaded record and edit it so it becomes dirty store.find('person', 'deleted-record').then(async(function(tom) { tom.set('name', "Tom Mothereffin' Dale"); equal(get(tom, 'isDirty'), true, "precond - record should be dirty after editing"); tom.deleteRecord(); return tom.save(); })).then(async(function(tom) { equal(get(tom, 'isDirty'), false, "record should not be dirty"); equal(get(tom, 'isDeleted'), true, "record should be considered deleted"); })); }); test("if a deleted record errors, it enters the error state", function() { var count = 0; adapter.deleteRecord = function(store, type, record) { if (count++ === 0) { return Ember.RSVP.reject(); } else { return Ember.RSVP.resolve(); } }; store.push('person', { id: 'deleted-record', name: "Tom Dale" }); var tom; store.find('person', 'deleted-record').then(async(function(person) { tom = person; person.deleteRecord(); return person.save(); })).then(null, async(function() { equal(tom.get('isError'), true, "Tom is now errored"); // this time it succeeds return tom.save(); })).then(async(function() { equal(tom.get('isError'), false, "Tom is not errored anymore"); })); }); test("if a created record is marked as invalid by the server, it enters an error state", function() { adapter.createRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (get(record, 'name').indexOf('Bro') === -1) { return Ember.RSVP.reject(new DS.InvalidError({ name: ['common... name requires a "bro"'] })); } else { return Ember.RSVP.resolve(); } }; var yehuda = store.createRecord('person', { id: 1, name: "Yehuda Katz" }); // Wrap this in an Ember.run so that all chained async behavior is set up // before flushing any scheduled behavior. Ember.run(function() { yehuda.save().then(null, async(function(error) { equal(get(yehuda, 'isValid'), false, "the record is invalid"); ok(get(yehuda, 'errors.name'), "The errors.name property exists"); set(yehuda, 'updatedAt', true); equal(get(yehuda, 'isValid'), false, "the record is still invalid"); // This tests that we handle undefined values without blowing up var errors = get(yehuda, 'errors'); set(errors, 'other_bound_property', undefined); set(yehuda, 'errors', errors); set(yehuda, 'name', "Brohuda Brokatz"); equal(get(yehuda, 'isValid'), true, "the record is no longer invalid after changing"); equal(get(yehuda, 'isDirty'), true, "the record has outstanding changes"); equal(get(yehuda, 'isNew'), true, "precond - record is still new"); return yehuda.save(); })).then(async(function(person) { strictEqual(person, yehuda, "The promise resolves with the saved record"); equal(get(yehuda, 'isValid'), true, "record remains valid after committing"); equal(get(yehuda, 'isNew'), false, "record is no longer new"); })); }); }); test("if a created record is marked as erred by the server, it enters an error state", function() { adapter.createRecord = function(store, type, record) { return Ember.RSVP.reject(); }; Ember.run(function() { var person = store.createRecord('person', { id: 1, name: "John Doe" }); person.save().then(null, async(function() { ok(get(person, 'isError'), "the record is in the error state"); })); }); }); test("if an updated record is marked as invalid by the server, it enters an error state", function() { adapter.updateRecord = function(store, type, record) { equal(type, Person, "the type is correct"); if (get(record, 'name').indexOf('Bro') === -1) { return Ember.RSVP.reject(new DS.InvalidError({ name: ['common... name requires a "bro"'] })); } else { return Ember.RSVP.resolve(); } }; var yehuda = store.push('person', { id: 1, name: "Brohuda Brokatz" }); Ember.run(function() { store.find('person', 1).then(async(function(person) { equal(person, yehuda, "The same object is passed through"); equal(get(yehuda, 'isValid'), true, "precond - the record is valid"); set(yehuda, 'name', "Yehuda Katz"); equal(get(yehuda, 'isValid'), true, "precond - the record is still valid as far as we know"); equal(get(yehuda, 'isDirty'), true, "the record is dirty"); return yehuda.save(); })).then(null, async(function(reason) { equal(get(yehuda, 'isDirty'), true, "the record is still dirty"); equal(get(yehuda, 'isValid'), false, "the record is invalid"); set(yehuda, 'updatedAt', true); equal(get(yehuda, 'isValid'), false, "the record is still invalid"); set(yehuda, 'name', "Brohuda Brokatz"); equal(get(yehuda, 'isValid'), true, "the record is no longer invalid after changing"); equal(get(yehuda, 'isDirty'), true, "the record has outstanding changes"); return yehuda.save(); })).then(async(function(yehuda) { equal(get(yehuda, 'isValid'), true, "record remains valid after committing"); equal(get(yehuda, 'isDirty'), false, "record is no longer new"); })); }); }); test("if a updated record is marked as erred by the server, it enters an error state", function() { adapter.updateRecord = function(store, type, record) { return Ember.RSVP.reject(); }; var person = store.push(Person, { id: 1, name: "John Doe" }); store.find('person', 1).then(async(function(record) { equal(record, person, "The person was resolved"); person.set('name', "Jonathan Doe"); return person.save(); })).then(null, async(function(reason) { ok(get(person, 'isError'), "the record is in the error state"); })); }); test("can be created after the DS.Store", function() { expect(1); adapter.find = function(store, type) { equal(type, Person, "the type is correct"); return Ember.RSVP.resolve({ id: 1 }); }; store.find('person', 1); }); test("the filter method can optionally take a server query as well", function() { adapter.findQuery = function(store, type, query, array) { return Ember.RSVP.resolve([ { id: 1, name: "Yehuda Katz" }, { id: 2, name: "Tom Dale" } ]); }; var asyncFilter = store.filter('person', { page: 1 }, function(data) { return data.get('name') === "Tom Dale"; }); var loadedFilter; asyncFilter.then(async(function(filter) { loadedFilter = filter; return store.find('person', 2); })).then(async(function(tom) { equal(get(loadedFilter, 'length'), 1, "The filter has an item in it"); deepEqual(loadedFilter.toArray(), [ tom ], "The filter has a single entry in it"); })); }); test("relationships returned via `commit` do not trigger additional findManys", function() { Person.reopen({ dogs: DS.hasMany() }); store.push('dog', { id: 1, name: "Scruffy" }); adapter.find = function(store, type, id) { return Ember.RSVP.resolve({ id: 1, name: "Tom Dale", dogs: [1] }); }; adapter.updateRecord = function(store, type, record) { return new Ember.RSVP.Promise(function(resolve, reject) { store.push('person', { id: 1, name: "Tom Dale", dogs: [1, 2] }); store.push('dog', { id: 2, name: "Scruffles" }); resolve({ id: 1, name: "Scruffy" }); }); }; adapter.findMany = function(store, type, ids) { ok(false, "Should not get here"); }; store.find('person', 1).then(async(function(person) { return Ember.RSVP.hash({ tom: person, dog: store.find('dog', 1) }); })).then(async(function(records) { records.tom.get('dogs'); return records.dog.save(); })).then(async(function(tom) { ok(true, "Tom was saved"); })); }); test("relationships don't get reset if the links is the same", function() { Person.reopen({ dogs: DS.hasMany({ async: true }) }); var count = 0; adapter.findHasMany = function() { ok(count++ === 0, "findHasMany is only called once"); return Ember.RSVP.resolve([{ id: 1, name: "Scruffy" }]); }; store.push('person', { id: 1, name: "Tom Dale", links: { dogs: "/dogs" } }); var tom, dogs; store.find('person', 1).then(async(function(person) { tom = person; dogs = tom.get('dogs'); return dogs; })).then(async(function(dogs) { equal(dogs.get('length'), 1, "The dogs are loaded"); store.push('person', { id: 1, name: "Tom Dale", links: { dogs: "/dogs" } }); ok(tom.get('dogs') instanceof DS.PromiseArray, 'dogs is a promise'); return tom.get('dogs'); })).then(async(function(dogs) { equal(dogs.get('length'), 1, "The same dogs are loaded"); })); }); test("async hasMany always returns a promise", function() { Person.reopen({ dogs: DS.hasMany({ async: true }) }); adapter.createRecord = function(store, type, record) { var hash = { name: "Tom Dale" }; hash.dogs = Ember.A(); hash.id = 1; return Ember.RSVP.resolve(hash); }; var tom = store.createRecord('person', { name: "Tom Dale" }); ok(tom.get('dogs') instanceof DS.PromiseArray, "dogs is a promise before save"); tom.save().then(async(function() { ok(tom.get('dogs') instanceof DS.PromiseArray, "dogs is a promise after save"); })); });
mit
otm/longest-common-prefix
lcp.go
708
// Package lcp (Longest Common Prefix) is used for text compleation package lcp // Find returns an array of strings that matches the longest needle func Find(needle string, haystack []string) ([]string, error) { result := make([]string, len(haystack)) temp := make([]string, 0, len(result)) copy(result, haystack) for i, l := 0, len(needle); i < l; i++ { for j := 0; j < len(result); j++ { if i >= len(result[j]) { continue } if needle[i] == result[j][i] { temp = append(temp, result[j]) } } if len(temp) == 0 { if i == 0 { return make([]string, 0), nil } return result, nil } result, temp = temp, make([]string, 0, len(result)) } return result, nil }
mit
fabsgc/framework
Core/Facade/FacadeEntity.php
2444
<?php /*\ | ------------------------------------------------------ | @file : FacadeEntity.php | @author : Fabien Beaujean | @description : easier way to instantiate entities | @version : 3.0 Bêta | ------------------------------------------------------ \*/ namespace Gcs\Framework\Core\Facade; use Gcs\Framework\Core\Exception\MissingEntityException; /** * Class FacadeEntity * @package Gcs\Framework\Core\Facade */ class FacadeEntity { /** * Constructor * @access public * @since 3.0 * @package Gcs\Framework\Core\Facade */ final public function __construct() { } /** * instantiate the good Entity * @access public * @param $name string * @param $arguments array * @throws \Gcs\Framework\Core\Exception\MissingEntityException * @return \Gcs\Framework\Core\Orm\Entity\Entity * @since 3.0 * @package Gcs\Framework\Core\Facade */ public function __call($name, $arguments) { if (file_exists(APP_RESOURCE_ENTITY_PATH . $name . '.php')) { include_once(APP_RESOURCE_ENTITY_PATH . $name . '.php'); $class = '\Orm\Entity\\' . $name; $params = []; foreach ($arguments as $value) { array_push($params, $value); } $reflect = new \ReflectionClass($class); /** @var \Gcs\Framework\Core\Orm\Entity\Entity $instance */ $instance = $reflect->newInstanceArgs($params); return $instance; } else { $file = ''; $line = ''; $stack = debug_backtrace(0); $trace = $this->getStackTraceFacade($stack); foreach ($trace as $value) { if ($value['function'] == $name) { $file = $value['file']; $line = $value['line']; break; } } throw new MissingEntityException('undefined Entity "' . $name . '" in "' . $file . '" line ' . $line); } } /** * @param $string * @return mixed * @since 3.0 * @package Gcs\Framework\Core\Facade */ public function getStackTraceFacade($string) { return $string; } /** * Destructor * @access public * @return void * @since 3.0 * @package Gcs\Framework\Core\Facade */ public function __destruct() { } }
mit
floraison/fugit
doc/cron.rb
559
require 'fugit' c = Fugit::Cron.parse('0 0 * * sun') # or c = Fugit::Cron.new('0 0 * * sun') p Time.now # => 2017-01-03 09:53:27 +0900 p c.next_time # => 2017-01-08 00:00:00 +0900 p c.previous_time # => 2017-01-01 00:00:00 +0900 p c.brute_frequency # => [ 604800, 604800, 53 ] # [ delta min, delta max, occurrence count ] p c.match?(Time.parse('2017-08-06')) # => true p c.match?(Time.parse('2017-08-07')) # => false p c.match?('2017-08-06') # => true p c.match?('2017-08-06 12:00') # => false
mit
fieldenms/tg
platform-web-ui/src/main/web/ua/com/fielden/platform/web/components/tg-toast.js
13130
import '/resources/polymer/@polymer/iron-flex-layout/iron-flex-layout.js'; import '/resources/polymer/@polymer/paper-dialog/paper-dialog.js' import '/resources/polymer/@polymer/paper-dialog-scrollable/paper-dialog-scrollable.js' import '/resources/polymer/@polymer/paper-styles/color.js'; import '/resources/polymer/@polymer/paper-button/paper-button.js'; import '/resources/polymer/@polymer/paper-toast/paper-toast.js'; import '/resources/polymer/@polymer/paper-spinner/paper-spinner.js'; import '/resources/polymer/@polymer/polymer/lib/elements/dom-bind.js'; import { tearDownEvent, containsRestictedTags } from '/resources/reflection/tg-polymer-utils.js'; import { Polymer } from '/resources/polymer/@polymer/polymer/lib/legacy/polymer-fn.js'; import { html } from '/resources/polymer/@polymer/polymer/lib/utils/html-tag.js'; const paperToastStyle = html` <custom-style> <style> #toast { @apply --layout-horizontal; @apply --layout-center; max-width: 256px; left:0; bottom:0; } .more { padding-left: 8px; color: #03A9F4; font-weight: 800; cursor: pointer; } #toast paper-spinner { width: 1.5em; height: 1.5em; min-width: 1em; min-height: 1em; max-width: 2em; max-height: 2em; padding: 2px; margin-left: 1em; --paper-spinner-layer-1-color: var(--paper-blue-500); --paper-spinner-layer-2-color: var(--paper-blue-500); --paper-spinner-layer-3-color: var(--paper-blue-500); --paper-spinner-layer-4-color: var(--paper-blue-500); } .toast-dialog paper-button { color: var(--paper-light-blue-500); --paper-button-flat-focus-color: var(--paper-light-blue-50); } .toast-dialog paper-button:hover { background: var(--paper-light-blue-50); } </style> </custom-style>`; paperToastStyle.setAttribute('style', 'display: none;'); document.head.appendChild(paperToastStyle.content); const template = html` <paper-toast id="toast" class="paper-toast" text="[[_text]]" on-tap="_showMoreIfPossible" allow-click-through always-on-top duration="0"> <!-- TODO responsive-width="250px" --> <paper-spinner id="spinner" hidden$="[[_skipShowProgress]]" active alt="in progress..." tabIndex="-1"></paper-spinner> <div id='btnMore' hidden$="[[_skipShowMore(_showProgress, _hasMore)]]" class="more" on-tap="_showMessageDlg">MORE</div> </paper-toast> `; const PROGRESS_DURATION = 3600000; // 1 hour const CRITICAL_DURATION = 5000; // 5 seconds const MORE_DURATION = 4000; // 4 seconds const STANDARD_DURATION = 2000; // 2 seconds Polymer({ // attributes="msgHeading -- TODO was this ever needed?" _template: template, is: 'tg-toast', properties: { ///////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////// EXTERNAL PROPERTIES ////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////// // These mandatory properties must be specified in attributes, when constructing descendant elements. // // No default values are allowed in this case. // ///////////////////////////////////////////////////////////////////////////////////////////////////////// text: { type: String }, msgText: { type: String, value: '' }, showProgress: { type: Boolean }, hasMore: { type: Boolean }, isCritical: { type: Boolean, value: false }, ///////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////// INNER PROPERTIES, THAT GOVERN CHILDREN ///////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////// // These properties derive from other properties and are considered as 'private' -- need to have '_' // // prefix. // // Also, these properties are designed to be bound to children element properties -- it is necessary to// // populate their default values in ready callback (to have these values populated in children)! // ///////////////////////////////////////////////////////////////////////////////////////////////////////// _text: { type: String }, _msgText: { type: String, value: '' }, _showProgress: { type: Boolean }, _hasMore: { type: Boolean, observer: '_hasMoreChanged' }, _isCritical: { type: Boolean, value: false }, _skipShowProgress: { type: Boolean, computed: '_shouldSkipProgress(_showProgress, _hasMore)' } }, ready: function () { //Indicates whether toast overlay can be closed via history (back button or not) this.$.toast.skipHistoryAction = true; // Styles to truncate the toast text. const label = this.$.toast.$$('#label'); label.style.flex = '1'; label.style.whiteSpace = 'nowrap'; label.style.overflow = 'hidden'; label.style.textOverflow = 'ellipsis'; }, _hasMoreChanged: function (newValue, oldValue) { // let's set a cursor for the whole toast if it can be "clicked" const cursor = newValue === true ? 'pointer' : 'inherit'; this.$.toast.style.cursor = cursor; }, _showMoreIfPossible: function (e) { if (this._hasMore) { // show dialog with 'more' information and close toast this._showMessageDlg(e); } else if (!this._showProgress && this._isCritical !== true) { // close toast on tap; however, do not close if it represents progress indication or if it is critical, but does not have MORE button (rare cases) this._closeToast(); } }, _showMessageDlg: function (event) { const self = this; const _msgText = self._msgText; // provide strong guarantees on _msgText immutability here -- this will be used later for msgDialog message text (after two async calls) // need to open dialog asynchronously for it to open on mobile devices this.async(function () { // build and display the dialog const domBind = document.createElement('dom-bind'); domBind._dialogClosed = function () { document.body.removeChild(this); }.bind(domBind); domBind.innerHTML = ` <template> <paper-dialog id="msgDialog" class="toast-dialog" on-iron-overlay-closed="_dialogClosed" always-on-top with-backdrop entry-animation="scale-up-animation" exit-animation="fade-out-animation"> <paper-dialog-scrollable> <p id="msgPar" style="padding: 10px;white-space: break-spaces;"></p> </paper-dialog-scrollable> <div class="buttons"> <paper-button dialog-confirm affirmative autofocus> <span>Close</span> </paper-button> </div> </paper-dialog> </template> `; document.body.appendChild(domBind); this.async(function () { // please note that domBind.$.msgPar is rendered after body.appendChild(domBind), but has been put here (into async(100)) to provide stronger guarantees along with msgDialog.open() if (containsRestictedTags(_msgText) === true) { domBind.$.msgPar.textContent = _msgText; } else { domBind.$.msgPar.innerHTML = _msgText; } // actual msgDialog opening domBind.$.msgDialog.open(); self.$.toast.close(); // must close paper-toast after msgDialog is opened; this is because other fast toast messages can interfere -- paper-toast should still be opened to prevent other messages early opening (see '... && previousToast.opened && ...' condition in 'show' method) }, 100); }, 100); tearDownEvent(event); }, _shouldSkipProgress: function (progress, hasMore) { return !progress || hasMore; }, _skipShowMore: function (progress, hasMore) { return progress || !hasMore; }, _getPreviousToast() { const toasts = document.querySelectorAll('#toast'); let toast = null; let existingToastCount = 0; for (let index = 0; index < toasts.length; index++) { const currToast = toasts.item(index); if (currToast.parentNode === document.body) { existingToastCount++; if (existingToastCount > 1) { throw 'More than one toast exist in body direct children.'; } toast = currToast; } } return toast; }, show: function () { const previousToast = this._getPreviousToast(); if (!previousToast) { // initial values this.$.toast.error = false; this.$.toast._autoCloseCallBack = null; // must NOT interfere with _autoClose of paper-toast // Override refit function for paper-toast which behaves really weird (Maybe next releas of paper-toast iron-fit-behavior and iron-overlay-behavior will change this weird behaviour). this.$.toast.refit = function () { }; document.body.appendChild(this.$.toast); this._showNewToast(); } else if (previousToast.error === true && previousToast.opened && this.isCritical === false) { // discard new toast if existing toast is critical and new one is not; however if new one is critical -- do not discard it -- show overridden information console.warn(' toast show: DISCARDED: text = ', this.text + ', critical = ' + this.isCritical); } else { // '__dataHost' is used to detemine 'tg-toast' instance from 'previousToast' found on body (parent of 'previousToast' is body, that is why there is a need to use other accessing method). // WARNING: '__dataHost' is not a public Polymer API. const previousTgToast = previousToast.__dataHost; if (previousTgToast !== this) { previousTgToast.text = this.text; previousTgToast.msgText = this.msgText; previousTgToast.showProgress = this.showProgress; previousTgToast.hasMore = this.hasMore; previousTgToast.isCritical = this.isCritical; } previousTgToast._showNewToast(); } }, _showNewToast: function () { this._text = this.text; this._msgText = this.msgText; this._showProgress = this.showProgress; this._hasMore = this.hasMore; this._isCritical = this.isCritical; let customDuration; if (this._showProgress && !this._hasMore) { customDuration = PROGRESS_DURATION; } else if (this._isCritical === true) { customDuration = CRITICAL_DURATION; } else if (this._hasMore === true) { customDuration = MORE_DURATION; } else { customDuration = STANDARD_DURATION; } if (this._isCritical === true || this.$.toast.error === false) { // if critical toast arrived then delay its closing; also delay closing if toast is not critical but old toast is not critical too if (this.$.toast._autoCloseCallBack !== null) { this.$.toast.cancelAsync(this.$.toast._autoCloseCallBack); this.$.toast._autoCloseCallBack = null; } this.$.toast._autoCloseCallBack = this.$.toast.async(this._closeToast.bind(this), customDuration); } this.$.toast.error = this._isCritical; if (this._isCritical === true) { this.$.toast.style.background = '#D50000'; this.$.btnMore.style.color = '#FFCDD2'; } else { this.$.toast.style.background = 'black'; this.$.btnMore.style.color = '#03A9F4'; } this.$.toast.show(); }, _closeToast: function () { this.$.toast.close(); this.$.toast._autoCloseCallBack = null; this.$.toast.error = false; } });
mit
supun19/directPayFrontend
src/app/class/User.ts
185
export class User{ constructor(public id:string,public firstName:string,public lastName:string,public accountNumber:string,public nic:string,public phoneNumber:string){ } }
mit
nesi/pan_pdu
rlib/webbrowser.rb
9665
require 'net/http' require 'net/https' require 'uri' require 'nokogiri' #WebBrowser class, derived from Rob Burrowes' Wikarekare source (MIT License). #Encapsulates simple methods to log into a web site, and pull pages. class WebBrowser attr_reader :host attr_accessor :session attr_accessor :cookie attr_reader :page attr_accessor :referer attr_accessor :debug #Create a WebBrowser instance # @param host [String] the host we want to connect to # @return [WebBrowser] def initialize(host) @host = host #Need to do this, as passing nil is different to passing nothing to initialize! @cookies = nil @debug = false end #Create a WebBrowser instance, connect to the host via http, and yield the WebBrowser instance. # Automatically closes the http session on returning from the block passed to it. # @param host [String] the host we want to connect to # @param port [Fixnum] (80) the port the remote web server is running on # @param block [Proc] # @yieldparam [WebBrowser] the session descriptor for further calls. def self.http_session(host, port = 80) wb = self.new(host) wb.http_session(port) do yield wb end end #Create a WebBrowser instance, connect to the host via https, and yield the WebBrowser instance. # Automatically closes the http session on returning from the block passed to it. # @param host [String] the host we want to connect to # @param port [Fixnum] (443) the port the remote web server is running on # @param block [Proc] # @yieldparam [WebBrowser] the session descriptor for further calls. def self.https_session(host, port=443) wb = self.new(host) wb.https_session(port) do yield wb end end #Creating a session for http connection # attached block would then call get or post NET::HTTP calls # @param port [Fixnum] Optional http server port # @param block [Proc] # @yieldparam [Net::HTTP] def http_session(port = 80) @http = Net::HTTP.new(@host, port) @ssl = @http.use_ssl = false @http.start do |session| #ensure we close the session after the block @session = session yield end end #Creating a session for https connection # attached block would then call get or post NET::HTTP calls # @param port [Fixnum] Optional http server port # @param block [Proc] # @yieldparam [Net::HTTP] def https_session(port = 443) @http = Net::HTTP.new(@host, port) @ssl = @http.use_ssl = true #Use https. Doesn't happen automatically! @http.verify_mode = OpenSSL::SSL::VERIFY_NONE #ignore that this is not a signed cert. (as they usually aren't in embedded devices) @http.start do |session| #ensure we close the session after the block @session = session yield end end #send the query to the web server using an http get, and returns the response. # Cookies in the response get preserved in @cookie, so they will be sent along with subsequent calls # We are currently ignoring redirects from the PDU's we are querying. # @param query [String] The URL after the http://host/ bit and not usually not including parameters, if form_values are passed in # @param form_values [Hash{String=>Object-with-to_s}] The parameter passed to the web server eg. ?key1=value1&key2=value2... # @return [String] The Net::HTTPResponse.body text response from the web server def get_page(query,form_values=nil) query += form_values_to_s(form_values, query.index('?') != nil) #Should be using req.set_form_data, but it seems to by stripping the leading / and then the query fails. #$stderr.puts query url = @ssl ? URI.parse("https://#{@host}/#{query}") : URI.parse("http://#{@host}/#{query}") $stderr.puts url if @debug req = Net::HTTP::Get.new(url.path) header = {'User-Agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5', 'Content-Type' => 'application/x-www-form-urlencoded'} header['Cookie'] = @cookie if @cookie != nil $stderr.puts header['Cookie'] if debug req.initialize_http_header( header ) response = @session.request(req) if(response.code.to_i != 200) if(response.code.to_i == 302) #ignore the redirects. #$stderr.puts "302" #response.each {|key, val| $stderr.printf "%s = %s\n", key, val } #Location seems to have cgi params removed. End up with .../cginame?& #$stderr.puts "Redirect to #{response['location']}" #Location seems to have cgi params removed. End up with .../cginame?& if (response_text = response.response['set-cookie']) != nil @cookie = response_text else @cookie = '' end #$stderr.puts return end raise "#{response.code} #{response.message}" end if (response_text = response.response['set-cookie']) != nil @cookie = response_text else @cookie = '' end return response.body end #send the query to the web server using an http post, and returns the response. # Cookies in the response get preserved in @cookie, so they will be sent along with subsequent calls # We are currently ignoring redirects from the PDU's we are querying. # @param query [String] The URL after the http://host/ bit and not usually not including parameters, if form_values are passed in # @param form_values [Hash{String=>Object-with-to_s}] The parameter passed to the web server eg. ?key1=value1&key2=value2... # @return [String] The Net::HTTPResponse.body text response from the web server def post_page(query,form_values=nil) #query += form_values_to_s(form_values) #Should be using req.set_form_data, but it seems to by stripping the leading / and then the query fails. #$stderr.puts query url = @ssl ? URI.parse("https://#{@host}/#{query}") : URI.parse("http://#{@host}/#{query}") $stderr.puts url if @debug req = Net::HTTP::Post.new(url.path) header = {'User-Agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5', 'Content-Type' => 'application/x-www-form-urlencoded'} header['Cookie'] = @cookie if @cookie != nil $stderr.puts header['Cookie'] if debug req.initialize_http_header( header ) req.set_form_data(form_values, '&') if form_values != nil response = @session.request(req) if(response.code.to_i != 200) if(response.code.to_i == 302) #ignore the redirects. #$stderr.puts "302" #response.each {|key, val| $stderr.printf "%s = %s\n", key, val } #Location seems to have cgi params removed. End up with .../cginame?& #$stderr.puts "Redirect of Post to #{response['location']}" #Location seems to have cgi params removed. End up with .../cginame?& if (response_text = response.response['set-cookie']) != nil @cookie = response_text else @cookie = '' end #$stderr.puts return end raise "#{response.code} #{response.message}" end if (response_text = response.response['set-cookie']) != nil @cookie = response_text else @cookie = '' end @response = response return response.body end =begin #Take an html response with an embedded table and turn the table rows into Array rows. # @example [ [row1_column1, row1_column2],...] # @param s [String] The html response body # @return [Array] An Array of table rows extracted from the Table # def extract_table(s) #Document.new(s).elements["HTML/BODY/TABLE/TR"].each do |tr| entry = true doc = Hpricot(s) (doc/"table/tr").each do |tr| new_row = [] (tr/"td").each do |cell| new_row << cell.inner_text.strip #Want the cell contents less the format tags, stripping leading and trailing spaces. end if(entry == true) entry = false row_names << new_row row_names.each_with_index { |v,i| index[v] = i } #Create a hash index of row names to their index else resultset << new_row end end end =end #Extract form field values from the html body. # @param body [String] The html response body # @return [Hash] Keys are the field names, values are the field values def extract_input_fields(body) entry = true @inputs = {} doc = Nokogiri::HTML(body) doc.xpath("//form/input").each do |f| @inputs[f.get_attribute('name')] = f.get_attribute('value') end end #Extract links from the html body. # @param body [String] The html response body # @return [Hash] Keys are the link text, values are the html links def extract_link_fields(body) entry = true @inputs = {} doc = Nokogiri::HTML(body) doc.xpath("//a").each do |f| return URI.parse( f.get_attribute('href') ).path if(f.get_attribute('name') == 'URL$1') end return nil end #Take a hash of the params to the post and generate a safe URL string. # @param form_values [Hash] Keys are the field names, values are the field values # @param has_q [Boolean] We have a leading ? for the html get, so don't need to add one. # @return [String] The 'safe' text for fields the get or post query to the web server def form_values_to_s(form_values=nil, has_q = false) return "" if form_values == nil s = (has_q == true ? "" : "?") first = true form_values.each do |key,value| s += "&" if !first s += "#{URI.escape(key)}=#{URI.escape(value)}" first = false end return s end end
mit
jumilla/laravel-extension
tests/Generators/Commands/RequestMakeCommandTests.php
2318
<?php use LaravelPlus\Extension\Generators\Commands\RequestMakeCommand as Command; class RequestMakeCommandTests extends TestCase { use ConsoleCommandTrait; /** * @test */ public function test_withNoParameter() { // 1. setup $app = $this->createApplication(); // 2. condition // 3. test $command = $app->make(Command::class); try { $this->runCommand($app, $command); Assert::failure(); } catch (RuntimeException $ex) { Assert::stringStartsWith('Not enough arguments', $ex->getMessage()); } } /** * @test */ public function test_withNameParameter() { // 1. setup $app = $this->createApplication(); // 2. condition // 3. test $command = $app->make(Command::class); $result = $this->runCommand($app, $command, [ 'name' => 'foo', ]); Assert::same(0, $result); Assert::fileExists($app['path'].'/Http/Requests/Foo.php'); } /** * @test */ public function test_withNameAndAddonParameter_addonNotFound() { // 1. setup $app = $this->createApplication(); // 2. condition // 3. test $command = $app->make(Command::class); try { $result = $this->runCommand($app, $command, [ 'name' => 'foo', '--addon' => 'bar', ]); Assert::failure(); } // RuntimeException: Addon 'bar' is not found. catch (RuntimeException $ex) { Assert::equals("Addon 'bar' is not found.", $ex->getMessage()); } } /** * @test */ public function test_withNameAndAddonParameter_addonFound() { // 1. setup $app = $this->createApplication(); $this->createAddon('bar', 'minimum', [ 'namespace' => 'Bar', ]); // 2. condition // 3. test $command = $app->make(Command::class); $result = $this->runCommand($app, $command, [ 'name' => 'foo', '--addon' => 'bar', ]); Assert::same(0, $result); Assert::fileExists($app['path.base'].'/addons/bar/classes/Requests/Foo.php'); } }
mit
krasi-totev/Telerik-Academy-2016-Homeworks
Module 1/C#/Operators-and-Expressions-Homework/Trapezoids/Trapezoids.cs
317
using System; class Trapezoids { static void Main() { double a = double.Parse(Console.ReadLine()); double b = double.Parse(Console.ReadLine()); double h = double.Parse(Console.ReadLine()); double area = h * ((a + b) / 2); Console.WriteLine("{0:F7}", area); } }
mit
ismailakbudak/hesap
app/models/admin_profile.rb
272
class AdminProfile < ActiveRecord::Base belongs_to :admin validates_presence_of :first_name, :last_name def full_name [first_name, last_name].join(' ') end def self.by_letter(letter) where("last_name LIKE ?", "#{letter}%").order(:last_name) end end
mit
HenryJW/fcc-stocks-chart-app
server/app.js
1380
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '../client'))); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
mit
jaroslavtyc/drd-plus-tables
DrdPlus/Tables/Measurements/Wounds/Exceptions/Exception.php
174
<?php declare(strict_types = 1); namespace DrdPlus\Tables\Measurements\Wounds\Exceptions; interface Exception extends \DrdPlus\Tables\Measurements\Exceptions\Exception { }
mit
brett-harvey/Smart-Contracts
Ethereum-based-Roll4Win/node_modules/workbox-build/src/entry-points/options/generate-sw-schema.js
1052
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const joi = require('joi'); const commonGenerateSchema = require('./common-generate-schema'); const defaults = require('./defaults'); // Define some additional constraints. module.exports = commonGenerateSchema.keys({ globDirectory: joi.string().required(), importScripts: joi.array().items(joi.string()), importWorkboxFrom: joi.string().default(defaults.importWorkboxFrom).valid( 'cdn', 'local', 'disabled' ), swDest: joi.string().required(), });
mit
TFaga/kumuluzee-examples
java-magazine-trains/ui/src/main/java/com/acme/trains/BookingsBean.java
847
package com.acme.trains; import com.acme.trains.models.Booking; import java.util.List; import javax.enterprise.inject.Model; import javax.inject.Inject; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.GenericType; /** * <p>Manages bookings for the UI via the REST interface from the bookings microservice.</p> * * @author Tilen Faganel * @since 2.0.0 */ @Model public class BookingsBean { @Inject private ServiceRegistry services; /** * <p>Retrieves the list of all available bookings.</p> * * @return List of all available bookings. */ public List<Booking> getAllBookings() { return ClientBuilder.newClient() .target(services.discoverServiceURI("trains-booking")).path("bookings") .request().get(new GenericType<List<Booking>>() {}); } }
mit
tedeh/jayson
examples/relay/server_public.js
280
'use strict'; const jayson = require('jayson'); // create a server where "add" will relay a localhost-only server const server = new jayson.server({ add: new jayson.client.http({ port: 3001 }) }); // let the frontend server listen to *:3000 server.http().listen(3000);
mit
cecilgol/utdebatecamp_com
config/environments/test.rb
576
Rails.application.configure do config.cache_classes = true config.eager_load = false config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_dispatch.show_exceptions = false config.action_controller.allow_forgery_protection = false config.action_mailer.perform_caching = false config.action_mailer.delivery_method = :test config.active_support.deprecation = :stderr end
mit
SCPR/kpcc_backroom_handshakes
ballot_box/utils_import.py
13058
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.utils.timezone import localtime from ballot_box.models import * from election_registrar.models import * from ballot_box.utils_data import Framer, Checker import logging import time import datetime import os.path import shutil import pytz logger = logging.getLogger("kpcc_backroom_handshakes") checker = Checker() class Saver(object): """ """ log_message = "\n*** My Import Messages ***\n" def make_office(self, office): """ """ log_message = "" try: obj, created = Office.objects.get_or_create( officeid=office["officeid"], defaults={ "name": office["officename"], "slug": office["officeslug"], "active": office["active"], "poss_error": False, } ) if created: log_message += "* CREATED OFFICE: %s \n" % (office["officeslug"]) else: log_message += "* %s exists\n" % (office["officeslug"]) except Exception, exception: error_output = "%s %s" % (exception, office["officeslug"]) logger.debug(error_output) raise return log_message def make_contest(self, office, contest): """ """ log_message = "" try: this_office = Office.objects.get(officeid=office["officeid"]) except Exception, exception: error_output = "%s %s" % (exception, office["officeid"]) logger.debug(error_output) raise try: obj, created = this_office.contest_set.update_or_create( election_id=contest["election_id"], resultsource_id=contest["resultsource_id"], contestid=contest["contestid"], defaults={ # don't overwrite admin edits # "contestname": contest["contestname"], # "contestdescription": contest["contestdescription"], # "seatnum": contest["seatnum"], "is_uncontested": contest["is_uncontested"], "is_national": contest["is_national"], "is_statewide": contest["is_statewide"], "is_ballot_measure": contest["is_ballot_measure"], "is_judicial": contest["is_judicial"], "reporttype": contest["reporttype"], "precinctstotal": contest["precinctstotal"], "precinctsreporting": contest["precinctsreporting"], "precinctsreportingpct": contest["precinctsreportingpct"], "votersregistered": contest["votersregistered"], "votersturnout": contest["votersturnout"], "poss_error": contest["poss_error"], } ) if created: log_message += "\t* CREATED CONTEST: %s\n" % (contest["contestid"]) else: log_message += "\t* %s exists but we updated figures\n" % (contest["contestid"]) except Exception, exception: error_output = "%s %s" % (exception, contest["contestid"]) logger.debug(error_output) raise return log_message def make_judicial(self, contest, judicial): """ """ log_message = "" try: this_contest = Contest.objects.get(contestid=contest["contestid"]) except Exception, exception: error_output = "%s %s" % (exception, contest["contestid"]) logger.debug(error_output) raise try: presave = this_contest.judicialcandidate_set.get(judgeid=judicial["judgeid"]) if presave.yespct: preyespct = "%0.1f" % (presave.yespct * 100) else: preyespct = None if presave.nopct: prenopct = "%0.1f" % (presave.nopct * 100) else: prenopct = None except Exception, exception: error_output = "ALERT: %s" % (exception) logger.debug(error_output) try: obj, created = this_contest.judicialcandidate_set.update_or_create( judgeid=judicial["judgeid"], defaults={ "ballotorder": judicial["ballotorder"], # don't overwrite admin edits # "firstname": judicial["firstname"], # "lastname": judicial["lastname"], # "fullname": judicial["fullname"], "yescount": judicial["yescount"], "yespct": judicial["yespct"] / 100, "nocount": judicial["nocount"], "nopct": judicial["nopct"] / 100, "poss_error": judicial["poss_error"], } ) if created: log_message += "\t\t* CREATED JUDGE: %s\n" % (judicial["judgeid"]) else: log_message += "\t\t* UPDATED %s: %s from %s%% to %s%%\n" % (this_contest.contestname, judicial["fullname"], prevotepct, judicial["votepct"]) except Exception, exception: error_output = "%s %s" % (exception, judicial["judgeid"]) logger.debug(error_output) raise return log_message def make_measure(self, contest, measure): """ """ log_message = "" try: this_contest = Contest.objects.get(contestid=contest["contestid"], election_id=contest["election_id"]) except Exception, exception: error_output = "%s %s" % (exception, contest["contestid"]) logger.debug(error_output) raise try: presave = this_contest.ballotmeasure_set.get(measureid=measure["measureid"]) if presave.yespct: preyespct = "%0.1f" % (presave.yespct * 100) else: preyespct = None if presave.nopct: prenopct = "%0.1f" % (presave.nopct * 100) else: prenopct = None except Exception, exception: error_output = "ALERT: %s" % (exception) logger.debug(error_output) try: obj, created = this_contest.ballotmeasure_set.update_or_create( measureid=measure["measureid"], defaults={ "ballotorder": measure["ballotorder"], # don't overwrite admin edits # "fullname": measure["fullname"], # "description": measure["description"], "yescount": measure["yescount"], "yespct": measure["yespct"] / 100, "nocount": measure["nocount"], "nopct": measure["nopct"] / 100, "poss_error": measure["poss_error"], } ) if created: log_message += "\t\t* CREATED MEASURE: %s\n" % (measure["measureid"]) else: log_message += "\t\t* UPDATED %s:\n\t\t\t* Yes from %s%% to %s%%.\n\t\t\t* No from %s%% to %s%%.\n" % (this_contest.contestname, preyespct, measure["yespct"], prenopct, measure["nopct"]) except Exception, exception: error_output = "%s %s" % (exception, measure["measureid"]) logger.debug(error_output) raise return log_message def make_candidate(self, contest, candidate): """ """ log_message = "" try: this_contest = Contest.objects.get(contestid=contest["contestid"]) except Exception, exception: error_output = "%s %s" % (exception, contest["contestid"]) logger.debug(error_output) raise try: presave = this_contest.candidate_set.get(candidateid=candidate["candidateid"]) if presave.votepct: prevotepct = "%0.1f" % (presave.votepct * 100) else: prevotepct = None if presave.party: candidate["party"] = presave.party else: pass if presave.incumbent: candidate["incumbent"] = presave.incumbent else: pass except Exception, exception: error_output = "ALERT: %s" % (exception) logger.debug(error_output) try: obj, created = this_contest.candidate_set.update_or_create( candidateid=candidate["candidateid"], defaults={ "ballotorder": candidate["ballotorder"], # don't overwrite admin edits # "firstname": candidate["firstname"], # "lastname": candidate["lastname"], # "fullname": candidate["fullname"], "party": candidate["party"], "incumbent": candidate["incumbent"], "votecount": candidate["votecount"], "votepct": candidate["votepct"] / 100, "poss_error": candidate["poss_error"], } ) if created: log_message += "\t\t* CREATED CANDIDATE: %s\n" % (candidate["candidateid"]) else: outputname = candidate["fullname"].decode("utf8") log_message += "\t\t* UPDATED %s: %s from %s%% to %s%%\n" % (this_contest.contestname, outputname, prevotepct, candidate["votepct"]) except Exception, exception: error_output = "%s %s" % (exception, candidate["candidateid"]) logger.debug(error_output) raise return log_message def _eval_timestamps(self, file_time, database_time): """ """ fttz = localtime(file_time).tzinfo dbtz = localtime(database_time).tzinfo if fttz == None and dbtz == None: raise Exception elif fttz == None: raise Exception elif dbtz == None: raise Exception else: if fttz._tzname == "PDT" or fttz._tzname == "PST": if file_time > database_time: return True else: return False else: raise Exception def _update_result_timestamps(self, src, file_timestamp): """ """ obj = ResultSource.objects.get(source_slug=src.source_slug) obj.source_latest = file_timestamp obj.save(update_fields=["source_latest"]) def _make_office_id(self, *args, **kwargs): """ """ framer = Framer() required_keys = [ "source_short", "officeslug", ] if len(args) != len(required_keys): raise Exception else: pass if kwargs: args = list(args) # this needs work but it's a start args.append(kwargs.values()[0].lower()) output = framer._concat(*args, delimiter="-") else: output = framer._concat(*args, delimiter="-") return output def _make_contest_id(self, *args, **kwargs): """ """ framer = Framer() required_keys = [ # "electionid", "source_short", "level", "officeslug", ] if len(args) != len(required_keys): raise Exception else: pass if kwargs: args = list(args) # this needs work but it's a start args.append(str(kwargs.values()[0]).lower()) output = framer._concat(*args, delimiter="-") else: output = framer._concat(*args, delimiter="-") return output def _make_this_id(self, contest_type, *args, **kwargs): """ """ framer = Framer() if contest_type == "measure": required_keys = [ "contestid", "measure_id", ] elif contest_type == "judicial": required_keys = [ "contestid", "judicialslug", ] elif contest_type == "candidate": required_keys = [ "contestid", "candidateslug", ] if len(args) != len(required_keys): raise Exception else: pass if kwargs: args = list(args) # this needs work but it's a start args.append(str(kwargs.values()[0]).lower()) output = framer._concat(*args, delimiter="-") else: output = framer._concat(*args, delimiter="-") return output
mit
r5w/drunken-archer
js/svg-test.js
5658
/*jslint browser: true */ /*global $, jQuery,Snap, console, mina, alert */ // First lets create our drawing surface out of existing SVG element // If you want to create new surface just provide dimensions // like s = Snap(800, 600); function init(w, h) { "use strict"; var s = Snap.select("#svg"), printmessage = function (string) { console.log(string); }, howWide = w, howHigh = h, bg = s.rect(0, 0, howWide, howHigh), cursor, cursorg, i, /* colours = [ "#111111", //blue "#556270", //rose "#4ECDC4", //bronze "#C7F464", //pale grey "#FF6B6B", //dark grey "#C44D58", //black "#EB6841" //cream ], */ colours = [ //"#758b98", // sky blue "#6a8798", //blue "#9c2b27", //rose "#4c3d2a", //bronze "#a1a29d", //pewter "#393937", //charcoal "#1c1c1a", //black "#dcceab" //cream ], numberOfSides = colours.length, size = howWide / 13.333, Xcentre = float2int( (bg.getBBox().width) / 2 ), Ycentre = float2int( (bg.getBBox().height) / 2 ), bigCircle, dotgroup, newpointX, newpointY, newPointArr, papergroup; //bg = s.rect(0, 0, 400, 400); bg.attr({fill: '#fff'}); /* bigCircle.drag(); var mediumCircle = s.circle(100,150,75); mediumCircle.attr({ fill: 'yellow', stroke: 'brown', strokeWidth: 4 }); var message = "HELLO WORLD!" var t1 = s.text(50,50,"CHEESE!!!"); t1.attr({text: message}); t1.attr({textpath: "M10,10L100,100"}); var g = s.group(mediumCircle,bigCircle); Snap.animate(0,200, function(val){ bigCircle.attr({radius:val}); }, 10000); //mediumCircle.drag(); */ console.log(Xcentre); bigCircle = s.circle(Xcentre, Ycentre, (size * 4.5)); cursor = s.circle(Xcentre + size * 5, Ycentre, size); bigCircle.attr({ fill: '#fff', stroke: '#eee', strokeWidth: 2 }); cursor.attr({ fill: '#0f0', stroke: '#333', strokeWidth: 20 }); //cursor.attr({cx:180,cy:180}); bigCircle.click(function () { printmessage(this.node.r.baseVal.value); }); cursorg = s.g( bigCircle, cursor); dotgroup = []; newPointArr = []; papergroup = s.g(); function float2int (value) { return value | 0; } function setCursorPoint(x,y) { //currentx = cursorg.cx; //currenty = cursorg.cy; //cursor.attr({cx:x,cy:y}); //cursorg.attr({cx:x,cy:y}); //cursorg.animate({transform: 'r360, x, y'}, 500, mina.easeinout); chosen(180); } function chosen(a) { console.log("chosenangle is" + a); //a = (a + numberOfSides) % 360; //a = (a + 1080) % 360; //angle = a; var to = "r" + [a, Xcentre, Ycentre]; cursorg.animate({ transform: to }, 500, mina.easeinout); cursorg.attr({'rx':a}); } function dotclickhandle(e, thing) { //var angle = e * 2 * Math.PI ; var currentangle,angle; currentangle = cursorg.attr("rx"); console.log("currnangle::"+currentangle); angle = e * ( 360 / numberOfSides); // if (angle>180) { // angle = 360-angle; // } return function (thing) { console.log("currnangle::"+currentangle); //var data = e.data; //alert(e.data); console.log("angle::"+angle); console.log(thing.target.cx.baseVal.value); console.log(e + "x:" + dotgroup[e].thisx + "y:" + dotgroup[e].thisy); //console.log("cursor"+c); //setCursorPoint(dotgroup[e].thisx,dotgroup[e].thisy); chosen(angle); // var thisx = elem.target.cx.baseVal.value; // var thisy = elem.target.cy.baseVal.value; // var thisid = this.id; // printmessage("x: " + thisx + " y: " + thisy + " ID: " + thisid); }; } function distanceAround(numberOfSidesval,Xcentreval,Ycentreval,diameter,degree) { var result,magicvalue; result = []; magicvalue = 3; //x = Xcentreval ; //console.log("x:"+x); //x = Xcentreval + (diameter/2) ; //x = Xcentreval + diameter * magicvalue; //y = Ycentreval ; //console.log("y:"+y); //y = Ycentreval + (diameter/2) ; //y = Ycentreval + diameter * magicvalue; //result.x = Math.cos(degree * 2 * Math.PI / numberOfSidesval) * Xcentreval * 3 ; //result.y = Math.sin(degree * 2 * Math.PI / numberOfSidesval) * Ycentreval * 3 ; result.x = Xcentreval + diameter * magicvalue * Math.cos(degree * 2 * Math.PI / numberOfSidesval); result.y = Ycentreval + diameter * magicvalue * Math.sin(degree * 2 * Math.PI / numberOfSidesval); console.log(result); return result; } for (i = 0; i <= numberOfSides - 1; i += 1) { dotgroup.push(i); //newpointX = Xcentre + size * 3 * Math.cos(i * 2 * Math.PI / numberOfSides); //newpointY = Ycentre + size * 3 * Math.sin(i * 2 * Math.PI / numberOfSides); //console.log(Xcentre); //console.log(Ycentre); newPointArr = distanceAround(numberOfSides,Xcentre,Ycentre,size,i); newpointX = newPointArr.x; //console.log(newPointArr); newpointY = newPointArr.y; dotgroup[i] = s.circle(newpointX, newpointY, size); dotgroup[i].id = i; dotgroup[i].attr({ fill: colours[i]}); dotgroup[i].thisx =newpointX dotgroup[i].thisy =newpointY /* dotgroup[i].click(function(elem){ //var this = dotgroup[i]; //console.log(elem); //var thisx = elem.target.cx.baseVal.value; //var thisy = elem.target.cy.baseVal.value; //var thisid = this.id; //printmessage("x: " + thisx + " y: " + thisy + " ID: " + thisid); }) */ dotgroup[i].click(dotclickhandle(dotgroup[i].id,cursor)); papergroup.add(dotgroup[i]); //console.log(dotgroup[i]); } //papergroup.animate({transform: 'r360, Xcentre, Ycentre'}, 2000, mina.easeinout); //papergroup.drag(); } //window.onload = init; jQuery(document).ready(function ($) { "use strict"; var svgsize = $('#svg').width(); //console.log(svgsize); init(svgsize, svgsize); });
mit
cacampbell/Sympal
setup.py
807
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) setup( name='Sympal', packages=['Sympal'], version='0.5', description='Basic end user Sympa listserv management with Python requests', url='https://github.com/cacampbell/Sympal', download_url='https://github.com/cacampbell/Sympal/tarball/0.5', author='Chris Campbell', author_email='cacampbell@ucdavis.edu', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='sympa listserv requests', install_requires=['DateTime', 'lxml', 'requests'], )
mit
danurwenda/xeroxampah
application/views/admin/chart/config_step.php
8273
<div class="step-pane" data-step="3"> <div class="row"> <h3 class="row header smaller lighter blue"> <span class="col-xs-6"> Header </span><!-- /.col --> </h3> <div> <form class="form-horizontal" id="config-form"> <div class="form-group"> <label for="header_target" class="col-xs-12 col-sm-3 col-md-3 control-label no-padding-right">Title links to</label> <div class="col-xs-12 col-sm-5"> <span class="block input-icon input-icon-right"> <select class="form-control" id="header_target" name="header_target"> <option value="0" class="nolink"></option> </select> </span> </div> </div> <div class="form-group"> <label for="header_text" class="col-xs-12 col-sm-3 col-md-3 control-label no-padding-right">Title text</label> <div class="col-xs-12 col-sm-5"> <span class="block input-icon input-icon-right"> <input type="text" id="header_text" name="header_text" class="width-100" /> </span> </div> </div> <div class="form-group"> <label for="sub_text" class="col-xs-12 col-sm-3 col-md-3 control-label no-padding-right">Subtitle text</label> <div class="col-xs-12 col-sm-5"> <span class="block input-icon input-icon-right"> <input type="text" id="sub_text" name="sub_text" class="width-100" /> </span> </div> </div> </form> </div> </div> <div class="row"> <div class="col-sm-6"> <h3 class="row header smaller lighter blue"> <span class="col-xs-6"> Indicators </span><!-- /.col --> </h3> <div> <table id="indicator-table" class="table table-bordered table-hover"> <thead> <tr> <th>Nama</th> <th>Satuan</th> <th>Frekuensi</th> <th>Nilai akhir</th> <th> <i class="ace-icon fa fa-clock-o bigger-110 hidden-480"></i> Tanggal terakhir </th> </tr> </thead> <tbody> </tbody> </table> </div> </div><!-- /.col --> <div class="col-sm-6"> <h3 class="row header smaller lighter blue"> <span class="col-xs-6"> Drop here </span><!-- /.col --> </h3> <div id="cart" class="well well-sm"> <ol> <li class="placeholder">Add your items here</li> </ol> </div> </div> </div> </div> <?php echo js_asset('jquery.dataTables.js', 'ace'); echo js_asset('jquery.dataTables.bootstrap.js', 'ace'); ?> <script> $(function () { var $wizard = $('#fuelux-wizard-container') .on('actionclicked.fu.wizard', function (e, info) { if (info.step == 3) { if ($('#selection-form').valid()) { //submit form using ajax //put return data (array of array) to a global variable //after done, jump to next step $.ajax({ type: "POST", url: 'upload/get_sheet_data', data: $('#selection-form').serialize(), dataType: 'json', success: function (data) { //return value berupa array of [row,col,val] preview_data = data; //jump var wizard = $wizard.data('fu.wizard'); //move to step 4 wizard.currentStep = 4; wizard.setState(); //create dummy form $dummy_form = $('<form/>', { action: "upload/submit", method: "POST" }); //add serialized data from #selection-form $.each($('#selection-form').serializeArray(), function (a, b) { $dummy_form.append('<input type="hidden" name="' + b.name + '" value="' + b.value + '">'); }); } }); } e.preventDefault(); } }) .on('changed.fu.wizard', function () { if ($(this).data('fu.wizard').selectedItem().step === 3) { //initiate dataTable after all data is populated (from the 1st step of wizard) //and after this step is loaded if (!$.fn.dataTable.isDataTable('#indicator-table')) { $('#indicator-table').dataTable({ paging: false, scrollCollapse: true, scrollY: '200px', aaSorting: []//disable initial sorting }); } else { $('#indicator-table').DataTable().draw(); } //make it draggable $("#indicator-table tbody tr").draggable({ appendTo: "body", cursorAt: {left: 5, top: 20}, helper: "clone", start: function (e, ui) { var name = $(this).find('.in-name').text(); $(ui.helper).data('iid', $(this).data('iid')).html(name) } }); } }); $("#cart ol").droppable({ activeClass: "ui-state-default", hoverClass: "ui-state-hover", accept: ":not(.ui-sortable-helper)", drop: function (event, ui) { var $ol = $(this); $ol.find(".placeholder").remove(); var $li = $("<li/>", { class: 'action-buttons' }); var $delButton = $('<a/>', { class: 'pull-right red' }).click(function () { //remove $li from ol $li.remove(); //check apakah list kosong, jika ya kasih placeholder if ($ol.children('li').length < 1) $('<li class="placeholder">Add your items here</li>').appendTo($ol); }).append($('<i/>', { class: 'ace-icon fa fa-trash-o bigger-130' })); $li .data('iid', ui.helper.data('iid')) .append(ui.helper.text(), $delButton) .appendTo($ol); } }).sortable({ items: "li:not(.placeholder)", sort: function () { // gets added unintentionally by droppable interacting with sortable // using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options $(this).removeClass("ui-state-default"); } }); }); </script>
mit
pingzing/Philosopher
Philosopher.Multiplat/Philosopher.Multiplat/Services/IDataService.cs
775
using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; using Philosopher.Multiplat.Models; namespace Philosopher.Multiplat.Services { public interface IDataService : INotifyPropertyChanged { IDataService Create(); IDataService Create(string hostname, uint portNumber); string BaseUrl { get; set; } uint PortNumber { get; set; } void ChangeHostName(string hostname, uint portNumber = 3000); void Login(string user, string pass); Task<ResultOrErrorResponse<List<ServerScript>>> GetScripts(CancellationToken token); Task<string> CallServerScript(ServerScript script, CancellationToken token); } }
mit
iauns/spire-scirun
spire_scirun/SRInterface.cpp
6261
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2013 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// \author James Hughes /// \date February 2013 #include "SRInterface.h" #include "namespaces.h" #include "src/SciBall.h" #include "src/SRCamera.h" #include "spire/src/Hub.h" #include "spire/src/InterfaceImplementation.h" using namespace std::placeholders; namespace CPM_SPIRE_SCIRUN_NS { //------------------------------------------------------------------------------ SRInterface::SRInterface(std::shared_ptr<spire::Context> context, const std::vector<std::string>& shaderDirs, bool createThread, LogFunction logFP) : spire::Interface(context, shaderDirs, createThread, logFP), mCamDistance(7.0f), mScreenWidth(640), mScreenHeight(480), mCamAccumPosDown(0.0f, 0.0f, 0.0f), mCamAccumPosNow(0.0f, 0.0f, 0.0f), mCamera(new SRCamera(*this)), // Should come after all vars have been initialized. mSciBall(new SciBall(spire::V3(0.0f, 0.0f, 0.0f), 1.0f)) // Should come after all vars have been initialized. { buildAndApplyCameraTransform(); } //------------------------------------------------------------------------------ SRInterface::~SRInterface() { } //------------------------------------------------------------------------------ void SRInterface::eventResize(size_t width, size_t height) { mScreenWidth = width; mScreenHeight = height; // Ensure glViewport is called appropriately. spire::Hub::RemoteFunction resizeFun = std::bind(spire::InterfaceImplementation::resize, _1, width, height); mHub->addFunctionToThreadQueue(resizeFun); } //------------------------------------------------------------------------------ spire::V2 SRInterface::calculateScreenSpaceCoords(const glm::ivec2& mousePos) { float windowOriginX = 0.0f; float windowOriginY = 0.0f; // Transform incoming mouse coordinates into screen space. spire::V2 mouseScreenSpace; mouseScreenSpace.x = 2.0f * (static_cast<float>(mousePos.x) - windowOriginX) / static_cast<float>(mScreenWidth) - 1.0f; mouseScreenSpace.y = 2.0f * (static_cast<float>(mousePos.y) - windowOriginY) / static_cast<float>(mScreenHeight) - 1.0f; // Rotation with flipped axes feels much more natural. mouseScreenSpace.y = -mouseScreenSpace.y; return mouseScreenSpace; } //------------------------------------------------------------------------------ void SRInterface::inputMouseDown(const glm::ivec2& pos, MouseButton btn) { // Translation variables. mCamAccumPosDown = mCamAccumPosNow; mTransClick = calculateScreenSpaceCoords(pos); if (btn == MOUSE_LEFT) { spire::V2 mouseScreenSpace = calculateScreenSpaceCoords(pos); mSciBall->beginDrag(mouseScreenSpace); } else if (btn == MOUSE_RIGHT) { // Store translation starting position. } mActiveDrag = btn; } //------------------------------------------------------------------------------ void SRInterface::inputMouseMove(const glm::ivec2& pos, MouseButton btn) { if (mActiveDrag == btn) { if (btn == MOUSE_LEFT) { spire::V2 mouseScreenSpace = calculateScreenSpaceCoords(pos); mSciBall->drag(mouseScreenSpace); buildAndApplyCameraTransform(); } else if (btn == MOUSE_RIGHT) { spire::V2 curTrans = calculateScreenSpaceCoords(pos); spire::V2 delta = curTrans - mTransClick; /// \todo This 2.5f value is a magic number, and it's real value should /// be calculated based off of the world space position of the /// camera. This value could easily be calculated based off of /// mCamDistance. spire::V2 trans = (-delta) * 2.5f; spire::M44 camRot = mSciBall->getTransformation(); spire::V3 translation = static_cast<spire::V3>(camRot[0].xyz()) * trans.x + static_cast<spire::V3>(camRot[1].xyz()) * trans.y; mCamAccumPosNow = mCamAccumPosDown + translation; buildAndApplyCameraTransform(); } } } //------------------------------------------------------------------------------ void SRInterface::inputMouseWheel(int32_t delta) { // Reason why we subtract: Feels more natural to me =/. mCamDistance -= static_cast<float>(delta) / 100.0f; buildAndApplyCameraTransform(); } //------------------------------------------------------------------------------ void SRInterface::inputMouseUp(const glm::ivec2& /*pos*/, MouseButton /*btn*/) { } //------------------------------------------------------------------------------ void SRInterface::buildAndApplyCameraTransform() { spire::M44 camRot = mSciBall->getTransformation(); spire::M44 finalTrafo = camRot; // Translation is a post rotation operation where as zoom is a pre transform // operation. We should probably ensure the user doesn't scroll passed zero. // Remember, we are looking down NEGATIVE z. finalTrafo[3].xyz() = mCamAccumPosNow + static_cast<spire::V3>(camRot[2].xyz()) * mCamDistance; mCamera->setViewTransform(finalTrafo); } } // namespace CPM_SPIRE_SCIRUN_NS
mit
rachwal/DesignPatterns
structural/src/bridge/application_window.cc
764
// Based on "Design Patterns: Elements of Reusable Object-Oriented Software" // book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm // // Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. #include "application_window.h" namespace structural { namespace bridge { ApplicationWindow::ApplicationWindow(const std::string& application_title, WindowImp* imp) : Window(imp), application_title_(application_title) { } void ApplicationWindow::DrawText(const std::string& text, const commons::Point<float>& point) { auto imp = GetWindowImp(); imp->DeviceText(text, point.x(), point.y()); } void ApplicationWindow::DrawTitle() { DrawText(application_title_, commons::Point<float>(0, 0)); } } }
mit
amaozhao/basecms
cmsplugin_carousel/migrations/0001_initial.py
2338
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations import filer.fields.image class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cms', '0004_auto_20140924_1038'), ('filer', '0001_initial'), ] operations = [ migrations.CreateModel( name='Carousel', fields=[ ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')), ('domid', models.CharField(max_length=50, verbose_name='Name')), ('interval', models.IntegerField(default=5000, help_text=b'The amount of time in milliseconds to delay cycling items. If zero carousel will not automatically cycle.')), ('show_title', models.BooleanField(default=True, help_text=b'Display image titles, if true.')), ('show_caption', models.BooleanField(default=True, help_text=b'Display image captions, if true.')), ('width', models.PositiveIntegerField(default=0, help_text=b'Fixed width in pixels for carousel images.', verbose_name='\u5bbd')), ('height', models.PositiveIntegerField(default=0, help_text=b'Fixed height in pixels for carousel images.', verbose_name='height')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), migrations.CreateModel( name='CarouselItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('caption_title', models.CharField(max_length=100, null=True, blank=True)), ('caption_content', models.TextField(null=True, blank=True)), ('url', models.CharField(default=None, max_length=256, blank=True)), ('carousel', models.ForeignKey(to='cmsplugin_carousel.Carousel')), ('image', filer.fields.image.FilerImageField(blank=True, to='filer.Image', null=True)), ], options={ }, bases=(models.Model,), ), ]
mit
DoctorMcKay/node-steam-user
enums/EGameSearchAction.js
220
/** * @enum EGameSearchAction */ module.exports = { "None": 0, "Accept": 1, "Decline": 2, "Cancel": 3, // Value-to-name mapping for convenience "0": "None", "1": "Accept", "2": "Decline", "3": "Cancel", };
mit
ThunderKey/gemsurance-as-a-service
db/migrate/20170223114856_create_gem_usages.rb
322
# frozen_string_literal: true class CreateGemUsages < ActiveRecord::Migration[5.0] def change create_table :gem_usages do |t| t.references :gem_version, foreign_key: true, index: true, null: false t.references :resource, foreign_key: true, index: true, null: false t.timestamps end end end
mit
francesconistri/p2ptv-pi
pistream/node_modules/jspm/node_modules/systemjs-builder/lib/trace.js
28914
var getCanonicalName = require('./utils').getCanonicalName; var glob = require('glob'); var toFileURL = require('./utils').toFileURL; var fromFileURL = require('./utils').fromFileURL; var asp = require('bluebird').promisify; var fs = require('fs'); var path = require('path'); var extend = require('./utils').extend; var Promise = require('bluebird'); var getPackage = require('./utils').getPackage; var getPackageConfigPath = require('./utils').getPackageConfigPath; module.exports = Trace; function Trace(loader, traceCache) { // when creating a new trace, we by default invalidate the freshness of the trace cache Object.keys(traceCache).forEach(function(canonical) { var load = traceCache[canonical]; if (load && !load.conditional) load.fresh = false; }); this.loader = loader; // stored traced load records this.loads = traceCache || {}; // in progress traces this.tracing = {}; } /* * High-level functions */ var namedRegisterRegEx = /(System\.register(Dynamic)?|define)\(('[^']+'|"[^"]+")/g; Trace.prototype.traceModule = function(moduleName, traceOpts) { var loader = this.loader; return Promise.resolve(loader.normalize(moduleName)) .then(function(normalized) { return traceCanonical(getCanonicalName(loader, normalized), traceOpts); }); }; Trace.prototype.traceCanonical = function(canonical, traceOpts) { var self = this; return toCanonicalConditionalEnv.call(self, traceOpts.conditions) .then(function(canonicalConditionalEnv) { if (!traceOpts.traceConditionsOnly) return self.getAllLoadRecords(canonical, traceOpts.excludeURLs, traceOpts.tracePackageConfig, traceOpts.traceAllConditionals, canonicalConditionalEnv, {}, []); else return self.getConditionLoadRecords(canonical, traceOpts.excludeURLs, traceOpts.tracePackageConfig, canonicalConditionalEnv, false, {}, []); }) .then(function(loads) { // if it is a bundle, we just use a regex to extract the list of loads // as "true" records for subtraction arithmetic use only var thisLoad = loads[canonical]; if (thisLoad && !thisLoad.conditional && thisLoad.metadata.bundle) { namedRegisterRegEx.lastIndex = 0; var curMatch; while ((curMatch = namedRegisterRegEx.exec(thisLoad.source))) loads[curMatch[3].substr(1, curMatch[3].length - 2)] = true; } return { moduleName: canonical, tree: loads }; }); } function isLoadFresh(load, loader, loads) { if (load === undefined) return false; if (load === false) return true; if (load.configHash != loader.configHash) return false; if (load.fresh) return true; if (load.conditional) return false; // stat to check freshness if (load.plugin) { var plugin = loads[load.plugin]; if (!isLoadFresh(plugin, loader, loads)) return false; } try { var timestamp = fs.statSync(path.resolve(fromFileURL(loader.baseURL), load.path)).mtime.getTime(); } catch(e) {} return load.fresh = timestamp == load.timestamp; } /* * Low-level functions */ // runs the pipeline hooks, returning the load record for a module Trace.prototype.getLoadRecord = function(canonical, excludeURLs, parentStack) { var loader = this.loader; var loads = this.loads; if (isLoadFresh(loads[canonical], loader, loads)) return Promise.resolve(loads[canonical]); if (this.tracing[canonical]) return this.tracing[canonical]; var self = this; var isPackageConditional = canonical.indexOf('/#:') != -1; return this.tracing[canonical] = Promise.resolve(loader.decanonicalize(canonical)) .then(function(normalized) { // modules already set in the registry are system modules if (loader.has(normalized)) return false; // package conditional fallback normalization if (!isPackageConditional) normalized = normalized.replace('/#:', '/'); // -- conditional load record creation: sourceless intermediate load record -- // boolean conditional var booleanIndex = canonical.lastIndexOf('#?'); if (booleanIndex != -1) { var condition = canonical.substr(booleanIndex + 2) if (condition.indexOf('|') == -1) condition += '|default'; return { name: canonical, fresh: true, conditional: { condition: condition, branch: canonical.substr(0, booleanIndex) } }; } // package environment conditional // NB handle subpaths as tracked in https://github.com/systemjs/builder/issues/440 var pkgEnvIndex = canonical.indexOf('/#:'); if (pkgEnvIndex != -1) { // NB handle a package plugin load here too if (canonical.indexOf('!') != -1) throw new Error('Unable to trace ' + canonical + ' - building package environment mappings of plugins is not currently supported.'); var pkgName = canonical.substr(0, pkgEnvIndex); var subPath = canonical.substr(pkgEnvIndex + 3); var normalizedPkgName = loader.decanonicalize(pkgName); var pkg = loader.packages[normalizedPkgName]; // record package config paths var loadPackageConfig; var packageConfigPath = getPackageConfigPath(loader.packageConfigPaths, normalizedPkgName); if (packageConfigPath) { loadPackageConfig = getCanonicalName(loader, packageConfigPath); (loader.meta[packageConfigPath] = loader.meta[packageConfigPath] || {}).format = 'json'; } // effective analog of the same function in SystemJS packages.js // to work out the path with defaultExtension added. // we cheat here and use normalizeSync to apply the right checks, while // skipping any map entry by temporarily removing it. function toPackagePath(subPath) { var pkgMap = pkg.map; pkg.map = {}; // NB remove use of normalizeSync var normalized = loader.normalizeSync(pkgName + '/' + subPath); pkg.map = pkgMap; return normalized; } var envMap = pkg.map[subPath]; var metadata = {}; var fallback; // resolve the fallback return Promise.resolve() .then(function() { return loader.locate({ name: toPackagePath(subPath), metadata: metadata }) }) .then(function(address) { // allow build: false trace opt-out if (metadata.build === false) return false; fallback = getCanonicalName(loader, address); // check if the fallback exists return new Promise(function(resolve) { fs.exists(fromFileURL(address), resolve); }) .then(function(fallbackExists) { if (!fallbackExists) fallback = null; }); }) .then(function() { // environment trace return loader.normalize(pkg.map['@env'] || '@system-env') .then(function(normalizedCondition) { var conditionModule = getCanonicalName(loader, normalizedCondition); return Promise.all(Object.keys(envMap).map(function(envCondition) { var mapping = envMap[envCondition]; var negate = envCondition[0] == '~'; return Promise.resolve() .then(function() { if (mapping == '.') return loader.normalize(pkgName); else if (mapping.substr(0, 2) == './') return toPackagePath(mapping.substr(2)) else return loader.normalize(mapping, normalizedPkgName); }) .then(function(normalizedMapping) { return { condition: (negate ? '~' : '') + conditionModule + '|' + (negate ? envCondition.substr(1) : envCondition), branch: getCanonicalName(loader, normalizedMapping) }; }); })); }) .then(function(envs) { return { name: canonical, fresh: true, packageConfig: loadPackageConfig, conditional: { envs: envs, fallback: fallback } }; }); }); } // conditional interpolation var interpolationRegEx = /#\{[^\}]+\}/; var interpolationMatch = canonical.match(interpolationRegEx); if (interpolationMatch) { var condition = interpolationMatch[0].substr(2, interpolationMatch[0].length - 3); if (condition.indexOf('|') == -1) condition += '|default'; var metadata = {}; return Promise.resolve(loader.locate({ name: normalized.replace(interpolationRegEx, '*'), metadata: metadata })) .then(function(address) { if (address.substr(0, 8) != 'file:///') metadata.build = false; // allow build: false trace opt-out if (metadata.build === false) return false; // glob the conditional interpolation variations from the filesystem var globIndex = address.indexOf('*'); return asp(glob)(fromFileURL(address), { dot: true, nobrace: true, noglobstar: true, noext: true, nodir: true }) .then(function(paths) { var branches = {}; paths.forEach(function(path) { path = toFileURL(path); var pathCanonical = getCanonicalName(loader, path); var interpolate = pathCanonical.substr(interpolationMatch.index, path.length - address.length + 1); if (metadata.loader) { if (loader.pluginFirst) pathCanonical = getCanonicalName(loader, metadata.loader) + '!' + pathCanonical; else pathCanonical = pathCanonical + '!' + getCanonicalName(loader, metadata.loader); } branches[interpolate] = pathCanonical; }); return { name: canonical, fresh: false, // we never cache conditional interpolates and always reglob conditional: { condition: condition, branches: branches } }; }); }); } // -- trace loader hooks -- var load = { name: canonical, // baseURL-relative path to address path: null, metadata: {}, deps: [], depMap: {}, source: null, // this is falsified by builder.reset to indicate we should restat fresh: true, // timestamp from statting the underlying file source at path timestamp: null, // each load stores a hash of the configuration from the time of trace // configHash is set by the loader.config function of the builder configHash: loader.configHash, plugin: null, runtimePlugin: false, // plugins via syntax must build in the plugin package config pluginConfig: null, // packages have a config file that must be built in for bundles packageConfig: null, // these are only populated by the separate builder.getDeferredImports(tree) method deferredImports: null }; var curHook = 'locate'; var originalSource; return Promise.resolve(loader.locate({ name: normalized, metadata: load.metadata})) .then(function(address) { curHook = ''; if (address.substr(0, 8) != 'file:///') load.metadata.build = false; // build: false build config - null load record if (load.metadata.build === false) return false; if (address.substr(0, 8) == 'file:///') load.path = path.relative(fromFileURL(loader.baseURL), fromFileURL(address)); return Promise.resolve() .then(function() { // set load.plugin to canonical plugin name if a plugin load if (load.metadata.loaderModule) return Promise.resolve(loader.normalize(load.metadata.loader, normalized)) .then(function(pluginNormalized) { load.plugin = getCanonicalName(loader, pluginNormalized); if (pluginNormalized.indexOf('!') == -1 && load.metadata.loaderModule.build !== false && getPackage(loader.packages, pluginNormalized)) { var packageConfigPath = getPackageConfigPath(loader.packageConfigPaths, pluginNormalized); if (packageConfigPath) { load.pluginConfig = getCanonicalName(loader, packageConfigPath); (loader.meta[packageConfigPath] = loader.meta[packageConfigPath] || {}).format = 'json'; } } }); }) .then(function() { if (load.metadata.loaderModule && load.metadata.loaderModule.build === false) { load.runtimePlugin = true; return load; } curHook = 'fetch'; return loader.fetch({ name: normalized, metadata: load.metadata, address: address }) .then(function(source) { if (typeof source != 'string') throw new TypeError('Loader fetch hook did not return a source string'); originalSource = source; curHook = 'translate'; // default loader fetch hook will set load.metadata.timestamp if (load.metadata.timestamp) { load.timestamp = load.metadata.timestamp; load.metadata.timestamp = undefined; } return loader.translate({ name: normalized, metadata: load.metadata, address: address, source: source }); }) .then(function(source) { load.source = source; curHook = 'instantiate'; if (load.metadata.format == 'esm' && !load.metadata.originalSource) { var esmCompiler = require('../compilers/esm.js'); load.metadata.parseTree = esmCompiler.parse(source); return Promise.resolve({ deps: esmCompiler.getDeps(load.metadata.parseTree) }); } return loader.instantiate({ name: normalized, metadata: load.metadata, address: address, source: source }); }) .then(function(result) { curHook = ''; if (!result) throw new TypeError('Native ES Module builds not supported. Ensure transpilation is included in the loader pipeline.'); load.deps = result.deps; // legacy es module transpilation translates to get the dependencies, so we need to revert for re-compilation if (load.metadata.format == 'esm' && load.metadata.originalSource) load.source = originalSource; // record package config paths if (getPackage(loader.packages, normalized)) { var packageConfigPath = getPackageConfigPath(loader.packageConfigPaths, normalized); if (packageConfigPath) { load.packageConfig = getCanonicalName(loader, packageConfigPath); (loader.meta[packageConfigPath] = loader.meta[packageConfigPath] || {}).format = 'json'; } } // sanitize source map var sourceMap = load.metadata.sourceMap; if (sourceMap) { if (typeof sourceMap == 'string') sourceMap = load.metadata.sourceMap = JSON.parse(sourceMap); var originalName = load.name.split('!')[0]; // force set the filename of the original file sourceMap.file = originalName + '!transpiled'; // force set the sources list if only one source if (!sourceMap.sources || sourceMap.sources.length <= 1) sourceMap.sources = [originalName]; } // normalize dependencies to populate depMap return Promise.all(result.deps.map(function(dep) { return loader.normalize(dep, normalized, address) .then(function(normalized) { try { load.depMap[dep] = getCanonicalName(loader, normalized); } catch(e) { if (!excludeURLs || normalized.substr(0, 7) == 'file://') throw e; (loader.meta[normalized] = loader.meta[normalized] || {}).build = false; load.depMap[dep] = normalized; } }); })); }); }) .catch(function(err) { var msg = (curHook ? ('Error on ' + curHook + ' for ') : 'Error tracing ') + canonical + ' at ' + normalized; if (parentStack) parentStack.reverse().forEach(function(parent) { msg += '\n\tLoading ' + parent; }); // rethrow loader hook errors with the hook information if (err instanceof Error) err.message = msg + '\n\t' + err.message; else err = msg + '\n\t' + err; throw err; }) .then(function() { // remove unnecessary metadata for trace load.metadata.entry = undefined; load.metadata.builderExecute = undefined; load.metadata.parseTree = undefined; return load; }); }); }) .then(function(load) { self.tracing[canonical] = undefined; return loads[canonical] = load; }).catch(function(err) { self.tracing[canonical] = undefined; throw err; }); }; /* * Returns the full trace tree of a module * * - traceAllConditionals indicates if conditional boundaries should be traversed during the trace. * - conditionalEnv represents the conditional tracing environment module values to impose on the trace * forcing traces for traceAllConditionals false, and skipping traces for traceAllConditionals true. * * conditionalEnv provides canonical condition tracing rules of the form: * * { * 'some/interpolation|value': true, // include ALL variations * 'another/interpolation|value': false, // include NONE * 'custom/interpolation|value': ['specific', 'values'] * * // default BOOLEAN entry:: * '@system-env|browser': false, * '~@system-env|browser': false * * // custom boolean entry * // boolean only checks weak truthiness to allow overlaps * '~@system-env|node': true * } * */ var systemModules = ['@empty', '@system-env', '@@amd-helpers', '@@global-helpers']; Trace.prototype.getAllLoadRecords = function(canonical, excludeURLs, tracePackageConfig, traceAllConditionals, canonicalConditionalEnv, curLoads, parentStack) { var loader = this.loader; curLoads = curLoads || {}; if (canonical in curLoads) return curLoads; var self = this; return this.getLoadRecord(canonical, excludeURLs, parentStack) .then(function(load) { // conditionals, build: false and system modules are falsy loads in the trace trees // (that is, part of depcache, but not built) // we skip system modules though if (systemModules.indexOf(canonical) == -1) curLoads[canonical] = load; if (load) { parentStack = parentStack.concat([canonical]); return Promise.all(Trace.getLoadDependencies(load, tracePackageConfig, true, traceAllConditionals, canonicalConditionalEnv).map(function(dep) { return self.getAllLoadRecords(dep, excludeURLs, tracePackageConfig, traceAllConditionals, canonicalConditionalEnv, curLoads, parentStack); })); } }) .then(function() { return curLoads; }); }; // helper function -> returns the "condition" build of a tree // that is the modules needed to determine the exact conditional solution of the tree Trace.prototype.getConditionLoadRecords = function(canonical, excludeURLs, tracePackageConfig, canonicalConditionalEnv, inConditionTree, curLoads, parentStack) { var loader = this.loader; if (canonical in curLoads) return curLoads; var self = this; return this.getLoadRecord(canonical, excludeURLs, parentStack) .then(function(load) { if (inConditionTree && systemModules.indexOf(canonical) == -1) curLoads[canonical] = load; if (load) { parentStack = parentStack.concat([canonical]) // trace into the conditions themselves return Promise.all(Trace.getLoadDependencies(load, tracePackageConfig, true, true, canonicalConditionalEnv, true).map(function(dep) { return self.getConditionLoadRecords(dep, excludeURLs, tracePackageConfig, canonicalConditionalEnv, true, curLoads, parentStack); })) .then(function() { // trace non-conditions return Promise.all(Trace.getLoadDependencies(load, tracePackageConfig, true, true, canonicalConditionalEnv).map(function(dep) { return self.getConditionLoadRecords(dep, excludeURLs, tracePackageConfig, canonicalConditionalEnv, inConditionTree, curLoads, parentStack); })); }); } }) .then(function() { return curLoads; }); } function conditionalComplement(condition) { var negative = condition[0] == '~'; return (negative ? '' : '~') + condition.substr(negative); } function toCanonicalConditionalEnv(conditionalEnv) { var loader = this.loader; var canonicalConditionalEnv = {}; return Promise.all(Object.keys(conditionalEnv).map(function(m) { var negate = m[0] == '~'; var exportIndex = m.lastIndexOf('|'); var moduleName = m.substring(negate, exportIndex != -1 ? exportIndex : m.length); return loader.normalize(moduleName) .then(function(normalized) { var canonicalCondition = (negate ? '~' : '') + getCanonicalName(loader, normalized) + (exportIndex != -1 ? m.substr(exportIndex) : '|default'); canonicalConditionalEnv[canonicalCondition] = conditionalEnv[m]; }); })) .then(function() { return canonicalConditionalEnv; }); } /* * to support static conditional builds, we use the conditional tracing options * to inline resolved conditions for the trace * basically rewriting the tree without any conditionals * where conditions are still present or conflicting we throw an error */ Trace.prototype.inlineConditions = function(tree, loader, conditionalEnv) { var self = this; return toCanonicalConditionalEnv.call(this, conditionalEnv) .then(function(canonicalConditionalEnv) { var inconsistencyErrorMsg = 'For static condition inlining only an exact environment resolution can be built, pending https://github.com/systemjs/builder/issues/311.'; // ensure we have no condition conflicts for (var c in conditionalEnv) { var val = conditionalEnv[c]; if (typeof val == 'string') continue; var complement = conditionalComplement(c); if (val instanceof Array || complement in conditionalEnv && conditionalEnv[complement] != !conditionalEnv[c]) throw new TypeError('Error building condition ' + c + '. ' + inconsistencyErrorMsg); } var conditionalResolutions = {}; var importsSystemEnv = false; // for each conditional in the tree, work out its substitution Object.keys(tree) .filter(function(m) { return tree[m] && tree[m].conditional; }) .forEach(function(c) { var resolution = Trace.getConditionalResolutions(tree[c].conditional, false, conditionalEnv); var branches = resolution.branches; if (branches.length > 1) throw new TypeError('Error building condition ' + c + '. ' + inconsistencyErrorMsg); if (branches.length == 0) throw new TypeError('No resolution found at all for condition ' + c + '.'); conditionalResolutions[c] = branches[0]; }); // resolve any chained conditionals Object.keys(conditionalResolutions).forEach(function(c) { var resolution = conditionalResolutions[c]; // yes this hangs on circular... while (conditionalResolutions[resolution]) { resolution = conditionalResolutions[resolution]; conditionalResolutions[c] = resolution; } }); // finally we do a deep clone of the tree, applying the conditional resolutions as we go // if we have a dependency on a condition not in the tree, we throw as it would be an unresolved external var inlinedTree = {}; Object.keys(tree).forEach(function(m) { var load = tree[m]; if (typeof load == 'boolean') { inlinedTree[m] = load; return; } if (load.conditional) return; var clonedLoad = extend({}, load); clonedLoad.depMap = {}; Object.keys(load.depMap).forEach(function(d) { var normalizedDep = load.depMap[d]; normalizedDep = conditionalResolutions[normalizedDep] || normalizedDep; if (normalizedDep == '@system-env') importsSystemEnv = true; if (normalizedDep.indexOf(/#[\:\?\{]/) != -1) throw new Error('Unable to inline conditional dependency ' + normalizedDep + '. Try including the ' + d + ' dependency of ' + load.name + ' in the build.'); clonedLoad.depMap[d] = normalizedDep; }); inlinedTree[m] = clonedLoad; }); // if we explicitly import from the system environment, then we need to build it into a static build // this is normally excluded as it is a system module in SystemJS but won't be available in static // builds which is exactly what this function acts on if (importsSystemEnv) { inlinedTree['@system-env'] = { name: '@system-env', path: null, metadata: { format: 'json' }, deps: [], depMap: {}, source: JSON.stringify({ production: conditionalEnv['@system-env|production'], browser: conditionalEnv['@system-env|browser'], node: conditionalEnv['@system-env|node'] }), fresh: true, timestamp: null, configHash: loader.configHash, }; } return inlinedTree; }); }; Trace.getConditionalResolutions = function(conditional, traceAllConditionals, conditionalEnv) { if (traceAllConditionals !== false) traceAllConditionals = true; conditionalEnv = conditionalEnv || {}; // flattens all condition objects into a resolution object // with the condition module and possible branches given the environment segment var resolution = { condition: null, branches: [] }; function envTrace(condition) { // trace the condition modules as dependencies themselves var negate = condition[0] == '~'; resolution.condition = condition.substr(negate, condition.lastIndexOf('|') - negate); // return the environment trace info var envTrace = conditionalEnv[condition]; return envTrace === undefined ? traceAllConditionals : envTrace; } var deps = []; // { condition, branch } boolean conditional if (conditional.branch) { if (envTrace(conditional.condition)) resolution.branches.push(conditional.branch); else resolution.branches.push('@empty'); } // { envs: [{condition, branch},...], fallback } package environment map else if (conditional.envs) { var doFallback = true; conditional.envs.forEach(function(env) { if (envTrace(env.condition)) resolution.branches.push(env.branch); // if we're specifically not tracing the negative of this condition // then we stop the fallback branch from building if (!envTrace(conditionalComplement(env.condition))) doFallback = false; }); var resolutionCondition = resolution.condition; if (doFallback && conditional.fallback) resolution.branches.push(conditional.fallback); } // { condition, branches } conditional interpolation else if (conditional.branches) { var et = envTrace(conditional.condition); if (et !== undefined && et !== false) { Object.keys(conditional.branches).forEach(function(branch) { var dep = conditional.branches[branch]; if (et === true) resolution.branches.push(dep); else if (et.indexOf(branch) != -1) resolution.branches.push(dep); }); } } return resolution; }; // Returns the ordered immediate dependency array from the trace of a module Trace.getLoadDependencies = function(load, tracePackageConfig, traceRuntimePlugin, traceAllConditionals, canonicalConditionalEnv, conditionsOnly) { if (traceAllConditionals !== false) traceAllConditionals = true; canonicalConditionalEnv = canonicalConditionalEnv || {}; var deps = []; if (!load.conditional && conditionsOnly) return deps; // conditional load records have their branches all included in the trace if (load.conditional) { var resolution = Trace.getConditionalResolutions(load.conditional, traceAllConditionals, canonicalConditionalEnv); if (tracePackageConfig && load.packageConfig) deps.push(load.packageConfig); deps.push(resolution.condition); if (conditionsOnly) return deps; else return deps.concat(resolution.branches); } // trace the plugin as a dependency if (traceRuntimePlugin && load.runtimePlugin) deps.push(load.plugin); // plugins by syntax build in their config if (tracePackageConfig && load.pluginConfig) deps.push(load.pluginConfig); // add the dependencies load.deps.forEach(function(dep) { deps.push(load.depMap[dep]); }); // trace the package config if necessary if (tracePackageConfig && load.packageConfig) deps.push(load.packageConfig); return deps; };
mit
PK-420/SuperSquirrel
src/main/framework/gameObjects/Block.java
3203
/* * The MIT License * * Copyright 2014 Patrick Kerr. * * 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. */ package main.framework.gameObjects; import main.framework.*; import java.awt.Graphics; import java.awt.Rectangle; import java.util.LinkedList; import main.graphics.Animation; /** * This class represents a static block of the desired texture and ObjectId * @author Patrick Kerr */ public final class Block extends GameObject { private Animation anim; /** * Represents the block[type] texture to load */ protected int type; /** * Creates a block object * @param x Horizontal position of the object on the map * @param y Vertical position of the object on the map * @param id ObjectId representing the type of block * @param type integer representing the block[type] texture to load (-1 represents an animated block) */ public Block (int x, int y, ObjectId id, int type) { super(x, y, id); this.type = type; super.x *= sizeX; super.y *= sizeY; if (type == -1) { // Init Animation For Special Blocks // currently only supports water... // add verif. ObjectId before drawing anim = new Animation(15, tex.block[16], tex.block[17], tex.block[18]); this.type = -1; } } @Override public void tick(LinkedList<GameObject> mapObj) { // Block Tick = Animated Blocks (Fire, Water, Lava...) if (type == -1) { anim.runAnimation(); } } @Override public void render(Graphics g) { // Draw according to ObjectId? if (type == -1) { anim.drawAnimation(g, (int)x, (int)y); } else { g.drawImage(tex.block[type], (int)x, (int)y, null); } ////////////// Collision Box // g.setColor(Color.BLUE); // Graphics2D g2d = (Graphics2D) g; // g2d.draw(getBounds()); } @Override public Rectangle getBounds() { return new Rectangle((int)x, (int)y, (int)sizeX, (int)sizeY); } }
mit
yasaichi/everett
spec/lib/everett/configuration_spec.rb
2444
require "rails_helper" RSpec.describe Everett::Configuration do # NOTE: To avoid changing state of Everett::Configuration#instance let(:configuration) { Class.new(described_class).instance } describe "#instantiated_observers" do subject { configuration.instantiated_observers } before do stub_const "FooObserver", Class.new.include(Singleton) configuration.observers = observers end context "when #observers include invalid values" do let(:observers) { [FooObserver, nil] } it { expect { subject }.to raise_error(TypeError) } end context "when #observers include valid values" do let(:observers) { [FooObserver, :bar_observer, "baz_observer"] } let(:expectation) { [FooObserver, BarObserver, BazObserver].map(&:instance) } before do stub_const "BarObserver", Class.new.include(Singleton) stub_const "BazObserver", Class.new.include(Singleton) end it { is_expected.to be_an_instance_of(Array).and contain_exactly(*expectation) } end end describe "#observers" do subject { configuration.observers } it { is_expected.to eq [] } end describe "#observers=" do describe "#observers" do subject { configuration.observers } context "when passing one observer" do before do configuration.observers = observer end context "when the value is nil" do let(:observer) { nil } it { is_expected.to eq [] } end context "when the value isn't nil" do let(:observer) { :foo_observer } it { is_expected.to eq [observer] } end end context "when passing more than one observer as array" do before do configuration.observers = %i(foo_observer bar_observer) end it { is_expected.to eq %i(foo_observer bar_observer) } end context "when passing more than one observer as comma-separated values" do before do configuration.observers = :foo_observer, :bar_observer end it { is_expected.to eq %i(foo_observer bar_observer) } end end end describe "#reset" do before do configuration.observers = :foo_observer end describe "#observers" do subject { -> { configuration.observers } } it { expect { configuration.reset }.to change(&subject).from(%i(foo_observer)).to([]) } end end end
mit
xplenty/xplenty.jar
xplenty.jar-core/src/main/java/com/xplenty/api/request/ListJobs.java
1887
/** * */ package com.xplenty.api.request; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.ClientResponse; import com.xplenty.api.Xplenty; import com.xplenty.api.Xplenty.ClusterStatus; import com.xplenty.api.exceptions.XplentyAPIException; import com.xplenty.api.model.Job; import com.xplenty.api.util.Http; import com.xplenty.api.util.Http.MediaType; import com.xplenty.api.util.Http.Method; import java.util.List; import java.util.Properties; /** * @author Yuriy Kovalek * */ public class ListJobs extends AbstractParametrizedRequest<List<Job>> { public ListJobs(Properties params) { super(params, true); validateParameters(params); } private void validateParameters(Properties params) { if ( params.containsKey(PARAMETER_STATUS) && !(params.get(PARAMETER_STATUS) instanceof ClusterStatus) && !(params.get(PARAMETER_STATUS) instanceof String && "all".equals(params.get(PARAMETER_STATUS))) ) throw new XplentyAPIException("Invalid 'status' parameter"); } @Override public String getName() { return Xplenty.Resource.Jobs.name; } @Override public Method getHttpMethod() { return Http.Method.GET; } @Override public MediaType getResponseType() { return Http.MediaType.JSON; } @Override protected String getEndpointRoot() { return Xplenty.Resource.Jobs.value; } @Override public List<Job> getResponse(ClientResponse response) { String json = response.getEntity(String.class); try { return new ObjectMapper().readValue(json, new TypeReference<List<Job>>() {}); } catch (Exception e) { throw new XplentyAPIException(getName() + ": error parsing response object", e); } } @Override public boolean hasBody() { return false; } @Override public List<Job> getBody() { return null; } }
mit
AmauryD/Arma_AC
ARMA_AC/Menu/Menus/menus.hpp
243
#include "common.hpp" #include "console_menu.hpp" #include "logs_menu.hpp" #include "objects_menu.hpp" #include "text_dialog.hpp" #include "map_menu.hpp" #include "spectate_menu.hpp" #include "admin_menu.hpp" #include "config_helper_menu.hpp"
mit
punkbass/Systems-of-Linear-Equations-Minecraft-Game-Rpi
systemOfLinearEquationsGame2D.py
1872
import mcpi.minecraft as minecraft import mcpi.block as block import time import random repeat = 4 waitTime = 9 height = 4 gameMin = -20 gameMax = 20 coeffMin = -9 coeffMax = 9 mc = minecraft.Minecraft.create() #set Solution xS = random.randint(gameMin,gameMax) yS = random.randint(gameMin,gameMax) #first line #x coeff a1 = random.randint(coeffMin,coeffMax) #y coeff b1 = random.randint(coeffMin,coeffMax) if a1 == b1: b1 = random.randint(coeffMin,coeffMax) #constant c1 = a1*xS + b1*yS #2nd line #x coeff a2 = random.randint(coeffMin,coeffMax) if a1 == a2: a2 = random.randint(coeffMin,coeffMax) #y coeff b2 = random.randint(coeffMin,coeffMax) if a2 == b2: b2 = random.randint(coeffMin,coeffMax) if b1 == b2: b2 = random.randint(coeffMin,coeffMax) #constant c2 = a2*xS + b2*yS # Graph Paper mc.setBlocks(gameMin,1,gameMin, gameMax,height+1,gameMax, block.AIR.id) mc.setBlocks(gameMin-1,0,gameMin-1, gameMax,0,gameMax, block.WOOL.id, 0) mc.setBlocks(gameMin,height,gameMin, gameMax,height,gameMax, block.WOOL.id, 0) for xi in range(gameMin,gameMax): for yi in range(gameMin, gameMax): if xi % 2 == 0: if yi % 2 == 0: mc.setBlocks(xi, 1, yi, xi,height,yi, block.WOOL.id, 0) if xi % 2 == 1: if yi % 2 == 1: mc.setBlock(xi,height,yi, block.AIR.id) # axis mc.setBlocks(gameMin,0,0, gameMax,0,0, block.WOOL.id, 15) mc.setBlocks(0,0,gameMin, 0,0,gameMax, block.WOOL.id, 15) mc = minecraft.Minecraft.create() mc.setBlock(xS, random.randint(1,height-1), yS, block.GOLD_BLOCK.id) mc.player.setPos(gameMin-1,1,gameMin-1) line1 = str(a1) + "x + " + str(b1) + "y = " + str(c1) line2 = str(a2) + "x + " + str(b2) + "y = " + str(c2) mc.postToChat("Write this down quick!") for i in range(repeat): mc.postToChat(str(line1)) mc.postToChat(str(line2)) time.sleep(waitTime)
mit
Englebabz/CasGO
Entityclass/stringparser.go
11052
package Exp import ( "fmt" dbg "github.com/Englebabz/CasGO/Debugprint" "github.com/Englebabz/CasGO/Stringmanipulations" "strings" ) func textToCasReal(instring string, recs string) (exp Express, err error) { //TextToCas will turn a string (eg "2*x+3") to an Express class //var origin = instring //fmt.Println(instring, "oi") newstringindent := recs + " " origin := instring //fix stupid signs instring = strings.Replace(instring, "-", "+-", -1) instring = strings.Replace(instring, "++", "+", -1) instring = strings.Replace(instring, "--", "+", -1) instring = strings.Replace(instring, "(+-", "(-", -1) newinstring := "" for index, charbyte := range instring { char := string(charbyte) if char == "_" && index != 0 && strmans.StringInSlice(string(instring[index-1]), []string{"*", "/", "+", "-", "("}) == false && (((index >= 2 && string(instring[index-2]) == "-") || (index+1 < len(instring) && string(instring[index+1]) == "{")) == false) { newinstring += "*" } newinstring += char } instring = newinstring if len(strmans.StrToBracketpairs(instring)) > 0 && strmans.StrToBracketpairs(instring)[0][0] == 0 && strmans.StrToBracketpairs(instring)[0][1] == len(instring)-1 { instring = instring[1 : len(instring)-1] } if string(instring[0]) == "+" || string(instring[0]) == "*" { instring = instring[1:] } //fix negative numbers if instring == "-1" { //Avoid "-1" becomes product(-1,1) return Number("-1"), nil } if string(instring[0]) == "-" && len(strmans.FindCharOutsideBracket("+", instring)) == 0 { dbg.Debug(10, recs+origin+" Becomes minusnumber") retval, err := textToCasReal(instring[1:], newstringindent) if err == nil { return Product(Number("-1"), retval), nil } else { panic("bad input to TextToCas " + origin) } } /*if string(instring[0]) == "-" && len(strmans.StrToBracketpairs(instring)) == 0 { dbg.Debug(10, recs+origin+" Becomes minusnumber") retval, err := textToCasReal(instring[1:], newstringindent) if err == nil { return Product(Number("-1"), retval), nil } else { panic("bad input to TextToCas " + origin) } }*/ //remove unnecessary bracket it's sorrounding the whole instring bracketPairs := strmans.StrToBracketpairs(instring) if len(bracketPairs) > 0 && bracketPairs[0][0] == 0 && bracketPairs[0][1] == len(instring)-1 { instring = instring[1 : len(instring)-1] } bracketPairs = strmans.StrToBracketpairs(instring) if instring == "-1" { //Avoid "-1" becomes product(-1,1) return Number("-1"), nil } //parse addition plusses := strmans.FindCharOutsideBracket("+", instring) if len(plusses) > 0 { dbg.Debug(10, recs+origin+" becomes ADDITION"+ fmt.Sprintf("%v", strmans.SplitStringByIndexes(instring, plusses))) var retaddends []Express for _, addendstring := range strmans.SplitStringByIndexes(instring, plusses) { returnaddend, err := textToCasReal(addendstring, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } retaddends = append(retaddends, returnaddend) } return Addition(retaddends...), nil } //if it's not addition, check for product productsigns := strmans.FindCharOutsideBracket("*", instring) if len(productsigns) > 0 { dbg.Debug(10, recs+origin+" becomes PRODUCT"+ fmt.Sprintf("%v", strmans.SplitStringByIndexes(instring, productsigns))) var retfactors []Express for _, factorstring := range strmans.SplitStringByIndexes(instring, productsigns) { returnfactor, err := textToCasReal(factorstring, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } retfactors = append(retfactors, returnfactor) } return Product(retfactors...), nil } //if it's not a product, check for fraction fractionsigns := strmans.FindCharOutsideBracket("/", instring) if len(fractionsigns) > 0 { if len(fractionsigns) > 1 { dbg.Debug(0, "BAD FRACTION, DON'T DO STUFF LIKE 2/3/2 (BRACKETS PLEASE)") } dbg.Debug(10, recs+origin+" becomes FRACTION"+ fmt.Sprintf("%v", strmans.SplitStringByIndexes(instring, fractionsigns))) retnum, err1 := textToCasReal(strmans.SplitStringByIndexes(instring, fractionsigns)[0], newstringindent) retdenom, err2 := textToCasReal(strmans.SplitStringByIndexes(instring, fractionsigns)[1], newstringindent) if err1 != nil || err2 != nil { panic("bad input to TextToCas " + origin) } return Fraction(retnum, retdenom), nil } //if it's not a fraction, then it might be a power powersigns := strmans.FindCharOutsideBracket("^", instring) if len(powersigns) > 0 { if len(powersigns) > 1 { dbg.Debug(0, "BAD POWER, PLEASE USE BRACKETS") } dbg.Debug(10, recs+origin+" becomes POWER"+ fmt.Sprintf("%v", (strmans.SplitStringByIndexes(instring, powersigns)))) rootandexpstrings := strmans.SplitStringByIndexes(instring, powersigns) retroot, err1 := textToCasReal(rootandexpstrings[0], newstringindent) retexp, err2 := textToCasReal(rootandexpstrings[1], newstringindent) if err1 != nil || err2 != nil { panic("Bad input to TextToCas " + origin) } retval := Power(retroot, retexp) retval.Forcepowerprint = true return retval, nil } //no usual things to look after; check for functions for index, charbytes := range instring { char := string(charbytes) if char == "(" && string(instring[index-1]) != "(" && string(instring[index-1]) != ")" { startbracket := index //find function string bracketoffset := 1 var funcend int for indexk := len(instring) - 1; indexk > -1; indexk-- { if string(instring[indexk]) == "(" { bracketoffset++ } else if string(instring[indexk]) == ")" { bracketoffset-- if bracketoffset == 0 { funcend = indexk break } } } funcstring := instring[0:startbracket] insidebrackets := instring[startbracket+1 : funcend] //findcommas escapeoffset := 0 var commaindexes []int for index, charbytes := range insidebrackets { char := string(charbytes) if escapeoffset > 0 { if char == "}" { escapeoffset-- } } if char == "{" { escapeoffset++ } if char == "," { commaindexes = append(commaindexes, index) } } if len(commaindexes) == 0 { switch funcstring { case "sin": { dbg.Debug(10, recs+origin+" becomes sine: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Sine(argexp), nil } case "cos": { dbg.Debug(10, recs+origin+" becomes cosine: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Cosine(argexp), nil } case "tan": { dbg.Debug(10, recs+origin+" becomes tangent: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Tangent(argexp), nil } case "arcsin": { dbg.Debug(10, recs+origin+" becomes arcsine: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Arcsine(argexp), nil } case "arccos": { dbg.Debug(10, recs+origin+" becomes arccosine: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Arccosine(argexp), nil } case "arctan": { dbg.Debug(10, recs+origin+" becomes arctangent: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Arctangent(argexp), nil } case "ln": { dbg.Debug(10, recs+origin+" becomes natlogarithm: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Natlog(argexp), nil } case "log": { dbg.Debug(10, recs+origin+" becomes comlogarithm: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Comlog(argexp), nil } case "sqrt": { dbg.Debug(10, recs+origin+" becomes squareroot: "+insidebrackets) argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Squareroot(argexp), nil } default: { dbg.Debug(10, recs+origin+" becomes unknownfunction: "+ funcstring+"("+insidebrackets+")") argexp, err := textToCasReal(insidebrackets, newstringindent) if err != nil { panic("bad input to TextToCas " + origin) } return Unknownfunction(funcstring, []Express{argexp}), nil } } } else { argstrings := strmans.SplitStringByIndexes(insidebrackets, commaindexes) dbg.Debug(10, recs+origin+"becomes unknownfunction: "+ funcstring+"("+insidebrackets+")") var retargs []Express for _, argstr := range argstrings { retarg, err := textToCasReal(argstr, newstringindent) if err != nil { panic("Bad input to TextToCas " + origin) } retargs = append(retargs, retarg) } return Unknownfunction(funcstring, retargs), nil } } } stillsignsininstring := false bracketoffset := 0 for _, charbyte := range instring { char := string(charbyte) if char == "{" { bracketoffset++ } else if char == "}" { bracketoffset-- } if bracketoffset == 0 && (char == "+" || char == "*" || char == "/" || char == "^") { stillsignsininstring = true break } } if stillsignsininstring { brackets := strmans.StrToBracketpairs(instring) if string(instring[0]) == "-" && len(brackets) > 0 && brackets[0][0] == 1 && brackets[0][1] == len(instring)-1 { dbg.Debug(10, recs+origin+"becomes negative "+instring[1:len(instring)-1]) partret, err := textToCasReal(instring[1:len(instring)-1], newstringindent) if err != nil { panic("Bad input to TextToCas: " + origin) } return Product(Number("-1"), partret), nil } panic("BAD EXPRESSION") } if string(instring[0]) == "-" { dbg.Debug(10, recs+origin+" becomes negative "+instring[1:]) dbg.Debug(10, recs+" "+"-1") partret, err := textToCasReal(instring[1:], newstringindent) if err != nil { panic("Bad input to TextToCas: " + origin) } return Product(Number("-1"), partret), nil } else { //NUMBER INSTANCE dbg.Debug(10, recs+origin) return Number(instring), nil } } func TextToCas(instring string) (exp Express) { retval, err := textToCasReal(instring, "") if err != nil { panic("Bad input to TextToCas: " + instring) } return retval }
mit
takeshik/yacq
Yacq/Serialization/AssemblyRef.cs
8774
// -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // $Id$ /* YACQ <http://yacq.net/> * Yet Another Compilable Query Language, based on Expression Trees API * Copyright © 2011-2013 Takeshi KIRIYA (aka takeshik) <takeshik@yacq.net> * All rights reserved. * * This file is part of YACQ. * * 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. */ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using Parseq; using Parseq.Combinators; namespace XSpect.Yacq.Serialization { /// <summary> /// Indicades an reference of <see cref="Assembly"/> for serialization. /// </summary> [DataContract(Name = "Assembly", IsReference = true)] #if !SILVERLIGHT [Serializable()] #endif public class AssemblyRef { private static readonly Dictionary<AssemblyRef, Assembly> _cache = new Dictionary<AssemblyRef, Assembly>(); private static readonly Dictionary<Assembly, AssemblyRef> _reverseCache = new Dictionary<Assembly, AssemblyRef>(); private static readonly Lazy<Parser<Char, AssemblyName>> _parser = new Lazy<Parser<Char, AssemblyName>>(() => Tuple.Create( ','.Satisfy().Pipe(' '.Satisfy().Many(), (l, r) => r.StartWith(l)), '='.Satisfy().Pipe(' '.Satisfy().Many(), (l, r) => r.StartWith(l)) ).Let((comma, equal) => Combinator.Choice( Chars.OneOf('`', '[', ']', '+', ',').Let(ds => ds .Not() .Right('\\'.Satisfy().Right(ds)) .Or(Chars.NoneOf('`', '[', ']', '+', ',')) .Many() ), Combinator.Sequence( Chars.Sequence("Version"), equal, Chars.Digit() .Many() .SepBy(3, '.'.Satisfy()) .Select(cs => cs.SelectMany(_ => _)) ).Select(_ => _.SelectMany(cs => cs)), Combinator.Sequence( Chars.Sequence("Culture"), equal, Chars.Letter() .Many() ).Select(_ => _.SelectMany(cs => cs)), Combinator.Sequence( Chars.Sequence("PublicKeyToken"), equal, Chars.Hex() .Many(16) .Or(Chars.Sequence("null")) ).Select(_ => _.SelectMany(cs => cs)) ) .SepBy(comma) .Select(fs => fs .SelectMany(cs => cs.EndWith(',')) .Stringify() .If(String.IsNullOrWhiteSpace, _ => new AssemblyName(), s => new AssemblyName(s.Last() == ',' ? s.Remove(s.Length - 1) : s) ) ) )); #if !SILVERLIGHT [NonSerialized()] #endif private AssemblyName _descriptor; private static readonly String[] _loadedAssemblies = new [] { "Parseq", "System", "System.Core", "System.Interactive", "System.Interactive.Providers", "System.Reactive.Core", "System.Reactive.Interfaces", "System.Reactive.Linq", "System.Reactive.PlatformServices", "System.Reactive.Providers", "System.Runtime.Serialization", "System.Xml", "System.Xml.Linq", "Yacq", }; /// <summary> /// Gets the parser to generate an <see cref="AssemblyName"/> object. /// </summary> /// <value>The parser to generate an <see cref="AssemblyName"/> object.</value> public static Parser<Char, AssemblyName> Parser { get { return _parser.Value; } } /// <summary> /// Gets or sets the value of <see cref="Assembly.FullName"/>. /// </summary> /// <value>The value of <see cref="Assembly.FullName"/>, or <c>null</c> if referring assembly is mscorlib.</value> [DataMember(Order = 0, EmitDefaultValue = false)] public String Name { get; set; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyRef"/> class. /// </summary> public AssemblyRef() { } /// <summary> /// Initializes a new instance of the <see cref="AssemblyRef"/> class. /// </summary> /// <param name="name">The value of <see cref="Assembly.FullName"/>, or simple name if referring assembly is wellknown, or <c>null</c> for mscorlib.</param> public AssemblyRef(String name) { this.Name = name; } /// <summary> /// Returns the string value of this assembly reference. /// </summary> /// <returns>The value of <see cref="Assembly.FullName"/>, or simple name if referring assembly is wellknown.</returns> public String GetName() { return this.Name ?? "mscorlib"; } /// <summary> /// Returns the assembly reference which refers specified assembly. /// </summary> /// <param name="assembly">The assembly to refer.</param> /// <returns>The assembly reference which refers specified assembly.</returns> public static AssemblyRef Serialize(Assembly assembly) { return _reverseCache.GetValue(assembly) ?? #if SILVERLIGHT assembly.FullName.Split(',')[0] #else assembly.GetName().Name #endif .Let(n => new AssemblyRef( n == "mscorlib" ? null : _loadedAssemblies.Contains(n) ? n : assembly.FullName )) .Apply(a => _reverseCache.Add(assembly, a)); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override String ToString() { return this.Describe().Name; } /// <summary> /// Returns an object to describe this assembly reference. /// </summary> /// <returns>An object to describe this assembly reference.</returns> public AssemblyName Describe() { return this._descriptor ?? ( this._descriptor = Parser(this.GetName().AsStream()) .TryGetValue(out this._descriptor) .Let(_ => this._descriptor) ); } /// <summary> /// Dereferences this assembly reference. /// </summary> /// <returns>The assembly which is referred by this assembly reference.</returns> public Assembly Deserialize() { return _cache.GetValue(this) ?? Assembly.Load(this.GetName()) .Apply(a => _cache.Add(this, a)); } } } // vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et:
mit
joev/SVUI-Temp
SVUI_UnitFrames/elements/castbar.lua
26037
--[[ ############################################################################## S V U I By: Munglunch # ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local print = _G.print; local ipairs = _G.ipairs; local pairs = _G.pairs; local next = _G.next; local rawset = _G.rawset; local rawget = _G.rawget; local tostring = _G.tostring; local tonumber = _G.tonumber; local tinsert = _G.tinsert; local tremove = _G.tremove; local twipe = _G.wipe; --STRING local string = string; local format = string.format; local sub = string.sub; --MATH local math = math; --TABLE local table = table; local tsort = table.sort; local tremove = table.remove; --[[ MATH METHODS ]]-- local abs, ceil, floor = math.abs, math.ceil, math.floor; -- Basic local parsefloat = math.parsefloat; -- Uncommon local CreateFrame = _G.CreateFrame; local InCombatLockdown = _G.InCombatLockdown; local GameTooltip = _G.GameTooltip; local UnitClass = _G.UnitClass; local UnitIsPlayer = _G.UnitIsPlayer; local UnitReaction = _G.UnitReaction; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI'] local L = SV.L; local LSM = _G.LibStub("LibSharedMedia-3.0") local MOD = SV.UnitFrames if(not MOD) then return end local oUF_SVUI = MOD.oUF assert(oUF_SVUI, "SVUI UnitFrames: unable to locate oUF.") SV.SpecialFX:Register("overlay_castbar", [[Spells\Eastern_plaguelands_beam_effect.m2]], 2, -2, -2, 2, 0.95, -1, 0) SV.SpecialFX:Register("underlay_castbar", [[Spells\Xplosion_twilight_impact_noflash.m2]], 1, -1, -1, 1, 0.9, 0, 0) --[[ ########################################################## LOCAL VARIABLES ########################################################## ]]-- local ticks = {} local function SpellName(id) local name, _, _, _, _, _, _, _, _ = GetSpellInfo(id) if not name then name = "Voodoo Doll"; end return name end local CustomTickData = { ["ChannelTicks"] = { --Warlock [SpellName(1120)] = 6, --"Drain Soul" [SpellName(689)] = 6, -- "Drain Life" [SpellName(108371)] = 6, -- "Harvest Life" [SpellName(5740)] = 4, -- "Rain of Fire" [SpellName(755)] = 6, -- Health Funnel [SpellName(103103)] = 4, --Malefic Grasp --Druid [SpellName(44203)] = 4, -- "Tranquility" [SpellName(16914)] = 10, -- "Hurricane" --Priest [SpellName(15407)] = 3, -- "Mind Flay" [SpellName(129197)] = 3, -- "Mind Flay (Insanity)" [SpellName(48045)] = 5, -- "Mind Sear" [SpellName(47540)] = 2, -- "Penance" [SpellName(64901)] = 4, -- Hymn of Hope [SpellName(64843)] = 4, -- Divine Hymn --Mage [SpellName(5143)] = 5, -- "Arcane Missiles" [SpellName(10)] = 8, -- "Blizzard" [SpellName(12051)] = 4, -- "Evocation" --Monk [SpellName(115175)] = 9, -- "Smoothing Mist" }, ["ChannelTicksSize"] = { --Warlock [SpellName(1120)] = 2, --"Drain Soul" [SpellName(689)] = 1, -- "Drain Life" [SpellName(108371)] = 1, -- "Harvest Life" [SpellName(103103)] = 1, -- "Malefic Grasp" }, ["HastedChannelTicks"] = { [SpellName(64901)] = true, -- Hymn of Hope [SpellName(64843)] = true, -- Divine Hymn }, } --[[ ########################################################## LOCAL FUNCTIONS ########################################################## ]]-- local function HideTicks() for i=1,#ticks do ticks[i]:Hide() end end local function SetCastTicks(bar,count,mod) mod = mod or 0; HideTicks() if count and count <= 0 then return end local barWidth = bar:GetWidth() local offset = barWidth / count + mod; for i=1,count do if not ticks[i] then ticks[i] = bar:CreateTexture(nil,'OVERLAY') ticks[i]:SetTexture(SV.media.statusbar.lazer) ticks[i]:SetVertexColor(0,0,0,0.8) ticks[i]:SetWidth(1) ticks[i]:SetHeight(bar:GetHeight()) end ticks[i]:ClearAllPoints() ticks[i]:SetPoint("RIGHT", bar, "LEFT", offset * i, 0) ticks[i]:Show() end end local Fader_OnEvent = function(self, event, arg) if arg ~= "player" then return end local isTradeskill = self:GetParent().recipecount if(isTradeskill and isTradeskill > 0) then return end; if event == "UNIT_SPELLCAST_START" then self.fails = nil; self.isokey = nil; self.ischanneling = nil; self:SetAlpha(0) self.mask:SetAlpha(1) if self.anim:IsPlaying() then self.anim:Stop() end elseif event == "UNIT_SPELLCAST_CHANNEL_START" then self:SetAlpha(0) self.mask:SetAlpha(1) if self.anim:IsPlaying() then self.anim:Stop() end self.iscasting = nil; self.fails = nil; self.isokey = nil elseif event == "UNIT_SPELLCAST_SUCCEEDED" then self.fails = nil; self.isokey = true; self.fails_a = nil elseif event == "UNIT_SPELLCAST_FAILED" or event == "UNIT_SPELLCAST_FAILED_QUIET" then self.fails = true; self.isokey = nil; self.fails_a = nil elseif event == "UNIT_SPELLCAST_INTERRUPTED" then self.fails = nil; self.isokey = nil; self.fails_a = true elseif event == "UNIT_SPELLCAST_STOP" then if self.fails or self.fails_a then self:SetBackdropColor(1, 0.2, 0.2, 0.5) self.txt:SetText(SPELL_FAILED_FIZZLE) self.txt:SetTextColor(1, 0.8, 0, 0.5) elseif self.isokey then self:SetBackdropColor(0.2, 1, 0.2, 0.5) self.txt:SetText(SUCCESS) self.txt:SetTextColor(0.5, 1, 0.4, 0.5) end self.mask:SetAlpha(0) self:SetAlpha(0) if not self.anim:IsPlaying() then self.anim:Play() end elseif event == "UNIT_SPELLCAST_CHANNEL_STOP" then self.mask:SetAlpha(0) self:SetAlpha(0) if self.fails_a then self:SetBackdropColor(1, 0.2, 0.2, 0.5) self.txt:SetText(SPELL_FAILED_FIZZLE) self.txt:SetTextColor(0.5, 1, 0.4, 0.5) if not self.anim:IsPlaying() then self.anim:Play() end end end end local function SetCastbarFading(castbar, texture) local fader = CreateFrame("Frame", nil, castbar) fader:SetFrameLevel(2) fader:InsetPoints(castbar) fader:SetBackdrop({bgFile = texture}) fader:SetBackdropColor(0, 0, 0, 0) fader:SetAlpha(0) fader:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED") fader:RegisterEvent("UNIT_SPELLCAST_START") fader:RegisterEvent("UNIT_SPELLCAST_STOP") fader:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED") fader:RegisterEvent("UNIT_SPELLCAST_CHANNEL_START") fader:RegisterEvent("UNIT_SPELLCAST_CHANNEL_STOP") fader:RegisterEvent("UNIT_SPELLCAST_FAILED") fader:RegisterEvent("UNIT_SPELLCAST_FAILED_QUIET") fader.mask = CreateFrame("Frame", nil, castbar) fader.mask:SetBackdrop({bgFile = texture}) fader.mask:InsetPoints(castbar) fader.mask:SetFrameLevel(2) fader.mask:SetBackdropColor(0, 0, 0, 0) fader.mask:SetAlpha(0) fader.txt = fader:CreateFontString(nil, "OVERLAY") fader.txt:SetFont(SV.media.font.alert, 16) fader.txt:SetAllPoints(fader) fader.txt:SetJustifyH("CENTER") fader.txt:SetJustifyV("CENTER") fader.txt:SetText("") fader.anim = fader:CreateAnimationGroup("Flash") fader.anim.fadein = fader.anim:CreateAnimation("ALPHA", "FadeIn") fader.anim.fadein:SetFromAlpha(0) fader.anim.fadein:SetToAlpha(1) fader.anim.fadein:SetOrder(1) fader.anim.fadeout1 = fader.anim:CreateAnimation("ALPHA", "FadeOut") fader.anim.fadeout1:SetFromAlpha(1) fader.anim.fadeout1:SetToAlpha(0.75) fader.anim.fadeout1:SetOrder(2) fader.anim.fadeout2 = fader.anim:CreateAnimation("ALPHA", "FadeOut") fader.anim.fadeout1:SetFromAlpha(0.75) fader.anim.fadeout1:SetToAlpha(0.25) fader.anim.fadeout2:SetOrder(3) fader.anim.fadein:SetDuration(0) fader.anim.fadeout1:SetDuration(.8) fader.anim.fadeout2:SetDuration(.4) fader:SetScript("OnEvent", Fader_OnEvent) end local CustomCastDelayText = function(self, value) if not self.TimeFormat then return end if self.channeling then if self.TimeFormat == "CURRENT" then self.Time:SetText(("%.1f |cffaf5050%.1f|r"):format(abs(value - self.max), self.delay)) elseif self.TimeFormat == "CURRENTMAX" then self.Time:SetText(("%.1f / %.1f |cffaf5050%.1f|r"):format(value, self.max, self.delay)) elseif self.TimeFormat == "REMAINING" then self.Time:SetText(("%.1f |cffaf5050%.1f|r"):format(value, self.delay)) end else if self.TimeFormat == "CURRENT" then self.Time:SetText(("%.1f |cffaf5050%s %.1f|r"):format(value, "+", self.delay)) elseif self.TimeFormat == "CURRENTMAX" then self.Time:SetText(("%.1f / %.1f |cffaf5050%s %.1f|r"):format(value, self.max, "+", self.delay)) elseif self.TimeFormat == "REMAINING"then self.Time:SetText(("%.1f |cffaf5050%s %.1f|r"):format(abs(value - self.max), "+", self.delay)) end end end local CustomTimeText = function(self, value) if not self.TimeFormat then return end if self.channeling then if self.TimeFormat == "CURRENT" then self.Time:SetText(("%.1f"):format(abs(value - self.max))) elseif self.TimeFormat == "CURRENTMAX" then self.Time:SetText(("%.1f / %.1f"):format(value, self.max)) self.Time:SetText(("%.1f / %.1f"):format(abs(value - self.max), self.max)) elseif self.TimeFormat == "REMAINING" then self.Time:SetText(("%.1f"):format(value)) end else if self.TimeFormat == "CURRENT" then self.Time:SetText(("%.1f"):format(value)) elseif self.TimeFormat == "CURRENTMAX" then self.Time:SetText(("%.1f / %.1f"):format(value, self.max)) elseif self.TimeFormat == "REMAINING" then self.Time:SetText(("%.1f"):format(abs(value - self.max))) end end end local CustomCastTimeUpdate = function(self, duration) if(self.recipecount and self.recipecount > 0 and self.maxrecipe and self.maxrecipe > 1) then self.Text:SetText(self.recipecount .. "/" .. self.maxrecipe .. ": " .. self.previous) end if(self.Time) then if(self.delay ~= 0) then if(self.CustomDelayText) then self:CustomDelayText(duration) else self.Time:SetFormattedText("%.1f|cffff0000-%.1f|r", duration, self.delay) end else if(self.CustomTimeText) then self:CustomTimeText(duration) else self.Time:SetFormattedText("%.1f", duration) end end end if(self.Spark) then local xOffset = 0 local yOffset = 0 if self.Spark.xOffset then xOffset = self.Spark.xOffset yOffset = self.Spark.yOffset end if(self:GetReverseFill()) then self.Spark:SetPoint("CENTER", self, "RIGHT", -((duration / self.max) * self:GetWidth() + xOffset), yOffset) else self.Spark:SetPoint("CENTER", self, "LEFT", ((duration / self.max) * self:GetWidth() + xOffset), yOffset) end end end local CustomCastBarUpdate = function(self, elapsed) self.lastUpdate = (self.lastUpdate or 0) + elapsed if not (self.casting or self.channeling) then self.unitName = nil self.previous = nil self.casting = nil self.castid = nil self.channeling = nil self.tradeskill = nil self.recipecount = nil self.maxrecipe = 1 self:SetValue(1) self:Hide() return end if(self.Spark and self.Spark[1]) then self.Spark[1]:Hide(); self.Spark[1].overlay:Hide() end if(self.Spark and self.Spark[2]) then self.Spark[2]:Hide(); self.Spark[2].overlay:Hide() end if(self.casting) then if self.Spark then if self.Spark.iscustom then self.Spark.xOffset = -12 self.Spark.yOffset = 0 end if(self.Spark[1]) then self.Spark[1]:Show() self.Spark[1].overlay:Show() if not self.Spark[1].anim:IsPlaying() then self.Spark[1].anim:Play() end end end local duration = self.duration + self.lastUpdate if(duration >= self.max) then self.previous = nil self.casting = nil self.tradeskill = nil self.recipecount = nil self.maxrecipe = 1 self:Hide() if(self.PostCastStop) then self:PostCastStop(self.__owner.unit) end return end CustomCastTimeUpdate(self, duration) self.duration = duration self:SetValue(duration) elseif(self.channeling) then if self.Spark then if self.Spark.iscustom then self.Spark.xOffset = 12 self.Spark.yOffset = 4 end if(self.Spark[2]) then self.Spark[2]:Show() self.Spark[2].overlay:Show() if not self.Spark[2].anim:IsPlaying() then self.Spark[2].anim:Play() end end end local duration = self.duration - self.lastUpdate if(duration <= 0) then self.channeling = nil self.previous = nil self.casting = nil self.tradeskill = nil self.recipecount = nil self.maxrecipe = 1 self:Hide() if(self.PostChannelStop) then self:PostChannelStop(self.__owner.unit) end return end CustomCastTimeUpdate(self, duration) self.duration = duration self:SetValue(duration) end self.lastUpdate = 0 end local CustomChannelUpdate = function(self, unit, index, hasTicks) if not(unit == "player" or unit == "vehicle") then return end if hasTicks then local activeTicks = CustomTickData.ChannelTicks[index] if activeTicks and CustomTickData.ChannelTicksSize[index] and CustomTickData.HastedChannelTicks[index] then local mod1 = 1 / activeTicks; local haste = UnitSpellHaste("player") * 0.01; local mod2 = mod1 / 2; local total = 0; if haste >= mod2 then total = total + 1 end local calc1 = tonumber(parsefloat(mod2 + mod1, 2)) while haste >= calc1 do calc1 = tonumber(parsefloat(mod2 + mod1 * total, 2)) if haste >= calc1 then total = total + 1 end end local activeSize = CustomTickData.ChannelTicksSize[index] local sizeMod = activeSize / 1 + haste; local calc2 = self.max - sizeMod * activeTicks + total; if self.chainChannel then self.extraTickRatio = calc2 / sizeMod; self.chainChannel = nil end SetCastTicks(self, activeTicks + total, self.extraTickRatio) elseif activeTicks and CustomTickData.ChannelTicksSize[index] then local haste = UnitSpellHaste("player") * 0.01; local activeSize = CustomTickData.ChannelTicksSize[index] local sizeMod = activeSize / 1 + haste; local calc2 = self.max - sizeMod * activeTicks; if self.chainChannel then self.extraTickRatio = calc2 / sizeMod; self.chainChannel = nil end SetCastTicks(self, activeTicks, self.extraTickRatio) elseif activeTicks then SetCastTicks(self, activeTicks) else HideTicks() end else HideTicks() end end local CustomInterruptible = function(self, unit, useClass) local colors = oUF_SVUI.colors local r, g, b = self.CastColor[1], self.CastColor[2], self.CastColor[3] if useClass then local colorOverride; if UnitIsPlayer(unit) then local _, class = UnitClass(unit) colorOverride = colors.class[class] elseif UnitReaction(unit, "player") then colorOverride = colors.reaction[UnitReaction(unit, "player")] end if colorOverride then r, g, b = colorOverride[1], colorOverride[2], colorOverride[3] end end if self.interrupt and unit ~= "player" and UnitCanAttack("player", unit) then r, g, b = colors.interrupt[1], colors.interrupt[2], colors.interrupt[3] end self:SetStatusBarColor(r, g, b) if self.bg:IsShown() then self.bg:SetVertexColor(r * 0.2, g * 0.2, b * 0.2) end if(self.Spark and self.Spark[1]) then r, g, b = self.SparkColor[1], self.SparkColor[2], self.SparkColor[3] self.Spark[1]:SetVertexColor(r, g, b) self.Spark[2]:SetVertexColor(r, g, b) end end --[[ ########################################################## BUILD FUNCTION ########################################################## ]]-- function MOD:CreateCastbar(frame, reversed, moverName, ryu, useFader, isBoss, hasModel) local colors = oUF_SVUI.colors; local castbar = CreateFrame("StatusBar", nil, frame) castbar.OnUpdate = CustomCastBarUpdate; castbar.CustomDelayText = CustomCastDelayText; castbar.CustomTimeText = CustomTimeText; castbar.PostCastStart = MOD.PostCastStart; castbar.PostChannelStart = MOD.PostCastStart; castbar.PostCastStop = MOD.PostCastStop; castbar.PostChannelStop = MOD.PostCastStop; castbar.PostChannelUpdate = MOD.PostChannelUpdate; castbar.PostCastInterruptible = MOD.PostCastInterruptible; castbar.PostCastNotInterruptible = MOD.PostCastNotInterruptible; castbar:SetClampedToScreen(true) castbar:SetFrameLevel(2) castbar.LatencyTexture = castbar:CreateTexture(nil, "OVERLAY") local cbName = frame:GetName().."Castbar" local castbarHolder = CreateFrame("Frame", cbName, castbar) local organizer = CreateFrame("Frame", nil, castbar) organizer:SetFrameStrata("HIGH") local iconHolder = CreateFrame("Frame", nil, organizer) iconHolder:SetStyle("!_Frame", "Inset", false) organizer.Icon = iconHolder local buttonIcon = iconHolder:CreateTexture(nil, "BORDER") buttonIcon:InsetPoints() buttonIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS)) castbar.Icon = buttonIcon; local shieldIcon = iconHolder:CreateTexture(nil, "ARTWORK") shieldIcon:SetPoint("TOPLEFT", buttonIcon, "TOPLEFT", -7, 7) shieldIcon:SetPoint("BOTTOMRIGHT", buttonIcon, "BOTTOMRIGHT", 7, -8) shieldIcon:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\SHIELD") castbar.Shield = shieldIcon; castbar.Time = organizer:CreateFontString(nil, "OVERLAY") castbar.Time:SetDrawLayer("OVERLAY", 7) castbar.Text = organizer:CreateFontString(nil, "OVERLAY") castbar.Text:SetDrawLayer("OVERLAY", 7) castbar.Organizer = organizer local bgFrame = CreateFrame("Frame", nil, castbar) local hadouken = CreateFrame("Frame", nil, castbar) if ryu then castbar.Time:SetFontObject(SVUI_Font_Aura) castbar.Time:SetTextColor(1, 1, 1) castbar.Text:SetFontObject(SVUI_Font_Caps) castbar.Text:SetTextColor(1, 1, 1, 0.75) castbar.Text:SetWordWrap(false) castbar:SetStatusBarTexture(SV.media.statusbar.lazer) bgFrame:InsetPoints(castbar, -2, 10) bgFrame:SetFrameLevel(bgFrame:GetFrameLevel() - 1) castbar.LatencyTexture:SetTexture(SV.media.statusbar.lazer) castbar.noupdate = true; castbar.pewpew = true hadouken.iscustom = true; hadouken:SetHeight(50) hadouken:SetWidth(50) hadouken:SetAlpha(0.9) castbarHolder:SetPoint("TOP", frame, "BOTTOM", 0, isBoss and -4 or -35) if reversed then castbar:SetReverseFill(true) hadouken[1] = hadouken:CreateTexture(nil, "ARTWORK") hadouken[1]:SetAllPoints(hadouken) hadouken[1]:SetBlendMode("ADD") hadouken[1]:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\HADOUKEN-REVERSED") hadouken[1]:SetVertexColor(colors.spark[1],colors.spark[2],colors.spark[3]) hadouken[1].overlay = hadouken:CreateTexture(nil, "OVERLAY") hadouken[1].overlay:SetHeight(50) hadouken[1].overlay:SetWidth(50) hadouken[1].overlay:SetPoint("CENTER", hadouken) hadouken[1].overlay:SetBlendMode("ADD") hadouken[1].overlay:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\SKULLS-REVERSED") hadouken[1].overlay:SetVertexColor(1, 1, 1) SV.Animate:Sprite4(hadouken[1],false,false,true) hadouken[2] = hadouken:CreateTexture(nil, "ARTWORK") hadouken[2]:InsetPoints(hadouken, 4, 4) hadouken[2]:SetBlendMode("ADD") hadouken[2]:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\CHANNEL-REVERSED") hadouken[2]:SetVertexColor(colors.spark[1],colors.spark[2],colors.spark[3]) hadouken[2].overlay = hadouken:CreateTexture(nil, "OVERLAY") hadouken[2].overlay:SetHeight(50) hadouken[2].overlay:SetWidth(50) hadouken[2].overlay:SetPoint("CENTER", hadouken) hadouken[2].overlay:SetBlendMode("ADD") hadouken[2].overlay:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\CHANNEL-REVERSED") hadouken[2].overlay:SetVertexColor(1, 1, 1) SV.Animate:Sprite4(hadouken[2],false,false,true) castbar:SetPoint("BOTTOMLEFT", castbarHolder, "BOTTOMLEFT", 1, 1) organizer:SetPoint("LEFT", castbar, "RIGHT", 4, 0) castbar.Time:SetPoint("RIGHT", castbar, "LEFT", -4, 0) else hadouken[1] = hadouken:CreateTexture(nil, "ARTWORK") hadouken[1]:SetAllPoints(hadouken) hadouken[1]:SetBlendMode("ADD") hadouken[1]:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\HADOUKEN") hadouken[1]:SetVertexColor(colors.spark[1],colors.spark[2],colors.spark[3]) hadouken[1].overlay = hadouken:CreateTexture(nil, "OVERLAY") hadouken[1].overlay:SetHeight(50) hadouken[1].overlay:SetWidth(50) hadouken[1].overlay:SetPoint("CENTER", hadouken) hadouken[1].overlay:SetBlendMode("ADD") hadouken[1].overlay:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\HADOUKEN") hadouken[1].overlay:SetVertexColor(1, 1, 1) SV.Animate:Sprite4(hadouken[1],false,false,true) hadouken[2] = hadouken:CreateTexture(nil, "ARTWORK") hadouken[2]:InsetPoints(hadouken, 4, 4) hadouken[2]:SetBlendMode("ADD") hadouken[2]:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\CHANNEL") hadouken[2]:SetVertexColor(colors.spark[1],colors.spark[2],colors.spark[3]) hadouken[2].overlay = hadouken:CreateTexture(nil, "OVERLAY") hadouken[2].overlay:SetHeight(50) hadouken[2].overlay:SetWidth(50) hadouken[2].overlay:SetPoint("CENTER", hadouken) hadouken[2].overlay:SetBlendMode("ADD") hadouken[2].overlay:SetTexture("Interface\\Addons\\SVUI_UnitFrames\\assets\\Castbar\\CHANNEL") hadouken[2].overlay:SetVertexColor(1, 1, 1) SV.Animate:Sprite4(hadouken[2],false,false,true) castbar:SetPoint("BOTTOMRIGHT", castbarHolder, "BOTTOMRIGHT", -1, 1) organizer:SetPoint("RIGHT", castbar, "LEFT", -4, 0) castbar.Time:SetPoint("LEFT", castbar, "RIGHT", 4, 0) end -- castbar.Time:SetPoint("CENTER", organizer, "CENTER", 0, 0) -- castbar.Time:SetJustifyH("CENTER") castbar.Text:SetAllPoints(castbar) else castbar.Time:SetFontObject(SVUI_Font_Aura) castbar.Time:SetTextColor(1, 1, 1, 0.9) castbar.Time:SetPoint("RIGHT", castbar, "LEFT", -1, 0) castbar.Text:SetFontObject(SVUI_Font_Caps) castbar.Text:SetTextColor(1, 1, 1, 0.9) castbar.Text:SetAllPoints(castbar) castbar.Text:SetWordWrap(false) castbar.pewpew = false castbar:SetStatusBarTexture(SV.media.statusbar.glow) castbarHolder:SetPoint("TOP", frame, "BOTTOM", 0, -4) castbar:InsetPoints(castbarHolder, 2, 2) bgFrame:SetAllPoints(castbarHolder) bgFrame:SetFrameLevel(bgFrame:GetFrameLevel() - 1) castbar.LatencyTexture:SetTexture(SV.media.statusbar.default) if reversed then castbar:SetReverseFill(true) organizer:SetPoint("LEFT", castbar, "RIGHT", 6, 0) else organizer:SetPoint("RIGHT", castbar, "LEFT", -6, 0) end end if(hasModel) then SV.SpecialFX:SetFXFrame(bgFrame, "underlay_castbar") bgFrame.FX:SetFrameLevel(0) SV.SpecialFX:SetFXFrame(castbar, "overlay_castbar", nil, bgFrame) end castbar.bg = bgFrame:CreateTexture(nil, "BACKGROUND", nil, -2) castbar.bg:SetAllPoints(bgFrame) castbar.bg:SetTexture(SV.media.statusbar.default) castbar.bg:SetVertexColor(0,0,0,0.5) local borderB = bgFrame:CreateTexture(nil,"OVERLAY") borderB:SetColorTexture(0,0,0) borderB:SetPoint("BOTTOMLEFT") borderB:SetPoint("BOTTOMRIGHT") borderB:SetHeight(2) local borderT = bgFrame:CreateTexture(nil,"OVERLAY") borderT:SetColorTexture(0,0,0) borderT:SetPoint("TOPLEFT") borderT:SetPoint("TOPRIGHT") borderT:SetHeight(2) local borderL = bgFrame:CreateTexture(nil,"OVERLAY") borderL:SetColorTexture(0,0,0) borderL:SetPoint("TOPLEFT") borderL:SetPoint("BOTTOMLEFT") borderL:SetWidth(2) local borderR = bgFrame:CreateTexture(nil,"OVERLAY") borderR:SetColorTexture(0,0,0) borderR:SetPoint("TOPRIGHT") borderR:SetPoint("BOTTOMRIGHT") borderR:SetWidth(2) castbar:SetStatusBarColor(colors.casting[1],colors.casting[2],colors.casting[3]) castbar.LatencyTexture:SetVertexColor(0.1, 1, 0.2, 0.5) castbar.Spark = hadouken; castbar.Holder = castbarHolder; castbar.CastColor = oUF_SVUI.colors.casting castbar.SparkColor = oUF_SVUI.colors.spark if moverName then castbar.Holder.snapOffset = -6 SV:NewAnchor(castbar.Holder, moverName) end if useFader then SetCastbarFading(castbar, SV.media.statusbar.lazer) end castbar.TimeFormat = "REMAINING" return castbar end --[[ ########################################################## UPDATE ########################################################## ]]-- function MOD:PostCastStart(unit, index, ...) if unit == "vehicle" then unit = "player" end local db = SV.db.UnitFrames if(not db or not(db and db[unit] and db[unit].castbar)) then return end local unitDB = db[unit].castbar if unitDB.displayTarget and self.curTarget then self.Text:SetText(sub(index.." --> "..self.curTarget, 0, floor(32 / 245 * self:GetWidth() / db.fontSize * 12))) else self.Text:SetText(sub(index, 0, floor(32 / 245 * self:GetWidth() / db.fontSize * 12))) end self.unit = unit; if unit == "player" or unit == "target" then CustomChannelUpdate(self, unit, index, unitDB.ticks) CustomInterruptible(self, unit, db.castClassColor) end end function MOD:PostCastStop(unit, ...) self.chainChannel = nil; self.prevSpellCast = nil end function MOD:PostChannelUpdate(unit, index) if unit == "vehicle" then unit = "player" end local db = SV.db.UnitFrames[unit]; if(not db or not db.castbar or not(unit == "player")) then return end CustomChannelUpdate(self, unit, index, db.castbar.ticks) end function MOD:PostCastInterruptible(unit) if unit == "vehicle" or unit == "player" then return end CustomInterruptible(self, unit, SV.db.UnitFrames.castClassColor) end function MOD:PostCastNotInterruptible(unit) local castColor = self.CastColor; self:SetStatusBarColor(castColor[1], castColor[2], castColor[3]) if(self.Spark and self.Spark[1]) then local sparkColor = self.SparkColor; self.Spark[1]:SetVertexColor(sparkColor[1], sparkColor[2], sparkColor[3]) self.Spark[2]:SetVertexColor(sparkColor[1], sparkColor[2], sparkColor[3]) end end
mit
probml/pyprobml
scripts/parzen_window_demo2.py
2303
# Demonstrate a non-parametric (parzen) density estimator in 1D # Author: Gerardo Durán Martín import superimport import numpy as np import matplotlib.pyplot as plt from scipy.linalg import norm plt.rcParams["axes.spines.right"] = False plt.rcParams["axes.spines.top"] = False def K(u, axis=0): return np.all(np.abs(u) <= 1/2, axis=axis) def p1(x, X, h): """ KDE under a unit hypercube """ N, D = X.shape xden, _ = x.shape u = ((x - X.T) / h).reshape(D, xden, N) ku = K(u).sum(axis=1) / (N * h ** D) return ku def kdeg(x, X, h, return_components=False): """ KDE under a gaussian kernel """ N, D = X.shape nden, _ = x.shape Xhat = X.reshape(D, 1, N) xhat = x.reshape(D, nden, 1) u = xhat - Xhat u = norm(u, ord=2, axis=0) ** 2 / (2 * h ** 2) # (N, nden) px = np.exp(-u) if not return_components: px = px.sum(axis=1) px = px / (N * h * np.sqrt(2 * np.pi)) return px def main(): data = np.array([-2.1, -1.3, -0.4, 1.9, 5.1, 6.2])[:, None] yvals = np.zeros_like(data) xv = np.linspace(-5, 10, 100)[:, None] fig, ax = plt.subplots(2, 2) # Uniform h=1 ax[0,0].scatter(data, yvals, marker="x", c="tab:gray") ax[0,0].step(xv, p1(xv, data, 1), c="tab:blue", alpha=0.7) ax[0,0].set_title("unif, h=1.0") # Uniform h=2 ax[0,1].scatter(data, yvals, marker="x", c="tab:gray") ax[0,1].step(xv, p1(xv, data, 2), c="tab:blue", alpha=0.7) ax[0,1].set_title("unif, h=2.0") # Gaussian h=1 ax[1,0].scatter(data, yvals, marker="x", c="tab:gray", zorder=3) ax[1,0].plot(xv, kdeg(xv, data, 1), c="tab:blue", alpha=0.7, zorder=2) ax[1,0].plot(xv, kdeg(xv, data, 1, True), c="tab:red", alpha=0.7, linestyle="--", zorder=1, linewidth=1) ax[1,0].set_title("gauss, h=1.0") # Gaussian h=2 ax[1,1].scatter(data, yvals, marker="x", c="tab:gray", zorder=3) ax[1,1].plot(xv, kdeg(xv, data, 2), c="tab:blue", alpha=0.7, zorder=2) ax[1,1].plot(xv, kdeg(xv, data, 2, True), c="tab:red", alpha=0.7, linestyle="--", zorder=1, linewidth=1) ax[1,1].set_title("gauss, h=2.0") plt.tight_layout() plt.savefig("../figures/parzen_window2.pdf", dpi=300) plt.show() if __name__ == "__main__": main()
mit
mmazi/rescu
src/main/java/si/mazi/rescu/HttpResponseAware.java
1347
/* * Copyright (C) 2015 Matija Mazi * * 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. * */ package si.mazi.rescu; import java.util.List; import java.util.Map; public interface HttpResponseAware { void setResponseHeaders(Map<String, List<String>> headers); Map<String, List<String>> getResponseHeaders(); }
mit
Biggar/snorcoin
src/qt/locale/bitcoin_af_ZA.ts
111997
<?xml version="1.0" ?><!DOCTYPE TS><TS language="af_ZA" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Snorcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Snorcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Snorcoin&lt;/b&gt; weergawe</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Snorcoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation>Dubbel-klik om die adres of etiket te wysig</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Skep &apos;n nuwe adres</translation> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Maak &apos;n kopie van die huidige adres na die stelsel klipbord</translation> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+72"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation>&amp;Verwyder</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your Snorcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your Snorcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+197"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fout uitvoering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon nie na die %1 lêer skryf nie</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+164"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(geen etiket)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Tik Wagwoord in</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuwe wagwoord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Herhaal nuwe wagwoord</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+34"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Tik die nuwe wagwoord vir die beursie in.&lt;br/&gt;Gebruik asseblief &apos;n wagwoord van &lt;b&gt;ten minste 10 ewekansige karakters&lt;/b&gt;, of &lt;b&gt;agt (8) of meer woorde.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Enkripteer beursie</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Hierdie operasie benodig &apos;n wagwoord om die beursie oop te sluit.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Hierdie operasie benodig &apos;n wagwoord om die beursie oop te sluit.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Sluit beursie oop</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Verander wagwoord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Tik asseblief die ou en nuwe wagwoord vir die beursie in.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bevestig beursie enkripsie.</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR SNORCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Die beursie is nou bewaak</translation> </message> <message> <location line="-56"/> <source>Snorcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your snorcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Die beursie kon nie bewaak word nie</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Beursie bewaaking het misluk as gevolg van &apos;n interne fout. Die beursie is nie bewaak nie!</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Die wagwoord stem nie ooreen nie</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Beursie oopsluiting het misluk</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Die wagwoord wat ingetik was om die beursie oop te sluit, was verkeerd.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Beursie dekripsie het misluk</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>SnorcoinGUI</name> <message> <location filename="../snorcoingui.cpp" line="+250"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+254"/> <source>Synchronizing with network...</source> <translation>Sinchroniseer met die netwerk ...</translation> </message> <message> <location line="-324"/> <source>&amp;Overview</source> <translation>&amp;Oorsig</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Wys algemene oorsig van die beursie</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaksies</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Besoek transaksie geskiedenis</translation> </message> <message> <location line="+15"/> <source>E&amp;xit</source> <translation>S&amp;luit af</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sluit af</translation> </message> <message> <location line="+7"/> <source>Show information about Snorcoin</source> <translation>Wys inligting oor Snorcoin</translation> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation>Wys inligting oor Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opsies</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+259"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-322"/> <source>Send coins to a Snorcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for Snorcoin</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-180"/> <location line="+6"/> <location line="+513"/> <source>Snorcoin</source> <translation>Snorcoin</translation> </message> <message> <location line="-519"/> <location line="+6"/> <source>Wallet</source> <translation>Beursie</translation> </message> <message> <location line="+109"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <location line="+2"/> <source>&amp;About Snorcoin</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Snorcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Snorcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Lêer</translation> </message> <message> <location line="+10"/> <source>&amp;Settings</source> <translation>&amp;Instellings</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Blad nutsbalk</translation> </message> <message> <location line="-235"/> <location line="+294"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="-177"/> <source>Request payments (generates QR codes and snorcoin: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>&amp;Used sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Used &amp;receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <location line="+5"/> <source>Snorcoin client</source> <translation>Snorcoin klient</translation> </message> <message numerus="yes"> <location line="+120"/> <source>%n active connection(s) to Snorcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 agter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Ontvangs van laaste blok is %1 terug.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informasie</translation> </message> <message> <location line="+77"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-152"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+124"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>URI can not be parsed! This can be caused by an invalid Snorcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../snorcoin.cpp" line="+110"/> <source>A fatal error occurred. Snorcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+115"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nuwe ontvangende adres</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuwe stuurende adres</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Wysig ontvangende adres</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Wysig stuurende adres</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Snorcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kon nie die beursie oopsluit nie.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+558"/> <location line="+13"/> <source>Snorcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to Snorcoin-Qt.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where Snorcoin-Qt will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Snorcoin-Qt will download and store a copy of the Snorcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+105"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opsies</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Snorcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Snorcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Snorcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Snorcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Snorcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Snorcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+58"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Snorcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Snorcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Beursie</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Onlangse transaksies&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+392"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid Snorcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <location line="+37"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insecure requests to custom payment scripts unsupported</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <location line="+30"/> <location line="+17"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../snorcoin.cpp" line="+114"/> <location line="+5"/> <location filename="../intro.cpp" line="-32"/> <source>Snorcoin</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+32"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+352"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Snorcoin-Qt help message to get a list with possible Snorcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="+72"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-541"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Snorcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Snorcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Snorcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Snorcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+128"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+22"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>The amount to request</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label to associate with the receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The message to attach to payment request</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use this form to request payments. All fields are optional.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+58"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+2"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+2"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+2"/> <source>Message</source> <translation>Boodskap</translation> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+140"/> <location line="+213"/> <source>Send Coins</source> <translation>Stuur Munstukke</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Stuur aan vele ontvangers op eens</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balans:</translation> </message> <message> <location line="+10"/> <source>123.456 SNC</source> <translation>123.456 SNC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>S&amp;tuur</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-154"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <location line="+5"/> <location line="+5"/> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Total Amount %1</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+33"/> <location line="+585"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="-572"/> <location line="+585"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="-551"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Die adres waarheen die betaling gestuur moet word (b.v. 1H7wyVL5HCNoVFyyBJSDojwyxcCChU7TPA)</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+28"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="-18"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Verwyder die ontvanger</translation> </message> <message> <location line="+16"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+465"/> <source>Memo:</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Snorcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Die adres waarheen die betaling gestuur moet word (b.v. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Teken boodskap</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Snorcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Teken &amp;Boodskap</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Snorcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Snorcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Die adres waarheen die betaling gestuur moet word (b.v. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Snorcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+23"/> <source>The Snorcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+22"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Van</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Na</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>eie adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiket</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+48"/> <source>Credit</source> <translation>Krediet</translation> </message> <message numerus="yes"> <location line="-120"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nie aanvaar nie</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+48"/> <source>Debit</source> <translation>Debiet</translation> </message> <message> <location line="-57"/> <source>Transaction fee</source> <translation>Transaksie fooi</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Boodskap</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaksie ID</translation> </message> <message> <location line="+13"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>waar</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>onwaar</translation> </message> <message> <location line="-227"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+227"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipe</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ontvang van</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n.v.t)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum en tyd wat die transaksie ontvang was.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipe transaksie.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alles</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Vandag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Hierdie week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hierdie maand</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Verlede maand</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Hierdie jaar</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Reeks...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ontvang met</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Gestuur na</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Aan/na jouself</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Gemyn</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ander</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min bedrag</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Maak kopie van adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipe</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fout uitvoering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon nie na die %1 lêer skryf nie</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Reeks:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>aan</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+218"/> <source>Send Coins</source> <translation>Stuur Munstukke</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+183"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>snorcoin-core</name> <message> <location filename="../snorcoinstrings.cpp" line="+102"/> <source>Snorcoin version</source> <translation>Snorcoin weergawe</translation> </message> <message> <location line="+107"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="-55"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Options:</source> <translation>Opsies:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: snorcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: snorcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Luister vir konneksies op &lt;port&gt; (standaard: 8333 of testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Onderhou op die meeste &lt;n&gt; konneksies na eweknieë (standaard: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-142"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+79"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Use the test network</source> <translation>Gebruik die toets netwerk</translation> </message> <message> <location line="-118"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=snorcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Snorcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Snorcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Snorcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Snorcoin RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fout: Hardeskyf spasie is baie laag!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Send command to Snorcoin server</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Start Snorcoin server</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Usage (deprecated, use snorcoin-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Information</source> <translation>Informasie</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Snorcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>System error: </source> <translation>Sisteem fout:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-70"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+79"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-126"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>This help message</source> <translation>Hierdie help boodskap</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Loading addresses...</source> <translation>Laai adresse...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Snorcoin</source> <translation type="unfinished"/> </message> <message> <location line="+98"/> <source>Wallet needed to be rewritten: restart Snorcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-100"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+30"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-100"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ongeldige bedrag</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Onvoldoende fondse</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Laai blok indeks...</translation> </message> <message> <location line="-60"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Unable to bind to %s on this computer. Snorcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>Laai beursie...</translation> </message> <message> <location line="-54"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+66"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>Klaar gelaai</translation> </message> <message> <location line="+85"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="-33"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
mit
NathanWalker/nativescript-ng2-magic
install.js
17345
// ----------------------------------------------------------- // version 1.09 // ----------------------------------------------------------- "use strict"; var debugging = false; var fs = require('fs'); var cp = require('child_process'); var path = require('path'); var isRanFromNativeScript = fs.existsSync("../../app/App_Resources"); var hasNativeScript = fs.existsSync("../../nativescript"); // Figure out angular Seed Path for symlink... var angularSeedPath = '../../src/'; var seeds = ['client', 'app']; var seedId = 0; // Search for the actual seed, depending on where we are run from for (var i=0;i<seeds.length;i++) { if (fs.existsSync(angularSeedPath+seeds[i])) { seedId = i; break; } } angularSeedPath += seeds[seedId] + "/"; var nativescriptClientPath = '../../nativescript/app/' + seeds[seedId] + "/"; if (debugging) { console.log("Path is:", angularSeedPath, nativescriptClientPath); } // Root SymLink Code for Windows if (process.argv.length > 2) { if (process.argv[2] === 'symlink') { createRootSymLink(); console.log("Created Symlink"); } return 0; } if (!hasNativeScript && !isRanFromNativeScript) { console.log("Installing NativeScript Angular 2 Template..."); cp.execSync('tns create nativescript --template https://github.com/NativeScript/template-hello-world-ng', {cwd: '../..'}); console.log("Installing NativeScript support files..."); cp.execSync('npm install', {cwd: '../../nativescript'}); console.log("Installing support files"); if (process.platform === 'darwin') { try { cp.execSync('npm install image-to-ascii-cli', {cwd: '../..'}); } catch (Err) { console.log("Install Error", Err); } } console.log("Configuring..."); if (debugging) { cp.execSync('tns plugin add ../node_modules/nativescript-ng2-magic', {cwd: '../../nativescript'}); } else { cp.execSync('tns plugin add nativescript-ng2-magic', {cwd: '../../nativescript'}); } // remove sample component if (fs.existsSync('../../nativescript/app/app.component.ts')) { console.log("Removing sample component"); fs.unlinkSync('../../nativescript/app/app.component.ts'); } if (fs.existsSync('../../nativescript/app/app.component.html')) { console.log("Removing sample component html"); fs.unlinkSync('../../nativescript/app/app.component.html'); } // We need to create a symlink try { createSymLink(); } catch (err) { if (debugging) { console.log("Symlink error: ", err); } // Failed, which means they weren't running root; so lets try to get root AttemptRootSymlink(); } // Might silent fail on OSX, so we have to see if it exists if (!fs.existsSync(nativescriptClientPath)) { AttemptRootSymlink(); } // This does not look good on windows; windows ansi support in node sucks... So we aren't going to do this in windows if (process.platform === "darwin") { // image to ascii uses GM which may not be installed, so if it isn't installed; don't print the error message try { var ascii = cp.execSync('image-to-ascii -i https://cdn.filestackcontent.com/XXMT4f8S8OGngNsJj0pr', {cwd: '../image-to-ascii-cli/bin/'}).toString(); if (ascii.length > 30) { console.log(ascii); } } catch (err) { // Do Nothing; if the site can't be resolved; we don't want to fail the script } } displayFinalHelp(); if (!fs.existsSync(nativescriptClientPath)) { console.log("We were unable to create a symlink - from -"); console.log(" ", resolve(angularSeedPath), " - to - "); console.log(" ", resolve(nativescriptClientPath)); console.log("If you don't create this symlink, you will have to manually copy the code each time you change it."); } } if (isRanFromNativeScript) { if (!fs.existsSync('installed.ns') ) { fs.writeFileSync('installed.ns', 'installed'); fixTsConfig(); fixRefFile(); fixNativeScriptPackage(); fixAngularPackage(); fixMainFile( figureOutRootComponent()); // when being run from inside {N} app, the directory is different var srcRoot = '../../../src/'; for (var i=0;i<seeds.length;i++) { if (fs.existsSync(srcRoot + seeds[i])) { seedId = i; break; } } fixGitIgnore('nativescript/app/' + seeds[seedId]); fixGitIgnore('nativescript/app/node_modules'); fixGitIgnore('nativescript/app/platforms'); console.log("Completed Install"); } else { console.log("We have already been installed in the NativeScript app as a plugin."); return 0; } } return 0; /** * Searches for the bootstrap file until it finds one.... * @returns {string} */ function figureOutRootComponent() { var rootComponents = ['../../../src/app/app.module.ts', '../../../src/app.ts', '../../../boot.ts', '../../../src/main.ts']; for (var i=0;i<rootComponents.length; i++) { if (fs.existsSync(rootComponents[i])) { var result = processBootStrap(rootComponents[i]); if (result) { return result; } } } // Return a default component, if we can't find one... return { name: 'AppComponent', path: './client/components/app.component' }; } /** * Parses the bootstrap to figure out the default bootstrap component * @param file * @returns {*} */ function processBootStrap(file) { var data = fs.readFileSync(file).toString(); var idx = data.indexOf('bootstrap('); if (idx === -1) { return null; } else { idx+=10; } var odx1 = data.indexOf(',', idx); var odx2 = data.indexOf(')', idx); if (odx2 < odx1 && odx2 !== -1 || odx1 === -1) { odx1 = odx2; } if (odx1 === -1) { return null; } var componentRef = data.substring(idx, odx1); var exp = "import\\s+\\{("+componentRef+")\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } var result = function (r) { return { name: r[1], path: r[r.length - 1] }; }; //noinspection JSPotentiallyInvalidConstructorUsage var r = RegExp(exp, 'i').exec(data); if (r === null || r.length <= 1) { // check if using current style guide with spaces exp = "import\\s+\\{\\s+("+componentRef+")\\,\\s+([A-Z]{0,300})\\w+\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } r = RegExp(exp, 'i').exec(data); if (r === null || r.length <= 1) { // try just spaces with no angular cli style (, environment) etc. exp = "import\\s+\\{\\s+(" + componentRef + ")\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } r = RegExp(exp, 'i').exec(data); if (r !== null && r.length > 1) { return result(r); } } else { // angular cli return result(r); } return null; } return result(r); } /** * This will attempt to run the install script as root to make a symlink * */ function AttemptRootSymlink() { if (process.platform === 'win32') { var curPath = resolve("./"); if (debugging) { console.log("RootSymlink Base path is", curPath); } cp.execSync("powershell -Command \"Start-Process 'node' -ArgumentList '"+curPath+"/install.js symlink' -verb runas\""); } else { console.log("To automatically create a SymLink between your web app and NativeScript, we need root for a second."); cp.execSync("sudo "+process.argv[0] + " " + process.argv[1] +" symlink"); } } /** * Create the symlink when running as root */ function createRootSymLink() { var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/'); if (li2 > li1) { li1 = li2; } var AppPath = process.argv[1].substring(0,li1); var p1 = resolve(AppPath + "/" + nativescriptClientPath); var p2 = resolve(AppPath + "/" + angularSeedPath); if (debugging) { console.log("Path: ", p1, p2); } fs.symlinkSync(p2,p1,'junction'); } /** * Create Symlink */ function createSymLink() { if (debugging) { console.log("Attempting to Symlink", angularSeedPath, nativescriptClientPath); } fs.symlinkSync(resolve(angularSeedPath),resolve(nativescriptClientPath),'junction'); } /** * This fixes the TS Config file in the nativescript folder */ function fixTsConfig() { var tsConfig={}, tsFile = '../../tsconfig.json'; if (fs.existsSync(tsFile)) { tsConfig = require(tsFile); } if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.typeRoots) { tsConfig.compilerOptions = { target: "es5", module: "commonjs", declaration: false, removeComments: true, noLib: false, emitDecoratorMetadata: true, experimentalDecorators: true, lib: [ "dom" ], sourceMap: true, pretty: true, allowUnreachableCode: false, allowUnusedLabels: false, noImplicitAny: false, noImplicitReturns: true, noImplicitUseStrict: false, noFallthroughCasesInSwitch: true, typeRoots: [ "node_modules/@types", "node_modules" ], types: [ "jasmine" ] }; } // See: https://github.com/NativeScript/nativescript-angular/issues/205 // tsConfig.compilerOptions.noEmitHelpers = false; // tsConfig.compilerOptions.noEmitOnError = false; if (!tsConfig.exclude) { tsConfig.exclude = []; } if (tsConfig.exclude.indexOf('node_modules') === -1) { tsConfig.exclude.push('node_modules'); } if (tsConfig.exclude.indexOf('platforms') === -1) { tsConfig.exclude.push('platforms'); } fs.writeFileSync(tsFile, JSON.stringify(tsConfig, null, 4), 'utf8'); } /** * This fixes the references file to work with TS 2.0 in the nativescript folder */ function fixRefFile() { var existingRef='', refFile = '../../references.d.ts'; if (fs.existsSync(refFile)) { existingRef = fs.readFileSync(refFile).toString(); } if (existingRef.indexOf('typescript/lib/lib.d.ts') === -1) { // has not been previously modified var fix = '/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />\n' + '/// <reference path="./node_modules/typescript/lib/lib.d.ts" />\n'; fs.writeFileSync(refFile, fix, 'utf8'); } } /** * Fix the NativeScript Package file */ function fixNativeScriptPackage() { var packageJSON = {}, packageFile = '../../package.json'; packageJSON.name = "NativeScriptApp"; packageJSON.version = "0.0.0"; // var AngularJSON = {}; if (fs.existsSync(packageFile)) { packageJSON = require(packageFile); } else { console.log("This should not happen, your are missing your package.json file!"); return; } // if (fs.existsSync('../angular2/package.json')) { // AngularJSON = require('../angular2/package.json'); // } else { // // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back // AngularJSON.peerDependencies = { // "es6-shim": "^0.35.0", // "reflect-metadata": "0.1.2", // "rxjs": "5.0.0-beta.6", // "zone.js": "^0.6.12" // }; // } packageJSON.nativescript['tns-ios'] = { version: "2.3.0" }; packageJSON.nativescript['tns-android'] = {version: "2.3.0" }; // Copy over all the Peer Dependencies // for (var key in AngularJSON.peerDependencies) { // if (AngularJSON.peerDependencies.hasOwnProperty(key)) { // packageJSON.dependencies[key] = AngularJSON.peerDependencies[key]; // } // } // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template? if (!packageJSON.devDependencies) { packageJSON.devDependencies = {}; } packageJSON.devDependencies["@types/jasmine"] = "^2.5.35"; packageJSON.devDependencies["babel-traverse"] = "6.12.0"; packageJSON.devDependencies["babel-types"] = "6.11.1"; packageJSON.devDependencies.babylon = "6.8.4"; packageJSON.devDependencies.filewalker = "0.1.2"; packageJSON.devDependencies.lazy = "1.0.11"; // packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2"; packageJSON.devDependencies.typescript = "^2.0.2"; fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8'); } /** * Fix the Angular Package */ function fixAngularPackage() { var packageJSON = {}, packageFile = '../../../package.json'; if (fs.existsSync(packageFile)) { packageJSON = require(packageFile); } else { console.log("This should not happen, your are missing your main package.json file!"); return; } if (!packageJSON.scripts) { packageJSON.scripts = {}; } packageJSON.scripts["start.ios"] = "cd nativescript && tns emulate ios"; packageJSON.scripts["start.livesync.ios"] = "cd nativescript && tns livesync ios --emulator --watch"; packageJSON.scripts["start.android"] = "cd nativescript && tns emulate android"; packageJSON.scripts["start.livesync.android"] = "cd nativescript && tns livesync android --emulator --watch"; fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8'); } /** * Fix the Main NativeScript File * @param component */ function fixMainFile(component) { var mainTS = '', mainFile = '../../app/main.ts'; if (fs.existsSync(mainFile)) { mainTS = fs.readFileSync(mainFile).toString(); } if (mainTS.indexOf('MagicService') === -1) { // has not been previously modified var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' + 'import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";\n' + 'import { NgModule } from "@angular/core";\n' + 'import { AppComponent } from "./app/app.component";\n' + '\n' + '@NgModule({\n' + ' declarations: [AppComponent],\n' + ' bootstrap: [AppComponent],\n' + ' imports: [NativeScriptModule],\n' + '})\n' + 'class AppComponentModule {}\n\n' + 'platformNativeScriptDynamic().bootstrapModule(AppComponentModule);'; fs.writeFileSync(mainFile, fix, 'utf8'); } } /** * Fix .gitignore * @param path */ function fixGitIgnore(ignorePattern) { var fileString = '', ignoreFile = '../../../.gitignore'; if (fs.existsSync(ignoreFile)) { fileString = fs.readFileSync(ignoreFile).toString(); } if (fileString.indexOf(ignorePattern) === -1) { // has not been previously modified var fix = fileString + '\n' + ignorePattern; fs.writeFileSync(ignoreFile, fix, 'utf8'); } } /** * Display final help screen! */ function displayFinalHelp() { console.log("-------------- Welcome to the Magical World of NativeScript -----------------------------"); console.log("To finish, follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage"); console.log("After you have completed the steps in the usage guide, you can then:"); console.log(""); console.log("Run your app in the iOS Simulator with these options:"); console.log(" npm run start.ios"); console.log(" npm run start.livesync.ios"); console.log(""); console.log("Run your app in an Android emulator with these options:"); console.log(" npm run start.android"); console.log(" npm run start.livesync.android"); console.log("-----------------------------------------------------------------------------------------"); console.log(""); } function splitPath(v) { var x; if (v.indexOf('/') !== -1) { x = v.split('/'); } else { x = v.split("\\"); } return x; } function resolve(v) { var cwdPath = splitPath(process.argv[1]); // Kill the Script name cwdPath.length = cwdPath.length - 1; var resolvePath = splitPath(v); // Eliminate a trailing slash/backslash if (cwdPath[cwdPath.length-1] === "") { cwdPath.pop(); } if (v[0] === '/' || v[0] === "\\") { cwdPath = []; } for (var i=0;i<resolvePath.length;i++) { if (resolvePath[i] === '.' || resolvePath[i] === "") { continue; } if (resolvePath[i] === '..') { cwdPath.pop(); } else { cwdPath.push(resolvePath[i]); } } if (process.platform === 'win32') { var winResult = cwdPath.join("\\"); if (winResult[winResult.length-1] === "\\") { winResult = winResult.substring(0, winResult.length - 1); } return winResult; } else { var result = cwdPath.join('/'); if (result[0] !== '/') { result = '/' + result; } if (result[result.length-1] === '/') { result = result.substring(0, result.length - 1); } return result; } }
mit
TNOCS/csTouch
framework/csCommonSense/Controls/FloatingElements/Shares/Qr/QrViewModel.cs
1690
#region using System; using System.ComponentModel.Composition; using System.Windows.Media; using System.Windows.Media.Imaging; using Caliburn.Micro; using EndPoint = csShared.FloatingElements.Classes.EndPoint; #endregion namespace csShared { public class QrViewModel : Screen { [ImportingConstructor] public QrViewModel() { } private string text = "hi"; public string Text { get { return text; } set { if (text == value) return; text = value; NotifyOfPropertyChange(() => Text); } } private ImageSource qrImage; public ImageSource QrImage { get { return qrImage; } set { qrImage = value; NotifyOfPropertyChange(() => QrImage); } } public AppStateSettings AppState { get { return AppStateSettings.Instance; } } private EndPoint endPoint; public EndPoint EndPoint { get { return endPoint; } set { endPoint = value; var q = new MessagingToolkit.QRCode.Codec.QRCodeEncoder(); var bmp = q.Encode(endPoint.Value.ToString()); QrImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); } } public FloatingElement Element { get; set; } } }
mit
floriico/onyx
js/entity-component/weapon.js
227
define([], function () { 'use strict'; function Weapon(name, minDamage, maxDamage) { this.name = name; this.minDamage = minDamage; this.maxDamage = maxDamage; Object.freeze(this); } return Weapon; });
mit
jcerniauskas/spformfiller
app/scripts.ts/Providers/FieldValueProvider/DateFieldRandomValueProvider.ts
1399
import { IFieldInfo } from "./../../FieldInfo/IFieldInfo"; import { IFieldValueProvider } from "./IFieldValueProvider"; import { injectable, inject } from "inversify"; import { RandomDateProvider } from "../RandomValueProvider/RandomDateProvider"; import { IDateFormatService } from "../../Services/DateFormat/IDateFormatService"; import { IDateValue } from "../ValueTypes/IDateValue"; // this class returns a random date rounded to 5 minutes (you can only select time in 5 minute increments in SharePoint) @injectable() export class DateFieldRandomValueProvider implements IFieldValueProvider { constructor(@inject("IDateFormatService") private _dateFormatService: IDateFormatService) { } public async GetRandomValue(fieldInfo: IFieldInfo): Promise<any> { let randomDate: Date = await RandomDateProvider.GetRandomDatePlusMinusOneYear(); randomDate = DateFieldRandomValueProvider.RoundTo15Minutes(randomDate); const formattedDate = await this._dateFormatService.GetFormattedDate(randomDate); return Promise.resolve(<IDateValue>{ Date: randomDate, FormattedDate: formattedDate }); } // SharePoint requires time to be rounded to 5 minute intervals private static RoundTo15Minutes(date: Date): Date { const coeff = 1000 * 60 * 5; return new Date(Math.round(date.getTime() / coeff) * coeff); } }
mit
christiancannata/velaforfun
src/AppBundle/Controller/RegistrationController.php
4577
<?php /* * This file is part of the FOSUserBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace AppBundle\Controller; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FormEvent; use FOS\UserBundle\Event\GetResponseUserEvent; use FOS\UserBundle\Event\FilterUserResponseEvent; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use FOS\UserBundle\Model\UserInterface; /** * Controller managing the registration * * @author Thibault Duplessis <thibault.duplessis@gmail.com> * @author Christophe Coevoet <stof@notk.org> */ class RegistrationController extends \FOS\UserBundle\Controller\RegistrationController { public function registerAction(Request $request) { /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */ $formFactory = $this->get('fos_user.registration.form.factory'); /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->get('fos_user.user_manager'); /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->get('event_dispatcher'); $user = $userManager->createUser(); $user->setEnabled(true); $event = new GetResponseUserEvent($user, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event); if (null !== $event->getResponse()) { return $event->getResponse(); } $form = $formFactory->createForm(); $form->setData($user); $form->handleRequest($request); if ($form->isValid()) { $event = new FormEvent($form, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event); $userManager->updateUser($user); if (null === $response = $event->getResponse()) { $url = $this->generateUrl('fos_user_registration_confirmed'); $response = new RedirectResponse($url); } $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response)); return $response; } return $this->render('FOSUserBundle:Registration:register.html.twig', array( 'form' => $form->createView(), )); } /** * Tell the user to check his email provider */ public function checkEmailAction() { $email = $this->get('session')->get('fos_user_send_confirmation_email/email'); $this->get('session')->remove('fos_user_send_confirmation_email/email'); $user = $this->get('fos_user.user_manager')->findUserByEmail($email); if (null === $user) { throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email)); } return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array( 'user' => $user, )); } /** * Receive the confirmation token from user email provider, login the user */ public function confirmAction(Request $request, $token) { /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->get('fos_user.user_manager'); $user = $userManager->findUserByConfirmationToken($token); if (null === $user) { throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token)); } /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->get('event_dispatcher'); $user->setConfirmationToken(null); $user->setEnabled(true); $event = new GetResponseUserEvent($user, $request); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event); $userManager->updateUser($user); if (null === $response = $event->getResponse()) { $url = $this->generateUrl('fos_user_registration_confirmed'); $response = new RedirectResponse($url); } $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response)); return $response; } /** * Tell the user his account is now confirmed */ public function confirmedAction() { $user = $this->getUser(); if (!is_object($user) || !$user instanceof UserInterface) { throw new AccessDeniedException('This user does not have access to this section.'); } return $this->render('FOSUserBundle:Registration:confirmed.html.twig', array( 'user' => $user, )); } }
mit
andela-thomas/ci-cd
karma.conf.js
2176
// Karma configuration // Generated on Mon Jan 04 2016 20:42:17 GMT+0300 (EAT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'sinon'], // list of files / patterns to load in the browser files: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-mocks/angular-mocks.js', 'public/lib/jquery/dist/jquery.min.js', 'public/lib/Materialize/dist/js/materialize.min.js', 'public/js/app.min.js', 'tests/unit/client/**/*.spec.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'public/js/app.min.js': ['coverage'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https: //npmjs.org/browse/keyword/karma-reporter reporters: ['coverage', 'progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || //config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, coverageReporter: { type: 'html', dir: 'coverage/' }, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }); };
mit
leonis/itamae-plugin-recipe-awslogs
lib/itamae/plugin/recipe/awslogs.rb
223
module Itamae module Plugin module Recipe module Awslogs def self.template_path(name) Pathname.new(__FILE__).join('../../../../../templates', name).to_s end end end end end
mit
codestruck/octopus
includes/functions/themes.php
1502
<?php /** * @return string The name of the current theme. * @copyright (c) 2012 Codestruck, LLC. * @license http://opensource.org/licenses/mit-license.php/ */ function get_theme() { $resp = Octopus_Response::current(); return $resp ? $resp->getTheme() : ''; } /** * Sets the current theme. * @param String $theme The name of the theme to use. Should be a directory * in the site/themes directory. * @copyright (c) 2012 Codestruck, LLC. * @license http://opensource.org/licenses/mit-license.php/ */ function set_theme($theme) { $resp = Octopus_Response::current(); $resp->setTheme($theme); } /** * @return Mixed The full absolute path to a file in the current theme, or * false if no matching file is found. * @copyright (c) 2012 Codestruck, LLC. * @license http://opensource.org/licenses/mit-license.php/ */ function get_theme_file($file, $options = array()) { $file = ltrim($file, '/'); $theme = isset($options['theme']) ? $options['theme'] : get_theme(); foreach(array('SITE_DIR', 'OCTOPUS_DIR') as $dir) { $dir = isset($options[$dir]) ? end_in('/', $options[$dir]) : get_option($dir); if (!$dir) continue; $dir = $dir . 'themes/' . $theme . '/'; $f = $dir . $file; if (is_file($f)) { return $f; } } return false; }
mit
ilya3d/itladder
common/models/User2position.php
1887
<?php namespace common\models; use Yii; /** * This is the model class for table "user2position". * * @property integer $user_id * @property integer $position_id * @property integer $date_change * @property integer $status * * @property User $user * @property Position $position */ class User2position extends \yii\db\ActiveRecord { const STATUS_IN_PROGRESS = 0; const STATUS_COLLECTED = 1; const STATUS_COMPLETE = 2; /** * @inheritdoc */ public static function tableName() { return 'user2position'; } /** * @inheritdoc */ public function rules() { return [ [['user_id', 'position_id', 'date_change', 'status'], 'required'], [['user_id', 'position_id', 'status'], 'integer'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'user_id' => 'User ID', 'position_id' => 'Position ID', 'date_change' => 'Date Change', 'status' => 'Status', ]; } /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); } /** * @return \yii\db\ActiveQuery */ public function getPosition() { return $this->hasOne(Position::className(), ['id' => 'position_id']); } public function load($data, $formName = null) { $bFlag = parent::load($data, $formName); // todo create validator for data_change $formName = ($formName === null) ? $this->formName() : $formName; if (isset($data[$formName]['date_change']) && $data[$formName]['date_change']!='') $this->date_change = \DateTime::createFromFormat('d.m.Y',$data[$formName]['date_change'])->format('U'); return $bFlag; } }
mit
AlexandruGhergut/BattleAI
BattleAIMaven/src/main/java/Networking/Requests/AddPlayer.java
412
package Networking.Requests; import java.io.ObjectOutputStream; public class AddPlayer extends Request { private final String username; public AddPlayer(String username) { super(RequestType.ADD_PLAYER); this.username = username; } @Override public void execute(ObjectOutputStream outputStream) { } public String getUsername() { return username; } }
mit
674803226/spring-boot-demo
src/main/java/com/example/demo/Application.java
649
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
mit
Azure/azure-sdk-for-java
sdk/costmanagement/azure-resourcemanager-costmanagement/src/main/java/com/azure/resourcemanager/costmanagement/models/QueryGrouping.java
2396
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.costmanagement.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** The group by expression to be used in the query. */ @Fluent public final class QueryGrouping { @JsonIgnore private final ClientLogger logger = new ClientLogger(QueryGrouping.class); /* * Has type of the column to group. */ @JsonProperty(value = "type", required = true) private QueryColumnType type; /* * The name of the column to group. */ @JsonProperty(value = "name", required = true) private String name; /** * Get the type property: Has type of the column to group. * * @return the type value. */ public QueryColumnType type() { return this.type; } /** * Set the type property: Has type of the column to group. * * @param type the type value to set. * @return the QueryGrouping object itself. */ public QueryGrouping withType(QueryColumnType type) { this.type = type; return this; } /** * Get the name property: The name of the column to group. * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: The name of the column to group. * * @param name the name value to set. * @return the QueryGrouping object itself. */ public QueryGrouping withName(String name) { this.name = name; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (type() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property type in model QueryGrouping")); } if (name() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property name in model QueryGrouping")); } } }
mit
BlackFrog1/PowerArgs
PowerArgs/HelperTypesInternal/ArgParser.cs
11298
using System.Collections; using System.Collections.Generic; using System.Linq; namespace PowerArgs { internal class ArgParser { // todo - This class was originally very dumb. It parsed the command line arguments without knowledge of the definition. // However, several special syntaxes that folks were expecting would only be possible if the parser had pretty deep // knowledge of the program structure. So now this class takes in the definition and inspects it to handle these // special cases. I should finish the job and handle positional elements this way too. This would remove the need // for the 'ImplicitParameters' collection in the ParseResult. On that other hand that would be a breaking change just // for the sake of cleanup. I need to think it over. // // Another potential item would be to refactor the parse method here. It's a mess, but it's a working, heavily tested mess // so cleaning it up will mean accepting some risk. internal static ParseResult Parse(CommandLineArgumentsDefinition Definition, string[] commandLineArgs) { var args = commandLineArgs; ParseResult result = new ParseResult(); int argumentPosition = 0; for (int i = 0; i < args.Length; i++) { var token = args[i]; // this block handles action parameters that must always be the first token if (i == 0 && Definition.Actions.Count > 0 && Definition.FindMatchingAction(token) != null) { result.ImplicitParameters.Add(0, token); argumentPosition++; } // don't affect tokens on linux & macOS else if (token.StartsWith("/") && OperatingSystem.IsWindows()) { var param = ParseSlashExplicitOption(token); if (result.ExplicitParameters.ContainsKey(param.Key)) throw new DuplicateArgException("Argument specified more than once: " + param.Key); result.ExplicitParameters.Add(param.Key, param.Value); argumentPosition = -1; } else if (token.StartsWith("-")) { string key = token.Substring(1); if (key.Length == 0) throw new ArgException("Missing argument value after '-'"); string value; // Handles long form syntax --argName=argValue. if (key.StartsWith("-") && key.Contains("=")) { var index = key.IndexOf("="); value = key.Substring(index + 1); key = key.Substring(0, index); } else { if (i == args.Length - 1) { value = ""; } else if (IsBool(key, Definition, result)) { var next = args[i + 1].ToLower(); if (next == "true" || next == "false" || next == "0" || next == "1") { i++; value = next; } else { value = "true"; } } else { i++; value = args[i]; } } if (result.ExplicitParameters.ContainsKey(key)) { throw new DuplicateArgException("Argument specified more than once: " + key); } result.ExplicitParameters.Add(key, value); if(IsArrayOrList(key, Definition, result)) { while((i+1) < args.Length) { var nextToken = args[i+1]; if(nextToken.StartsWith("/") || nextToken.StartsWith("-")) { break; } else { result.AddAdditionalParameter(key, nextToken); i++; } } } argumentPosition = -1; } else { if (argumentPosition < 0) throw new UnexpectedArgException("Unexpected argument: " + token); var possibleActionContext = result.ImplicitParameters.ContainsKey(0) ? result.ImplicitParameters[0] : null; var potentialListArgument = Definition.FindArgumentByPosition(argumentPosition, possibleActionContext); if (potentialListArgument != null) { bool isArrayOrList = potentialListArgument.ArgumentType.IsArray || potentialListArgument.ArgumentType.GetInterfaces().Contains(typeof(IList)); if (isArrayOrList) { // this block does special handling to allow for space separated collections for positioned parameters result.ExplicitParameters.Add(potentialListArgument.DefaultAlias, token); argumentPosition = -1; // no more positional arguments are allowed after this while ((i + 1) < args.Length) { var nextToken = args[i + 1]; if (nextToken.StartsWith("/") || nextToken.StartsWith("-")) { break; } else { result.AddAdditionalParameter(potentialListArgument.DefaultAlias, nextToken); i++; } } } else { // not an array or list parameter so add to the implicit parameter collection result.ImplicitParameters.Add(argumentPosition, token); argumentPosition++; } } else { // not an array or list parameter so add to the implicit parameter collection result.ImplicitParameters.Add(argumentPosition, token); argumentPosition++; } } } return result; } internal static bool TryParseKey(string cmdLineArg, out string key) { if(cmdLineArg.StartsWith("-") == false && cmdLineArg.StartsWith("/") == false) { key = null; return false; } else { key = ParseKey(cmdLineArg); return true; } } internal static string ParseKey(string cmdLineArg) { if (cmdLineArg.StartsWith("/")) { var param = ParseSlashExplicitOption(cmdLineArg); return param.Key; } else if (cmdLineArg.StartsWith("-")) { string key = cmdLineArg.Substring(1); if (key.Length == 0) throw new ArgException("Missing argument value after '-'"); // Handles long form syntax --argName=argValue. if (key.StartsWith("-") && key.Contains("=")) { var index = key.IndexOf("="); key = key.Substring(0, index); } return key; } else { throw new ArgException("Could not parse key '"+cmdLineArg+"' because it did not start with a - or a /"); } } private static bool IsBool(string key, CommandLineArgumentsDefinition definition, ParseResult resultContext) { var match = definition.FindMatchingArgument(key, true); if (match == null) { var possibleActionContext = resultContext.ImplicitParameters.ContainsKey(0) ? resultContext.ImplicitParameters[0] : null; if (possibleActionContext == null) { return false; } else { var actionContext = definition.FindMatchingAction(possibleActionContext, true); if (actionContext == null) { return false; } match = actionContext.FindMatchingArgument(key, true); if (match == null) { return false; } } } return match.ArgumentType == typeof(bool); } private static bool IsArrayOrList(string key, CommandLineArgumentsDefinition definition, ParseResult resultContext) { var match = definition.FindMatchingArgument(key, true); if (match == null) { var possibleActionContext = resultContext.ImplicitParameters.ContainsKey(0) ? resultContext.ImplicitParameters[0] : null; if (possibleActionContext == null) { return false; } else { var actionContext = definition.FindMatchingAction(possibleActionContext, true); if (actionContext == null) { return false; } match = actionContext.FindMatchingArgument(key, true); if (match == null) { return false; } } } return match.ArgumentType.IsArray || match.ArgumentType.GetInterfaces().Contains(typeof(IList)); } private static KeyValuePair<string, string> ParseSlashExplicitOption(string a) { var key = a.Contains(":") ? a.Substring(1, a.IndexOf(":") - 1).Trim() : a.Substring(1, a.Length - 1); var value = a.Contains(":") ? a.Substring(a.IndexOf(":") + 1).Trim() : ""; if (key.Length == 0) throw new ArgException("Missing argument value after '/'"); return new KeyValuePair<string, string>(key, value); } } }
mit
jakdor/SSCAndroidApp
ssc/app/src/test/java/com/jakdor/sscapp/ExampleUnitTest.java
395
package com.jakdor.sscapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
gastonfc/ajax-upload
test/dummy/app/controllers/foo_controller.rb
528
class FooController < ApplicationController attr_accessor :uploaded_file skip_before_filter :verify_authenticity_token def index end def custom_response { success: false, errors: "Sample" } end ajax_upload_receiver :custom_response def model_response foo = Foo.new(image: params['file']) foo.save foo end ajax_upload_receiver :model_response def do_nothing end ajax_upload_receiver :do_nothing def wrong_return_type nil end ajax_upload_receiver :wrong_return_type end
mit
SpiderBeam/TagKit
TagKit.Markup/TagQualifiedName.cs
2437
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TagKit.Markup { public class TagQualifiedName { private string _name; private string _ns; private Int32 _hash; public static readonly TagQualifiedName Empty = new TagQualifiedName(string.Empty); public TagQualifiedName() : this(string.Empty, string.Empty) { } public TagQualifiedName(string name) : this(name, string.Empty) { } public TagQualifiedName(string name, string ns) { _ns = ns == null ? string.Empty : ns; _name = name == null ? string.Empty : name; } public string Namespace { get { return _ns; } } public string Name { get { return _name; } } public override int GetHashCode() { if (_hash == 0) { _hash = Name.GetHashCode() /*+ Namespace.GetHashCode()*/; // for perf reasons we are not taking ns's hashcode. } return _hash; } public bool IsEmpty { get { return Name.Length == 0 && Namespace.Length == 0; } } public override string ToString() { return Namespace.Length == 0 ? Name : string.Concat(Namespace, ":", Name); } public override bool Equals(object other) { TagQualifiedName qname; if ((object)this == other) { return true; } qname = other as TagQualifiedName; if (qname != null) { return (Name == qname.Name && Namespace == qname.Namespace); } return false; } public static bool operator ==(TagQualifiedName a, TagQualifiedName b) { if ((object)a == (object)b) return true; if ((object)a == null || (object)b == null) return false; return (a.Name == b.Name && a.Namespace == b.Namespace); } public static bool operator !=(TagQualifiedName a, TagQualifiedName b) { return !(a == b); } public static string ToString(string name, string ns) { return ns == null || ns.Length == 0 ? name : ns + ":" + name; } } }
mit
silentmx/customize
backend/src/main/java/com/ztw/admin/basic/security/JwtAuthenticationRequest.java
877
package com.ztw.admin.basic.security; import java.io.Serializable; /** * ${DESCRIPTION} * * @author 马旭 * @created 2017-07-16 11:06. */ public class JwtAuthenticationRequest implements Serializable { private static final long serialVersionUID = -3426623048482978448L; private String username; private String password; public JwtAuthenticationRequest() { super(); } public JwtAuthenticationRequest(String username, String password) { this.setUsername(username); this.setPassword(password); } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
mit
dflm25/codeigniteres.club
application/third_party/Sioen/Types/BaseConverter.php
835
<?php class BaseConverter implements ConverterInterface { /** * The options we use for html to markdown * * @var array */ protected $options = array( 'header_style' => 'atx', 'bold_style' => '__', 'italic_style' => '_', ); public function toJson(\DOMElement $node) { $html = $node->ownerDocument->saveXML($node); return array( 'type' => 'text', 'data' => array( 'text' => ' ' . $this->htmlToMarkdown($html) ) ); } public function toHtml(array $data) { return Markdown::defaultTransform($data['text']); } protected function htmlToMarkdown($html) { $markdown = new \HTML_To_Markdown($html, $this->options); return $markdown->output(); } }
mit
andalexo/bgv
scripts/bgvExtract/old/bgv_rawdata.py
16911
#!/usr/bin/env python # inspired from velo2-assembly.py # Author: Karol Hennessy - karol.hennessy@cern.ch # Author: Massimiliano Ferro-Luzzi # Author: Mariana Rihl # Last edited: 29 November 2016 from Gaudi.Configuration import * from GaudiPython.Bindings import AppMgr from GaudiPython.Bindings import gbl from Configurables import LHCbApp from Configurables import PrepareVeloFullRawBuffer from Configurables import DecodeVeloFullRawBuffer from Configurables import createODIN #from Configurables import nzsStreamListener #from Configurables import LbAppInit #from Configurables import Vetra #from Configurables import (CondDB, CondDBAccessSvc) import GaudiPython from ROOT import TH2F, TCanvas, TFile, TH1F import sys from math import sqrt import pickle #from collections import defaultdict import gzip ############################## import matplotlib as mpl mpl.use('Agg') #mpl.use('Qt4Agg') mpl.interactive(True) import matplotlib.pyplot as plt import numpy as np import scipy as sp from numpy import * import string import math, os, sys #from mytools import * # from funcs import * #from defs import * #import copy ############################## #from Configurables import DataOnDemandSvc #from DAQSys.DecoderClass import Decoder #from DAQSys.Decoders import DecoderDB as ddb from Configurables import CondDB CondDB().IgnoreHeartBeat = True CondDB().EnableRunStampCheck = False lhcb = LHCbApp() nevts = 1000000000 print 'Starting bgv_raw.py....' if len(sys.argv)<2 : print 'You must provide the run number [and optionally num_events ]: python -i bgv_rawdata.py 1571 [1000 ]' sys.exit(-1) for i in range(0,len(sys.argv)): print 'sys.argv[',i,'] = ',sys.argv[i] if len(sys.argv)>2 : nevts = int(sys.argv[2]) runnumber = sys.argv[1] print 'Will process at most ',nevts,' events from run number ', runnumber loc = [''] prepList = ['prepareCentral'] decoList = ['decodeCentral'] countmissing = [] files = [] rootfile = 'none' if runnumber == '1848': rootfile = 'Run_0001848_20160915.root' files.append("DATAFILE='Run_0001848_20160915-155509.bgvctrl.mdf' SVC='LHCb::MDFSelector'") files.append("DATAFILE='Run_0001848_20160915-155634.bgvctrl.mdf' SVC='LHCb::MDFSelector'") files.append("DATAFILE='Run_0001848_20160915-155800.bgvctrl.mdf' SVC='LHCb::MDFSelector'") EventSelector().Input = files EventSelector().PrintFreq = 500 # init appMgr = AppMgr() appMgr.addAlgorithm('LbAppInit') for s in range(0,len(prepList)): appMgr.addAlgorithm('PrepareVeloFullRawBuffer/'+prepList[s]) appMgr.addAlgorithm('DecodeVeloFullRawBuffer/'+decoList[s] ) # in TAE events ODIN bank exists only for central event appMgr.addAlgorithm('createODIN') prep = [] deco = [] for s in range(0,len(prepList)): print 'Added algo prepList[',s,'] to prep' prep.append(appMgr.algorithm(prepList[s])) deco.append(appMgr.algorithm(decoList[s])) for s in range(0,len(prepList)): print 'Config prep[',s,'] with loc[',s,'] =',loc[s] prep[s].RunWithODIN = False prep[s].OutputLevel = 3 prep[s].IgnoreErrorBanks = True prep[s].ADCLocation = loc[s]+'Raw/Velo/ADCBank' prep[s].ADCPartialLoc = loc[s]+'Raw/Velo/PreparedPartialADC' prep[s].RawEventLocation = loc[s]+'DAQ/RawEvent' print 'Config deco[',s,'] with loc[',s,'] =',loc[s] deco[s].CableOrder = [3, 2, 1, 0] deco[s].SectorCorrection = False deco[s].OutputLevel = 3 deco[s].DecodedPartialADCLocation = loc[s]+'Raw/Velo/DecodedPartialADC' deco[s].ADCLocation = loc[s]+'Raw/Velo/ADCBank' deco[s].DecodedADCLocation = loc[s]+'Raw/Velo/DecodedADC' deco[s].DecodedHeaderLocation = loc[s]+'Raw/Velo/DecodedHeaders' deco[s].EventInfoLocation = loc[s]+'Raw/Velo/EvtInfo' deco[s].DecodedPedestalLocation = loc[s]+'Raw/Velo/DecodedPed' for s in range(0,len(prepList)): print 'Prepare algo : loc[',s,'] : ' props = prep[s].properties() for k in props.keys(): print ' ',k, props[k].value() print 'Decoder algo : loc[',s,']' props = deco[s].properties() for k in props.keys(): print ' ',k, props[k].value() appMgr.OutputLevel = 3 #prepar.OutputLevel = 3 #decode.OutputLevel = 3 evt = appMgr.evtsvc() def get_peds(appMgr,nforpeds,tell1numbers,initpeds,outliercut): print '###### Make pedestals ' peds = {} cnts = {} for key in tell1numbers: peds[key] = [0.0]*2048 cnts[key] = [0.0]*2048 n = 0 while n <= nforpeds: result = appMgr.run(1) if not evt['/Event'].__nonzero__() : print '###### Broken event ??? Event ',n break for s in range(0,len(loc)): adcs = evt[loc[s]+'Raw/Velo/DecodedADC'] for sen in adcs.containedObjects(): key = sen.key() if key in tell1numbers: sdata = sen.decodedData() for ch in range(2048): if abs(initpeds[key][ch]-sdata[ch])<outliercut: peds[key][ch] += sdata[ch] cnts[key][ch] += 1.0 n += 1 # start counting events at 1 print 'Ped event ',n for key in tell1numbers: for ch in range(2048): peds[key][ch] = peds[key][ch] / cnts[key][ch] return peds def get_adcdata_by_key(adcs,key): for a in adcs.containedObjects(): k = a.key() if k == key: adcdata = a.decodedData() return adcdata def get_headerdata_by_key(headers,key): for h in headers.containedObjects(): k = h.key() if k == key: hdata = h.decodedData() return hdata def save_obj(obj, name ): #with open('obj/'+ name + '.pkl', 'wb') as f: with open('/afs/cern.ch/user/m/mrihl/BGVAnalysis/'+ name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name ): #with open('obj/' + name + '.pkl', 'rb') as f: with open('/afs/cern.ch/user/m/mrihl/BGVAnalysis/'+ name + '.pkl', 'rb') as f: return pickle.load(f) def BeetleHistograms(appMgr,nevts,tell1numbers,peds,channeldatacut): print '###### Make Beetle histograms ' f = TFile('ADCs_perBeetle'+runnumber+'.root', 'recreate') #channellist = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28] channellist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31] beetlelist = range(16) #linklist = range(64) beetlehists_ADC = {} beetlehists_pedSub = {} completepulsehists = {} averagepulshists = {} # stephists = {} print tell1numbers for key in tell1numbers: beetlehists_ADC[key] = [] beetlehists_pedSub[key] = [] completepulsehists[key] = {} averagepulshists[key] = {} # stephists[key] = [] print 'Created beetlehists_ADC[key=',key,'] list' for ll in range(0,len(beetlelist)): l = beetlelist[ll] print key, l hname = "h_Temperaturescan_source%02d"%(key)+"_Beetle%02d"%(l) htitl = "ADCs bgvtell0"+str(key)+" Beetle "+str(l) nxbi = 128 xmax = (32)*(64-l*4)-1.5 xmin = xmax-127 beetlehists_ADC[key].append( TH2F(hname, htitl, nxbi, xmin,xmax, 300, 362.5,661.5) ) # hname1 = "h_PedSub_source%03d"%(key)+"_Beetle%03d"%(l) # htitl1 = "pedestal subtracted ADCs bgvtell0 "+str(key)+" Beetle "+str(l) # beetlehists_pedSub[key].append( TH2F(hname1, htitl1, nxbi, xmin,xmax, 300, -149.5,150.5) ) print 'At index ',len(beetlehists_ADC[key])-1,' created histogram ',hname,nxbi,xmin,xmax,300, 362.5,661.5 completepulsehists[key][l] = {} averagepulshists[key][l] = [] for timeslot in range(nxbi): completepulsehists[key][l][xmin+timeslot] = [] for ll in range(0,len(beetlelist)): l = beetlelist[ll] hname1 = "h_PedSub_source%02d"%(key)+"_Beetle%02d"%(l) htitl1 = "pedestal subtracted ADCs bgvtell0"+str(key)+" Beetle "+str(l) nxbi = 128 xmax = (32)*(64-l*4)-1.5 xmin = xmax-127 beetlehists_pedSub[key].append( TH2F(hname1, htitl1, nxbi, xmin,xmax, 300, -149.5,150.5) ) print 'Stop creating histograms' ncheck = 0 n = 0 skipped = 0 step = 0 print 'Event ',n#,' step ',step n_badpcn = 0 not_wanted_bcid = 0 while True: n += 1 # start counting events at 1 if n%100==0: print 'processing event %s' %n skipevent = False result = appMgr.run(1) #print 'Event ',n,' result = ',result if not evt['/Event'].__nonzero__() : print '###### Broken event ??? Event ',n break #skipevent = True if n > nevts: break # if n > nevtsperstep*nsteps: # break adcs = [] headers = [] evtinfo = [] xx = [] for channel in range(2048): xx.append(channel-0.5) for s in range(0,len(loc)): a = evt[loc[s]+'Raw/Velo/DecodedADC'] # e.g. evt['Prev2/Raw/Velo/DecodedADC'][1] is 'previous2' data of bgvtell01 but evt['Prev2/Raw/Velo/DecodedADC'] is defined h = evt[loc[s]+'Raw/Velo/DecodedHeaders'] e = evt[loc[s]+'Raw/Velo/EvtInfo'] if (not(a) or not(h)): print ' MISSING ADCS or HEADERS DATA in loc [',s,'] ',loc[s]+'Raw/Velo/... !!!' countmissing[s] += 1 skipevent = True else: adcs.append( a ) headers.append( h ) evtinfo.append( e ) odinloc = 'DAQ/ODIN' #odinloc = 'Raw/Velo/EvtInfo' odin = evt[odinloc] if odin : bcid = odin.bunchId() bctyp = odin.bunchCrossingType() orbnr = odin.orbitNumber() evtim = (odin.eventTime()).ns() evtyp = odin.eventType() # if not (bcid in wanted_bcid_list): # skipevent = True # not_wanted_bcid += 1 if not(skipevent): ncheck += 1 #TAEfirstPCN = 0 for key in tell1numbers: pedestals = peds[key] link_adcs = [] link_head = [] # get all samples of a given link: for s in range(0,len(loc)): link_adcs.append( get_adcdata_by_key(adcs[s],key) ) # basically get decoded data for e.g. evt['Prev2/Raw/Velo/DecodedADC'][1] link_head.append( get_headerdata_by_key(headers[s],key) ) for beetle in beetlelist: for channel in range(128): datachannel = (2047-(beetle*128 + channel)) beetlehists_ADC[key][beetle].Fill(xx[datachannel],link_adcs[0][datachannel]) beetlehists_pedSub[key][beetle].Fill(xx[datachannel],(link_adcs[0][datachannel]-pedestals[datachannel])) # l = beetlelist[ll] # for k in channellist: # channeldata = [0.0] * len(loc) # for s in range(0,len(loc)): # channeldata[s] = abs(link_adcs[s][l*32+k] - pedestals[l*32+k]) # if sum(channeldata)>channeldatacut: # for s in range(0,len(loc)): # beetlehists[key][ll].Fill(xx[s],link_adcs[s][l*32+k]) # timeslot = xx[s] # if timeslot > -50 and timeslot < -20: # we see some strange entries in the area between -50 and -20 ns that would badly impact the average value for the pulsshape. # if link_adcs[s][l*32+k] < 515: # these "positive" values greater 515 need to be disregarded. # completepulsehists[key][l][timeslot].append(link_adcs[s][l*32+k]) # else: completepulsehists[key][l][timeslot].append(link_adcs[s][l*32+k]) # # Get the header bits from ADC header data: # for b in range(16): # b = beetle index, 0 to 15 # headbits = [0]*16 # to store bits of one full beetle (4x4 bits = 16 bits) # for p in range(4): # port p = 0 to 3 # l = b * 4 + p # link l = b * 4 + p, 0 to 63 # #pedestal = sum(pedestals[l*32:(l+1)*32])/32.0 # #for k in range(4): headbits[k+4*p] = int(hdata[l*4+k] < pedestal) # header bit k=0,1,2,3 in port p # for k in range(4): headbits[k+4*p] = int(hdata[l*4+k] < 512) # header bit k=0,1,2,3 in port p # Beetpcn = Get_pcn_from_beetle_ports(headbits) # tell1_beepcns.append(Beetpcn) # if TAEfirstPCN == 0: # TAEfirstPCN = Beetpcn # else: # if Beetpcn != (TAEfirstPCN+s) : badpcn = True # at least one inconsistent PCN in the TAE Event else: skipped += 1 print 'pulseshape_histograms: got data over ',ncheck,' events out of ',n-1 # for s in range(0,len(loc)): # print ' found ',countmissing[s],' events with missing data in',loc[s]+'Raw/Velo/... ' # print 'Got in total ',n_badpcn,' bad PCN events (at least one inconsistent PCN in the TAE Event)' # print 'Got in total ',not_wanted_bcid,' TAEs with an unwanted BCID from ODIN' f.Write() f.Close() ############################ main: ############################################################ pkldir = '/afs/cern.ch/user/m/mrihl/BGVAnalysis/' fname = pkldir+'peds_'+runnumber+'_v1' skipevts = 0 if skipevts > 0: print '###### Skip ', skipevts, ' events' appMgr.run(skipevts) #frawhists = make_raw_histograms(appMgr,nevts,[1]) #odinbcid=justcount_events(appMgr,nevts) bgvtell1numbers=[1,2,4,5,6,7,8,9] #bgvtell1numbers=[1] #frawhists = make_raw_histograms(appMgr,nevts,[1]) #frawhists = make_raw_histograms(appMgr,nevts,[1,2,4,5,6,7,8,9]) #frawhists = make_raw_histograms(appMgr,nevts,bgvtell1numbers,False) nevtsperstep = 1000 nsteps = 25 print ' - read from pickle file',fname,'\n' try: peds = load_obj('peds_'+runnumber+'_v1') except: print "couldn't find pedestal file, creating it now!" do_peds = True #needs to be set True for a new run! -> check Colin's try function, that could prevent running this every time if do_peds: outliercut = 5.0 peds = {} niter = 5 nforpeds = nevtsperstep/niter for key in bgvtell1numbers: peds[key] = [512.0]*2048 print 'peds[',key,'][0:5] = ',peds[key][0:5],' ...' for i in range(niter): peds = get_peds(appMgr,nforpeds,bgvtell1numbers,peds,(niter-i)*outliercut) for key in bgvtell1numbers: print 'peds[',key,'][0:5] = ',peds[key][0:5],' ...' pedsname = 'peds_'+runnumber+'_v1' save_obj(peds,pedsname) else: peds = load_obj('peds_'+runnumber+'_v1') appMgr.run(nevtsperstep) # skip first step! # ---->for key in bgvtell1numbers: # ----> print 'peds[',key,'][0:5] = ',peds[key][0:5],' ...' channeldatacut = 50 beetlehists = BeetleHistograms(appMgr,nevts,bgvtell1numbers,peds,channeldatacut) # for beetle in range(0,len(beetlelist)): # l = beetlelist[ll] # for channel in channellist: # channeldata = [0.0] * len(loc) # for s in range(0,len(loc)): # channeldata[s] = abs(link_adcs[s][l*32+k] - pedestals[l*32+k]) # if sum(channeldata)>channeldatacut: # for s in range(0,len(loc)): # beetlehists[key][ll].Fill(xx[s],link_adcs[s][l*32+k]) # timeslot = xx[s] # if timeslot > -50 and timeslot < -20: # we see some strange entries in the area between -50 and -20 ns that would badly impact the average value for the pulsshape. # if link_adcs[s][l*32+k] < 515: # these "positive" values greater 515 need to be disregarded. # completepulsehists[key][l][timeslot].append(link_adcs[s][l*32+k]) # else: completepulsehists[key][l][timeslot].append(link_adcs[s][l*32+k]) # for beetle in beetlelist: # for link in range(4): # for channel in channellist: # channels.append(2047-(beetle*128 + link*32 + channel))
mit
vquaiato/grimorium
db/migrate/20140908052815_add_multiple_choice_display_to_question.rb
152
class AddMultipleChoiceDisplayToQuestion < ActiveRecord::Migration def change add_column :questions, :show_as_multiple_choice, :boolean end end
mit
gameclosure/hookbox
docs/source/builder/builders.py
5964
from sphinx.application import TemplateBridge from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.highlighting import PygmentsBridge from pygments import highlight from pygments.lexer import RegexLexer, bygroups, using from pygments.token import * from pygments.filter import Filter, apply_filters from pygments.lexers import PythonLexer, PythonConsoleLexer from pygments.formatters import HtmlFormatter, LatexFormatter import re from mako.lookup import TemplateLookup from mako.template import Template import os class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.layout = builder.config.html_context.get('mako_layout', 'html') directories = [os.path.join(os.path.dirname(__file__), '..', t) for t in builder.config.templates_path ] self.lookup = TemplateLookup(directories=directories, format_exceptions=True, imports=[ "from builder import util" ] ) def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' return self.lookup.get_template(template).render_unicode(**context) def render_string(self, template, context): context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) context['mako_layout'] = self.layout == 'html' and 'static_base.mako' or 'site_base.mako' return Template(template, lookup=self.lookup, format_exceptions=True, imports=[ "from builder import util" ] ).render_unicode(**context) class StripDocTestFilter(Filter): def filter(self, lexer, stream): for ttype, value in stream: if ttype is Token.Comment and re.match(r'#\s*doctest:', value): continue yield ttype, value class PyConWithSQLLexer(RegexLexer): name = 'PyCon+SQL' aliases = ['pycon+sql'] flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'{sql}', Token.Sql.Link, 'sqlpopup'), (r'{opensql}', Token.Sql.Open, 'opensqlpopup'), (r'.*?\n', using(PythonConsoleLexer)) ], 'sqlpopup':[ ( r'(.*?\n)((?:PRAGMA|BEGIN|SELECT|INSERT|DELETE|ROLLBACK|COMMIT|ALTER|UPDATE|CREATE|DROP|PRAGMA|DESCRIBE).*?(?:{stop}\n?|$))', bygroups(using(PythonConsoleLexer), Token.Sql.Popup), "#pop" ) ], 'opensqlpopup':[ ( r'.*?(?:{stop}\n*|$)', Token.Sql, "#pop" ) ] } class PythonWithSQLLexer(RegexLexer): name = 'Python+SQL' aliases = ['pycon+sql'] flags = re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'{sql}', Token.Sql.Link, 'sqlpopup'), (r'{opensql}', Token.Sql.Open, 'opensqlpopup'), (r'.*?\n', using(PythonLexer)) ], 'sqlpopup':[ ( r'(.*?\n)((?:PRAGMA|BEGIN|SELECT|INSERT|DELETE|ROLLBACK|COMMIT|ALTER|UPDATE|CREATE|DROP|PRAGMA|DESCRIBE).*?(?:{stop}\n?|$))', bygroups(using(PythonLexer), Token.Sql.Popup), "#pop" ) ], 'opensqlpopup':[ ( r'.*?(?:{stop}\n*|$)', Token.Sql, "#pop" ) ] } def _strip_trailing_whitespace(iter_): buf = list(iter_) if buf: buf[-1] = (buf[-1][0], buf[-1][1].rstrip()) for t, v in buf: yield t, v class PopupSQLFormatter(HtmlFormatter): def _format_lines(self, tokensource): buf = [] for ttype, value in apply_filters(tokensource, [StripDocTestFilter()]): if ttype in Token.Sql: for t, v in HtmlFormatter._format_lines(self, iter(buf)): yield t, v buf = [] if ttype is Token.Sql: yield 1, "<div class='show_sql'>%s</div>" % re.sub(r'(?:[{stop}|\n]*)$', '', value) elif ttype is Token.Sql.Link: yield 1, "<a href='#' class='sql_link'>sql</a>" elif ttype is Token.Sql.Popup: yield 1, "<div class='popup_sql'>%s</div>" % re.sub(r'(?:[{stop}|\n]*)$', '', value) else: buf.append((ttype, value)) for t, v in _strip_trailing_whitespace(HtmlFormatter._format_lines(self, iter(buf))): yield t, v class PopupLatexFormatter(LatexFormatter): def _filter_tokens(self, tokensource): for ttype, value in apply_filters(tokensource, [StripDocTestFilter()]): if ttype in Token.Sql: if ttype is not Token.Sql.Link and ttype is not Token.Sql.Open: yield Token.Literal, re.sub(r'(?:[{stop}|\n]*)$', '', value) else: continue else: yield ttype, value def format(self, tokensource, outfile): LatexFormatter.format(self, self._filter_tokens(tokensource), outfile) #def autodoc_skip_member(app, what, name, obj, skip, options): # if what == 'class' and skip and name == '__init__': # return False # else: # return skip def setup(app): app.add_lexer('pycon+sql', PyConWithSQLLexer()) app.add_lexer('python+sql', PythonWithSQLLexer()) PygmentsBridge.html_formatter = PopupSQLFormatter PygmentsBridge.latex_formatter = PopupLatexFormatter
mit
Topolev/TimeCurrentCharacteristic
src/app/app.module.ts
1179
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import {CoordinatePlaneModule} from "./draw-tripping-characteristics/coordinate-plane.module"; import {NgbModule} from "@ng-bootstrap/ng-bootstrap"; import {Routes, RouterModule} from "@angular/router"; import {HomeComponent} from "./components/home.component"; import {ToolsComponent} from "./components/tools.component"; import {TimeCurrentCharacteristic} from "./components/tools/time-current-characteristics.component"; const appRoutes: Routes = [ { path: 'home-page', component: HomeComponent }, { path: 'tools', component: ToolsComponent}, { path: 'time-current-characteristics', component: TimeCurrentCharacteristic}, { path: '', redirectTo: '/home-page', pathMatch: 'full' } ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes), BrowserModule, CoordinatePlaneModule, NgbModule.forRoot(), ], declarations: [ AppComponent, HomeComponent, ToolsComponent, TimeCurrentCharacteristic ], bootstrap: [ AppComponent ] }) export class AppModule { }
mit
socites/beyond
lib/server/http/writer/file.js
1157
module.exports = function (response, resource) { "use strict"; let co = require('co'); let fs = require('co-fs'); co(function *() { try { let plain = ['text/html', 'text/plain', 'application/javascript', 'text/css', 'text/cache-manifest']; if (plain.indexOf(resource.contentType) !== -1) { let content = yield fs.readFile(resource.file, {'encoding': 'UTF8'}); response.writeHead(200, { 'Content-Type': resource.contentType, 'Content_Length': content.length }); response.end(content); } else { let content = yield fs.readFile(resource.file); response.writeHead(200, { 'Content-Type': resource.contentType, 'Content_Length': content.length }); response.write(content, 'binary'); response.end(); } } catch (exc) { require('./500.js')(response, exc); console.log(exc.stack); } }); };
mit
oyvindhermansen/easy-state
docs/src/templates/docs.js
1097
import React, { Fragment, Component } from 'react'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import { Container, Marginer } from '../components/Common'; import Footer from '../layouts/Footer'; const MainMarkdown = styled.div` max-width: 40rem; width: 100%; margin: 0 0 auto 250px; padding: 0 2rem; @media all and (max-width: 966px) { max-width: 100%; margin: 0; } `; export default class Template extends Component { componentDidMount() { window.scrollTo(0, 0); } render() { const { markdownRemark: { frontmatter, html } } = this.props.data; return ( <div> <Marginer> <MainMarkdown> <h1>{frontmatter.title}</h1> <div dangerouslySetInnerHTML={{ __html: html }} /> <Footer /> </MainMarkdown> </Marginer> </div> ); } } export const postQuery = graphql` query BlogPostByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { path title } } } `;
mit
Maartenvm/csWeb
example/services/database/Location.ts
367
class Location { lon: number; lat: number; bouwjaar: number; huisnummer: number; huisnummertoevoeging: string; postcode: string; woonplaatsnaam: string; gemeentenaam: string; provincienaam: string; pandidentificatie: string; gebruiksdoelverblijfsobject: string; oppervlakteverblijfsobject: string; } export = Location;
mit
GJRDiesel/ddwrt_timeclock
manage.py
252
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "timeclock.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
mit
VLN1-Hopur23/VLN1-Hopur23
ui/addstudentdialog.cpp
8104
#include "addstudentdialog.h" #include "ui_addstudentdialog.h" #include <QtGui> #include <QtCore> AddStudentDialog::AddStudentDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddStudentDialog) { ui->setupUi(this); /*QPixmap pix(":/db_images/Images of scientists/unknown.jpg"); ui->label_s_picture->setPixmap(pix);*/ string picUrl = _service.retrievePicUrl(_scientist.getScientistID()); QPixmap pixmap(QString::fromStdString(picUrl)); ui->label_s_picture->setPixmap(pixmap); ui->label_s_picture->setScaledContents(true); } AddStudentDialog::~AddStudentDialog() { delete ui; } void AddStudentDialog::on_button_add_scientist_save_clicked() { QString error = "<span style='color: red'>Not validated input<\\span>"; QString name = ui->input_add_scientist_name->text(); QString yearBorn = ui->input_add_scientist_year_born->text(); QString yearOfDeath = ui->input_add_scientist_year_of_death->text(); bool InputIsNotValid = false; int yearOfBirthInt = yearBorn.toInt(); int yearOfDeathInt = yearOfDeath.toInt(); ui->label_error_add_scientist_name->setText(""); ui->label_error_add_scientist_gender->setText(""); ui->label_error_add_scientist_year_born->setText(""); ui->label_error_add_scientist_year_of_death->setText(""); if(name.isEmpty() || !(ValidInput(typeOf(name.toStdString()),"ACI_AC_AI_A"))) { ui->label_error_add_scientist_name->setText(error); InputIsNotValid = true; } if(!ui->button_radio_add_scientist_femail->isChecked() && !ui->button_radio_add_scientist_male->isChecked()) { ui->label_error_add_scientist_gender->setText(error); InputIsNotValid = true; } if(yearBorn.isEmpty() || !(ValidInput(typeOf(yearBorn.toStdString()),"I")) || yearOfBirthInt>_time.getYearToDay() || yearOfBirthInt<0 ) { ui->label_error_add_scientist_year_born->setText(error); InputIsNotValid = true; } if(ui->button_radio_add_scientist_still_alive->isChecked()) { yearOfDeathInt = 0; ui->input_add_scientist_year_of_death->setText(""); } else if(yearOfDeath.isEmpty() || !(ValidInput(typeOf(yearOfDeath.toStdString()),"I")) || yearOfDeathInt>_time.getYearToDay() || yearOfDeathInt<0 || yearOfBirthInt>yearOfDeathInt) { ui->label_error_add_scientist_year_of_death->setText(error); InputIsNotValid = true; } if(InputIsNotValid) { return; } string gender; if(ui->button_radio_add_scientist_femail->isChecked()) { gender = "f"; } else { gender = "m"; } string nameString = name.toStdString(); Scientist scientist(_service.getSize(), nameString, gender, yearOfBirthInt, yearOfDeathInt); int scientistID; bool success = _service.addScientist(scientist, scientistID); if (success) { ui->input_add_scientist_name->setText(""); ui->input_add_scientist_year_born->setText(""); ui->input_add_scientist_year_of_death->setText(""); this->done(1);// 1 means successful } else { this->done(-1); // -1 means something went wrong } } void AddStudentDialog::on_button_add_scientist_cancel_clicked() { this->done(0); // 0 means canceled } // typeOf(command) gives back string if command =="A" it includes onli alphabetical char, c..="C" includes onlie allowed char(, .),c..="I", // includes onlie integers, if c..="Nv" input not validated, if c..="AC" includes Alphabet and allowed char, command can also be "AI",AC",ACI","CI","I","C","A","NV" string AddStudentDialog::typeOf(string what) { int whatSize = what.size(); while(what.substr(whatSize-1, whatSize) == " ") { what = what.substr(0, whatSize-1); whatSize = what.size(); } int* whatArrayInt = new int[whatSize] {}; bool* whatIsInt = new bool[whatSize] {false}; bool* whatIsAlphabet = new bool[whatSize] {false}; bool* whatIsAlowedChar = new bool[whatSize] {false}; bool* whatNotValidated = new bool[whatSize] {false}; for(int i = 0; i < whatSize; i++) { whatArrayInt[i] = (int)what.substr(i, i+1)[0]; // [0] gives first character in string array that is char } for(int i = 0; i < whatSize; i++) { if(whatArrayInt[i] >= 48 && whatArrayInt[i] <= 57) // 48 ='0' ...57 ='9' { whatIsInt[i] = true; } else if((whatArrayInt[i] >= 65 && whatArrayInt[i] <= 90) || (whatArrayInt[i] >= 97 && whatArrayInt[i] <= 122) || (whatArrayInt[i] == 32) )//65 = 'A', 90='Z', 97='a',122='z',32 =SPACE { whatIsAlphabet[i] = true; } else if(whatArrayInt[i] == 46 || whatArrayInt[i] == 44 ) // 46 = '.', 44 = ',', { whatIsAlowedChar[i] = true; } else { whatNotValidated[i] = true; } } bool ThereAreSomeCharNotValidated = false; bool ThereAreSomeInt = false; bool ThereAreSomeAlphabet = false; bool ThereAreSomeAlowedChar = false; for(int i = 0; i < whatSize; i++) { if(whatIsInt[i]) { ThereAreSomeInt = true; } else if(whatIsAlphabet[i]) { ThereAreSomeAlphabet = true; } else if(whatIsAlowedChar[i]) { ThereAreSomeAlowedChar = true; } else { ThereAreSomeCharNotValidated = true; } } if(ThereAreSomeCharNotValidated) { return "NV"; // has: Not Validated input } else if(ThereAreSomeAlphabet && ThereAreSomeAlowedChar && ThereAreSomeInt) { return "ACI"; // has only: Alphabet, char, int } else if(ThereAreSomeAlowedChar && ThereAreSomeAlphabet) { return "AC"; // has only: Alphabet, char } else if(ThereAreSomeAlowedChar && ThereAreSomeInt) { return "CI"; // has only: char , int } else if(ThereAreSomeAlphabet && ThereAreSomeInt) { return "AI"; // has only: Alphabet, int } else if(ThereAreSomeAlphabet) { return "A"; // has only: Alphabet } else if(ThereAreSomeAlowedChar) { return "C"; // has only: char } else if(ThereAreSomeInt) { return "I"; // has only: int } else { return "error in localtime::typeOf(string what)"; } } // Check can be "AI",AC",ACI","CI","I","C","A","NV" see ConsoleUI::typeOf() for mor info // Allowed can be "A_AC.._I" see above // Checks if input is allowed bool AddStudentDialog::ValidInput(string check, string allowed) { if( check == "NV") { return false; } int count_ = 0; int* whereAre = new int[6]{}; int allowedSize = allowed.size(); string oneAllowedIntax; whereAre[count_] = -1; count_++; for(int i = 0; i < allowedSize; i++) { if(allowed[i] == '_') { whereAre[count_] = i; count_++; } } whereAre[count_] = allowedSize; for (int i = 0; i < count_; i++) { oneAllowedIntax = allowed.substr(whereAre[i]+1, whereAre[i+1] - whereAre[i]-1); if (check == oneAllowedIntax ) { return true; } } return false; } void AddStudentDialog::on_PushButton_browse_s_picture_clicked() { // ScierntistID will map the right picture url in connection table // We need to get the url from the table with the scientist ID string url = ""; //":/db_images/Images of scientists/unknown.jpeg"; string filePath = QFileDialog::getOpenFileName( this, "Search for image", "", "Image files(*.png *.jpg)" ).toStdString(); if(filePath.length()) { // user select som file QPixmap pixmap(QString::fromStdString(filePath)); ui->label_s_picture->setPixmap(pixmap); ui->label_s_picture->setScaledContents(true); // add the url to database _service.addPicUrl(_scientist.getScientistID(),filePath); } }
mit
milkskin/portfolio
application/helpers/tree_helper.php
2893
<?php defined('BASEPATH') OR exit('No direct script access allowed'); if ( ! function_exists('structure_to_markup')) { function structure_to_markup($dir_struct = array(), $alter_uri = '/', $is_root = TRUE) { $uri_segment = explode('/', uri_string()); $dir_path = STORAGEPATH.preg_replace('/^\/'.STORAGEURI.'/', '', $alter_uri); $open_tag = '<ul>'; $inner_tag = ''; $close_tag = '</ul>'; ksort($dir_struct); foreach ($dir_struct as $key => $value) { $file_path = $dir_path.preg_replace('/'.preg_quote(DIR_SEPARATOR, '/').'$/', '', $key); if (is_array($value) && ! is_link($file_path)) { $inner_tag .= '<li>'; $inner_tag .= ('<a href="'.$alter_uri.$key.'">'); $inner_tag .= ($is_root ? $key : rawurldecode(preg_replace('/'.preg_quote(DIR_SEPARATOR, '/').'$/', '', $key))); $inner_tag .= '</a>'; if ( ! empty($value)) { $inner_tag .= structure_to_markup($value, $alter_uri.$key, FALSE); } $inner_tag .= '</li>'; } } if ($inner_tag === '') { $open_tag = ''; $close_tag = ''; } return ($open_tag.$inner_tag.$close_tag); } } if ( ! function_exists('structure_to_array')) { function structure_to_array($dir_struct = array(), $alter_uri = '/', $parent_id = '#') { $is_root = ($parent_id === '#'); $uri_segment = explode('/', uri_string()); $uri_matched_path = STORAGEPATH.preg_replace('/^'.STORAGEURI.'/', '', uri_string()); $dir_path = STORAGEPATH.preg_replace('/^\/'.STORAGEURI.'/', '', $alter_uri); $node_list = array(); ksort($dir_struct); foreach ($dir_struct as $key => $value) { $file_path = $dir_path.preg_replace('/'.preg_quote(DIR_SEPARATOR, '/').'$/', '', $key); if (is_array($value) && ! is_link($file_path)) { exec("tree -dfiv --inodes ".DIR_SEPARATOR."data | grep {$file_path}$ | awk '{print substr($2, 0, length($2) - 1)}'", $file_info); $inode = $file_info[0]; unset($file_info); $node_info = array( 'id' => 'dir_'.$inode, 'parent' => $parent_id, 'text' => ($is_root ? $key : rawurldecode(preg_replace('/'.preg_quote(DIR_SEPARATOR, '/').'$/', '', $key))), 'state' => array( 'opened' => FALSE, 'selected' => ($file_path === $uri_matched_path), ), 'a_attr' => array( 'href' => $alter_uri.$key, ), 'type' => ($is_root ? 'root' : 'default'), ); $node_list[] = $node_info; if ( ! empty($value)) { $subtree_node_list = structure_to_array($value, $alter_uri.$key, 'dir_'.$inode); $node_list = array_merge($node_list, $subtree_node_list); } } } return $node_list; } } if ( ! function_exists('path_encode')) { function path_encode($dir_path, $separator = DIR_SEPARATOR) { $segment = explode($separator, $dir_path); foreach ($segment as $key => $value) { $segment[$key] = rawurlencode($value); } return implode($separator, $segment); } }
mit
elementlo/Android-TeaWiki
src/com/zlz/activity/MainActivity.java
4824
package com.zlz.activity; import org.w3c.dom.Text; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v4.widget.DrawerLayout; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; import com.example.day1105_class_viewpagerfragment.R; import com.handmark.pulltorefresh.library.internal.Utils; import com.zlz.adaptar.MyFragmentPagerAdaptar; public class MainActivity extends FragmentActivity{ private ViewPager vp_list; private DrawerLayout drawer; private ImageView imgv_openDrawer,imgv_closeDrawer; private LinearLayout drawerMenu; private RadioGroup rg_indexActivity; private RadioButton rb1_indexActivity,rb3_indexActivity,rb2_indexActivity,rb4_indexActivity,rb5_indexActivity; private EditText et_search; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initUI(); setImgListeners(); setVpListListener(); setRgindexActivityListener(); MyFragmentPagerAdaptar mfAdaptar=new MyFragmentPagerAdaptar(getSupportFragmentManager()); vp_list.setAdapter(mfAdaptar); } private void setRgindexActivityListener() { // TODO Auto-generated method stub rg_indexActivity.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup arg0, int arg1) { // TODO Auto-generated method stub switch (arg1) { case R.id.rb1_indexActivity: vp_list.setCurrentItem(0); break; case R.id.rb2_indexActivity: vp_list.setCurrentItem(1); break; case R.id.rb3_indexActivity: vp_list.setCurrentItem(2); break; case R.id.rb4_indexActivity: vp_list.setCurrentItem(3); break; case R.id.rb5_indexActivity: vp_list.setCurrentItem(4); break; default: break; } } }); } private void setVpListListener() { // TODO Auto-generated method stub vp_list.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { // TODO Auto-generated method stub switch (position) { case 0: rb1_indexActivity.setChecked(true); break; case 1: rb2_indexActivity.setChecked(true); break; case 2: rb3_indexActivity.setChecked(true); break; case 3: rb4_indexActivity.setChecked(true); break; case 4: rb5_indexActivity.setChecked(true); break; default: break; } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub } }); } private void setImgListeners() { imgv_openDrawer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { drawer.openDrawer(drawerMenu); } }); imgv_closeDrawer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { drawer.closeDrawer(drawerMenu); } }); } public void onClick(View v){ switch (v.getId()) { case R.id.iv_search: if(TextUtils.isEmpty(et_search.getText())){ Toast.makeText(this, "ÇëÊäÈëÄÚÈÝ", 0).show(); }else { Intent intent_search=new Intent(this,SearchActivity.class); intent_search.putExtra("searchwhat", et_search.getText()); startActivity(intent_search); } break; default: break; } } private void initUI() { vp_list=(ViewPager) findViewById(R.id.vp_list); drawer=(DrawerLayout) findViewById(R.id.drawl); rb1_indexActivity=(RadioButton) findViewById(R.id.rb1_indexActivity); rb2_indexActivity=(RadioButton) findViewById(R.id.rb2_indexActivity); rb3_indexActivity=(RadioButton) findViewById(R.id.rb3_indexActivity); rb4_indexActivity=(RadioButton) findViewById(R.id.rb4_indexActivity); rb5_indexActivity=(RadioButton) findViewById(R.id.rb5_indexActivity); imgv_openDrawer=(ImageView) findViewById(R.id.imgv_openDrawer); imgv_closeDrawer=(ImageView) findViewById(R.id.imgv_closeDrawer); drawerMenu=(LinearLayout) findViewById(R.id.drawerMenu); rg_indexActivity=(RadioGroup) findViewById(R.id.rg_indexActivity); et_search=(EditText) findViewById(R.id.et_search); } }
mit
Ragg-/Delir
packages/unworked-plugins/noise/index.ts
1655
import { EffectPluginBase, Exceptions, PluginPreRenderRequest, RenderRequest, Type, TypeDescriptor, } from '@ragg/delir-core' import * as Tooloud from 'tooloud' export default class NoiseEffectPlugin extends EffectPluginBase { public static async pluginDidLoad() { // ✋( ͡° ͜ʖ ͡°) インターフェースに誓って if (typeof window === 'undefined') { throw new Exceptions.PluginLoadFailException('this plugin only running on Electron') } } public static provideParameters(): TypeDescriptor { return Type.none() } constructor() { super() } public async beforeRender(preRenderRequest: PluginPreRenderRequest) {} public async render(req: RenderRequest) { const canvas = req.destCanvas const ctx = req.destCanvas.getContext('2d') if (ctx == null) { return } ctx.clearRect(0, 0, canvas.width, canvas.height) const imageData: ImageData = ctx.getImageData(0, 0, req.destCanvas.width, req.destCanvas.height) const data: Uint8ClampedArray = imageData.data for (let x = 0; x < req.destCanvas.width; x++) { for (let y = 0; y < req.destCanvas.height; y++) { const head = canvas.width * y * 4 + x const value = Tooloud.Worley.Euclidean(x, y, 0) data[head + 0] = (value[0] * 255) | 0 data[head + 1] = (value[1] * 255) | 0 data[head + 2] = (value[2] * 255) | 0 data[head + 3] = 255 } } ctx.putImageData(imageData, 0, 0) } }
mit
kaiprt/DoCheck
app/models/event.rb
125
class Event < ActiveRecord::Base belongs_to :experience has_many :checklists has_many :items, through: :checklists end
mit
HenriquePaulo/projeto
backend/appengine/routes/Products/rest.py
1400
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from gaebusiness.business import CommandExecutionException from gaepermission.decorator import login_not_required from tekton.gae.middleware.json_middleware import JsonResponse from Product_app import Product_facade def index(): cmd = Product_facade.list_products_cmd() product_list = cmd() product_form = Product_facade.product_form() product_dcts = [product_form.fill_with_model(m) for m in product_list] return JsonResponse(product_dcts) def new(_resp, **product_properties): cmd = Product_facade.save_product_cmd(**product_properties) return _save_or_update_json_response(cmd, _resp) @login_not_required def edit(_resp, id, **product_properties): cmd = Product_facade.update_product_cmd(id, **product_properties) return _save_or_update_json_response(cmd, _resp) def delete(_resp, id): cmd = Product_facade.delete_product_cmd(id) try: cmd() except CommandExecutionException: _resp.status_code = 500 return JsonResponse(cmd.errors) def _save_or_update_json_response(cmd, _resp): try: product = cmd() except CommandExecutionException: _resp.status_code = 500 return JsonResponse(cmd.errors) product_form = Product_facade.product_form() return JsonResponse(product_form.fill_with_model(product))
mit
RadoChervenkov/Football-League-Management-System
Source/FootballLeagueManagementSystem/Web/FLMS.Web/GlimpseSecurityPolicy.cs
1133
/* // Uncomment this class to provide custom runtime policy for Glimpse using Glimpse.AspNet.Extensions; using Glimpse.Core.Extensibility; namespace FLMS.Web { public class GlimpseSecurityPolicy:IRuntimePolicy { public RuntimePolicy Execute(IRuntimePolicyContext policyContext) { // You can perform a check like the one below to control Glimpse's permissions within your application. // More information about RuntimePolicies can be found at http://getglimpse.com/Help/Custom-Runtime-Policy // var httpContext = policyContext.GetHttpContext(); // if (!httpContext.User.IsInRole("Administrator")) // { // return RuntimePolicy.Off; // } return RuntimePolicy.On; } public RuntimeEvent ExecuteOn { // The RuntimeEvent.ExecuteResource is only needed in case you create a security policy // Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; } } } } */
mit
feitian124/xdomain
app/app.js
335
import Ember from 'ember'; import Resolver from 'ember/resolver'; import loadInitializers from 'ember/load-initializers'; Ember.MODEL_FACTORY_INJECTIONS = true; var App = Ember.Application.extend({ modulePrefix: 'xdomain', // TODO: loaded via config Resolver: Resolver }); loadInitializers(App, 'xdomain'); export default App;
mit
lucasmichot/Carbon
tests/Localization/EnToTest.php
11446
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\Localization; /** * @group localization */ class EnToTest extends LocalizationTestCase { public const LOCALE = 'en_TO'; // English public const CASES = [ // Carbon::parse('2018-01-04 00:00:00')->addDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Tomorrow at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Saturday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Sunday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Monday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Tuesday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Wednesday at 12:00 AM', // Carbon::parse('2018-01-05 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-05 00:00:00')) 'Thursday at 12:00 AM', // Carbon::parse('2018-01-06 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-06 00:00:00')) 'Friday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Tuesday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Wednesday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(4)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Thursday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(5)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Friday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(6)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Saturday at 12:00 AM', // Carbon::now()->subDays(2)->calendar() 'Last Sunday at 8:49 PM', // Carbon::parse('2018-01-04 00:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Yesterday at 10:00 PM', // Carbon::parse('2018-01-04 12:00:00')->subHours(2)->calendar(Carbon::parse('2018-01-04 12:00:00')) 'Today at 10:00 AM', // Carbon::parse('2018-01-04 00:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Today at 2:00 AM', // Carbon::parse('2018-01-04 23:00:00')->addHours(2)->calendar(Carbon::parse('2018-01-04 23:00:00')) 'Tomorrow at 1:00 AM', // Carbon::parse('2018-01-07 00:00:00')->addDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Tuesday at 12:00 AM', // Carbon::parse('2018-01-08 00:00:00')->subDay()->calendar(Carbon::parse('2018-01-08 00:00:00')) 'Yesterday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(1)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Yesterday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Last Tuesday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(3)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Last Monday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(4)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Last Sunday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(5)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Last Saturday at 12:00 AM', // Carbon::parse('2018-01-04 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-04 00:00:00')) 'Last Friday at 12:00 AM', // Carbon::parse('2018-01-03 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-03 00:00:00')) 'Last Thursday at 12:00 AM', // Carbon::parse('2018-01-02 00:00:00')->subDays(6)->calendar(Carbon::parse('2018-01-02 00:00:00')) 'Last Wednesday at 12:00 AM', // Carbon::parse('2018-01-07 00:00:00')->subDays(2)->calendar(Carbon::parse('2018-01-07 00:00:00')) 'Last Friday at 12:00 AM', // Carbon::parse('2018-01-01 00:00:00')->isoFormat('Qo Mo Do Wo wo') '1st 1st 1st 1st 1st', // Carbon::parse('2018-01-02 00:00:00')->isoFormat('Do wo') '2nd 1st', // Carbon::parse('2018-01-03 00:00:00')->isoFormat('Do wo') '3rd 1st', // Carbon::parse('2018-01-04 00:00:00')->isoFormat('Do wo') '4th 1st', // Carbon::parse('2018-01-05 00:00:00')->isoFormat('Do wo') '5th 1st', // Carbon::parse('2018-01-06 00:00:00')->isoFormat('Do wo') '6th 1st', // Carbon::parse('2018-01-07 00:00:00')->isoFormat('Do wo') '7th 1st', // Carbon::parse('2018-01-11 00:00:00')->isoFormat('Do wo') '11th 2nd', // Carbon::parse('2018-02-09 00:00:00')->isoFormat('DDDo') '40th', // Carbon::parse('2018-02-10 00:00:00')->isoFormat('DDDo') '41st', // Carbon::parse('2018-04-10 00:00:00')->isoFormat('DDDo') '100th', // Carbon::parse('2018-02-10 00:00:00', 'Europe/Paris')->isoFormat('h:mm a z') '12:00 am CET', // Carbon::parse('2018-02-10 00:00:00')->isoFormat('h:mm A, h:mm a') '12:00 AM, 12:00 am', // Carbon::parse('2018-02-10 01:30:00')->isoFormat('h:mm A, h:mm a') '1:30 AM, 1:30 am', // Carbon::parse('2018-02-10 02:00:00')->isoFormat('h:mm A, h:mm a') '2:00 AM, 2:00 am', // Carbon::parse('2018-02-10 06:00:00')->isoFormat('h:mm A, h:mm a') '6:00 AM, 6:00 am', // Carbon::parse('2018-02-10 10:00:00')->isoFormat('h:mm A, h:mm a') '10:00 AM, 10:00 am', // Carbon::parse('2018-02-10 12:00:00')->isoFormat('h:mm A, h:mm a') '12:00 PM, 12:00 pm', // Carbon::parse('2018-02-10 17:00:00')->isoFormat('h:mm A, h:mm a') '5:00 PM, 5:00 pm', // Carbon::parse('2018-02-10 21:30:00')->isoFormat('h:mm A, h:mm a') '9:30 PM, 9:30 pm', // Carbon::parse('2018-02-10 23:00:00')->isoFormat('h:mm A, h:mm a') '11:00 PM, 11:00 pm', // Carbon::parse('2018-01-01 00:00:00')->ordinal('hour') '0th', // Carbon::now()->subSeconds(1)->diffForHumans() '1 second ago', // Carbon::now()->subSeconds(1)->diffForHumans(null, false, true) '1s ago', // Carbon::now()->subSeconds(2)->diffForHumans() '2 seconds ago', // Carbon::now()->subSeconds(2)->diffForHumans(null, false, true) '2s ago', // Carbon::now()->subMinutes(1)->diffForHumans() '1 minute ago', // Carbon::now()->subMinutes(1)->diffForHumans(null, false, true) '1m ago', // Carbon::now()->subMinutes(2)->diffForHumans() '2 minutes ago', // Carbon::now()->subMinutes(2)->diffForHumans(null, false, true) '2m ago', // Carbon::now()->subHours(1)->diffForHumans() '1 hour ago', // Carbon::now()->subHours(1)->diffForHumans(null, false, true) '1h ago', // Carbon::now()->subHours(2)->diffForHumans() '2 hours ago', // Carbon::now()->subHours(2)->diffForHumans(null, false, true) '2h ago', // Carbon::now()->subDays(1)->diffForHumans() '1 day ago', // Carbon::now()->subDays(1)->diffForHumans(null, false, true) '1d ago', // Carbon::now()->subDays(2)->diffForHumans() '2 days ago', // Carbon::now()->subDays(2)->diffForHumans(null, false, true) '2d ago', // Carbon::now()->subWeeks(1)->diffForHumans() '1 week ago', // Carbon::now()->subWeeks(1)->diffForHumans(null, false, true) '1w ago', // Carbon::now()->subWeeks(2)->diffForHumans() '2 weeks ago', // Carbon::now()->subWeeks(2)->diffForHumans(null, false, true) '2w ago', // Carbon::now()->subMonths(1)->diffForHumans() '1 month ago', // Carbon::now()->subMonths(1)->diffForHumans(null, false, true) '1mo ago', // Carbon::now()->subMonths(2)->diffForHumans() '2 months ago', // Carbon::now()->subMonths(2)->diffForHumans(null, false, true) '2mos ago', // Carbon::now()->subYears(1)->diffForHumans() '1 year ago', // Carbon::now()->subYears(1)->diffForHumans(null, false, true) '1yr ago', // Carbon::now()->subYears(2)->diffForHumans() '2 years ago', // Carbon::now()->subYears(2)->diffForHumans(null, false, true) '2yrs ago', // Carbon::now()->addSecond()->diffForHumans() '1 second from now', // Carbon::now()->addSecond()->diffForHumans(null, false, true) '1s from now', // Carbon::now()->addSecond()->diffForHumans(Carbon::now()) '1 second after', // Carbon::now()->addSecond()->diffForHumans(Carbon::now(), false, true) '1s after', // Carbon::now()->diffForHumans(Carbon::now()->addSecond()) '1 second before', // Carbon::now()->diffForHumans(Carbon::now()->addSecond(), false, true) '1s before', // Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true) '1 second', // Carbon::now()->addSecond()->diffForHumans(Carbon::now(), true, true) '1s', // Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true) '2 seconds', // Carbon::now()->diffForHumans(Carbon::now()->addSecond()->addSecond(), true, true) '2s', // Carbon::now()->addSecond()->diffForHumans(null, false, true, 1) '1s from now', // Carbon::now()->addMinute()->addSecond()->diffForHumans(null, true, false, 2) '1 minute 1 second', // Carbon::now()->addYears(2)->addMonths(3)->addDay()->addSecond()->diffForHumans(null, true, true, 4) '2yrs 3mos 1d 1s', // Carbon::now()->addYears(3)->diffForHumans(null, null, false, 4) '3 years from now', // Carbon::now()->subMonths(5)->diffForHumans(null, null, true, 4) '5mos ago', // Carbon::now()->subYears(2)->subMonths(3)->subDay()->subSecond()->diffForHumans(null, null, true, 4) '2yrs 3mos 1d 1s ago', // Carbon::now()->addWeek()->addHours(10)->diffForHumans(null, true, false, 2) '1 week 10 hours', // Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2) '1 week 6 days', // Carbon::now()->addWeek()->addDays(6)->diffForHumans(null, true, false, 2) '1 week 6 days', // Carbon::now()->addWeek()->addDays(6)->diffForHumans(["join" => true, "parts" => 2]) '1 week and 6 days from now', // Carbon::now()->addWeeks(2)->addHour()->diffForHumans(null, true, false, 2) '2 weeks 1 hour', // Carbon::now()->addHour()->diffForHumans(["aUnit" => true]) 'an hour from now', // CarbonInterval::days(2)->forHumans() '2 days', // CarbonInterval::create('P1DT3H')->forHumans(true) '1d 3h', ]; }
mit
atmanager/atmanager
src/ATManager/AtBundle/Controller/AtecnicaController.php
18322
<?php namespace ATManager\AtBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use ATManager\AtBundle\Entity\AtTecnico; use ATManager\AtBundle\Entity\AtHistorico; use ATManager\FrontendBundle\Form\AtBuscadorInicialType; use ATManager\FrontendBundle\Form\AtBuscadorInicialDeTecnicosType; use ATManager\AtBundle\Form\AtBuscadorCasosExitosType; class AtecnicaController extends Controller { public function buscadorAction(Request $request) { /* Asumimos que este es la funcion que inicia un proceso en cascada que incluye: 1) Escoger un estadio para recuperar las AT 2) Visualizar las AT por el estadio escogido 3) Asignar un tecnico responsable a la AT escogida (link "Aceptar") 4) Regresar al punto 2, luego del paso 3. Si queremos regresar al punto 2, guardando la URL en una variable de sesśion debemos utilizar las siguientes definiciones: 1, 2, 3 */ // [1] obtiene el string de la URL que nos muestra el punto 2, // guardandola en la variable $retorno. $retorno = 'http://'.$request->getHost().$request->getRequestUri(); // [2] inicalizamos la variable de session global: $sesion = $this->get('session'); // [3] le asignamos el valor obtenido $sesion->set('retorno',$retorno); // 3 /* en esta funcion solo se define la variable de session la que usará en otras funciones del controlador como por ejemplo: generoAgendaTecnicoAction(Request $request, $id)*/ $em = $this->getDoctrine()->getManager(); $clas_esta = $em->getRepository('BackendBundle:EstadioClasif')->findOneByIniciaAt(true); $esta = $em->getRepository('BackendBundle:Estadio')->findOneByClasificacion($clas_esta); $form = $this->createForm(new AtBuscadorInicialType(), null, array( 'method' => 'GET' )); // asigna al select del estadio del type, el estadio que eligio el usuario $form->get('estadio')->setData($esta); $form->handleRequest($request); $objt = $this->get('security.context')->getToken()->getUser(); $sector=$objt->getSector(); if ($form->isValid()) { $entities =array(); /*$objt = $this->get('security.context')->getToken()->getUser(); $sector=$objt->getSector();*/ $estadio=$form->get('estadio')->getData(); $entities = $em->getRepository('FrontendBundle:At')->findByFiltroPorSectorEstadio($sector, $estadio); $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('FrontendBundle:At:viewStarting.html.twig', array( 'form'=>$form->createView(), 'entities' => $entities, 'estadio' => $estadio )); } return $this->render('AtBundle:Atecnica:find.html.twig', array( 'form'=>$form->createView(), 'sector'=>$sector )); } /* Devuelve las atenciones atendidas por los técnicos (mapatecnico) del sector. Ultima Modificación: Octubre 13, 2014 Autor: Dario */ public function generoAgendaTecnicoAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('FrontendBundle:At')->find($id); $objtl = $this->get('security.context')->getToken()->getUser(); $opciones['sector'] = $objtl->getSector(); /* $mapatec = $em->getRepository('AtBundle:AtTecnico')->findBySector($opciones['sector']);*/ $mapatec = $em->getRepository('AtBundle:AtTecnico')->MapaTecnico($opciones['sector']); return $this->render('AtBundle:Atecnica:newAtTecnico.html.twig', array( 'entity'=>$entity, 'mapatec'=>$mapatec )); } /* Agrega a la coleccion de At Tecnico, el tecnico ppal de una AT Agrega a la colección de Historico la primer evolución (Diagnostico) Agosto 2014 Dario/Juan */ public function asignarTecnicoATAction($at,$tec) { /* recupero la variable de session definida en: buscadorAction()*/ $sesion = $this->get('session'); /*la asigno a una variable que utilizare como parametro para redireccionar al finaliza el proceso*/ $ret = $sesion->get('retorno'); /*--*/ $objatt=new AtTecnico(); $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('FrontendBundle:At')->find($at); $objtl = $this->get('security.context')->getToken()->getUser(); $opciones['sector'] = $objtl->getSector(); try{ $objt= $em->getRepository('BackendBundle:Tecnico')->findOneById($tec); $rol = $em->getRepository('BackendBundle:Rol')->findOneByPrincipal(true); $objatt->setAt($entity); $objatt->setRol($rol); $objatt->setTecnico($objt); $em->persist($objatt); $ath= new AtHistorico(); $ath->setAt($entity); $clas_esta = $em->getRepository('BackendBundle:EstadioClasif')->findOneByDiagnosAt(true); $estadio = $em->getRepository('BackendBundle:Estadio')->findOneByClasificacion($clas_esta); $ath->setEstadio($estadio); $ath->setComentario('At Aceptada. Agregada a la agenda de: '.$objt->getNombre()); // hasta aquí guarda el historico de la at asignada $em->persist($ath); $em->flush(); if(isset($_GET['mail'])) { $message = \Swift_Message::newInstance() ->setSubject('Envio de at') ->setFrom('atmanagerpro@gmail.com') ->setTo($objt->getEmail()) ->setBody("tienes una At pendiente: ".$entity->getId()." ".$entity->getDescripcion()); $this->get('mailer')->send($message); } $this->get('session')->getFlashBag()->add('success','Solicitud '.$entity.' aceptada !!'); return $this->redirect($ret); } catch(\Exception $ex){ $this->get('session')->getFlashBag()->add('error',$ex->getMessage()); return $this->redirect($ret); } } public function cancelarAction($id) { /* recupero la variable de session definida en: buscadorAction()*/ $sesion = $this->get('session'); /*la asigno a una variable que utilizare como parametro para redireccionar al finaliza el proceso*/ $ret = $sesion->get('retorno'); $fechafin=new \DateTime(); try{ $em = $this->getDoctrine()->getManager(); $objtl = $this->get('security.context')->getToken()->getUser(); $entity = $em->getRepository('FrontendBundle:At')->find($id); $entity->setFechafin($fechafin); $em->persist($entity); // $ath= new atHistorico(); $ath->setAt($entity); $clas_esta = $em->getRepository('BackendBundle:EstadioClasif')->findOneByCancelaAt(true); $estadio = $em->getRepository('BackendBundle:Estadio')->findOneByClasificacion($clas_esta); $ath->setEstadio($estadio); $ath->setComentario('At Cancelada por:,'.' '.$objtl->getNombre() ); $em->persist($ath); // $em->flush(); $this->get('session')->getFlashBag()->add('success','Se canceló AT'); return $this->redirect($ret); } catch(\Exception $ex){ $this->get('session')->getFlashBag()->add('error',$ex->getMessage()); return $this->redirect($ret); } } // Fecha: 24/08/2014 // Busca las ats del técnico logueado public function buscarAgendaTecnicoAction(Request $request) { $retorno = 'http://'.$request->getHost().$request->getRequestUri(); $sesion = $this->get('session'); $sesion->set('retorno',$retorno); /* ------------------------------------*/ $objt = $this->get('security.context')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); // proponer el estadio "En diagnostico" $clas_esta = $em->getRepository('BackendBundle:EstadioClasif')->findOneByDiagnosAt(true); $esta = $em->getRepository('BackendBundle:Estadio')->findOneByClasificacion($clas_esta); $form = $this->createForm(new AtBuscadorInicialType(), null, array( 'method' => 'GET' )); // asigna al select estadio del type, el estadio que eligio el usuario $form->get('estadio')->setData($esta); $form->handleRequest($request); if ($form->isValid()) { $entities = array(); $sector=$objt->getSector(); $rol=$em->getRepository('BackendBundle:Rol')->findOneByPrincipal(true); $estadio=$form->get('estadio')->getData(); $entities = $em->getRepository('FrontendBundle:At')->findByFiltroPorTecnico($objt,$rol,$estadio); $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('AtBundle:Atecnica:veragendatecnico.html.twig', array( 'entities' => $entities, 'tecnico' => $objt, 'retorno' =>$retorno, 'volver' => 'atecnica_buscarAgendaTecnico' )); } return $this->render('AtBundle:Atecnica:findagenda.html.twig', array( 'form'=>$form->createView() )); } public function showAction($id) { /* recupero la variable de session definida en: buscadorAction()*/ $sesion = $this->get('session'); /*la asigno a una variable que utilizare como parametro para redireccionar al finaliza el proceso*/ $ret = $sesion->get('retorno'); $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('FrontendBundle:At')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find At entity.'); } return $this->render('AtBundle:Atecnica:atshow.html.twig', array ( 'entity' => $entity, 'ret' => $ret ) ); } // Fecha: 24/09/2014 // Busca descripcion de tareas de AT Cerradas public function baseConocimientoAction(Request $request) { $retorno = 'http://'.$request->getHost().$request->getRequestUri(); $sesion = $this->get('session'); $sesion->set('retorno',$retorno); /* ------------------------------------*/ $objt = $this->get('security.context')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $form = $this->createForm(new AtBuscadorCasosExitosType(),null,array( 'method' => 'GET' )); $form->handleRequest($request); if ($form->isValid()) { $entities =array(); $falla=$form->get('falla')->getData(); $descripcion=$form->get('descripcion')->getData(); $numAt=$form->get('numero')->getData(); if($numAt=="") { if($falla=="" and $descripcion=="") { $entities =array(); } else{ $entities = $em->getRepository('FrontendBundle:At')->findByCasosPorFallaDescripcion($falla,$descripcion); } }else{ $entities = $em->getRepository('FrontendBundle:At')->findByCasosPorNumeroAt($numAt); } $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('AtBundle:Atecnica:basecono.html.twig', array( 'entities' => $entities, 'retorno' =>$retorno )); } return $this->render('AtBundle:Atecnica:findcono.html.twig', array( 'form'=>$form->createView() )); } // Fecha: 24/09/2014 // Fec. Edición: 15/10/2014 // Busca descripcion de tareas de AT Cerradas public function baseConocimientoAction2() { $em = $this->getDoctrine()->getManager(); $sintomas= array(); $ats = $em->getRepository('FrontendBundle:At')->findAll(); foreach($ats as $at){ if($at->miUltimoEstadio()->getClasificacion()->getFinalizaAt()){ $partes=explode(" ",$at->getDescripcion()); foreach($partes as $palabras){ $cambio= strtoupper($palabras); if(strlen($cambio)>3){ if(!array_search($cambio, $sintomas)){ array_push($sintomas, $cambio); } } } } } return $this->render('AtBundle:Atecnica:findcono.html.twig', array( 'sintomas'=>$sintomas )); } public function obtenerXsintomasAction($sintoma) { $retorno = 'http://'.$this->getRequest()->getHost().$this->getRequest()->getRequestUri(); $sesion = $this->get('session'); $sesion->set('retorno',$retorno); $em = $this->getDoctrine()->getManager(); $entities=$em->getRepository('FrontendBundle:At')->findByCasosXSintoma($sintoma); $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('AtBundle:Atecnica:basecono.html.twig', array( 'entities' => $entities, 'retorno' =>$retorno ) ); } public function reasignotecAction($id) { /* recupero la variable de session definida en: buscadorAction()*/ $sesion = $this->get('session'); /*la asigno a una variable que utilizare como parametro para redireccionar al finaliza el proceso*/ $ret = $sesion->get('retorno'); /*--*/ $tecnicos=array(); $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('FrontendBundle:At')->find($id); $tecnicos = $em->getRepository('AtBundle:AtTecnico')->TecnicosEnAt($entity); return $this->render('AtBundle:Atecnica:AtTecnico.html.twig', array( 'entity'=>$entity, 'tecnicos'=>$tecnicos, 'ret'=>$ret )); } public function verDetalleAtAction($id) { /* recupero la variable de session definida en: buscadorAction()*/ $sesion = $this->get('session'); /*la asigno a una variable que utilizare como parametro para redireccionar al finaliza el proceso*/ $ret = $sesion->get('retorno'); /*--*/ $tecnicos=array(); $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('FrontendBundle:At')->find($id); return $this->render('AtBundle:Atecnica:verdetalleat.html.twig', array( 'entity'=>$entity, 'ret'=>$ret )); } /* Fecha: 10/06/2015 busca las at del tecnico JDS logueado */ public function buscarAgendaTodosLosTecnicosAction(Request $request) { $retorno = 'http://'.$request->getHost().$request->getRequestUri(); $sesion = $this->get('session'); $sesion->set('retorno',$retorno); /* ------------------------------------*/ $objt = $this->get('security.context')->getToken()->getUser(); $sector=$objt->getSector(); $em = $this->getDoctrine()->getManager(); $clas_esta = $em->getRepository('BackendBundle:EstadioClasif')->findOneByDiagnosAt(true); $esta = $em->getRepository('BackendBundle:Estadio')->findOneByClasificacion($clas_esta); $form = $this->createForm(new AtBuscadorInicialDeTecnicosType($sector), null, array( 'method' => 'GET' )); // asigna al select del estadio del type, el estadio que eligio el usuario $form->get('estadio')->setData($esta); $form->handleRequest($request); if ($form->isValid()) { $entities =array(); $sector=$objt->getSector(); $rol=$em->getRepository('BackendBundle:Rol')->findOneByPrincipal(true); $estadio=$form->get('estadio')->getData(); $objt=$form->get('tecnico')->getData(); /* mejorar esto*/ if($estadio){ $entities = $em->getRepository('FrontendBundle:At')->findByFiltroPorTecnico($objt,$rol,$estadio); }else{ $entities = $em->getRepository('FrontendBundle:At')->findByFiltroPorTecnicoSinEstadio($objt,$rol); } $paginator = $this->get('knp_paginator'); $entities = $paginator->paginate($entities, $this->getRequest()->query->get('pagina',1), 10); return $this->render('AtBundle:Atecnica:veragendatecnico.html.twig', array( 'entities' => $entities, 'tecnico' => $objt, 'retorno' =>$retorno, 'volver' => 'atecnica_buscarAgendaTodosLosTecnicos' )); } return $this->render('AtBundle:Atecnica:findagenda.html.twig', array( 'form'=>$form->createView() )); } }
mit
MicrosoftLearning/20486-DevelopingASPNETMVCWebApplications
Allfiles/20486C/Mod12/LabFiles/PhotoSharingApplication_12_begin/PhotoSharingApplication/Scripts/SlideShow.js
13864
var percentIncrement; var percentCurrent = 100; function slideSwitch() { percentCurrent += percentIncrement; if (percentCurrent > 100) { percentCurrent = percentIncrement; } $('#slideshow-progress-bar').progressbar({ value: percentCurrent }); var $activeCard = $('#slide-show DIV.active-card'); if ($activeCard.length == 0) { $activeCard = $('#slide-show DIV.slide-show-card:last'); } var $nextCard = $activeCard.next(); if ($nextCard.length == 0) { $nextCard = $('#slide-show DIV.slide-show-card:first'); } $activeCard.addClass('last-active-card'); $nextCard.css({ opacity: 0.0 }); $nextCard.addClass('active-card'); $nextCard.animate({ opacity: 1.0 }, 1000, function () { $activeCard.removeClass('active-card last-active-card'); }); } function calculateIncrement() { var cardCount = $('#slide-show DIV.slide-show-card').length; percentIncrement = 100 / cardCount; $('#slideshow-progress-bar').progressbar({ value: 100 }); } $(document).ready(function () { calculateIncrement(); setInterval("slideSwitch()", 5000); }); // SIG // Begin signature block // SIG // MIIdkQYJKoZIhvcNAQcCoIIdgjCCHX4CAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFHUn+GodKIdT // SIG // FxBZJoM43zyw4i/hoIIYUzCCBMIwggOqoAMCAQICEzMA // SIG // AADEbnbQTT3+qWUAAAAAAMQwDQYJKoZIhvcNAQEFBQAw // SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj // SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTE2MDkwNzE3 // SIG // NTg1MloXDTE4MDkwNzE3NTg1MlowgbIxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xDDAKBgNVBAsTA0FPQzEnMCUGA1UECxMe // SIG // bkNpcGhlciBEU0UgRVNOOjIxMzctMzdBMC00QUFBMSUw // SIG // IwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2 // SIG // aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC // SIG // AQEAqAOaxVKZdoyjPfy9uhrlY+gXqPO2HT08Lji9AvkD // SIG // m7a2L4oeywzQwHli8PsGJUpAJn5mklxaYkRzNXQc6vlX // SIG // LhfGBpmZvyyliAAd1U4+nX9OSR/JILaeIDdpsj00fq5M // SIG // KDKEN5rke829Z7zYi7BKYCdhLsF+TP+9bmKyugxwD22w // SIG // 968hYs2QH6mHBlFrg4RBOmVfqJ3sVLpWegyuiKC47UL1 // SIG // Gx9WTBFrzVU5Yj2DoDWC0yHCeZmKYZ1DAAaCnbxg3FaU // SIG // php+rCyhoIhQvNp7p/Ye5KI+/maUhxJbC8IVkIhlVgkV // SIG // ZPGTG3nPqobvv/R8M3VSWG+Bzm5sDQ2qqantewIDAQAB // SIG // o4IBCTCCAQUwHQYDVR0OBBYEFIgFI+sRvRCO+4uWphUm // SIG // a179Vd5QMB8GA1UdIwQYMBaAFCM0+NlSRnAK7UD7dvuz // SIG // K7DDNbMPMFQGA1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly9j // SIG // cmwubWljcm9zb2Z0LmNvbS9wa2kvY3JsL3Byb2R1Y3Rz // SIG // L01pY3Jvc29mdFRpbWVTdGFtcFBDQS5jcmwwWAYIKwYB // SIG // BQUHAQEETDBKMEgGCCsGAQUFBzAChjxodHRwOi8vd3d3 // SIG // Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29m // SIG // dFRpbWVTdGFtcFBDQS5jcnQwEwYDVR0lBAwwCgYIKwYB // SIG // BQUHAwgwDQYJKoZIhvcNAQEFBQADggEBAHA4fpI5l7wp // SIG // 6BDuQHFFn6eP+H1gqogUC/LlBaunLgbmKfDC+FMh0iyj // SIG // TzqCZs88tTk9xhRmK5qa4DunNndbc7kmjdx3hRhDVw25 // SIG // +zdkQbybUpdFJGoUsmpOE7EVD5P1sDENBjhjW8Y6Jazk // SIG // eNS1bEph1Z5/CFgzglgY9XPtY5D5MxudYwogJ1sx1NUN // SIG // uQP9Lca4S2IzbSOD939E9L7+uV+62QCM93nEEvxIJZgA // SIG // 30JP86y4CqiXcWSst7V0u/t+cyKw3oHQB9hu3d47wjU4 // SIG // 2ra1e3MSh/mV/aBLBZddLof1PNygNkIkCUDLW4xks0Fd // SIG // sUaXDX9hqRwUT1tLCuMi98MwggYAMIID6KADAgECAhMz // SIG // AAAAww6bp9iy3PcsAAAAAADDMA0GCSqGSIb3DQEBCwUA // SIG // MH4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5n // SIG // dG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVN // SIG // aWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01p // SIG // Y3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBIDIwMTEwHhcN // SIG // MTcwODExMjAyMDI0WhcNMTgwODExMjAyMDI0WjB0MQsw // SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ // SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z // SIG // b2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNyb3Nv // SIG // ZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUA // SIG // A4IBDwAwggEKAoIBAQC7V9c40bEGf0ktqW2zY596urY6 // SIG // IVu0mK6N1KSBoMV1xSzvgkAqt4FTd/NjAQq8zjeEA0BD // SIG // V4JLzu0ftv2AbcnCkV0Fx9xWWQDhDOtX3v3xuJAnv3VK // SIG // /HWycli2xUibM2IF0ZWUpb85Iq2NEk1GYtoyGc6qIlxW // SIG // SLFvRclndmJdMIijLyjFH1Aq2YbbGhElgcL09Wcu53kd // SIG // 9eIcdfROzMf8578LgEcp/8/NabEMC2DrZ+aEG5tN/W1H // SIG // OsfZwWFh8pUSoQ0HrmMh2PSZHP94VYHupXnoIIJfCtq1 // SIG // UxlUAVcNh5GNwnzxVIaA4WLbgnM+Jl7wQBLSOdUmAw2F // SIG // iDFfCguLAgMBAAGjggF/MIIBezAfBgNVHSUEGDAWBgor // SIG // BgEEAYI3TAgBBggrBgEFBQcDAzAdBgNVHQ4EFgQUpxNd // SIG // HyGJVegD7p4XNuryVIg1Ga8wUQYDVR0RBEowSKRGMEQx // SIG // DDAKBgNVBAsTA0FPQzE0MDIGA1UEBRMrMjMwMDEyK2M4 // SIG // MDRiNWVhLTQ5YjQtNDIzOC04MzYyLWQ4NTFmYTIyNTRm // SIG // YzAfBgNVHSMEGDAWgBRIbmTlUAXTgqoXNzcitW2oynUC // SIG // lTBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpb3BzL2NybC9NaWNDb2RTaWdQ // SIG // Q0EyMDExXzIwMTEtMDctMDguY3JsMGEGCCsGAQUFBwEB // SIG // BFUwUzBRBggrBgEFBQcwAoZFaHR0cDovL3d3dy5taWNy // SIG // b3NvZnQuY29tL3BraW9wcy9jZXJ0cy9NaWNDb2RTaWdQ // SIG // Q0EyMDExXzIwMTEtMDctMDguY3J0MAwGA1UdEwEB/wQC // SIG // MAAwDQYJKoZIhvcNAQELBQADggIBAE2XTzR+8XCTnOPV // SIG // GkucEX5rJsSlJPTfRNQkurNqCImZmssx53Cb/xQdsAc5 // SIG // f+QwOxMi3g7IlWe7bn74fJWkkII3k6aD00kCwaytWe+R // SIG // t6dmAA6iTCXU3OddBwLKKDRlOzmDrZUqjsqg6Ag6HP4+ // SIG // e0BJlE2OVCUK5bHHCu5xN8abXjb1p0JE+7yHsA3ANdkm // SIG // h1//Z+8odPeKMAQRimfMSzVgaiHnw40Hg16bq51xHykm // SIG // CRHU9YLT0jYHKa7okm2QfwDJqFvu0ARl+6EOV1PM8piJ // SIG // 858Vk8gGxGNSYQJPV0gc9ft1Esq1+fTCaV+7oZ0NaYMn // SIG // 64M+HWsxw+4O8cSEQ4fuMZwGADJ8tyCKuQgj6lawGNSy // SIG // vRXsN+1k02sVAiPGijOHOtGbtsCWWSygAVOEAV/ye8F6 // SIG // sOzU2FL2X3WBRFkWOCdTu1DzXnHf99dR3DHVGmM1Kpd+ // SIG // n2Y3X89VM++yyrwsI6pEHu77Z0i06ELDD4pRWKJGAmEm // SIG // Whm/XJTpqEBw51swTHyA1FBnoqXuDus9tfHleR7h9VgZ // SIG // b7uJbXjiIFgl/+RIs+av8bJABBdGUNQMbJEUfe7K4vYm // SIG // 3hs7BGdRLg+kF/dC/z+RiTH4p7yz5TpS3Cozf0pkkWXY // SIG // ZRG222q3tGxS/L+LcRbELM5zmqDpXQjBRUWlKYbsATFt // SIG // XnTGVjELMIIGBzCCA++gAwIBAgIKYRZoNAAAAAAAHDAN // SIG // BgkqhkiG9w0BAQUFADBfMRMwEQYKCZImiZPyLGQBGRYD // SIG // Y29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0w // SIG // KwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0 // SIG // ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1MzA5WhcNMjEw // SIG // NDAzMTMwMzA5WjB3MQswCQYDVQQGEwJVUzETMBEGA1UE // SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe // SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw // SIG // HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0Ew // SIG // ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCf // SIG // oWyx39tIkip8ay4Z4b3i48WZUSNQrc7dGE4kD+7Rp9FM // SIG // rXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr6Hu97IkHD/cO // SIG // BJjwicwfyzMkh53y9GccLPx754gd6udOo6HBI1PKjfpF // SIG // zwnQXq/QsEIEovmmbJNn1yjcRlOwhtDlKEYuJ6yGT1VS // SIG // DOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd++NIT8wi3U21S // SIG // tEWQn0gASkdmEScpZqiX5NMGgUqi+YSnEUcUCYKfhO1V // SIG // eP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68eeEExd8yb3zuD // SIG // k6FhArUdDbH895uyAc4iS1T/+QXDwiALAgMBAAGjggGr // SIG // MIIBpzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQj // SIG // NPjZUkZwCu1A+3b7syuwwzWzDzALBgNVHQ8EBAMCAYYw // SIG // EAYJKwYBBAGCNxUBBAMCAQAwgZgGA1UdIwSBkDCBjYAU // SIG // DqyCYEBWJ5flJRP8KuEKU5VZ5KShY6RhMF8xEzARBgoJ // SIG // kiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJk/IsZAEZFglt // SIG // aWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jvc29mdCBSb290 // SIG // IENlcnRpZmljYXRlIEF1dGhvcml0eYIQea0WoUqgpa1M // SIG // c1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BBhj9odHRwOi8v // SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0 // SIG // cy9taWNyb3NvZnRyb290Y2VydC5jcmwwVAYIKwYBBQUH // SIG // AQEESDBGMEQGCCsGAQUFBzAChjhodHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY3Jvc29mdFJv // SIG // b3RDZXJ0LmNydDATBgNVHSUEDDAKBggrBgEFBQcDCDAN // SIG // BgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wDRDbd6bStd9vO // SIG // eVFNAbEudHFbbQwTq86+e4+4LtQSooxtYrhXAstOIBNQ // SIG // md16QOJXu69YmhzhHQGGrLt48ovQ7DsB7uK+jwoFyI1I // SIG // 4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mRKiQicPv2/OR4 // SIG // mS4N9wficLwYTp2OawpylbihOZxnLcVRDupiXD8WmIsg // SIG // P+IHGjL5zDFKdjE9K3ILyOpwPf+FChPfwgphjvDXuBfr // SIG // Tot/xTUrXqO/67x9C0J71FNyIe4wyrt4ZVxbARcKFA7S // SIG // 2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGysOUzU9nm/qhh6 // SIG // YinvopspNAZ3GmLJPR5tH4LwC8csu89Ds+X57H2146So // SIG // dDW4TsVxIxImdgs8UoxxWkZDFLyzs7BNZ8ifQv+AeSGA // SIG // nhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU2DKATCYqSCRf // SIG // WupW76bemZ3KOm+9gSd0BhHudiG/m4LBJ1S2sWo9iaF2 // SIG // YbRuoROmv6pH8BJv/YoybLL+31HIjCPJZr2dHYcSZAI9 // SIG // La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCleKuzoJZ1GtmS // SIG // hxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/Jmu5J4PcBZW+J // SIG // C33Iacjmbuqnl84xKf8OxVtc2E0bodj6L54/LlUWa8kT // SIG // o/0wggd6MIIFYqADAgECAgphDpDSAAAAAAADMA0GCSqG // SIG // SIb3DQEBCwUAMIGIMQswCQYDVQQGEwJVUzETMBEGA1UE // SIG // CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe // SIG // MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTIw // SIG // MAYDVQQDEylNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0 // SIG // ZSBBdXRob3JpdHkgMjAxMTAeFw0xMTA3MDgyMDU5MDla // SIG // Fw0yNjA3MDgyMTA5MDlaMH4xCzAJBgNVBAYTAlVTMRMw // SIG // EQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRt // SIG // b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRp // SIG // b24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p // SIG // bmcgUENBIDIwMTEwggIiMA0GCSqGSIb3DQEBAQUAA4IC // SIG // DwAwggIKAoICAQCr8PpyEBwurdhuqoIQTTS68rZYIZ9C // SIG // Gypr6VpQqrgGOBoESbp/wwwe3TdrxhLYC/A4wpkGsMg5 // SIG // 1QEUMULTiQ15ZId+lGAkbK+eSZzpaF7S35tTsgosw6/Z // SIG // qSuuegmv15ZZymAaBelmdugyUiYSL+erCFDPs0S3XdjE // SIG // LgN1q2jzy23zOlyhFvRGuuA4ZKxuZDV4pqBjDy3TQJP4 // SIG // 494HDdVceaVJKecNvqATd76UPe/74ytaEB9NViiienLg // SIG // Ejq3SV7Y7e1DkYPZe7J7hhvZPrGMXeiJT4Qa8qEvWeSQ // SIG // Oy2uM1jFtz7+MtOzAz2xsq+SOH7SnYAs9U5WkSE1JcM5 // SIG // bmR/U7qcD60ZI4TL9LoDho33X/DQUr+MlIe8wCF0JV8Y // SIG // KLbMJyg4JZg5SjbPfLGSrhwjp6lm7GEfauEoSZ1fiOIl // SIG // XdMhSz5SxLVXPyQD8NF6Wy/VI+NwXQ9RRnez+ADhvKwC // SIG // gl/bwBWzvRvUVUvnOaEP6SNJvBi4RHxF5MHDcnrgcuck // SIG // 379GmcXvwhxX24ON7E1JMKerjt/sW5+v/N2wZuLBl4F7 // SIG // 7dbtS+dJKacTKKanfWeA5opieF+yL4TXV5xcv3coKPHt // SIG // bcMojyyPQDdPweGFRInECUzF1KVDL3SV9274eCBYLBNd // SIG // YJWaPk8zhNqwiBfenk70lrC8RqBsmNLg1oiMCwIDAQAB // SIG // o4IB7TCCAekwEAYJKwYBBAGCNxUBBAMCAQAwHQYDVR0O // SIG // BBYEFEhuZOVQBdOCqhc3NyK1bajKdQKVMBkGCSsGAQQB // SIG // gjcUAgQMHgoAUwB1AGIAQwBBMAsGA1UdDwQEAwIBhjAP // SIG // BgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFHItOgIx // SIG // kEO5FAVO4eqnxzHRI4k0MFoGA1UdHwRTMFEwT6BNoEuG // SIG // SWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8w // SIG // M18yMi5jcmwwXgYIKwYBBQUHAQEEUjBQME4GCCsGAQUF // SIG // BzAChkJodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtp // SIG // L2NlcnRzL01pY1Jvb0NlckF1dDIwMTFfMjAxMV8wM18y // SIG // Mi5jcnQwgZ8GA1UdIASBlzCBlDCBkQYJKwYBBAGCNy4D // SIG // MIGDMD8GCCsGAQUFBwIBFjNodHRwOi8vd3d3Lm1pY3Jv // SIG // c29mdC5jb20vcGtpb3BzL2RvY3MvcHJpbWFyeWNwcy5o // SIG // dG0wQAYIKwYBBQUHAgIwNB4yIB0ATABlAGcAYQBsAF8A // SIG // cABvAGwAaQBjAHkAXwBzAHQAYQB0AGUAbQBlAG4AdAAu // SIG // IB0wDQYJKoZIhvcNAQELBQADggIBAGfyhqWY4FR5Gi7T // SIG // 2HRnIpsLlhHhY5KZQpZ90nkMkMFlXy4sPvjDctFtg/6+ // SIG // P+gKyju/R6mj82nbY78iNaWXXWWEkH2LRlBV2AySfNIa // SIG // SxzzPEKLUtCw/WvjPgcuKZvmPRul1LUdd5Q54ulkyUQ9 // SIG // eHoj8xN9ppB0g430yyYCRirCihC7pKkFDJvtaPpoLpWg // SIG // Kj8qa1hJYx8JaW5amJbkg/TAj/NGK978O9C9Ne9uJa7l // SIG // ryft0N3zDq+ZKJeYTQ49C/IIidYfwzIY4vDFLc5bnrRJ // SIG // OQrGCsLGra7lstnbFYhRRVg4MnEnGn+x9Cf43iw6IGmY // SIG // slmJaG5vp7d0w0AFBqYBKig+gj8TTWYLwLNN9eGPfxxv // SIG // FX1Fp3blQCplo8NdUmKGwx1jNpeG39rz+PIWoZon4c2l // SIG // l9DuXWNB41sHnIc+BncG0QaxdR8UvmFhtfDcxhsEvt9B // SIG // xw4o7t5lL+yX9qFcltgA1qFGvVnzl6UJS0gQmYAf0AAp // SIG // xbGbpT9Fdx41xtKiop96eiL6SJUfq/tHI4D1nvi/a7dL // SIG // l+LrdXga7Oo3mXkYS//WsyNodeav+vyL6wuA6mk7r/ww // SIG // 7QRMjt/fdW1jkT3RnVZOT7+AVyKheBEyIXrvQQqxP/uo // SIG // zKRdwaGIm1dxVk5IRcBCyZt2WwqASGv9eZ/BvW1taslS // SIG // cxMNelDNMYIEqjCCBKYCAQEwgZUwfjELMAkGA1UEBhMC // SIG // VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT // SIG // B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw // SIG // b3JhdGlvbjEoMCYGA1UEAxMfTWljcm9zb2Z0IENvZGUg // SIG // U2lnbmluZyBQQ0EgMjAxMQITMwAAAMMOm6fYstz3LAAA // SIG // AAAAwzAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM // SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor // SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBTEY18l02hV // SIG // Znt/KSiw9zLPnKbuNTBeBgorBgEEAYI3AgEMMVAwTqAm // SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A // SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t // SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQCGqc5r // SIG // hBWs92Zcc3Z+t+wNq/0TAkmGKBlvyIsUBtazsWU4oKfY // SIG // uvMZYy5pHB5w0i9klBpihQVYVWYBaHuU+2b0v9Jg8g6G // SIG // EksXmAWUSZrLG28c0H9jm4FUDT2xR1trJBprUXQSEK6C // SIG // zwCn7YECRrrbgegW2uOCgvw4T5Zo4Aro3H0I6PstS/vZ // SIG // LT09mExyrI2HUl1CxE6rK5OKhZJGc+/pH1Z6oBjOfOCR // SIG // CF38AgjJ8E2vg6mIiUsN1HA55qS/Bgvr89+nsLNgp8iw // SIG // LgduUk77YffZ07jMj75OMeTYI4wzGh5iqv5jWXpORh8e // SIG // G6gDoPkIT8y/66K6QJMGjZNB0YbmoYICKDCCAiQGCSqG // SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l // SIG // LVN0YW1wIFBDQQITMwAAAMRudtBNPf6pZQAAAAAAxDAJ // SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3 // SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTcxMjI5MDYyMzQz // SIG // WjAjBgkqhkiG9w0BCQQxFgQUUE2t38MU+qJXJVJhJ2+u // SIG // jXUz10wwDQYJKoZIhvcNAQEFBQAEggEAeqb/aKCATPRJ // SIG // /XGEBQ2kIjtmgCpvUS3f7IqOGv7FMQCSV55RcN+1ICKS // SIG // h+K2MOzudu59PIsS6booD+l3uBiepHRUdwbKBcEX71ws // SIG // a1SX4Ybh+m1bsKU5ylIa1PbG9Yfuw+iMJjEURwK8gB5x // SIG // DYd0Gc7u+KhPRe012Ru30wjptJdxEwJ7pUeOrmGlQdyX // SIG // 1HvTSTWDgOohA14MEVyYinTbfXf9Lta8BTMmcVyqKIYl // SIG // Xv+FsQ/yRM9oe9vDSmjx/35tdhXFsYmlPIOE5Q9fHPM4 // SIG // RqgwQRIUfymxvaNtN78CsS4B1707ZSn1SkrhEcwNzAmN // SIG // 1E/MuP2ZXo/kvytsq+nIBw== // SIG // End signature block
mit
ipjohnson/Grace
src/Grace/DependencyInjection/Impl/BaseExportLocatorScope.cs
11037
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using Grace.Data; using Grace.Data.Immutable; namespace Grace.DependencyInjection.Impl { /// <summary> /// base locator scope used by InjectionScope and LifetimeScope /// </summary> public abstract partial class BaseExportLocatorScope : DisposalScope, IExportLocatorScope { private ImmutableHashTree<object, object> _extraData = ImmutableHashTree<object, object>.Empty; private ImmutableHashTree<string, object> _lockObjects = ImmutableHashTree<string, object>.Empty; /// <summary> /// Cache delegate for base scopes /// </summary> protected readonly ActivationStrategyDelegateCache DelegateCache; /// <summary> /// Internal scoped storage used by Scoped Lifestyle /// </summary> protected ScopedStorage InternalScopedStorage = ScopedStorage.Empty; /// <summary> /// Default constructor /// </summary> /// <param name="parent">parent scope</param> /// <param name="name">name of scope</param> /// <param name="delegateCache">delegate cache</param> protected BaseExportLocatorScope(IExportLocatorScope parent, string name, ActivationStrategyDelegateCache delegateCache) { Parent = parent; ScopeName = name ?? ""; DelegateCache = delegateCache; } /// <summary> /// Parent for scope /// </summary> public IExportLocatorScope Parent { get; } /// <summary> /// Name of scope /// </summary> public string ScopeName { get; } /// <summary> /// Scope id /// </summary> public Guid ScopeId => (Guid)( GetExtraData("LocatorScopeId") ?? SetExtraData("LocatorScopeId", Guid.NewGuid(), false)); /// <summary> /// Keys for data /// </summary> public IEnumerable<object> Keys => _extraData.Keys; /// <summary> /// Values for data /// </summary> public IEnumerable<object> Values => _extraData.Values; /// <summary> /// Enumeration of all the key value pairs /// </summary> public IEnumerable<KeyValuePair<object, object>> KeyValuePairs => _extraData; /// <summary> /// Extra data associated with the injection request. /// </summary> /// <param name="key">key of the data object to get</param> /// <returns>data value</returns> public object GetExtraData(object key) { return _extraData.GetValueOrDefault(key); } /// <summary> /// Sets extra data on the locator scope /// </summary> /// <param name="key">object name</param> /// <param name="newValue">new object value</param> /// <param name="replaceIfExists"></param> /// <returns>the final value of key</returns> public object SetExtraData(object key, object newValue, bool replaceIfExists = true) { return ImmutableHashTree.ThreadSafeAdd(ref _extraData, key, newValue, replaceIfExists); } /// <summary> /// Gets a named object that can be used for locking /// </summary> /// <param name="lockName">lock name</param> /// <returns>lock</returns> public object GetLockObject(string lockName) { return _lockObjects.GetValueOrDefault(lockName) ?? ImmutableHashTree.ThreadSafeAdd(ref _lockObjects, lockName, new object()); } /// <summary> /// Locate a specific type /// </summary> /// <param name="type">type to locate</param> /// <returns>located instance</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public object Locate(Type type) { return DelegateCache.ExecuteActivationStrategyDelegate(type, this); } /// <summary> /// Locate type or return default value /// </summary> /// <param name="type"></param> /// <param name="defaultValue"></param> /// <returns></returns> public object LocateOrDefault(Type type, object defaultValue) { return DelegateCache.ExecuteActivationStrategyDelegateAllowNull(type, this) ?? defaultValue; } /// <summary> /// Locate type /// </summary> /// <typeparam name="T">type to locate</typeparam> /// <returns>located instance</returns> public T Locate<T>() { return (T)Locate(typeof(T)); } /// <summary> /// Locate or return default /// </summary> /// <typeparam name="T"></typeparam> /// <param name="defaultValue"></param> /// <returns></returns> public T LocateOrDefault<T>(T defaultValue = default(T)) { return (T)LocateOrDefault(typeof(T), defaultValue); } public T GetOrCreateScopedService<T>(int id, ActivationStrategyDelegate createDelegate, IInjectionContext context) { var initialStorage = InternalScopedStorage; var storage = initialStorage; while (!ReferenceEquals(storage, ScopedStorage.Empty)) { if (storage.Id == id) { return (T)storage.ScopedService; } storage = storage.Next; } var value = createDelegate(this, this, context); if (Interlocked.CompareExchange(ref InternalScopedStorage, new ScopedStorage { Id = id, Next = initialStorage, ScopedService = value }, initialStorage) == initialStorage) { return (T)value; } return HandleScopedStorageCollision<T>(id, (T)value); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="createDelegate"></param> /// <returns></returns> public virtual T GetOrCreateScopedService<T>(int id, Func<T> createDelegate) { var initialStorage = InternalScopedStorage; var storage = initialStorage; while (!ReferenceEquals(storage, ScopedStorage.Empty)) { if (storage.Id == id) { return (T)storage.ScopedService; } storage = storage.Next; } var value = createDelegate(); if (ReferenceEquals( Interlocked.CompareExchange(ref InternalScopedStorage, new ScopedStorage { Id = id, Next = initialStorage, ScopedService = value }, initialStorage), initialStorage)) { return (T)value; } return HandleScopedStorageCollision<T>(id, (T)value); } private T HandleScopedStorageCollision<T>(int id, T value) { ScopedStorage newStorage = new ScopedStorage { Id = id, ScopedService = value }; SpinWait spinWait = new SpinWait(); var initialStorage = InternalScopedStorage; do { var current = initialStorage; newStorage.Next = current; while (!ReferenceEquals(current, ScopedStorage.Empty)) { if (current.Id == id) { return value; } current = current.Next; } if (ReferenceEquals( Interlocked.CompareExchange(ref InternalScopedStorage, newStorage, initialStorage), initialStorage)) { return value; } spinWait.SpinOnce(); initialStorage = InternalScopedStorage; } while (true); } #if !NETSTANDARD1_0 object IServiceProvider.GetService(Type type) { return DelegateCache.ExecuteActivationStrategyDelegateAllowNull(type, this); } #endif public abstract IExportLocatorScope BeginLifetimeScope(string scopeName = ""); public abstract IInjectionContext CreateContext(object extraData = null); public abstract object Locate(Type type, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false); public abstract T Locate<T>(object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false); public abstract List<object> LocateAll(Type type, object extraData = null, ActivationStrategyFilter consider = null, IComparer<object> comparer = null); public abstract List<T> LocateAll<T>(Type type = null, object extraData = null, ActivationStrategyFilter consider = null, IComparer<T> comparer = null); public abstract bool TryLocate<T>(out T value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false); public abstract bool TryLocate(Type type, out object value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false); public abstract object LocateByName(string name, object extraData = null, ActivationStrategyFilter consider = null); public abstract List<object> LocateAllByName(string name, object extraData = null, ActivationStrategyFilter consider = null); public abstract bool TryLocateByName(string name, out object value, object extraData = null, ActivationStrategyFilter consider = null); public abstract bool CanLocate(Type type, ActivationStrategyFilter consider = null, object key = null); /// <summary> /// class for storing scoped instances /// </summary> protected class ScopedStorage { /// <summary> /// storage id /// </summary> public int Id; /// <summary> /// Scoped service instance /// </summary> public object ScopedService; /// <summary> /// Next scoped storage in list /// </summary> public ScopedStorage Next; /// <summary> /// /// </summary> public static ScopedStorage Empty; static ScopedStorage() { var empty = new ScopedStorage(); empty.Next = empty; // this is intentional and need so you can make the assumption that Next is never null Empty = empty; } } } }
mit
OpnUC/OpnUC-core
config/session.php
6905
<?php use Illuminate\Support\Str; return [ /* |-------------------------------------------------------------------------- | Default Session Driver |-------------------------------------------------------------------------- | | This option controls the default session "driver" that will be used on | requests. By default, we will use the lightweight native driver but | you may specify any of the other wonderful drivers provided here. | | Supported: "file", "cookie", "database", "apc", | "memcached", "redis", "array" | */ 'driver' => env('SESSION_DRIVER', 'file'), /* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire on the browser closing, set that option. | */ 'lifetime' => env('SESSION_LIFETIME', 120), 'expire_on_close' => false, /* |-------------------------------------------------------------------------- | Session Encryption |-------------------------------------------------------------------------- | | This option allows you to easily specify that all of your session data | should be encrypted before it is stored. All encryption will be run | automatically by Laravel and you can use the Session like normal. | */ 'encrypt' => false, /* |-------------------------------------------------------------------------- | Session File Location |-------------------------------------------------------------------------- | | When using the native session driver, we need a location where session | files may be stored. A default has been set for you but a different | location may be specified. This is only needed for file sessions. | */ 'files' => storage_path('framework/sessions'), /* |-------------------------------------------------------------------------- | Session Database Connection |-------------------------------------------------------------------------- | | When using the "database" or "redis" session drivers, you may specify a | connection that should be used to manage these sessions. This should | correspond to a connection in your database configuration options. | */ 'connection' => null, /* |-------------------------------------------------------------------------- | Session Database Table |-------------------------------------------------------------------------- | | When using the "database" session driver, you may specify the table we | should use to manage the sessions. Of course, a sensible default is | provided for you; however, you are free to change this as needed. | */ 'table' => 'sessions', /* |-------------------------------------------------------------------------- | Session Cache Store |-------------------------------------------------------------------------- | | When using the "apc" or "memcached" session drivers, you may specify a | cache store that should be used for these sessions. This value must | correspond with one of the application's configured cache stores. | */ 'store' => null, /* |-------------------------------------------------------------------------- | Session Sweeping Lottery |-------------------------------------------------------------------------- | | Some session drivers must manually sweep their storage location to get | rid of old sessions from storage. Here are the chances that it will | happen on a given request. By default, the odds are 2 out of 100. | */ 'lottery' => [2, 100], /* |-------------------------------------------------------------------------- | Session Cookie Name |-------------------------------------------------------------------------- | | Here you may change the name of the cookie used to identify a session | instance by ID. The name specified here will get used every time a | new session cookie is created by the framework for every driver. | */ 'cookie' => env( 'SESSION_COOKIE', Str::Slug(env('APP_NAME', 'laravel'), '_').'_session' ), /* |-------------------------------------------------------------------------- | Session Cookie Path |-------------------------------------------------------------------------- | | The session cookie path determines the path for which the cookie will | be regarded as available. Typically, this will be the root path of | your application but you are free to change this when necessary. | */ 'path' => '/', /* |-------------------------------------------------------------------------- | Session Cookie Domain |-------------------------------------------------------------------------- | | Here you may change the domain of the cookie used to identify a session | in your application. This will determine which domains the cookie is | available to in your application. A sensible default has been set. | */ 'domain' => env('SESSION_DOMAIN', null), /* |-------------------------------------------------------------------------- | HTTPS Only Cookies |-------------------------------------------------------------------------- | | By setting this option to true, session cookies will only be sent back | to the server if the browser has a HTTPS connection. This will keep | the cookie from being sent to you if it can not be done securely. | */ 'secure' => env('SESSION_SECURE_COOKIE', false), /* |-------------------------------------------------------------------------- | HTTP Access Only |-------------------------------------------------------------------------- | | Setting this value to true will prevent JavaScript from accessing the | value of the cookie and the cookie will only be accessible through | the HTTP protocol. You are free to modify this option if needed. | */ 'http_only' => true, /* |-------------------------------------------------------------------------- | Same-Site Cookies |-------------------------------------------------------------------------- | | This option determines how your cookies behave when cross-site requests | take place, and can be used to mitigate CSRF attacks. By default, we | do not enable this as other CSRF protection services are in place. | | Supported: "lax", "strict" | */ 'same_site' => null, ];
mit
MasterkeyInformatica/Repository
src/Cache/CacheKeyStorage.php
2158
<?php namespace Masterkey\Repository\Cache; /** * CacheKeyStorage * * @author Matheus Lopes Santos <fale_com_lopez@hotmail.com> * @version 1.0.0 * @since 14/03/2018 * @package Masterkey\Repository\Cache */ class CacheKeyStorage { /** * @var string */ protected $storagePath; /** * @var string */ protected $storageFile = 'repository-cache-keys.json'; /** * @var null|array */ protected $storedKeys = null; /** * @param string $storagePath */ public function __construct(string $storagePath) { $this->storagePath = $storagePath; $this->loadKeys(); } /** * @return array|null */ private function loadKeys() { if (!is_null($this->storedKeys) && is_array($this->storedKeys)) { return $this->storedKeys; } $file = $this->getStorageFilePath(); if (!file_exists($file)) { $this->writeKeys(); } $content = file_get_contents($file); $this->storedKeys = json_decode($content, true); } /** * @return string */ private function getStorageFilePath(): string { return $this->storagePath . '/' . $this->storageFile; } /** * @return bool|int */ private function writeKeys(): bool { $file = $this->getStorageFilePath(); $keys = $this->storedKeys ?? []; $content = json_encode($keys, true); return file_put_contents($file, $content); } /** * @param string $group * @param string $key * @return bool|int */ public function storeKey(string $group, string $key) { $this->storedKeys[$group] = $this->readKeys($group); if (!in_array($key, $this->storedKeys[$group])) { $this->storedKeys[$group][] = $key; } return $this->writeKeys(); } /** * @param string $group * @return mixed */ public function readKeys(string $group) { $this->storedKeys[$group] = $this->storedKeys[$group] ?? []; return $this->storedKeys[$group]; } }
mit
m11t/paf-quiz
src/webapp/app/question/question.service.ts
4258
import { Injectable } from '@angular/core'; import { Headers, Http, Response, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Question } from './question'; import { UserService } from './../user/user.service'; import { MessageService } from './../misc/message.service'; import { ResponseHandler } from './../misc/responsehandler'; @Injectable() export class QuestionService extends ResponseHandler { private questionsLink: string = '/api/questions'; constructor( private http: Http, private userService: UserService, messageService: MessageService ) { super(messageService); } /** * Return the serialized Question from a server response * * @private * @param {*} response to be converted * @returns {Question} question object created from the response * * @memberOf QuestionService */ private mapQuestion(response: any): Question { return new Question(response); } /** * Returns the list of questions from a Server HAL response * * @private * @param {*} response to be converted * @returns {Array<Question>} list of questions * * @memberOf QuestionService */ private mapQuestions(response: any) { return response._embedded.questions.map( (question: any) => new Question(question) ); } /** * Returns an observable for the http request to a question resource * * @param {string} link link to the question resource * @returns {Observable<User>} HTTP-Request-Observable * * @memberOf QuestionService */ public getQuestion(link: string): Observable<Question> { return this.http .get(link, this.userService.getAuthorizationOptions()) .map(this.mapJSON) .map(this.mapQuestion) .catch(err => this.handleError(err)); } /** * Get a list of questions from the server * * @param {string} link to the list of questions * @returns {Observable<Array<Question>>} HTTP-Request * * @memberOf QuestionService */ public getQuestions(link: string) { return this.http .get(link, this.userService.getAuthorizationOptions()) .map(this.mapJSON) .map(this.mapQuestions) .catch(err => this.handleError(err)); } /** * Save a question in the servers database * * @param {Question} question to be saved * @returns {Observable<Question>} HTTP-Request * * @memberOf QuestionService */ public save(question: Question): Observable<Question> { let requestOptions = this.userService.getAuthorizationOptions(); requestOptions.headers.append('Content-Type', 'application/json'); return this.http .post(this.questionsLink, question, requestOptions) .map(this.mapJSON) .catch(err => this.handleError(err)); } /** * Save the image of a question * * @param {string} link to the repository endpoint to save the image * @param {FormData} formData including the image file * @returns {Observable<Question>} HTTP-Request * * @memberOf QuestionService */ public saveImage(link: string, formData: FormData) { return this.http .post(link, formData, this.userService.getAuthorizationOptions()) .map(this.mapJSON) .catch(err => this.handleError(err)); } /** * Remove a question from the server * * @param {Question} question to be deleted * @returns {Observable<Question>} HTTP-Request * * @memberOf QuestionService */ public remove(question: Question): Observable<Question> { return this.http .delete(question._links.self.href, this.userService.getAuthorizationOptions()) .map(this.mapJSON) .catch(err => this.handleError(err)) } }
mit
sharpplayer/learnstones
slideshows/oconnor/js/presentation_wrapper.js
4083
(function ($) { ls.getSelectedIndex = function () { return $presentation.get_current_slide(); } ls.setSelectedIndex = function (index) { $presentation.set_current_slide(index); } ls.next = function () { $presentation.next_slide(); } ls.save = function () { var ret = []; var checkboxes = new Object(); $('#ls_frmpresentation :input').each(function () { var component = $(this); if (component.attr('name').indexOf('lsi_') === 0) { if (component.attr('type') === 'radio') { if (component.prop('checked')) { ret.push(this); $("input[data-radio-id=" + component.attr('data-radio-id') + "]").prop('checked', true); } } else if (component.attr('type') === 'checkbox') { var hidden; if (component.attr('data-checkbox-id') in checkboxes) { hidden = checkboxes[component.attr('data-checkbox-id')]; } else { hidden = document.createElement("input"); ret.push(hidden); checkboxes[component.attr('data-checkbox-id')] = $(hidden); hidden = $(hidden); hidden.prop('name', component.attr('data-checkbox-id')); } $("input[name=" + component.attr('name') + "]").prop('checked', component.prop('checked')); if (component.prop('checked')) { if (hidden.val()) { hidden.val(hidden.val() + "," + $(this).val()); } else { hidden.val($(this).val()); } } } else { ret.push(this); $("input[name=" + component.attr('name') + "]").val($(this).val()); } } }); $('#ls_frmpresentation textarea').each(function () { if ($(this).attr('name').indexOf('lsi_') == 0) { ret.push(this); $("textarea[name=" + $(this).attr('name') + "]").html($(this).val()); } }); $('#ls_frmpresentation select').each(function () { if ($(this).attr('name').indexOf('lsi_') == 0) { ret.push(this); $("select[name=" + $(this).attr('name') + "]").val($(this).val()); } }); return ret; } ls.populate = function () { //Need to copy learnstone menu div and content div into the slide portion $("div.ls_slideshow") .each(function () { $(this) .ls_presentation( { ele: function () { var element = $("<form></form>"); // Fix because jQuery cannot clone selectedIndex var toClone = $(this).find("div").first(); var cloned = toClone.clone(true); toClone.find("select").each(function () { var selectedValue = $(this).val(); cloned.find("select[name=" + this.name + "] option[value=" + selectedValue + "]").attr("selected", "selected"); }); element .attr("method", "post") .prop('id', 'ls_frmpresentation') .append( $("<div></div>") .append($("#ls_slides").find("div").eq(0).clone(true)) ) .append( $("<div></div>") .append(cloned) ); return element; } }); }); } } (jQuery));
mit
Mazdallier/Enchiridion
src/main/java/joshie/enchiridion/wiki/gui/scrollbars/ScrollbarPage.java
1229
package joshie.enchiridion.wiki.gui.scrollbars; import joshie.enchiridion.wiki.WikiHelper; public class ScrollbarPage extends ScrollbarAbstract { public static boolean isMoving = false; public static int lastY; public ScrollbarPage() { super(1002); } public int getScrollHeight() { return 100; } @Override public boolean displayScroll() { return false; } @Override public int getScrollbarHeight() { int scrollbarMaximum = getHeight() - 235; //Maximum Height of the Scrollbar aka 100% USE UR BRAIN FOR SOME MATHS BOY return scrollbarMaximum; } @Override public int getScrollbarPosition() { return WikiHelper.getPage().getData().getScroll(); } @Override public void scroll(int amount) { WikiHelper.getPage().getData().scroll(WikiHelper.isEditMode(), amount); } @Override public void setLastY(int y) { this.lastY = y; } @Override public int getLastY() { return lastY; } @Override public void setMoving(boolean value) { this.isMoving = value; } @Override public boolean isMoving() { return isMoving; } }
mit
tsiry95/openshift-strongloop-cartridge
strongloop/node_modules/strong-arc/arc-api/server/boot/explorer.js
781
module.exports = function mountLoopBackExplorer(server) { var explorer; try { explorer = require('loopback-component-explorer'); } catch(err) { console.log( 'Run `npm install loopback-component-explorer` to enable the LoopBack explorer' ); return; } var restApiRoot = server.get('restApiRoot'); var explorerApp = explorer.routes(server, { basePath: restApiRoot }); server.use('/explorer', explorerApp); server.once('started', function() { var baseUrl = server.get('url').replace(/\/$/, ''); // express 4.x (loopback 2.x) uses `mountpath` // express 3.x (loopback 1.x) uses `route` var explorerPath = explorerApp.mountpath || explorerApp.route; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); }); };
mit
cmcampione/thingshub
thingshub-server-authorization/src/validate.js
8994
'use strict'; const process = require('process'); const utils = require('./utils'); const config = require('./config'); const db = require('./db'); const bl = require('./bl'); /** Validate object to attach all functions to */ const validate = Object.create(null); /** Suppress tracing for things like unit testing */ const suppressTrace = process.env.OAUTHRECIPES_SURPRESS_TRACE === 'true'; /** * Log the message and throw it as an Error * @param {String} msg - Message to log and throw * @throws {Error} The given message as an error * @returns {undefined} */ validate.logAndThrow = (msg) => { if (!suppressTrace) { console.trace(msg); } throw new Error(msg); }; /** * Given a user this will return the user if it exists otherwise this will throw an error * @param {Object} user - The user profile * @throws {Error} If the user does not exist or the password does not match * @returns {Object} The user if valid */ validate.userExists = (user) => { if (user == null) { validate.logAndThrow('User does not exist'); } return user; }; /** * Given a user and a password this will return the user if it exists and the password matches, * otherwise this will throw an error * @param {Object} user - The user profile * @param {String} password - The user's password * @throws {Error} If the user does not exist or the password does not match * @returns {Object} The user if valid */ validate.user = (user, password) => { validate.userExists(user); return new Promise((resolve, reject) => { user.comparePassword(password, (err, isMatch) => { if (err) { reject(err); return; } if (isMatch) { resolve(user); return; } reject(); }); }); }; /** * Given a client and a client secret this return the client if it exists and its clientSecret * matches, otherwise this will throw an error * @param {Object} client - The client profile * @param {String} clientSecret - The client's secret * @throws {Error} If the client or the client secret does not match * @returns {Object} The client if valid */ validate.client = (client, clientSecret) => { validate.clientExists(client); if (client.clientSecret !== clientSecret) { validate.logAndThrow('Client secret does not match'); } return client; }; /** * Given a client this will return the client if it exists , otherwise this will throw an error * @param {Object} client - The client profile * @throws {Error} If the client does not exist * @returns {Object} The client if valid */ validate.clientExists = (client) => { if (client == null) { validate.logAndThrow('Client does not exist'); } return client; }; /** * Given a token and accessToken this will return either the user or the client associated with * the token if valid. Otherwise this will throw. * @param {Object} token - The token * @param {Object} accessToken - The access token * @throws {Error} If the token is not valid * @returns {Promise} Resolved with the user or client associated with the token if valid */ validate.token = (token, accessToken) => { utils.verifyToken(accessToken); // token is a user token if (token.userID != null) { return bl.usersMngr.findUserById(token.userID) .then(user => validate.userExists(user)) .then(user => user); } // token is a client token return db.clients.find(token.clientID) .then(client => validate.clientExists(client)) .then(client => client); }; /** * Given a refresh token and client this will return the refresh token if it exists and the client * id's match otherwise this will throw an error * throw an error * @param {Object} token - The token record from the DB * @param {Object} refreshToken - The raw refresh token * @param {Object} client - The client profile * @throws {Error} If the refresh token does not exist or the client id's don't match * @returns {Object} The refresh token if valid */ validate.refreshToken = (token, refreshToken, client) => { utils.verifyToken(refreshToken); if (client.id !== token.clientID) { validate.logAndThrow('RefreshToken clientID does not match client id given'); } return refreshToken; }; /** * Given a auth code, client, and redirectURI this will return the auth code if it exists and is * not 0, the client id matches it, and the redirectURI matches it, otherwise this will throw an * error. * @param {Object} code - The auth code record from the DB * @param {Object} authCode - The raw auth code * @param {Object} client - The client profile * @param {Object} redirectURI - The redirectURI to check against * @throws {Error} If the auth code does not exist or is zero or does not match the client or * the redirectURI * @returns {Object} The auth code token if valid */ validate.authCode = (code, authCode, client, redirectURI) => { utils.verifyToken(code); if (client.id !== authCode.clientID) { validate.logAndThrow('AuthCode clientID does not match client id given'); } if (redirectURI !== authCode.redirectURI) { validate.logAndThrow('AuthCode redirectURI does not match redirectURI given'); } return authCode; }; /** * I mimic openid connect's offline scope to determine if we send a refresh token or not * @param {Array} scope - The scope to check if is a refresh token if it has 'offline_access' * @returns {Boolean} true If the scope is offline_access, otherwise false */ validate.isRefreshToken = ({ scope }) => scope != null && scope.indexOf('offline_access') === 0; /** * Given a userId, clientID, and scope this will generate a refresh token, save it, and return it * @param {Object} userId - The user profile * @throws {Object} clientID - the client profile * @throws {Object} scope - the scope * @returns {Promise} The resolved refresh token after saved */ validate.generateRefreshToken = ({ userID, clientID, scope }) => { const refreshToken = utils.createToken({ sub : userID, exp : config.refreshToken.expiresIn }); return db.refreshTokens.save(refreshToken, userID, clientID, scope) .then(() => refreshToken); }; /** * Given an auth code this will generate a access token, save that token and then return it. * @param {userID} userID - The user profile * @param {clientID} clientID - The client profile * @param {scope} scope - The scope * @returns {Promise} The resolved refresh token after saved */ validate.generateToken = ({ userID, clientID, scope }) => { const token = utils.createToken({ sub : userID, exp : config.token.expiresIn }); const expiration = config.token.calculateExpirationDate(); return db.accessTokens.save(token, expiration, userID, clientID, scope) .then(() => token); }; /** * Given an auth code this will generate a access and refresh token, save both of those and return * them if the auth code indicates to return both. Otherwise only an access token will be returned. * @param {Object} authCode - The auth code * @throws {Error} If the auth code does not exist or is zero * @returns {Promise} The resolved refresh and access tokens as an array */ validate.generateTokens = (authCode) => { if (validate.isRefreshToken(authCode)) { return Promise.all([ validate.generateToken(authCode), validate.generateRefreshToken(authCode), ]); } return Promise.all([validate.generateToken(authCode)]); }; /** * Given a token this will resolve a promise with the token if it is not null and the expiration * date has not been exceeded. Otherwise this will throw a HTTP error. * @param {Object} token - The token to check * @returns {Promise} Resolved with the token if it is a valid token otherwise rejected with error */ validate.tokenForHttp = (token) => { try { utils.verifyToken(token); } catch (err) { const error = new Error('invalid_token'); error.status = 400; return Promise.reject(error); } return Promise.resolve(token); }; /** * Given a token this will return the token if it is not null. Otherwise this will throw a * HTTP error. * @param {Object} token - The token to check * @throws {Error} If the client is null * @returns {Object} The client if it is a valid client */ validate.tokenExistsForHttp = (token) => { if (token == null) { const error = new Error('invalid_token'); error.status = 400; throw error; } return token; }; /** * Given a client this will return the client if it is not null. Otherwise this will throw a * HTTP error. * @param {Object} client - The client to check * @throws {Error} If the client is null * @returns {Object} The client if it is a valid client */ validate.clientExistsForHttp = (client) => { if (client == null) { const error = new Error('invalid_token'); error.status = 400; throw error; } return client; }; module.exports = validate;
mit
PATRIC3/oxcart
js/tools/smooth-scroll.js
2257
angular.module('smooth-scroll', []) .service('anchorSmoothScroll', function(){ var yOffset = 95; this.scrollTo = function(eID) { // Taken from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript var startY = currentYPosition(); var stopY = elmYPosition(eID)-yOffset; var distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 100); if (speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if (stopY > startY) { for ( var i=startY; i<stopY; i+=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for ( var i=startY; i>stopY; i-=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; } function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; } }; }) .controller('ScrollCtrl', ['$scope', '$location', 'anchorSmoothScroll', function($scope, $location, anchorSmoothScroll) { $scope.gotoElement = function (id){ $location.hash(id); anchorSmoothScroll.scrollTo(id); }; }]);
mit
rlbaltha/engDept
src/English/PeopleBundle/EnglishPeopleBundle.php
134
<?php namespace English\PeopleBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class EnglishPeopleBundle extends Bundle { }
mit
Danack/FlickrGuzzle
src/Intahwebz/FlickrGuzzle/DTO/PublicEditability.php
296
<?php namespace Intahwebz\FlickrGuzzle\DTO; use Intahwebz\FlickrGuzzle\DataMapper; class PublicEditability { use DataMapper; static protected $dataMap = array( ['canComment','cancomment'],// => int 1 ['canAddMeta','canaddmeta'],// => int 0 ); var $canComment; var $canAddMeta; }
mit
jmvdev/htdocs
admin/email_logs.php
1797
<?php include('header-admin.php'); $isSent = false; $res = $page_protect->get_email_logs(); if(isset($_POST['resend_email'])){ $err_id = $_POST['error_log_id']; $q = 'SELECT * FROM email_logs WHERE id = '. $err_id. ' AND isSent = 0'; $res_query = mysql_query($q); $res_query = mysql_fetch_array($res_query); $e_sender = $res_query['e_sender']; $e_receiver = $res_query['e_receiver']; $e_message = $res_query['e_message']; $e_subject = $res_query['e_subject']; $isSent = $page_protect->email_notif($e_receiver, $e_message, $e_subject, true); if($isSent){ $q = 'UPDATE email_logs set isSent = 1 WHERE id = '. $err_id; mysql_query($q); } else { echo "<div>Email Sending Failed</div>"; } } ?> <div class=" container-fluid"> <div class="row"> <div class="col-md-2"> </div> <div class="col-md-7"> <table class="table"> <tr> <th>Subject</th> <th>Body</th> <th>Recipient</th> <th>Sender</th> <th>DateTime</th> <th>Action</th> </tr> <?php while($row = mysql_fetch_array($res)){ echo '<tr>'; echo '<td>'.$row['e_subject'].'</td>'; echo '<td>'.$row['e_message'].'</td>'; echo '<td>'.$row['e_recipient'].'</td>'; echo '<td>'.$row['e_sender'].'</td>'; echo '<td>'.$row['timestamps'].'</td>'; echo '<td> <form action='; echo $_SERVER["PHP_SELF"]; echo ' method="post"> <input type="hidden" name="error_log_id" value ="'.$row['id'].'"/> <input type="submit" class="btn btn-primary" name="resend_email" value="Resend"/> </form> </td>'; echo '</tr>'; } ?> </table> </div> <div class="col-md-3"> </div> </div> <?php include('footer-admin.php'); ?>
mit
MNL82/oakmodelview
Lib/OakXML/XMLRef.cpp
1412
/** * oakmodelview - version 0.1.0 * -------------------------------------------------------- * Copyright (C) 2017, by Mikkel Nøhr Løvgreen (mikkel@oakmodelview.com) * Report bugs and download new versions at http://oakmodelview.com/ * * This library is distributed under the MIT License. * See accompanying file LICENSE in the root folder. */ #ifdef XML_BACKEND #include "XMLRef.h" namespace Oak { namespace XML { std::string Ref::emptyStr = ""; // ============================================================================= // (public) RefUPtr Ref::copy() const { return MakeUPtr(); } // ============================================================================= // (public) Element Ref::getTarget(Element source, bool create) const { UNUSED(create); return source; } // ============================================================================= // (public) void Ref::clearTarget(Element source, bool onlyIfEmpty) const { UNUSED(source); UNUSED(onlyIfEmpty); } // ============================================================================= // (public) bool Ref::hasTarget(Element source) const { return !getTarget(source).isNull(); } // ============================================================================= // (public) Element Ref::getSource(Element target) const { return target; } } // namespace XML } // namespace Oak #endif // XML_BACKEND
mit
JakubKopys/myshop
resources/views/admin/layouts/nav.blade.php
1568
<div class="option"> <a href="{{URL::action('Admin\MainController@index')}}" class={{ Request::is('admin') ? 'active' : '' }}> <i class="fa fa-home" aria-hidden="true"></i> Home </a> </div> <div class="option"> <a href="{{URL::action('Admin\ProductController@index')}}" class={{ Request::is('*products*') ? 'active' : '' }}> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Manage Products </a> </div> <div class="option"> <a href="{{URL::action('Admin\UserController@index')}}" class={{ Request::is('*users*') ? 'active' : '' }}> <i class="fa fa-users" aria-hidden="true"></i> Manage Users </a> </div> <div class="option"> <a href="{{URL::action('Admin\CategoryController@index')}}" class={{ Request::is('*categories*') ? 'active' : '' }}> <i class="fa fa-th" aria-hidden="true"></i> Manage Categories </a> </div> <div class="option"> <a href="#" class={{ Request::is('*orders*') ? 'active' : '' }}> <i class="fa fa-cart-arrow-down" aria-hidden="true"></i> Orders </a> </div> <div class="option"> <a href="{{ url('/logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> <i class="fa fa-sign-out" aria-hidden="true"></i> Logout <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </a> </div> <div class="option down"> <a href="/"> <i class="fa fa-chevron-left" aria-hidden="true"></i> Back To The Store </a> </div>
mit
gustavofoa/mpmjadmin
src/main/java/br/com/mpmjadmin/util/TabController.java
713
package br.com.mpmjadmin.util; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.stage.Stage; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j @Getter @Setter public abstract class TabController { @FXML private TabPane mainTabPanel; private Stage primaryStage; private Tab tab; protected boolean activeTab(String text) { for (Tab tab : getMainTabPanel().getTabs()) { if (tab.getText().equals(text)) { getMainTabPanel().getSelectionModel().select(tab); return true; } } return false; } public void tabSelectedAction(String tabTitle) { log.debug("Tab selected: "+tabTitle); } }
mit
Useurmind/rokuby
lib/rokuby/RokubyRake/rake/version.rb
156
module Rake VERSION = '0.9.2' module Version # :nodoc: all MAJOR, MINOR, BUILD = VERSION.split '.' NUMBERS = [ MAJOR, MINOR, BUILD ] end end
mit
famry/fameCMSv2
themes/vokalplus/config.rb
1270
# Require any additional compass plugins here. add_import_path "bower_components/foundation/scss" # Set this to the root of your project when deployed: http_path = "/" css_dir = "stylesheets" sass_dir = "scss" images_dir = "images" javascripts_dir = "js" # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: # line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass if Gem.loaded_specs["sass"].version >= Gem::Version.create('3.4') warn "You're using Sass 3.4 or higher to compile Foundation. This version causes CSS classes to output incorrectly, so we recommend using Sass 3.3 or 3.2." warn "To use the right version of Sass on this project, run \"bundle\" and then use \"bundle exec compass watch\" to compile Foundation." end
mit
ntentan/atiaa
src/exceptions/TableNotFoundException.php
1276
<?php /* * The MIT License * * Copyright 2014-2018 James Ekow Abaka Ainooson * * 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. */ namespace ntentan\atiaa\exceptions; class TableNotFoundException extends \Exception { const NO_COLUMNS = 1; }
mit