repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
node-opcua/node-opcua
packages/node-opcua-variant/source/cast_variant.ts
3421
import { Variant } from "./variant"; import { DataType } from "./DataType_enum"; // TODO /** * cast the variant value to match the type required by the variable * - the method will throw if no conversion is possible * - the original variant will not be modified if it already has the required type * - the variant will be modified accordingly to match the required type * * | .... | Byte | UInt16 | UInt32 | UInt64 | Boolean | SByte | Int16 | Int32 | Int64 | Float | Double | String | anything else | * | ------- | ---- | ------ | ------ | ------ | ------- | ----- | ----- | ------ | ----- | ----- | ------ | ------ | ------------- | * | Byte | - | OK | OK | OK | F=0;T<>0| <128 | OK | OK | OK | OK | OK | | | * | UInt16 |<=255 | - | OK | OK | F=0;T<>0| <128 |<2^15-1| OK | OK | OK | OK | | | * | UInt32 |<=255 |<2^16 | - | OK | F=0;T<>0| <128 |<2^15-1| <2^31-1| OK | OK | OK | | | * | UInt64 |<=255 |<2^16 |<2^31 | - | F=0;T<>0| <128 |<2^15-1| <2^31-1| OK | OK(*) | OK(*) | | | * | Boolean | x |F=0;T=1 |F=0;T=1 | F=0;T=1| - |F=0;T=1|F=0;T=1|F=0;T=1 |F=0;T=1|F=0;T=1|F=0;T=1 | | | * | SByte |>=0 | >=0 | >=0 | >=0 | F=0;T<>0| - | OK | OK | OK | OK | OK | | | * | Int16 |a<x<b | >=0 | OK | OK | F=0;T<>0|<128 | - | OK | OK | OK | OK | | | * | Int32 |a<x<b |a<x<b | >=0 | OK | F=0;T<>0|<128 | | - | OK | OK | OK | | | * | Int64 |a<x<b |a<x<b | a<x<b | >=0 | F=0;T<>0|<128 | - | | - | OK | OK | | | * | Float |err |err | err | err | F=0;T<>0| err | err | err | err | - | OK | | | * | Double |err |err | err | err | F=0;T<>0| err | err | err | err | * | - | | | * | String |err |err | err | err | err | err | err | err | err | err | err | - | | */ /* export function castVariant(variant: Variant, targetDataType: DataType): Variant { if (targetDataType !== variant.dataType) { switch (targetDataType) { case DataType.SByte: case DataType.Int16: case DataType.Int32: case DataType.Int64: case DataType.Byte: case DataType.Int16: case DataType.UInt32: case DataType.UInt32: case DataType.UInt64: case DataType.Double: case DataType.Float: switch (variant.dataType) { case DataType.SByte: case DataType.Int16: case DataType.Int32: case DataType.Int64: case DataType.Byte: case DataType.UInt16: case DataType.UInt32: case DataType.UInt64: case DataType.Double: case DataType.Float: variant.dataType = targetDataType; break; } break; } } return variant; } */
mit
cwkingjr/node-web
src/services/errorHandler.js
851
'use strict'; const HttpStatus = require('http-status-codes'); const Sequelize = require('sequelize'); function handleError(err, req, res, next) { const status = err.status || HttpStatus.INTERNAL_SERVER_ERROR; res.status(status); res.json({ message: err.message || HttpStatus.getStatusText(status), error: req.app.get('env') === 'development' ? err : {} }); // Will never get here but this shuts up eslint unused var warning on // 'next', which is required for error middleware signature match next(err); } function handleSequelizeError(err, req, res, next) { if (err instanceof Sequelize.UniqueConstraintError) { err.status = HttpStatus.UNPROCESSABLE_ENTITY; } else if (err instanceof Sequelize.ValidationError) { err.status = HttpStatus.BAD_REQUEST; } next(err); } module.exports = { handleError, handleSequelizeError };
mit
antanta/MyApp
MyApp.Web.Mvc/Controllers/RandomFileGeneratorController.cs
853
using MyApp.Services.FileManipulations; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace MyApp.Web.Mvc.Controllers { public class RandomFileGeneratorController : Controller { public RandomFileGeneratorController(IRandomFileCreator randomFileCreator) { this.randomFileCreator = randomFileCreator; } [HttpGet] public async Task<ActionResult> GenerateRandomFiles(int numberOfFiles) { FileMetadata[] result = await this.randomFileCreator.CreateRandomFilesAsync(numberOfFiles); return Json(result, JsonRequestBehavior.AllowGet); } #region Private members private readonly IRandomFileCreator randomFileCreator; #endregion } }
mit
johnboxall/google_auth_proxy
validator.go
974
package main import ( "encoding/csv" "fmt" "log" "os" "strings" ) func NewValidator(domains []string, usersFile string) func(string) bool { validUsers := make(map[string]bool) if usersFile != "" { log.Printf("using authenticated emails file %s", usersFile) r, err := os.Open(usersFile) if err != nil { log.Fatalf("failed opening authenticated-emails-file=%q, %s", usersFile, err) } csv_reader := csv.NewReader(r) csv_reader.Comma = ',' csv_reader.Comment = '#' csv_reader.TrimLeadingSpace = true records, err := csv_reader.ReadAll() for _, r := range records { validUsers[r[0]] = true } } validator := func(email string) bool { valid := false for _, domain := range domains { emailSuffix := fmt.Sprintf("@%s", domain) valid = valid || strings.HasSuffix(email, emailSuffix) } if !valid { _, valid = validUsers[email] } log.Printf("validating: is %s valid? %v", email, valid) return valid } return validator }
mit
islenska-org/icelandic
src/slugify.js
227
const decompose = require('./decompose'); // Create a slug string from Icelandic text module.exports = function (str) { return decompose(str.trim()) .replace(/[^\w\s-]/g, '') .trim() .replace(/[-\s]+/g, '-'); };
mit
dbohn/holger
src/Modules/DECTInfo.php
1351
<?php namespace Holger\Modules; use Holger\HasEndpoint; class DECTInfo { protected $endpoint = [ 'controlUri' => '/upnp/control/x_contact', 'uri' => 'urn:dslforum-org:service:X_AVM-DE_OnTel:1', 'scpdurl' => '/x_contactSCPD.xml', ]; use HasEndpoint; /** * List all available Handset IDs * URI: urn:dslforum-org:service:X_AVM-DE_OnTel:1#GetDECTHandsetList. * * @return array */ public function getHandsets() { return explode(',', $this->prepareRequest()->GetDECTHandsetList()); } /** * Retrieve full information about the handsets * i.e. call getHandsetInfo for each handset. * * @return array */ public function getFullHandsetInfo() { $handsets = $this->getHandsets(); $result = []; foreach ($handsets as $handset) { $result[$handset] = $this->getHandsetInfo($handset); } return $result; } /** * Returns all available information about one handset. * Fields: NewHandsetName, NewPhonebookID. * * @param $handsetId * * @return mixed */ public function getHandsetInfo($handsetId) { $idParam = new \SoapParam($handsetId, 'NewDectID'); return $this->prepareRequest()->GetDECTHandsetInfo($idParam); } }
mit
LeukemiaResearch/How-R-you-App
client/translations/translations.js
17132
angular.module('leukemiapp').config(config); function config($translateProvider) { $translateProvider.translations('en', { JANUARY: 'January', FEBRUARY: 'February', MARCH: 'March', APRIL: 'April', MAI: 'May', JUNE: 'June', JULY: 'July', AUGUST: 'August', SEPTEMBER: 'September', OCTOBER: 'October', NOVEMBER: 'November', DECEMBER: 'December', monthsList: 'January_February_March_April_May_June_July_August_September_October_November_December', SUNDAY: 'Sunday', MONDAY: 'Monday', TUESDAY: 'Tuesday', WEDNESDAY: 'Wednesday', THURSDAY: 'Thurday', FRIDAY: 'Friday', SATURDAY: 'Saturday', weekdaysList: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday', weekdaysShortList: 'Su_Mo_Tu_We_Th_Fr_Sa', reminders: { reminders: 'Reminders', bloodsamples: 'Blood collection', highdoses: 'High doses' }, notes: { notes: 'Notes:', placeholderLoggedIn: 'Click here to type a note', placeholderLoggedOut: 'Log in to create notes' }, sidemenu: { treatments: 'Treatments', leukemia: 'Leukemia', l_standard: 'Standard Intensity', l_intermediate: 'Intermediate Intensity', l_intermediate_cns3: 'Intermediate Intensity + CNS3', l_high: 'High Intensity', arthritis: 'Arthritis' }, settings: { modules: 'Modules', selectModules: 'Choose modules to be shown active on the front page', done: 'Done', cancel: 'Cancel' }, medicine: { medicine: 'Medicine', //question 1 tablet6MP: 'Tablet 6 MP', tabletMTX: 'Tablet MTX', mgDay: 'mg/day', mgWeek: 'mg/week', //frontside sixmp: '6 MP', mtx: 'MTX', mgDaily: 'mg / daily', mgWeekly: 'mg / weekly' }, bloodsamples: { bloodsamples: 'Blood samples', leukocytes: 'Leukocytes', neutrophiles: 'Neutrophiles', crp: 'CRP', //frontside thrombocytes: 'Thrombocytes', thrombocytes_measure: '10^9 L', hemoglobin: 'Hemoglobin', hemoglobin_measure: 'mmol / L', alat: 'ALAT', alat_measure: 'U / L' }, pain: { pain: 'Pain', morphine: 'Morfine', type: 'Type', intensity: 'Intensity', //question 1 howMuchMorphine: 'How much morphine was given?', administrationType: 'Administration type:', oral: 'Tablet', intravenous: 'Intravenous', dose: 'Dose:', mg: 'mg', mgDay: 'mg/day', mgHour: 'mg/hour', //question 2 whereIsPain: 'Where is the pain?', stomach: 'Stomach', legs: 'Legs', arms: 'Arms', head: 'Head', other: 'Other', //TODO translate question 3↓ //question 3 changeScale: 'Change scale', faceExpression: 'Face expression', activity: 'Activity', cry: 'Crying', comfort: 'Trøstbarhed', faceExpression0: 'Upåvirket/Afslappet', faceExpression1: 'Bekymret,indadvendt', faceExpression2: 'Hyppigt til konstant dirren omkring munden eller sammenbidt', legs0: 'Normal position eller afslappet', legs1: 'Urolig, spændt', legs2: 'Trækker benene op under sig, sparker', activity0: 'Normal stilling eller ligger stille, bevæger sig frit', activity1: 'Vrider sig, kan ikke finde ro', activity2: '"Går i bro", stiv eller kaster sig rundt', cry0: 'Græder ikke (Vågen eller sovende)', cry1: 'Klynker, klager sig af og til', cry2: 'Græder uafbrudt, skriger eller klager sig hyppigt', comfort0: 'Tilfreds, afslappet', comfort1: 'Kan beroliges ved berøring, ved at blive talt til og kan afledes fra smerten', comfort2: 'Vanskelig at trøste eller utrøstelig', smiley0: 'Man kan gøre fuldstændig, som man plejer uden at tænke på, at det gør ondt.', smiley2: 'Man kan gøre, som man plejer, men af og til må man standse op, fordi det gør ondt.', smiley4: 'Man har mest lyst til at sidde stille og få læst en historie eller se fjernsyn, fordi det gør ondt.', smiley6: 'Man tænker på, at det gør ondt hele tiden.', smiley8: 'Man har så ondt, at man har lyst til at græde, fordi det gør ondt.', smiley10: 'Man har så ondt, at man slet ikke kan holde det ud.', //frontside painType: 'Type of pain', painIntensity: 'Strength' }, mucositis: { mucositis: 'Mucositis', mouthSores: 'Oral sores', nausea: 'Nausea', // TODO translate question 1↓ //question 1 painQ0: 'Ingen', painQ1: 'Let smerte', painQ2: 'Moderat smerte', painQ3: 'Kraftige smerter med behov for morfin', painQ4: 'Kraftige smerter og behov for store mængder morfin', soresAndRedness: 'Sores and redness', soresQ0: 'Ingen', soresQ1: 'Rødme (ingen sår)', soresQ2: 'Enkelte eller flere mindre sår', soresQ3: 'Udtalt rødme, store eller mange sår', soresQ4: 'Størstedelen af munden er påvirket af rødme eller sår', foodIntakeInfluence: 'Influence on food intake', foodIntakeQ0: 'Ingen', foodIntakeQ1: 'Spiser næsten normalt', foodIntakeQ2: 'Spiser enkelte typer af fast føde', foodIntakeQ3: 'Drikker og spiser flydende', foodIntakeQ4: 'Drikker minimalt og har behov for iv, væske, sondemad eller TPN', //frontside pain: 'Pain', soresRedness: 'Sores/Redness', foodIntake: 'Food intake', pain0: 'Ingen smerter', // TODO translate ↓ pain1: 'Lette smerter', pain2: 'Moderate smerter', pain3: 'Kraftige smerter', pain4: 'Uudholdlige smerter', sores0: 'Ingen sår', sores1: 'Ingen sår, let rødmen', sores2: 'Enkelte mindre sår', sores3: 'Mange sår', sores4: 'Udtalt rødmen + mange store sår', foodIntake0: 'Ingen påvirkning', foodIntake1: 'Spiser næsten normalt', foodIntake2: 'Spiser lidt fast føde', foodIntake3: 'Spiser flydende føde', foodIntake4: 'Behov for sondemad' }, arthritis: { arthritis: 'Arthritis pain', pain: 'Pain', //frontside intensity: 'Intensity' }, wizard: { cancel: 'Cancel', previous: 'Previous', next: 'Next', update: 'Update', save: 'Save', time: 'Time', existingRecordTitle: 'Update record', existingRecord: 'There already exists a registration with this timestamp. Do you wish to update it?', invalidInputTitle: 'Error', invalidInput: 'One or more fields are not filled in properly!', saved: 'Registration saved!', updated: 'Registration updated!', failed: 'Failed to save registration', saveRegistrationLoggedOut: 'Log in to save the registration', // question templates pain: 'Pain' }, graphData: { from: 'From:', till: 'Till:', noData: 'No data available for this period.', table: 'Table', graph: 'Graph', //datetimepicker date: 'Date', today: 'Today', close: 'Close', choose: 'Pick', timestamp: 'Time', //editing records update: 'Update', delete: 'Delete', cancel: 'Cancel', edit: 'Edit registration' } }); $translateProvider.translations('da_DK', { JANUARY: 'Januar', FEBRUARY: 'Februar', MARCH: 'Marts', APRIL: 'April', MAI: 'Maj', JUNE: 'Juni', JULY: 'Juli', AUGUST: 'August', SEPTEMBER: 'September', OCTOBER: 'Oktober', NOVEMBER: 'November', DECEMBER: 'December', monthsList: 'Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December', SUNDAY: 'Søndag', MONDAY: 'Mandag', TUESDAY: 'Tirsdag', WEDNESDAY: 'Onsdag', THURSDAY: 'Torsdag', FRIDAY: 'Fredag', SATURDAY: 'Lørdag', weekdaysList: 'Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag', weekdaysShortList: 'Sø_Ma_Ti_On_To_Fr_Lø', reminders: { reminders: 'Påmindelse', bloodsamples: 'Blodprøver', highdoses: 'Højdosis' }, notes: { notes: 'Noter:', placeholderLoggedIn: 'Tryk for at indtaste tekst', placeholderLoggedOut: 'Logge ind for at oprette noter' }, sidemenu: { treatments: 'Behandlinger', leukemia: 'Leukæmi', l_standard: 'Standard Intensiv', l_intermediate: 'Intermediær Intensiv', l_intermediate_cns3: 'Intermediær Intensiv + CNS3', l_high: 'Høj Intensiv', arthritis: 'Gigt' }, settings: { modules: 'Moduler', selectModules: 'Vælg moduler, der skal vises på forsiden', done: 'Gem', cancel: 'Annuller' }, medicine: { medicine: 'Medicin', //question 1 tablet6MP: 'Tablet 6 MP', tabletMTX: 'Tablet MTX', mgDay: 'mg/dag', mgWeek: 'mg/uge', //frontside sixmp: '6 MP', mtx: 'MTX', mgDaily: 'mg / daglig', mgWeekly: 'mg / ugentlig' }, bloodsamples: { bloodsamples: 'Blodprøver', leukocytes: 'Leukocytter', neutrophiles: 'Neutrofile', crp: 'CRP', //frontside thrombocytes: 'Thrombocytter', thrombocytes_measure: '10^9 L', hemoglobin: 'Hæmoglobin', hemoglobin_measure: 'mmol / L', alat: 'ALAT', alat_measure: 'U / L' }, pain: { pain: 'Smerte', morphine: 'Morfin', type: 'Type', intensity: 'Styrke', //question 1 howMuchMorphine: 'Hvor meget morfin er givet?', administrationType: 'Administration type:', oral: 'Tablet', intravenous: 'Intravenøs', dose: 'Dosis:', mg: 'mg', mgDay: 'mg/døgn', mgHour: 'mg/time', //question 2 whereIsPain: 'Hvor er smerten?', stomach: 'Mave', legs: 'Ben', arms: 'Arme', head: 'Hoved', other: 'Andet', //question 3 changeScale: 'Skift skala', faceExpression: 'Ansigtsudtryk', activity: 'Aktivitet', cry: 'Gråd', comfort: 'Trøstbarhed', faceExpression0: 'Upåvirket/Afslappet', faceExpression1: 'Bekymret,indadvendt', faceExpression2: 'Hyppigt til konstant dirren omkring munden eller sammenbidt', legs0: 'Normal position eller afslappet', legs1: 'Urolig, spændt', legs2: 'Trækker benene op under sig, sparker', activity0: 'Normal stilling eller ligger stille, bevæger sig frit', activity1: 'Vrider sig, kan ikke finde ro', activity2: '"Går i bro", stiv eller kaster sig rundt', cry0: 'Græder ikke (Vågen eller sovende)', cry1: 'Klynker, klager sig af og til', cry2: 'Græder uafbrudt, skriger eller klager sig hyppigt', comfort0: 'Tilfreds, afslappet', comfort1: 'Kan beroliges ved berøring, ved at blive talt til og kan afledes fra smerten', comfort2: 'Vanskelig at trøste eller utrøstelig', smiley0: 'Man kan gøre fuldstændig, som man plejer uden at tænke på, at det gør ondt.', smiley2: 'Man kan gøre, som man plejer, men af og til må man standse op, fordi det gør ondt.', smiley4: 'Man har mest lyst til at sidde stille og få læst en historie eller se fjernsyn, fordi det gør ondt.', smiley6: 'Man tænker på, at det gør ondt hele tiden.', smiley8: 'Man har så ondt, at man har lyst til at græde, fordi det gør ondt.', smiley10: 'Man har så ondt, at man slet ikke kan holde det ud.', //frontside painType: 'Smerte typen', painIntensity: 'Intensitet' }, mucositis: { mucositis: 'Mucositis', mouthSores: 'Mundsår', nausea: 'Kvalme', //question 1 painQ0: 'Ingen', painQ1: 'Let smerte', painQ2: 'Moderat smerte', painQ3: 'Kraftige smerter med behov for morfin', painQ4: 'Kraftige smerter og behov for store mængder morfin', soresAndRedness: 'Sår og rødme', soresQ0: 'Ingen', soresQ1: 'Rødme (ingen sår)', soresQ2: 'Enkelte eller flere mindre sår', soresQ3: 'Udtalt rødme, store eller mange sår', soresQ4: 'Størstedelen af munden er påvirket af rødme eller sår', foodIntakeInfluence: 'Påvirkning af fødeindtag', foodIntakeQ0: 'Ingen', foodIntakeQ1: 'Spiser næsten normalt', foodIntakeQ2: 'Spiser enkelte typer af fast føde', foodIntakeQ3: 'Drikker og spiser flydende', foodIntakeQ4: 'Drikker minimalt og har behov for iv, væske, sondemad eller TPN', //frontside pain: 'Smerte', soresRedness: 'Sår/Rødme', foodIntake: 'Fødeindtag', pain0: 'Ingen smerter', pain1: 'Lette smerter', pain2: 'Moderate smerter', pain3: 'Kraftige smerter', pain4: 'Uudholdlige smerter', sores0: 'Ingen sår', sores1: 'Ingen sår, let rødmen', sores2: 'Enkelte mindre sår', sores3: 'Mange sår', sores4: 'Udtalt rødmen + mange store sår', foodIntake0: 'Ingen påvirkning', foodIntake1: 'Spiser næsten normalt', foodIntake2: 'Spiser lidt fast føde', foodIntake3: 'Spiser flydende føde', foodIntake4: 'Behov for sondemad' }, arthritis: { arthritis: 'Gigt Smerte', pain: 'Smerte', //frontside intensity: 'Intensitet' }, wizard: { cancel: 'Fortryd', previous: 'Forrige', next: 'Næste', update: 'Opdater', save: 'Gem', time: 'Tid', existingRecordTitle: 'Opdater registrering', existingRecord: 'Der findes allerede en registrering på dette tidspunkt! Vil du rette den?', invalidInputTitle: 'Fejl', invalidInput: 'Et eller flere felter er enten ikke udfyldt, eller ikke udfyldt korrekt!', saved: 'Registrering gemt!', updated: 'Registrering opdateret!', failed: 'Kunne ikke gemme registreringen', saveRegistrationLoggedOut: 'Log ind for at spare registrering', // question templates pain: 'Smerte' }, graphData: { from: 'Fra:', till: 'Til:', noData: 'Ingen data tilgængelige for denne periode.', table: 'Tabel', graph: 'Graf', //datetimepicker date: 'Dato', today: 'I dag', close: 'Luk', choose: 'Vælg', timestamp: 'Tidspunkt', //editing records update: 'Rediger', delete: 'Slet', cancel: 'Annuller', edit: 'Ændre registrering' } }); $translateProvider.determinePreferredLanguage(); //$translateProvider.preferredLanguage('da_DK'); $translateProvider.useSanitizeValueStrategy('escape'); // security setting $translateProvider.fallbackLanguage(['en', 'da_DK']); }
mit
bagabont/hotkey-ninja
source/server/config/express.js
2642
var express = require('express'), User = require('../models/user'), multer = require('multer'), Application = require('../models/application'), bodyParser = require('body-parser'); module.exports = function (config, app, passport) { //Initialize passport app.use(passport.initialize()); // Create default administrator account, if it does not exist (function createAdminAccount() { User.findOne({username: 'admin'}, function (err, user) { if (err) { throw err; } if (user) { return; } user = new User({ username: 'admin', password: 'admin' }); user.save(function (err) { if (err) { throw err; } console.log('Admin account created!'); }); }); })(); app.disable('x-powered-by'); app.disable('etag'); app.set('view engine', 'jade'); app.set('views', config.rootPath + '/server/views'); // configure public directory app.use(express.static(config.rootPath + '/public')); app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); // configure file uploader app.use(multer({inMemory: true})); // app.use(express.json()); // to support JSON-encoded bodies // app.use(express.urlencoded()); // setup routers app.use('/api/v1/applications', require('../routes/applications')(passport)); // app.use(function (req, res, next) { // res.setHeader('Content-Type', 'text/plain') // res.end(JSON.stringify(req.body, null, 2)) // next(); // }) app.use('/', require('../routes/dojo')()); app.use('/', require('../routes/admin')(passport)); app.get('/', function (req, res, next) { Application.find({}, function (err, models) { if (err) { return next(err); } var applications = []; for (var i = 0; i < models.length; i++) { var app = { id: models[i].id, name: models[i].name, platform: models[i].platform }; applications.push(app); } res.render('index', { title: 'Hotkey Ninja', applications: applications }); //res.end(JSON.stringify(req.body, null, 2)); //next(); }); }); };
mit
kadet1090/KeyLighter
Matcher/DelegateRegexMatcher.php
1317
<?php declare(strict_types=1); /** * Highlighter * * Copyright (C) 2016, Some right reserved. * * @author Kacper "Kadet" Donat <kacper@kadet.net> * * Contact with author: * Xmpp: me@kadet.net * E-mail: contact@kadet.net * * From Kadet with love. */ namespace Kadet\Highlighter\Matcher; use Kadet\Highlighter\Parser\TokenFactoryInterface; class DelegateRegexMatcher implements MatcherInterface { private $regex; private $callable; /** * RegexMatcher constructor. * * @param $regex * @param callable $callable */ public function __construct($regex, callable $callable) { $this->regex = $regex; $this->callable = $callable; } /** * Matches all occurrences and returns token list * * @param string $source Source to match tokens * * @param TokenFactoryInterface $factory * * @return \Generator */ public function match($source, TokenFactoryInterface $factory) { preg_match_all($this->regex, $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); $callable = $this->callable; foreach ($matches as $match) { foreach ($callable($match, $factory) as $token) { yield $token; } } } }
mit
evanlok/belongs_to_hstore
lib/belongs_to_hstore/version.rb
47
module BelongsToHstore VERSION = '0.0.3' end
mit
amireh/sinatra-api
spec/helpers/rspec_api_response_matchers.rb
3760
module RSpec module APIResponseMatchers class Fail def initialize(http_rc = 400, *keywords) @http_rc = http_rc @keywords = (keywords || []).flatten @raw_keywords = @keywords.dup end def matches?(api_rc) if api_rc.is_a?(Proc) api_rc = api_rc.yield end @api_rc = api_rc return false if api_rc.http_rc != @http_rc return false if api_rc.status != :error if @keywords.empty? return true if api_rc.messages.empty? return false end if @keywords.size == 1 @keywords = @keywords.first.split(/\s/) end @keywords = Regexp.new(@keywords.join('.*'), 'i') matched = false api_rc.messages.each { |m| if m.match(@keywords) matched = true break end } matched end # Fail#matches def failure_message m = "Expected: \n" if @api_rc.status != :error m << "* The API response status to be :error, but got #{@api_rc.status}\n" end if @api_rc.http_rc != @http_rc m << "* The HTTP RC to be #{@http_rc}, but got #{@api_rc.http_rc}\n" end formatted_keywords = @raw_keywords.join(' ') if @raw_keywords.any? && @api_rc.messages.any? m << "* One of the following API response messages: \n" m << @api_rc.messages.collect.with_index { |m, i| "\t#{i+1}. #{m}" }.join("\n") m << "\n to be matched by the keywords: #{formatted_keywords}\n" elsif @raw_keywords.any? && @api_rc.messages.empty? m << "* The API response to contain some messages (got 0) and for at least\n" << " one of them to match the keywords #{formatted_keywords}\n" elsif @raw_keywords.empty? && @api_rc.messages.any? m << "* The API response to contain no messages, but got: \n" m << @api_rc.messages.collect.with_index { |m, i| "\t#{i+1}. #{m}" }.join("\n") m << "\n" end m end # def negative_failure_message # "expected API response [status:#{@api_rc.status}] not to be :error, " << # "and API response [messages: #{@api_rc.messages}] not to match '#{@keywords}'" # end end # Fail class Success def initialize(http_rc) @http_rc = http_rc end def matches?(api_rc) if api_rc.is_a?(Proc) api_rc = api_rc.yield end @api_rc = api_rc return false unless @http_rc.include?(api_rc.http_rc) return false if api_rc.status != :success true end def failure_message m = "Expected:\n" if @api_rc.status != :success m << "* The API response status to be :success, but got #{@api_rc.status}\n" end if @api_rc.http_rc != @http_rc m << "* The HTTP RC to be #{@http_rc}, but got #{@api_rc.http_rc}\n" end if @api_rc.messages.any? m << "* The API response messages to be empty, but got: \n" m << @api_rc.messages.collect.with_index { |m, i| "\t#{i+1}. #{m}" }.join("\n") m << "\n" end m end # def negative_failure_message # m = "expected API response [status:#{@api_rc.status}] not to be :success" # if @api_rc.messages.any? # m << ", and no messages, but got: #{@api_rc.messages}" # end # m # end end def fail(http_rc = 400, *keywords) Fail.new(http_rc, keywords) end def succeed(http_rc = 200..205) http_rc = http_rc.respond_to?(:to_a) ? http_rc.to_a : [ http_rc ] Success.new(http_rc.flatten) end end end
mit
tyson-nw/xmlForm
oldsrc/validator/Validator_Date.php
210
<?php class Validator_Date extends Validator{ static function Validate($input, $value){ //TODO:: test for date return $value; throw new ValidateException("$value is not a properly formatted date"); } }
mit
mjacobus/gossiper
lib/gossiper/mailer.rb
703
module Gossiper class Mailer < ActionMailer::Base def mail_for(notification) @notification = NotificationDecorator.new(notification) config = notification config.attachments.each do |filename, file| attachments[filename] = file end config.instance_variables.each do |name, value| instance_variable_set("@#{name}", value) end mail( from: config.from, reply_to: config.reply_to, to: config.to, cc: config.cc, bcc: config.bcc, subject: config.subject, template_name: config.template_name, template_path: config.template_path ) end end end
mit
dirkrombauts/production-helper-for-ti3
ProductionHelperForTI3.Domain/Technologies.cs
283
using System; namespace ProductionHelperForTI3.Domain { public static class Technologies { public static Technology SarweenTools = new Technology("Sarween Tools"); public static Technology EnviroCompensator = new Technology("Enviro Compensator"); } }
mit
Spurch/ASP-.NET-WebForms
DataBindingHomeWork/Account/Register.aspx.designer.cs
1744
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DataBindingHomeWork.Account { public partial class Register { /// <summary> /// ErrorMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal ErrorMessage; /// <summary> /// Email control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Email; /// <summary> /// Password control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Password; /// <summary> /// ConfirmPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox ConfirmPassword; } }
mit
Prev/jikji
jikji/sample_proj/pages.py
1777
from jikji import getview, addpage # It is a sample data for this project. # You can call API using http, or fetching data from RDBMS instead of fixed data. item_list = [ {'id': 1, 'image_url': '/images/image1.jpg', 'location': 'Paris, France', 'year': '2018'}, {'id': 2, 'image_url': '/images/image2.jpg', 'location': 'San Francisco, CA', 'year': '2017'}, {'id': 3, 'image_url': '/images/image3.jpg', 'location': 'Seattle, WA', 'year': '2018'}, {'id': 4, 'image_url': '/images/image4.jpg', 'location': 'Seoul, Korea', 'year': '2018'}, {'id': 5, 'image_url': '/images/image5.jpg', 'location': 'Venice, Italy', 'year': '2017'}, ] # In Jikji, `view` works similar with controller of MVC pattern. # Defining URL rule of the views can be done like below. getview('home.index').url_rule = '/' # If you pass a single dict object to the params, you can use property on the url rule. getview('gallery.index').url_rule = '/{id}/' # If you pass list object to the params, you can use '${number}' operator on the url rule. # For example, you may call the function `addpage` with params `[article_id, user_id, article_data]`, # then you can define url rule like below: # getview('article.index').url_rule = '/articles/$1/$2/' # Now you have to call `addpage` for the views. # Jikji will automatically generate the pages by calling view functions with given params. for item in item_list: addpage(view='gallery.index', params=item) # Note that if you want to pass a **single list-type param**, embrace it with a tuple or a list. # Otherwise, jikji will try to decompose the list to multiple params, e.g., # params=['a', 'b', 'c'] => index('a', 'b', 'c'), while you may want # params=(['a', 'b', 'c'],) => index(['a', 'b', 'c']). addpage(view='home.index', params=(item_list,))
mit
cannabisdark/cannabisdarkcoin
src/qt/locale/cannabisdarkcoin_ko_KR.ts
117293
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ko_KR" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;cannabisdarkcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2014 CannabisDarkcoin team Copyright © 2014 The cannabisdarkcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <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> 이 프로그램은 시험용입니다. MIT/X11 프로그램 라이선스에 따라 배포합니다. COPYING 또는 http://www.opensource.org/licenses/mit-license.php를 참조하십시오. 이 프로그램에는 OpenSSL 툴킷(http://www.openssl.org) 사용 목적으로 개발한 OpenSSL 프로젝트를 포함하고 있으며, 암호화 프로그램은 Eric Young(eay@cryptsoft.com)이, UPnP 프로그램은 Thomas Bernard가 작성했습니다.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>주소 또는 표를 편집하기 위해 더블클릭 하시오</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>새 주소 만들기</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>현재 선택한 주소를 시스템 클립보드로 복사하기</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your cannabisdarkcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>계좌 복사(&amp;C)</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>현재 목록에 선택한 주소 삭제</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;삭제</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>표 복사</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>편집&amp;</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>각각의 파일에 쉼표하기(*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>표</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>주소</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(표 없음)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>암호문 대화상자</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>암호 입력하기</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>새로운 암호</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>새 암호 반복</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <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>새로운 암호를 지갑에 입력. 8자보다 많은 단어를 입력하거나 10 자보다 많은 여러 종류를 암호에 사용하세요.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>지갑 암호화</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>이 작업은 지갑을 열기위해 사용자의 지갑의 암호가 필요합니다.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>지갑 열기</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>이 작업은 지갑을 해독하기 위해 사용자의 지갑 암호가 필요합니다.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>지갑 해독</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>암호 변경</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>지갑의 예전 암호와 새로운 암호를 입력</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>지갑의 암호화를 확정</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 COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>지갑 암호화를 허용하시겠습니까?</translation> </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="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>경고: 캡스록 키가 켜져있습니다!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>지갑 암호화 완료</translation> </message> <message> <location line="-58"/> <source>cannabisdarkcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>지갑 암호화 실패</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>지갑 암호화는 내부 에러로 인해 실패했습니다. 당신의 지갑은 암호화 되지 않았습니다.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>지정한 암호가 일치하지 않습니다.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>지갑 열기를 실패하였습니다.</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>지갑 해독을 위한 암호가 틀렸습니다.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>지갑 해독에 실패하였습니다.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>지갑 비밀번호가 성공적으로 변경되었습니다</translation> </message> </context> <context> <name>CannabisDarkcoinGUI</name> <message> <location filename="../cannabisdarkcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>메시지 서명&amp;...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>네트워크와 동기화중...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;개요</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>지갑의 일반적 개요를 보여 줍니다.</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;거래</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>거래내역을 검색합니다.</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>나가기(&amp;X)</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>적용 중단</translation> </message> <message> <location line="+6"/> <source>Show information about cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Qt 정보(&amp;Q)</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Qt 정보를 표시합니다</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;옵션</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>지갑 암호화&amp;...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>지갑 백업&amp;...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>암호문 변경&amp;...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>지갑을 다른장소에 백업</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>지갑 암호화에 사용되는 암호를 변경합니다</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>디버그 창&amp;</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>디버깅 및 진단 콘솔을 엽니다</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>메시지 확인&amp;...</translation> </message> <message> <location line="-202"/> <source>cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>지갑</translation> </message> <message> <location line="+180"/> <source>&amp;About cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>보이기/숨기기(&amp;S)</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;파일</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;설정</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;도움말</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>툴바 색인표</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[테스트넷]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>cannabisdarkcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to cannabisdarkcoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About cannabisdarkcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about cannabisdarkcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>현재까지</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>따라잡기...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <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="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>거래 보내기</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>거래 들어오는 중</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>날짜: %1 거래액: %2 형식: %3 주소: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid cannabisdarkcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>지갑이 암호화 되었고 현재 차단해제 되었습니다</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>지갑이 암호화 되었고 현재 잠겨져 있습니다</translation> </message> <message> <location line="+25"/> <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 numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>시간</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>일</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../cannabisdarkcoin.cpp" line="+109"/> <source>A fatal error occurred. cannabisdarkcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>네트워크 경고</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>수량:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>거래량</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>우선도:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>수수료:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>아니요</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>수수료 이후:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>트리 모드</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>리스트 모드</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>거래량</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>주소</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>날짜</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>확인</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>확인됨</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>우선도</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>주소 복사하기</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>라벨 복사하기</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>거래액 복사</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>송금 ID 복사</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>수량 복사</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>수수료 복사</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>수수료 이후 복사</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>bytes를 복사</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>우선도 복사</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation>최상</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>상</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>중상</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>중</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>중하</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>하</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>예</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(표 없슴)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>~로부터 변경 %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>주소 편집</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;표</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;주소</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>새로 받는 주소</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>새로 보내는 주소</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>받는 주소 편집</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>보내는 주소 편집</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>입력된 주소는&quot;%1&quot; 이미 주소록에 있습니다.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid cannabisdarkcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>지갑을 열 수 없습니다.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>새로운 키 생성이 실패하였습니다</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>cannabisdarkcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </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> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>선택들</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>메인(&amp;M)</translation> </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. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>송금 수수료(&amp;F)</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start cannabisdarkcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start cannabisdarkcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>네트워크(&amp;N)</translation> </message> <message> <location line="+6"/> <source>Automatically open the cannabisdarkcoin 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>사용중인 UPnP 포트 매핑(&amp;U)</translation> </message> <message> <location line="+7"/> <source>Connect to the cannabisdarkcoin 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>프록시 IP(&amp;I):</translation> </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>포트(&amp;P):</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>프록시의 포트번호입니다(예: 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 버전(&amp;V):</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>프록시의 SOCKS 버전입니다(예: 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>창(&amp;W)</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>창을 최소화 하면 트레이에 아이콘만 표시합니다.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>작업 표시줄 대신 트레이로 최소화(&amp;M)</translation> </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>창을 닫으면 프로그램에서 나가지 않고 최소화합니다. 이 옵션을 활성화하면, 프로그램은 메뉴에서 나가기를 선택한 후에만 닫힙니다.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>닫을때 최소화(&amp;I)</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>표시(&amp;D)</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>사용자 인터페이스 언어(&amp;L):</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting cannabisdarkcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>거래액을 표시할 단위(&amp;U):</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>인터페이스에 표시하고 코인을 보낼때 사용할 기본 최소화 단위를 선택하십시오.</translation> </message> <message> <location line="+9"/> <source>Whether to show cannabisdarkcoin 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>송금 목록에 주소 표시(&amp;D)</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>확인(&amp;O)</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>취소(&amp;C)</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>기본값</translation> </message> <message> <location line="+149"/> <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 cannabisdarkcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>지정한 프록시 주소가 잘못되었습니다.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>유형</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the cannabisdarkcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>지갑</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>당신의 현재 사용 가능한 잔액</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>아직 사용 불가능:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>아직 사용 가능하지 않은 채굴된 잔액</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>총액:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>당신의 현재 총액</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;최근 거래내역&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>오래됨</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <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>클라이언트 이름</translation> </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="+348"/> <source>N/A</source> <translation>없음</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>클라이언트 버전</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>정보&amp;</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>오픈SSL 버전을 사용합니다</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>시작 시간</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>네트워크</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>연결 수</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>블럭 체인</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>현재 블럭 수</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>예상 전체 블럭</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>최종 블럭 시각</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>열기(&amp;O)</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the cannabisdarkcoin-Qt help message to get a list with possible cannabisdarkcoin 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>콘솔(&amp;C)</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>빌드 날짜</translation> </message> <message> <location line="-104"/> <source>cannabisdarkcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>cannabisdarkcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>로그 파일 디버그</translation> </message> <message> <location line="+7"/> <source>Open the cannabisdarkcoin 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>콘솔 초기화</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the cannabisdarkcoin 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>기록을 찾아보려면 위 아래 화살표 키를, 화면을 지우려면 &lt;b&gt;Ctrl-L&lt;/b&gt;키를 사용하십시오.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>사용할 수 있는 명령을 둘러보려면 &lt;b&gt;help&lt;/b&gt;를 입력하십시오.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>코인들 보내기</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>코인 컨트롤 기능들</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>자동 선택</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>자금이 부족합니다!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>수량:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>거래량:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>우선도:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>수수료:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>수수료 이후:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>다수의 수령인들에게 한번에 보내기</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>수령인 추가하기</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>모두 지우기(&amp;A)</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>잔액:</translation> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>전송 기능 확인</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>보내기(&amp;E)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a cannabisdarkcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>수량 복사</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>거래액 복사</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>수수료 복사</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>수수료 이후 복사</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>bytes 복사</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>우선도 복사</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>코인 전송을 확인</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>수령인 주소가 정확하지 않습니다. 재확인 바랍니다</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>지불하는 금액은 0 보다 커야 합니다.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>잔고를 초과하였습니다.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>%1 의 거래수수료를 포함하면 잔고를 초과합니다.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>두개 이상의 주소입니다. 한번에 하나의 주소에만 작업할 수 있습니다.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <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="+251"/> <source>WARNING: Invalid cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(표 없슴)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>금액:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>지급&amp;수신:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>당신의 주소록에 이 주소를 추가하기 위하여 표를 입역하세요 </translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>표:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>클립보드로 부터 주소를 붙이세요</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a cannabisdarkcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>서명 - 싸인 / 메시지 확인</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>메시지 서명(&amp;S)</translation> </message> <message> <location line="-118"/> <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>여러분 자신을 증명하기 위해 주소를 첨가하고 섬여할 수 있습니다. 피싱 공격으로 말미암아 여러분의 서명을 통해 속아 넘어가게 할 수 있으므로, 서명하지 않은 어떤 모호한 요소든 주의하십시오. 동의하는 완전 무결한 조항에만 서명하십시오.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>클립보드로 부터 주소를 붙이세요</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>여기에 서명하려는 메시지를 입력하십시오</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>현재 서명을 시스템 클립보드에 복사</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>메시지 필드의 모든 서명 재설정</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>모두 지우기(&amp;A)</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>메시지 검증(&amp;V)</translation> </message> <message> <location line="-64"/> <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. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified cannabisdarkcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>모든 검증 메시지 필드 재설정</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a cannabisdarkcoin address (e.g. EakqhrmwJuHG22WirpfBvQMMUuisWZNzrP)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>서명을 만들려면 &quot;메시지 서명&quot;을 누르십시오</translation> </message> <message> <location line="+3"/> <source>Enter cannabisdarkcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>입력한 주소가 잘못되었습니다.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>주소를 확인하고 다시 시도하십시오.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>입력한 주소는 키에서 참조하지 않습니다.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>지갑 잠금 해제를 취소했습니다.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>입력한 주소에 대한 개인키가 없습니다.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>메시지 서명에 실패했습니다.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>메시지를 서명했습니다.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>서명을 해독할 수 없습니다.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>서명을 확인하고 다시 시도하십시오.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>메시지 다이제스트와 서명이 일치하지 않습니다.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>메시지 검증에 실패했습니다.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>메시지를 검증했습니다.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>%1 까지 열림</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>충돌</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/오프라인</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/미확인</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 확인됨</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>상태</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>날짜</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>소스</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>생성하다</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>으로부터</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>에게</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>자신의 주소</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>라벨</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>예금</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>허용되지 않는다</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>차변</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>송금 수수료</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>총액</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>메시지</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>설명</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>송금 ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 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="+7"/> <source>Debug information</source> <translation>디버깅 정보</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>송금</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>입력</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>거래량</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>참</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>거짓</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>. 아직 성공적으로 통보하지 않음</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>알수없음</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>거래 세부 내역</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>이 창은 거래의 세부내역을 보여줍니다</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>날짜</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>형식</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>주소</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>수량</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>%1 까지 열림</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>확인됨(%1 확인됨)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>오프라인</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>미확인</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>충돌</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>이 블럭은 다른 노드로부터 받지 않아 허용되지 않을 것임.</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>생성되었으나 거절됨</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>다음과 함께 받음 : </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>보낸 주소</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>다음에게 보냄 :</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>자신에게 지불</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>채굴됨</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(없음)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>거래상황. 마우스를 올리면 승인횟수가 표시됩니다.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>거래가 이루어진 날짜와 시각.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>거래의 종류.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>거래가 도달할 주소</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>변경된 잔고.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>전체</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>오늘</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>이번주</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>이번 달</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>지난 달</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>올 해</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>범위...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>보낸 주소</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>받는 주소</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>자기거래</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>채굴</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>기타</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>검색하기 위한 주소 또는 표 입력</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>최소 거래량</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>주소 복사하기</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>표 복사하기</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>거래액 복사</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>송금 ID 복사</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>표 수정하기</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>거래 내역 확인</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>각각의 파일에 쉼표하기(*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>확인됨</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>날짜</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>종류</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>표</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>주소</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>거래량</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>아이디</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>범위:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>상대방</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>cannabisdarkcoin-core</name> <message> <location filename="../cannabisdarkcoinstrings.cpp" line="+33"/> <source>cannabisdarkcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>사용법:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or cannabisdarkcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>커맨드 목록</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>커맨드 도움말</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>옵션:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: cannabisdarkcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: cannabisdarkcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>데이터 폴더 안에 지갑 파일을 선택하세요.</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>데이터 폴더 지정</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>데이터베이스 캐시 크기를 메가바이트로 지정(기본값:25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>가장 잘 연결되는 사용자를 유지합니다(기본값: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>피어 주소를 받기 위해 노드에 연결하고, 받은 후에 연결을 끊습니다</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>공인 주소를 지정하십시오</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>이상행동 네트워크 참여자의 연결을 차단시키기 위한 한계치 (기본값: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>이상행동을 하는 네트워크 참여자들을 다시 연결시키는데 걸리는 시간 (기본값: 86400초)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>IPv4 감청을 위한 RPC 포트 %u번을 설정중 오류가 발생했습니다: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <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="-5"/> <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="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>명령줄과 JSON-RPC 명령 수락</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>데몬으로 백그라운드에서 실행하고 명령을 허용</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>테스트 네트워크 사용</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>외부 접속을 승인합니다</translation> </message> <message> <location line="-38"/> <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="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>경고: -paytxfee값이 너무 큽니다! 이 값은 송금할때 지불할 송금 수수료입니다.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong cannabisdarkcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <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="-18"/> <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="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>손상된 wallet.dat에서 개인키 복원을 시도합니다</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>블록 생성 옵션:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>지정된 노드에만 연결하기</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <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="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <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="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the CannabisDarkcoin Wiki for SSL setup instructions)</source> <translation>SSL 옵션: (SSL 설정 절차를 보혀면 비트코인 위키를 참조하십시오)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>추적오류 정보를 degug.log 자료로 보내는 대신 콘솔로 보내기</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <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>바이트 단위의 최소 블록 크기 설정(기본값: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>클라이언트 시작시 debug.log 파일 비우기(기본값: 디버그 안할때 1)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>밀리초 단위로 연결 제한시간을 설정하십시오(기본값: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <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="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 연결에 사용할 사용자 이름</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>경고: 이 버전이 오래되어 업그레이드가 필요합니다!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat 파일이 손상되었고 복구가 실패하였습니다.</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 연결에 사용할 암호</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=cannabisdarkcoinrpc 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;cannabisdarkcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>지정한 IP 주소의 JSON-RPC 연결 허용</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>실행 중인 노드로 명령 전송 &lt;ip&gt; (기본값: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>최고의 블럭이 변하면 명령을 실행(cmd 에 있는 %s 는 블럭 해시에 의해 대체되어 짐)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>지갑을 최근 형식으로 개선하시오</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>키 풀 크기 설정 &lt;n&gt;(기본값: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>누락된 지갑 송금에 대한 블록 체인 다시 검색</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>JSON-RPC 연결에 OpenSSL(https) 사용</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>서버 인증 파일 (기본값: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>서버 개인 키(기본값: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>도움말 메시지입니다</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. cannabisdarkcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>이 컴퓨터의 %s에 바인딩할 수 없습니다 (바인딩 과정에 %d 오류 발생, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>-addnode, -seednode, -connect 옵션에 대해 DNS 탐색 허용</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>주소를 불러오는 중...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>wallet.dat 불러오기 에러: 지갑 오류</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of cannabisdarkcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart cannabisdarkcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>wallet.dat 불러오기 에러</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>잘못된 -proxy 주소입니다: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>-onlynet에 지정한 네트워크를 알 수 없습니다: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>요청한 -socks 프록히 버전을 알 수 없습니다: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind 주소를 확인할 수 없습니다: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip 주소를 확인할 수 없습니다: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;amount&gt;에 대한 양이 잘못되었습니다: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>효력없는 금액</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>자금 부족</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>블럭 인덱스를 불러오는 중...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. cannabisdarkcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>지갑을 불러오는 중...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>지갑을 다운그레이드 할 수 없습니다</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>기본 계좌에 기록할 수 없습니다</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>재검색 중...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>로딩 완료</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>%s 옵션을 사용하려면</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>오류</translation> </message> <message> <location line="+6"/> <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>설정 파일에 rpcpassword=&lt;암호&gt;를 설정해야 합니다: %s 파일이 없으면 소유자 읽기 전용 파일 권한으로 만들어야 합니다.</translation> </message> </context> </TS>
mit
SpringMT/worker_scoreboard
spec/spec_helper.rb
87
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'worker_scoreboard'
mit
cloudant-labs/azure-storage-liberation
examples/Azure2CouchDB/Azure2CouchDB/DynamicTableEntityToCouchDBEntityConverter.cs
1771
using Azure.Storage.Liberation; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; namespace Azure2CouchDB { class DynamicTableEntityToCouchDBEntityConverter : DynamicTableEntityConverter { private readonly string tableName; public DynamicTableEntityToCouchDBEntityConverter(string tableName) { this.tableName = tableName; } protected override void WriteObjectProperties(JsonWriter writer, DynamicTableEntity entity) { GenerateUniqueId(writer, entity); WriteAzureMetaData(writer, entity); foreach (var property in entity.Properties) { WriteProperty(writer, property); } } private void GenerateUniqueId(JsonWriter writer, DynamicTableEntity entity) { var idValue = string.Format("{0}-{1}-{2}", tableName, entity.PartitionKey, entity.RowKey); writer.WritePropertyName("_id"); writer.WriteValue(idValue); } private void WriteAzureMetaData(JsonWriter writer, DynamicTableEntity entity) { writer.WritePropertyName("AzureMetaData"); writer.WriteStartObject(); writer.WritePropertyName("Table"); writer.WriteValue(tableName); writer.WritePropertyName("PartitionKey"); writer.WriteValue(entity.PartitionKey); writer.WritePropertyName("RowKey"); writer.WriteValue(entity.RowKey); writer.WritePropertyName("Timestamp"); writer.WriteValue(entity.Timestamp); writer.WritePropertyName("ETag"); writer.WriteValue(entity.ETag); writer.WriteEndObject(); } } }
mit
UFABC-NoBox/NoPlan
server.js
2059
const _ = require('lodash') const chalk = require('chalk') const inquirer = require('inquirer') const SerialPort = require('serialport') const comm = require('./lib/Comm.js') require('draftlog').into(console) const Match = require('./lib/Match') const MatchSimulated = require('./lib/MatchSimulated') const MatchSSLSimulated = require('./lib/MatchSSLSimulated') const players = require('require-smart')('./players') const test_players = require('require-smart')('./players/tests') const PORT = 10006 const HOST = '224.5.23.2' const sleep = ms => new Promise((res, rej) => setTimeout(res, ms)) const TAG = 'server' const isSimulated = !!process.env.SIMULATED const usePrediction = false const noStation = process.env.NO_STATION | false async function startup(){ console.info(TAG, chalk.yellow('startup')) console.info(TAG, chalk.yellow('isSimulated'), isSimulated) console.info(TAG, chalk.yellow('usePrediction'), usePrediction) let MatchClass = (isSimulated ? MatchSimulated : Match) if(noStation) { MatchClass = MatchSSLSimulated } let match = new MatchClass({ vision: { PORT, HOST }, robots: { attacker: { visionId: 2, radioId: 2, class: test_players.OrbitalIntentionPlayer, predict: usePrediction, } }, driver: { port: ( (isSimulated || noStation) ? null : await getPort('/dev/ttyUSB0')), debug: true, baudRate: 115200, } }) await match.init() console.log('Listening in:', PORT) await comm(match, {PORT:8080}) } process.on('unhandledRejection', (e) => { console.error('Unhandled Rejection') console.error(e) process.exit(1) }) startup() async function getPort(prefered) { let ports = await SerialPort.list() let found = _.find(ports, {comName: prefered}) if (found) return prefered console.log(`Port '${prefered}' not available`) let answer = await inquirer.prompt({ type: 'list', name: 'port', choices: _.map(ports, 'comName'), message: 'Select Cursor port' }) return answer.port }
mit
chrisJohn404/ljswitchboard-builder
build_scripts/sign_mac_build_before_compression.js
3613
console.log('sign_mac_build_before_compression'); var errorCatcher = require('./error_catcher'); var fs = require('fs'); var fse = require('fs-extra'); var fsex = require('fs.extra'); var path = require('path'); var q = require('q'); var async = require('async'); var child_process = require('child_process'); // Figure out what OS we are building for var buildOS = { 'darwin': 'darwin', 'win32': 'win32' }[process.platform]; if(typeof(buildOS) === 'undefined') { buildOS = 'linux'; } var curVersion = process.versions.node.split('.').join('_'); var pathToBinaryPartials = [ __dirname, '..', 'temp_project_files', 'ljswitchboard-io_manager', 'node_binaries', buildOS, process.arch, curVersion, 'node' ].join(path.sep); var pathToRefBindingNode = [ __dirname, '..', 'temp_project_files', 'ljswitchboard-io_manager', 'node_modules', 'ref','build','Release','binding.node' ].join(path.sep); var pathToFFIBindingNode = [ __dirname, '..', 'temp_project_files', 'ljswitchboard-io_manager', 'node_modules', 'ffi','build','Release','ffi_bindings.node' ].join(path.sep); var pathToParentPListPartials = [ __dirname, '..', 'branding_files', 'kipling_parent.plist' ].join(path.sep) var pathToChildPListPartials = [ __dirname, '..', 'branding_files', 'kipling_child.plist' ].join(path.sep); var nodePath = path.resolve(path.join(pathToBinaryPartials)); var refBindingPath = path.resolve(path.join(pathToRefBindingNode)); var ffiBindingPath = path.resolve(path.join(pathToFFIBindingNode)); var pathToParentPList = path.resolve(path.join(pathToParentPListPartials)) var pathToChildPList = path.resolve(path.join(pathToChildPListPartials)) if(typeof(process.argv) !== 'undefined') { var cliArgs = process.argv; if(process.argv.length == 4) { // Get rid of the first two arguments cliArgs = cliArgs.slice(2, cliArgs.length); nodePath = cliArgs[1].split('"').join(); } } console.log('nodePath', nodePath); var buildScripts = [{ 'script': ['codesign --sign "LabJack Corporation" --force --timestamp --options runtime', '--deep --entitlements "'+pathToParentPList+'"', '"' + nodePath + '"'].join(' '), 'text': 'Signing Node.exe', }, { 'script': ['codesign --sign "LabJack Corporation" --force --timestamp --options runtime', '--deep --entitlements "'+pathToParentPList+'"', '"' + refBindingPath + '"'].join(' '), 'text': 'Signing ref: binding.node', }, { 'script': ['codesign --sign "LabJack Corporation" --force --timestamp --options runtime', '--deep --entitlements "'+pathToParentPList+'"', '"' + ffiBindingPath + '"'].join(' '), 'text': 'Signing ffi: ffi_binding.node', }]; buildScripts.forEach(function(buildScript) { buildScript.cmd = buildScript.script; buildScript.isFinished = false; buildScript.isSuccessful = false; }); async.eachSeries( buildScripts, function(buildScript, cb) { console.log('Starting Step:', buildScript.text); child_process.exec(buildScript.cmd, function(error, stdout, stderr) { if (error) { console.error('Error Executing', error); console.error(buildScript.script, buildScript.text); cb(error); } console.log('stdout: ',stdout); console.log('stderr: ',stderr); cb(); }) }, function(err) { if(err) { console.log('Error Executing Build Scripts...', err); process.exit(1); } }); // buildScripts.forEach(function(buildScript) { // try { // console.log('Starting Step:', buildScript.text); // var execOutput = child_process.execSync(buildScript.cmd); // console.log('execOutput: ' , execOutput.toString()); // } catch(err) { // process.exit(1); // } // });
mit
khyrulimam/PTUN-Report-Tool
src/main/java/com/ptun/app/eventbus/events/ManagemenTimeEvent.java
351
package com.ptun.app.eventbus.events; import com.ptun.app.db.models.TimeManagement; import lombok.Data; /** * Created by Lenovo on 4/29/2017. */ @Data public class ManagemenTimeEvent { private TimeManagement timeManagement; public ManagemenTimeEvent(TimeManagement timeManagement) { this.timeManagement = timeManagement; } }
mit
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/md/ic_airline_seat_flat_angled.js
496
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ic_airline_seat_flat_angled = exports.ic_airline_seat_flat_angled = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M22.25 14.29l-.69 1.89L9.2 11.71l2.08-5.66 8.56 3.09c2.1.76 3.18 3.06 2.41 5.15zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94c1.49-.72 2.12-2.51 1.41-4C7.99 4.71 6.2 4.08 4.7 4.8c-1.49.71-2.12 2.5-1.4 4 .71 1.49 2.5 2.12 4 1.4z" } }] };
mit
Azure/azure-sdk-for-python
sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/operations/_private_endpoint_connections_operations.py
23508
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class PrivateEndpointConnectionsOperations(object): """PrivateEndpointConnectionsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.cosmosdb.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_database_account( self, resource_group_name, # type: str account_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.PrivateEndpointConnectionListResult"] """List all private endpoint connections on a Cosmos DB account. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.cosmosdb.models.PrivateEndpointConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-10-15" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_database_account.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('PrivateEndpointConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_database_account.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections'} # type: ignore def get( self, resource_group_name, # type: str account_name, # type: str private_endpoint_connection_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.PrivateEndpointConnection" """Gets a private endpoint connection. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection, or the result of cls(response) :rtype: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-10-15" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str account_name, # type: str private_endpoint_connection_name, # type: str parameters, # type: "_models.PrivateEndpointConnection" **kwargs # type: Any ): # type: (...) -> Optional["_models.PrivateEndpointConnection"] cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.PrivateEndpointConnection"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-10-15" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'PrivateEndpointConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str account_name, # type: str private_endpoint_connection_name, # type: str parameters, # type: "_models.PrivateEndpointConnection" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.PrivateEndpointConnection"] """Approve or reject a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. :type private_endpoint_connection_name: str :param parameters: :type parameters: ~azure.mgmt.cosmosdb.models.PrivateEndpointConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.cosmosdb.models.PrivateEndpointConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str account_name, # type: str private_endpoint_connection_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-10-15" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str account_name, # type: str private_endpoint_connection_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param account_name: Cosmos DB database account name. :type account_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, account_name=account_name, private_endpoint_connection_name=private_endpoint_connection_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'), 'privateEndpointConnectionName': self._serialize.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}'} # type: ignore
mit
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/fa/handPointerO.js
926
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var handPointerO = exports.handPointerO = { "viewBox": "0 0 1792 1792", "children": [{ "name": "path", "attribs": { "d": "M640 128q-53 0-90.5 37.5t-37.5 90.5v512 384l-151-202q-41-54-107-54-52 0-89 38t-37 90q0 43 26 77l384 512q38 51 102 51h718q22 0 39.5-13.5t22.5-34.5l92-368q24-96 24-194v-217q0-41-28-71t-68-30-68 28-28 68h-32v-61q0-48-32-81.5t-80-33.5q-46 0-79 33t-33 79v64h-32v-90q0-55-37-94.5t-91-39.5q-53 0-90.5 37.5t-37.5 90.5v96h-32v-570q0-55-37-94.5t-91-39.5zM640 0q107 0 181.5 77.5t74.5 184.5v220q22-2 32-2 99 0 173 69 47-21 99-21 113 0 184 87 27-7 56-7 94 0 159 67.5t65 161.5v217q0 116-28 225l-92 368q-16 64-68 104.5t-118 40.5h-718q-60 0-114.5-27.5t-90.5-74.5l-384-512q-51-68-51-154 0-105 74.5-180.5t179.5-75.5q71 0 130 35v-547q0-106 75-181t181-75zM768 1408v-384h-32v384h32zM1024 1408v-384h-32v384h32zM1280 1408v-384h-32v384h32z" } }] };
mit
nicola/ldnode
lib/create-server.js
1835
module.exports = createServer var express = require('express') var fs = require('fs') var https = require('https') var http = require('http') var SolidWs = require('solid-ws') var debug = require('./debug') var createApp = require('./create-app') function createServer (argv) { argv = argv || {} var app = express() var ldpApp = createApp(argv) var ldp = ldpApp.locals.ldp var mount = argv.mount || '/' // Removing ending '/' if (mount.length > 1 && mount[mount.length - 1] === '/') { mount = mount.slice(0, -1) } app.use(mount, ldpApp) debug.settings('Base URL (--mount): ' + mount) var server = http.createServer(app) if (ldp && (ldp.webid || ldp.idp || argv.sslKey || argv.sslCert)) { debug.settings('SSL Private Key path: ' + argv.sslKey) debug.settings('SSL Certificate path: ' + argv.sslCert) if (!argv.sslCert && !argv.sslKey) { throw new Error('Missing SSL cert and SSL key to enable WebIDs') } if (!argv.sslKey && argv.sslCert) { throw new Error('Missing path for SSL key') } if (!argv.sslCert && argv.sslKey) { throw new Error('Missing path for SSL cert') } var key try { key = fs.readFileSync(argv.sslKey) } catch (e) { throw new Error('Can\'t find SSL key in ' + argv.sslKey) } var cert try { cert = fs.readFileSync(argv.sslCert) } catch (e) { throw new Error('Can\'t find SSL cert in ' + argv.sslCert) } var credentials = { key: key, cert: cert } if (ldp.webid && ldp.auth === 'tls') { credentials.requestCert = true } server = https.createServer(credentials, app) } // Setup Express app if (ldp.live) { var solidWs = SolidWs(server, ldpApp) ldpApp.locals.ldp.live = solidWs.publish.bind(solidWs) } return server }
mit
skygiraffe/skygiraffe-slackbot
src/main/java/com/sg/model/sgdsRs/repdet/ReportMetaData.java
8021
package com.sg.model.sgdsRs.repdet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.codehaus.jackson.annotate.JsonAnyGetter; import org.codehaus.jackson.annotate.JsonAnySetter; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.annotate.JsonPropertyOrder; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "ReportID", "ReportName", "ReportDescription", "ReportIcon", "ReportType", "Folder", "ReportOrdinal", "ReportSharedSlicers", "NumOfTabs", "Tabs", "ReportUpdateID", "IsHidden", "CredentialRequirements", "AtLeastOneParameterIsMandatory" }) public class ReportMetaData { @JsonProperty("ReportID") private String reportID; @JsonProperty("ReportName") private String reportName; @JsonProperty("ReportDescription") private String reportDescription; @JsonProperty("ReportIcon") private ReportIcon reportIcon; @JsonProperty("ReportType") private String reportType; @JsonProperty("Folder") private String folder; @JsonProperty("ReportOrdinal") private Integer reportOrdinal; @JsonProperty("ReportSharedSlicers") private List<ReportSharedSlicer> reportSharedSlicers = new ArrayList<ReportSharedSlicer>();@JsonProperty("NumOfTabs") private Integer numOfTabs; @JsonProperty("Tabs") private List<Tab> tabs = new ArrayList<Tab>(); @JsonProperty("ReportUpdateID") private String reportUpdateID; @JsonProperty("IsHidden") private Boolean isHidden; @JsonProperty("CredentialRequirements") private Object credentialRequirements; @JsonProperty("AtLeastOneParameterIsMandatory") private Boolean atLeastOneParameterIsMandatory; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The reportID */ @JsonProperty("ReportID") public String getReportID() { return reportID; } /** * * @param reportID * The ReportID */ @JsonProperty("ReportID") public void setReportID(String reportID) { this.reportID = reportID; } /** * * @return * The reportName */ @JsonProperty("ReportName") public String getReportName() { return reportName; } /** * * @param reportName * The ReportName */ @JsonProperty("ReportName") public void setReportName(String reportName) { this.reportName = reportName; } /** * * @return * The reportDescription */ @JsonProperty("ReportDescription") public String getReportDescription() { return reportDescription; } /** * * @param reportDescription * The ReportDescription */ @JsonProperty("ReportDescription") public void setReportDescription(String reportDescription) { this.reportDescription = reportDescription; } /** * * @return * The reportIcon */ @JsonProperty("ReportIcon") public ReportIcon getReportIcon() { return reportIcon; } /** * * @param reportIcon * The ReportIcon */ @JsonProperty("ReportIcon") public void setReportIcon(ReportIcon reportIcon) { this.reportIcon = reportIcon; } /** * * @return * The reportType */ @JsonProperty("ReportType") public String getReportType() { return reportType; } /** * * @param reportType * The ReportType */ @JsonProperty("ReportType") public void setReportType(String reportType) { this.reportType = reportType; } /** * * @return * The folder */ @JsonProperty("Folder") public String getFolder() { return folder; } /** * * @param folder * The Folder */ @JsonProperty("Folder") public void setFolder(String folder) { this.folder = folder; } /** * * @return * The reportOrdinal */ @JsonProperty("ReportOrdinal") public Integer getReportOrdinal() { return reportOrdinal; } /** * * @param reportOrdinal * The ReportOrdinal */ @JsonProperty("ReportOrdinal") public void setReportOrdinal(Integer reportOrdinal) { this.reportOrdinal = reportOrdinal; } /** * * @return * The reportSharedSlicers */ @JsonProperty("ReportSharedSlicers") public List<ReportSharedSlicer> getReportSharedSlicers() { return reportSharedSlicers; } /** * * @param reportSharedSlicers * The ReportSharedSlicers */ @JsonProperty("ReportSharedSlicers") public void setReportSharedSlicers(List<ReportSharedSlicer> reportSharedSlicers) { this.reportSharedSlicers = reportSharedSlicers; } /** * * @return * The numOfTabs */ @JsonProperty("NumOfTabs") public Integer getNumOfTabs() { return numOfTabs; } /** * * @param numOfTabs * The NumOfTabs */ @JsonProperty("NumOfTabs") public void setNumOfTabs(Integer numOfTabs) { this.numOfTabs = numOfTabs; } /** * * @return * The tabs */ @JsonProperty("Tabs") public List<Tab> getTabs() { return tabs; } /** * * @param tabs * The Tabs */ @JsonProperty("Tabs") public void setTabs(List<Tab> tabs) { this.tabs = tabs; } /** * * @return * The reportUpdateID */ @JsonProperty("ReportUpdateID") public String getReportUpdateID() { return reportUpdateID; } /** * * @param reportUpdateID * The ReportUpdateID */ @JsonProperty("ReportUpdateID") public void setReportUpdateID(String reportUpdateID) { this.reportUpdateID = reportUpdateID; } /** * * @return * The isHidden */ @JsonProperty("IsHidden") public Boolean getIsHidden() { return isHidden; } /** * * @param isHidden * The IsHidden */ @JsonProperty("IsHidden") public void setIsHidden(Boolean isHidden) { this.isHidden = isHidden; } /** * * @return * The credentialRequirements */ @JsonProperty("CredentialRequirements") public Object getCredentialRequirements() { return credentialRequirements; } /** * * @param credentialRequirements * The CredentialRequirements */ @JsonProperty("CredentialRequirements") public void setCredentialRequirements(Object credentialRequirements) { this.credentialRequirements = credentialRequirements; } /** * * @return * The atLeastOneParameterIsMandatory */ @JsonProperty("AtLeastOneParameterIsMandatory") public Boolean getAtLeastOneParameterIsMandatory() { return atLeastOneParameterIsMandatory; } /** * * @param atLeastOneParameterIsMandatory * The AtLeastOneParameterIsMandatory */ @JsonProperty("AtLeastOneParameterIsMandatory") public void setAtLeastOneParameterIsMandatory(Boolean atLeastOneParameterIsMandatory) { this.atLeastOneParameterIsMandatory = atLeastOneParameterIsMandatory; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
mit
TravisWheelerLab/NINJA
NINJA/CandidateHeap.cpp
4332
#include "CandidateHeap.hpp" CandidateHeap::CandidateHeap(std::string dir, int *activeIJs, int kPrime, TreeBuilderExtMem *tb, long sizeExp) : ArrayHeapExtMem(dir, activeIJs, sizeExp) { initialize(kPrime, tb); } CandidateHeap::CandidateHeap(std::string dir, int *activeIJs, int kPrime, TreeBuilderExtMem *tb) : ArrayHeapExtMem(dir, activeIJs) { initialize(kPrime, tb); } CandidateHeap::~CandidateHeap() { clear(); } void CandidateHeap::initialize(int kPrime, TreeBuilderExtMem *tb) { this->firstActiveNode = -1; this->origSize = 0; this->expired = false; this->representedRowCount = 0; this->tb = tb; this->kPrime = kPrime; rowCounts = new int[tb->nextInternalNode + 1](); rDeltas = new float[tb->nextInternalNode + 1](); nextActiveNode = new int[tb->nextInternalNode + 1](); prevActiveNode = new int[tb->nextInternalNode + 1](); rPrimes = new float[tb->RSize](); for (int i = 0; i < tb->RSize; i++) { rPrimes[i] = tb->R[i]; } } void CandidateHeap::insert(int i, int j, float key) { ArrayHeapExtMem::insert(i, j, key); rowCounts[i]++; rowCounts[j]++; } void CandidateHeap::buildNodeList() { origSize = ArrayHeapExtMem::size(); int prev = -1; for (int i = 0; i < tb->nextInternalNode + 1; i++) { if (rowCounts[i] > 0) { representedRowCount++; if (firstActiveNode == -1) { firstActiveNode = i; } else { prevActiveNode[i] = prev; nextActiveNode[prev] = i; } prev = i; } } prevActiveNode[0] = -1; nextActiveNode[prev] = -1; } void CandidateHeap::removeMin() { HeapReturn x = ArrayHeapExtMem::getBinaryHeapWithMin(); int i = 0, j = 0; if (x.which) { auto *H = (BinaryHeap_FourInts *) x.h; i = H->heap->front().first; j = H->heap->front().second; } else { auto *H = (BinaryHeap_TwoInts *) x.h; i = H->heap->front().first; j = H->heap->front().second; } int prev = 0, next = 0; if (--rowCounts[i] == 0) { // compact list representedRowCount--; prev = prevActiveNode[i]; next = nextActiveNode[i]; if (next != -1) prevActiveNode[next] = prev; if (prev != -1) nextActiveNode[prev] = next; } if (--rowCounts[j] == 0) { // compact list representedRowCount--; prev = prevActiveNode[j]; next = nextActiveNode[j]; if (next != -1) prevActiveNode[next] = prev; if (prev != -1) nextActiveNode[prev] = next; } ArrayHeapExtMem::removeMin(); } void CandidateHeap::calcDeltaValues(int newK) { //prevActiveNode[0] = -1; //nextActiveNode[0] = -1; int x = firstActiveNode; float minRdelt1, minRdelt2; minRdelt1 = FLT_MAX; minRdelt2 = FLT_MAX; k_over_kprime = ((float) newK - 2) / ((float) kPrime - 2); int rx, prev, next; while (x != -1) { rx = tb->redirect[x]; if (rx == -1) { prev = prevActiveNode[x]; next = nextActiveNode[x]; if (next != -1) prevActiveNode[next] = prev; if (prev != -1) nextActiveNode[prev] = next; x = next; } else { rDeltas[x] = k_over_kprime * rPrimes[rx] - tb->R[rx]; if (rDeltas[x] < minRdelt1) { minRdelt2 = minRdelt1; minRdelt1 = rDeltas[x]; } else if (rDeltas[x] < minRdelt2) { minRdelt2 = rDeltas[x]; } x = nextActiveNode[x]; } } minDeltaSum = minRdelt1 + minRdelt2; } void CandidateHeap::clear() { ArrayHeapExtMem::deleteAll(); if (rPrimes != nullptr) { delete[] rPrimes; rPrimes = nullptr; } if (rDeltas != nullptr) { delete[] rDeltas; rDeltas = nullptr; } if (rowCounts != nullptr) { delete[] rowCounts; rowCounts = nullptr; } if (nextActiveNode != nullptr) { delete[] nextActiveNode; nextActiveNode = nullptr; } if (prevActiveNode != nullptr) { delete[] prevActiveNode; prevActiveNode = nullptr; } }
mit
Hates/magento_models
lib/magento_models/catalog_category_product.rb
155
module MagentoModels class CatalogCategoryProduct < Base self.primary_key = "category_id" self.table_name = "catalog_category_product" end end
mit
maxence-charriere/jubiz
video.go
981
package jubiz import ( "errors" "fmt" "net/url" "regexp" "strings" ) var ( regexpSrc = regexp.MustCompile(`src="(.+?)"`) videoProviders = []string{ "https://www.youtube.com", "https://player.vimeo.com", "//www.dailymotion.com/embed/Video", } ) type Video struct { URL *url.URL } func parseVideo(tag string) (v Video, err error) { src := regexpSrc.FindString(tag) if len(src) == 0 { err = errors.New("no src property") return } srcSplit := strings.Split(src, "=") if len(srcSplit) < 2 { err = fmt.Errorf("invalid src attribute: %v", src) return } endpoint := srcSplit[1] endpoint = strings.Trim(endpoint, `"`) if !isTrustedVideoSource(endpoint) { err = fmt.Errorf("not trusted Video source: %v", src) return } v.URL, err = url.Parse(endpoint) return } func isTrustedVideoSource(endpoint string) bool { for _, provider := range videoProviders { if strings.HasPrefix(endpoint, provider) { return true } } return false }
mit
kleisauke/fullcalendar
src/list/ListEventRenderer.ts
2331
import { htmlEscape } from '../util' import EventRenderer from '../component/renderers/EventRenderer' export default class ListEventRenderer extends EventRenderer { renderFgSegs(segs) { if (!segs.length) { this.component.renderEmptyMessage() } else { this.component.renderSegList(segs) } } // generates the HTML for a single event row fgSegHtml(seg) { let view = this.view let calendar = view.calendar let theme = calendar.theme let eventFootprint = seg.footprint let eventDef = eventFootprint.eventDef let componentFootprint = eventFootprint.componentFootprint let url = eventDef.url let classes = [ 'fc-list-item' ].concat(this.getClasses(eventDef)) let bgColor = this.getBgColor(eventDef) let timeHtml if (componentFootprint.isAllDay) { timeHtml = view.getAllDayHtml() } else if (view.isMultiDayRange(componentFootprint.unzonedRange)) { if (seg.isStart || seg.isEnd) { // outer segment that probably lasts part of the day timeHtml = htmlEscape(this._getTimeText( calendar.msToMoment(seg.startMs), calendar.msToMoment(seg.endMs), componentFootprint.isAllDay )) } else { // inner segment that lasts the whole day timeHtml = view.getAllDayHtml() } } else { // Display the normal time text for the *event's* times timeHtml = htmlEscape(this.getTimeText(eventFootprint)) } if (url) { classes.push('fc-has-url') } return '<tr class="' + classes.join(' ') + '">' + (this.displayEventTime ? '<td class="fc-list-item-time ' + theme.getClass('widgetContent') + '">' + (timeHtml || '') + '</td>' : '') + '<td class="fc-list-item-marker ' + theme.getClass('widgetContent') + '">' + '<span class="fc-event-dot"' + (bgColor ? ' style="background-color:' + bgColor + '"' : '') + '></span>' + '</td>' + '<td class="fc-list-item-title ' + theme.getClass('widgetContent') + '">' + '<a' + (url ? ' href="' + htmlEscape(url) + '"' : '') + '>' + htmlEscape(eventDef.title || '') + '</a>' + '</td>' + '</tr>' } // like "4:00am" computeEventTimeFormat() { return this.opt('mediumTimeFormat') } }
mit
bigprof-software/online-invoicing-system
app/resources/lib/Request.php
3871
<?php /* Request($var) -- class for providing sanitized values of given request variable (->sql, ->attr, ->html, ->url, and ->raw) */ class Request { public $sql, $url, $attr, $html, $raw; public function __construct($var, $filter = false) { $unsafe = (isset($_REQUEST[$var]) ? $_REQUEST[$var] : ''); if($filter) $unsafe = call_user_func_array($filter, [$unsafe]); $this->sql = makeSafe($unsafe, false); $this->url = urlencode($unsafe); $this->attr = html_attr($unsafe); $this->html = $this->attr; $this->raw = $unsafe; } /** * Retrieve specified variable's value from HTTP REQUEST parameters * * @param string $var The variable * @param scalar $default The default value to use if $var doesn't exist, is empty, or is one of $changeToDefault * @param array $changeToDefault If $var is one of these values, treat like it's empty * * @return scalar The value as retrieved from the Request, or $default */ public static function val($var, $default = '', $changeToDefault = []) { if( !isset($_REQUEST[$var]) || $_REQUEST[$var] === '' || in_array($_REQUEST[$var], $changeToDefault) ) return $default; return $_REQUEST[$var]; } /** * @return bool indicating if $var is part of request, regardless of its value */ public static function has($var) { return isset($_REQUEST[$var]); } public static function lookup($var, $default = '') { return self::val($var, $default, defined('empty_lookup_value') ? [empty_lookup_value] : []); } public static function dateComponents($var, $default = '') { return parseMySQLDate( intval(self::val($var . 'Year')) . '-' . intval(self::val($var . 'Month')) . '-' . intval(self::val($var . 'Day')), $default ); } public static function multipleChoice($var, $default = '') { return is_array($_REQUEST[$var]) ? implode(', ', $_REQUEST[$var]) : $default; } public static function fileUpload($var, $options = []) { // set defaults for $options $options = array_merge([ 'maxSize' => 100, // KB 'types' => 'jpg|jpeg|gif|png', 'noRename' => false, 'dir' => '', 'id' => '', 'removeOnSuccess' => false, 'removeOnRequest' => false, // $options['failure'] => function(id) -- called if no file upload occured, return value is returned // $options['success'] => function(uploadedName, id) -- called if a file is uploaded successfully // $options['remove'] => function(id, fileRemoved) -- called when removing old file ], $options); // handle remove request $fileRemoved = false; if( $options['removeOnRequest'] && !empty($_REQUEST["{$var}_remove"]) && !empty($options['remove']) && is_callable($options['remove']) ) { call_user_func_array($options['remove'], [$options['id']]); $fileRemoved = true; } $uploadedName = PrepareUploadedFile( $var, $options['maxSize'], $options['types'], $options['noRename'], $options['dir'] ); // if file upload failed, return $options['failure'] or empty if not defined if(!$uploadedName) { if( !empty($options['failure']) && is_callable($options['failure']) ) return call_user_func_array($options['failure'], [$options['id'], $fileRemoved]); return ''; } // if upload is successful, call $options['success'] if( !empty($options['success']) && is_callable($options['success']) ) call_user_func_array($options['success'], [$uploadedName, $options['id']]); // if removeOnSuccess if( $options['removeOnSuccess'] && !empty($options['remove']) && is_callable($options['remove']) && !$fileRemoved ) { call_user_func_array($options['remove'], [$options['id']]); $fileRemoved = true; } return $uploadedName; } public static function checkBox($var, $default = '0') { return self::val($var, $default) ? 1 : 0; } }
mit
volkadserver/volkadserver-management-ui
app/actions/orderSourceActionCreators.js
556
import Marty from "marty"; import OrderConstants from "../constants/orderConstants.js"; class OrderSourceActionCreators extends Marty.ActionCreators { receiveOrders(orders) { this.dispatch(OrderConstants.RECEIVE_ORDERS, orders); return orders; } receiveCreatives(creatives) { this.dispatch(OrderConstants.RECEIVE_CREATIVES, creatives); return creatives; } receiveFlights(flights) { this.dispatch(OrderConstants.RECEIVE_FLIGHTS, flights); return flights; } } export default Marty.register(OrderSourceActionCreators);
mit
jezzlucena/node-simple-messenger
routes/messages.js
2270
var mongo = require('mongodb'); //MongoDB configuration var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('simple-messenger-db', server); //Opening the connection with the database db.open(function(err, db) { if(!err) { console.log("Connected to 'simple-messenger-db' database"); //In case the database is empty, populate it db.collection('messages', {strict:true}, function(err, collection) { if (err) { console.log("The 'messages' collection doesn't exist. Creating it with sample data..."); populateDB(); } }); } }); //Find all messages, ordered by "created_on" exports.findAll = function(req, res) { db.collection('messages', function(err, collection) { collection.find().sort({created_on: 1}).toArray(function(err, items) { res.send(items); }); }); }; //Add a message to the database exports.addMessage = function(req, res) { var message = req.body; console.log('Adding message: ' + JSON.stringify(message)); db.collection('messages', function(err, collection) { message.created_on = new Date(); collection.insert(message, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred'}); } else { console.log('Success: ' + JSON.stringify(result[0])); res.send(result[0]); } }); }); } /*--------------------------------------------------------------------------------------------------------------------*/ // Populate database with sample data -- Only used once: the first time the application is started. // You'd typically not find this code in a real-life app, since the database would already exist. var populateDB = function() { var messages = [ { user_name: "System", created_on: new Date(), content: "Welcome to our simple messenger. There is no moderation, so watch out for yourselves.", } ]; db.collection('messages', function(err, collection) { collection.insert(messages, {safe:true}, function(err, result) {}); }); };
mit
tilfin/gc-ddns
app.js
522
'use strict'; const config = require('config').config; const restify = require('restify'); const resource = require('./resource'); const server = restify.createServer({ name: 'Dynamic DNS API Service for Google Cloud' }); server.use(restify.requestLogger()); server.use(restify.queryParser()); server.use(restify.bodyParser({ mapParams: true })); resource(server); if (!module.parent) { const port = process.env.PORT || config.app.port; server.listen(port); console.log("Start API Service port: %d", port); }
mit
ehomeshasha/easydata
article/urls.py
1157
from __future__ import unicode_literals from django.conf.urls import patterns, url #from article.views import article_view, article_list, chapter_list from article.views import ArticlePostView, ArticleView, ArticleIndexListView,\ ArticleListView, ArticleIndexPostView, delete_article, delete_articleindex urlpatterns = patterns('', url(r"^view/(?P<pk>\d+)/$", ArticleView.as_view(), name="article_view"), url(r"^list/$", ArticleListView.as_view(), name="article_list"), url(r"^new/$", ArticlePostView.as_view(), name="article_new"), url(r"^edit/(?P<pk>\d+)/$", ArticlePostView.as_view(), name="article_edit"), url(r"^delete/(?P<pk>\d+)/$", delete_article, name="article_delete"), #url(r"^indexview/(?P<pk>\d+)/$", ArticleIndexView.as_view(), name="articleindex_view"), url(r"^indexlist/$", ArticleIndexListView.as_view(), name="articleindex_list"), url(r"^indexnew/$", ArticleIndexPostView.as_view(), name="articleindex_new"), url(r"^indexedit/(?P<pk>\d+)/$", ArticleIndexPostView.as_view(), name="articleindex_edit"), url(r"^indexdelete/(?P<pk>\d+)/$", delete_articleindex, name="articleindex_delete"), )
mit
kerzyte/OWLib
DataTool/ToolLogic/Extract/ExtractFlags.cs
3092
using DataTool.Flag; namespace DataTool.ToolLogic.Extract { public class ExtractFlags : ICLIFlags { [CLIFlag(Help = "Output path", Positional = 2, Required = true)] public string OutputPath; [CLIFlag(Default = "tif", Flag = "convert-textures-type", Help = "Texture ouput type", Valid = new[] { "dds", "tif", "tga", "png" })] public string ConvertTexturesType; [CLIFlag(Default = true, Flag = "convert-lossless-textures", Help = "Output lossless textures (if converted)", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ConvertTexturesLossless; [CLIFlag(Default = true, Flag = "convert-textures", Help = "Convert .004 files to {convert-textures-type}", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ConvertTextures; [CLIFlag(Default = true, Flag = "convert-sound", Help = "Convert .wem files to .ogg", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ConvertSound; [CLIFlag(Default = true, Flag = "convert-models", Help = "Convert .00C files to .owmdl", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ConvertModels; [CLIFlag(Default = true, Flag = "convert-animations", Help = "Convert .006 files to .seanim", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ConvertAnimations; [CLIFlag(Default = false, Flag = "skip-textures", Help = "Skip texture extraction", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool SkipTextures; [CLIFlag(Default = false, Flag = "skip-sound", Help = "Skip sound extraction", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool SkipSound; [CLIFlag(Default = false, Flag = "skip-models", Help = "Skip model extraction", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool SkipModels; [CLIFlag(Default = false, Flag = "skip-animations", Help = "Skip animation extraction", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool SkipAnimations; [CLIFlag(Default = false, Flag = "extract-refpose", Help = "Extract skeleton refposes", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool ExtractRefpose; [CLIFlag(Default = false, Flag = "raw", Help = "Skip all conversion", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] public bool Raw; [CLIFlag(Default = (byte)0, Flag = "lod", Help = "Force extracted model LOD", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagLOD" })] public byte LOD; // [CLIFlag(Default = false, Flag = "convert-bnk", Help = "Convert .bnk files to .wem", Parser = new[] { "DataTool.Flag.Converter", "CLIFlagBoolean" })] // public bool ConvertBnk; public override bool Validate() => true; } }
mit
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/Nikon/NoiseReduction.php
831
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Nikon; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class NoiseReduction extends AbstractTag { protected $Id = 'mixed'; protected $Name = 'NoiseReduction'; protected $FullName = 'mixed'; protected $GroupName = 'Nikon'; protected $g0 = 'MakerNotes'; protected $g1 = 'Nikon'; protected $g2 = 'Camera'; protected $Type = 'string'; protected $Writable = false; protected $Description = 'Noise Reduction'; protected $flag_Permanent = true; }
mit
Chantouch/www.jcolabs.com
resources/views/backend/qualifications/show.blade.php
578
@extends('backend.layouts.admin_app') @section('content') <section class="content-header"> <h1> Qualification </h1> </section> <div class="content"> <div class="box box-primary"> <div class="box-body"> <div class="row" style="padding-left: 20px"> @include('backend.qualifications.show_fields') <a href="{!! route('admin.qualifications.index') !!}" class="btn btn-default">Back</a> </div> </div> </div> </div> @endsection
mit
ac9831/StudyProject-Asp.Net
DevStateManagement/DevStateManagement/Global.asax.cs
774
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace DevStateManagement { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { Application["Now"] = DateTime.Now; } protected void Session_Start(object sender, EventArgs e) { Session["Now"] = DateTime.Now; } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } } }
mit
drauta/blog-laravel
src/views/forms/formResponderComentario.blade.php
1077
<form class="background-white p20 add-comment" method="post" action="{!! route('createComentComent', ['id'=>$post->id]) !!}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="hidden" id="post_id" name="post_id" value="{{ $post->id }}"> <input type="hidden" id="quotedComment" name="quotedComment" value="{{ $comment->id }}"> <div class="row"> <div class="form-group col-sm-12"> <label for="comentario">Respuesta <span class="required">*</span></label> <textarea class="form-control" rows="5" id="comentario" name="comentario" required>{{ old('comentario') }}</textarea> </div> <div class="col-sm-4 col-sm-offset-8"> <button class="btn btn-primary btn-block" type="submit"><i class="fa fa-comments"></i>Contestar</button> </div> <!-- /.col-sm-4 --> </div> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <!-- /.row --> </form>
mit
openheritage/open-plaques-3
config/initializers/geojson_renderer.rb
1453
ActionController::Renderers.add :geojson do |object, options| self.content_type ||= Mime[:json] '{}' if object.respond_to? :each_with_index # is a set if things geojson = '{' geojson += '"type": "FeatureCollection",' geojson += '"features": [' object.each_with_index do |o, index| if o.respond_to?(:as_geojson) && (o.longitude != nil) # object defines its own as_geojson(options) method geojson += o.as_geojson(options).to_json geojson += "," elsif o.respond_to?(:longitude) && o.respond_to?(:latitude) && o.longitude != nil && o.latitude != 51.475 geojson += { type: 'Feature', geometry: { type: 'Point', coordinates: [o.longitude, o.latitude] }, properties: o.as_json(options) }.to_json geojson += "," end end geojson = geojson.chomp(',') geojson += ']}' geojson elsif object.respond_to? :as_geojson # object defines its own as_geojson(options) method object.as_geojson(options).to_json elsif object.respond_to?(:longitude) && object.respond_to?(:latitude) && object.longitude != nil && object.latitude != 51.475 { type: 'Feature', geometry: { type: 'Point', coordinates: [object.longitude, object.latitude] }, properties: object.as_json(options) }.to_json end end
mit
tenthirtyone/mobile-bazaar
frontend/app/js/profile/profile.route.js
1923
(function() { 'use strict'; angular .module('mobile-bazaar.profile') .run(appRun); appRun.$inject = ['routerHelper']; function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'profile', config: { url: '/profile', views: { '': { templateUrl: 'views/profile.template.html', controller: 'ProfileController', controllerAs: 'profile', }, 'store@profile': { templateUrl: 'views/store.template.html', controller: 'StoreController', controllerAs: 'store', name: 'store', isTab: true, }, 'about@profile': { templateUrl: 'views/about.template.html', controller: 'AboutController', controllerAs: 'about', name: 'about', isTab: true, }, 'following@profile': { templateUrl: 'views/following.template.html', controller: 'FollowingController', controllerAs: 'following', name: 'following', isTab: true, }, 'followers@profile': { templateUrl: 'views/followers.template.html', controller: 'FollowersController', controllerAs: 'followers', name: 'followers', isTab: true, }, 'settings@profile': { templateUrl: 'views/settings.template.html', controller: 'SettingsController', controllerAs: 'settings', name: 'settings', isTab: true, }, } } }]; } }());
mit
claws/txBOM
examples/observations_client.py
1762
#!/usr/bin/env python ''' A demonstration of the observations client. The observations client keeps itself up to date by inspecting the first observation retrieved and determines the appropriate time to begin the periodic observations retrieval such that the minimum number of requests are made to keep the observations client up to date. As the observation update rate is 30 minutes this demonstration can be a little underwhelming to watch. The important point to understand is that you can create one of these objects and it will call you back when a new observation has been retrieved, it does all the work for you. ''' from twisted.internet import reactor from twisted.python import log import logging import txbom.observations # Lets implement our own observations client that # will call us back upon a new observation being # retrieved. class MyObservationsClient(txbom.observations.Client): def observationsReceived(self, observations): ''' This method receives observation updates as they are retrieved. ''' if self.observations: if self.observations.current: print "Current observation data:" print self.observations.current else: print "No current observation" else: print "No observations" logging.basicConfig(level=logging.DEBUG) # Send any Twisted log messages to logging logger _observer = log.PythonLoggingObserver() _observer.start() # Adelaide observations identifier observation_url = "http://www.bom.gov.au/fwo/IDS60901/IDS60901.94675.json" client = MyObservationsClient(observation_url) # strart the client's periodic observations update service. reactor.callWhenRunning(client.start) reactor.run()
mit
zackb/continuum
continuum-core/src/main/java/continuum/atom/Particles.java
348
package continuum.atom; import java.io.Serializable; import java.util.List; import java.util.Map; /** * The particles represented in a time translator */ public interface Particles extends Map<String, String>, Serializable { String put(String key, String value); String get(String key); List<String> names(); ParticlesID ID(); }
mit
DaveKerk/Cloud-Code
HPCWProblem01/Problem01.js
168
/* * David Kerkhoff * Berthoud High School * March 2nd, 2017 * HPCodeWars Problem 01 */ var judgeName; input(type = text) judgeName; return (judgeName);
mit
jonathangerbaud/Contacts
src/com/abewy/android/apps/contacts/adapter/MultiObjectAdapter.java
3378
/** * @author Jonathan */ package com.abewy.android.apps.contacts.adapter; import java.util.ArrayList; import java.util.List; import android.widget.AbsListView; import com.abewy.android.extended.adapter.MultiTypeAdapter; import com.abewy.android.extended.adapter.TypeAdapter; import com.abewy.android.extended.items.BaseType; import com.crashlytics.android.Crashlytics; import com.haarman.listviewanimations.itemmanipulation.AnimateDismissAdapter; import com.haarman.listviewanimations.itemmanipulation.OnDismissCallback; public class MultiObjectAdapter extends MultiTypeAdapter<BaseType> { private AnimateDismissAdapter<BaseType> deleteAdapter; public MultiObjectAdapter(AbsListView listView) { this(listView, 0); } public MultiObjectAdapter(AbsListView listView, int layoutType) { super(layoutType); if (listView != null) { deleteAdapter = new AnimateDismissAdapter<BaseType>(this, new OnDismissCallback() { @Override public void onDismiss(AbsListView listView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { removeAt(position); } } }); deleteAdapter.setAbsListView(listView); } } @Override public void remove(BaseType object) { remove(object, false); } public void remove(BaseType object, boolean animated) { if (animated == false || deleteAdapter == null) { super.remove(object); notifyDataSetChanged(); } else { List<Integer> list = new ArrayList<Integer>(); list.add(getItemPosition(object)); deleteAdapter.animateDismiss(list); } } @Override public void removeAt(int index) { removeAt(index, false); } public void removeAt(int index, boolean animated) { if (index >= 0 && index < getCount()) { if (animated == false || deleteAdapter == null) { super.removeAt(index); notifyDataSetChanged(); } else { List<Integer> list = new ArrayList<Integer>(); list.add(index); deleteAdapter.animateDismiss(list); } } } @Override public void removeFirst() { removeFirst(false); } public void removeFirst(boolean animated) { if (animated == false || deleteAdapter == null) { super.removeFirst(); } else { List<Integer> list = new ArrayList<Integer>(); list.add(0); deleteAdapter.animateDismiss(list); } } @Override public void removeLast() { removeLast(false); } public void removeLast(boolean animated) { if (animated == false || deleteAdapter == null) { super.removeLast(); } else { List<Integer> list = new ArrayList<Integer>(); list.add(getCount() - 1); deleteAdapter.animateDismiss(list); } } @Override protected TypeAdapter<BaseType> getAdapter(BaseType object, int layoutType) { TypeAdapter<BaseType> adapter = AdapterSelector.getAdapter(object, layoutType, this); if (adapter == null) { Crashlytics.setString("MultiObjectAdapter_object", object != null ? object.toString() : "object is null"); Crashlytics.setString("MultiObjectAdapter_layout", String.valueOf(layoutType)); } return adapter; } private List<Integer> types = new ArrayList<Integer>(); @Override protected int getItemViewType(BaseType object) { int type = object.getItemViewType(); int index = types.indexOf(type); if (index == -1) { index = types.size(); types.add(type); } return index; } }
mit
ofa/connect
open_connect/connectmessages/tests/test_models.py
36780
# -*- coding: utf-8 -*- """Tests for connectmessages.models.""" # pylint: disable=invalid-name, protected-access from textwrap import dedent import datetime from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.test import TestCase, override_settings from django.utils.timezone import now from mock import patch from model_mommy import mommy import pytz from open_connect.connectmessages.models import Message, UserThread, Thread from open_connect.connectmessages.tasks import send_system_message from open_connect.connectmessages.tests import ConnectMessageTestCase from open_connect.connect_core.utils.basetests import ConnectTestMixin USER_MODEL = get_user_model() class ThreadPublicManagerByUserTest(ConnectTestMixin, TestCase): """ThreadPublicManager.by_user tests.""" def test_by_user_user_is_in_group(self): """Should return threads that user is a part of.""" recipient = self.create_user() thread = self.create_thread(recipient=recipient) result = Thread.public.by_user(user=recipient) self.assertIn(thread, result) def test_by_user_user_is_not_in_group_or_recipient(self): """Should not have threads the user is not a part of.""" thread = self.create_thread() user = self.create_user() result = Thread.public.by_user(user=user) self.assertNotIn(thread, result) def test_invisible_thread(self): """Should not have threads that are marked invisible.""" thread = self.create_thread(visible=False) result = Thread.public.by_user(thread.recipients.first()) self.assertNotIn(thread, result) def test_first_message_sender_is_banned(self): """Threads started by banned members should not be visible.""" group = mommy.make('groups.Group') normal_user = self.create_user() normal_user.add_to_group(group.pk) banned_user = self.create_user(is_banned=True) thread = self.create_thread(sender=banned_user, group=group) # normal_user should not see the thread from the banned user result = Thread.public.by_user(normal_user) self.assertNotIn(thread, result) def test_first_message_sender_is_banned_and_is_user(self): """Threads started by banned member are visible to the banned member.""" group = mommy.make('groups.Group') banned_user = self.create_user(is_banned=True) banned_user.add_to_group(group.pk) thread = self.create_thread(sender=banned_user, group=group) result = Thread.public.by_user(banned_user) self.assertIn(thread, result) def test_non_active_userthread(self): """Userthreads that are not active should not be in the by_user""" user = self.create_user() thread = self.create_thread(recipient=user) UserThread.objects.filter( thread=thread, user=user).update(status='deleted') result = Thread.public.by_user(user) self.assertNotIn(thread, result) def test_userthread_status(self): """The current userthread_status should be selected.""" thread = self.create_thread() thread = Thread.public.by_user(thread.test_shortcuts['recipient']) self.assertEqual(thread[0].userthread_status, 'active') class ThreadPublicManagerByGroupTest(ConnectTestMixin, TestCase): """ThreadPublicManager.by_group tests.""" def test_by_group(self): """Should return threads posted to the group.""" thread = self.create_thread() result = Thread.public.by_group(thread.group) self.assertIn(thread, result) def test_by_group_no_messages_for_another_group(self): """Should not have threads posted to another group.""" thread = self.create_thread() other_group = mommy.make('groups.Group') result = Thread.public.by_group(thread.group) self.assertNotIn(other_group, result) def test_invisible_thread(self): """Should not have threads that are marked invisible.""" thread = self.create_thread(visible=False) result = Thread.public.by_group(thread.group) self.assertNotIn(thread, result) def test_first_message_sender_is_banned(self): """Threads started by banned members should not be visible.""" banned_user = self.create_user(is_banned=True) thread = self.create_thread(sender=banned_user) result = Thread.public.by_group(thread.group) self.assertNotIn(thread, result) def test_group_is_private(self): """Private groups should not have their threads exposed.""" group = mommy.make('groups.Group', private=True) thread = self.create_thread(group=group) result = Thread.public.by_group(group) self.assertNotIn(thread, result) @override_settings(TIME_ZONE='US/Central') class ThreadTest(ConnectTestMixin, TestCase): """Thread model tests.""" def test_unicode(self): """Unicode conversion should be Thread and the id of the thread.""" thread = mommy.prepare('connectmessages.Thread') self.assertEqual(str(thread), "Thread %s" % thread.subject) def test_add_user_to_thread(self): """Test that add_user_to_thread adds the user to the thread.""" thread = self.create_thread() user = self.create_user() thread.add_user_to_thread(user) self.assertTrue( UserThread.objects.filter(thread=thread, user=user).exists()) def test_get_absolute_url(self): """Test get_absolute_url""" thread = self.create_thread() self.assertEqual( thread.get_absolute_url(), '/messages/id/{pk}/'.format( pk=thread.pk) ) def test_get_unsubscribe_url(self): """Test the get_unsubscribe_url method on the Thread model""" thread = self.create_thread() self.assertEqual( thread.get_unsubscribe_url(), reverse('thread_unsubscribe', args=[thread.pk]) ) def test_group_serializable(self): """Test the thread serialization method for a group message""" sender = self.create_user() thread = self.create_thread(sender=sender) message = thread.first_message chicago = pytz.timezone('US/Central') self.assertDictEqual( thread.serializable(), { 'id': thread.pk, 'total_messages': '1', 'json_url': reverse('thread_details_json', args=[thread.pk]), 'subject': thread.subject, 'snippet': unicode(message.snippet), 'read': None, 'group': unicode(thread.group), 'group_url': reverse( 'group_details', kwargs={'pk': thread.group.pk}), 'group_id': thread.group.pk, 'type': 'group', 'unread_messages': 1, 'category': str(thread.group.category.slug), 'reply_url': reverse( 'create_reply', args=[thread.pk]), 'unsubscribe_url': thread.get_unsubscribe_url(), 'is_system_thread': False, 'userthread_status': None, 'latest_message_at': str(thread.latest_message.created_at.astimezone(chicago)) } ) def test_direct_serializable(self): """Test the thread serialization method for a direct message""" sender = self.create_user() recipient = self.create_user() thread = self.create_thread( direct=True, sender=sender, recipient=recipient) message = thread.first_message chicago = pytz.timezone('US/Central') self.assertDictItemsEqualUnordered( thread.serializable(), { 'id': thread.pk, 'total_messages': '1', 'subject': thread.subject, 'snippet': unicode(message.snippet), 'recipients': [ str(sender), str(recipient) ], 'json_url': str( reverse('thread_details_json', args=[thread.pk])), 'read': None, 'group': u'', 'group_url': '', 'group_id': None, 'type': 'direct', 'unread_messages': 1, 'category': u'', 'reply_url': reverse( 'create_direct_message_reply', args=[thread.pk]), 'unsubscribe_url': thread.get_unsubscribe_url(), 'is_system_thread': False, 'userthread_status': None, 'latest_message_at': str(thread.latest_message.created_at.astimezone(chicago)) } ) @override_settings(SYSTEM_USER_EMAIL='systemuser-email@connect.local') def test_systemthread(self): """Test the thread serialization method for a system message""" # The sqlite test runner doesn't run south migrations, so create the # user here if it doesn't exist USER_MODEL.objects.get_or_create( email='systemuser-email@connect.local', defaults={ 'username': 'systemuser-email@connect.local', 'is_active': True, 'is_superuser': True } ) recipient = self.create_user() send_system_message(recipient, 'Subject Here', 'Content Here') thread = Thread.public.by_user(recipient).first() message = thread.first_message chicago = pytz.timezone('US/Central') self.assertDictItemsEqualUnordered( thread.serializable(), { 'id': thread.pk, 'total_messages': '1', 'subject': thread.subject, 'snippet': unicode(message.snippet), 'json_url': str( reverse('thread_details_json', args=[thread.pk])), 'read': False, 'group': u'', 'group_url': '', 'group_id': None, 'type': 'direct', 'unread_messages': 1, 'category': u'', 'reply_url': reverse( 'create_direct_message_reply', args=[thread.pk]), 'unsubscribe_url': thread.get_unsubscribe_url(), 'is_system_thread': True, 'userthread_status': 'active', 'latest_message_at': str(thread.latest_message.created_at.astimezone(chicago)) } ) class ThreadLastReadAndUnreadCountTest(ConnectTestMixin, TestCase): """Tests for last_read_at and unread_messages attributes.""" def test_last_read_at(self): """last_read_at should be correctly set.""" recipient = self.create_user() thread = self.create_thread(recipient=recipient) last_read_at = datetime.datetime( 2014, 3, 17, 19, 42, 37, tzinfo=pytz.timezone('UTC')) UserThread.objects.filter( thread=thread, user=recipient).update(last_read_at=last_read_at) result = Thread.public.by_user( user=recipient, queryset=Thread.objects.filter(pk=thread.pk) ).first() self.assertEqual( result.last_read_at, last_read_at) self.assertEqual(result.serializable()['unread_messages'], 1) def test_unread_message_count_thread_never_opened(self): """If thread has never been opened, count should equal all messages.""" recipient = self.create_user() thread = self.create_thread(recipient=recipient) mommy.make(Message, thread=thread, sender=self.create_superuser()) result = Thread.public.by_user( user=recipient, queryset=Thread.objects.filter(pk=thread.pk) ).first() self.assertEqual( result.last_read_at, None) self.assertEqual(result.serializable()['unread_messages'], 2) @override_settings(TIME_ZONE='US/Central') class MessageTest(ConnectTestMixin, TestCase): """Tests for Message model.""" def test_get_absolute_url_resolves_to_threads(self): """get_absolute_url should resolve to threads.""" thread = self.create_thread() self.assertEqual( thread.first_message.get_absolute_url(), '/messages/id/{pk}/'.format( pk=thread.pk) ) def test_serializable(self): """Test serializable values.""" thread = self.create_thread() message = thread.first_message self.assertEqual( message.serializable(), { 'group': unicode(thread.group), 'reply_url': reverse( 'create_reply', args=[thread.pk]), 'flag_url': reverse( 'flag_message', kwargs={'message_id': message.pk} ), 'sent_at': str( message.created_at.astimezone( pytz.timezone('US/Central') ) ), 'sender': { 'sender': str(message.sender), 'sender_is_staff' : message.sender.is_staff, 'sender_url': reverse( 'user_details', kwargs={'user_uuid': message.sender.uuid} ), }, 'text': message.text, 'read': None, 'is_system_message': False, 'pending': False, 'id': message.pk, 'snippet': message.snippet } ) def test_serizable_pending(self): """Test the 'pending' logic in message.serlizable""" thread = self.create_thread() message = thread.first_message # Confirm that an 'approved' message is not marked as pending self.assertEqual(message.status, 'approved') self.assertEqual(message.serializable()['pending'], False) message.status = 'pending' message.save() self.assertEqual(message.status, 'pending') self.assertEqual(message.serializable()['pending'], True) # A flagged message should appear the same as an approved thread to the # end-user message.status = 'flagged' message.save() self.assertEqual(message.status, 'flagged') self.assertEqual(message.serializable()['pending'], False) def test_text_cleaner(self): """Test _text_cleaner().""" text = """ <html>This is HTML Yes it is </html>""" message = Message(text=dedent(text)) result = message._text_cleaner() self.assertEqual(result, 'This is HTML Yes it is') def test_save_calls_text_cleaner(self): """Test that save calls _text_cleaner().""" thread = self.create_thread() with patch.object(Message, '_text_cleaner') as mock: mock.return_value = '' self.assertEqual(mock.call_count, 0) thread.first_message.save() self.assertEqual(mock.call_count, 1) def test_long_snippet(self): """Long Snippet should return first 140 characters of clean_text.""" message = Message(clean_text=''.join('x' for _ in range(0, 200))) self.assertEqual( message.long_snippet, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 'xxxxxxxx' ) def test_snippet_short(self): """Short messages w/em dash should return all ASCII stripped text""" # Em dashes are turned into double dashes, stripped from end message = Message(clean_text=u'short — test— ') self.assertEqual( message.snippet, 'short -- test' ) def test_snippet_long_unicode(self): """Test a unicode-filled string replaces the unicode character""" message = Message(clean_text=u"This sentence — pauses a bit") self.assertEqual( message.snippet, 'This sentence -- paus...' ) def test_snippet_long_strip_end(self): """Test long unicode-filled snippets ending with a non-letter""" # Without stripping the non-character end this would end with ' --' message = Message(clean_text=u"This was a longer — sentence") self.assertEqual( message.snippet, 'This was a longer...' ) def test_snippet_beginning_nonletter(self): """Test a long snippet that starts and ends with a non-letter""" message = Message(clean_text=u"!I already know what this will be!!!!!") self.assertEqual( message.snippet, 'I already know what...' ) class MessageShortenTest(ConnectTestMixin, TestCase): """Tests for shortening links in a message.""" def test_links_in_message_are_shortened(self): """Links in a message should be replaced with short code.""" sender = self.create_user() group = self.create_group() sender.add_to_group(group.pk) thread = mommy.make(Thread, group=group) message = Message( text='This is a <a href="http://www.razzmatazz.local">link</a>', thread=thread, sender=sender ) message.save() self.assertEqual(message.links.count(), 1) self.assertTrue(message.links.get().short_code in message.text) def test_links_in_message_are_not_shortened(self): """If shorten=False, links in message should not be replaced.""" sender = self.create_user() group = self.create_group() sender.add_to_group(group.pk) thread = mommy.make(Thread, group=group) message = Message( text='This is a <a href="http://www.razzmatazz.local">link</a>', thread=thread, sender=sender ) message.save(shorten=False) self.assertEqual(message.links.count(), 0) self.assertTrue('www.razzmatazz.local' in message.text) def test_shorten_increments_message_count(self): """Increment message_count if the same url is used multiple times.""" sender = self.create_user() thread = self.create_thread(sender=sender) thread.first_message.text = ( 'This is a <a href="http://www.razzmatazz.local">link</a>') thread.first_message.save() message2 = Message.objects.create( text='This is a <a href="http://www.razzmatazz.local">link</a>', thread=thread, sender=sender ) self.assertEqual(message2.links.get().message_count, 2) def test_non_http_links_not_shortened(self): """Non http/s links shouldn't be shortened.""" sender = self.create_user() group = self.create_group() sender.add_to_group(group.pk) thread = mommy.make(Thread, group=group) message = Message( text='This is an email: <a href="mailto:a@b.local">lnk</a>', thread=thread, sender=sender ) message.save() self.assertEqual(message.links.count(), 0) @override_settings(SYSTEM_USER_EMAIL='systemuser-email@connect.local') class InitialStatusTestTest(ConnectTestMixin, TestCase): """Test for determining the initial status of a message""" def test_system_message_approved(self): """Test that a system message is always approved""" system_user, _ = USER_MODEL.objects.get_or_create( email='systemuser-email@connect.local', defaults={ 'username': 'systemuser-email@connect.local', 'is_active': True, 'is_superuser': True } ) thread = self.create_thread(sender=system_user, direct=True) self.assertEqual(thread.first_message.get_initial_status(), 'approved') def test_user_can_send_up_to_10_dms(self): """User should be able to send up to 10 dms before they're pending.""" user = self.create_user() threads = [ self.create_thread(direct=True, sender=user) for _ in range(0, 10) ] for thread in threads: self.assertEqual( thread.first_message.get_initial_status(), 'approved') should_be_pending = self.create_thread(direct=True, sender=user) self.assertEqual( should_be_pending.first_message.get_initial_status(), 'pending' ) def test_superuser_unlimited_direct_messages(self): """Superusers should be able to send an unlimited number of DMs""" user = self.create_user(is_superuser=True) threads = [ self.create_thread(direct=True, sender=user) for _ in range(0, 11) ] for thread in threads: self.assertEqual( thread.first_message.get_initial_status(), 'approved') class MessageDeleteTest(ConnectTestMixin, TestCase): """Tests for deleting a message.""" def test_no_deleted_messages_in_query(self): """Deleted messages shouldn't be in regular queries.""" thread = self.create_thread() thread.first_message.delete() self.assertNotIn(thread.first_message, Message.objects.all()) def test_deleted_messages_in_with_deleted_query(self): """Deleted messages should show in with_deleted queries.""" thread = self.create_thread() thread.first_message.delete() self.assertTrue( Message.objects.with_deleted().filter( pk=thread.first_message.pk).exists() ) def test_delete(self): """Delete should mark a message as deleted and update the thread.""" # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the second message message = Message.objects.get(pk=message.pk) message.delete() # Verify the thread now has one message thread = Thread.objects.get(pk=thread.pk) self.assertEqual(thread.total_messages, 1) # Verify the message status is now deleted deleted_message = Message.objects.with_deleted().get(pk=message.pk) self.assertEqual(deleted_message.status, 'deleted') def test_delete_message_is_first_message(self): """Delete should update thread.first_message if message was first.""" # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the first message thread = Thread.objects.get(pk=thread.pk) thread.first_message.delete() # Verify that thread.first_message is updated to what was the second. thread = Thread.objects.get(pk=thread.pk) self.assertEqual(thread.first_message, message) def test_delete_message_is_latest_message(self): """Delete should update thread.latest_message if message was last.""" # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the second message message = Message.objects.get(pk=message.pk) message.delete() # Verify that thread.latest_message is updated to what was the first. thread = Thread.objects.get(pk=thread.pk) self.assertEqual(thread.latest_message, thread.first_message) def test_delete_message_is_only_message_in_thread(self): """Delete should mark a thread as deleted if it was the only message.""" thread = self.create_thread() thread.first_message.delete() thread = Thread.objects.with_deleted().get(pk=thread.pk) self.assertEqual(thread.status, 'deleted') self.assertEqual(thread.total_messages, 0) class MessageFlagTest(ConnectTestMixin, TestCase): """Tests for flagging a message.""" def test_flag(self): """Flagging a message 1 time should mark it as pending.""" recipient = self.create_user() thread = self.create_thread(recipient=recipient) message = thread.first_message self.assertEqual(message.status, 'approved') message.flag(recipient) self.assertEqual(message.flags.count(), 1) self.assertEqual(message.status, 'flagged') class TestMessagesForUser(ConnectMessageTestCase): """Tests for Thread.messages_for_user method.""" def setUp(self): """Setup the TestMessageForUser TestCase""" self.user = mommy.make(USER_MODEL) group = mommy.make('groups.Group') self.user.add_to_group(group.pk) self.sender = mommy.make(USER_MODEL, is_superuser=True) self.thread = mommy.make( 'connectmessages.Thread', recipients=[self.user], group=group) def test_get_message_new(self): """New message should not be marked as read.""" message = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) thread = Thread.public.by_user(user=self.user)[0] messages = thread.messages_for_user(self.user) self.assertEqual(messages[0], message) self.assertFalse(messages[0].read) def test_get_message_read(self): """A message that has been read should show up as read.""" message = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) user_thread = UserThread.objects.get( thread=self.thread, user=self.user) user_thread.read = True user_thread.save() thread = Thread.public.by_user(user=self.user)[0] messages = thread.messages_for_user(self.user) self.assertEqual(messages[0], message) self.assertTrue(messages[0].read) def test_get_message_reply(self): """New replies should have just the read messages marked read.""" message1 = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) message1.created_at = now() - datetime.timedelta(days=1) message1.save() message2 = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) message2.created_at = now() - datetime.timedelta(hours=2) message2.save() # thread.last_read_at is normally set by the by_user query self.thread.last_read_at = now() - datetime.timedelta(hours=3) messages = self.thread.messages_for_user(self.user) # Messages are returned sorted from newest to oldest self.assertEqual(messages[0], message2) self.assertFalse(messages[0].read) self.assertEqual(messages[1], message1) self.assertTrue(messages[1].read) class TestVisibleToUser(ConnectTestMixin, TestCase): """Tests for the Message.visible_to_user method.""" def test_user_is_group_member_status_is_approved(self): """User should see approved messages in groups they belong to.""" group = mommy.make('groups.Group', moderated=True) thread = self.create_thread(group=group) message = thread.first_message message.status = 'approved' message.save() user = self.create_user() user.add_to_group(group.pk) self.assertTrue(message.visible_to_user(user)) def test_user_is_group_member_status_is_not_approved(self): """User should not see unapproved messages.""" group = mommy.make('groups.Group', moderated=True) thread = self.create_thread(group=group) message = thread.first_message message.status = 'pending' message.save() user = self.create_user() user.add_to_group(group.pk) self.assertFalse(message.visible_to_user(user)) def test_group_is_not_private_user_is_not_member(self): """User should see approved messages in any non-private group.""" thread = self.create_thread() user = self.create_user() self.assertTrue(thread.first_message.visible_to_user(user)) def test_group_is_private_user_is_not_member(self): """Non-members should not see messages in private groups.""" thread = self.create_thread() thread.group.private = True thread.save() message = thread.first_message user = self.create_user() self.assertFalse(message.visible_to_user(user)) def test_user_is_superuser(self): """Superusers should see anything, including deleted messages.""" super_user = self.create_superuser() regular_user = self.create_user() thread = self.create_thread(status='deleted') message = thread.first_message self.assertTrue(message.visible_to_user(super_user)) self.assertFalse(message.visible_to_user(regular_user)) def test_user_is_sender(self): """Senders should always have access to non-deleted messages.""" sender = self.create_user() thread = self.create_thread(sender=sender, status='pending') self.assertTrue(thread.first_message.visible_to_user(sender)) def test_reply_from_banned_user(self): """Test replies sent by banned users are visible only to that user""" # Create 2 users. By default neither is banned, but one will be soon viewing_user = self.create_user() banned_user = self.create_user() # Create a new group and add both our users to it group = self.create_group() viewing_user.add_to_group(group.pk) banned_user.add_to_group(group.pk) # Create a new thread sent to the group we created above thread = self.create_thread(group=group) # Create a reply sent by a soon-to-be-banned user message = mommy.make( 'connectmessages.Message', thread=thread, sender=banned_user) # Confirm both users can see the message, as neither is banned self.assertTrue(message.visible_to_user(viewing_user)) self.assertTrue(message.visible_to_user(banned_user)) # Ban the banned user banned_user.is_banned = True banned_user.save() # Confirm the non-banned user can no longer see the banned user's reply # but the banned user can see his or her own message self.assertFalse(message.visible_to_user(viewing_user)) self.assertTrue(message.visible_to_user(banned_user)) def test_user_is_group_moderator(self): """Group moderators should see any message sent to their group.""" thread = self.create_thread() user = self.create_user() thread.group.owners.add(user) message = thread.first_message message.status = 'pending' message.save() self.assertTrue(message.visible_to_user(user)) def test_user_is_global_moderator(self): """Group moderators should see any message sent to their group.""" thread = self.create_thread() user = self.create_user() message = thread.first_message message.status = 'pending' message.save() self.assertFalse(message.visible_to_user(user)) self.add_perm(user, 'can_moderate_all_messages', 'accounts', 'user') # To get rid of the user permission cache we should re-grab our user latest_user = USER_MODEL.objects.get(pk=user.pk) self.assertTrue(message.visible_to_user(latest_user)) def test_user_is_recipient(self): """Recipients of a thread should see approved messages.""" recipient = self.create_user() thread = self.create_thread(recipient=recipient) self.assertTrue(thread.first_message.visible_to_user(recipient)) def test_recipient_flag_set_true(self): """ If message.is_recipient is true, users should see approved messages. """ recipient = self.create_user() group = mommy.make('groups.Group', private=True) thread = self.create_thread(group=group) self.assertFalse(thread.first_message.visible_to_user(recipient)) setattr(thread.first_message, 'is_recipient', '1') self.assertTrue(thread.first_message.visible_to_user(recipient)) def test_user_is_sender_message_is_moderated(self): """The sender of a message should be able to see their own message.""" thread = self.create_thread() message = thread.first_message message.status = 'pending' message.save() self.assertTrue(message.visible_to_user(message.sender)) def test_message_is_vetoed(self): """Vetoed messages should not be visible to anyone.""" thread = self.create_thread() message = thread.first_message message.status = 'vetoed' message.save() self.assertFalse(message.visible_to_user(message.sender)) class TestThreadGetByUser(TestCase): """Tests for Thread.get_by_user.""" def setUp(self): """Setup the TestThreadGetByUser Testcase""" # Create a private group self.group = mommy.make('groups.Group', private=True) self.user = mommy.make( 'accounts.User', is_active=True, invite_verified=True) self.thread = mommy.make( 'connectmessages.Thread', group=self.group) sender = mommy.make('accounts.User') sender.add_to_group(self.group.pk) mommy.make( 'connectmessages.Message', thread=self.thread, sender=sender) def test_thread_is_not_moderated(self): """Return thread if it is posted to a public group.""" self.assertRaises( ObjectDoesNotExist, Thread.public.get_by_user, **{'thread_id': self.thread.pk, 'user': self.user} ) self.group.private = False self.group.save() self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) def test_user_is_superuser(self): """Return thread if user is a superuser.""" self.user.is_superuser = True self.user.save() self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) def test_user_is_recipient(self): """Return thread if user is a recipient.""" UserThread.objects.create(user=self.user, thread=self.thread) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) def test_user_is_group_member(self): """Return thread if user is a group member.""" self.user.add_to_group(self.thread.group.pk) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) def test_user_is_group_owner(self): """Return thread if user is a group owner.""" self.thread.group.owners.add(self.user) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread ) def test_user_does_not_have_access(self): """Raise ObjectDoesNotExist if user doesn't have access.""" self.assertRaises( ObjectDoesNotExist, Thread.public.get_by_user, **{'thread_id': self.thread.pk, 'user': self.user} ) class TestUserThread(ConnectTestMixin, TestCase): """Tests for the UserThread model.""" def test_delete(self): """Delete should mark the UT as deleted.""" thread = self.create_thread() ut = UserThread.objects.get( user=thread.recipients.first(), thread=thread) ut_id = ut.pk ut.delete() ut = UserThread.objects.with_deleted().get(pk=ut_id) self.assertEqual(ut.status, 'deleted') def test_archive(self): """Should mark UT as archived.""" thread = self.create_thread() ut = UserThread.objects.get( user=thread.recipients.first(), thread=thread) ut_id = ut.pk ut.archive() ut = UserThread.objects.get(pk=ut_id) self.assertEqual(ut.status, 'archived')
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_91/safe/CWE_91__object-classicGet__CAST-cast_int_sort_of2__ID_test-interpretation.php
1512
<?php /* Safe sample input : get the field userData from the variable $_GET via an object sanitize : cast via + = 0 construction : interpretation */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = $tainted + 0; $query = "//User[@id= $tainted ]"; $xml = simplexml_load_file("users.xml");//file load echo "query : ". $query ."<br /><br />" ; $res=$xml->xpath($query);//execution print_r($res); echo "<br />" ; ?>
mit
dumplingyzr/HearthTracker
app/src/main/java/dumplingyzr/hearthtracker/activities/ClassSelectAdapter.java
1672
package dumplingyzr.hearthtracker.activities; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import dumplingyzr.hearthtracker.R; /** * Created by dumplingyzr on 2016/11/28. */ public class ClassSelectAdapter extends BaseAdapter { private String[] mClassNames = { "Warrior", "Shamman", "Rogue", "Paladin", "Hunter", "Druid", "Warlock", "Mage", "Priest" }; private int[] mClassImages = { R.drawable.icon_warrior_64, R.drawable.icon_shaman_64, R.drawable.icon_rogue_64, R.drawable.icon_paladin_64, R.drawable.icon_hunter_64, R.drawable.icon_druid_64, R.drawable.icon_warlock_64, R.drawable.icon_mage_64, R.drawable.icon_priest_64 }; public int getCount() { return mClassNames.length; } public long getItemId(int position) { return 0; } public Object getItem(int position) { return null; } public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = LayoutInflater.from(parent.getContext()).inflate(R.layout.class_select_item, parent, false); } else { view = convertView; } ImageView imageView = (ImageView) view.findViewById(R.id.class_image); imageView.setImageResource(mClassImages[position]); TextView textView = (TextView) view.findViewById(R.id.class_name); textView.setText(mClassNames[position]); return view; } }
mit
layabox/layaair
src/layaAir/laya/d3/core/reflectionProbe/ReflectionProbeManager.ts
4493
import { BaseRender } from "../render/BaseRender"; import { ReflectionProbe } from "./ReflectionProbe"; import { ReflectionProbeList } from "./ReflectionProbeList"; import { SingletonList } from "../../component/SingletonList"; import { Bounds } from "../Bounds"; import { SimpleSingletonList } from "../../component/SimpleSingletonList"; import { TextureCube } from "../../resource/TextureCube"; import { Vector4 } from "../../math/Vector4"; import { Vector3 } from "../../math/Vector3"; /** *<code>ReflectionProbeManager</code> 类用于反射探针管理 * @miner */ export class ReflectionProbeManager { /** @internal 反射探针队列 */ private _reflectionProbes:ReflectionProbeList = new ReflectionProbeList(); /** @internal 环境探针 */ private _sceneReflectionProbe:ReflectionProbe; /** @internal 需要跟新反射探针的渲染队列 */ private _motionObjects:SingletonList<BaseRender> = new SingletonList<BaseRender>(); /** @internal */ _needUpdateAllRender:boolean = false; constructor(){ this._sceneReflectionProbe = new ReflectionProbe(); this._sceneReflectionProbe.bounds= new Bounds(new Vector3(0,0,0),new Vector3(0,0,0)); this._sceneReflectionProbe.boxProjection = false; this._sceneReflectionProbe._isScene = true; } set sceneReflectionProbe(value:TextureCube){ this._sceneReflectionProbe.reflectionTexture = value; } set sceneReflectionCubeHDRParam(value:Vector4){ this._sceneReflectionProbe.reflectionHDRParams = value; } /** * 更新baseRender的反射探针 * @param baseRender */ _updateMotionObjects(baseRender:BaseRender):void{ if(this._reflectionProbes.length==0){ baseRender._probReflection = this._sceneReflectionProbe; return; } var elements:ReflectionProbe[] = this._reflectionProbes.elements; var maxOverlap:number = 0; var mainProbe:ReflectionProbe; var renderBounds:Bounds = baseRender.bounds; var overlop ; for(var i:number = 0,n:number = this._reflectionProbes.length;i<n;i++){ var renflectProbe = elements[i]; if(!mainProbe){ overlop = renderBounds.calculateBoundsintersection(renflectProbe.bounds); if(overlop <maxOverlap) continue; }else{ if(mainProbe.importance>renflectProbe.importance) continue;//重要性判断 overlop = renderBounds.calculateBoundsintersection(renflectProbe.bounds); if(overlop <maxOverlap && mainProbe.importance == renflectProbe.importance) continue; } mainProbe = renflectProbe; maxOverlap = overlop; } if(!mainProbe&&this._sceneReflectionProbe)//如果没有相交 传场景反射球 mainProbe = this._sceneReflectionProbe; baseRender._probReflection = mainProbe; } /** * 场景中添加反射探针 * @internal * @param reflectionProbe */ add(reflectionProbe:ReflectionProbe){ this._reflectionProbes.add(reflectionProbe); this._needUpdateAllRender = true; } /** * 场景中删除反射探针 * @internal * @param reflectionProbe */ remove(reflectionProbe:ReflectionProbe){ this._reflectionProbes.remove(reflectionProbe); this._needUpdateAllRender = true; } /** * 添加运动物体。 * @param 运动物体。 */ addMotionObject(renderObject:BaseRender){ this._motionObjects.add(renderObject); } /** * 更新运动物体的反射探针信息 */ update():void{ var elements: BaseRender[] = this._motionObjects.elements; for(var i:number = 0,n:number = this._motionObjects.length;i<n;i++){ this._updateMotionObjects(elements[i]); } this.clearMotionObjects(); } /** * 更新传入所有渲染器反射探针 * @param 渲染器列表 */ updateAllRenderObjects(baseRenders:SimpleSingletonList){ var elements = baseRenders.elements; for(var i:number = 0,n:number = baseRenders.length;i<n;i++){ this._updateMotionObjects(elements[i] as BaseRender); } this._needUpdateAllRender = false; } /** * 清楚变动队列 */ clearMotionObjects(){ this._motionObjects.length = 0; } destroy(){ } }
mit
jeremyevans/roda
spec/plugin/recheck_precompiled_assets_spec.rb
3666
require_relative "../spec_helper" require 'fileutils' run_tests = true begin begin require 'tilt/sass' rescue LoadError begin for lib in %w'tilt sass' require lib end rescue LoadError warn "#{lib} not installed, skipping assets plugin test" run_tests = false end end end if run_tests metadata_file = File.expand_path('spec/assets/tmp/precompiled.json') describe 'recheck_precompiled_assets plugin' do define_method(:compile_assets) do |opts={}| Class.new(Roda) do plugin :assets, {:css => 'app.scss', :path => 'spec/assets/tmp', :css_dir=>nil, :precompiled=>metadata_file, :public=>'spec/assets/tmp', :prefix=>nil}.merge!(opts) compile_assets end end before do Dir.mkdir('spec/assets/tmp') unless File.directory?('spec/assets/tmp') FileUtils.cp('spec/assets/css/app.scss', 'spec/assets/tmp/app.scss') FileUtils.cp('spec/assets/js/head/app.js', 'spec/assets/tmp/app.js') compile_assets File.utime(Time.now, Time.now - 20, metadata_file) app(:bare) do plugin :assets, :public => 'spec/assets/tmp', :prefix=>nil, :precompiled=>metadata_file plugin :recheck_precompiled_assets route do |r| r.assets "#{assets(:css)}\n#{assets(:js)}" end end end after do FileUtils.rm_r('spec/assets/tmp') if File.directory?('spec/assets/tmp') end it 'should support :recheck_precompiled option to recheck precompiled file for new precompilation data' do css_hash = app.assets_opts[:compiled]['css'] app.assets_opts[:compiled]['js'].must_be_nil body.scan("href=\"/app.#{css_hash}.css\"").length.must_equal 1 body("/app.#{css_hash}.css").must_match(/color:\s*red/) File.write('spec/assets/tmp/app.scss', File.read('spec/assets/tmp/app.scss').sub('red', 'blue')) compile_assets File.utime(Time.now, Time.now - 10, metadata_file) app.assets_opts[:compiled]['css'].must_equal css_hash body.scan("href=\"/app.#{css_hash}.css\"").length.must_equal 1 body("/app.#{css_hash}.css").must_match(/color:\s*red/) css2_hash = nil 2.times do app.recheck_precompiled_assets css2_hash = app.assets_opts[:compiled]['css'] css2_hash.wont_equal css_hash body.scan("href=\"/app.#{css2_hash}.css\"").length.must_equal 1 body("/app.#{css2_hash}.css").must_match(/color:\s*blue/) body("/app.#{css_hash}.css").must_match(/color:\s*red/) end compile_assets(:js=>'app.js', :js_dir=>nil) app.recheck_precompiled_assets js_hash = app.assets_opts[:compiled]['js'] body.scan("src=\"/app.#{js_hash}.js\"").length.must_equal 1 body("/app.#{js_hash}.js").must_match(/console\.log\(.test.\)/) app.assets_opts[:compiled].replace({}) app.compile_assets body.strip.must_be_empty app.plugin :assets, :css => 'app.scss', :path => 'spec/assets/tmp', :css_dir=>nil, :css_opts => {:cache=>false} app.compile_assets body.scan("href=\"/app.#{css2_hash}.css\"").length.must_equal 1 body("/app.#{css2_hash}.css").must_match(/color:\s*blue/) end end describe 'recheck_precompiled_assets plugin' do it "should not allow loading if not using assets plugin" do proc{app(:recheck_precompiled_assets)}.must_raise Roda::RodaError end it "should not allow loading if using assets plugin without :precompiled option" do proc do app(:bare) do plugin :assets plugin :recheck_precompiled_assets end end.must_raise Roda::RodaError end end end
mit
forgephp/core
classes/Config/Source.php
316
<?php namespace Forge\Config; /** * Base Config source Interface * * Used to identify either config readers or writers when calling Config::attach() * * @package SuperFan * @category Config * @author Zach Jenkins <zach@superfanu.com> * @copyright (c) 2017 SuperFan, Inc. */ interface Source {}
mit
xoddong/concrete
app/routes/users.server.routes.js
1427
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../../app/controllers/users.server.controller'); // Setting up the users profile api app.route('/users/me').get(users.me); app.route('/users').put(users.update); app.route('/users/accounts').delete(users.removeOAuthProvider); // Setting up the users password api app.route('/users/password').post(users.changePassword); app.route('/auth/forgot').post(users.forgot); app.route('/auth/reset/:token').get(users.validateResetToken); app.route('/auth/reset/:token').post(users.reset); // Setting up the users authentication api app.route('/auth/signup').post(users.signup); app.route('/auth/signin').post(users.signin); app.route('/auth/signout').get(users.signout); // Setting the facebook oauth routes app.route('/auth/facebook').get(passport.authenticate('facebook', { scope: ['email'] })); app.route('/auth/facebook/callback').get(users.oauthCallback('facebook')); // Setting the google oauth routes app.route('/auth/google').get(passport.authenticate('google', { scope: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] })); app.route('/auth/google/callback').get(users.oauthCallback('google')); // Finish by binding the user middleware app.param('userId', users.userByID); };
mit
austriapro/ebinterface-word-plugin
eRechnungWordPlugIn/SettingsEditor/Views/FrmZustellSettingsView.Designer.cs
10265
namespace SettingsEditor.Views { partial class FrmZustellSettingsView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.cBtnSave = new WinFormsMvvm.Controls.CommandButton(); this.cmdBtnClose = new WinFormsMvvm.Controls.CommandButton(); this.label19 = new System.Windows.Forms.Label(); this.tbxTemplatePath = new System.Windows.Forms.TextBox(); this.label18 = new System.Windows.Forms.Label(); this.tbxLocalFilePath = new System.Windows.Forms.TextBox(); this.cmdBtnGetFileDlg = new WinFormsMvvm.Controls.CommandButton(); this.label1 = new System.Windows.Forms.Label(); this.commandButton1 = new WinFormsMvvm.Controls.CommandButton(); this.label2 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.cBtnTest = new WinFormsMvvm.Controls.CommandButton(); this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit(); this.SuspendLayout(); // // cBtnSave // this.cBtnSave.DataBindings.Add(new System.Windows.Forms.Binding("Command", this.bindingSource1, "SaveCommand", true)); this.cBtnSave.DialogResult = System.Windows.Forms.DialogResult.OK; this.cBtnSave.Location = new System.Drawing.Point(406, 225); this.cBtnSave.Name = "cBtnSave"; this.cBtnSave.Size = new System.Drawing.Size(75, 23); this.cBtnSave.TabIndex = 85; this.cBtnSave.Text = "Speichern"; this.cBtnSave.UseVisualStyleBackColor = true; // // cmdBtnClose // this.cmdBtnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cmdBtnClose.Location = new System.Drawing.Point(490, 225); this.cmdBtnClose.Name = "cmdBtnClose"; this.cmdBtnClose.Size = new System.Drawing.Size(75, 23); this.cmdBtnClose.TabIndex = 84; this.cmdBtnClose.Text = "Schliessen"; this.cmdBtnClose.UseVisualStyleBackColor = true; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(12, 12); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(352, 13); this.label19.TabIndex = 83; this.label19.Text = "Pfad und Dateiname des aufzurufenden Programmes oder der Batchdatei"; // // tbxTemplatePath // this.tbxTemplatePath.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "ExeFileName", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.tbxTemplatePath.Location = new System.Drawing.Point(12, 37); this.tbxTemplatePath.Name = "tbxTemplatePath"; this.tbxTemplatePath.Size = new System.Drawing.Size(514, 20); this.tbxTemplatePath.TabIndex = 81; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(12, 126); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(125, 13); this.label18.TabIndex = 80; this.label18.Text = "Parameter für den Aufruf "; // // tbxLocalFilePath // this.tbxLocalFilePath.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "Arguments", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.tbxLocalFilePath.Location = new System.Drawing.Point(12, 151); this.tbxLocalFilePath.Name = "tbxLocalFilePath"; this.tbxLocalFilePath.Size = new System.Drawing.Size(553, 20); this.tbxLocalFilePath.TabIndex = 79; // // cmdBtnGetFileDlg // this.cmdBtnGetFileDlg.DataBindings.Add(new System.Windows.Forms.Binding("Command", this.bindingSource1, "GetExeFileCommand", true)); this.cmdBtnGetFileDlg.Location = new System.Drawing.Point(532, 35); this.cmdBtnGetFileDlg.Name = "cmdBtnGetFileDlg"; this.cmdBtnGetFileDlg.Size = new System.Drawing.Size(32, 23); this.cmdBtnGetFileDlg.TabIndex = 86; this.cmdBtnGetFileDlg.Text = "..."; this.cmdBtnGetFileDlg.UseVisualStyleBackColor = true; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(9, 183); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(235, 65); this.label1.TabIndex = 87; this.label1.Text = "Ersetzungsmöglichkeiten im Parameter:\r\n\r\n{0} = Dateiname der ebInterface Rechnung" + "\r\n{1} = e-Mail Adresse des Rechnungsstellers\r\n{2} = e-Mail Adresse des Rechnungs" + "empfängers"; // // commandButton1 // this.commandButton1.DataBindings.Add(new System.Windows.Forms.Binding("Command", this.bindingSource1, "WorkingDirCommand", true)); this.commandButton1.Location = new System.Drawing.Point(533, 92); this.commandButton1.Name = "commandButton1"; this.commandButton1.Size = new System.Drawing.Size(32, 23); this.commandButton1.TabIndex = 90; this.commandButton1.Text = "..."; this.commandButton1.UseVisualStyleBackColor = true; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 69); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(202, 13); this.label2.TabIndex = 89; this.label2.Text = "Vollständiger Pfad zum Arbeitsverzeichnis"; // // textBox1 // this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bindingSource1, "WorkingDirectory", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.textBox1.Location = new System.Drawing.Point(12, 94); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(514, 20); this.textBox1.TabIndex = 88; // // cBtnTest // this.cBtnTest.Location = new System.Drawing.Point(325, 225); this.cBtnTest.Name = "cBtnTest"; this.cBtnTest.Size = new System.Drawing.Size(75, 23); this.cBtnTest.TabIndex = 91; this.cBtnTest.Text = "Testen"; this.cBtnTest.UseVisualStyleBackColor = true; this.cBtnTest.Visible = false; // // bindingSource1 // this.bindingSource1.DataSource = typeof(SettingsEditor.ViewModels.ZustellSettingsViewModel); // // FrmZustellSettingsView // this.AcceptButton = this.cBtnSave; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cmdBtnClose; this.ClientSize = new System.Drawing.Size(579, 270); this.Controls.Add(this.cBtnTest); this.Controls.Add(this.commandButton1); this.Controls.Add(this.label2); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Controls.Add(this.cmdBtnGetFileDlg); this.Controls.Add(this.cBtnSave); this.Controls.Add(this.cmdBtnClose); this.Controls.Add(this.label19); this.Controls.Add(this.tbxTemplatePath); this.Controls.Add(this.label18); this.Controls.Add(this.tbxLocalFilePath); this.Name = "FrmZustellSettingsView"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Einstellungen: Zustelldienst"; ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private WinFormsMvvm.Controls.CommandButton cBtnSave; private WinFormsMvvm.Controls.CommandButton cmdBtnClose; private System.Windows.Forms.Label label19; private System.Windows.Forms.TextBox tbxTemplatePath; private System.Windows.Forms.Label label18; private System.Windows.Forms.TextBox tbxLocalFilePath; private WinFormsMvvm.Controls.CommandButton cmdBtnGetFileDlg; private System.Windows.Forms.Label label1; private System.Windows.Forms.BindingSource bindingSource1; private WinFormsMvvm.Controls.CommandButton commandButton1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox1; private WinFormsMvvm.Controls.CommandButton cBtnTest; } }
mit
WIPACrepo/iceprod
tests/server/scheduled_tasks/non_active_tasks_test.py
4248
""" Test script for scheduled_tasks/non_active_tasks """ import logging logger = logging.getLogger('scheduled_tasks_non_active_tasks_test') import os import sys import shutil import tempfile import unittest from functools import partial from unittest.mock import patch, MagicMock from tornado.testing import AsyncTestCase from rest_tools.client import RestClient from tests.util import unittest_reporter, glob_tests from iceprod.server.modules.schedule import schedule from iceprod.server.scheduled_tasks import non_active_tasks class non_active_tasks_test(AsyncTestCase): def setUp(self): super(non_active_tasks_test,self).setUp() self.test_dir = tempfile.mkdtemp(dir=os.getcwd()) def cleanup(): shutil.rmtree(self.test_dir) self.addCleanup(cleanup) self.cfg = { 'queue':{ 'init_queue_interval':0.1, 'submit_dir':self.test_dir, '*':{'type':'Test1','description':'d'}, }, 'master':{ 'url':False, }, 'site_id':'abcd', } @unittest_reporter def test_100_non_active_tasks(self): s = schedule(self.cfg,None,None,None) non_active_tasks.non_active_tasks(s) @unittest_reporter async def test_200_run(self): rc = MagicMock(spec=RestClient) pilots = {} dataset_summaries = {'processing':['foo']} task = {'status':'processing','status_changed':'2000-01-01T00:00:00'} tasks = {} pilots = {} async def client(method, url, args=None): logger.info('REST: %s, %s', method, url) if url.startswith('/dataset_summaries'): return dataset_summaries elif url.startswith('/pilots'): return pilots elif url.startswith('/datasets/foo/task_summaries'): return tasks elif url == '/datasets/foo/tasks/bar' and method == 'GET': return task elif url == '/datasets/foo/tasks/bar/status' and method == 'PUT': client.called = True return {} elif url.startswith('/logs'): return {} else: raise Exception() client.called = False rc.request = client await non_active_tasks.run(rc, debug=True) self.assertFalse(client.called) tasks['processing'] = ['bar'] await non_active_tasks.run(rc, debug=True) self.assertTrue(client.called) client.called = False del dataset_summaries['processing'] dataset_summaries['truncated'] = ['foo'] pilots['a'] = {'tasks':['bar']} await non_active_tasks.run(rc, debug=True) self.assertFalse(client.called) @unittest_reporter(name='run() - error') async def test_201_run(self): rc = MagicMock(spec=RestClient) pilots = {'a':{}} # try tasks error async def client(method, url, args=None): logger.info('REST: %s, %s', method, url) if url.startswith('/dataset_summaries'): return {'processing':['foo']} elif url.startswith('/pilots'): return pilots else: raise Exception() rc.request = client with self.assertRaises(Exception): await non_active_tasks.run(rc, debug=True) # check it normally hides the error await non_active_tasks.run(rc, debug=False) # try dataset level error async def client(method, url, args=None): raise Exception() rc.request = client with self.assertRaises(Exception): await non_active_tasks.run(rc, debug=True) # check it normally hides the error await non_active_tasks.run(rc, debug=False) def load_tests(loader, tests, pattern): suite = unittest.TestSuite() alltests = glob_tests(loader.getTestCaseNames(non_active_tasks_test)) suite.addTests(loader.loadTestsFromNames(alltests,non_active_tasks_test)) return suite
mit
hanguyen7394/angular2
app/modules/mod_login.component/mod_login.component.ts
482
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { User } from '../../model/user/user'; @Component({ moduleId: module.id, selector: 'mod_login', templateUrl: 'mod_login.component.html' }) export class ModLoginComponent implements OnInit { public model = new User(1,'', '', '', '', '','','',1,0,0,0,0); constructor(private route: Router) { } ngOnInit() { } goCreateUser() { this.route.navigate(['/create']); } }
mit
rpschill/vanessaschill
blog/urls.py
256
from django.conf.urls import url, include from blog import views from .models import Article urlpatterns = [ url(r'^$', views.ArticleList, name='article-list'), url(r'^(?P<slug>[\w-]+)/$', views.ArticleDetail.as_view(), name='article-detail'), ]
mit
0xaio/create-react-app
packages/react-scripts/scripts/get-schema.js
1853
'use strict'; const fetch = require("node-fetch"); const fs = require("fs"); const { buildClientSchema, introspectionQuery, printSchema } = require("graphql/utilities"); const chalk = require("chalk"); function isURL(str) { const urlRegex = "^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost|django)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$"; const url = new RegExp(urlRegex, "i"); return str.length < 2083 && url.test(str) } const url = process.argv[3]; const saveJson = process.argv[4] === 'json'; if (!url) { console.log("Usage: get-schema " + chalk.green("url")); console.log(" " + chalk.green("url") + " is your graphql server address"); process.exit() } if (!isURL(url)) { console.log(chalk.red(url) + " is not a valid url"); process.exit(1) } console.log("Downloading for url: " + chalk.green(url)); fetch(url, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({query: introspectionQuery}) }) .then(res => res.json()) .then(res => { console.log(res); console.log("schema.graphql has downloaded and saved"); if (saveJson) { const jsonString = JSON.stringify(res.data); console.log("schema.json has been saved"); fs.writeFileSync("schema.json", jsonString) } const schemaString = printSchema(buildClientSchema(res.data)); fs.writeFileSync("schema.graphql", schemaString) }) .catch(e => { console.log(chalk.red("\nError:")); console.error(e); process.exit(1) });
mit
nikestep/java-mockito-bazel
java/com/nicholasestep/sample/SampleWrapper.java
1010
package com.nicholasestep.sample; import com.nicholasestep.logging.Logger; import com.nicholasestep.sample.Sample; import java.util.Collection; import java.util.Map; public class SampleWrapper { private static final int sampleInt = 12; private static final String sampleString = "hi nik"; private static final boolean sampleBoolean = false; private final Sample sample; private final Logger logger; public SampleWrapper(Sample sample, Logger logger) { this.sample = sample; this.logger = logger; } public int getInt() { logger.logAction(); return sample.getInt(sampleInt); } public String getString() { return sample.getString(sampleString); } public boolean getBoolean() { logger.logAction(); return sample.getBoolean(sampleBoolean); } public Collection<String> getCollection() { logger.logAction(); logger.logAction(); return sample.getCollection(); } public Map<String, String> getMap() { return sample.getMap(); } }
mit
Gyscos/alumine
src/ml/bayes.rs
507
use alg::Vector; use ml::Classifier; pub struct NaiveBayes { k: usize, } pub enum Value { Double(f32), Integer(i32), Boolean(bool), } impl NaiveBayes { pub fn new(k: usize) -> Self { NaiveBayes { k: k, } } } impl Classifier for NaiveBayes { type Input = Vector<Value>; type Label = usize; fn train(&mut self, samples: &[Vector<Value>], labels: &[usize]) { } fn classify(&self, input: &Vector<Value>) -> usize { 0 } }
mit
Stanislavska/MoviesRental1
vendor/autoload.php
183
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInitc39e2ce89821956467c22e4730f68a16::getLoader();
mit
skift/youtube_estore
db/migrate/20130917185900_create_youtube_estore_channels.rb
521
class CreateYoutubeEstoreChannels < ActiveRecord::Migration def change create_table :youtube_estore_channels, force: true do |t| t.datetime :published_at t.string :description t.integer :subscriber_count t.integer :video_count t.string :username t.string :title t.integer :view_count t.string :default_thumbnail t.string :t_id t.datetime "rails_created_at" t.datetime "rails_updated_at" end end end
mit
umpirsky/platform
src/Oro/Bundle/TagBundle/Entity/TagManager.php
10831
<?php namespace Oro\Bundle\TagBundle\Entity; use Doctrine\ORM\Query\Expr; use Doctrine\ORM\EntityManager; use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Bundle\FrameworkBundle\Routing\Router; use Symfony\Component\Security\Core\SecurityContextInterface; use Oro\Bundle\SecurityBundle\SecurityFacade; use Oro\Bundle\UserBundle\Entity\User; use Oro\Bundle\SearchBundle\Engine\ObjectMapper; use Oro\Bundle\TagBundle\Entity\Repository\TagRepository; class TagManager { const ACL_RESOURCE_REMOVE_ID_KEY = 'oro_tag_unassign_global'; const ACL_RESOURCE_CREATE_ID_KEY = 'oro_tag_create'; const ACL_RESOURCE_ASSIGN_ID_KEY = 'oro_tag_assign_unassign'; /** * @var EntityManager */ protected $em; /** * @var string */ protected $tagClass; /** * @var string */ protected $taggingClass; /** * @var ObjectMapper */ protected $mapper; /** * @var SecurityContextInterface */ protected $securityContext; /** * @var SecurityFacade */ protected $securityFacade; /** * @var Router */ protected $router; public function __construct( EntityManager $em, $tagClass, $taggingClass, ObjectMapper $mapper, SecurityContextInterface $securityContext, SecurityFacade $securityFacade, Router $router ) { $this->em = $em; $this->tagClass = $tagClass; $this->taggingClass = $taggingClass; $this->mapper = $mapper; $this->securityContext = $securityContext; $this->securityFacade = $securityFacade; $this->router = $router; } /** * Adds multiple tags on the given taggable resource * * @param Tag[] $tags Array of Tag objects * @param Taggable $resource Taggable resource */ public function addTags($tags, Taggable $resource) { foreach ($tags as $tag) { if ($tag instanceof Tag) { $resource->getTags()->add($tag); } } } /** * Loads or creates multiples tags from a list of tag names * * @param array $names Array of tag names * @return Tag[] */ public function loadOrCreateTags(array $names) { if (empty($names)) { return array(); } array_walk( $names, function (&$item) { $item = trim($item); } ); $names = array_unique($names); $tags = $this->em->getRepository($this->tagClass)->findBy(array('name' => $names)); $loadedNames = array(); /** @var Tag $tag */ foreach ($tags as $tag) { $loadedNames[] = $tag->getName(); } $missingNames = array_udiff($names, $loadedNames, 'strcasecmp'); if (sizeof($missingNames)) { foreach ($missingNames as $name) { $tag = $this->createTag($name); $tags[] = $tag; } } return $tags; } /** * Prepare array * * @param Taggable $entity * @param ArrayCollection|null $tags * @return array */ public function getPreparedArray(Taggable $entity, $tags = null) { if (is_null($tags)) { $this->loadTagging($entity); $tags = $entity->getTags(); } $result = array(); /** @var Tag $tag */ foreach ($tags as $tag) { $entry = array( 'name' => $tag->getName() ); if (!$tag->getId()) { $entry = array_merge( $entry, array( 'id' => $tag->getName(), 'url' => false, 'owner' => true ) ); } else { $entry = array_merge( $entry, array( 'id' => $tag->getId(), 'url' => $this->router->generate('oro_tag_search', array('id' => $tag->getId())), 'owner' => false ) ); } $taggingCollection = $tag->getTagging()->filter( function (Tagging $tagging) use ($entity) { // only use tagging entities that related to current entity return $tagging->getEntityName() == ClassUtils::getClass($entity) && $tagging->getRecordId() == $entity->getTaggableId(); } ); /** @var Tagging $tagging */ foreach ($taggingCollection as $tagging) { if ($this->getUser()->getId() == $tagging->getCreatedBy()->getId()) { $entry['owner'] = true; } } $entry['moreOwners'] = $taggingCollection->count() > 1; $result[] = $entry; } return $result; } /** * Saves tags for the given taggable resource * * @param Taggable $resource Taggable resource */ public function saveTagging(Taggable $resource) { $oldTags = $this->getTagging($resource, $this->getUser()->getId()); $newTags = $resource->getTags(); if (isset($newTags['all'], $newTags['owner'])) { $newOwnerTags = new ArrayCollection($newTags['owner']); $newAllTags = new ArrayCollection($newTags['all']); $manager = $this; $tagsToAdd = $newOwnerTags->filter( function ($tag) use ($oldTags, $manager) { return !$oldTags->exists($manager->compareCallback($tag)); } ); $tagsToDelete = $oldTags->filter( function ($tag) use ($newOwnerTags, $manager) { return !$newOwnerTags->exists($manager->compareCallback($tag)); } ); if (!$tagsToDelete->isEmpty() && $this->securityFacade->isGranted(self::ACL_RESOURCE_ASSIGN_ID_KEY) ) { $this->deleteTaggingByParams( $tagsToDelete, ClassUtils::getClass($resource), $resource->getTaggableId(), $this->getUser()->getId() ); } // process if current user allowed to remove other's tag links if ($this->securityFacade->isGranted(self::ACL_RESOURCE_REMOVE_ID_KEY)) { // get 'not mine' taggings $oldTags = $this->getTagging($resource, $this->getUser()->getId(), true); $tagsToDelete = $oldTags->filter( function ($tag) use ($newAllTags, $manager) { return !$newAllTags->exists($manager->compareCallback($tag)); } ); if (!$tagsToDelete->isEmpty()) { $this->deleteTaggingByParams( $tagsToDelete, ClassUtils::getClass($resource), $resource->getTaggableId() ); } } foreach ($tagsToAdd as $tag) { if (!$this->securityFacade->isGranted(self::ACL_RESOURCE_ASSIGN_ID_KEY) || (!$this->securityFacade->isGranted(self::ACL_RESOURCE_CREATE_ID_KEY) && !$tag->getId()) ) { // skip tags that have not ID because user not granted to create tags continue; } $this->em->persist($tag); $alias = $this->mapper->getEntityConfig(ClassUtils::getClass($resource)); $tagging = $this->createTagging($tag, $resource) ->setAlias($alias['alias']); $this->em->persist($tagging); } if (!$tagsToAdd->isEmpty()) { $this->em->flush(); } } } /** * @param Tag $tag * @return callable */ public function compareCallback($tag) { return function ($index, $item) use ($tag) { /** @var Tag $item */ return $item->getName() == $tag->getName(); }; } /** * Loads all tags for the given taggable resource * * @param Taggable $resource Taggable resource * @return $this */ public function loadTagging(Taggable $resource) { $tags = $this->getTagging($resource); $this->addTags($tags, $resource); return $this; } /** * Remove tagging related to tags by params * * @param array|ArrayCollection|int $tagIds * @param string $entityName * @param int $recordId * @param null|int $createdBy * @return array */ public function deleteTaggingByParams($tagIds, $entityName, $recordId, $createdBy = null) { /** @var TagRepository $repository */ $repository = $this->em->getRepository($this->tagClass); if (!$tagIds) { $tagIds = array(); } elseif ($tagIds instanceof ArrayCollection) { $tagIds = array_map( function ($item) { /** @var Tag $item */ return $item->getId(); }, $tagIds->toArray() ); } return $repository->deleteTaggingByParams($tagIds, $entityName, $recordId, $createdBy); } /** * Creates a new Tag object * * @param string $name Tag name * @return Tag */ private function createTag($name) { return new $this->tagClass($name); } /** * Creates a new Tagging object * * @param Tag $tag Tag object * @param Taggable $resource Taggable resource object * @return Tagging */ private function createTagging(Tag $tag, Taggable $resource) { return new $this->taggingClass($tag, $resource); } /** * Gets all tags for the given taggable resource * * @param Taggable $resource Taggable resource * @param null|int $createdBy * @param bool $all * @return ArrayCollection */ private function getTagging(Taggable $resource, $createdBy = null, $all = false) { /** @var TagRepository $repository */ $repository = $this->em->getRepository($this->tagClass); return new ArrayCollection($repository->getTagging($resource, $createdBy, $all)); } /** * Return current user * * @return User */ private function getUser() { return $this->securityContext->getToken()->getUser(); } }
mit
pokoot/Rubik
system/library/json.php
34130
<?php namespace Library; if ( ! defined("BASE_PATH")) exit("No direct script access allowed."); /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Converts to and from JSON format. * * JSON (JavaScript Object Notation) is a lightweight data-interchange * format. It is easy for humans to read and write. It is easy for machines * to parse and generate. It is based on a subset of the JavaScript * Programming Language, Standard ECMA-262 3rd Edition - December 1999. * This feature can also be found in Python. JSON is a text format that is * completely language independent but uses conventions that are familiar * to programmers of the C-family of languages, including C, C++, C#, Java, * JavaScript, Perl, TCL, and many others. These properties make JSON an * ideal data-interchange language. * * This package provides a simple encoder and decoder for JSON notation. It * is intended for use with client-side Javascript applications that make * use of HTTPRequest to perform server communication functions - data can * be encoded into JSON notation for use in a client-side javascript, or * decoded from incoming Javascript requests. JSON format is native to * Javascript, and can be directly eval()'ed with no further parsing * overhead * * All strings should be in ASCII or UTF-8 format! * * LICENSE: Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: Redistributions of source code must retain the * above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * @category * @package Services_JSON * @author Michal Migurski <mike-json@teczno.com> * @author Matt Knapp <mdknapp[at]gmail[dot]com> * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> * @copyright 2005 Michal Migurski * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_SLICE', 1); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_STR', 2); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_ARR', 3); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_OBJ', 4); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_CMT', 5); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_LOOSE_TYPE', 16); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_SUPPRESS_ERRORS', 32); /** * Converts to and from JSON format. * * Brief example of use: * * <code> * // create a new instance of Services_JSON * $json = new Services_JSON(); * * // convert a complexe value to JSON notation, and send it to the browser * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); * $output = $json->encode($value); * * print($output); * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] * * // accept incoming POST data, assumed to be in JSON notation * $input = file_get_contents('php://input', 1000000); * $value = $json->decode($input); * </code> */ class Services_JSON{ public static $instance; /** * constructs a new JSON instance * * @param int $use object behavior flags; combine with boolean-OR * * possible values: * - SERVICES_JSON_LOOSE_TYPE: loose typing. * "{...}" syntax creates associative arrays * instead of objects in decode(). * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. * Values which can't be encoded (e.g. resources) * appear as NULL instead of throwing errors. * By default, a deeply-nested resource will * bubble up with an error, so all return values * from encode() should be checked with isError() */ function Services_JSON($use = 0){ self::$instance = $this; $this->use = $use; } /** * convert a string from one UTF-16 char to one UTF-8 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf16 UTF-16 character * @return string UTF-8 character * @access private */ function utf162utf8($utf16) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch(true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; } /** * convert a string from one UTF-8 char to one UTF-16 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf8 UTF-8 character * @return string UTF-16 character * @access private */ function utf82utf16($utf8) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); } switch(strlen($utf8)) { case 1: // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return $utf8; case 2: // return a UTF-16 character from a 2-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1}))); case 3: // return a UTF-16 character from a 3-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2}))); } // ignoring UTF-32 for now, sorry return ''; } /** * encodes an arbitrary variable into JSON format * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function encode($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (float) $var; case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = strlen($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1})); $c += 1; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2})); $c += 2; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3})); $c += 3; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4})); $c += 4; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4}), ord($var{$c + 5})); $c += 5; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { $properties = array_map(array($this, 'name_value'), array_keys($var), array_values($var)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; } // treat it like a regular array $elements = array_map(array($this, 'encode'), $var); foreach($elements as $element) { if(Services_JSON::isError($element)) { return $element; } } return '[' . join(',', $elements) . ']'; case 'object': $vars = get_object_vars($var); $properties = array_map(array($this, 'name_value'), array_keys($vars), array_values($vars)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; default: return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) ? 'null' : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); } } /** * array-walking function for use in generating JSON-formatted name-value pairs * * @param string $name name of key to use * @param mixed $value reference to an array element to be encoded * * @return string JSON-formatted name-value pair, like '"name":value' * @access private */ function name_value($name, $value) { $encoded_value = $this->encode($value); if(Services_JSON::isError($encoded_value)) { return $encoded_value; } return $this->encode(strval($name)) . ':' . $encoded_value; } /** * reduce a string by removing leading and trailing comments and whitespace * * @param $str string string value to strip of comments and whitespace * * @return string string value stripped of comments and whitespace * @access private */ function reduce_string($str) { $str = preg_replace(array( // eliminate single line comments in '// ...' form '#^\s*//(.+)$#m', // eliminate multi-line comments in '/* ... */' form, at start of string '#^\s*/\*(.+)\*/#Us', // eliminate multi-line comments in '/* ... */' form, at end of string '#/\*(.+)\*/\s*$#Us' ), '', $str); // eliminate extraneous space return trim($str); } /** * decodes a JSON string into appropriate variable * * @param string $str JSON-formatted string * * @return mixed number, boolean, string, array, or object * corresponding to given JSON input string. * See argument 1 to Services_JSON() above for object-output behavior. * Note that decode() always returns strings * in ASCII or UTF-8 format! * @access public */ function decode($str) { $str = $this->reduce_string($str); switch (strtolower($str)) { case 'true': return true; case 'false': return false; case 'null': return null; default: $m = array(); if (is_numeric($str)) { // Lookie-loo, it's a number // This would work on its own, but I'm trying to be // good about returning integers where appropriate: // return (float)$str; // Return float or int, as appropriate return ((float)$str == (integer)$str) ? (integer)$str : (float)$str; } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { // STRINGS RETURNED IN UTF-8 FORMAT $delim = substr($str, 0, 1); $chrs = substr($str, 1, -1); $utf8 = ''; $strlen_chrs = strlen($chrs); for ($c = 0; $c < $strlen_chrs; ++$c) { $substr_chrs_c_2 = substr($chrs, $c, 2); $ord_chrs_c = ord($chrs{$c}); switch (true) { case $substr_chrs_c_2 == '\b': $utf8 .= chr(0x08); ++$c; break; case $substr_chrs_c_2 == '\t': $utf8 .= chr(0x09); ++$c; break; case $substr_chrs_c_2 == '\n': $utf8 .= chr(0x0A); ++$c; break; case $substr_chrs_c_2 == '\f': $utf8 .= chr(0x0C); ++$c; break; case $substr_chrs_c_2 == '\r': $utf8 .= chr(0x0D); ++$c; break; case $substr_chrs_c_2 == '\\"': case $substr_chrs_c_2 == '\\\'': case $substr_chrs_c_2 == '\\\\': case $substr_chrs_c_2 == '\\/': if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || ($delim == "'" && $substr_chrs_c_2 != '\\"')) { $utf8 .= $chrs{++$c}; } break; case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): // single, escaped unicode character $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) . chr(hexdec(substr($chrs, ($c + 4), 2))); $utf8 .= $this->utf162utf8($utf16); $c += 5; break; case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): $utf8 .= $chrs{$c}; break; case ($ord_chrs_c & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 2); ++$c; break; case ($ord_chrs_c & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 3); $c += 2; break; case ($ord_chrs_c & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 4); $c += 3; break; case ($ord_chrs_c & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 5); $c += 4; break; case ($ord_chrs_c & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 6); $c += 5; break; } } return $utf8; } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { // array, or object notation if ($str{0} == '[') { $stk = array(SERVICES_JSON_IN_ARR); $arr = array(); } else { if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $stk = array(SERVICES_JSON_IN_OBJ); $obj = array(); } else { $stk = array(SERVICES_JSON_IN_OBJ); $obj = new stdClass(); } } array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => 0, 'delim' => false)); $chrs = substr($str, 1, -1); $chrs = $this->reduce_string($chrs); if ($chrs == '') { if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } else { return $obj; } } //print("\nparsing {$chrs}\n"); $strlen_chrs = strlen($chrs); for ($c = 0; $c <= $strlen_chrs; ++$c) { $top = end($stk); $substr_chrs_c_2 = substr($chrs, $c, 2); if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { // found a comma that is not inside a string, array, etc., // OR we've reached the end of the character list $slice = substr($chrs, $top['where'], ($c - $top['where'])); array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); if (reset($stk) == SERVICES_JSON_IN_ARR) { // we are in an array, so just push an element onto the stack array_push($arr, $this->decode($slice)); } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { // we are in an object, so figure // out the property name and set an // element in an associative array, // for now $parts = array(); if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // "name":value pair $key = $this->decode($parts[1]); $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // name:value pair, where name is unquoted $key = $parts[1]; $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } } } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { // found a quote, and we are not inside a string array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); //print("Found start of string at {$c}\n"); } elseif (($chrs{$c} == $top['delim']) && ($top['what'] == SERVICES_JSON_IN_STR) && ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { // found a quote, we're in a string, and it's not escaped // we know that it's not escaped becase there is _not_ an // odd number of backslashes at the end of the string so far array_pop($stk); //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '[') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-bracket, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); //print("Found start of array at {$c}\n"); } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { // found a right-bracket, and we're in an array array_pop($stk); //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '{') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-brace, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); //print("Found start of object at {$c}\n"); } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { // found a right-brace, and we're in an object array_pop($stk); //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($substr_chrs_c_2 == '/*') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a comment start, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); $c++; //print("Found start of comment at {$c}\n"); } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { // found a comment end, and we're in one now array_pop($stk); $c++; for ($i = $top['where']; $i <= $c; ++$i) $chrs = substr_replace($chrs, ' ', $i, 1); //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } } if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { return $obj; } } } } /** * @todo Ultimately, this should just call PEAR::isError() */ function isError($data, $code = null) { if (class_exists('pear')) { return PEAR::isError($data, $code); } elseif (is_object($data) && (get_class($data) == 'services_json_error' || is_subclass_of($data, 'services_json_error'))) { return true; } return false; } } if (class_exists('PEAR_Error')) { class Services_JSON_Error extends PEAR_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { parent::PEAR_Error($message, $code, $mode, $options, $userinfo); } } } else { /** * @todo Ultimately, this class shall be descended from PEAR_Error */ class Services_JSON_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { } } } ?>
mit
jmikrut/keen-2017
src/content/work/assets/SubscriptionsForSaas/modules/List/Icons/Pause/index.js
362
import React from 'react'; import './Pause.css'; export default (props) => { let color = props.color ? props.color : ''; return ( <svg className="plus" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"> <line stroke={color} x1="4.76" y1="3.76" x2="4.76" y2="8.24"/> <line stroke={color} x1="7.24" y1="8.24" x2="7.24" y2="3.76"/> </svg> ); }
mit
GistBox/github
lib/github_api/request/jsonize.rb
1076
# encoding: utf-8 require 'faraday' module Github class Request::Jsonize < Faraday::Middleware CONTENT_TYPE = 'Content-Type'.freeze MIME_TYPE = 'application/json'.freeze dependency 'multi_json' def call(env) if request_with_body?(env) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE env[:body] = encode_body env unless env[:body].respond_to?(:to_str) end @app.call env end def encode_body(env) if MultiJson.respond_to?(:dump) MultiJson.dump env[:body] else MultiJson.encode env[:body] end end def request_with_body?(env) type = request_type(env) has_body?(env) and (type.empty? or type == MIME_TYPE) end # Don't encode bodies in string form def has_body?(env) body = env[:body] and !(body.respond_to?(:to_str) and body.empty?) end def request_type(env) type = env[:request_headers][CONTENT_TYPE].to_s type = type.split(';', 2).first if type.index(';') type end end # Request::Jsonize end # Github
mit
cvan/cbir-portal
settings.py
7976
import os import logging import logging.handlers import environment import logconfig # If using a separate Python package (e.g. a submodule in vendor/) to share # logic between applications, you can also share settings. Just create another # settings file in your package and import it like so: # # from comrade.core.settings import * # # The top half of this settings.py file is copied from comrade for clarity. We # use the import method in actual deployments. # Make filepaths relative to settings. path = lambda root,*a: os.path.join(root, *a) ROOT = os.path.dirname(os.path.abspath(__file__)) # List of admin e-mails - we use Hoptoad to collect error notifications, so this # is usually blank. ADMINS = () MANAGERS = ADMINS # Deployment Configuration class DeploymentType: PRODUCTION = "PRODUCTION" DEV = "DEV" SOLO = "SOLO" STAGING = "STAGING" dict = { SOLO: 1, PRODUCTION: 2, DEV: 3, STAGING: 4 } if 'DEPLOYMENT_TYPE' in os.environ: DEPLOYMENT = os.environ['DEPLOYMENT_TYPE'].upper() else: DEPLOYMENT = DeploymentType.SOLO SITE_ID = DeploymentType.dict[DEPLOYMENT] DEBUG = DEPLOYMENT != DeploymentType.PRODUCTION STATIC_MEDIA_SERVER = DEPLOYMENT == DeploymentType.SOLO TEMPLATE_DEBUG = DEBUG SSL_ENABLED = DEBUG INTERNAL_IPS = ('127.0.0.1',) # Logging if DEBUG: LOG_LEVEL = logging.DEBUG else: LOG_LEVEL = logging.INFO # Only log to syslog if this is not a solo developer server. USE_SYSLOG = DEPLOYMENT != DeploymentType.SOLO # Cache Backend CACHE_TIMEOUT = 3600 MAX_CACHE_ENTRIES = 10000 CACHE_MIDDLEWARE_SECONDS = 3600 CACHE_MIDDLEWARE_KEY_PREFIX = '' # Don't require developers to install memcached, and also make debugging easier # because cache is automatically wiped when the server reloads. if DEPLOYMENT == DeploymentType.SOLO: CACHE_BACKEND = ('locmem://?timeout=%(CACHE_TIMEOUT)d' '&max_entries=%(MAX_CACHE_ENTRIES)d' % locals()) else: CACHE_BACKEND = ('memcached://127.0.0.1:11211/?timeout=%(CACHE_TIMEOUT)d' '&max_entries=%(MAX_CACHE_ENTRIES)d' % locals()) # E-mail Server if DEPLOYMENT != DeploymentType.SOLO: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'YOU@YOUR-SITE.com' EMAIL_HOST_PASSWORD = 'PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = "Bueda Support <support@bueda.com>" SERVER_EMAIL = "Bueda Operations <ops@bueda.com>" CONTACT_EMAIL = 'support@bueda.com' # Internationalization TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' USE_I18N = False # Testing # Use nosetests instead of unittest TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Paths MEDIA_ROOT = path(ROOT, 'media') MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/admin' ROOT_URLCONF = 'urls' # Version Information # Grab the current commit SHA from git - handy for confirming the version # deployed on a remote server is the one you think it is. #import subprocess #GIT_COMMIT = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], # stdout=subprocess.PIPE).communicate()[0].strip() #del subprocess # Database DATABASES = {} if DEPLOYMENT == DeploymentType.PRODUCTION: DATABASES['default'] = { 'NAME': 'boilerplate', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'your-database.com', 'PORT': '', 'USER': 'boilerplate', 'PASSWORD': 'your-password' } elif DEPLOYMENT == DeploymentType.DEV: DATABASES['default'] = { 'NAME': 'boilerplate_dev', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'your-database.com', 'PORT': '', 'USER': 'boilerplate', 'PASSWORD': 'your-password' } elif DEPLOYMENT == DeploymentType.STAGING: DATABASES['default'] = { 'NAME': 'boilerplate_staging', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'your-database.com', 'PORT': '', 'USER': 'boilerplate', 'PASSWORD': 'your-password' } else: DATABASES['default'] = { 'NAME': 'db', 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'PORT': '', 'USER': '', 'PASSWORD': '' } # Message Broker (for Celery) BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = "boilerplate" BROKER_PASSWORD = "boilerplate" BROKER_VHOST = "boilerplate" CELERY_RESULT_BACKEND = "amqp" # Run tasks eagerly in development, so developers don't have to keep a celeryd # processing running. CELERY_ALWAYS_EAGER = DEPLOYMENT == DeploymentType.SOLO CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # South # Speed up testing when you have lots of migrations. SOUTH_TESTS_MIGRATE = False SKIP_SOUTH_TESTS = True # Logging SYSLOG_FACILITY = logging.handlers.SysLogHandler.LOG_LOCAL0 SYSLOG_TAG = "boilerplate" # See PEP 391 and logconfig.py for formatting help. Each section of LOGGING # will get merged into the corresponding section of log_settings.py. # Handlers and log levels are set up automatically based on LOG_LEVEL and DEBUG # unless you set them here. Messages will not propagate through a logger # unless propagate: True is set. LOGGERS = { 'loggers': { 'boilerplate': {}, }, } logconfig.initialize_logging(SYSLOG_TAG, SYSLOG_FACILITY, LOGGERS, LOG_LEVEL, USE_SYSLOG) # Debug Toolbar DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False } # Application Settings CBIR_PATH = path('../cbir') GALLERY_PATH = os.path.join(MEDIA_ROOT, 'images', 'gallery') GALLERY_URL = MEDIA_URL + 'images/gallery/' GALLERY_SIZE = 10000 # Number of images in gallery # Maximum length of the filename. Forms should use this and raise # ValidationError if the length is exceeded. # @see http://code.djangoproject.com/ticket/9893 # Columns are 250 but this leaves 50 chars for the upload_to prefix MAX_FILENAME_LENGTH = 200 MAX_FILEPATH_LENGTH = 250 IMAGE_UPLOAD_PATH = 'uploads/images/' IMAGE_UPLOAD_URL = MEDIA_URL + IMAGE_UPLOAD_PATH IMAGE_UPLOAD_PATH_FULL = os.path.join(MEDIA_ROOT, IMAGE_UPLOAD_PATH) IMAGE_ALLOWED_TYPES = {'.pgm': 'image/x-portable-graymap'} IMAGE_ALLOWED_EXTENSIONS = IMAGE_ALLOWED_TYPES.keys() IMAGE_ALLOWED_MIMETYPES = IMAGE_ALLOWED_TYPES.values() SECRET_KEY = 'some-super-secret-token' LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/' # Sessions SESSION_ENGINE = "django.contrib.sessions.backends.cache" # Middleware MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) if DEPLOYMENT != DeploymentType.SOLO: MIDDLEWARE_CLASSES += ( 'django.middleware.transaction.TransactionMiddleware', ) # Templates TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) if DEPLOYMENT != DeploymentType.SOLO: TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', TEMPLATE_LOADERS), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.request', 'django.core.context_processors.csrf', 'django.core.context_processors.media', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.media', ) TEMPLATE_DIRS = ( path(ROOT, 'templates') ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.markup', 'django.contrib.messages', 'images', ) if DEPLOYMENT == DeploymentType.SOLO: INSTALLED_APPS += ( 'django_extensions', 'django_nose', )
mit
rcarver/mysql-inspector
test/mysql_inspector/cli_diff_test.rb
1793
require 'helper' describe "mysql-inspector diff" do describe "parsing arguments" do subject { parse_command(MysqlInspector::CLI::DiffCommand, args) } let(:args) { [] } specify "it compares current to target" do subject.ivar(:version1).must_equal "current" subject.ivar(:version2).must_equal "target" end specify "it compares current to something else" do args << "other" subject.ivar(:version1).must_equal "current" subject.ivar(:version2).must_equal "other" end specify "it compares two arbitrary versions" do args << "other1" args << "other2" subject.ivar(:version1).must_equal "other1" subject.ivar(:version2).must_equal "other2" end end describe "running" do subject { inspect_database "diff" } before do create_mysql_database schema_a inspect_database "write #{database_name} current" create_mysql_database schema_b inspect_database "write #{database_name} target" end specify do stderr.must_equal "" stdout.must_equal <<-EOL.unindented diff current target - colors = things COL - `color` varchar(255) NOT NULL + `first_name` varchar(255) NOT NULL + `last_name` varchar(255) NOT NULL IDX - KEY `color` (`color`) + KEY `name` (`first_name`,`last_name`) CST - CONSTRAINT `belongs_to_color` FOREIGN KEY (`color`) REFERENCES `colors` (`name`) ON DELETE NO ACTION ON UPDATE CASCADE + CONSTRAINT `belongs_to_user` FOREIGN KEY (`first_name`,`last_name`) REFERENCES `users` (`first_name`,`last_name`) ON DELETE NO ACTION ON UPDATE CASCADE + users EOL status.must_equal 0 end end end
mit
vgrem/Office365-REST-Python-Client
office365/sharepoint/tenant/administration/site_creation_default_storage_quota.py
118
from office365.runtime.client_value import ClientValue class SiteCreationDefaultStorageQuota(ClientValue): pass
mit
Bathlamos/RTDC
core/src/main/java/rtdc/core/json/JSONStringer.java
3154
package rtdc.core.json; /* Copyright (c) 2006 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * JSONStringer provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. * <p> * A JSONStringer instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting cascade style. For example, <pre> * myString = new JSONStringer() * .object() * .key("JSON") * .value("Hello, World!") * .endObject() * .toString();</pre> which produces the string <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2 */ public class JSONStringer extends JSONWriter { /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ public JSONStringer() { super(new StringWriter()); } /** * Return the JSON text. This method is used to obtain the product of the * JSONStringer instance. It will return <code>null</code> if there was a * problem in the construction of the JSON text (such as the calls to * <code>array</code> were not properly balanced with calls to * <code>endArray</code>). * @return The JSON text. */ public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } }
mit
NewFuture/BitTorrent
Torrent.Client/SeedMode.cs
2560
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Torrent.Client.Messages; namespace Torrent.Client { class SeedMode:TorrentMode { private const int MaxConnectedPeers = 100; public SeedMode(BlockManager manager, BlockStrategist strategist, TorrentData metadata, TransferMonitor monitor) : base(manager, strategist, metadata, monitor) {} public SeedMode(TorrentMode oldMode):this(new BlockManager(oldMode.Metadata, oldMode.BlockManager.MainDirectory), oldMode.BlockStrategist, oldMode.Metadata, oldMode.Monitor) { } public override void Start() { base.Start(); PeerListener.Register(Metadata.InfoHash, peer => SendHandshake(peer, DefaultHandshake)); } public override void Stop(bool closeStreams) { base.Stop(closeStreams); PeerListener.Deregister(Metadata.InfoHash); } protected override void HandleRequest(RequestMessage request, PeerState peer) { if (!peer.IsChoked && request.Length <= Global.Instance.BlockSize) { BlockManager.GetBlock(new byte[request.Length], request.Index, request.Offset, request.Length, BlockRead, peer); } } protected override bool AddPeer(PeerState peer) { if (Peers.Count >= MaxConnectedPeers) return false; SendBitfield(peer); return base.AddPeer(peer); } private void SendBitfield(PeerState peer) { SendMessage(peer, new BitfieldMessage(BlockStrategist.Bitfield)); } protected override void HandleInterested(InterestedMessage interested, PeerState peer) { base.HandleInterested(interested, peer); peer.IsChoked = false; SendMessage(peer, new UnchokeMessage()); } private void BlockRead(bool success, Block block, object state) { var peer = (PeerState)state; try { if (success) { Monitor.Read(block.Info.Length); SendMessage(peer, new PieceMessage(block.Info.Index, block.Info.Offset, block.Data)); } } catch (Exception e) { HandleException(e); } } protected override void HandlePiece(PieceMessage piece, PeerState peer) {} } }
mit
mikeSimonson/destrukt
src/UnorderedList.php
413
<?php namespace Shadowhand\Destrukt; use Shadowhand\Destrukt\Ability; class UnorderedList implements StructInterface { use Ability\Storage; use Ability\ValueStorage; public function validate(array $data) { if (array_values($data) !== $data) { throw new \InvalidArgumentException( 'List structures cannot be indexed by keys' ); } } }
mit
otto-gebb/KreatorDSL
src/KreatorDsl/Ast/DimensionedNode.cs
928
namespace KreatorDsl.Ast { /// <summary> /// Repreaents a dimensioned value (an integer with a unit of measure). /// </summary> public class DimensionedNode : ValueNode { /// <summary> /// Initializes a new instance of the <see cref="DimensionedNode"/> class. /// </summary> /// <param name="integerValue">The integer value.</param> /// <param name="unit">The unit of measure.</param> public DimensionedNode(int integerValue, string unit) { IntegerValue = integerValue; Unit = unit; } /// <summary> /// Gets the integer value. /// </summary> public int IntegerValue { get; } /// <summary> /// Gets the unit of measure. /// </summary> public string Unit { get; } /// <summary> /// Returns the string representation part /// specific to this particular AST Node class. /// </summary> public override string ToStringImpl() { return $"{IntegerValue}<{Unit}>"; } } }
mit
Kait-tt/tacowasa
spec/schemes/label_spec.js
2149
'use strict'; const expect = require('chai').expect; const helper = require('../helper'); const db = require('../../lib/schemes'); describe('schemes', () => { describe('label', () => { afterEach(() => helper.db.clean()); describe('#create', () => { let user, project, label; beforeEach(async () => { user = await db.User.create({username: 'user1'}); project = await db.Project.create({name: 'project1', createUserId: user.id}); label = await db.Label.create({name: 'label1', color: '343434', projectId: project.id}); }); it('should create a new label', async () => { const _labels = await db.Label.findAll({include: [{all: true, nested: false}]}); expect(_labels).to.have.lengthOf(1); expect(_labels[0]).to.have.property('name', 'label1'); expect(_labels[0]).to.have.property('color', '343434'); }); describe('task#addLabel', () => { let stage, cost, task; beforeEach(async () => { stage = await db.Stage.create({name: 'todo', displayName: 'ToDo', assigned: true, projectId: project.id}); cost = await db.Cost.create({name: 'medium', value: 3, projectId: project.id}); task = await db.Task.create({ projectId: project.id, stageId: stage.id, userId: user.id, costId: cost.id, title: 'title1', body: 'body1', isWorking: true }); await task.addLabel(label); }); it('task should have a label', async () => { const _task = await db.Task.findById(task.id, {include: [{model: db.Label}]}); expect(_task.labels).to.have.lengthOf(1); expect(_task.labels[0]).to.have.property('name', 'label1'); }); }); }); }); });
mit
udacity/course-web-forms
etc/js_grader.js
9455
function Queue(grader) { this.grader = grader; this.gradingSteps = []; this.flushing = false; }; Queue.prototype = { add: function(callback, messages, keepGoing) { if (keepGoing !== false) { keepGoing = true; } if (!callback) { throw new Error("UD: Every test added to the queue must have a valid function."); } this.gradingSteps.push({ callback: callback, isCorrect: false, wrongMessage: messages.wrongMessage || null, comment: messages.comment || null, category: messages.category || null, keepGoing: keepGoing }); }, flush: function() { if (!this.flushing) { this.flushing = true; } this.step(); }, clear: function() { this.flushing = false; this.gradingSteps = []; }, step: function() { if (this.gradingSteps.length === 0) { this.clear(); } if (this.flushing) { var test = this.gradingSteps.shift(); try { test.isCorrect = test.callback(); } catch (e) { test.isCorrect = false; } if (!test.isCorrect) { console.log(test.wrongMessage + " " + test.isCorrect); } this.registerResults(test); if (test.isCorrect || (test.keepGoing)) { this.step(); } else { this.clear(); } } }, registerResults: function (test) { this.grader.registerResults(test); } }; function Grader (categoryMessages) { var self = this; this.specificFeedback = []; this.comments = []; this.isCorrect = false; this.correctHasChanged = false; this.queue = new Queue(self); this.categoryMessages = categoryMessages || null; this.generalFeedback = []; }; Grader.prototype = { addTest: function (callback, messages, keepGoing) { this.queue.add(callback, messages, keepGoing); }, runTests: function () { this.queue.flush(); }, registerResults: function (test) { this.generateSpecificFeedback(test); this.generateGeneralFeedback(test); this.setCorrect(test); }, generateSpecificFeedback: function (test) { if (!test.isCorrect && test.wrongMessage) { this.addSpecificFeedback(test.wrongMessage); } else if (test.isCorrect && test.comment) { this.addComment(test.comment) } }, generateGeneralFeedback: function (test) { if (!test.isCorrect && test.category) { if (this.generalFeedback.indexOf(this.categoryMessages[test.category]) === -1) { this.generalFeedback.push(this.categoryMessages[test.category]); } } }, setCorrect: function (test) { if (this.correctHasChanged) { this.isCorrect = this.isCorrect && test.isCorrect; } else { this.correctHasChanged = true; this.isCorrect = test.isCorrect; } }, addSpecificFeedback: function (feedback) { this.specificFeedback.push(feedback); }, addComment: function (feedback) { this.comments.push(feedback); }, getFormattedWrongMessages: function () { var allMessages, message; allMessages = this.specificFeedback.concat(this.generalFeedback); message = allMessages.join('\n\n'); return message; }, getFormattedComments: function () { return this.comments.join('\n\n'); }, isType: function (theirValue, expectedType, showDefaultWrongMessage) { showDefaultWrongMessage = showDefaultWrongMessage || false; var isCorrect = false; if (typeof theirValue !== expectedType) { if (typeof theirValue === 'function') { theirValue = theirValue.name; }; isCorrect = false; } else if (typeof theirValue === expectedType){ isCorrect = true; } return isCorrect; }, isInstance: function (theirValue, expectedInstance, showDefaultWrongMessage) { showDefaultWrongMessage = showDefaultWrongMessage || false; var isCorrect = false; if (theirValue instanceof expectedInstance !== true) { isCorrect = false; } else if (theirValue instanceof expectedInstance === true){ isCorrect = true; } return isCorrect; }, isValue: function (theirValue, expectedValue, showDefaultWrongMessage) { showDefaultWrongMessage = showDefaultWrongMessage || false; var isCorrect = false; if (!deepCompare(theirValue, expectedValue)) { isCorrect = false; } else if (deepCompare(theirValue, expectedValue)) { isCorrect = true; } return isCorrect; }, isInRange: function (theirValue, lower, upper, showDefaultWrongMessage) { showDefaultWrongMessage = showDefaultWrongMessage || false; var isCorrect = false; if (typeof theirValue !== 'number' || isNaN(theirValue)) { isCorrect = false } else if (theirValue > upper || theirValue < lower) { isCorrect = false; } else if (theirValue < upper || theirValue > lower) { isCorrect = true; } return isCorrect; }, // TODO: does this ever actually fail? or does it just error? isSet: function (value, showDefaultWrongMessage) { showDefaultWrongMessage = showDefaultWrongMessage || false; var isCorrect = false; if (value === undefined) { isCorrect = false; } else { isCorrect = true; } return isCorrect; } } function sendResultsToExecutor() { var output = { isCorrect: false, test_feedback: "", test_comments: "", congrats: "" } for (arg in arguments) { var thisIsCorrect = arguments[arg].isCorrect; var thisTestFeedback = arguments[arg].getFormattedWrongMessages(); var thisTestComment = arguments[arg].getFormattedComments(); if (typeof thisIsCorrect !== 'boolean') { thisIsCorrect = false; } switch (arg) { case '0': output.congrats = arguments[arg]; case '1': output.isCorrect = thisIsCorrect; output.test_feedback = thisTestFeedback; output.test_comments = thisTestComment; break; default: output.isCorrect = thisIsCorrect && output.isCorrect; if (output.test_feedback !== "") { output.test_feedback = [output.test_feedback, thisTestFeedback].join('\n'); } else { output.test_feedback = thisTestFeedback; } if (output.test_comments !== "") { output.test_comments = [output.test_comments, thisTestFeedback].join('\n'); } else { output.test_comments = thisTestComment; } break; } } output = JSON.stringify(output); console.info("UDACITY_RESULT:" + output); } // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript?lq=1 function deepCompare () { var i, l, leftChain, rightChain; function compare2Objects (x, y) { var p; // remember that NaN === NaN returns false // and isNaN(undefined) returns true if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') { return true; } // Compare primitives and functions. // Check if both arguments link to the same object. // Especially useful on step when comparing prototypes if (x === y) { return true; } // Works in case when functions are created in constructor. // Comparing dates is a common scenario. Another built-ins? // We can even handle functions passed across iframes if ((typeof x === 'function' && typeof y === 'function') || (x instanceof Date && y instanceof Date) || (x instanceof RegExp && y instanceof RegExp) || (x instanceof String && y instanceof String) || (x instanceof Number && y instanceof Number)) { return x.toString() === y.toString(); } // At last checking prototypes as good a we can if (!(x instanceof Object && y instanceof Object)) { return false; } if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) { return false; } if (x.constructor !== y.constructor) { return false; } if (x.prototype !== y.prototype) { return false; } // Check for infinitive linking loops if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) { return false; } // Quick checking of one object beeing a subset of another. // todo: cache the structure of arguments[0] for performance for (p in y) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } } for (p in x) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } switch (typeof (x[p])) { case 'object': case 'function': leftChain.push(x); rightChain.push(y); if (!compare2Objects (x[p], y[p])) { return false; } leftChain.pop(); rightChain.pop(); break; default: if (x[p] !== y[p]) { return false; } break; } } return true; } if (arguments.length < 1) { return true; //Die silently? Don't know how to handle such case, please help... // throw "Need two or more arguments to compare"; } for (i = 1, l = arguments.length; i < l; i++) { leftChain = []; //Todo: this can be cached rightChain = []; if (!compare2Objects(arguments[0], arguments[i])) { return false; } } return true; }
mit
phoenixmusical/membres
lib/utils/calendar.js
1512
var Calendar = require('calendar').Calendar; var Event = require('../models/event'); var IndexedCollection = require('./indexed-collection'); var firstYear = 2014; var calendar = new Calendar(0); var monthNames = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"]; function fetchEventsMap(filter){ return Event.find(filter) .then(function(events){ var eventsMap = IndexedCollection(); events.forEach(function(event){ var day = event.start.getDate(); eventsMap.add(day, event); }); return eventsMap; }); } function getDateRange(year, month){ var endMonth = month + 1; var endYear = year; if(endMonth > 12){ endMonth -= 12; endYear++; } return { start: new Date(year, month, 1, 0, 0, 0, 0), end: new Date(endYear, endMonth, 1, 23, 59, 59, 0) }; } exports.create = function(year, month, filter){ if(month < 0 || month > 11){ throw new Error("Invalid month"); } if(year < firstYear){ throw new Error("Invalid year"); } var range = getDateRange(year, month); filter.start = { $gt: range.start, $lt: range.end }; return fetchEventsMap(filter) .then(function(eventsMap){ var weeks = calendar.monthDays(year, month).map(function(week){ return week.map(function(day){ return { number: day || "", events: eventsMap.get(day) }; }); }); return { monthName: monthNames[month], month: month+1, year: year, weeks: weeks }; }); };
mit
jgin/testphp
web/bundles/hrmpayroll/app/view/Well/AssignEquipments.js
7212
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ Ext.define('sisprod.view.Well.AssignEquipments',{ extend: 'sisprod.view.base.BaseDataWindow', alias: 'widget.assignEquipments', require: [ 'sisprod.view.base.BaseDataWindow' ], messages: { equipmentEmptyText: 'Type an equipment name...', labels: { engineEquipment: 'Engine', pumpingUnitEquipment: 'Pumping Unit', gearboxRating: 'Gearbox Rating', gearboxPeakBalanced: 'Gearbox Peak Balanced' } }, title: 'Assign Equipments', modal: true, width: 600, initComponent: function(){ var me = this; // var wellEquipment = me.wellEquipment; var idWellEquipment, engine, engineEquipment, pumpingUnit, pumpingUnitEquipment; console.log(wellEquipment); if(Ext.isDefined(wellEquipment) && wellEquipment !== null) { idWellEquipment = wellEquipment['idWellEquipment']; // engine = wellEquipment['engineEquipment']; var engineLocation = ''; if(Ext.isDefined(engine['location']) && engine['location'] !== null) engineLocation = engine['location']['locationName']; // engineEquipment = Ext.create('sisprod.model.EquipmentTempModel', { idEquipment: engine['idEquipment'], equipmentName: engine['equipmentName'], equipmentCode: engine['equipmentCode'], locationName: engineLocation }); // pumpingUnit = wellEquipment['pumpingUnitEquipment']; var pumpingUnitLocation = ''; if(Ext.isDefined(pumpingUnit['location']) && pumpingUnit['location'] !== null) pumpingUnitLocation = pumpingUnit['location']['locationName']; pumpingUnitEquipment = Ext.create('sisprod.model.EquipmentTempModel', { idEquipment: pumpingUnit['idEquipment'], equipmentName: pumpingUnit['equipmentName'], equipmentCode: pumpingUnit['equipmentCode'], locationName: pumpingUnitLocation }); } // var fluidLevelConfigParam = me.fluidLevelConfigParam; var gearboxRating = 0, gearboxPeakBalanced = 0; if(Ext.isDefined(fluidLevelConfigParam) && fluidLevelConfigParam !== null) { gearboxRating = fluidLevelConfigParam['gearboxRating']; gearboxPeakBalanced = fluidLevelConfigParam['gearboxBalanced']; } // me.formOptions = { bodyPadding: 2, layout: 'anchor', fieldDefaults: { labelWidth: 120 }, items: [ { xtype: 'hiddenfield', name: 'idWellEquipment', value: idWellEquipment }, { xtype: 'hiddenfield', name: 'idWell', value: me.record['idWell'] }, { xtype: 'sensitivecombo', anchor: '100%', name: 'engineIdEquipment', id: 'engineIdEquipment', fieldLabel: me.messages.labels.engineEquipment, labelWidth: 120, hideTrigger: false, padding: '0 0 0 12', store: Ext.create('sisprod.store.EngineEquipmentStore'), emptyText: me.messages.equipmentEmptyText, forceSelection : true, allowBlank: false, displayTpl: Ext.create('Ext.XTemplate', '<tpl for=".">','{equipmentName} - {equipmentCode} ({locationName})','</tpl>'), valueField: 'idEquipment', listConfig: { getInnerTpl: function() { return "{equipmentName} - {equipmentCode} ({locationName})"; } }, value: engineEquipment }, { xtype: 'fieldset', layout: 'anchor', title: me.messages.labels.pumpingUnitEquipment, items: [ { xtype: 'sensitivecombo', anchor: '100%', name: 'unitIdEquipment', id: 'unitIdEquipment', fieldLabel: me.messages.labels.pumpingUnitEquipment, labelWidth: 120, hideTrigger: false, store: Ext.create('sisprod.store.PumpingUnitEquipmentStore'), emptyText: me.messages.equipmentEmptyText, forceSelection : true, allowBlank: false, displayTpl: Ext.create('Ext.XTemplate', '<tpl for=".">','{equipmentName} - {equipmentCode} ({locationName})','</tpl>'), valueField: 'idEquipment', listConfig: { getInnerTpl: function() { return "{equipmentName} - {equipmentCode} ({locationName})"; } }, value: pumpingUnitEquipment }, { xtype: 'fieldcontainer', layout: 'hbox', anchor: '100%', items: [ { xtype: 'numberfield', name: 'gearboxRating', labelWidth: 120, flex: 1, allowBlank: false, fieldLabel: me.messages.labels.gearboxRating, value: gearboxRating }, { xtype: 'numberfield', name: 'gearboxBalanced', margin: '0 0 0 10', labelWidth: 160, flex: 1, allowBlank: false, fieldLabel: me.messages.labels.gearboxPeakBalanced, value: gearboxPeakBalanced } ] } ] } ] }; me.callParent(arguments); } });
mit
isovic/aligneval
setup.py
10455
#! /usr/bin/python import os SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)); import sys sys.path.append(SCRIPT_PATH + '/src') sys.path.append(SCRIPT_PATH + '/wrappers'); import subprocess; # from evalpaths import * # import generate_data # import filesandfolders; # from basicdefines import *; import basicdefines; import generate_data; def create_folders(): sys.stderr.write('Generating folders...\n'); if not os.path.exists(basicdefines.EVALUATION_PATH_ROOT_ABS): sys.stderr.write('Creating folder "%s".\n' % basicdefines.EVALUATION_PATH_ROOT_ABS); os.makedirs(basicdefines.EVALUATION_PATH_ROOT_ABS); if not os.path.exists(basicdefines.TOOLS_ROOT_ABS): sys.stderr.write('Creating folder "%s".\n' % basicdefines.TOOLS_ROOT_ABS); os.makedirs(basicdefines.TOOLS_ROOT_ABS); if not os.path.exists(basicdefines.ALIGNERS_PATH_ROOT_ABS): sys.stderr.write('Creating folder "%s".\n' % basicdefines.ALIGNERS_PATH_ROOT_ABS); os.makedirs(basicdefines.ALIGNERS_PATH_ROOT_ABS); sys.stderr.write('\n'); def unpack_reference_genomes(): sys.stderr.write('Unpacking reference genomes [~400 MB]\n'); tar_gz_references = basicdefines.find_files(basicdefines.REFERENCE_GENOMES_ROOT_ABS, '*.tar.gz'); for file_path in tar_gz_references: subprocess.call(('tar -xzvf %s -C %s/' % (file_path, os.path.dirname(file_path))), shell='True'); sys.stderr.write('\n'); def download_hg19_GRCh38_reference(): hg19_GRCh38_path = 'http://hgdownload.cse.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.gz'; sys.stderr.write('Downloading the Human reference genome (GRCh38).'); command = 'mkdir -p %s/download; cd %s/download; wget %s' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, basicdefines.REFERENCE_GENOMES_ROOT_ABS, hg19_GRCh38_path); subprocess.call(command, shell='True'); sys.stderr.write('\n'); hg_archive_filename = os.path.basename(hg19_GRCh38_path); sys.stderr.write('Unpacking the Human reference genome (GRCh38).'); command = 'cd %s/download; gunzip %s' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, hg_archive_filename); subprocess.call(command, shell='True'); sys.stderr.write('\n'); hg_archive_filename = os.path.basename(hg19_GRCh38_path); sys.stderr.write('Unpacking the Human reference genome (GRCh38).'); command = 'mv %s/download/hg38.fa %s/' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, basicdefines.REFERENCE_GENOMES_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); def download_hg19_GRCh37_reference(): hg19_GRCh37_path = 'http://hgdownload.cse.ucsc.edu/goldenPath/hg19/bigZips/chromFa.tar.gz'; sys.stderr.write('Downloading the Human reference genome (GRCh37).\n'); command = 'mkdir -p %s/download; cd %s/download; wget %s' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, basicdefines.REFERENCE_GENOMES_ROOT_ABS, hg19_GRCh37_path); subprocess.call(command, shell='True'); sys.stderr.write('\n'); hg_archive_filename = os.path.basename(hg19_GRCh37_path); sys.stderr.write('Unpacking the Human reference genome (GRCh37).\n'); command = 'cd %s/download; mkdir -p hgchroms; tar -C hgchroms/ -xzvf %s' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, hg_archive_filename); subprocess.call(command, shell='True'); sys.stderr.write('\n'); hg19_with_masking_fa = '%s/download/hgchroms/hg19_with_masking.fa' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS); sys.stderr.write('Joining the chromosomes into one multifasta file on path: %s.\n' % (hg19_with_masking_fa)); command = 'cd %s/download;' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS); command += 'cat hgchroms/chr1.fa > %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr2.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr3.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr4.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr5.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr6.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr7.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr8.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr9.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr10.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr11.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr12.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr13.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr14.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr15.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr16.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr17.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr18.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr19.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr20.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr21.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chr22.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chrX.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chrY.fa >> %s;' % (hg19_with_masking_fa); command += 'cat hgchroms/chrM.fa >> %s;' % (hg19_with_masking_fa); subprocess.call(command, shell='True'); sys.stderr.write('\n'); hg19_fa = '%s/hg19.fa' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS); sys.stderr.write('Converting the hg19 multifasta (%s) bases to uppercase (%s).\n' % (hg19_with_masking_fa, hg19_fa)); command = 'cd %s; %s/samscripts/src/fastqfilter.py touppercase %s %s' % (basicdefines.REFERENCE_GENOMES_ROOT_ABS, basicdefines.TOOLS_ROOT_ABS, hg19_with_masking_fa, hg19_fa); subprocess.call(command, shell='True'); sys.stderr.write('\n'); def unpack_sample_sim_reads(): sys.stderr.write('Unpacking pre-simulated data [~400 MB]\n'); tar_gz = basicdefines.find_files(basicdefines.READS_SIMULATED_ROOT_ABS, '*.tar.gz'); for file_path in tar_gz: subprocess.call(('tar -xzvf %s -C %s/' % (file_path, os.path.dirname(file_path))), shell='True'); sys.stderr.write('\n'); def download_aligners(): sys.stderr.write('Installing alignment tools.\n'); aligner_wrappers = basicdefines.find_files(basicdefines.WRAPPERS_PATH_ROOT_ABS, 'wrapper_*.py'); for wrapper in aligner_wrappers: wrapper_basename = os.path.splitext(os.path.basename(wrapper))[0]; command = 'import %s; %s.download_and_install()' % (wrapper_basename, wrapper_basename); exec(command); def setup_tools(): if (not os.path.exists(basicdefines.TOOLS_ROOT_ABS)): os.makedirs(basicdefines.TOOLS_ROOT_ABS); sys.stderr.write('Cloning Cgmemtime Git repo. Git needs to be installed.\n'); command = 'cd %s; git clone https://github.com/isovic/cgmemtime.git' % (basicdefines.TOOLS_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); sys.stderr.write('Cloning Samscripts Git repo. Git needs to be installed.\n'); command = 'cd %s; git clone https://github.com/isovic/samscripts.git' % (basicdefines.TOOLS_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); sys.stderr.write('Downloading and unpacking the ART next generation sequence simulator.\n'); command = 'cd %s; wget http://www.niehs.nih.gov/research/resources/assets/docs/artbinvanillaicecream031114linux64tgz.tgz; tar -xzvf artbinvanillaicecream031114linux64tgz.tgz' % (basicdefines.TOOLS_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); sys.stderr.write('Downloading and unpacking PBsim.\n'); command = 'cd %s; wget http://pbsim.googlecode.com/files/pbsim-1.0.3-Linux-amd64.tar.gz; tar -xzvf pbsim-1.0.3-Linux-amd64.tar.gz' % (basicdefines.TOOLS_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); sys.stderr.write('Downloading and unpacking LAST aligner. Its scripts are needed to convert from MAF to SAM.\n'); command = 'cd %s; wget http://last.cbrc.jp/last-534.zip; unzip last-534.zip' % (basicdefines.TOOLS_ROOT_ABS); subprocess.call(command, shell='True'); sys.stderr.write('\n'); def verbose_usage_and_exit(): sys.stderr.write('Usage:\n'); sys.stderr.write('\t%s [mode]\n' % sys.argv[0]); sys.stderr.write('\n'); sys.stderr.write('\tParameter mode specifies which step to execute.\n'); sys.stderr.write('\t- mode - "all", "folders", "references", "aligners", "tools", "simdata" or "generate-simdata".\n'); sys.stderr.write('\n'); exit(0); if __name__ == '__main__': if (len(sys.argv) != 2): verbose_usage_and_exit(); mode = sys.argv[1]; mode_valid = False; if (mode == 'references' or mode == 'simdata'): mode_valid = True; sys.stderr.write('Running this script will consume large amount of disk space.\n'); yes_no = raw_input("Do you want to continue? [y/n] "); if (yes_no != 'y'): sys.stderr.write('Exiting.\n\n'); exit(0); if (mode == 'all' or mode == 'folders'): create_folders(); mode_valid = True; if (mode == 'all' or mode == 'references'): unpack_reference_genomes(); # download_hg19_GRCh38_reference(); sys.stderr.write('Please make sure you ran "./setup tools" prior to running this command.\n\n'); download_hg19_GRCh37_reference(); mode_valid = True; if (mode == 'all' or mode == 'aligners'): download_aligners(); mode_valid = True; if (mode == 'all' or mode == 'tools'): setup_tools(); mode_valid = True; if (mode == 'all' or mode == 'simdata'): # generate_data.GenerateAll(); sys.stderr.write('Please make sure you ran "./setup tools" and "./setup references" prior to running this command.\n\n'); unpack_sample_sim_reads(); if (not os.path.exists('%s/saccharomyces_cerevisiae.fa' % basicdefines.REFERENCE_GENOMES_ROOT_ABS)): sys.stderr.write('ERROR: Can not continue with setting up the simulated data until reference sequences are unpacked! Run "./setup.py references" first.\n'); exit(1); generate_data.GenerateGridTest(10000); mode_valid = True; if (mode == 'generate-simdata'): sys.stderr.write('Please make sure you ran "./setup tools" and "./setup references" prior to running this command.\n\n'); generate_data.GenerateAll(); mode_valid = True; if (mode_valid == False): sys.stderr.write('Selected mode not recognized!\n'); verbose_usage_and_exit(); # sys.stderr.write('Generating simulated data...\n'); # generate_data.GenerateAll(); # sys.stderr.write('Finished generating simulated data!\n'); # sudo apt-get install python-matplotlib # sudo apt-get install python-tk # sudo apt-get install python-pip
mit
hyonholee/azure-sdk-for-net
sdk/storagesync/Microsoft.Azure.Management.StorageSync/src/Generated/Models/ServerEndpointCloudTieringStatus.cs
3036
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.StorageSync.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Server endpoint cloud tiering status object. /// </summary> public partial class ServerEndpointCloudTieringStatus { /// <summary> /// Initializes a new instance of the ServerEndpointCloudTieringStatus /// class. /// </summary> public ServerEndpointCloudTieringStatus() { CustomInit(); } /// <summary> /// Initializes a new instance of the ServerEndpointCloudTieringStatus /// class. /// </summary> /// <param name="health">Cloud tiering health state. Possible values /// include: 'Healthy', 'Error'</param> /// <param name="lastUpdatedTimestamp">Last updated timestamp</param> /// <param name="lastCloudTieringResult">Last cloud tiering result /// (HResult)</param> /// <param name="lastSuccessTimestamp">Last cloud tiering success /// timestamp</param> public ServerEndpointCloudTieringStatus(string health = default(string), System.DateTime? lastUpdatedTimestamp = default(System.DateTime?), int? lastCloudTieringResult = default(int?), System.DateTime? lastSuccessTimestamp = default(System.DateTime?)) { Health = health; LastUpdatedTimestamp = lastUpdatedTimestamp; LastCloudTieringResult = lastCloudTieringResult; LastSuccessTimestamp = lastSuccessTimestamp; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets cloud tiering health state. Possible values include: /// 'Healthy', 'Error' /// </summary> [JsonProperty(PropertyName = "health")] public string Health { get; private set; } /// <summary> /// Gets last updated timestamp /// </summary> [JsonProperty(PropertyName = "lastUpdatedTimestamp")] public System.DateTime? LastUpdatedTimestamp { get; private set; } /// <summary> /// Gets last cloud tiering result (HResult) /// </summary> [JsonProperty(PropertyName = "lastCloudTieringResult")] public int? LastCloudTieringResult { get; private set; } /// <summary> /// Gets last cloud tiering success timestamp /// </summary> [JsonProperty(PropertyName = "lastSuccessTimestamp")] public System.DateTime? LastSuccessTimestamp { get; private set; } } }
mit
fpellicero/RegneHostilWebsite
src/RegneHostil/AdminBundle/RegneHostilAdminBundle.php
140
<?php namespace RegneHostil\AdminBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class RegneHostilAdminBundle extends Bundle { }
mit
Interscope/ustudio-theme
themes/sample/files/static/js/playlist.js
1651
(function(d){var c=function(b,a,c,d){this._document=b;this._eventBus=a;this._configuration=c;this._playlist=d;this._startIndex=this._currentIndex=0;this._loopPlayback=this._configuration.loop_playback||!1;this._eventBus.subscribe("Playlist.selectVideo",this.selectVideo,this);this._eventBus.subscribe("Playlist.nextVideo",this.nextVideo,this);this._eventBus.subscribe("Playlist.previousVideo",this.previousVideo,this);this._eventBus.subscribe("Player.ended",this.videoEnded,this);this._eventBus.subscribe("start", this._onStart,this);this.log=function(a){console.log(a)}};c.prototype._onStart=function(){this.selectVideo({index:this._currentIndex})};c.prototype.getVideo=function(){return this._playlist[this._currentIndex]};c.prototype.selectVideo=function(b){var a;this._currentIndex=b.index;if(a=this.getVideo())a.index=b.index,this._eventBus.broadcast("Playlist.videoSelected",[{video:a}])};c.prototype.nextVideo=function(b){var a=this._currentIndex+1;a>=this._playlist.length&&(a=0);return void 0==b||b||a!=this._startIndex? (this.selectVideo({index:a}),!0):!1};c.prototype.previousVideo=function(b){var a=this._currentIndex-1;0>a&&(a=this._playlist.length-1);return void 0==b||b||a!=this._startIndex?(this.selectVideo({index:a}),!0):!1};c.prototype.videoEnded=function(){this.nextVideo(this._loopPlayback)||(this._eventBus.broadcast("Playlist.ended"),this.selectVideo({index:this._startIndex}))};c.prototype.onStart=function(){};d.uStudio=d.uStudio||{};d.uStudio.Playlist=c;uStudio.uStudioCore.instance.registerModule({name:"uStudioPlaylist", initialize:function(b,a,d,e){b=new c(document,a,b,d);a.subscribe("start",b.onStart,b);e()}})})(this);
mit
zpasal/source-mas
tools/Node.hpp
213
#ifndef __NODE_H #define __NODE_H namespace MojiAlati { template <typename T> class TListaNode { public: T Vrijednost; TListaNode<T> *Slijedeci; }; } //end-of-namespace #endif
mit
mozmark/note-recognition
notes.js
490
var midiMap = {}; var position_names = [ ['C'], ['C#','Db'], ['D'], ['D#','Eb'], ['E'], ['F'], ['F#','Gb'], ['G'], ['G#','Ab'], ['A'], ['A#','Bb'], ['B'] ]; for (midi_num = 21; midi_num <= 108; midi_num++) { var scale_pos = midi_num % 12; var octave = Math.floor(midi_num / 12) - 1; var note_names = position_names[scale_pos]; // TODO: calculate frequency information midiMap[midi_num] = {'note':note_names[0],'octave':octave}; }
mit
wwahmed/ews-java-api
src/main/java/javax/xml/stream/XMLOutputFactory.java
11809
/* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * Copyright (c) 2009 by Oracle Corporation. All Rights Reserved. */ package javax.xml.stream; import javax.xml.transform.Result; /** * Defines an abstract implementation of a factory for * getting XMLEventWriters and XMLStreamWriters. * * The following table defines the standard properties of this specification. * Each property varies in the level of support required by each implementation. * The level of support required is described in the 'Required' column. * * <table border="2" rules="all" cellpadding="4"> * <thead> * <tr> * <th align="center" colspan="2"> * Configuration parameters * </th> * </tr> * </thead> * <tbody> * <tr> * <th>Property Name</th> * <th>Behavior</th> * <th>Return type</th> * <th>Default Value</th> * <th>Required</th> * </tr> * <tr><td>javax.xml.stream.isRepairingNamespaces</td><td>defaults prefixes on the output side</td><td>Boolean</td><td>False</td><td>Yes</td></tr> * </tbody> * </table> * * <p>The following paragraphs describe the namespace and prefix repair algorithm:</p> * * <p>The property can be set with the following code line: * <code>setProperty("javax.xml.stream.isRepairingNamespaces",new Boolean(true|false));</code></p> * * <p>This property specifies that the writer default namespace prefix declarations. * The default value is false. </p> * * <p>If a writer isRepairingNamespaces it will create a namespace declaration * on the current StartElement for * any attribute that does not * currently have a namespace declaration in scope. If the StartElement * has a uri but no prefix specified a prefix will be assigned, if the prefix * has not been declared in a parent of the current StartElement it will be declared * on the current StartElement. If the defaultNamespace is bound and in scope * and the default namespace matches the URI of the attribute or StartElement * QName no prefix will be assigned.</p> * * <p>If an element or attribute name has a prefix, but is not * bound to any namespace URI, then the prefix will be removed * during serialization.</p> * * <p>If element and/or attribute names in the same start or * empty-element tag are bound to different namespace URIs and * are using the same prefix then the element or the first * occurring attribute retains the original prefix and the * following attributes have their prefixes replaced with a * new prefix that is bound to the namespace URIs of those * attributes. </p> * * <p>If an element or attribute name uses a prefix that is * bound to a different URI than that inherited from the * namespace context of the parent of that element and there * is no namespace declaration in the context of the current * element then such a namespace declaration is added. </p> * * <p>If an element or attribute name is bound to a prefix and * there is a namespace declaration that binds that prefix * to a different URI then that namespace declaration is * either removed if the correct mapping is inherited from * the parent context of that element, or changed to the * namespace URI of the element or attribute using that prefix.</p> * * @version 1.2 * @author Copyright (c) 2009 by Oracle Corporation. All Rights Reserved. * @see XMLInputFactory * @see XMLEventWriter * @see XMLStreamWriter * @since 1.6 */ public abstract class XMLOutputFactory { /** * Property used to set prefix defaulting on the output side */ public static final String IS_REPAIRING_NAMESPACES= "javax.xml.stream.isRepairingNamespaces"; static final String JAXPFACTORYID = "javax.xml.stream.XMLOutputFactory"; // static final String DEFAULIMPL = "com.sun.xml.stream.ZephyrWriterFactory"; static final String DEFAULIMPL = "com.sun.xml.stream.ZephyrWriterFactory"; protected XMLOutputFactory(){} /** * Create a new instance of the factory. * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLOutputFactory newInstance() throws FactoryConfigurationError { return (XMLOutputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true); } /** * Create a new instance of the factory. * This static method creates a new factory instance. This method uses the * following ordered lookup procedure to determine the XMLOutputFactory * implementation class to load: * Use the javax.xml.stream.XMLOutputFactory system property. * Use the properties file "lib/stax.properties" in the JRE directory. * This configuration file is in standard java.util.Properties format * and contains the fully qualified name of the implementation class * with the key being the system property defined above. * Use the Services API (as detailed in the JAR specification), if available, * to determine the classname. The Services API will look for a classname * in the file META-INF/services/javax.xml.stream.XMLOutputFactory in jars * available to the runtime. * Platform default XMLOutputFactory instance. * * Once an application has obtained a reference to a XMLOutputFactory it * can use the factory to configure and obtain stream instances. * * Note that this is a new method that replaces the deprecated newInstance() method. * No changes in behavior are defined by this replacement method relative to the * deprecated method. * * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLOutputFactory newFactory() throws FactoryConfigurationError { return (XMLOutputFactory) FactoryFinder.find(JAXPFACTORYID, DEFAULIMPL, true); } /** * Create a new instance of the factory. * * @param factoryId Name of the factory to find, same as * a property name * @param classLoader classLoader to use * @return the factory implementation * @throws FactoryConfigurationError if an instance of this factory cannot be loaded * * @deprecated This method has been deprecated because it returns an * instance of XMLInputFactory, which is of the wrong class. * Use the new method {@link #newFactory(String, * ClassLoader)} instead. */ public static XMLInputFactory newInstance(String factoryId, ClassLoader classLoader) throws FactoryConfigurationError { try { //do not fallback if given classloader can't find the class, throw exception return (XMLInputFactory) FactoryFinder.find(factoryId, classLoader, null, factoryId.equals(JAXPFACTORYID) ? true : false); } catch (FactoryFinder.ConfigurationError e) { throw new FactoryConfigurationError(e.getException(), e.getMessage()); } } /** * Create a new instance of the factory. * If the classLoader argument is null, then the ContextClassLoader is used. * * Note that this is a new method that replaces the deprecated * newInstance(String factoryId, ClassLoader classLoader) method. * * No changes in behavior are defined by this replacement method relative * to the deprecated method. * * * @param factoryId Name of the factory to find, same as * a property name * @param classLoader classLoader to use * @return the factory implementation * @throws FactoryConfigurationError if an instance of this factory cannot be loaded */ public static XMLOutputFactory newFactory(String factoryId, ClassLoader classLoader) throws FactoryConfigurationError { try { //do not fallback if given classloader can't find the class, throw exception return (XMLOutputFactory) FactoryFinder.find(factoryId, classLoader, null, factoryId.equals(JAXPFACTORYID) ? true : false); } catch (FactoryFinder.ConfigurationError e) { throw new FactoryConfigurationError(e.getException(), e.getMessage()); } } /** * Create a new XMLStreamWriter that writes to a writer * @param stream the writer to write to * @throws XMLStreamException */ public abstract XMLStreamWriter createXMLStreamWriter(java.io.Writer stream) throws XMLStreamException; /** * Create a new XMLStreamWriter that writes to a stream * @param stream the stream to write to * @throws XMLStreamException */ public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream) throws XMLStreamException; /** * Create a new XMLStreamWriter that writes to a stream * @param stream the stream to write to * @param encoding the encoding to use * @throws XMLStreamException */ public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream, String encoding) throws XMLStreamException; /** * Create a new XMLStreamWriter that writes to a JAXP result. This method is optional. * @param result the result to write to * @throws UnsupportedOperationException if this method is not * supported by this XMLOutputFactory * @throws XMLStreamException */ public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException; /** * Create a new XMLEventWriter that writes to a JAXP result. This method is optional. * @param result the result to write to * @throws UnsupportedOperationException if this method is not * supported by this XMLOutputFactory * @throws XMLStreamException */ public abstract XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException; /** * Create a new XMLEventWriter that writes to a stream * @param stream the stream to write to * @throws XMLStreamException */ public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream) throws XMLStreamException; /** * Create a new XMLEventWriter that writes to a stream * @param stream the stream to write to * @param encoding the encoding to use * @throws XMLStreamException */ public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream, String encoding) throws XMLStreamException; /** * Create a new XMLEventWriter that writes to a writer * @param stream the stream to write to * @throws XMLStreamException */ public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException; /** * Allows the user to set specific features/properties on the underlying implementation. * @param name The name of the property * @param value The value of the property * @throws IllegalArgumentException if the property is not supported */ public abstract void setProperty(String name, Object value) throws IllegalArgumentException; /** * Get a feature/property on the underlying implementation * @param name The name of the property * @return The value of the property * @throws IllegalArgumentException if the property is not supported */ public abstract Object getProperty(String name) throws IllegalArgumentException; /** * Query the set of properties that this factory supports. * * @param name The name of the property (may not be null) * @return true if the property is supported and false otherwise */ public abstract boolean isPropertySupported(String name); }
mit
yacoder/allo-cpp
include/allo_never_look_back_allocator.hpp
581
/* Copyright (c) 2017 Maksim Galkin This file is subject to the terms and conditions of the MIT license, distributed with this code package in the LICENSE file, also available at: https://github.com/yacoder/allo-cpp/blob/master/LICENSE */ #pragma once #include "allo_private_allocator.hpp" #include "allocation_strategies/allo_never_look_back_strategy.hpp" namespace allo { template <typename T, typename TInnerAllocator = std::allocator<T>> using never_look_back_allocator = private_allocator<T, strategies::never_look_back_strategy, TInnerAllocator>; } // namespace allo
mit
rwjblue/ember-template-lint
test/unit/base-plugin-test.js
27681
'use strict'; const { traverse, preprocess } = require('@glimmer/syntax'); const Rule = require('./../../lib/rules/base'); const { readdirSync, existsSync, readFileSync } = require('fs'); const { join, parse } = require('path'); const ruleNames = Object.keys(require('../../lib/rules')); describe('base plugin', function() { function runRules(template, rules) { let ast = preprocess(template); for (let ruleConfig of rules) { let { Rule } = ruleConfig; let options = Object.assign({}, ruleConfig, { moduleName: 'layout.hbs', rawSource: template, }); let rule = new Rule(options); traverse(ast, rule.getVisitor()); } } let messages, config; beforeEach(function() { messages = []; config = {}; }); function buildPlugin(visitor) { class FakeRule extends Rule { log(result) { messages.push(result.source); } process(node) { this.log({ message: 'Node source', line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } visitor() { return visitor; } } return FakeRule; } function plugin(Rule, name, config) { return { Rule, name, config, ruleNames }; } it('all presets correctly reexported', function() { const presetsPath = join(__dirname, '../../lib/config'); const files = readdirSync(presetsPath); const presetFiles = files .map(it => parse(it)) .filter(it => it.ext === '.js' && it.name !== 'index') .map(it => it.name); const exportedPresets = require(join(presetsPath, 'index.js')); const exportedPresetNames = Object.keys(exportedPresets); expect(exportedPresetNames).toEqual(presetFiles); }); describe('rules setup is correct', function() { const rulesEntryPath = join(__dirname, '../../lib/rules'); const files = readdirSync(rulesEntryPath); const deprecatedFiles = readdirSync(join(rulesEntryPath, 'deprecations')); const deprecatedRules = deprecatedFiles.filter(fileName => { return fileName.endsWith('.js'); }); const expectedRules = files.filter(fileName => { return fileName.endsWith('.js') && !['base.js', 'index.js'].includes(fileName); }); it('has correct rules reexport', function() { const defaultExport = require(rulesEntryPath); const exportedRules = Object.keys(defaultExport); exportedRules.forEach(ruleName => { let pathName = join(rulesEntryPath, `${ruleName}`); if (ruleName.startsWith('deprecated-')) { pathName = join(rulesEntryPath, 'deprecations', `${ruleName}`); } expect(defaultExport[ruleName]).toEqual(require(pathName)); }); expect(expectedRules.length + deprecatedRules.length).toEqual(exportedRules.length); }); it('has docs/rule reference for each item', function() { function transformFileName(fileName) { return fileName.replace('.js', '.md'); } const ruleDocsFolder = join(__dirname, '../../docs/rule'); deprecatedFiles.forEach(ruleFileName => { const docFilePath = join(ruleDocsFolder, 'deprecations', transformFileName(ruleFileName)); expect(existsSync(docFilePath)).toBe(true); }); expectedRules.forEach(ruleFileName => { const docFilePath = join(ruleDocsFolder, transformFileName(ruleFileName)); expect(existsSync(docFilePath)).toBe(true); }); }); it('All files under docs/rule/ have a link from docs/rules.md.', function() { const docsPath = join(__dirname, '../../docs'); const entryPath = join(docsPath, 'rule'); const ruleFiles = readdirSync(entryPath).filter( name => name.endsWith('.md') && name !== '_TEMPLATE_.md' ); const deprecatedRuleFiles = readdirSync(join(entryPath, 'deprecations')).filter(name => name.endsWith('.md') ); const allRulesFile = readFileSync(join(docsPath, 'rules.md'), { encoding: 'utf8', }); ruleFiles.forEach(fileName => { expect(allRulesFile.includes(`(rule/${fileName})`)).toBe(true); }); deprecatedRuleFiles.forEach(fileName => { expect(allRulesFile.includes(`(rule/deprecations/${fileName})`)).toBe(true); }); }); it('All rules has test files', function() { const testsPath = join(__dirname, '../unit/rules'); const ruleFiles = readdirSync(testsPath).filter(name => name.endsWith('-test.js')); const deprecatedRuleFiles = readdirSync(join(testsPath, 'deprecations')).filter(name => name.endsWith('-test.js') ); expectedRules.forEach(ruleFileName => { const ruleTestFileName = ruleFileName.replace('.js', '-test.js'); expect(ruleFiles.includes(ruleTestFileName)).toBe(true); }); deprecatedRules.forEach(ruleFileName => { const ruleTestFileName = ruleFileName.replace('.js', '-test.js'); expect(deprecatedRuleFiles.includes(ruleTestFileName)).toBe(true); }); }); }); describe('parses templates', function() { let visitor = { ElementNode(node) { this.process(node); }, TextNode(node) { if (!node.loc) { return; } this.process(node); }, }; function expectSource(config) { let template = config.template; let nodeSources = config.sources; it(`can get raw source for \`${template}\``, function() { runRules(template, [plugin(buildPlugin(visitor), 'fake', config)]); expect(messages).toEqual(nodeSources); }); } expectSource({ template: '<div>Foo</div>', sources: ['<div>Foo</div>', 'Foo'], }); expectSource({ template: '<div>\n <div data-foo="blerp">\n Wheee!\n </div>\n</div>', sources: [ '<div>\n <div data-foo="blerp">\n Wheee!\n </div>\n</div>', '\n ', '<div data-foo="blerp">\n Wheee!\n </div>', '"blerp"', '\n Wheee!\n ', '\n', ], }); }); describe('node types', function() { let wasCalled; let visitor = { Template() { wasCalled = true; }, }; it('calls the "Template" node type', function() { runRules('<div>Foo</div>', [plugin(buildPlugin(visitor), 'fake', config)]); expect(wasCalled).toBe(true); }); }); describe('parses instructions', function() { function processTemplate(template) { let Rule = buildPlugin({ MustacheCommentStatement(node) { this.process(node); }, }); Rule.prototype.log = function(result) { messages.push(result.message); }; Rule.prototype.process = function(node) { config = this._processInstructionNode(node); }; runRules(template, [plugin(Rule, 'fake', 'foo')]); } function expectConfig(instruction, expectedConfig) { it(`can parse \`${instruction}\``, function() { processTemplate(`{{! ${instruction} }}`); expect(config).toEqual(expectedConfig); expect(messages).toEqual([]); }); } // Global enable/disable expectConfig('template-lint-disable', { value: false, tree: false }); expectConfig('template-lint-disable-tree', { value: false, tree: true }); expectConfig('template-lint-enable', { value: 'foo', tree: false }); expectConfig('template-lint-enable-tree', { value: 'foo', tree: true }); expectConfig(' template-lint-enable-tree ', { value: 'foo', tree: true }); // Specific enable/disable expectConfig('template-lint-disable fake', { value: false, tree: false }); expectConfig('template-lint-disable-tree "fake"', { value: false, tree: true }); expectConfig("template-lint-disable fake 'no-bare-strings'", { value: false, tree: false }); expectConfig('template-lint-disable no-bare-strings fake block-indentation', { value: false, tree: false, }); expectConfig('template-lint-disable no-bare-strings', null); expectConfig(' template-lint-disable fake ', { value: false, tree: false }); expectConfig('template-lint-disable no-bare-strings fake block-indentation ', { value: false, tree: false, }); // Configure expectConfig('template-lint-configure fake { "key1": "value", "key2": { "key3": 1 } }', { value: { key1: 'value', key2: { key3: 1 } }, tree: false, }); expectConfig('template-lint-configure-tree "fake" { "key": "value" }', { value: { key: 'value' }, tree: true, }); expectConfig("template-lint-configure-tree 'fake' true", { value: true, tree: true, }); expectConfig('template-lint-configure-tree fake false', { value: false, tree: true, }); expectConfig('template-lint-configure-tree no-bare-strings { "key": "value" }', null); expectConfig(' template-lint-configure-tree fake { "key": "value" }', { value: { key: 'value' }, tree: true, }); // Not config expectConfig('this code is awesome', null); expectConfig('', null); // Errors it('logs an error when it encounters an unknown rule name', function() { processTemplate( [ '{{! template-lint-enable notarule }}', '{{! template-lint-disable fake norme meneither }}', '{{! template-lint-configure nope false }}', ].join('\n') ); expect(messages).toEqual([ 'unrecognized rule name `notarule` in template-lint-enable instruction', 'unrecognized rule name `norme` in template-lint-disable instruction', 'unrecognized rule name `meneither` in template-lint-disable instruction', 'unrecognized rule name `nope` in template-lint-configure instruction', ]); }); it("logs an error when it can't parse a configure instruction's JSON", function() { processTemplate('{{! template-lint-configure fake { not: "json" ] }}'); expect(messages).toEqual([ 'malformed template-lint-configure instruction: `{ not: "json" ]` is not valid JSON', ]); }); it('logs an error when it encounters an unrecognized instruction starting with `template-lint`', function() { processTemplate( [ '{{! template-lint-bloober fake }}', '{{! template-lint- fake }}', '{{! template-lint fake }}', ].join('\n') ); expect(messages).toEqual([ 'unrecognized template-lint instruction: `template-lint-bloober`', 'unrecognized template-lint instruction: `template-lint-`', 'unrecognized template-lint instruction: `template-lint`', ]); }); it('only logs syntax errors once across all rules', function() { runRules( '{{! template-lint-enable notarule }}{{! template-lint-disable meneither }}{{! template-lint-configure norme true }}', [ plugin(buildPlugin({}), 'fake1'), plugin(buildPlugin({}), 'fake2'), plugin(buildPlugin({}), 'fake3'), plugin(buildPlugin({}), 'fake4'), plugin(buildPlugin({}), 'fake5'), ] ); expect(messages).toHaveLength(3); }); }); describe('scopes instructions', function() { let events; function getId(node) { if (node.attributes) { for (let i = 0; i < node.attributes.length; i++) { if (node.attributes[i].name === 'id') { return node.attributes[i].value.chars; } } } return ''; } function addEvent(event, node, plugin) { events.push([event, getId(node), plugin.config]); } function buildPlugin() { class FakeRule extends Rule { log(result) { messages.push(result.source); } visitor() { let pluginContext = this; return { ElementNode: { enter(node) { addEvent('element/enter', node, pluginContext); }, exit(node) { addEvent('element/exit', node, pluginContext); }, keys: { children: { enter(node) { addEvent('element/enter:children', node, pluginContext); }, exit(node) { addEvent('element/exit:children', node, pluginContext); }, }, }, }, MustacheCommentStatement: { enter(node) { addEvent('comment/enter', node, pluginContext); }, exit(node) { addEvent('comment/exit', node, pluginContext); }, }, }; } } return FakeRule; } function processTemplate(template, config) { if (config === undefined) { config = true; } runRules(template, [plugin(buildPlugin(), 'fake', config)]); } beforeEach(function() { messages = []; events = []; }); function expectEvents(data) { let description = data.desc; let template = data.template; let expectedEvents = data.events; let config = data.config; it(description, function() { processTemplate(template, config); expect(events).toEqual(expectedEvents); expect(messages).toEqual([]); }); } expectEvents({ desc: 'handles top-level instructions', template: ['{{! template-lint-configure fake "foo" }}', '<div id="id1"></div>'].join('\n'), events: [ ['comment/enter', '', true], ['comment/exit', '', 'foo'], ['element/enter', 'id1', 'foo'], ['element/enter:children', 'id1', 'foo'], ['element/exit:children', 'id1', 'foo'], ['element/exit', 'id1', 'foo'], ], }); expectEvents({ desc: 'handles element-child instructions', template: [ '<div id="id1">', ' {{! template-lint-configure fake "foo" }}', ' <span id="id2"></span>', '</div>', '<i id="id3"></i>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['comment/enter', '', true], ['comment/exit', '', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ['element/enter', 'id3', true], ['element/enter:children', 'id3', true], ['element/exit:children', 'id3', true], ['element/exit', 'id3', true], ], }); expectEvents({ desc: 'handles niece/nephew instructions', template: [ '<div id="id1">', ' {{! template-lint-configure fake "foo" }}', ' <span id="id2">', ' {{! template-lint-configure fake "bar" }}', ' <b id="id3"/>', ' </span>', '</div>', '<i id="id4"></i>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['comment/enter', '', true], ['comment/exit', '', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'bar'], ['element/enter', 'id3', 'bar'], ['element/enter:children', 'id3', 'bar'], ['element/exit:children', 'id3', 'bar'], ['element/exit', 'id3', 'bar'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ['element/enter', 'id4', true], ['element/enter:children', 'id4', true], ['element/exit:children', 'id4', true], ['element/exit', 'id4', true], ], }); expectEvents({ desc: 'handles sibling instructions', template: [ '<div id="id1">', ' {{! template-lint-configure fake "foo" }}', ' <span id="id2"/>', ' {{! template-lint-configure fake "bar" }}', ' <b id="id3"/>', '</div>', '<i id="id4"></i>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['comment/enter', '', true], ['comment/exit', '', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'bar'], ['element/enter', 'id3', 'bar'], ['element/enter:children', 'id3', 'bar'], ['element/exit:children', 'id3', 'bar'], ['element/exit', 'id3', 'bar'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ['element/enter', 'id4', true], ['element/enter:children', 'id4', true], ['element/exit:children', 'id4', true], ['element/exit', 'id4', true], ], }); expectEvents({ desc: 'handles in-element instructions', template: [ '<div id="id1">', ' <span id="id2" {{! template-lint-configure fake "foo" }}>', ' <i id="id3">', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', true], ['element/enter', 'id3', true], ['element/enter:children', 'id3', true], ['element/enter', 'id4', true], ['element/enter:children', 'id4', true], ['element/exit:children', 'id4', true], ['element/exit', 'id4', true], ['element/exit:children', 'id3', true], ['element/exit', 'id3', true], ['element/exit:children', 'id2', true], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ], }); expectEvents({ desc: 'handles in-element tree instructions', template: [ '<div id="id1">', ' <span id="id2" {{! template-lint-configure-tree fake "foo" }}>', ' <i id="id3">', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['element/enter', 'id3', 'foo'], ['element/enter:children', 'id3', 'foo'], ['element/enter', 'id4', 'foo'], ['element/enter:children', 'id4', 'foo'], ['element/exit:children', 'id4', 'foo'], ['element/exit', 'id4', 'foo'], ['element/exit:children', 'id3', 'foo'], ['element/exit', 'id3', 'foo'], ['element/exit:children', 'id2', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ], }); expectEvents({ desc: 'handles in-element instruction in descendant of in-element tree instruction', template: [ '<div id="id1" {{! template-lint-configure-tree fake "foo" }}>', ' <span id="id2">', ' <i id="id3" {{! template-lint-configure fake "bar" }}>', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', 'foo'], ['element/enter:children', 'id1', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['element/enter', 'id3', 'bar'], ['element/enter:children', 'id3', 'foo'], ['element/enter', 'id4', 'foo'], ['element/enter:children', 'id4', 'foo'], ['element/exit:children', 'id4', 'foo'], ['element/exit', 'id4', 'foo'], ['element/exit:children', 'id3', 'foo'], ['comment/enter', '', 'bar'], ['comment/exit', '', 'bar'], ['element/exit', 'id3', 'bar'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id1', 'foo'], ], }); expectEvents({ desc: 'handles in-element tree instruction in descendant of in-element tree instruction', template: [ '<div id="id1" {{! template-lint-configure-tree fake "foo" }}>', ' <span id="id2">', ' <i id="id3" {{! template-lint-configure-tree fake "bar" }}>', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', 'foo'], ['element/enter:children', 'id1', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['element/enter', 'id3', 'bar'], ['element/enter:children', 'id3', 'bar'], ['element/enter', 'id4', 'bar'], ['element/enter:children', 'id4', 'bar'], ['element/exit:children', 'id4', 'bar'], ['element/exit', 'id4', 'bar'], ['element/exit:children', 'id3', 'bar'], ['comment/enter', '', 'bar'], ['comment/exit', '', 'bar'], ['element/exit', 'id3', 'bar'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id1', 'foo'], ], }); expectEvents({ desc: 'handles descendant instruction of in-element tree instruction', template: [ '<div id="id1" {{! template-lint-configure-tree fake "foo" }}>', ' <span id="id2">', ' {{! template-lint-configure fake "bar" }}', ' <i id="id3">', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', 'foo'], ['element/enter:children', 'id1', 'foo'], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'bar'], ['element/enter', 'id3', 'bar'], ['element/enter:children', 'id3', 'bar'], ['element/enter', 'id4', 'bar'], ['element/enter:children', 'id4', 'bar'], ['element/exit:children', 'id4', 'bar'], ['element/exit', 'id4', 'bar'], ['element/exit:children', 'id3', 'bar'], ['element/exit', 'id3', 'bar'], ['element/exit:children', 'id2', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id1', 'foo'], ], }); expectEvents({ desc: 'enable restores default config', config: 'foo', template: [ '<div id="id1">', ' {{! template-lint-configure fake "bar" }}', ' <span id="id2">', ' {{! template-lint-disable fake }}', ' <i id="id3">', ' {{! template-lint-enable fake }}', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', 'foo'], ['element/enter:children', 'id1', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'bar'], ['element/enter', 'id2', 'bar'], ['element/enter:children', 'id2', 'bar'], ['comment/enter', '', 'bar'], ['comment/exit', '', 'foo'], ['element/enter', 'id4', 'foo'], ['element/enter:children', 'id4', 'foo'], ['element/exit:children', 'id4', 'foo'], ['element/exit', 'id4', 'foo'], ['element/exit:children', 'id2', 'bar'], ['element/exit', 'id2', 'bar'], ['element/exit:children', 'id1', 'foo'], ['element/exit', 'id1', 'foo'], ], }); expectEvents({ desc: 'enabling a disabled-by-default rule actually enables it', config: false, template: [ '<div id="id1">', ' {{! template-lint-enable fake }}', ' <span id="id2"></span>', '</div>', ].join('\n'), events: [ ['comment/exit', '', true], ['element/enter', 'id2', true], ['element/enter:children', 'id2', true], ['element/exit:children', 'id2', true], ['element/exit', 'id2', true], ], }); // Not really a case that makes sense, but just to be sure it doesn't mess // up the config stack expectEvents({ desc: "ensures this pretty silly case doesn't mess up the config stack", template: [ '<div id="id1">', ' <span id="id2" {{! template-lint-configure fake "bar" }} {{! template-lint-configure fake "foo" }}>', ' <i id="id3">', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['element/enter', 'id2', 'foo'], ['element/enter:children', 'id2', true], ['element/enter', 'id3', true], ['element/enter:children', 'id3', true], ['element/enter', 'id4', true], ['element/enter:children', 'id4', true], ['element/exit:children', 'id4', true], ['element/exit', 'id4', true], ['element/exit:children', 'id3', true], ['element/exit', 'id3', true], ['element/exit:children', 'id2', true], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['comment/enter', '', 'foo'], ['comment/exit', '', 'foo'], ['element/exit', 'id2', 'foo'], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ], }); expectEvents({ desc: "it doesn't call a disabled rule's visitor handlers", template: [ '<div id="id1">', ' <span id="id2" {{! template-lint-disable fake }}>', ' <i id="id3">', ' <b id="id4"/>', ' </i>', ' </span>', '</div>', ].join('\n'), events: [ ['element/enter', 'id1', true], ['element/enter:children', 'id1', true], ['element/enter:children', 'id2', true], ['element/enter', 'id3', true], ['element/enter:children', 'id3', true], ['element/enter', 'id4', true], ['element/enter:children', 'id4', true], ['element/exit:children', 'id4', true], ['element/exit', 'id4', true], ['element/exit:children', 'id3', true], ['element/exit', 'id3', true], ['element/exit:children', 'id2', true], ['element/exit:children', 'id1', true], ['element/exit', 'id1', true], ], }); }); });
mit
Proxiweb/react-boilerplate
app/containers/AdminFournisseurInfos/index.js
2401
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { createStructuredSelector } from 'reselect'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { isPristine, change } from 'redux-form'; import Paper from 'material-ui/Paper'; import { makeSelectPending } from 'containers/App/selectors'; import { makeSelectFournisseursIds, makeSelectDomain, } from 'containers/Commande/selectors'; import { loadFournisseurs, loadRelais } from 'containers/Commande/actions'; import InfosFormContainer from './containers/InfosFormContainer'; import classnames from 'classnames'; import styles from './styles.css'; class InfosFournisseur extends Component { static propTypes = { fournisseurs: PropTypes.object.isRequired, donnees: PropTypes.object.isRequired, params: PropTypes.object.isRequired, loadFournisseurs: PropTypes.func.isRequired, pending: PropTypes.bool.isRequired, }; componentDidMount() { const { fournisseurs, params: { fournisseurId }, donnees } = this.props; try { if (!donnees.datas.entities.relais) this.props.loadRelais(); } catch (e) { this.props.loadRelais(); } if (!fournisseurs || !fournisseurs[fournisseurId]) { this.props.loadFournisseurs({ id: fournisseurId, jointures: true }); } } render() { const { fournisseurs, params: { fournisseurId }, donnees, pending, } = this.props; let relais = null; try { relais = donnees.datas.entities.relais; } catch (e) {} return ( <div className="row center-md"> <div className="col-md-8"> <Paper> {fournisseurs && fournisseurs[fournisseurId] && relais && <InfosFormContainer params={this.props.params} fournisseur={fournisseurs[fournisseurId]} relais={relais} />} </Paper> </div> </div> ); } } const mapStateToProps = createStructuredSelector({ pending: makeSelectPending(), fournisseurs: makeSelectFournisseursIds(), donnees: makeSelectDomain(), }); const mapDispatchToProps = dispatch => bindActionCreators( { loadFournisseurs, loadRelais, }, dispatch ); export default connect(mapStateToProps, mapDispatchToProps)(InfosFournisseur);
mit
burflip/IG
_3dhbasicelement.cpp
2421
#include "_3dhbasicelement.h" #include <GL/glut.h> #include <GL/gl.h> #include <vertex.h> using namespace std; bool _3dHBasicElement::chess = false; _3dHBasicElement::_3dHBasicElement() { base_color = _vertex3f(0,1,0); drawing_mode = 0; is_red_when_chess = false; } _3dHBasicElement::_3dHBasicElement(float x, float y, float z) { _3dHBasicElement(); translate(x,y,z); } void _3dHBasicElement::drawPoints() { glPointSize(3); glColor3f(base_color.x,base_color.y,base_color.z); glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); } void _3dHBasicElement::drawWire() { glColor3f(base_color.x,base_color.y,base_color.z); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } void _3dHBasicElement::drawSolid() { glColor3f(base_color.x,base_color.y,base_color.z); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); } void _3dHBasicElement::drawChess() { const _vertex3f color_chess_red(1,0,0); const _vertex3f color_chess_blue(0,0,1); if(is_red_when_chess) { glColor3f(color_chess_red.x,color_chess_red.y,color_chess_red.z); } else { glColor3f(color_chess_blue.x,color_chess_blue.y,color_chess_blue.z); } glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); } void _3dHBasicElement::drawMode() { switch(this->drawing_mode) { case PUNTOS: drawPoints(); break; case ALAMBRE: drawWire(); break; case SOLIDO: drawSolid(); break; case AJEDREZ: drawChess(); break; } } void _3dHBasicElement::draw() { } void _3dHBasicElement::drawCube(float r) { glutSolidCube(r); } void _3dHBasicElement::drawSphere(float r, int slices, int stacks) { glutSolidSphere(r,slices,stacks); } void _3dHBasicElement::drawCilinder(float r, float h, float t, int slices, int stacks) { if(t == 0.0) { t = r; } static GLUquadricObj * qobj = NULL; if(qobj==NULL) qobj= gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluCylinder(qobj,r,h,t,slices,stacks); } void _3dHBasicElement::drawCone(float r, float h, int slices, int stacks) { glutSolidCone(r,h,slices,stacks); } void _3dHBasicElement::scale(float x, float y, float z) { glScalef(x,y,z); } void _3dHBasicElement::translate(float x, float y, float z) { glTranslatef(x,y,z); } void _3dHBasicElement::rotate(float x, float y, float z, float angle) { glRotatef(angle,x,y,z); }
mit
MHSCSClub/MHSAlumDB
chatv3/sendmail.php
5349
<?php ini_set('display_errors', 1); include( '../php/rds.php' ); include("../php/signal.class.php"); include("../php/auth.php"); session_start(); if(!isset($_COOKIE['alumdbauth'])){ header("location: /auth/"); exit; } else { $resp = auth::check_auth($_COOKIE['alumdbauth']); if($resp->isError()){ header("location: /auth/"); exit; } } $conn = new mysqli($dbhost, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $indivUser = $_SESSION['individual']; $sql = "SELECT firstLogin FROM users WHERE username = '$indivUser'"; $result = $conn->query($sql); $firstlog; if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $firstlog = $row["firstLogin"]; } else { echo "0 results"; } if($firstlog == '1'){ header("location: /userIDselection/"); } $sql = "SELECT userid FROM users WHERE username = '$indivUser'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $id = $row["userid"]; } else { echo "0 results"; } $recip = $_GET['alumniid']; $sql = "SELECT username FROM users WHERE userid = $recip"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $username = $row["username"]; } else { echo "0 results"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>MHS Alum DB - Log-in</title> <link rel="shortcut icon" href="/favicon.ico" /> <!-- Bootstrap core CSS --> <link href="../../css/bootstrap.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-sm bg-dark fixed-top navbar-dark"> <div class="navbar-header"> <a class="navbar-brand" href="#"> <img src="/resources/img/logo.jpg" width="250" height="50" alt=""> </a> </div> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Homepage</a> </li> <li class="nav-item"> <a class="nav-link" href="/mainprofile">My Profile</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="/ui" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Directories </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="/ui">Main Directory</a> <a class="dropdown-item" href="/internshipui">Internship Directory</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="/events">Events</a> </li> <li class="nav-item"> <a class="nav-link" href="/chatv3">Chat</a> </li> </ul> <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="/auth/logout">Logout</a> </li> </ul> </div> </nav> <br> <br> <br> <form method="post" class = "form-signin"> <div class="form-group"> <label for="eventtitle">Send to</label> <input type="text" class="form-control" id="sendto" name = "sendto" placeholder="<?php $username?>" readonly> </div> <div class="form-group"> <label for="body">Message body</label> <textarea class="form-control" id="body" name = "body" rows="3"></textarea> </div> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script>window.jQuery || document.write('<script src="../resources/js/jquery-slim.min.js"><\/script>')</script> <script src="../resources/js/popper.min.js"></script> <script src="../resources/js/bootstrap.min.js"></script> </body> </html> <?php //unique value for the conversation $sendto = $_GET['alumniid']; $body = $_POST['body']; $stmt = $conn->prepare("INSERT INTO inbox (fromuser, recipid, body, timereceived) VALUES (?, ?, ?, NOW())"); $stmt->bind_param('sis', $indivUser, $sendto, $body); $stmt->execute(); $stmt->close(); echo "sent"; ?>
mit
spyderinvestments/billpay
src/javascripts/controllers/dashboard.js
1981
'use strict'; //index, navbar controller app.controller('dashboardCtrl', function ($scope, $state, $uibModal, $log, api) { if (!localStorage.getItem("token")) { $state.go('login'); } api.getBills().then( data => $scope.allBills = data.data, err => console.error(err) ); // $scope.allBills = [{ // name: 'Rent', // amount: '4000', // due: '3/1/2016', // repeats: 'monthly', // split: [ // 'Joe', 'Mike', 'Steve' // ], // notes: 'none', // paid: false // }, { // name: 'Internet/Cable', // amount: '200', // due: '3/1/2016', // repeats: 'monthly', // split: [ // 'Joe', 'Mike', 'Steve' // ], // notes: 'none', // paid: false // }, { // name: 'Water', // amount: '400', // due: '3/1/2016', // repeats: 'monthly', // split: [ // 'Joe', 'Mike', 'Steve' // ], // notes: 'none', // paid: false // }, { // name: 'Random', // amount: '60', // due: '3/1/2016', // repeats: 'monthly', // split: [ // 'Joe', 'Mike', 'Steve' // ], // notes: 'none', // paid: false // }, { // name: 'Dinner', // amount: '50', // due: '3/1/2016', // repeats: 'monthly', // split: [ // 'Steph' // ], // notes: 'none', // paid: false // }]; $scope.open = function (size) { function addBillCtrl($scope, $uibModalInstance) { $scope.ok = function () { //TODO: do something // $uibModalInstance.close($scope.selected.item); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; } var modalInstance = $uibModal.open({ animation: true, controller: addBillCtrl, templateUrl: 'myModalContent.html' }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; });
mit
basarevych/webfm
assets/js/browser.js
1764
import './polyfills'; import utf8 from 'utf8'; import { byteDecode } from 'base64util'; import socketIOClient from 'socket.io-client'; import sailsIOClient from 'sails.io.js/sails.io'; import './lib/i18n'; import Breakpoints from 'breakpoints-js'; import React from 'react'; import { hydrate } from 'react-dom'; import createHistory from 'history/createBrowserHistory'; import storeFactory from './store/storeFactory'; import Root from './containers/Root'; import { initApp, screenResize } from './actions/app'; import { locals as styles } from '!!css-loader!sass-loader!../styles/export.scss'; window.io = sailsIOClient(socketIOClient); window.io.sails.autoConnect = true; window.io.sails.reconnection = true; window.io.sails.environment = process.env.NODE_ENV; Breakpoints({ xs: { min: 0, max: parseInt(styles.sm) - 1, }, sm: { min: parseInt(styles.sm), max: parseInt(styles.md) - 1, }, md: { min: parseInt(styles.md), max: parseInt(styles.lg) - 1, }, lg: { min: parseInt(styles.lg), max: parseInt(styles.xl) - 1, }, xl: { min: parseInt(styles.xl), max: Infinity, }, }); const history = createHistory(); const store = storeFactory( history, JSON.parse( byteDecode(window.__STATE__), (key, value) => _.isString(value) ? utf8.decode(value) : value ) ); delete window.__STATE__; window.addEventListener('resize', () => store.dispatch(screenResize())); window.addEventListener('orientationchange', () => store.dispatch(screenResize())); document.addEventListener('DOMContentLoaded', () => { hydrate( <Root store={store} history={history} />, document.getElementById('app') ); document.body.classList.add('loaded'); setTimeout(() => store.dispatch(initApp(history))); });
mit
getguesstimate/guesstimate-app
src/components/lib/FlowGrid/edge.js
3403
import React, {Component} from 'react' import PropTypes from 'prop-types' import angleBetweenPoints from 'angle-between-points' import {getClassName} from 'gEngine/utils' class Rectangle { constructor(locations){ this.left = locations.left this.right = locations.right this.top = locations.top this.bottom = locations.bottom } _xMiddle() { return (this.left + ((this.right - this.left)/2)) } _yMiddle() { return (this.top + ((this.bottom - this.top)/2)) } topPoint(adjust) { return {x: this._xMiddle() + adjust, y: this.top} } bottomPoint(adjust) { return {x: this._xMiddle() + adjust, y: this.bottom} } leftPoint(adjust) { return {x: this.left, y: this._yMiddle() + adjust} } rightPoint(adjust) { return {x: this.right, y: this._yMiddle() + adjust} } angleTo(otherRectangle) { const other = new Rectangle(otherRectangle) const points = [ {x: (this._xMiddle()), y: (-1 * this._yMiddle())}, {x: (other._xMiddle()), y: (-1 * other._yMiddle())} ] return angleBetweenPoints(...points) } positionFrom(otherRectangle) { const angle = this.angleTo(otherRectangle) const RECTANGLE_ANGLE = 30 // this is 45 for a perfect square // if (angle < RECTANGLE_ANGLE) { return 'ON_RIGHT' } else if (angle < (180 - RECTANGLE_ANGLE)) { return 'ON_TOP' } else if (angle < (180 + RECTANGLE_ANGLE)) { return 'ON_LEFT' } else if (angle < (360 - RECTANGLE_ANGLE)) { return 'ON_BOTTOM' } else { return 'ON_RIGHT' } } adjustment(otherRectangle) { return this.shouldAdjust(otherRectangle) ? this.adjustmentAmount(otherRectangle) : 0 } shouldAdjust(otherRectangle) { const angle = this.angleTo(otherRectangle) return (((angle) % 90) < 4) } //this randomness really messes up with rendering, will stop for now adjustmentAmount(otherRectangle) { const ADJUSTMENT_RANGE = 20 return (Math.random() * ADJUSTMENT_RANGE) - (ADJUSTMENT_RANGE / 2) } showPosition(otherRectangle) { const positionFrom = this.positionFrom(otherRectangle) const adjust = 0 switch (positionFrom) { case 'ON_LEFT': return this.leftPoint(adjust) case 'ON_RIGHT': return this.rightPoint(adjust) case 'ON_TOP': return this.topPoint(adjust) case 'ON_BOTTOM': return this.bottomPoint(adjust) } } } export default class Edge extends Component{ displayName: 'Edge' static propTypes = { input: PropTypes.object.isRequired, output: PropTypes.object.isRequired, } shouldComponentUpdate(nextProps) { return (!_.isEqual(this.props !== nextProps)) } _isValidNode({top, left, right, bottom}) { return _.every([top, left, right, bottom], _.isFinite) } render() { const {output, input, hasErrors, pathStatus} = this.props if (!this._isValidNode(input) || !this._isValidNode(output)) { return (false) } let inputPoints = (new Rectangle(input)).showPosition(output) let outputPoints = (new Rectangle(output)).showPosition(input) let points = `M${inputPoints.x},${inputPoints.y} L${outputPoints.x} ,${outputPoints.y}` return ( <path className={getClassName('basic-arrow', pathStatus, hasErrors ? ' hasErrors' : null)} d={points} markerEnd={`url(#MarkerArrow-${hasErrors ? 'hasErrors' : pathStatus})`} fill="none" /> ) } }
mit
ProfilerTeam/Profiler
protected/modules_core/comment/CommentModule.php
2339
<?php /** * CommentModule adds the comment content addon functionalities. * * @package profiler.modules_core.comment * @since 0.5 */ class CommentModule extends HWebModule { public $isCoreModule = true; /** * On content deletion make sure to delete all its comments * * @param CEvent $event */ public static function onContentDelete($event) { foreach (Comment::model()->findAllByAttributes(array('object_model' => get_class($event->sender), 'object_id' => $event->sender->id)) as $comment) { $comment->delete(); } } /** * On User delete, also delete all comments * * @param CEvent $event */ public static function onUserDelete($event) { foreach (Comment::model()->findAllByAttributes(array('created_by' => $event->sender->id)) as $comment) { $comment->delete(); } return true; } /** * On run of integrity check command, validate all module data * * @param CEvent $event */ public static function onIntegrityCheck($event) { $integrityChecker = $event->sender; $integrityChecker->showTestHeadline("Validating Comment Module (" . Comment::model()->count() . " entries)"); // Loop over all comments foreach (Comment::model()->findAll() as $c) { if ($c->source === null) { $integrityChecker->showFix("Deleting comment id " . $c->id . " without existing target!"); if (!$integrityChecker->simulate) $c->delete(); } } } /** * On init of the WallEntryLinksWidget, attach the comment link widget. * * @param CEvent $event */ public static function onWallEntryLinksInit($event) { $event->sender->addWidget('application.modules_core.comment.widgets.CommentLinkWidget', array('object' => $event->sender->object), array('sortOrder' => 10)); } /** * On init of the WallEntryAddonWidget, attach the comment widget. * * @param CEvent $event */ public static function onWallEntryAddonInit($event) { $event->sender->addWidget('application.modules_core.comment.widgets.CommentsWidget', array('object' => $event->sender->object), array('sortOrder' => 20)); } }
mit
p404/elblog
spec/generators/elblog/views_generator_spec.rb
895
require 'rails_helper' require 'generators/elblog/views_generator' require "generator_spec" RSpec.describe Elblog::Generators::ViewsGenerator, :type => :generator do destination File.expand_path("../../../tmp", __FILE__) before :context do run_generator end after :context do rm_r(destination_root + '/app/views/elblog') end describe "Simulate run_generator elblog:views" do specify 'should copy all views elblog' do expect(destination_root).to have_structure { directory 'app' do directory 'views' do directory 'elblog' do directory 'posts' do file '_form.html.erb' file 'edit.html.erb' file 'index.html.erb' file 'new.html.erb' file 'show.html.erb' end end end end } end end end
mit
dakota/cakephp
tests/TestCase/Shell/Helper/TableHelperTest.php
13179
<?php declare(strict_types=1); /** * CakePHP : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP Project * @since 3.1.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Test\TestCase\Shell\Helper; use Cake\Console\ConsoleIo; use Cake\Shell\Helper\TableHelper; use Cake\TestSuite\Stub\ConsoleOutput; use Cake\TestSuite\TestCase; /** * TableHelper test. */ class TableHelperTest extends TestCase { /** * @var \Cake\Console\ConsoleOutput */ public $stub; /** * @var \Cake\Console\ConsoleIo */ public $io; /** * @var \Cake\Shell\Helper\TableHelper */ public $helper; /** * setUp method * * @return void */ public function setUp(): void { parent::setUp(); $this->stub = new ConsoleOutput(); $this->io = new ConsoleIo($this->stub); $this->helper = new TableHelper($this->io); } /** * Test output * * @return void */ public function testOutputDefaultOutput() { $data = [ ['Header 1', 'Header', 'Long Header'], ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with inconsistent keys. * * When outputting entities or other structured data, * headers shouldn't need to have the same keys as it is * annoying to use. * * @return void */ public function testOutputInconsistentKeys() { $data = [ ['Header 1', 'Header', 'Long Header'], ['a' => 'short', 'b' => 'Longish thing', 'c' => 'short'], ['c' => 'Longer thing', 'a' => 'short', 'b' => 'Longest Value'], ]; $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test that output works when data contains just empty strings. * * @return void */ public function testOutputEmptyStrings() { $data = [ ['Header 1', 'Header', 'Empty'], ['short', 'Longish thing', ''], ['Longer thing', 'short', ''], ]; $this->helper->output($data); $expected = [ '+--------------+---------------+-------+', '| <info>Header 1</info> | <info>Header</info> | <info>Empty</info> |', '+--------------+---------------+-------+', '| short | Longish thing | |', '| Longer thing | short | |', '+--------------+---------------+-------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test that output works when data contains nulls. */ public function testNullValues() { $data = [ ['Header 1', 'Header', 'Empty'], ['short', 'Longish thing', null], ['Longer thing', 'short', null], ]; $this->helper->output($data); $expected = [ '+--------------+---------------+-------+', '| <info>Header 1</info> | <info>Header</info> | <info>Empty</info> |', '+--------------+---------------+-------+', '| short | Longish thing | |', '| Longer thing | short | |', '+--------------+---------------+-------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with multi-byte characters * * @return void */ public function testOutputUtf8() { $data = [ ['Header 1', 'Head', 'Long Header'], ['short', 'ÄÄÄÜÜÜ', 'short'], ['Longer thing', 'longerish', 'Longest Value'], ]; $this->helper->output($data); $expected = [ '+--------------+-----------+---------------+', '| <info>Header 1</info> | <info>Head</info> | <info>Long Header</info> |', '+--------------+-----------+---------------+', '| short | ÄÄÄÜÜÜ | short |', '| Longer thing | longerish | Longest Value |', '+--------------+-----------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with multi-byte characters * * @return void */ public function testOutputFullwidth() { $data = [ ['Header 1', 'Head', 'Long Header'], ['short', '竜頭蛇尾', 'short'], ['Longer thing', 'longerish', 'Longest Value'], ]; $this->helper->output($data); $expected = [ '+--------------+-----------+---------------+', '| <info>Header 1</info> | <info>Head</info> | <info>Long Header</info> |', '+--------------+-----------+---------------+', '| short | 竜頭蛇尾 | short |', '| Longer thing | longerish | Longest Value |', '+--------------+-----------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output without headers * * @return void */ public function testOutputWithoutHeaderStyle() { $data = [ ['Header 1', 'Header', 'Long Header'], ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->setConfig(['headerStyle' => false]); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| Header 1 | Header | Long Header |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with different header style * * @return void */ public function testOutputWithDifferentHeaderStyle() { $data = [ ['Header 1', 'Header', 'Long Header'], ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->setConfig(['headerStyle' => 'error']); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| <error>Header 1</error> | <error>Header</error> | <error>Long Header</error> |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output without table headers * * @return void */ public function testOutputWithoutHeaders() { $data = [ ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->setConfig(['headers' => false]); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| short | Longish thing | short |', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with formatted cells * * @return void */ public function testOutputWithFormattedCells() { $data = [ ['short', 'Longish thing', '<info>short</info>'], ['Longer thing', 'short', '<warning>Longest</warning> <error>Value</error>'], ]; $this->helper->setConfig(['headers' => false]); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| short | Longish thing | <info>short</info> |', '| Longer thing | short | <warning>Longest</warning> <error>Value</error> |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with row separator * * @return void */ public function testOutputWithRowSeparator() { $data = [ ['Header 1', 'Header', 'Long Header'], ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->setConfig(['rowSeparator' => true]); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '+--------------+---------------+---------------+', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output with row separator and no headers * * @return void */ public function testOutputWithRowSeparatorAndHeaders() { $data = [ ['Header 1', 'Header', 'Long Header'], ['short', 'Longish thing', 'short'], ['Longer thing', 'short', 'Longest Value'], ]; $this->helper->setConfig(['rowSeparator' => true]); $this->helper->output($data); $expected = [ '+--------------+---------------+---------------+', '| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |', '+--------------+---------------+---------------+', '| short | Longish thing | short |', '+--------------+---------------+---------------+', '| Longer thing | short | Longest Value |', '+--------------+---------------+---------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test output when there is no data. */ public function testOutputWithNoData() { $this->helper->output([]); $this->assertEquals([], $this->stub->messages()); } /** * Test output with a header but no data. */ public function testOutputWithHeaderAndNoData() { $data = [ ['Header 1', 'Header', 'Long Header'], ]; $this->helper->output($data); $expected = [ '+----------+--------+-------------+', '| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |', '+----------+--------+-------------+', ]; $this->assertEquals($expected, $this->stub->messages()); } /** * Test no data when headers are disabled. */ public function testOutputHeaderDisabledNoData() { $this->helper->setConfig(['header' => false]); $this->helper->output([]); $this->assertEquals([], $this->stub->messages()); } }
mit
ccgus/jstalk
jscocoa/Tests/7 split call.js
1506
// Split call disabled by default since ObjJ syntax var useSplitCall = __jsc__.useSplitCall __jsc__.useSplitCall = true // JSCocoaController.sharedController.evalJSFile(NSBundle.mainBundle.bundlePath + '/Contents/Resources/class.js') // Define a new class var newClass = JSCocoaController.createClass_parentClass("SplitCallTester", "NSObject") // // Test bool // var encoding = '*' var encodingName = reverseEncodings[encoding] var fn = new Function('a', 'b', 'c', 'return a+b+c') var fnName = 'performSomeTest:withObject:andObject:' var fnEncoding = objc_encoding.apply(null, [encodingName, encodingName, encodingName, encodingName]); // JSCocoaController.log('Adding method ' + fnName + ' with encoding ' + fnEncoding) JSCocoaController.addInstanceMethod_class_jsFunction_encoding(fnName, SplitCallTester, fn, fnEncoding) var o = SplitCallTester.alloc.init o.release var a = 'hello' var b = 'world' var c = '!' var r1 = o.performSomeTest_withObject_andObject(a, b, c) var r2 = o.performSomeTest_withObject_andObject_(a, b, c) var r3 = o['performSomeTest:withObject:andObject:'](a, b, c) var r4 = o.perform( { someTest : a ,withObject : b ,andObject : c } ) /* JSCocoaController.log('r1=' + r1) JSCocoaController.log('r2=' + r2) JSCocoaController.log('r3=' + r3) JSCocoaController.log('r4=' + r4) */ if (r1 != 'helloworld!' || r1 != r2 || r1 != r3 || r1 != r4) throw 'split call failed' o = null __jsc__.useSplitCall = useSplitCall
mit
ShaneHudson/ShaneHudson.Net
craft/vendor/craftcms/cms/src/web/View.php
53212
<?php /** * @link https://craftcms.com/ * @copyright Copyright (c) Pixel & Tonic, Inc. * @license https://craftcms.github.io/license/ */ namespace craft\web; use Craft; use craft\base\Element; use craft\events\RegisterTemplateRootsEvent; use craft\events\TemplateEvent; use craft\helpers\ElementHelper; use craft\helpers\FileHelper; use craft\helpers\Html as HtmlHelper; use craft\helpers\Json; use craft\helpers\Path; use craft\helpers\StringHelper; use craft\web\twig\Environment; use craft\web\twig\Extension; use craft\web\twig\Template; use craft\web\twig\TemplateLoader; use Twig_ExtensionInterface; use yii\base\Arrayable; use yii\base\Exception; use yii\helpers\Html; use yii\web\AssetBundle as YiiAssetBundle; /** * @inheritdoc * @property Environment $twig the Twig environment * @author Pixel & Tonic, Inc. <support@pixelandtonic.com> * @since 3.0 */ class View extends \yii\web\View { // Constants // ========================================================================= /** * @event RegisterTemplateRootsEvent The event that is triggered when registering CP template roots */ const EVENT_REGISTER_CP_TEMPLATE_ROOTS = 'registerCpTemplateRoots'; /** * @event RegisterTemplateRootsEvent The event that is triggered when registering site template roots */ const EVENT_REGISTER_SITE_TEMPLATE_ROOTS = 'registerSiteTemplateRoots'; /** * @event TemplateEvent The event that is triggered before a template gets rendered */ const EVENT_BEFORE_RENDER_TEMPLATE = 'beforeRenderTemplate'; /** * @event TemplateEvent The event that is triggered after a template gets rendered */ const EVENT_AFTER_RENDER_TEMPLATE = 'afterRenderTemplate'; /** * @event TemplateEvent The event that is triggered before a page template gets rendered */ const EVENT_BEFORE_RENDER_PAGE_TEMPLATE = 'beforeRenderPageTemplate'; /** * @event TemplateEvent The event that is triggered after a page template gets rendered */ const EVENT_AFTER_RENDER_PAGE_TEMPLATE = 'afterRenderPageTemplate'; /** * @const TEMPLATE_MODE_CP */ const TEMPLATE_MODE_CP = 'cp'; /** * @const TEMPLATE_MODE_SITE */ const TEMPLATE_MODE_SITE = 'site'; // Properties // ========================================================================= /** * @var array The sizes that element thumbnails should be rendered in */ private static $_elementThumbSizes = [30, 60, 100, 200]; /** * @var Environment|null The Twig environment instance used for CP templates */ private $_cpTwig; /** * @var Environment|null The Twig environment instance used for site templates */ private $_siteTwig; /** * @var */ private $_twigOptions; /** * @var Twig_ExtensionInterface[] List of Twig extensions registered with [[registerTwigExtension()]] */ private $_twigExtensions = []; /** * @var */ private $_templatePaths; /** * @var */ private $_objectTemplates; /** * @var string|null */ private $_templateMode; /** * @var array|null */ private $_cpTemplateRoots; /** * @var array|null */ private $_siteTemplateRoots; /** * @var array|null */ private $_templateRoots; /** * @var string|null The root path to look for templates in */ private $_templatesPath; /** * @var */ private $_defaultTemplateExtensions; /** * @var */ private $_indexTemplateFilenames; /** * @var */ private $_namespace; /** * @var array */ private $_jsBuffers = []; /** * @var array the registered generic `<script>` code blocks * @see registerScript() */ private $_scripts; /** * @var */ private $_hooks; /** * @var */ private $_textareaMarkers; /** * @var */ private $_renderingTemplate; /** * @var */ private $_isRenderingPageTemplate = false; // Public Methods // ========================================================================= /** * @inheritdoc */ public function init() { parent::init(); // Set the initial template mode based on whether this is a CP or Site request $request = Craft::$app->getRequest(); if ($request->getIsConsoleRequest() || $request->getIsCpRequest()) { $this->setTemplateMode(self::TEMPLATE_MODE_CP); } else { $this->setTemplateMode(self::TEMPLATE_MODE_SITE); } // Register the cp.elements.element hook $this->hook('cp.elements.element', [$this, '_getCpElementHtml']); } /** * Returns the Twig environment. * * @return Environment */ public function getTwig(): Environment { return $this->_templateMode === self::TEMPLATE_MODE_CP ? $this->_cpTwig ?? ($this->_cpTwig = $this->createTwig()) : $this->_siteTwig ?? ($this->_siteTwig = $this->createTwig()); } /** * Creates a new Twig environment. * * @return Environment */ public function createTwig(): Environment { $twig = new Environment(new TemplateLoader($this), $this->_getTwigOptions()); $twig->addExtension(new \Twig_Extension_StringLoader()); $twig->addExtension(new Extension($this, $twig)); if (YII_DEBUG) { $twig->addExtension(new \Twig_Extension_Debug()); } // Add plugin-supplied extensions foreach ($this->_twigExtensions as $extension) { $twig->addExtension($extension); } // Set our timezone /** @var \Twig_Extension_Core $core */ $core = $twig->getExtension(\Twig_Extension_Core::class); $core->setTimezone(Craft::$app->getTimeZone()); return $twig; } /** * Registers a new Twig extension, which will be added on existing environments and queued up for future environments. * * @param Twig_ExtensionInterface $extension */ public function registerTwigExtension(Twig_ExtensionInterface $extension) { $this->_twigExtensions[] = $extension; // Add it to any existing Twig environments if ($this->_cpTwig !== null) { $this->_cpTwig->addExtension($extension); } if ($this->_siteTwig !== null) { $this->_siteTwig->addExtension($extension); } } /** * Returns whether a template is currently being rendered. * * @return bool Whether a template is currently being rendered. */ public function getIsRenderingTemplate(): bool { return $this->_renderingTemplate !== null; } /** * Renders a Twig template. * * @param string $template The name of the template to load * @param array $variables The variables that should be available to the template * @return string the rendering result * @throws \Twig_Error_Loader if the template doesn’t exist * @throws Exception in case of failure * @throws \RuntimeException in case of failure */ public function renderTemplate(string $template, array $variables = []): string { if (!$this->beforeRenderTemplate($template, $variables)) { return ''; } Craft::trace("Rendering template: $template", __METHOD__); // Render and return $renderingTemplate = $this->_renderingTemplate; $this->_renderingTemplate = $template; Craft::beginProfile($template, __METHOD__); try { $output = $this->getTwig()->render($template, $variables); } catch (\RuntimeException $e) { if (!YII_DEBUG) { // Throw a generic exception instead throw new Exception('An error occurred when rendering a template.', 0, $e); } throw $e; } Craft::endProfile($template, __METHOD__); $this->_renderingTemplate = $renderingTemplate; $this->afterRenderTemplate($template, $variables, $output); return $output; } /** * Returns whether a page template is currently being rendered. * * @return bool Whether a page template is currently being rendered. */ public function getIsRenderingPageTemplate(): bool { return $this->_isRenderingPageTemplate; } /** * Renders a Twig template that represents an entire web page. * * @param string $template The name of the template to load * @param array $variables The variables that should be available to the template * @return string the rendering result */ public function renderPageTemplate(string $template, array $variables = []): string { if (!$this->beforeRenderPageTemplate($template, $variables)) { return ''; } ob_start(); ob_implicit_flush(false); $isRenderingPageTemplate = $this->_isRenderingPageTemplate; $this->_isRenderingPageTemplate = true; $this->beginPage(); echo $this->renderTemplate($template, $variables); $this->endPage(); $this->_isRenderingPageTemplate = $isRenderingPageTemplate; $output = ob_get_clean(); $this->afterRenderPageTemplate($template, $variables, $output); return $output; } /** * Renders a macro within a given Twig template. * * @param string $template The name of the template the macro lives in. * @param string $macro The name of the macro. * @param array $args Any arguments that should be passed to the macro. * @return string The rendered macro output. * @throws Exception in case of failure * @throws \RuntimeException in case of failure */ public function renderTemplateMacro(string $template, string $macro, array $args = []): string { $twig = $this->getTwig(); $twigTemplate = $twig->loadTemplate($template); $renderingTemplate = $this->_renderingTemplate; $this->_renderingTemplate = $template; try { $output = call_user_func_array([$twigTemplate, 'macro_'.$macro], $args); } catch (\RuntimeException $e) { if (!YII_DEBUG) { // Throw a generic exception instead throw new Exception('An error occurred when rendering a template.', 0, $e); } throw $e; } $this->_renderingTemplate = $renderingTemplate; return (string)$output; } /** * Renders a template defined in a string. * * @param string $template The source template string. * @param array $variables Any variables that should be available to the template. * @return string The rendered template. */ public function renderString(string $template, array $variables = []): string { $twig = $this->getTwig(); $twig->setDefaultEscaperStrategy(false); $lastRenderingTemplate = $this->_renderingTemplate; $this->_renderingTemplate = 'string:'.$template; $result = $twig->createTemplate($template)->render($variables); $this->_renderingTemplate = $lastRenderingTemplate; $twig->setDefaultEscaperStrategy(); return $result; } /** * Renders a micro template for accessing properties of a single object. * The template will be parsed for {variables} that are delimited by single braces, which will get replaced with * full Twig output tags, i.e. {{ object.variable }}. Regular Twig tags are also supported. * * @param string $template the source template string * @param mixed $object the object that should be passed into the template * @param array $variables any additional variables that should be available to the template * @return string The rendered template. * @throws Exception in case of failure * @throws \RuntimeException in case of failure */ public function renderObjectTemplate(string $template, $object, array $variables = []): string { // If there are no dynamic tags, just return the template if (strpos($template, '{') === false) { return $template; } try { $twig = $this->getTwig(); // Temporarily disable strict variables if it's enabled $strictVariables = $twig->isStrictVariables(); if ($strictVariables) { $twig->disableStrictVariables(); } // Is this the first time we've parsed this template? $cacheKey = md5($template); if (!isset($this->_objectTemplates[$cacheKey])) { // Replace shortcut "{var}"s with "{{object.var}}"s, without affecting normal Twig tags $template = preg_replace('/(?<![\{\%])\{(?![\{\%])/', '{{object.', $template); $template = preg_replace('/(?<![\}\%])\}(?![\}\%])/', '|raw}}', $template); $this->_objectTemplates[$cacheKey] = $twig->createTemplate($template); } // Get the variables to pass to the template if ($object instanceof Arrayable) { // See if we should be including any of the extra fields $extra = []; foreach ($object->extraFields() as $field => $definition) { if (is_int($field)) { $field = $definition; } if (strpos($template, $field) !== false) { $extra[] = $field; } } $variables = array_merge($object->toArray([], $extra, false), $variables); } $variables['object'] = $object; // Render it! $twig->setDefaultEscaperStrategy(false); $lastRenderingTemplate = $this->_renderingTemplate; $this->_renderingTemplate = 'string:'.$template; /** @var Template $templateObj */ $templateObj = $this->_objectTemplates[$cacheKey]; $output = $templateObj->render($variables); $this->_renderingTemplate = $lastRenderingTemplate; $twig->setDefaultEscaperStrategy(); // Re-enable strict variables if ($strictVariables) { $twig->enableStrictVariables(); } } catch (\RuntimeException $e) { if (!YII_DEBUG) { // Throw a generic exception instead throw new Exception('An error occurred when rendering a template.', 0, $e); } throw $e; } return $output; } /** * Returns whether a template exists. * Internally, this will just call [[resolveTemplate()]] with the given template name, and return whether that * method found anything. * * @param string $name The name of the template. * @return bool Whether the template exists. */ public function doesTemplateExist(string $name): bool { try { return ($this->resolveTemplate($name) !== false); } catch (\Twig_Error_Loader $e) { // _validateTemplateName() han an issue with it return false; } } /** * Finds a template on the file system and returns its path. * All of the following files will be searched for, in this order: * * - TemplateName * - TemplateName.html * - TemplateName.twig * - TemplateName/index.html * - TemplateName/index.twig * * If this is a front-end request, the actual list of file extensions and index filenames are configurable via the * [defaultTemplateExtensions](http://craftcms.com/docs/config-settings#defaultTemplateExtensions) and * [indexTemplateFilenames](http://craftcms.com/docs/config-settings#indexTemplateFilenames) config settings. * * For example if you set the following in config/general.php: * * ```php * 'defaultTemplateExtensions' => ['htm'], * 'indexTemplateFilenames' => ['default'], * ``` * * then the following files would be searched for instead: * * - TemplateName * - TemplateName.htm * - TemplateName/default.htm * * The actual directory that those files will depend on the current [[setTemplateMode()|template mode]] * (probably `templates/` if it’s a front-end site request, and `vendor/craftcms/cms/src/templates/` if it’s a Control * Panel request). * * If this is a front-end site request, a folder named after the current site handle will be checked first. * * - templates/SiteHandle/... * - templates/... * * And finally, if this is a Control Panel request _and_ the template name includes multiple segments _and_ the first * segment of the template name matches a plugin’s handle, then Craft will look for a template named with the * remaining segments within that plugin’s templates/ subfolder. * * To put it all together, here’s where Craft would look for a template named “foo/bar”, depending on the type of * request it is: * * - Front-end site requests: * - templates/SiteHandle/foo/bar * - templates/SiteHandle/foo/bar.html * - templates/SiteHandle/foo/bar.twig * - templates/SiteHandle/foo/bar/index.html * - templates/SiteHandle/foo/bar/index.twig * - templates/foo/bar * - templates/foo/bar.html * - templates/foo/bar.twig * - templates/foo/bar/index.html * - templates/foo/bar/index.twig * - Control Panel requests: * - vendor/craftcms/cms/src/templates/foo/bar * - vendor/craftcms/cms/src/templates/foo/bar.html * - vendor/craftcms/cms/src/templates/foo/bar.twig * - vendor/craftcms/cms/src/templates/foo/bar/index.html * - vendor/craftcms/cms/src/templates/foo/bar/index.twig * - path/to/fooplugin/templates/bar * - path/to/fooplugin/templates/bar.html * - path/to/fooplugin/templates/bar.twig * - path/to/fooplugin/templates/bar/index.html * - path/to/fooplugin/templates/bar/index.twig * * @param string $name The name of the template. * @return string|false The path to the template if it exists, or `false`. */ public function resolveTemplate(string $name) { // Normalize the template name $name = trim(preg_replace('#/{2,}#', '/', str_replace('\\', '/', StringHelper::convertToUtf8($name))), '/'); $key = $this->_templatesPath.':'.$name; // Is this template path already cached? if (isset($this->_templatePaths[$key])) { return $this->_templatePaths[$key]; } // Validate the template name $this->_validateTemplateName($name); // Look for the template in the main templates folder $basePaths = []; // Should we be looking for a localized version of the template? if ($this->_templateMode === self::TEMPLATE_MODE_SITE && Craft::$app->getIsInstalled()) { /** @noinspection PhpUnhandledExceptionInspection */ $sitePath = $this->_templatesPath.DIRECTORY_SEPARATOR.Craft::$app->getSites()->getCurrentSite()->handle; if (is_dir($sitePath)) { $basePaths[] = $sitePath; } } $basePaths[] = $this->_templatesPath; foreach ($basePaths as $basePath) { if (($path = $this->_resolveTemplate($basePath, $name)) !== null) { return $this->_templatePaths[$key] = $path; } } unset($basePaths); // Check any registered template roots if ($this->_templateMode === self::TEMPLATE_MODE_CP) { $roots = $this->getCpTemplateRoots(); } else { $roots = $this->getSiteTemplateRoots(); } if (!empty($roots)) { foreach ($roots as $templateRoot => $basePaths) { /** @var string[] $basePaths */ $templateRootLen = strlen($templateRoot); if (strncasecmp($templateRoot.'/', $name.'/', $templateRootLen + 1) === 0) { $subName = strlen($name) === $templateRootLen ? '' : substr($name, $templateRootLen + 1); foreach ($basePaths as $basePath) { if (($path = $this->_resolveTemplate($basePath, $subName)) !== null) { return $this->_templatePaths[$key] = $path; } } } } } return false; } /** * Returns any registered CP template roots. * * @return array */ public function getCpTemplateRoots(): array { return $this->_getTemplateRoots('cp'); } /** * Returns any registered site template roots. * * @return array */ public function getSiteTemplateRoots(): array { return $this->_getTemplateRoots('site'); } /** * Registers a hi-res CSS code block. * * @param string $css the CSS code block to be registered * @param array $options the HTML attributes for the style tag. * @param string|null $key the key that identifies the CSS code block. If null, it will use * $css as the key. If two CSS code blocks are registered with the same key, the latter * will overwrite the former. * @deprecated in 3.0. Use [[registerCss()]] and type your own media selector. */ public function registerHiResCss(string $css, array $options = [], string $key = null) { Craft::$app->getDeprecator()->log('registerHiResCss', 'craft\\web\\View::registerHiResCss() has been deprecated. Use registerCss() instead, and type your own media selector.'); $css = "@media only screen and (-webkit-min-device-pixel-ratio: 1.5),\n". "only screen and ( -moz-min-device-pixel-ratio: 1.5),\n". "only screen and ( -o-min-device-pixel-ratio: 3/2),\n". "only screen and ( min-device-pixel-ratio: 1.5),\n". "only screen and ( min-resolution: 1.5dppx){\n". $css."\n". '}'; $this->registerCss($css, $options, $key); } /** * @inheritdoc */ public function registerJs($js, $position = self::POS_READY, $key = null) { // Trim any whitespace and ensure it ends with a semicolon. $js = StringHelper::ensureRight(trim($js, " \t\n\r\0\x0B"), ';'); parent::registerJs($js, $position, $key); } /** * Starts a JavaScript buffer. * JavaScript buffers work similarly to [output buffers](http://php.net/manual/en/intro.outcontrol.php) in PHP. * Once you’ve started a JavaScript buffer, any JavaScript code included with [[registerJs()]] will be included * in a buffer, and you will have the opportunity to fetch all of that code via [[clearJsBuffer()]] without * having it actually get output to the page. */ public function startJsBuffer() { // Save any currently queued JS into a new buffer, and reset the active JS queue $this->_jsBuffers[] = $this->js; $this->js = []; } /** * Clears and ends a JavaScript buffer, returning whatever JavaScript code was included while the buffer was active. * * @param bool $scriptTag Whether the JavaScript code should be wrapped in a `<script>` tag. Defaults to `true`. * @return string|false The JS code that was included in the active JS buffer, or `false` if there isn’t one */ public function clearJsBuffer(bool $scriptTag = true) { if (empty($this->_jsBuffers)) { return false; } // Combine the JS $js = ''; foreach ([self::POS_HEAD, self::POS_BEGIN, self::POS_END, self::POS_LOAD, self::POS_READY] as $pos) { if (!empty($this->js[$pos])) { $js .= implode("\n", $this->js[$pos])."\n"; } } // Set the active queue to the last one $this->js = array_pop($this->_jsBuffers); if ($scriptTag === true && !empty($js)) { return Html::script($js, ['type' => 'text/javascript']); } return $js; } /** * Registers a generic `<script>` code block. * * @param string $script the generic `<script>` code block to be registered * @param int $position the position at which the generic `<script>` code block should be inserted * in a page. The possible values are: * - [[POS_HEAD]]: in the head section * - [[POS_BEGIN]]: at the beginning of the body section * - [[POS_END]]: at the end of the body section * @param array $options the HTML attributes for the `<script>` tag. * @param string $key the key that identifies the generic `<script>` code block. If null, it will use * $script as the key. If two generic `<script>` code blocks are registered with the same key, the latter * will overwrite the former. */ public function registerScript($script, $position = self::POS_END, $options = [], $key = null) { $key = $key ?: md5($script); $this->_scripts[$position][$key] = Html::script($script, $options); } /** * @inheritdoc */ protected function renderHeadHtml() { $lines = []; if (!empty($this->title)) { $lines[] = '<title>'.Html::encode($this->title).'</title>'; } if (!empty($this->_scripts[self::POS_HEAD])) { $lines[] = implode("\n", $this->_scripts[self::POS_HEAD]); } $html = parent::renderHeadHtml(); return empty($lines) ? $html : implode("\n", $lines).$html; } /** * @inheritdoc */ protected function renderBodyBeginHtml() { $lines = []; if (!empty($this->_scripts[self::POS_BEGIN])) { $lines[] = implode("\n", $this->_scripts[self::POS_BEGIN]); } $html = parent::renderBodyBeginHtml(); return empty($lines) ? $html : implode("\n", $lines).$html; } /** * @inheritdoc */ protected function renderBodyEndHtml($ajaxMode) { $lines = []; if (!empty($this->_scripts[self::POS_END])) { $lines[] = implode("\n", $this->_scripts[self::POS_END]); } $html = parent::renderBodyEndHtml($ajaxMode); return empty($lines) ? $html : implode("\n", $lines).$html; } /** * @inheritdoc */ public function endBody() { $this->registerAssetFlashes(); parent::endBody(); } /** * Returns the content to be inserted in the head section. * This includes: * - Meta tags registered using [[registerMetaTag()]] * - Link tags registered with [[registerLinkTag()]] * - CSS code registered with [[registerCss()]] * - CSS files registered with [[registerCssFile()]] * - JS code registered with [[registerJs()]] with the position set to [[POS_HEAD]] * - JS files registered with [[registerJsFile()]] with the position set to [[POS_HEAD]] * * @param bool $clear Whether the content should be cleared from the queue (default is true) * @return string the rendered content */ public function getHeadHtml(bool $clear = true): string { // Register any asset bundles $this->registerAllAssetFiles(); $html = $this->renderHeadHtml(); if ($clear === true) { $this->metaTags = []; $this->linkTags = []; $this->css = []; $this->cssFiles = []; unset($this->jsFiles[self::POS_HEAD], $this->js[self::POS_HEAD]); } return $html; } /** * Returns the content to be inserted at the end of the body section. * This includes: * - JS code registered with [[registerJs()]] with the position set to [[POS_BEGIN]], [[POS_END]], [[POS_READY]], or [[POS_LOAD]] * - JS files registered with [[registerJsFile()]] with the position set to [[POS_BEGIN]] or [[POS_END]] * * @param bool $clear Whether the content should be cleared from the queue (default is true) * @return string the rendered content */ public function getBodyHtml(bool $clear = true): string { // Register any asset bundles $this->registerAllAssetFiles(); // Get the rendered body begin+end HTML $html = $this->renderBodyBeginHtml(). $this->renderBodyEndHtml(true); // Clear out the queued up files if ($clear === true) { unset( $this->jsFiles[self::POS_BEGIN], $this->jsFiles[self::POS_END], $this->js[self::POS_BEGIN], $this->js[self::POS_END], $this->js[self::POS_READY], $this->js[self::POS_LOAD] ); } return $html; } /** * Registers any asset bundles and JS code that were queued-up in the session flash data. * * @throws Exception if any of the registered asset bundles are not actually asset bundles */ protected function registerAssetFlashes() { $session = Craft::$app->getSession(); if ($session->getIsActive()) { foreach ($session->getAssetBundleFlashes(true) as $name => $position) { if (!is_subclass_of($name, YiiAssetBundle::class)) { throw new Exception("$name is not an asset bundle"); } $this->registerAssetBundle($name, $position); } foreach ($session->getJsFlashes(true) as list($js, $position, $key)) { $this->registerJs($js, $position, $key); } } } /** * Registers all files provided by all registered asset bundles, including depending bundles files. * Removes a bundle from [[assetBundles]] once files are registered. */ protected function registerAllAssetFiles() { foreach ($this->assetBundles as $bundleName => $bundle) { $this->registerAssetFiles($bundleName); } } /** * Translates messages for a given translation category, so they will be * available for `Craft.t()` calls in the Control Panel. * Note this should always be called *before* any JavaScript is registered * that will need to use the translations, unless the JavaScript is * registered at [[self::POS_READY]]. * * @param string $category The category the messages are in * @param string[] $messages The messages to be translated */ public function registerTranslations(string $category, array $messages) { $jsCategory = Json::encode($category); $js = ''; foreach ($messages as $message) { $translation = Craft::t($category, $message); if ($translation !== $message) { $jsMessage = Json::encode($message); $jsTranslation = Json::encode($translation); $js .= ($js !== '' ? "\n" : '')."Craft.translations[{$jsCategory}][{$jsMessage}] = {$jsTranslation};"; } } if ($js === '') { return; } $js = <<<JS if (typeof Craft.translations[{$jsCategory}] === 'undefined') { Craft.translations[{$jsCategory}] = {}; } {$js} JS; $this->registerJs($js, self::POS_BEGIN); } /** * Returns the active namespace. * This is the default namespaces that will be used when [[namespaceInputs()]], [[namespaceInputName()]], * and [[namespaceInputId()]] are called, if their $namespace arguments are null. * * @return string|null The namespace. */ public function getNamespace() { return $this->_namespace; } /** * Sets the active namespace. * This is the default namespaces that will be used when [[namespaceInputs()]], [[namespaceInputName()]], * and [[namespaceInputId()]] are called, if their|null $namespace arguments are null. * * @param string|null $namespace The new namespace. Set to null to remove the namespace. */ public function setNamespace(string $namespace = null) { $this->_namespace = $namespace; } /** * Returns the current template mode (either 'site' or 'cp'). * * @return string Either 'site' or 'cp'. */ public function getTemplateMode(): string { return $this->_templateMode; } /** * Sets the current template mode. * The template mode defines: * - the base path that templates should be looked for in * - the default template file extensions that should be automatically added when looking for templates * - the "index" template filenames that sholud be checked when looking for templates * * @param string $templateMode Either 'site' or 'cp' * @throws Exception if $templateMode is invalid */ public function setTemplateMode(string $templateMode) { // Validate if (!in_array($templateMode, [ self::TEMPLATE_MODE_CP, self::TEMPLATE_MODE_SITE ], true) ) { throw new Exception('"'.$templateMode.'" is not a valid template mode'); } // Set the new template mode $this->_templateMode = $templateMode; // Update everything if ($templateMode == self::TEMPLATE_MODE_CP) { $this->setTemplatesPath(Craft::$app->getPath()->getCpTemplatesPath()); $this->_defaultTemplateExtensions = ['html', 'twig']; $this->_indexTemplateFilenames = ['index']; } else { $this->setTemplatesPath(Craft::$app->getPath()->getSiteTemplatesPath()); $generalConfig = Craft::$app->getConfig()->getGeneral(); $this->_defaultTemplateExtensions = $generalConfig->defaultTemplateExtensions; $this->_indexTemplateFilenames = $generalConfig->indexTemplateFilenames; } } /** * Returns the base path that templates should be found in. * * @return string */ public function getTemplatesPath(): string { return $this->_templatesPath; } /** * Sets the base path that templates should be found in. * * @param string $templatesPath */ public function setTemplatesPath(string $templatesPath) { $this->_templatesPath = rtrim($templatesPath, '/\\'); } /** * Renames HTML input names so they belong to a namespace. * This method will go through the passed-in $html looking for `name=` attributes, and renaming their values such * that they will live within the passed-in $namespace (or the [[getNamespace()|active namespace]]). * By default, any `id=`, `for=`, `list=`, `data-target=`, `data-reverse-target=`, and `data-target-prefix=` * attributes will get namespaced as well, by prepending the namespace and a dash to their values. * For example, the following HTML: * * ```html * <label for="title">Title</label> * <input type="text" name="title" id="title"> * ``` * * would become this, if it were namespaced with “foo”: * * ```html * <label for="foo-title">Title</label> * <input type="text" name="foo[title]" id="foo-title"> * ``` * * Attributes that are already namespaced will get double-namespaced. For example, the following HTML: * * ```html * <label for="bar-title">Title</label> * <input type="text" name="bar[title]" id="title"> * ``` * * would become: * * ```html * <label for="foo-bar-title">Title</label> * <input type="text" name="foo[bar][title]" id="foo-bar-title"> * ``` * * @param string $html The template with the inputs. * @param string|null $namespace The namespace. Defaults to the [[getNamespace()|active namespace]]. * @param bool $otherAttributes Whether id=, for=, etc., should also be namespaced. Defaults to `true`. * @return string The HTML with namespaced input names. */ public function namespaceInputs(string $html, string $namespace = null, bool $otherAttributes = true): string { if ($html === '') { return ''; } if ($namespace === null) { $namespace = $this->getNamespace(); } if ($namespace !== null) { // Protect the textarea content $this->_textareaMarkers = []; $html = preg_replace_callback('/(<textarea\b[^>]*>)(.*?)(<\/textarea>)/is', [$this, '_createTextareaMarker'], $html); // name= attributes $html = preg_replace('/(?<![\w\-])(name=(\'|"))([^\'"\[\]]+)([^\'"]*)\2/i', '$1'.$namespace.'[$3]$4$2', $html); // id= and for= attributes if ($otherAttributes) { $idNamespace = $this->formatInputId($namespace); $html = preg_replace('/(?<![\w\-])((id|for|list|aria\-labelledby|data\-target|data\-reverse\-target|data\-target\-prefix)=(\'|")#?)([^\.\'"][^\'"]*)?\3/i', '$1'.$idNamespace.'-$4$3', $html); } // Bring back the textarea content $html = str_replace(array_keys($this->_textareaMarkers), array_values($this->_textareaMarkers), $html); } return $html; } /** * Namespaces an input name. * This method applies the same namespacing treatment that [[namespaceInputs()]] does to `name=` attributes, * but only to a single value, which is passed directly into this method. * * @param string $inputName The input name that should be namespaced. * @param string|null $namespace The namespace. Defaults to the [[getNamespace()|active namespace]]. * @return string The namespaced input name. */ public function namespaceInputName(string $inputName, string $namespace = null): string { if ($namespace === null) { $namespace = $this->getNamespace(); } if ($namespace !== null) { $inputName = preg_replace('/([^\'"\[\]]+)([^\'"]*)/', $namespace.'[$1]$2', $inputName); } return $inputName; } /** * Namespaces an input ID. * This method applies the same namespacing treatment that [[namespaceInputs()]] does to `id=` attributes, * but only to a single value, which is passed directly into this method. * * @param string $inputId The input ID that should be namespaced. * @param string|null $namespace The namespace. Defaults to the [[getNamespace()|active namespace]]. * @return string The namespaced input ID. */ public function namespaceInputId(string $inputId, string $namespace = null): string { if ($namespace === null) { $namespace = $this->getNamespace(); } if ($namespace !== null) { $inputId = $this->formatInputId($namespace).'-'.$inputId; } return $inputId; } /** * Formats an ID out of an input name. * This method takes a given input name and returns a valid ID based on it. * For example, if given the following input name: * foo[bar][title] * the following ID would be returned: * foo-bar-title * * @param string $inputName The input name. * @return string The input ID. */ public function formatInputId(string $inputName): string { return rtrim(preg_replace('/[\[\]\\\]+/', '-', $inputName), '-'); } /** * Queues up a method to be called by a given template hook. * For example, if you place this in your plugin’s [[BasePlugin::init()|init()]] method: * * ```php * Craft::$app->view->hook('myAwesomeHook', function(&$context) { * $context['foo'] = 'bar'; * return 'Hey!'; * }); * ``` * * you would then be able to add this to any template: * * ```twig * {% hook "myAwesomeHook" %} * ``` * * When the hook tag gets invoked, your template hook function will get called. The $context argument will be the * current Twig context array, which you’re free to manipulate. Any changes you make to it will be available to the * template following the tag. Whatever your template hook function returns will be output in place of the tag in * the template as well. * * @param string $hook The hook name. * @param callback $method The callback function. */ public function hook(string $hook, $method) { $this->_hooks[$hook][] = $method; } /** * Invokes a template hook. * This is called by [[HookNode|<code>{% hook %}</code> tags]]. * * @param string $hook The hook name. * @param array &$context The current template context. * @return string Whatever the hooks returned. */ public function invokeHook(string $hook, array &$context): string { $return = ''; if (isset($this->_hooks[$hook])) { foreach ($this->_hooks[$hook] as $method) { $return .= $method($context); } } return $return; } // Events // ------------------------------------------------------------------------- /** * Performs actions before a template is rendered. * * @param mixed $template The name of the template to render * @param array &$variables The variables that should be available to the template * @return bool Whether the template should be rendered */ public function beforeRenderTemplate(string $template, array &$variables): bool { // Fire a 'beforeRenderTemplate' event $event = new TemplateEvent([ 'template' => $template, 'variables' => $variables, ]); $this->trigger(self::EVENT_BEFORE_RENDER_TEMPLATE, $event); $variables = $event->variables; return $event->isValid; } /** * Performs actions after a template is rendered. * * @param mixed $template The name of the template that was rendered * @param array $variables The variables that were available to the template * @param string $output The template’s rendering result */ public function afterRenderTemplate(string $template, array $variables, string &$output) { // Fire an 'afterRenderTemplate' event if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER_TEMPLATE)) { $event = new TemplateEvent([ 'template' => $template, 'variables' => $variables, 'output' => $output, ]); $this->trigger(self::EVENT_AFTER_RENDER_TEMPLATE, $event); $output = $event->output; } } /** * Performs actions before a page template is rendered. * * @param mixed $template The name of the template to render * @param array &$variables The variables that should be available to the template * @return bool Whether the template should be rendered */ public function beforeRenderPageTemplate(string $template, array &$variables): bool { // Fire a 'beforeRenderPageTemplate' event $event = new TemplateEvent([ 'template' => $template, 'variables' => &$variables, ]); $this->trigger(self::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, $event); $variables = $event->variables; return $event->isValid; } /** * Performs actions after a page template is rendered. * * @param mixed $template The name of the template that was rendered * @param array $variables The variables that were available to the template * @param string $output The template’s rendering result */ public function afterRenderPageTemplate(string $template, array $variables, string &$output) { // Fire an 'afterRenderPageTemplate' event if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER_PAGE_TEMPLATE)) { $event = new TemplateEvent([ 'template' => $template, 'variables' => $variables, 'output' => $output, ]); $this->trigger(self::EVENT_AFTER_RENDER_PAGE_TEMPLATE, $event); $output = $event->output; } } // Private Methods // ========================================================================= /** * Ensures that a template name isn't null, and that it doesn't lead outside the template folder. Borrowed from * [[Twig_Loader_Filesystem]]. * * @param string $name * @throws \Twig_Error_Loader */ private function _validateTemplateName(string $name) { if (StringHelper::contains($name, "\0")) { throw new \Twig_Error_Loader(Craft::t('app', 'A template name cannot contain NUL bytes.')); } if (Path::ensurePathIsContained($name) === false) { Craft::error('Someone tried to load a template outside the templates folder: '. $name); throw new \Twig_Error_Loader(Craft::t('app', 'Looks like you are trying to load a template outside the template folder.')); } } /** * Searches for a template files, and returns the first match if there is one. * * @param string $basePath The base path to be looking in. * @param string $name The name of the template to be looking for. * @return string|null The matching file path, or `null`. */ private function _resolveTemplate(string $basePath, string $name) { // Normalize the path and name $basePath = FileHelper::normalizePath($basePath); $name = trim(FileHelper::normalizePath($name), '/'); // $name could be an empty string (e.g. to load the homepage template) if ($name) { // Maybe $name is already the full file path $testPath = $basePath.DIRECTORY_SEPARATOR.$name; if (is_file($testPath)) { return $testPath; } foreach ($this->_defaultTemplateExtensions as $extension) { $testPath = $basePath.DIRECTORY_SEPARATOR.$name.'.'.$extension; if (is_file($testPath)) { return $testPath; } } } foreach ($this->_indexTemplateFilenames as $filename) { foreach ($this->_defaultTemplateExtensions as $extension) { $testPath = $basePath.($name ? DIRECTORY_SEPARATOR.$name : '').DIRECTORY_SEPARATOR.$filename.'.'.$extension; if (is_file($testPath)) { return $testPath; } } } return null; } /** * Returns the Twig environment options * * @return array */ private function _getTwigOptions(): array { if ($this->_twigOptions !== null) { return $this->_twigOptions; } $this->_twigOptions = [ 'base_template_class' => Template::class, // See: https://github.com/twigphp/Twig/issues/1951 'cache' => Craft::$app->getPath()->getCompiledTemplatesPath(), 'auto_reload' => true, 'charset' => Craft::$app->charset, ]; if (YII_DEBUG) { $this->_twigOptions['debug'] = true; $this->_twigOptions['strict_variables'] = true; } return $this->_twigOptions; } /** * Returns any registered template roots. * * @param string $which 'cp' or 'site' * @return array */ private function _getTemplateRoots(string $which): array { if (isset($this->_templateRoots[$which])) { return $this->_templateRoots[$which]; } if ($which === 'cp') { $name = self::EVENT_REGISTER_CP_TEMPLATE_ROOTS; } else { $name = self::EVENT_REGISTER_SITE_TEMPLATE_ROOTS; } $event = new RegisterTemplateRootsEvent(); $this->trigger($name, $event); $roots = []; foreach ($event->roots as $templatePath => $dir) { $templatePath = strtolower(trim($templatePath, '/')); $roots[$templatePath][] = $dir; } // Longest (most specific) first krsort($roots, SORT_STRING); return $this->_templateRoots[$which] = $roots; } /** * Replaces textarea contents with a marker. * * @param array $matches * @return string */ private function _createTextareaMarker(array $matches): string { $marker = '{marker:'.StringHelper::randomString().'}'; $this->_textareaMarkers[$marker] = $matches[2]; return $matches[1].$marker.$matches[3]; } /** * Returns the HTML for an element in the CP. * * @param array &$context * @return string|null */ private function _getCpElementHtml(array &$context) { if (!isset($context['element'])) { return null; } /** @var Element $element */ $element = $context['element']; if (!isset($context['context'])) { $context['context'] = 'index'; } // How big is the element going to be? if (isset($context['size']) && ($context['size'] === 'small' || $context['size'] === 'large')) { $elementSize = $context['size']; } else if (isset($context['viewMode']) && $context['viewMode'] === 'thumbs') { $elementSize = 'large'; } else { $elementSize = 'small'; } // Create the thumb/icon image, if there is one // --------------------------------------------------------------------- $thumbUrl = $element->getThumbUrl(self::$_elementThumbSizes[0]); if ($thumbUrl !== null) { $srcsets = []; foreach (self::$_elementThumbSizes as $i => $size) { if ($i == 0) { $srcset = $thumbUrl; } else { $srcset = $element->getThumbUrl($size); } $srcsets[] = $srcset.' '.$size.'w'; } $imgHtml = '<div class="elementthumb">'. '<img '. 'sizes="'.($elementSize === 'small' ? self::$_elementThumbSizes[0] : self::$_elementThumbSizes[2]).'px" '. 'srcset="'.implode(', ', $srcsets).'" '. 'alt="">'. '</div> '; } else { $imgHtml = ''; } $htmlAttributes = array_merge( $element->getHtmlAttributes($context['context']), [ 'class' => 'element '.$elementSize, 'data-type' => get_class($element), 'data-id' => $element->id, 'data-site-id' => $element->siteId, 'data-status' => $element->getStatus(), 'data-label' => (string)$element, 'data-url' => $element->getUrl(), 'data-level' => $element->level, ]); if ($context['context'] === 'field') { $htmlAttributes['class'] .= ' removable'; } if ($element::hasStatuses()) { $htmlAttributes['class'] .= ' hasstatus'; } if ($thumbUrl !== null) { $htmlAttributes['class'] .= ' hasthumb'; } $html = '<div'; foreach ($htmlAttributes as $attribute => $value) { $html .= ' '.$attribute.($value !== null ? '="'.HtmlHelper::encode($value).'"' : ''); } if (ElementHelper::isElementEditable($element)) { $html .= ' data-editable'; } $html .= '>'; if ($context['context'] === 'field' && isset($context['name'])) { $html .= '<input type="hidden" name="'.$context['name'].'[]" value="'.$element->id.'">'; $html .= '<a class="delete icon" title="'.Craft::t('app', 'Remove').'"></a> '; } if ($element::hasStatuses()) { $status = $element->getStatus(); $statusClasses = $status.' '.($element::statuses()[$status]['color'] ?? ''); $html .= '<span class="status '.$statusClasses.'"></span>'; } $html .= $imgHtml; $html .= '<div class="label">'; $html .= '<span class="title">'; $label = HtmlHelper::encode($element); if ($context['context'] === 'index' && ($cpEditUrl = $element->getCpEditUrl())) { $cpEditUrl = HtmlHelper::encode($cpEditUrl); $html .= "<a href=\"{$cpEditUrl}\">{$label}</a>"; } else { $html .= $label; } $html .= '</span></div></div>'; return $html; } }
mit
VeryGame/XUE
xue/src/main/java/org/rschrage/util/math/CoordinateType.java
100
package org.rschrage.util.math; /** * Coordinate type */ public enum CoordinateType { X, Y }
mit
tamasflamich/nmemory
Main/Source/NMemory.Shared/Tables/ITable`2.cs
3771
// ----------------------------------------------------------------------------------- // <copyright file="ITable`2.cs" company="NMemory Team"> // Copyright (C) NMemory Team // // 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. // </copyright> // ----------------------------------------------------------------------------------- namespace NMemory.Tables { using NMemory.Indexes; using NMemory.Transactions; /// <summary> /// Defines an interface for database tables. /// </summary> /// <typeparam name="TEntity"> /// The type of the entities contained by the table. /// </typeparam> /// <typeparam name="TPrimaryKey"> /// The type of the primary key of the entities. /// </typeparam> public interface ITable<TEntity, TPrimaryKey> : ITable<TEntity> where TEntity : class { /// <summary> /// Gets the primary key index of the table. /// </summary> new IUniqueIndex<TEntity, TPrimaryKey> PrimaryKeyIndex { get; } /// <summary> /// Updates the properties of the specified entity contained by the table. /// </summary> /// <param name="key"> /// The primary key of the entity to be updated. /// </param> /// <param name="entity"> /// An entity that contains the new property values. /// </param> void Update(TPrimaryKey key, TEntity entity); /// <summary> /// Updates the properties of the specified entity contained by the table. /// </summary> /// <param name="key"> /// The primary key of the entity to be updated. /// </param> /// <param name="entity"> /// An entity that contains the new property values. /// </param> /// <param name="entity"> /// The transaction within which the update operation is executed. /// </param> void Update(TPrimaryKey key, TEntity entity, Transaction transaction); /// <summary> /// Deletes an entity from the table. /// </summary> /// <param name="key"> /// The primary key of the entity to be deleted. /// </param> void Delete(TPrimaryKey key); /// <summary> /// Deletes an entity from the table. /// </summary> /// <param name="key"> /// The primary key of the entity to be deleted. /// </param> /// <param name="entity"> /// The transaction within which the update operation is executed. /// </param> void Delete(TPrimaryKey key, Transaction transaction); } }
mit