code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using AzureFromTheTrenches.Commanding.Abstractions; namespace InMemoryCommanding.Commands { public class CommandWithoutResult : ICommand { public string DoSomething { get; set; } } }
JamesRandall/AccidentalFish.Commanding
Samples/InMemoryCommanding/Commands/CommandWithoutResult.cs
C#
mit
207
/* * Copyright (C) 2020 wea_ondara * * BungeePerms is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BungeePerms is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.alpenblock.bungeeperms; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import net.alpenblock.bungeeperms.platform.Sender; public class TabCompleter { private static final List<Entry> ENTRIES = new ArrayList<>(); static { ENTRIES.add(new Entry("bungeeperms.help",/* */ "/bp help [page]")); ENTRIES.add(new Entry("bungeeperms.reload",/* */ "/bp reload")); ENTRIES.add(new Entry("bungeeperms.debug",/* */ "/bp debug <true|false>")); ENTRIES.add(new Entry("bungeeperms.overview",/* */ "/bp overview")); ENTRIES.add(new Entry("bungeeperms.users",/* */ "/bp users [-c]")); ENTRIES.add(new Entry("bungeeperms.user.info",/* */ "/bp user <user> info [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.delete",/* */ "/bp user <user> delete")); ENTRIES.add(new Entry("bungeeperms.user.display",/* */ "/bp user <user> display [displayname] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.prefix",/* */ "/bp user <user> prefix [prefix] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.suffix",/* */ "/bp user <user> suffix [suffix] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.add",/* */ "/bp user <user> addperm <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.add",/* */ "/bp user <user> addtimedperm <perm> <duration> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.remove",/* */ "/bp user <user> removeperm <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.remove",/* */ "/bp user <user> removetimedperm <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.has",/* */ "/bp user <user> has <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.list",/* */ "/bp user <user> list [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.perms.list",/* */ "/bp user <user> listonly [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.group.add",/* */ "/bp user <user> addgroup <group> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.group.add",/* */ "/bp user <user> addtimedgroup <group> <duration> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.group.remove",/* */ "/bp user <user> removegroup <group> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.group.remove",/* */ "/bp user <user> removetimedgroup <group> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.user.group.set",/* */ "/bp user <user> setgroup <group>")); ENTRIES.add(new Entry("bungeeperms.user.groups",/* */ "/bp user <user> groups")); ENTRIES.add(new Entry("bungeeperms.groups",/* */ "/bp groups")); ENTRIES.add(new Entry("bungeeperms.group.info",/* */ "/bp group <group> info [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.users",/* */ "/bp group <group> users [-c]")); ENTRIES.add(new Entry("bungeeperms.group.create",/* */ "/bp group <group> create")); ENTRIES.add(new Entry("bungeeperms.group.delete",/* */ "/bp group <group> delete")); ENTRIES.add(new Entry("bungeeperms.group.inheritances.add",/* */ "/bp group <group> addinherit <addgroup> [server] [world]]")); ENTRIES.add(new Entry("bungeeperms.group.inheritances.add",/* */ "/bp group <group> addtimedinherit <addgroup> <duration> [server] [world]]")); ENTRIES.add(new Entry("bungeeperms.group.inheritances.remove",/**/ "/bp group <group> removeinherit <removegroup> [server] [world]]")); ENTRIES.add(new Entry("bungeeperms.group.inheritances.remove",/**/ "/bp group <group> removetimedinherit <removegroup> [server] [world]]")); ENTRIES.add(new Entry("bungeeperms.group.rank",/* */ "/bp group <group> rank <newrank>")); ENTRIES.add(new Entry("bungeeperms.group.weight",/* */ "/bp group <group> weight <newweight>")); ENTRIES.add(new Entry("bungeeperms.group.ladder",/* */ "/bp group <group> ladder <newladder>")); ENTRIES.add(new Entry("bungeeperms.group.default",/* */ "/bp group <group> default <true|false>")); ENTRIES.add(new Entry("bungeeperms.group.display",/* */ "/bp group <group> display [displayname] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.prefix",/* */ "/bp group <group> prefix [prefix] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.suffix",/* */ "/bp group <group> suffix [suffix] [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.perms.add",/* */ "/bp group <group> addperm <perm> [server] [world]]")); ENTRIES.add(new Entry("bungeeperms.group.perms.add",/* */ "/bp group <group> addtimedperm <perm> <duration> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.perms.remove",/* */ "/bp group <group> removeperm <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.perms.remove",/* */ "/bp group <group> removetimedperm <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.perms.has",/* */ "/bp group <group> has <perm> [server] [world]")); ENTRIES.add(new Entry("bungeeperms.group.perms.list",/* */ "/bp group <group> list")); ENTRIES.add(new Entry("bungeeperms.group.perms.list",/* */ "/bp group <group> listonly")); ENTRIES.add(new Entry("bungeeperms.promote",/* */ "/bp promote <user> [ladder]")); ENTRIES.add(new Entry("bungeeperms.demote",/* */ "/bp demote <user> [ladder]")); ENTRIES.add(new Entry("bungeeperms.format",/* */ "/bp format")); ENTRIES.add(new Entry("bungeeperms.cleanup",/* */ "/bp cleanup")); ENTRIES.add(new Entry("bungeeperms.migrate",/* */ "/bp migrate <backend> [yaml|mysql]")); ENTRIES.add(new Entry("bungeeperms.migrate",/* */ "/bp migrate <useuuid> [true|false]")); ENTRIES.add(new Entry("bungeeperms.uuid",/* */ "/bp uuid <player|uuid> [-rm]")); } public static List<String> tabComplete(Sender sender, String[] args) { List<Entry> l = sender == null ? ENTRIES : filterbyperm(sender, ENTRIES); // switch (args.length) // { // case 0: // case 1: // break; // } l = filterbyargs(l, args); return makeSuggestions(l, args); } private static List<Entry> filterbyperm(Sender sender, List<Entry> entries) { List<Entry> ret = new ArrayList(); for (Entry e : entries) { if (e.getPermission() == null || BungeePerms.getInstance().getPermissionsChecker().hasPermOrConsoleOnServerInWorld(sender, e.getPermission())) ret.add(e); } return ret; } private static List<Entry> filterbyargs(List<Entry> entries, String[] args) { List<Entry> filtered = new ArrayList(entries); for (int i = 0; i < args.length; i++) { for (int j = 0; j < filtered.size(); j++) { String[] split = filtered.get(j).getTemplate().replaceAll("/bp ?", "").split(" "); if (i >= split.length) //more args then template elements { filtered.remove(j--); continue; } if (split[i].startsWith("<") || split[i].startsWith("[")) //value selector { // String[] options = split[i].replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("<", "").replaceAll(">", "").split("|"); // if (!matchesOption(options, args[i])) // { // filtered.remove(j--); // continue; // } } else //no values selector { if (i + 1 == args.length && !split[i].startsWith(args[i].toLowerCase())) { filtered.remove(j--); continue; } else if (i + 1 < args.length && !split[i].equalsIgnoreCase(args[i])) { filtered.remove(j--); continue; } } } } return filtered; } private static List<String> makeSuggestions(List<Entry> entries, String[] args) { int pos = Math.max(0, args.length - 1); String lastarg = args.length == 0 ? "" : args[pos]; List<String> ret = new ArrayList(); for (int i = 0; i < entries.size(); i++) { String[] split = entries.get(i).getTemplate().replaceAll("/bp ?", "").split(" "); if (pos >= split.length) //for safety continue; if (!split[pos].startsWith("<") && !split[pos].startsWith("[") && !ret.contains(split[pos]) && split[pos].toLowerCase().startsWith(lastarg.toLowerCase())) ret.add(split[pos]); else if (split[pos].startsWith("<") || split[pos].startsWith("[")) { String strip = split[pos].replaceAll("<", "").replaceAll(">", "").replaceAll("\\[", "").replaceAll("\\]", ""); if (strip.equals("group")) { if (BungeePerms.getInstance() != null) //needed for test cases for (Group g : BungeePerms.getInstance().getPermissionsManager().getGroups()) if (!ret.contains(g.getName()) && g.getName().toLowerCase().startsWith(lastarg.toLowerCase())) ret.add(g.getName()); } else if (strip.equals("user")) { if (BungeePerms.getInstance() != null) //needed for test cases for (Sender s : BungeePerms.getInstance().getPlugin().getPlayers()) if (!ret.contains(s.getName()) && s.getName().toLowerCase().startsWith(lastarg.toLowerCase())) ret.add(s.getName()); } else if (strip.equals("-c")) { ret.add("-c"); } } } Collections.sort(ret, String.CASE_INSENSITIVE_ORDER); return ret; } // private static boolean matchesOption(String[] options, String arg) // { // for (String o : options) // { // switch (o) // { // case "": // break; // default: // return false; // } // } // } @AllArgsConstructor @Getter private static class Entry { private final String permission; private final String template; } }
weaondara/BungeePerms
src/main/java/net/alpenblock/bungeeperms/TabCompleter.java
Java
mit
12,243
using EleicaoBrasil.Web.ModelView; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; namespace EleicaoBrasil.Web.Util { public class HttpUtil { public static HttpResponseMessage TrataException(Exception e, HttpRequestMessage request) { ErrorMV errorvm = new ErrorMV() { Message = e.Message }; if (e is EleicaoBrasil.Model.DataExceptions.DataException) return request.CreateResponse<ErrorMV>((HttpStatusCode)422, errorvm); else return request.CreateResponse<ErrorMV>(HttpStatusCode.InternalServerError, errorvm); } } }
Politbook/politbook_server
EleicaoBrasil.Web/Util/HttpUtil.cs
C#
mit
744
require 'model_id/version' require 'model_id/base' module ModelId end
abonec/model_id
lib/model_id.rb
Ruby
mit
71
import {storeFreeze} from "ngrx-store-freeze"; import {localStorageSync} from "ngrx-store-localstorage"; import {combineReducers, StoreModule} from "@ngrx/store"; import {appReducers} from "./shared/store/reducers/app.reducer"; import {AgmCoreModule} from "angular2-google-maps/core"; import {RouterStoreModule} from "@ngrx/router-store"; import {EffectsModule} from "@ngrx/effects"; import {AuthEffectService} from "./shared/store/effects/auth-effects.service"; import {UserEffectService} from "./shared/store/effects/user-effects.service"; import {RVEffectService} from "./shared/store/effects/rv-effects.service"; import {UIEffectService} from "./shared/store/effects/ui-effects.service"; import {StoreDevtoolsModule} from "@ngrx/store-devtools"; import {INITIAL_APP_STATE} from "./shared/store/state/application.state"; import {compose} from "@ngrx/core/compose"; export function myCompose(...args: any[]) { let functions:any = []; for (let _i = 0; _i < args.length; _i++) { functions[_i - 0] = args[_i]; } return function (arg:any) { if (functions.length === 0) { return arg; } let last = functions[functions.length - 1]; let rest = functions.slice(0, -1); return rest.reduceRight(function (composed:any, fn:any) { return fn(composed); }, last(arg)); }; }; export const ngGoogleMapsConf = AgmCoreModule.forRoot({apiKey:'AIzaSyDSA-Sc8yoe_NIGqOwTGoNPiKge0KRK_wo',libraries:['places']}); export const syncedState = ['authState', 'storeData', 'router']; //export function reducers() { return myCompose(storeFreeze, localStorageSync(syncedState, true), combineReducers)(appReducers) } export const storeConf = StoreModule.provideStore(compose(storeFreeze, localStorageSync(syncedState, true), combineReducers)(appReducers), INITIAL_APP_STATE); export const routerStoreConf = RouterStoreModule.connectRouter(); export const authEffectsConf = EffectsModule.run(AuthEffectService); export const userEffectsConf = EffectsModule.run(UserEffectService); export const rvEffectsConf = EffectsModule.run(RVEffectService); export const postEffectsConf = EffectsModule.run(UIEffectService); export const storeDevToolsConf = StoreDevtoolsModule.instrumentOnlyWithExtension();
apollo-utn-frd/apollo
client/src/app/app.exports.ts
TypeScript
mit
2,209
import datetime import requests import numpy as np import pandas as pd import sys # August 3, 2015: Updated the getNipa() method to accomodate possible differences in data availability for series in tables. # Cleaned up and organized the code substantially. class initialize: def __init__(self,apiKey=None): ''' Saves the API key.''' self.apiKey = apiKey # 1. Methods for getting information about the available datasets, parameters, and parameter values. def getDataSetList(self): '''Method returns a list of describing the datasets available through the BEA API. No arguments''' r = requests.get('http://www.bea.gov/api/data?&UserID='+self.apiKey+'&method=GETDATASETLIST&ResultFormat=JSON&') rJson = r.json() lines='Datasets available through the BEA API:\n\n' n=1 dataSetList = [] for element in rJson['BEAAPI']['Results']['Dataset']: if np.mod(n,5)==0: lines = lines+str(n).ljust(4,' ')+element['DatasetName'].ljust(20,' ') +': '+element['DatasetDescription']+'\n\n' dataSetList.append(element['DatasetName']) else: lines = lines+str(n).ljust(4,' ')+element['DatasetName'].ljust(20,' ') +': '+element['DatasetDescription']+'\n' dataSetList.append(element['DatasetName']) n+=1 print(lines) self.dataSets = lines self.dataSetList = dataSetList def getParameterList(self,dataSetName): '''Method returns a list of the parameters for a given dataset. Argument: one of the dataset names returned by getDataSetList().''' r = requests.get('http://www.bea.gov/api/data?&UserID='+self.apiKey+'&method=GETPARAMETERLIST&datasetname='+dataSetName+'&ResultFormat=JSON&') rJson = r.json() lines = 'Parameters for the '+dataSetName+' dataset.\n\n' strWidth = 25 descrWidth = 50 parameterList = [] def splitString(origString, maxLength): splitLines = [] line = '' for word in origString.split(' '): if len(line)+1+len(word)<maxLength: line = line+word+' ' else: splitLines.append(line) line = word+' ' if len(line) != 0: splitLines.append(line) return splitLines for element in rJson['BEAAPI']['Results']['Parameter']: elementKeys = list(element.keys()) lines = lines+'Parameter name'.ljust(strWidth,' ') +' '+element['ParameterName']+'\n' split = splitString(element['ParameterDescription'],descrWidth) for n,line in enumerate(split): if n ==0: lines = lines+'Description'.ljust(strWidth,' ') + ' '+line+'\n' else: lines = lines+' '.ljust(strWidth,' ') + ' '+line+'\n' parameterList.append(element['ParameterName']) if element['ParameterIsRequiredFlag']==0: lines = lines+'Required?'.ljust(strWidth,' ') + ' No'+'\n' else: lines = lines+'Required?'.ljust(strWidth,' ') + ' Yes'+'\n' if 'AllValue' in elementKeys: if element['AllValue']=='': lines = lines+'\"All\" Value'.ljust(strWidth,' ') + ' N/A'+'\n' else: lines = lines+'\"All\" Value'.ljust(strWidth,' ') +' '+element['AllValue']+'\n' # if element['MultipleAcceptedFlag']==0: # lines = lines+'Multiple (list) accepted?'.ljust(strWidth,' ') + ' No'+'\n' # else: # lines = lines+'Multiple (list) accepted?'.ljust(strWidth,' ') + ' Yes'+'\n' lines = lines+'Data type'.ljust(strWidth,' ') + ' '+element['ParameterDataType']+'\n' if 'ParameterDefaultValue' in elementKeys: if element['ParameterDefaultValue']=='': lines = lines+'Default value'.ljust(strWidth,' ') + ' N/A'+'\n\n\n' else: lines = lines+'Default value'.ljust(strWidth,' ') + ' '+element['ParameterDefaultValue']+'\n\n\n' else: lines = lines+'\n\n' print(lines) self.parameters = lines self.parameterList = parameterList def getParameterValues(self,dataSetName, parameterName): '''Method returns a list of the values accepted for a given parameter of a dataset. Arguments: one of the dataset names returned by getDataSetList() and a parameter returned by getParameterList().''' r = requests.get('http://bea.gov/api/data?&UserID='+self.apiKey+'&method=GetParameterValues&datasetname='+dataSetName+'&ParameterName='+parameterName+'&') rJson = r.json() lines='Values accepted for '+parameterName+' in dataset '+dataSetName+':\n\n' if dataSetName.lower() == 'nipa' and parameterName.lower() == 'showmillions' and 'ParamValue' not in rJson['BEAAPI']['Results'].keys(): lines+= 'ShowMillions'.ljust(20,' ')+': N\n' lines+= 'Description'.ljust(20,' ')+': Units in billions of USD (default)\n\n' lines+= 'ShowMillions'.ljust(20,' ')+': Y\n' lines+= 'Description'.ljust(20,' ')+': Units in millions of USD\n\n' else: descrWidth = 50 def splitString(origString, maxLength): splitLines = [] line = '' for word in origString.split(' '): if len(line)+1+len(word)<maxLength: line = line+word+' ' else: splitLines.append(line) line = word+' ' if len(line) != 0: splitLines.append(line) return splitLines columnNames = [] for n,element in enumerate(rJson['BEAAPI']['Results']['ParamValue']): for key in element.keys(): if key not in columnNames: columnNames.append(key) data = np.zeros([n,len(columnNames)]) data[:] = np.nan tempFrame = pd.DataFrame(data,columns = columnNames) for n,element in enumerate(rJson['BEAAPI']['Results']['ParamValue']): for key,value in element.items(): tempFrame.loc[n,key] = element[key] # Sort tempFrame if the parameter falls into one of a few special categories if dataSetName.lower() == 'nipa': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['TableID']) elif parameterName.lower() =='year': tempFrame = tempFrame[['TableID','FirstAnnualYear','LastAnnualYear','FirstQuarterlyYear','LastQuarterlyYear','FirstMonthlyYear','LastMonthlyYear']] tempFrame.sort(columns = ['TableID']) elif dataSetName.lower() == 'fixedassets': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['TableID']) elif parameterName.lower() =='year': tempFrame = tempFrame[['TableID','FirstAnnualYear','LastAnnualYear']] tempFrame.sort(columns = ['TableID']) elif dataSetName.lower() == 'gdpbyindustry': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['Key']) for i in tempFrame.index: for c in tempFrame.columns: split = splitString(tempFrame.loc[i,c],descrWidth) for n, words in enumerate(split): if n==0: try: lines+=c.ljust(20,' ')+': '+str(int(words))+'\n' except: lines+=c.ljust(20,' ')+': '+str(words)+'\n' else: try: lines+=''.ljust(20,' ')+' '+str(words)+'\n' except: lines+=''.ljust(20,' ')+' '+str(words)+'\n' lines+='\n' print(lines) self.parameterValues = lines # 2. Methods for retreiving data. # 2.1 Regional Data (statistics by state, county, and MSA) def getRegionalData(self,KeyCode=None,GeoFips='STATE',Year='ALL'): '''Retrieve state and regional data. Name Type Required? Multiple values? "All" Value Default KeyCode int yes no N/A GeoFips str no yes 'STATE' or 'COUNTY' or 'MSA' STATE Year int no yes "ALL" ALL ''' # if type(KeyCode)==list: # KeyCode = ','.join(KeyCode) # if type(Year)==list: # Year = [str(y) for y in Year] # Year = ','.join(Year) # if type(GeoFips)==list: # GeoFips = ','.join(GeoFips) uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=RegionalData&KeyCode='+str(KeyCode)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() dataDict = {} # dates = [] # YearList = [] # name ='' columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],'A') if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],'A') if 'DataValue' in element.keys(): frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['PublicTable']+' - '+rJson['BEAAPI']['Results']['Statistic']+' - '+rJson['BEAAPI']['Results']['UnitOfMeasure'] return {'note':note,'data':frame} except: print('Invalid input.',sys.exc_info()[0]) # 2.2 NIPA (National Income and Product Accounts) def getNipa(self,TableID=None,Frequency='A',Year='X',ShowMillions='N'): '''Retrieve data from a NIPA table. Name Type Required? "All" Value Default TableID int yes N/A None Frequency(A/Q) str yes N/A None Year int yes "X" "X" ShowMillions str no N/A 'N' ''' if Frequency=='M': print('Error: monthly Frequency available for NIPA tables.') uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=NIPA&TableID='+str(TableID)+'&Frequency='+Frequency+'&Year='+str(Year)+'&ShowMillions='+ShowMillions+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['LineDescription'] not in columnNames: columnNames.append(element['LineDescription']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) frame.loc[date,element['LineDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # # 3.3 NIUnderlyingDetail (National Income and Product Accounts) # def getNIUnderlyingDetail(self,TableID,Frequency='A',Year='X'): # if type(Year)==list: # Year = [str(y) for y in Year] # Year = ','.join(Year) # uri = 'http://bea.gov/api/data/?UserID='+apiKey+'&method=GetData&datasetname=NIUnderlyingDetail&TableID='+str(TableID)+'&Year='+str(Year)+'&Frequency='+str(Frequency)+'&ResultFormat=JSON&' # r = requests.get(uri) # rJson = r.json() # columnNames = [] # dates = [] # try: # 3.4 Fixed Assets def getFixedAssets(self,TableID=None,Year='X'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=FixedAssets&TableID='+str(TableID)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['LineDescription'] not in columnNames: columnNames.append(element['LineDescription']) date = convertDate(element['TimePeriod'],'A') if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],'A') frame.loc[date,element['LineDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # 3.5 # def getMne(self,DirectionOfInvestment=None,OwnershipLevel=None,NonbankAffiliatesOnly=None,Classification=None,Country='all',Industry='all',Year='all',State='all',SeriesID=0): # 3.6 Gross domestic product by industry def getGdpByIndustry(self,TableID =None, Industry='ALL',Frequency='A',Year = 'ALL'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=GDPbyIndustry&TableID='+str(TableID)+'&Industry='+str(Industry)+'&Frequency='+str(Frequency)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['IndustrYDescription'] not in columnNames: columnNames.append(element['IndustrYDescription']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) frame.loc[date,element['IndustrYDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # 3.7 ITA: International transactions def getIta(self,Indicator=None,AreaOrCountry='ALL',Frequency='A',Year='ALL'): if Indicator=='ALL' and 'ALL' in AreaOrCountry: print('Warning: You may not select \'ALL\' for both Indicator and AreaOrCountry') else: uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=ita&Indicator='+str(Indicator)+'&AreaOrCountry='+str(AreaOrCountry)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: if AreaOrCountry.lower() == 'all': columnNames = [] dates = [] for element in rJson['BEAAPI']['Results']['Data']: if element['AreaOrCountry'] not in columnNames: columnNames.append(element['AreaOrCountry']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) if len(element['DataValue'].replace(',',''))>0: frame.loc[date,element['AreaOrCountry']] = float(element['DataValue'].replace(',','')) else: frame.loc[date,element['AreaOrCountry']] = np.nan else: columnNames = [] dates = [] for element in rJson['BEAAPI']['Results']['Data']: if element['Indicator'] not in columnNames: columnNames.append(element['Indicator']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) if len(element['DataValue'].replace(',',''))>0: frame.loc[date,element['Indicator']] = float(element['DataValue'].replace(',','')) else: frame.loc[date,element['Indicator']] = np.nan frame = frame.sort_index() units = rJson['BEAAPI']['Results']['Data'][0]['CL_UNIT'] mult = rJson['BEAAPI']['Results']['Data'][0]['UNIT_MULT'] if int(mult) == 3: units = 'Thousands of '+units elif int(mult) == 6: units = 'Millions of '+units elif int(mult) == 9: units = 'Billions of '+units if Frequency.lower() == 'q': Notes = rJson['BEAAPI']['Results']['Notes'] for note in Notes: if note['NoteRef'] == 'Q': noteQ = note['NoteText'] units = units + ', '+ noteQ return {'note':units,'data':frame} except: print(rJson['BEAAPI']['Error']['ErrorDetail']['Description']) # 3.8 IIP: International investment position def getIip(self,TypeOfInvestment=None,Component=None,Frequency='A',Year='ALL'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=IIP&TypeOfInvestment='+str(TypeOfInvestment)+'&Component='+str(Component)+'&Year='+str(Year)+'&Frequency='+str(Frequency)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Data']: if element['TimeSeriesDescription'] not in columnNames: columnNames.append(element['TimeSeriesDescription']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['TimeSeriesDescription']] = np.nan else: frame.loc[date,element['TimeSeriesDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() units = rJson['BEAAPI']['Data'][0]['CL_UNIT'] mult = rJson['BEAAPI']['Data'][0]['UNIT_MULT'] if int(mult) == 3: units = 'Thousands of '+units elif int(mult) == 6: units = 'Millions of '+units elif int(mult) == 9: units = 'Billions of '+units return {'note':units,'date':frame} except: print('Error: invalid input.') # 3.9 Regional Income: detailed regional income and employment data sets. def getRegionalIncome(self,TableName=None,LineCode=None,GeoFips=None,Year ='ALL'): '''GeoFips can equal STATE COUNTY MSA MIC PORT DIV CSA''' uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=RegionalIncome&TableName='+str(TableName)+'&LineCode='+str(LineCode)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] Frequency = 'A' try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['GeoName']] = np.nan else: frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() units = rJson['BEAAPI']['Results']['UnitOfMeasure'] return {'notes':units,'data':frame} except: print('Error: invalid input.') # 3.10 Regional product: detailed state and MSA product data sets def getRegionalProduct(self,Component=None,IndustryId=1,GeoFips='State',Year ='ALL'): '''GeoFips can equal either STATE or MSA''' uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=regionalProduct&Component='+str(Component)+'&IndustryId='+str(IndustryId)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] Frequency = 'A' try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['GeoName']] = np.nan else: frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Data'][0]['CL_UNIT'] return {'note':note,'date':frame} except: print('Error: invalid input.') # Auxiliary function. def convertDate(dateString,Frequency): '''Function for converting the date strings from BEA with quarter indicators into datetime format''' if Frequency=='A': month='01' elif Frequency=='Q': if dateString[-1]=='1': month='01' elif dateString[-1]=='2': month='04' elif dateString[-1]=='3': month='07' else: month='10' return datetime.datetime.strptime(dateString[0:4]+'-'+month+'-01','%Y-%m-%d')
letsgoexploring/beapy-package
beapy.py
Python
mit
25,953
#include <iostream> #include <seqan/align.h> using namespace seqan; using namespace std; int main() { typedef String<char> TSequence; // sequence type typedef Align<TSequence,ArrayGaps> TAlign; // align type typedef Row<TAlign>::Type TRow; // gapped sequence type TSequence seq1 = "ACGTCACCTC"; TSequence seq2 = "ACGGGCCTATC"; TAlign align; resize(rows(align), 2); assignSource(row(align,0),seq1); assignSource(row(align,1),seq2); std::cout << align; TRow &row1 = row(align,0); TRow &row2 = row(align,1); insertGaps(row1,2,2); insertGap(row1,5); insertGaps(row2,9,2); std::cout << align; typedef Iterator<TRow, Rooted>::Type TIt1; typedef Iterator<Rows<TAlign>::Type, Rooted>::Type TIt2; TIt2 it2 = begin(rows(align)); TIt1 it1; int gapCounter=0; while(!atEnd(it2)){ it1 = begin(row(align,position(it2))); while(!atEnd(it1)){ goNext(it1); if (isGap(*it2,position(it1))) gapCounter+=countGaps(it1); } goNext(it2); } cout << gapCounter << endl; }
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/qhuulr654q26tohr/2013-04-10T10-48-27.899+0200/sandbox/PMSB13/apps/5.0/5.0.cpp
C++
mit
1,130
# vim:ts=4:sts=4:sw=4:expandtab """The public API of satori.events. """ import hashlib import random import traceback from satori.objects import Object from satori.events.misc import Namespace from .dispatcher import Dispatcher from .protocol import KeepAlive, Disconnect, Attach, Detach, Map, Unmap, Send, Receive __all__ = ( 'Event', 'MappingId', 'QueueId', 'Manager', ) class Event(Namespace): """Describes an event. """ pass class MappingId(str): # pylint: disable-msg=R0904 """A (globally-unique) identifier of a mapping. """ def __new__(cls, value=None): if value is None: value = hashlib.md5(str(random.getrandbits(512))).hexdigest() return str.__new__(cls, value) class QueueId(str): # pylint: disable-msg=R0904 """A (globally-unique) identifier of an event queue. """ pass class Manager(Object): """Abstract. Manages Clients within a single process. """ def __init__(self): self.dispatcher = Dispatcher() def run(self): """Execute this Manager's event loop. """ handlers = { KeepAlive: self._handleKeepAlive, Attach: self._handleAttach, Detach: self._handleDetach, Map: self._handleMap, Unmap: self._handleUnmap, Send: self._handleSend, Receive: self._handleReceive, Disconnect: self._handleDisconnect, } while True: client = self.scheduler.next() if client is None: break try: command = client.recvCommand() except StopIteration: command = Disconnect() except Exception: print 'Exception in client, removing from queue' traceback.print_exc() self.scheduler.remove(client) else: handlers[command.__class__](command, client) def _handleKeepAlive(self, command, sender): raise NotImplementedError() def _handleDisconnect(self, command, sender): raise NotImplementedError() def _handleAttach(self, command, sender): raise NotImplementedError() def _handleDetach(self, command, sender): raise NotImplementedError() def _handleMap(self, command, sender): raise NotImplementedError() def _handleUnmap(self, command, sender): raise NotImplementedError() def _handleSend(self, command, sender): raise NotImplementedError() def _handleReceive(self, command, sender): raise NotImplementedError()
zielmicha/satori
satori.events/satori/events/api.py
Python
mit
2,752
<?php if (!isset($login) || $login->validated != '1') { include DIR."/php/controller/403.php"; die(); } else { function htmlHead() { ?> <script src="http://maps.google.com/maps/api/js"></script> <script src="/jslib/gmaps.js"></script> <style> #map, #panorama { height:450px; background:#6699cc; } </style> <?php } function mainContent() { global $login, $p, $message; $center=getCenter($p->findings); $init=[ 'res'=>summarize($p->findings), 'lat'=>$center->latitude, 'long'=>$center->longitude ] ?> <div class="row"> <div class="col-md-12"> <h2>Species map</h2> <h5><?= count($p->findings).' data found'?><?= ($center->errCount > 0) ? ', ('.$center->errCount.') has incomplete coordinates' : '' ?></h5> <div id="map"></div> </div> </div> <div id="init"><?php echo json_encode($init, JSON_UNESCAPED_SLASHES); ?></div> <div id="modalDetails" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Species Findings</h4> </div> <div class="modal-body"> <div id="details-panel" class="table-responsive"></div> </div> </div> </div> </div> <script src="/js/common/speciesmap.js"></script> <?php } function getCenter($coordinates) { $x=0; $y=0; $z=0; $count=count($coordinates); $errCount=0; if ($count == 0) return (object) ['longitude'=>0,'latitude'=>0,'count'=>0,'errCount'=>0]; foreach ($coordinates as $v) { if ($v->latitude == null || $v->longitude == null) { $count--; $errCount++; continue; } $lat = $v->latitude * M_PI / 180; $long = $v->longitude * M_PI / 180; $x += cos($lat) * cos($long); $y += cos($lat) * sin($long); $z += sin($lat); } //$x /= $count; $y /= $count; $z /= $count; //Ndak perlu. |$xyz| ndak akan ubah arah $base_r = sqrt($x*$x + $y*$y); $res = (object) [ 'longitude'=>atan2($y,$x) * 180/M_PI, 'latitude'=>atan2($z,$base_r) * 180/M_PI, 'count'=>$count, 'errCount'=>$errCount ]; return $res; } function tableRow($row) { return "<tr><td>$row->localname</td>" . "<td>".date('F Y',strtotime($row->survey_date))."</td>" . "<td>$row->iucn_status</td>" . "<td>$row->indo_status</td>" . "<td>$row->district</td></tr>"; } function summarize($findings) { $res = []; //localname, survey_month, survey_years, iucn_status, indo_status, district foreach ($findings as $v) { if ($v->latitude == null || $v->longitude == null) continue; $key = $v->latitude.','.$v->longitude; if (!isset($res[$key])) { $res[$key] = (object) [ 'latitude'=>$v->latitude, 'longitude'=>$v->longitude, 'count'=>1, 'info'=>"<table><thead><tr><th>Local Name</th><th>Survey Month</th><th>IUCN Status</th><th>Indonesia Status</th><th>District</th></thead><tbody>" .tableRow($v) ]; } else { $res[$key]->count++; $res[$key]->info .= tableRow($v); } } foreach ($res as $k=>$v) { $res[$k]->info.='</tbody></table>'; //$res[$k]->info = htmlentities($res[$k]->info); } return array_values($res); } $pageTitle = "Species Map"; include DIR.'/php/view/tulang.php'; }
fandisus/SSBIN
php/view/common/speciesmap.php
PHP
mit
3,611
module Mediadrawer module Rails VERSION = "0.0.2" end end
tracersoft/mediadrawer-rails
lib/mediadrawer/rails/version.rb
Ruby
mit
66
var Square = UI.component({ components: [Animator, KeyInput], animationMap: { moveLeft: { transform: [-50, 0, 0], time: 200, easing: "linear" }, moveRight: { transform: [50, 0, 0], time: 200, easing: "linear" } }, handleKeyPress: function(e) { if(e.keyCode === 37) { this.Animator.animate(this.animationMap.moveLeft); } else if(e.keyCode === 39) { this.Animator.animate(this.animationMap.moveRight); } }, render: function() { return {}; } }); var BigView = UI.component({ render: function() { var boxes = ["argo", "avatar", "breaking_bad", "brick_mansions", "crazy_stupid_love", "descendants", "gangs_of_new_york", "good_night_and_good_luck", "quantum_of_solace", "slumdog_millionaire", "the_kings_speech"]; var repeats = 2; while(--repeats) { boxes = boxes.concat(boxes); } var x = 0, y = 0; var tex_width = 186; var tex_height = 270; var scale = 0.5; var box_width = tex_width * scale; var box_height = tex_height * scale; var covers = boxes.map(function(box) { var box = UI.new(Square, { top: y, left: x, width: box_width, height: box_height, background: "boxes/box_"+box+".png" }); //console.info(box); x += box_width; if(x > 1000-box_width) { x = 0; y += box_height; } return box; }); //console.info(covers); var args = [Square, { name: "background-colored", top: 0, left: 0, width: 1000, height: 700 }].concat(covers); return UI.new.apply(this, args); } }); UI.render(BigView, document.getElementById("app")); var fps = document.getElementById("fps");
davedx/lustro
examples/auto-atlassing.js
JavaScript
mit
1,618
class RenameTableAttributesOptionToAttributeList < ActiveRecord::Migration def change rename_table :attributes_options, :attribute_lists rename_table :attribute_class_options_attributes_options, :attribute_class_options_attribute_lists rename_column :attribute_class_options_attribute_lists, :attributes_option_id, :attribute_list_id rename_index :attribute_class_options_attribute_lists, :index_acoao_on_attribute_option_id, :index_acoao_on_attribute_list_id end end
andrew2net/sitescan_common
db/migrate/20160315133239_rename_table_attributes_option_to_attribute_list.rb
Ruby
mit
488
package edu.cmu.hcii.whyline.bytecode; /** * @author Andrew J. Ko * */ public abstract class Instantiation extends Instruction { public Instantiation(CodeAttribute method) { super(method); } public String getReadableDescription() { return "new"; } public String getAssociatedName() { return null; } public abstract QualifiedClassName getClassnameOfTypeProduced(); }
andyjko/whyline
edu/cmu/hcii/whyline/bytecode/Instantiation.java
Java
mit
383
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("GorokuEdit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("GorokuEdit")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
go63/BenzGorokuSearch
GorokuEdit/Properties/AssemblyInfo.cs
C#
mit
2,757
<!-- Unsafe sample input : get the field userData from the variable $_GET via an object SANITIZE : use in_array to check if $tainted is in the white list File : unsafe, use of untrusted data in a quoted property value (CSS) --> <!--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.--> <!DOCTYPE html> <html> <head> <style> <?php class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } //flaw echo "body { color :\'". $tainted ."\' ; }" ; ?> </style> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/unsafe/CWE_79__object-classicGet__whitelist_using_array__Use_untrusted_data_propertyValue_CSS-quoted_Property_Value.php
PHP
mit
1,677
package MestreCuca; public enum Medidas { grama, unidade, xicara, colher_sopa }
glauber-barboza/crescer-2015-1
eclipse/MestreCucaAntigo/src/MestreCuca/Medidas.java
Java
mit
88
// Copyright (c) 2018-2020 The DÃSH Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/script.h> #include <test/test_biblepay.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(script_p2pk_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(IsPayToPublicKey) { // Test CScript::IsPayToPublicKey() static const unsigned char p2pkcompressedeven[] = { 0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG }; BOOST_CHECK(CScript(p2pkcompressedeven, p2pkcompressedeven+sizeof(p2pkcompressedeven)).IsPayToPublicKey()); static const unsigned char p2pkcompressedodd[] = { 0x41, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG }; BOOST_CHECK(CScript(p2pkcompressedodd, p2pkcompressedodd+sizeof(p2pkcompressedodd)).IsPayToPublicKey()); static const unsigned char p2pkuncompressed[] = { 0x41, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_CHECKSIG }; BOOST_CHECK(CScript(p2pkuncompressed, p2pkuncompressed+sizeof(p2pkuncompressed)).IsPayToPublicKey()); static const unsigned char missingop[] = { 0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; BOOST_CHECK(!CScript(missingop, missingop+sizeof(missingop)).IsPayToPublicKey()); static const unsigned char wrongop[] = { 0x41, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OP_EQUALVERIFY }; BOOST_CHECK(!CScript(wrongop, wrongop+sizeof(wrongop)).IsPayToPublicKey()); static const unsigned char tooshort[] = { 0x41, 0x02, 0, 0, OP_CHECKSIG }; BOOST_CHECK(!CScript(tooshort, tooshort+sizeof(tooshort)).IsPayToPublicKey()); } BOOST_AUTO_TEST_SUITE_END()
biblepay/biblepay
src/test/script_p2pk_tests.cpp
C++
mit
2,196
(function myAppCoreConstants() { 'use strict'; angular .module('myApp.core') .constant('FIREBASE_URL', 'https://blistering-heat-2473.firebaseio.com'); })();
neggro/angularjs_firebase
client/app/core/core.constants.js
JavaScript
mit
183
#!/usr/bin/env node const fs = require('fs'); const yaml = require('js-yaml'); const cli = require('../lib/cli'); // define cli options const optionList = [ { name: 'help', type: Boolean, description: 'show this help' }, { name: 'host', alias: 'h', type: String, description: 'host name' }, { name: 'port', alias: 'p', type: Number, description: 'port number' }, { name: 'watch', alias: 'w', type: Boolean, description: 'start in a watch mode' }, { name: 'docker', alias: 'd', type: Boolean, description: 'parse docker-compose.yml for parameters' }, // { name: 'file', alias: 'f', type: String, description: 'override the default docker-compose.yml file name' }, { name: 'service', alias: 's', type: String, description: 'service to look for when parsing docker-compose file' }, { name: 'flags', alias: 'l', type: String, description: 'custom flags to pass to rsync (default -rtR)' }, { name: 'volume', alias: 'v', type: String, description: 'override the default volume name' }, { name: 'version', type: Boolean, description: 'print version number' }, { name: 'files', type: String, defaultOption: true, multiple: true } ]; // define cli usage const usage = function (options) { return require('command-line-usage')([ { header: 'Synopsis', content: [ '$ drsync [bold]{--help}', ] }, { header: 'Options', optionList } ]) }; let args = require('command-line-args')(optionList, {}, process.argv); // override args with options from drsync.yml if (fs.existsSync('./drsync.yml')) { const overrides = yaml.safeLoad(fs.readFileSync('./drsync.yml', 'utf8')); if (overrides) { args = Object.assign({}, args, overrides.options); } } let options = {}; try { options = cli(args); } catch (err) { console.log(err.message); process.exit(); } // show help if requested if (options.help) { console.log(usage(options)); process.exit(); } // show version and exit if (options.version) { console.log(require('../package.json').version); process.exit(); } require('../lib/drsync')(options).subscribe(console.log);
stefda/drsync
bin/drsync.js
JavaScript
mit
2,107
<?php namespace water\session; /* * This class will manage session cookied and allow the opening a session via * a user object and getting a user by there session ID. */ use water\database\Users; class SessionStore{ public static function hasSession(){ if(isset($_SESSION['login-data'])){ $data = explode("\\", $_SESSION['login-data']); $user = Users::getUser($data[0]); if($user !== false){ if(isset($user["sessions"][$data[1]])){ return true; } else{ SessionStore::destroySession(); return false; } } else{ SessionStore::destroySession(); return false; } } else{ return false; } } public static function getCurrentSession(){ if(SessionStore::hasSession()){ $data = explode("\\", $_SESSION['login-data']); return Users::getUser($data[0]); } else{ return false; } } public static function createSession($user){ SessionStore::destroySession(); $_SESSION['login-data'] = $user . "\\" . Users::addSession($user, $_SERVER['REMOTE_ADDR']); } public static function destroySession(){ if(isset($_SESSION['login-data'])) { $data = explode("\\", $_SESSION['login-data']); Users::deleteSession($data[0], $data[1]); unset($_SESSION['login-data']); } } }
Falkirks/TeamShog
src/session/SessionStore.php
PHP
mit
1,586
/** * Created by alykoshin on 20.01.16. */ 'use strict'; var gulp = require('gulp'); module.exports = function(config) { // Define test task gulp.task('task21', function () { console.log('task21 is running, config:', config); }); // Define test task gulp.task('task22', function () { console.log('task22 is running, config:', config); }); };
alykoshin/require-dir-all
demo/21_gulp_advanced/gulp/tasks-enabled/task2.js
JavaScript
mit
371
# Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. from types import StringType from Bio.Alphabet import ProteinAlphabet from Bio.Seq import Seq from Bio.SCOP.Raf import to_one_letter_code from Bio.PDB.PDBExceptions import PDBException from Bio.PDB.Residue import Residue, DisorderedResidue from Vector import calc_dihedral, calc_angle __doc__=""" Polypeptide related classes (construction and representation). Example: >>> ppb=PPBuilder() >>> for pp in ppb.build_peptides(structure): >>> print pp.get_sequence() """ standard_aa_names=["ALA", "CYS", "ASP", "GLU", "PHE", "GLY", "HIS", "ILE", "LYS", "LEU", "MET", "ASN", "PRO", "GLN", "ARG", "SER", "THR", "VAL", "TRP", "TYR"] aa1="ACDEFGHIKLMNPQRSTVWY" aa3=standard_aa_names d1_to_index={} dindex_to_1={} d3_to_index={} dindex_to_3={} # Create some lookup tables for i in range(0, 20): n1=aa1[i] n3=aa3[i] d1_to_index[n1]=i dindex_to_1[i]=n1 d3_to_index[n3]=i dindex_to_3[i]=n3 def index_to_one(index): """ Index to corresponding one letter amino acid name. For example: 0 to A. """ return dindex_to_1[index] def one_to_index(s): """ One letter code to index. For example: A to 0. """ return d1_to_index[s] def index_to_three(i): """ Index to corresponding three letter amino acid name. For example: 0 to ALA. """ return dindex_to_3[i] def three_to_index(s): """ Three letter code to index. For example: ALA to 0. """ return d3_to_index[s] def three_to_one(s): """ Three letter code to one letter code. For example: ALA to A. """ i=d3_to_index[s] return dindex_to_1[i] def one_to_three(s): """ One letter code to three letter code. For example: A to ALA. """ i=d1_to_index[s] return dindex_to_3[i] def is_aa(residue, standard=0): """ Return 1 if residue object/string is an amino acid. @param residue: a L{Residue} object OR a three letter amino acid code @type residue: L{Residue} or string @param standard: flag to check for the 20 AA (default false) @type standard: boolean """ if not type(residue)==StringType: residue=residue.get_resname() residue=residue.upper() if standard: return d3_to_index.has_key(residue) else: return to_one_letter_code.has_key(residue) class Polypeptide(list): """ A polypeptide is simply a list of L{Residue} objects. """ def get_ca_list(self): """ @return: the list of C-alpha atoms @rtype: [L{Atom}, L{Atom}, ...] """ ca_list=[] for res in self: ca=res["CA"] ca_list.append(ca) return ca_list def get_phi_psi_list(self): """ Return the list of phi/psi dihedral angles """ ppl=[] lng=len(self) for i in range(0, lng): res=self[i] try: n=res['N'].get_vector() ca=res['CA'].get_vector() c=res['C'].get_vector() except: # Some atoms are missing # Phi/Psi cannot be calculated for this residue ppl.append((None, None)) res.xtra["PHI"]=None res.xtra["PSI"]=None continue # Phi if i>0: rp=self[i-1] try: cp=rp['C'].get_vector() phi=calc_dihedral(cp, n, ca, c) except: phi=None else: # No phi for residue 0! phi=None # Psi if i<(lng-1): rn=self[i+1] try: nn=rn['N'].get_vector() psi=calc_dihedral(n, ca, c, nn) except: psi=None else: # No psi for last residue! psi=None ppl.append((phi, psi)) # Add Phi/Psi to xtra dict of residue res.xtra["PHI"]=phi res.xtra["PSI"]=psi return ppl def get_tau_list(self): """ Return list of tau torsions angles for all 4 consecutive Calpha atoms. """ ca_list=self.get_ca_list() tau_list=[] for i in range(0, len(ca_list)-3): atom_list=[ca_list[i], ca_list[i+1], ca_list[i+2], ca_list[i+3]] vector_list=map(lambda a: a.get_vector(), atom_list) v1, v2, v3, v4=vector_list tau=calc_dihedral(v1, v2, v3, v4) tau_list.append(tau) # Put tau in xtra dict of residue res=ca_list[i+2].get_parent() res.xtra["TAU"]=tau return tau_list def get_theta_list(self): """ Return list of theta angles for all 3 consecutive Calpha atoms. """ theta_list=[] ca_list=self.get_ca_list() for i in range(0, len(ca_list)-2): atom_list=[ca_list[i], ca_list[i+1], ca_list[i+2]] vector_list=map(lambda a: a.get_vector(), atom_list) v1, v2, v3=vector_list theta=calc_angle(v1, v2, v3) theta_list.append(theta) # Put tau in xtra dict of residue res=ca_list[i+1].get_parent() res.xtra["THETA"]=theta return theta_list def get_sequence(self): """ Return the AA sequence. @return: polypeptide sequence @rtype: L{Seq} """ s="" for res in self: resname=res.get_resname() if to_one_letter_code.has_key(resname): resname=to_one_letter_code[resname] else: resname='X' s=s+resname seq=Seq(s, ProteinAlphabet) return seq def __repr__(self): """ Return <Polypeptide start=START end=END>, where START and END are sequence identifiers of the outer residues. """ start=self[0].get_id()[1] end=self[-1].get_id()[1] s="<Polypeptide start=%s end=%s>" % (start, end) return s class _PPBuilder: """ Base class to extract polypeptides. It checks if two consecutive residues in a chain are connected. The connectivity test is implemented by a subclass. """ def __init__(self, radius): """ @param radius: distance @type radius: float """ self.radius=radius def _accept(self, residue): "Check if the residue is an amino acid." if is_aa(residue): return 1 else: if "CA" in residue.child_dict: #It has an alpha carbon... #We probably need to update the hard coded list of #non-standard residues, see function is_aa for details. import warnings warnings.warn("Assuming residue %s is an unknown modified " "amino acid" % residue.get_resname()) return 1 # not a standard AA so skip return 0 def build_peptides(self, entity, aa_only=1): """ Build and return a list of Polypeptide objects. @param entity: polypeptides are searched for in this object @type entity: L{Structure}, L{Model} or L{Chain} @param aa_only: if 1, the residue needs to be a standard AA @type aa_only: int """ is_connected=self._is_connected accept=self._accept level=entity.get_level() # Decide wich entity we are dealing with if level=="S": model=entity[0] chain_list=model.get_list() elif level=="M": chain_list=entity.get_list() elif level=="C": chain_list=[entity] else: raise PDBException("Entity should be Structure, Model or Chain.") pp_list=[] for chain in chain_list: chain_it=iter(chain) prev=chain_it.next() pp=None for next in chain_it: if aa_only and not accept(prev): prev=next continue if is_connected(prev, next): if pp is None: pp=Polypeptide() pp.append(prev) pp_list.append(pp) pp.append(next) else: pp=None prev=next return pp_list class CaPPBuilder(_PPBuilder): """ Use CA--CA distance to find polypeptides. """ def __init__(self, radius=4.3): _PPBuilder.__init__(self, radius) def _is_connected(self, prev, next): for r in [prev, next]: if not r.has_id("CA"): return 0 n=next["CA"] p=prev["CA"] # Unpack disordered if n.is_disordered(): nlist=n.disordered_get_list() else: nlist=[n] if p.is_disordered(): plist=p.disordered_get_list() else: plist=[p] for nn in nlist: for pp in plist: if (nn-pp)<self.radius: return 1 return 0 class PPBuilder(_PPBuilder): """ Use C--N distance to find polypeptides. """ def __init__(self, radius=1.8): _PPBuilder.__init__(self, radius) def _is_connected(self, prev, next): if not prev.has_id("C"): return 0 if not next.has_id("N"): return 0 test_dist=self._test_dist c=prev["C"] n=next["N"] # Test all disordered atom positions! if c.is_disordered(): clist=c.disordered_get_list() else: clist=[c] if n.is_disordered(): nlist=n.disordered_get_list() else: nlist=[n] for nn in nlist: for cc in clist: # To form a peptide bond, N and C must be # within radius and have the same altloc # identifier or one altloc blank n_altloc=nn.get_altloc() c_altloc=cc.get_altloc() if n_altloc==c_altloc or n_altloc==" " or c_altloc==" ": if test_dist(nn, cc): # Select the disordered atoms that # are indeed bonded if c.is_disordered(): c.disordered_select(c_altloc) if n.is_disordered(): n.disordered_select(n_altloc) return 1 return 0 def _test_dist(self, c, n): "Return 1 if distance between atoms<radius" if (c-n)<self.radius: return 1 else: return 0 if __name__=="__main__": import sys from Bio.PDB.PDBParser import PDBParser p=PDBParser(PERMISSIVE=1) s=p.get_structure("scr", sys.argv[1]) ppb=PPBuilder() print "C-N" for pp in ppb.build_peptides(s): print pp.get_sequence() for pp in ppb.build_peptides(s[0]): print pp.get_sequence() for pp in ppb.build_peptides(s[0]["A"]): print pp.get_sequence() for pp in ppb.build_peptides(s): for phi, psi in pp.get_phi_psi_list(): print phi, psi ppb=CaPPBuilder() print "CA-CA" for pp in ppb.build_peptides(s): print pp.get_sequence() for pp in ppb.build_peptides(s[0]): print pp.get_sequence() for pp in ppb.build_peptides(s[0]["A"]): print pp.get_sequence()
NirBenTalLab/proorigami-cde-package
cde-root/usr/lib64/python2.4/site-packages/Bio/PDB/Polypeptide.py
Python
mit
11,950
const { FuseBox, QuantumPlugin, UglifyJSPlugin } = require("fuse-box"); const fuse = FuseBox.init({ target: "browser@es5", homeDir: ".", output: "dist/$name.js", plugins: [ QuantumPlugin({ treeshake: true, target: "browser", }), UglifyJSPlugin({ }) ], }); fuse.bundle("remark-bundle").instructions("> index.js"); fuse.run();
zipang/markdown-bundle
src/remark/bundle/fuse.js
JavaScript
mit
348
import { Controller } from 'marionette'; import Layout from '../commons/layout'; import MainPage from '../pages/mainPage'; import ImportPage from '../pages/importPage'; import ProfileView from '../pages/profileView'; export default Controller.extend({ defaultRoute(){ Layout.main.show( new MainPage() ); }, register(){ //Layout.main.show( new RegisterView() ); }, viewProfile(id){ Layout.main.show( new ProfileView(id) ); }, createAi(){ //Layout.main.show( new CreateAIView(id) ); }, import(){ Layout.main.show( new ImportPage() ); } });
jbsouvestre/challengr
Challengr/public/js/routes/controller.js
JavaScript
mit
619
require 'pp' require "google_drive" require "ruby-progressbar" ENV['SSL_CERT_FILE'] = Gem.loaded_specs['google-api-client'].full_gem_path+'/lib/cacerts.pem' module Pairity class GoogleSync CONFIG_FILE = Dir.home + "/.pairity_google.json" attr_reader :sheet_url def initialize(matrix) @matrix = matrix @people = {} @sheet_url = nil end def load unless File.exists?(CONFIG_FILE) puts "Welcome, newcomer!" puts "Please follow these instructions to allow #{Rainbow("Pairity").white} to use Google Sheets to sync its precious data." end session = GoogleDrive.saved_session(CONFIG_FILE) puts "Loading Matrix from Google Sheets..." progressbar = ProgressBar.create(total: 100) progressbar.progress += 20 sheet = session.spreadsheet_by_title("Pairity") unless sheet puts "Creating a new spreadsheet called: Pairity" sheet = session.create_spreadsheet("Pairity") sheet.add_worksheet("Days") sheet.add_worksheet("Resistance") sheet.add_worksheet("Weights") ws = sheet.worksheets[0] ws.title = "People" ws.save else end @sheet_url = sheet.worksheets[0].human_url ws = sheet.worksheets[0] # Add People and Tiers to Matrix ws.num_rows.times do |row| next unless row > 0 name = ws[row + 1, 1] next if name.strip.empty? tier = ws[row + 1, 2] if name == "Han Solo" person = @matrix.han_solo else person = Person.new(name: name, tier: tier) @matrix.add_person(person) end @people[person] = row + 1 end # Add data to edges (1..3).each do |i| ws = sheet.worksheets[i] @people.each do |p1, row| @people.each do |p2, col| next if p1 == p2 data = ws[row, col] edit_edge(p1, p2, data, i) end end end @matrix end def clear_worksheet(ws) (1..ws.num_rows).each do |i| (1..ws.num_rows).each do |j| ws[i, j] = "" ws[j, i] = "" end end end def save puts "Saving Matrix to Google Sheets..." progressbar = ProgressBar.create(total: 100) session = GoogleDrive.saved_session(CONFIG_FILE) sheet = session.spreadsheet_by_title("Pairity") @people = @matrix.all_people.sort progressbar.progress += 20 ws = sheet.worksheets[0] clear_worksheet(ws) ws[1, 1] = "Name" ws[1, 2] = "Tier (1-3)" @people.each_with_index do |person, index| ws[index + 2, 1] = person.name ws[index + 2, 2] = person.tier end ws.save (1..3).each do |i| ws = sheet.worksheets[i] clear_worksheet(ws) @people.each_with_index do |person, index| ws[1, index + 2] = person.name ws[index + 2, 1] = person.name end progressbar.progress += 20 @people.combination(2) do |pair| p1, p2 = pair index1 = @people.index(p1) index2 = @people.index(p2) edge = @matrix[p1,p2] case i when 1 ws[1,1] = "Days" data = edge.days when 2 ws[1,1] = "Resistances" data = edge.resistance when 3 ws[1,1] = "Weights" data = edge.weight end ws[index1 + 2, index2 + 2] = data ws[index2 + 2, index1 + 2] = data end max = ws.max_rows @people.each_with_index do |person, index| ws[index + 2, index + 2] = "" ws[index + 2, index + 2] = "" max = index + 3 end ws.save end progressbar.progress += 20 end def edit_edge(p1, p2, data, i) case i when 1 @matrix[p1, p2].days = data.to_i when 2 @matrix[p1, p2].resistance = (data ? 1 : data.to_i) when 3 @matrix[p1, p2].weight = data.to_i end end def find_person(name) person = @people.find { |person| person.name == name } end end end
kitlangton/pairity
lib/pairity/google_sync.rb
Ruby
mit
4,194
import{ FETCH_TIMELOGS } from '../actions/TimelogActions'; function ajax(url, callback) { var data; var fetch; fetch = new XMLHttpRequest(); fetch.onreadystatechange = function() { if (fetch.readyState == XMLHttpRequest.DONE ) { if(fetch.status == 200){ var data = JSON.parse(fetch.responseText); console.log('---------------------- ajax response '); console.log(data); if (callback) callback(data); } else if(fetch.status == 404) { data = { error: 'There was an error 404' }; console.log('---------------------- ajax response '); console.log(data); } else { data = { error: 'something else other than 200 was returned' }; console.log('---------------------- ajax response '); console.log(data); } } }; fetch.open("GET", url, true); fetch.send(); return data; } var defaultState = ajax('timelogs.json', function (return_data) { return return_data; }); export default function timelogReducer(state = defaultState, action) { switch (action.type) { case FETCH_TIMELOGS: var new_state = ajax('timelogs.json', function (return_data) { console.log('Fetch timelogs was run'); return return_data; }); return new_state; default: return state; } }
pdx-code/teampro
src/reducers/TimelogReducer.js
JavaScript
mit
1,374
# This is an example of adding a custom plugin to Projeny # If you uncomment this then initialize a new project (for eg. "prj -p MyProject -bf") # Then after that completes there should be a new file at UnityProjects/MyProject/MyP-win/MyExampleFile.txt #import mtm.ioc.Container as Container #from mtm.ioc.Inject import Inject #class CustomProjectInitHandler: #_varMgr = Inject('VarManager') #def onProjectInit(self, projectName, platform): #outputPath = self._varMgr.expand('[ProjectPlatformRoot]/MyExampleFile.txt') #with open(outputPath, 'w') as f: #f.write("This is a sample of configuring the generated project directory") #Container.bind('ProjectInitHandlers').toSingle(CustomProjectInitHandler)
modesttree/Projeny
Source/prj/plugins/ExamplePlugin.py
Python
mit
745
package com.sensepost.yeti.gui; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.HashSet; import com.sensepost.yeti.common.JIPCalc; import com.sensepost.yeti.persistence.DataStore; /** * * @author willemmouton */ public class ReverseLookupInit extends BaseDlg { private String buffer = ""; public ReverseLookupInit() { initComponents(); this.setLocationRelativeTo(null); this.setModalityType(ModalityType.APPLICATION_MODAL); } public ArrayList<String> getTargets() { ArrayList<String> result = new ArrayList<>(); String[] ips = txtIPRanges.getText().split("\n"); for (String ip : ips) { @SuppressWarnings("static-access") ArrayList<String> al = new JIPCalc(ip.trim()).getTargets(); result.addAll(al); } return result; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); txtIPRanges = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); cbxImportFrom = new javax.swing.JComboBox(); btnLoadFromSource = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); cbxMakeRanges = new javax.swing.JCheckBox(); cbxRanges = new javax.swing.JComboBox(); btnStart = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); setName("Form"); // NOI18N jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input params...")); jPanel1.setName("jPanel1"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N txtIPRanges.setColumns(20); txtIPRanges.setRows(5); txtIPRanges.setName("txtIPRanges"); // NOI18N jScrollPane1.setViewportView(txtIPRanges); jLabel3.setText("Sources"); // NOI18N jLabel3.setName("jLabel3"); // NOI18N cbxImportFrom.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Initial IP Addresses", "Discovered IP Addresses" })); cbxImportFrom.setName("cbxImportFrom"); // NOI18N btnLoadFromSource.setText("Load"); // NOI18N btnLoadFromSource.setName("btnLoadFromSource"); // NOI18N btnLoadFromSource.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnLoadFromSourceMouseClicked(evt); } }); jLabel1.setText("IP ranges"); // NOI18N jLabel1.setName("jLabel1"); // NOI18N cbxMakeRanges.setText("Make ranges"); // NOI18N cbxMakeRanges.setName("cbxMakeRanges"); // NOI18N cbxMakeRanges.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { cbxMakeRangesItemStateChanged(evt); } }); cbxRanges.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "/24", "/16" })); cbxRanges.setEnabled(false); cbxRanges.setName("cbxRanges"); // NOI18N cbxRanges.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbxRangesActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(cbxMakeRanges) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cbxRanges, 0, 151, Short.MAX_VALUE) .add(101, 101, 101)) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(jLabel3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cbxImportFrom, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btnLoadFromSource)) .add(jLabel1)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cbxImportFrom, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel3) .add(btnLoadFromSource)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cbxMakeRanges) .add(cbxRanges, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)) ); btnStart.setText("Start"); // NOI18N btnStart.setName("btnStart"); // NOI18N btnStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnStartMouseClicked(evt); } }); btnCancel.setText("Cancel"); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnCancelMouseClicked(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(210, Short.MAX_VALUE) .add(btnCancel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btnStart) .addContainerGap()) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(btnCancel) .add(btnStart)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnStartMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMouseClicked this.cancelled = false; this.setVisible(false); // TODO add your handling code here: }//GEN-LAST:event_btnStartMouseClicked private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked this.setVisible(false); }//GEN-LAST:event_btnCancelMouseClicked private void btnLoadFromSourceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLoadFromSourceMouseClicked HashSet<String> ips = new HashSet<>(); switch (cbxImportFrom.getSelectedIndex()) { case 0: { ips.addAll(DataStore.getInitialDataItems(DataStore.IP)); ips.addAll(DataStore.getAllIPSForCurrentFootprint()); break; } case 1: { ips.addAll(DataStore.getInitialDataItems(DataStore.IP)); break; } case 2: { } } for (String ip : ips) { txtIPRanges.append(ip + "\n"); } }//GEN-LAST:event_btnLoadFromSourceMouseClicked private void cbxMakeRangesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbxMakeRangesItemStateChanged this.cbxRanges.setEnabled(cbxMakeRanges.isSelected()); if (this.buffer.isEmpty()) { if (cbxMakeRanges.isSelected()) { this.buffer = txtIPRanges.getText(); } else { txtIPRanges.setText(this.buffer); this.buffer = ""; } } this.cbxRanges.setSelectedIndex(0); }//GEN-LAST:event_cbxMakeRangesItemStateChanged private void cbxRangesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxRangesActionPerformed HashSet<String> ips = new HashSet<>(); for (String ip : this.buffer.split("\\n")) { String[] ipParts = ip.split("\\."); String modIp = ""; switch (cbxRanges.getSelectedIndex()) { case 0: modIp = String.format("%s.%s.%s.0/24", ipParts[0], ipParts[1], ipParts[2]); break; case 1: modIp = String.format("%s.%s.0.0/16", ipParts[0], ipParts[1]); break; default: return; } ips.add(modIp); } txtIPRanges.setText(""); for (String ip : ips) { txtIPRanges.append(ip + "\n"); } }//GEN-LAST:event_cbxRangesActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnLoadFromSource; private javax.swing.JButton btnStart; private javax.swing.JComboBox cbxImportFrom; private javax.swing.JCheckBox cbxMakeRanges; private javax.swing.JComboBox cbxRanges; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea txtIPRanges; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }
sensepost/yeti
src/main/java/com/sensepost/yeti/gui/ReverseLookupInit.java
Java
mit
11,627
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MessParser { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MenuItem_Exit_Click(object sender, RoutedEventArgs e) { this.Close(); } private void MenuItem_Open_Click(object sender, RoutedEventArgs e) { var dialog = new Microsoft.Win32.OpenFileDialog(); dialog.DefaultExt = ".txt"; dialog.Filter = "TXT Files (*.txt)|*.txt"; bool? result = dialog.ShowDialog(); if (result == true) { string filename = dialog.FileName; var content = File.ReadAllText(filename); tbContent.Text = content; } } private void MenuItem_About_Click(object sender, RoutedEventArgs e) { MessageBox.Show("ESO little project for mess files.", "About", MessageBoxButton.OK, MessageBoxImage.Information); } } }
ewasow/learning-cs
MessParser/MessParser/MainWindow.xaml.cs
C#
mit
1,583
/** * @fileoverview Tests for cli. * @author Ian Christian Myers */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var assert = require("chai").assert, CLIEngine = require("../../lib/cli-engine"); require("shelljs/global"); /*global tempdir, mkdir, rm, cp*/ //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ describe("CLIEngine", function() { describe("executeOnFiles()", function() { var engine; it("should report zero messages when given a config file and a valid file", function() { engine = new CLIEngine({ // configFile: path.join(__dirname, "..", "..", ".eslintrc") }); var report = engine.executeOnFiles(["lib/cli.js"]); // console.dir(report.results[0].messages); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return one error message when given a config with rules with options and severity level set to error", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/quotes-error.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/single-quoted.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); it("should return two messages when given a config file and a directory of files", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/semi-error.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/formatters"]); assert.equal(report.results.length, 2); assert.equal(report.results[0].messages.length, 0); assert.equal(report.results[1].messages.length, 0); }); it("should return zero messages when given a config with environment set to browser", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/env-browser.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given an option to set environment to browser", function() { engine = new CLIEngine({ envs: ["browser"], rules: { "no-undef": 2 }, reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given a config with environment set to Node.js", function() { engine = new CLIEngine({ configFile: "tests/fixtures/configurations/env-node.json", reset: true }); var report = engine.executeOnFiles(["tests/fixtures/globals-node.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should not return results from previous call when calling more than once", function() { engine = new CLIEngine({ ignore: false, reset: true, rules: { semi: 2 } }); var report = engine.executeOnFiles(["tests/fixtures/missing-semicolon.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/missing-semicolon.js"); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 2); report = engine.executeOnFiles(["tests/fixtures/passing.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/passing.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when given a directory with eslint excluded files in the directory", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore" }); var report = engine.executeOnFiles(["tests/fixtures/"]); assert.equal(report.results.length, 0); }); it("should return zero messages when given a file in excluded files list", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore" }); var report = engine.executeOnFiles(["tests/fixtures/passing"]); assert.equal(report.results.length, 0); }); it("should return two messages when given a file in excluded files list while ignore is off", function() { engine = new CLIEngine({ ignorePath: "tests/fixtures/.eslintignore", ignore: false, reset: true, rules: { "no-undef": 2 } }); var report = engine.executeOnFiles(["tests/fixtures/undef.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/undef.js"); assert.equal(report.results[0].messages[0].ruleId, "no-undef"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-undef"); assert.equal(report.results[0].messages[1].severity, 2); }); it("should return zero messages when executing a file with a shebang", function() { engine = new CLIEngine({ ignore: false, reset: true }); var report = engine.executeOnFiles(["tests/fixtures/shebang.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); it("should thrown an error when loading a custom rule that doesn't exist", function() { engine = new CLIEngine({ ignore: false, reset: true, rulesPaths: ["./tests/fixtures/rules/wrong"], configFile: "./tests/fixtures/rules/eslint.json" }); assert.throws(function() { engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); }, /Definition for rule 'custom-rule' was not found/); }); it("should thrown an error when loading a custom rule that doesn't exist", function() { engine = new CLIEngine({ ignore: false, reset: true, rulePaths: ["./tests/fixtures/rules/wrong"], configFile: "./tests/fixtures/rules/eslint.json" }); assert.throws(function() { engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); }, /Error while loading rule 'custom-rule'/); }); it("should return one message when a custom rule matches a file", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, rulePaths: ["./tests/fixtures/rules/"], configFile: "./tests/fixtures/rules/eslint.json" }); var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/rules/test/test-custom-rule.js"); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "custom-rule"); assert.equal(report.results[0].messages[0].severity, 1); }); it("should return messages when multiple custom rules match a file", function() { engine = new CLIEngine({ ignore: false, reset: true, rulePaths: [ "./tests/fixtures/rules/dir1", "./tests/fixtures/rules/dir2" ], configFile: "./tests/fixtures/rules/multi-rulesdirs.json" }); var report = engine.executeOnFiles(["tests/fixtures/rules/test-multi-rulesdirs.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "tests/fixtures/rules/test-multi-rulesdirs.js"); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "no-literals"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-strings"); assert.equal(report.results[0].messages[1].severity, 2); }); it("should return zero messages when executing with reset flag", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false }); var report = engine.executeOnFiles(["./tests/fixtures/missing-semicolon.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/missing-semicolon.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when executing with reset flag in Node.js environment", function() { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, envs: ["node"] }); var report = engine.executeOnFiles(["./tests/fixtures/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/process-exit.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages and ignore local config file when executing with no-eslintrc flag", function () { engine = new CLIEngine({ ignore: false, reset: true, useEslintrc: false, envs: ["node"] }); var report = engine.executeOnFiles(["./tests/fixtures/eslintrc/quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/eslintrc/quotes.js"); assert.equal(report.results[0].messages.length, 0); }); it("should return zero messages when executing with local config file", function () { engine = new CLIEngine({ ignore: false, reset: true }); var report = engine.executeOnFiles(["./tests/fixtures/eslintrc/quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].filePath, "./tests/fixtures/eslintrc/quotes.js"); assert.equal(report.results[0].messages.length, 1); }); // These tests have to do with https://github.com/eslint/eslint/issues/963 describe("configuration hierarchy", function() { var fixtureDir; // copy into clean area so as not to get "infected" by this project's .eslintrc files before(function() { fixtureDir = tempdir() + "/eslint/fixtures"; mkdir("-p", fixtureDir); cp("-r", "./tests/fixtures/config-hierarchy", fixtureDir); }); after(function() { rm("-r", fixtureDir); }); // Default configuration - blank it("should return zero messages when executing with reset and no .eslintrc", function () { engine = new CLIEngine({ reset: true, useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Default configuration - conf/eslint.json it("should return one message when executing with no .eslintrc", function () { engine = new CLIEngine({ useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 3); assert.equal(report.results[0].messages[0].ruleId, "no-undef"); assert.equal(report.results[0].messages[0].severity, 2); assert.equal(report.results[0].messages[1].ruleId, "no-console"); assert.equal(report.results[0].messages[1].severity, 2); assert.equal(report.results[0].messages[2].ruleId, "quotes"); assert.equal(report.results[0].messages[2].severity, 2); }); // Default configuration - conf/environments.json (/*eslint-env node*/) it("should return one message when executing with no .eslintrc in the Node.js environment", function () { engine = new CLIEngine({ useEslintrc: false }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes-node.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level .eslintrc it("should return one message when executing with .eslintrc in the Node.js environment", function () { engine = new CLIEngine(); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-process-exit"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level .eslintrc it("should return zero messages when executing with .eslintrc in the Node.js environment and reset", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Project configuration - first level .eslintrc it("should return one message when executing with .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 2); }); // Project configuration - first level package.json it("should return one message when executing with package.json"); // Project configuration - second level .eslintrc it("should return one message when executing with local .eslintrc that overrides parent .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-console"); assert.equal(report.results[0].messages[0].severity, 1); }); // Project configuration - third level .eslintrc it("should return one message when executing with local .eslintrc that overrides parent and grandparent .eslintrc", function () { engine = new CLIEngine({ reset: true }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/subsubbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --config with first level .eslintrc it("should return two messages when executing with config file that adds to local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 1); assert.equal(report.results[0].messages[1].ruleId, "quotes"); assert.equal(report.results[0].messages[1].severity, 2); }); // Command line configuration - --config with first level .eslintrc it("should return no messages when executing with config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Command line configuration - --config with second level .eslintrc it("should return two messages when executing with config file that adds to local and parent .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 2); assert.equal(report.results[0].messages[0].ruleId, "semi"); assert.equal(report.results[0].messages[0].severity, 1); assert.equal(report.results[0].messages[1].ruleId, "no-console"); assert.equal(report.results[0].messages[1].severity, 1); }); // Command line configuration - --config with second level .eslintrc it("should return one message when executing with config file that overrides local and parent .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "no-console"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --config with first level .eslintrc it("should return no messages when executing with config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml" }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 0); }); // Command line configuration - --rule with --config and first level .eslintrc it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml", rules: { quotes: [1, "double"] } }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); // Command line configuration - --rule with --config and first level .eslintrc it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function () { engine = new CLIEngine({ reset: true, configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml", rules: { quotes: [1, "double"] } }); var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]); assert.equal(report.results.length, 1); assert.equal(report.results[0].messages.length, 1); assert.equal(report.results[0].messages[0].ruleId, "quotes"); assert.equal(report.results[0].messages[0].severity, 1); }); }); // it("should return zero messages when executing with global node flag", function () { // engine = new CLIEngine({ // ignore: false, // reset: true, // useEslintrc: false, // configFile: "./conf/eslint.json", // envs: ["node"] // }); // var files = [ // "./tests/fixtures/globals-node.js" // ]; // var report = engine.executeOnFiles(files); // console.dir(report.results[0].messages); // assert.equal(report.results.length, 1); // assert.equal(report.results[0].filePath, files[0]); // assert.equal(report.results[0].messages.length, 1); // }); // it("should return zero messages when executing with global env flag", function () { // engine = new CLIEngine({ // ignore: false, // reset: true, // useEslintrc: false, // configFile: "./conf/eslint.json", // envs: ["browser", "node"] // }); // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // var report = engine.executeOnFiles(files); // console.dir(report.results[1].messages); // assert.equal(report.results.length, 2); // assert.equal(report.results[0].filePath, files[0]); // assert.equal(report.results[0].messages.length, 1); // assert.equal(report.results[1].filePath, files[1]); // assert.equal(report.results[1].messages.length, 1); // }); // it("should return zero messages when executing with env flag", function () { // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // it("should allow environment-specific globals", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --env browser,node --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 9); // }); // it("should allow environment-specific globals, with multiple flags", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --env browser --env node --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 9); // }); // }); // it("should return zero messages when executing without env flag", function () { // var files = [ // "./tests/fixtures/globals-browser.js", // "./tests/fixtures/globals-node.js" // ]; // it("should not define environment-specific globals", function () { // cli.execute("--reset --no-eslintrc --config ./conf/eslint.json --no-ignore " + files.join(" ")); // assert.equal(console.log.args[0][0].split("\n").length, 12); // }); // }); // it("should return zero messages when executing with global flag", function () { // it("should default defined variables to read-only", function () { // var exit = cli.execute("--global baz,bat --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.calledOnce); // assert.equal(exit, 1); // }); // it("should allow defining writable global variables", function () { // var exit = cli.execute("--reset --global baz:false,bat:true --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.notCalled); // assert.equal(exit, 0); // }); // it("should allow defining variables with multiple flags", function () { // var exit = cli.execute("--reset --global baz --global bat:true --no-ignore ./tests/fixtures/undef.js"); // assert.isTrue(console.log.notCalled); // assert.equal(exit, 0); // }); // }); }); });
roadhump/eslint
tests/lib/cli-engine.js
JavaScript
mit
28,534
/* global angular, moment */ var app = angular.module('flowList', ['ui.grid']); app.controller('flowListCtrl', function($scope, $http) { 'use strict'; $http.get('/json/rawFlowsForLast/5/minutes') .success(function(data) { var retList = []; data.forEach(function(element) { var flowRecord = { srcAddress: element._source.ipv4_src_addr, dstAddress: element._source.ipv4_dst_addr, Packets: element._source.in_pkts, Bytes: element._source.in_bytes, Time: moment(element._source.timestamp) .format('YYYY-MM-DD HH:mm:ss') }; retList.push(flowRecord); }); $scope.flows = retList; }) .error(function() { console.warn('doh'); }); });
skarfacegc/FlowTrack2
www/js/flowListController.js
JavaScript
mit
836
require('date-utils'); var sendgrid = require('sendgrid')("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"); module.exports = function(app, config, passport, mongoose, fs, path){ var isAuthenticated = function(req, res, next){ if(req.isAuthenticated()){ return next(); } else { res.redirect("/login"); } } app.get("/", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/myaccount", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/create", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/search", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/login", passport.authenticate('google', { scope : ['profile', 'email'] }) ); app.get("/auth/google/callback", passport.authenticate('google', { successRedirect : '/', failureRedirect: '/login', failureFlash: true }) ); app.get('/logout', function(req, res) { req.logout(); res.redirect("/"); }); var getPools = function(query, res){ var requests = mongoose.model('request'); requests.find(query, function(err, result){ if (err) { console.log(err); } else { res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }; app.get('/api/comments', isAuthenticated, function(req, res) { var query = {$or:[{createdOn: {$eq: Date.today()}}, {everyday: {$eq: true}}]}; getPools(query, res); }); app.get('/api/mycomments', isAuthenticated, function(req, res) { var myEmailId = req.user.email; var query = {email: myEmailId}; getPools(query, res); }); app.delete('/api/comments', function (req, res) { var requests = mongoose.model('request'); var query = {_id: req.body.id}; requests.remove(query, function(err, result){ if (err) { console.log(err); } else { console.log("pool deleted"); } }); }); app.post('/api/comments', isAuthenticated, function(req, res) { var user = req.user; var request = mongoose.model('request'); var newRequest = new request({ email: user.email, name: user.name, originAddress: req.body.originAddress, destinationAddress: req.body.destinationAddress, provider: req.body.provider, time: req.body.time, encodedRoute: req.body.encodedRoute, createdOn: Date.today(), everyday: req.body.everyday }); newRequest.save(function (err, result) { if (err) { console.log(err); } else { console.log('documents into the "request" collection are:', result); res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }); app.post('/notify', isAuthenticated, function(req, res) { var notifications = req.body.notifications; console.log("notifications"); console.log(notifications); notifications.forEach(function(notification){ var payload = { to : notification.email, from : notification.from, subject : notification.subject, html : notification.html } sendgrid.send(payload, function(err, json) { if (err) { console.error(err); }else{ res.json(json); } }); }); }); app.get('/user', function (req, res) { res.json(req.user); }); }
prabhuramkumar/ThoughtPool
config/routes.js
JavaScript
mit
3,415
package com.mapzen.tangram; import android.support.annotation.Keep; import java.util.Map; /** * {@code LabelPickResult} represents labels that can be selected on the screen */ @Keep public class LabelPickResult { /** * Options for the type of LabelPickResult */ public enum LabelType { ICON, TEXT, } private LngLat coordinates; private LabelType type; private Map<String, String> properties; private LabelPickResult(double longitude, double latitude, int type, Map<String, String> properties) { this.properties = properties; this.coordinates = new LngLat(longitude, latitude); this.type = LabelType.values()[type]; } public LabelType getType() { return this.type; } /** * @return The coordinate of the feature for which this label has been created */ public LngLat getCoordinates() { return this.coordinates; } /** * @return A mapping of string keys to string or number values */ public Map<String, String> getProperties() { return this.properties; } }
quitejonny/tangram-es
platforms/android/tangram/src/main/java/com/mapzen/tangram/LabelPickResult.java
Java
mit
1,122
<?php require_once __DIR__ . '/../../vendor/autoload.php'; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class Progress extends Command { protected function configure() { $this->setName('progress'); } protected function execute(InputInterface $input, OutputInterface $output) { $progress = $this->getHelperSet()->get('progress'); $progress->start($output, 50); $i = 0; while ($i++ < 50) { $progress->advance(); } $progress->finish(); } } $app = new Application(); $app->add(new \Progress()); $app->run(new ArrayInput(array('command' => 'progress')));
dcsg/phplx-how-to-build-console-app
examples/Helpers/progress.php
PHP
mit
795
using System; namespace Infrastructure.Interface { public interface ITrackableEntity { DateTime CreatedDate { get; set; } string CreatedBy { get; set; } DateTime UpdatedDate { get; set; } string UpdatedBy { get; set; } } }
Radigeco/webapi-jwt-angular-boilerplate
Context/ITrackableEntity.cs
C#
mit
273
class Recipe < ActiveRecord::Base acts_as_taggable validates :name, presence: true validates :people, presence: true validates :duration, presence: true validates :instructions, presence: true belongs_to :user has_many :ingredient_groups, dependent: :destroy has_many :links, dependent: :destroy accepts_nested_attributes_for :ingredient_groups, reject_if: :all_blank, allow_destroy: true accepts_nested_attributes_for :links, reject_if: :all_blank, allow_destroy: true end
joren/recipes
app/models/recipe.rb
Ruby
mit
498
class AddRailSafetyFeatures < ActiveRecord::DataMigration def up [ {name: 'Event Data Recorders', description: 'Report the total number of fleet vehicles equipped with event data recorders according to IEEE 1482.1 standard.', active: true}, {name: 'Emergency Lighting', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for emergency lighting specified by APTA RT-S-VIM-20-10 standard.', active: true}, {name: 'Emergency Signage', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for the design of emergency signage specified by APTA RT-S-VIM021-10 standard.', active: true}, {name: 'Emergency Path Marking', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for low-location exit path marking specified by APTA RT-S-VIM-022- 10 standard.', active: true} ].each do |safety_feature| RailSafetyFeature.create!(safety_feature) end end end
camsys/transam_transit
db/data_migrations/20200528175309_add_rail_safety_features.rb
Ruby
mit
1,076
(function () { 'use strict'; angular.module('AngularPanelsApp.theme') .directive('trackWidth', trackWidth); /** @ngInject */ function trackWidth() { return { scope: { trackWidth: '=', minWidth: '=', }, link: function (scope, element) { scope.trackWidth = $(element).width() < scope.minWidth; scope.prevTrackWidth = scope.trackWidth; $(window).resize(function() { var trackWidth = $(element).width() < scope.minWidth; if (trackWidth !== scope.prevTrackWidth) { scope.$apply(function() { scope.trackWidth = trackWidth; }); } scope.prevTrackWidth = trackWidth; }); } }; } })();
mauroBus/angular-panels-app
src/app/theme/directives/trackWidth.js
JavaScript
mit
752
import { DynamoStore } from '@shiftcoders/dynamo-easy' import { Person } from '../models' const objectToPut: Person = { id: 'vogelsw', name: 'Werner Hans Peter Vogels', yearOfBirth: 1958, } // object literal or new Person(...) new DynamoStore(Person) .put(objectToPut) .ifNotExists() .exec() .then(() => console.log('done'))
shiftcode/dynamo-easy
snippets/store-requests/put.snippet.ts
TypeScript
mit
341
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * SDialogRepDpsList.java * * Created on 11/08/2010, 10:49:56 AM */ package erp.mtrn.form; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.lib.SLibTimeUtilities; import erp.lib.SLibUtilities; import erp.lib.form.SFormComponentItem; import erp.lib.form.SFormField; import erp.lib.form.SFormUtilities; import erp.lib.form.SFormValidation; import erp.mod.SModConsts; import erp.mod.cfg.db.SDbShift; import erp.mtrn.data.STrnFunctionalAreaUtils; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Map; import java.util.Vector; import javax.swing.AbstractAction; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; import sa.lib.SLibTimeUtils; import sa.lib.SLibUtils; /** * * @author Alfonso Flores, Claudio Peña, Edwin Carmona, Sergio Flores */ public class SDialogRepDpsList extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener { private int mnFormType; private int mnFormResult; private int mnFormStatus; private boolean mbFirstTime; private boolean mbResetingForm; private java.util.Vector<erp.lib.form.SFormField> mvFields; private erp.client.SClientInterface miClient; private erp.lib.form.SFormField moFieldDateInitial; private erp.lib.form.SFormField moFieldDateEnd; private erp.lib.form.SFormField moFieldCompanyBranch; private erp.lib.form.SFormField moFieldBizPartner; private erp.lib.form.SFormField moFieldShift; private boolean mbParamIsSupplier; private erp.mtrn.form.SDialogFilterFunctionalArea moDialogFilterFunctionalArea; private int mnFunctionalAreaId; private String msFunctionalAreasIds; /** Creates new form SDialogRepDpsList * @param client GUI client. */ public SDialogRepDpsList(erp.client.SClientInterface client) { super(client.getFrame(), true); miClient = client; initComponents(); initComponentsExtra(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jbPrint = new javax.swing.JButton(); jbExit = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jlDateInitial = new javax.swing.JLabel(); jftDateInitial = new javax.swing.JFormattedTextField(); jbDateInitial = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jlDateEnd = new javax.swing.JLabel(); jftDateEnd = new javax.swing.JFormattedTextField(); jbDateEnd = new javax.swing.JButton(); jPanel6 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jPanel8 = new javax.swing.JPanel(); jlCompanyBranch = new javax.swing.JLabel(); jcbCompanyBranch = new javax.swing.JComboBox(); jPanel9 = new javax.swing.JPanel(); jlBizPartner = new javax.swing.JLabel(); jcbBizPartner = new javax.swing.JComboBox<>(); jPanel10 = new javax.swing.JPanel(); jlShift = new javax.swing.JLabel(); jcbShift = new javax.swing.JComboBox<>(); jPanel11 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jckWithoutRelatedParty = new javax.swing.JCheckBox(); jPanel12 = new javax.swing.JPanel(); jlBizPartner1 = new javax.swing.JLabel(); jtfFunctionalArea = new javax.swing.JTextField(); jbFunctionalArea = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Listado de facturas de clientes"); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setPreferredSize(new java.awt.Dimension(392, 33)); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); jbPrint.setText("Imprimir"); jbPrint.setToolTipText("[Ctrl + Enter]"); jbPrint.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel1.add(jbPrint); jbExit.setText("Cerrar"); jbExit.setToolTipText("[Escape]"); jbExit.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel1.add(jbExit); getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuración del reporte:")); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Período:")); jPanel3.setPreferredSize(new java.awt.Dimension(376, 77)); jPanel3.setLayout(new java.awt.GridLayout(2, 1, 0, 1)); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateInitial.setText("Fecha inicial: *"); jlDateInitial.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel4.add(jlDateInitial); jftDateInitial.setText("dd/mm/yyyy"); jftDateInitial.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel4.add(jftDateInitial); jbDateInitial.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N jbDateInitial.setToolTipText("Seleccionar fecha inicial"); jbDateInitial.setFocusable(false); jbDateInitial.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel4.add(jbDateInitial); jPanel3.add(jPanel4); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateEnd.setText("Fecha final: *"); jlDateEnd.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel5.add(jlDateEnd); jftDateEnd.setText("dd/mm/yyyy"); jftDateEnd.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel5.add(jftDateEnd); jbDateEnd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N jbDateEnd.setToolTipText("Seleccionar fecha final"); jbDateEnd.setFocusable(false); jbDateEnd.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel5.add(jbDateEnd); jPanel3.add(jPanel5); jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros del reporte:")); jPanel6.setLayout(new java.awt.BorderLayout()); jPanel7.setLayout(new java.awt.GridLayout(5, 1, 0, 1)); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCompanyBranch.setText("Sucursal de la empresa:"); jlCompanyBranch.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel8.add(jlCompanyBranch); jcbCompanyBranch.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel8.add(jcbCompanyBranch); jPanel7.add(jPanel8); jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlBizPartner.setText("Cliente:"); jlBizPartner.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel9.add(jlBizPartner); jcbBizPartner.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jcbBizPartner.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel9.add(jcbBizPartner); jPanel7.add(jPanel9); jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlShift.setText("Turno:"); jlShift.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel10.add(jlShift); jcbShift.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jcbShift.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel10.add(jcbShift); jPanel7.add(jPanel10); jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0)); jLabel1.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel11.add(jLabel1); jckWithoutRelatedParty.setText("Sin partes relacionadas"); jPanel11.add(jckWithoutRelatedParty); jPanel7.add(jPanel11); jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlBizPartner1.setText("Área funcional:"); jlBizPartner1.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel12.add(jlBizPartner1); jtfFunctionalArea.setEditable(false); jtfFunctionalArea.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel12.add(jtfFunctionalArea); jbFunctionalArea.setText("..."); jbFunctionalArea.setToolTipText("Seleccionar asociado de negocios:"); jbFunctionalArea.setFocusable(false); jbFunctionalArea.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel12.add(jbFunctionalArea); jPanel7.add(jPanel12); jPanel6.add(jPanel7, java.awt.BorderLayout.NORTH); jPanel2.add(jPanel6, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER); setSize(new java.awt.Dimension(496, 339)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated windowActivated(); }//GEN-LAST:event_formWindowActivated private void initComponentsExtra() { mvFields = new Vector<>(); moFieldDateInitial = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDateInitial, jlDateInitial); moFieldDateInitial.setPickerButton(jbDateInitial); moFieldDateEnd = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDateEnd, jlDateEnd); moFieldDateEnd.setPickerButton(jbDateEnd); moFieldCompanyBranch = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbCompanyBranch, jlCompanyBranch); moFieldBizPartner = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbBizPartner, jlBizPartner); moFieldShift = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbShift, jlShift); mvFields.add(moFieldDateInitial); mvFields.add(moFieldDateEnd); mvFields.add(moFieldCompanyBranch); mvFields.add(moFieldBizPartner); mvFields.add(moFieldShift); jbPrint.addActionListener(this); jbExit.addActionListener(this); jbDateInitial.addActionListener(this); jbDateEnd.addActionListener(this); jbFunctionalArea.addActionListener(this); AbstractAction actionOk = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionPrint(); } }; SFormUtilities.putActionMap(getRootPane(), actionOk, "print", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK); AbstractAction action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionClose(); } }; SFormUtilities.putActionMap(getRootPane(), action, "exit", KeyEvent.VK_ESCAPE, 0); setModalityType(ModalityType.MODELESS); // áreas funcionales: jbFunctionalArea.setEnabled(miClient.getSessionXXX().getParamsCompany().getIsFunctionalAreas()); mnFunctionalAreaId = SLibConstants.UNDEFINED; moDialogFilterFunctionalArea = new SDialogFilterFunctionalArea(miClient); renderFunctionalArea(); } private void windowActivated() { if (mbFirstTime) { mbFirstTime = false; if (mbParamIsSupplier) { setTitle("Listado de facturas de proveedores"); jlBizPartner.setText("Proveedor:"); } else { setTitle("Listado de facturas de clientes"); jlBizPartner.setText("Cliente:"); } jftDateInitial.requestFocus(); } } private void actionPrint() { Cursor cursor = getCursor(); SFormValidation validation = formValidate(); Map<String, Object> map = null; JasperPrint jasperPrint = null; JasperViewer jasperViewer = null; String areasFilter = ""; if (miClient.getSessionXXX().getParamsCompany().getIsFunctionalAreas()) { if (msFunctionalAreasIds.isEmpty()) { areasFilter = ""; } else { areasFilter = " AND d.fid_func IN ( " + msFunctionalAreasIds + " ) "; } } if (validation.getIsError()) { if (validation.getComponent() != null) { validation.getComponent().requestFocus(); } if (validation.getMessage().length() > 0) { miClient.showMsgBoxWarning(validation.getMessage()); } } else { try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); map = miClient.createReportParams(); map.put("tDtInitial", moFieldDateInitial.getDate()); map.put("tDtEnd", moFieldDateEnd.getDate()); map.put("sCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "(TODAS)" : jcbCompanyBranch.getSelectedItem().toString()); map.put("nFidCtRef", mbParamIsSupplier ? SDataConstantsSys.BPSS_CT_BP_SUP : SDataConstantsSys.BPSS_CT_BP_CUS); map.put("nFidCtDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[0] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[0]); map.put("nFidClDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[1] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[1]); map.put("nFidTpDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[2] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[2]); map.put("sSqlWhereCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "" : " AND d.fid_cob = " + moFieldCompanyBranch.getKeyAsIntArray()[0]); map.put("sSqlWhereBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "" : " AND d.fid_bp_r = " + moFieldBizPartner.getKeyAsIntArray()[0]); map.put("sSqlWhereWithoutRelatedParty", jckWithoutRelatedParty.isSelected() ? " AND b.b_att_rel_pty = 0 " : ""); map.put("sTitle", mbParamIsSupplier ? " DE PROVEEDORES" : " DE CLIENTES"); map.put("sLocalCurrency", miClient.getSessionXXX().getParamsErp().getDbmsDataCurrency().getCurrency()); map.put("sBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "(TODOS)" : jcbBizPartner.getSelectedItem().toString()); map.put("nFidStDps", SDataConstantsSys.TRNS_ST_DPS_EMITED); map.put("nFidStDpsVal", SDataConstantsSys.TRNS_ST_DPS_VAL_EFF); map.put("nIdCurrencyLocal", miClient.getSessionXXX().getParamsErp().getFkCurrencyId()); map.put("sMark", mbParamIsSupplier ? "" : SDataConstantsSys.TXT_UNSIGNED); String sqlWhereTurn = ""; if (jcbShift.getSelectedIndex() > 0) { SDbShift shift = (SDbShift) miClient.getSession().readRegistry(SModConsts.CFGU_SHIFT, moFieldShift.getKeyAsIntArray()); if (shift.getTimeStart().before(shift.getTimeEnd())) { sqlWhereTurn += "AND (TIME(d.ts_new) BETWEEN '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "' AND '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "') "; } else { sqlWhereTurn += "AND (" + "(d.dt = '" + SLibUtils.DbmsDateFormatDate.format(moFieldDateInitial.getDate()) + "' AND TIME(d.ts_new) >= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "') OR " + "(d.dt = '" + SLibUtils.DbmsDateFormatDate.format(moFieldDateEnd.getDate()) + "' AND TIME(d.ts_new) <= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "') OR " + "(d.dt BETWEEN '" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.addDate(moFieldDateInitial.getDate(), 0, 0, 1)) + "' AND '" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.addDate(moFieldDateEnd.getDate(), 0, 0, -1)) + "' AND (" + "TIME(d.ts_new) >= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "' OR TIME(d.ts_new) <= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "'))) "; } } map.put("sTurn", jcbShift.getSelectedIndex() <= 0 ? "" : jcbShift.getSelectedItem().toString()); map.put("sFuncText", jtfFunctionalArea.getText()); map.put("sFilterFunctionalArea", areasFilter); map.put("sSqlWhereTurn", sqlWhereTurn); jasperPrint = SDataUtilities.fillReport(miClient, SDataConstantsSys.REP_TRN_DPS_LIST, map); jasperViewer = new JasperViewer(jasperPrint, false); jasperViewer.setTitle("Listado de facturas de " + (mbParamIsSupplier ? "proveedores" : "clientes")); jasperViewer.setVisible(true); } catch(Exception e) { SLibUtilities.renderException(this, e); } finally { setCursor(cursor); } } } private void actionClose() { mnFormResult = SLibConstants.FORM_RESULT_CANCEL; setVisible(false); } private void actionDateInitial() { miClient.getGuiDatePickerXXX().formReset(); miClient.getGuiDatePickerXXX().setDate(moFieldDateInitial.getDate()); miClient.getGuiDatePickerXXX().setVisible(true); if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) { moFieldDateInitial.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate()); jftDateInitial.requestFocus(); } } private void actionDateEnd() { miClient.getGuiDatePickerXXX().formReset(); miClient.getGuiDatePickerXXX().setDate(moFieldDateEnd.getDate()); miClient.getGuiDatePickerXXX().setVisible(true); if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) { moFieldDateEnd.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate()); jftDateEnd.requestFocus(); } } private void actionFunctionalArea() { moDialogFilterFunctionalArea.formRefreshCatalogues(); moDialogFilterFunctionalArea.formReset(); moDialogFilterFunctionalArea.setFunctionalAreaId(mnFunctionalAreaId); moDialogFilterFunctionalArea.setFormVisible(true); if (moDialogFilterFunctionalArea.getFormResult() == erp.lib.SLibConstants.FORM_RESULT_OK) { mnFunctionalAreaId = moDialogFilterFunctionalArea.getFunctionalAreaId(); renderFunctionalArea(); } } private void renderFunctionalArea() { String texts[] = STrnFunctionalAreaUtils.getTextFilterOfFunctionalAreas(miClient, mnFunctionalAreaId); msFunctionalAreasIds = texts[0]; jtfFunctionalArea.setText(texts[1]); jtfFunctionalArea.setCaretPosition(0); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JButton jbDateEnd; private javax.swing.JButton jbDateInitial; private javax.swing.JButton jbExit; private javax.swing.JButton jbFunctionalArea; private javax.swing.JButton jbPrint; private javax.swing.JComboBox<SFormComponentItem> jcbBizPartner; private javax.swing.JComboBox<SFormComponentItem> jcbCompanyBranch; private javax.swing.JComboBox<SFormComponentItem> jcbShift; private javax.swing.JCheckBox jckWithoutRelatedParty; private javax.swing.JFormattedTextField jftDateEnd; private javax.swing.JFormattedTextField jftDateInitial; private javax.swing.JLabel jlBizPartner; private javax.swing.JLabel jlBizPartner1; private javax.swing.JLabel jlCompanyBranch; private javax.swing.JLabel jlDateEnd; private javax.swing.JLabel jlDateInitial; private javax.swing.JLabel jlShift; private javax.swing.JTextField jtfFunctionalArea; // End of variables declaration//GEN-END:variables @Override public void formClearRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void formReset() { mnFormResult = SLibConstants.UNDEFINED; mnFormStatus = SLibConstants.UNDEFINED; mbFirstTime = true; for (int i = 0; i < mvFields.size(); i++) { ((erp.lib.form.SFormField) mvFields.get(i)).resetField(); } moFieldDateInitial.setFieldValue(SLibTimeUtilities.getBeginOfMonth(miClient.getSessionXXX().getWorkingDate())); moFieldDateEnd.setFieldValue(SLibTimeUtilities.getEndOfMonth(miClient.getSessionXXX().getWorkingDate())); jckWithoutRelatedParty.setSelected(false); } @Override public void formRefreshCatalogues() { SFormUtilities.populateComboBox(miClient, jcbCompanyBranch, SDataConstants.BPSU_BPB, new int[] { miClient.getSessionXXX().getCurrentCompany().getPkCompanyId() }); SFormUtilities.populateComboBox(miClient, jcbBizPartner, mbParamIsSupplier ? SDataConstants.BPSX_BP_SUP : SDataConstants.BPSX_BP_CUS); SFormUtilities.populateComboBox(miClient, jcbShift, SDataConstants.CFGU_SHIFT); } @Override public erp.lib.form.SFormValidation formValidate() { SFormValidation validation = new SFormValidation(); for (int i = 0; i < mvFields.size(); i++) { if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) { validation.setIsError(true); validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent()); break; } } if (!validation.getIsError()) { if (moFieldDateEnd.getDate().compareTo(moFieldDateInitial.getDate()) < 0) { validation.setMessage("La fecha final debe ser mayor o igual a la fecha inicial."); validation.setComponent(jftDateEnd); } } return validation; } @Override public void setFormStatus(int status) { mnFormStatus = status; } @Override public void setFormVisible(boolean visible) { setVisible(visible); } @Override public int getFormStatus() { return mnFormStatus; } @Override public int getFormResult() { return mnFormResult; } @Override public void setRegistry(erp.lib.data.SDataRegistry registry) { throw new UnsupportedOperationException("Not supported yet."); } @Override public erp.lib.data.SDataRegistry getRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setValue(int type, java.lang.Object value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public java.lang.Object getValue(int type) { throw new UnsupportedOperationException("Not supported yet."); } @Override public javax.swing.JLabel getTimeoutLabel() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() instanceof javax.swing.JButton) { javax.swing.JButton button = (javax.swing.JButton) e.getSource(); if (button == jbPrint) { actionPrint(); } else if (button == jbExit) { actionClose(); } else if (button == jbDateInitial) { actionDateInitial(); } else if (button == jbDateEnd) { actionDateEnd(); } else if (button == jbFunctionalArea) { actionFunctionalArea(); } } } public void setParamIsSupplier(boolean b) { mbParamIsSupplier = b; } }
swaplicado/siie32
src/erp/mtrn/form/SDialogRepDpsList.java
Java
mit
25,545
<?php return array( 'controllers' => array( 'factories' => array( \Saas\Controller\Frontend\SaasController::class => \Saas\Controller\Frontend\SaasControllerFactory::class, ), ), 'bjyauthorize' => array( 'guards' => array( 'BjyAuthorize\Guard\Controller' => array( array('controller' => \Saas\Controller\Frontend\SaasController::class, 'roles' => array('guest', 'user')), ), ), ), 'router' => array( 'routes' => array( 'frontend' => array( 'child_routes' => array( 'saas' => array( 'type' => 'Segment', 'options' => array( 'route' => '{saas}', 'defaults' => array( 'controller' => \Saas\Controller\Frontend\SaasController::class, 'action' => 'register', 'title' => 'Playground - Register' ) ) ), ) ) ) ) );
gregorybesson/playground
module/Saas/config/module.config.php
PHP
mit
1,171
#### # # This module allows for easy integration with Slack (https://slack.com/). The # messages are sent via JSON over plaintext, so don't use them for transmitting # anything sensitive. # #### ## Imports import json import urllib2 #### # # API Description # # These are all of the Slack API fields supported in this module. supported_fields = [ # The content of the message. This can be plaintext or Markdown text. 'text', # The name of the bot posting hte webhook integration message. 'username', # The link to an image for the bot's avatar. 'icon_url', # An emoji to use as the bot's image. Overrides 'icon_url'. 'icon_emoji', # Where to post the message. 'channel', # Whether to allow Markdown formatting in the 'text' field. 'mrkdwn', # A list of attachments. 'attachments' ] # These fields are supported as 'attachments' subfields. supported_attachments_subfields = [ # The title of the attachment. 'title', # The pretext. 'pretext', # The actual text. 'text', # Where to allow Markdown. Valid options are: ["pretext", "text", "fields"]. 'mrkdwn_in' ] class IncomingWebhooksSender(object): """ The IncomingWebhooksSender is an object to facilitate using a bot to post to the Slack team communication platform. Slack defines an API of available calls for "incoming webhooks" here: https://api.slack.com/incoming-webhooks This implementation is meant to be fully-featured, but also provides high- level methods that abstract away most of the configuration to make use in scripts easier. (Plus it's easier to read and document.) """ def __init__(self, integration_url, bot_name=None, icon_url=None, icon_emoji=None, channel=None, markdown=None): """ Creates a IncomingWebhooksSender object to send messages to a given Slack team. :param integration_url: The incoming webhook integration URL. This must be supplied at creation (or else the bot is useless). :param bot_name: The name the bot will use when posting. :param icon_url: A URL to use as the bot's icon. :param icon_emoji: A colon emoji to use as the bot's icon. This overrides 'icon_url'. :param channel: The default channel for this bot to post to. :param markdown: Whether to allow markdown (defaults to True if not specified). """ self.url = integration_url self.username = bot_name self.icon_url = icon_url self.icon_emoji = icon_emoji self.channel = channel self.mrkdwn = markdown # Check if the channel has a '#' or '@' at the beginning. If not, # throw an error. if not self.username and self.username is not None: raise ValueError("Null username specified.") if not self.channel and self.channel is not None: raise ValueError("Null channel specified.") if (channel is not None and not self.channel.startswith('#') and not self.channel.startswith('@')): raise ValueError( "Invalid channel. Need a '#' for channels or '@' for direct " + "messages." ) ############################################################################ # Public methods. def send_message(self, message): """ Sends a message to the default channel for this webhook (which is determined by the URL passed in during object construction). :param message: Message text you want to send. """ data = {'text': str(message)} self.__prep_and_send_data(data) def success(self, message=None): """ Sends a check mark with a message (if desired). :param message: An optional string to include. """ send_message = ":white_check_mark:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) def warning(self, message=None): """ Sends a yellow warning sign with a message (if desired). :param message: An optional string to include. """ send_message = ":warning:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) warn = warning def error(self, message=None): """ Sends a red circle with a message (if desired). :param message: An optional string to include. """ send_message = ":red_circle:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) critical = error def send_message_to_channel(self, message, channel): """ Sends a message to a specific channel. Use '#' for channels and private groups, and '@' for direct messages. For example: #general #my-private-group @someguy :param message: Message text you want to send. :param channel: The channel to which you want to send the data. """ data = { 'text': str(message), 'channel': channel } self.__prep_and_send_data(data) def send_dictionary(self, dictionary): """ Takes any dictionary and sends it through. It will be verified first, so the dictionary must only use the available fields in the Slack API. Note that with this method, you can send any message with any name to any channel, et cetera. :param dictionary: A dictionary of values you want to send. """ self.__prep_and_send_data(dictionary) ############################################################################ # Private methods. def __prep_and_send_data(self, data): """ Takes a dictionary and prepares it for transmission, then sends it. :param data: A map of Slack API fields to desired values. :type data: dict """ data = self.__update_data(data) self.__send_json(self.__prep_json_from_data(data)) def __update_data(self, data): """ Automatically updates the contents of the 'data' object with any fields that are set in the object but weren't specified in the data. This makes method calls simpler. This method will also verify the data in the dictionary. :param data: A map of Slack API fields to desired values. :type data: dict :returns: A copy of the `data` dictionary, but with extra values if they were specified in the object constructor. """ # Duplicate the data to make this method non-destructive. return_data = dict(data) # Iterate over each of the supported fields. for field in supported_fields: # Let's see if we have a value defined for that attribute. # Note that this requires the object's attributes to have the same # name as the Slack API fields. try: value = getattr(self, field) except AttributeError: # Didn't have it, but let's not throw an error. Just continue. continue # If the field isn't already in the data, add it. # This ensure that overriding calls are not overridden themselves. if value is not None and not field in return_data: return_data[field] = value # Ensure the dictionary is good-to-go. self.__verify_data(data) return return_data def __verify_data(self, data): """ Verifies that all of the fields in the `data` dictionary are valid. If any field is found that isn't considered a supported field, an error is raised. This also checks inside the list of attachments (if it's present) to be sure nothing is wrong. :param data: A map of Slack API fields to desired values. :type data: dict """ # Check it's a dictionary. if not isinstance(data, dict): raise ValueError("Received a non-dictionary form of data.") # Iterate over every key. for key in data: # If the key isn't supported, that's a problem! if not key in supported_fields: raise ValueError("Bad key in data: {}".format(key)) # The 'attachments' key should contain a list. if key == 'attachments': # Verify it's really a list. if not isinstance(data[key], list): raise ValueError("'attachments' field in data must be a list.") # Ensure there are no rogue values. for subkey in data[key]: if not subkey in supported_attachments_subfields: raise ValueError("Bad key in 'attachments': {}".format(subkey)) def __prep_json_from_data(self, data): """ Given data, this updates the contents and then gives back the string form of the JSON data. :param data: A map of Slack API fields to desired values. :type data: dict :returns: A string form of the dictionary. """ # Update all the data. data = self.__update_data(data) # Return the JSON string form of the data. return self.__get_json_from_data(data) def __get_json_from_data(self, data): """ Just gives back a string form of the data. This is just a wrapper so the 'json' module doesn't have to be loaded in addition to this one. :param data: A map of Slack API fields to desired values. :type data: dict :returns: The string format returned by `json.dumps(data)`. """ return json.dumps(data) def __send_json(self, data): """ Sends the given JSON data across an HTTP connection. This does not check if the data is valid. This is by design to ensure that if I ever mess something up with the `supported_fields` list or something, the object can still be used to send anything. :param data: JSON representation of a map of Slack API fields to desired values. :type data: str """ # Form the HTTP PUT request. request = urllib2.Request(self.url, data) # Send the data! urllib2.urlopen(request)
univ-of-utah-marriott-library-apple/management_tools
management_tools/slack.py
Python
mit
10,760
function testRequest(place) { //Pebble.sendAppMessage({"status": "Initiated"}); var req = new XMLHttpRequest(); req.open('GET', 'http://maps.googleapis.com/maps/api/geocode/json?address='+ place + '&sensor=false', true); req.onload = function(e) { if (req.readyState == 4 && req.status == 200) { //readystate 4 is DONE //status 200 is OK if(req.status == 200) { var response = JSON.parse(req.responseText); console.log(req.responseText); var location = response.results[0].formatted_address; //var icon = response.list[0].main.icon; //Pebble.sendAppMessage({'status': stat, 'message':'test completed'}); Pebble.sendAppMessage({"status": "Processed","location":location}); } else { console.log('Error'); Pebble.sendAppMessage({"status": "Error"}); } } }; req.send(null); } function testRequestTime() { Pebble.sendAppMessage({"status": "Initiated"}); var req = new XMLHttpRequest(); req.open('GET', 'https://maps.googleapis.com/maps/api/timezone/json?location=59,10&timestamp=360000000&sensor=false', true); req.onload = function(e) { if (req.readyState == 4 && req.status == 200) { //readystate 4 is DONE //status 200 is OK if(req.status == 200) { var response = JSON.parse(req.responseText); console.log(req.responseText); var rawOffset = response.rawOffset; var dstOffset = response.dstOffset; var totOffset = rawOffset+dstOffset; //var icon = response.list[0].main.icon; //Pebble.sendAppMessage({'status': stat, 'message':'test completed'}); Pebble.sendAppMessage({"status": "Processed","offset":totOffset}); } else { console.log('Error'); Pebble.sendAppMessage({"status": "Error"}); } } }; req.send(null); } function makeRequest(method, url, callback) { var req = new XMLHttpRequest(); req.open(method, url, true); req.onload = function(e) { if(req.readyState == 4) { callback(req); } }; req.send(null); } function getOffset(lat,lon){ var timestamp = new Date() / 1000 | 0; makeRequest('GET', 'https://maps.googleapis.com/maps/api/timezone/json?location='lat+','+lon+'timestamp='+timestamp+'&sensor=false', true,my_callback2); } function getLocation(place){ makeRequest('GET','http://maps.googleapis.com/maps/api/geocode/json?address='+ place +'&sensor=false',my_callback1); } // Function to send a message to the Pebble using AppMessage API function sendMessage() { //Pebble.sendAppMessage({"status": 0}); //testRequest(); //testRequestTime(); // PRO TIP: If you are sending more than one message, or a complex set of messages, // it is important that you setup an ackHandler and a nackHandler and call // Pebble.sendAppMessage({ /* Message here */ }, ackHandler, nackHandler), which // will designate the ackHandler and nackHandler that will be called upon the Pebble // ack-ing or nack-ing the message you just sent. The specified nackHandler will // also be called if your message send attempt times out. } // Called when JS is ready Pebble.addEventListener("ready", function(e) { }); // Called when incoming message from the Pebble is received Pebble.addEventListener("appmessage", function(e) { console.log("Received Status: " + e.payload.status); testRequest(e.payload.place); });
alin256/MultiZoneNew
src/pkjs/js/pebble-js-app.js
JavaScript
mit
3,399
version https://git-lfs.github.com/spec/v1 oid sha256:91f5e00183c2613cc249e316de2c35c08d8068c7e57cf90d3d4ea7b0179ef7cf size 651743
yogeshsaroya/new-cdnjs
ajax/libs/yasgui/0.0.6/yasgui.min.js
JavaScript
mit
131
<?php namespace Alloparty\UserBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('alloparty_user'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
ybert/alloparty
src/Alloparty/UserBundle/DependencyInjection/Configuration.php
PHP
mit
883
'use strict'; const inView = require('in-view'); const forEach = require('lodash/forEach'); require('gsap'); class Animations { constructor () { this.root = document; this.h1 = this.root.querySelector('[data-hat-title] h1'); this.curtainH1 = this.root.querySelector('[data-curtain-goRight]'); this.goUps = this.root.querySelectorAll('[data-stagger-goUp]'); this.skillsItems = this.root.querySelectorAll('[data-skills-item]'); this.experienceP = this.root.querySelectorAll('[data-experience-container]'); this.portfolioItems = this.root.querySelectorAll('[data-portfolio-item]'); this.map = this.root.querySelector('[data-map]'); this.travelsDescription = this.root.querySelector('[data-travels-p]'); this.contactContainer = this.root.querySelector('[data-contact-container]'); this.animationStarted = false; this.textSpanned = false; } } Animations.prototype.init = function () { if(this.animationStarted) { return; } this.setup(); window.setTimeout(this.animateH1.bind(this), 1000); this.addListenerDescription(); this.addListenerSkillsH2(); this.addListenerExperienceH2(); this.addListenerTravelsH2(); this.addListenerPortfolioH2(); this.addListenerContactH2(); this.triggerResize(); this.animationStarted = true; }; Animations.prototype.setup = function () { TweenMax.set(this.skillsItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.travelsDescription, {opacity: 0}); TweenMax.set(this.map, {opacity: 0}); TweenMax.set(this.experienceP, {opacity: 0}); TweenMax.set(this.portfolioItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.contactContainer, {opacity: 0, yPercent: 100}); this.h2ToBeSpanned = this.root.querySelectorAll('[data-to-be-spanned]'); forEach(this.h2ToBeSpanned, function (title) { let titleMod = title.innerText.split(''); let tmparray = []; forEach(titleMod, function (letter, index) { tmparray[index] = '<span class="letter-box" data-letter-box>' + letter + '</span>'; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = true; }; Animations.prototype.triggerResize = function () { window.dispatchEvent(new Event('resize')); }; Animations.prototype.animateH1 = function () { const spans = this.h1.querySelectorAll('span'); const tl = new TimelineLite({onComplete: this.afterH1.bind(this)}); tl.to(this.curtainH1, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(this.h1, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.curtainH1, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(spans, 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterH1 = function () { this.curtainH1.remove(); TweenMax.staggerTo(this.goUps, .22, {yPercent: -100, opacity: 1, onComplete: this.animateMenu.bind(this) }, .11); }; Animations.prototype.animateMenu = function () { const links = this.root.querySelectorAll('[data-audio-play]'); TweenMax.staggerTo(links, .21, {opacity: 1, yPercent: 100, delay: .66}, .08); }; Animations.prototype.addListenerDescription = function () { inView('[data-description]') .once('enter', function(el) { el.style.opacity = 1; }.bind(this)); }; //Skills Animations.prototype.addListenerSkillsH2 = function () { inView('[data-skills]') .once('enter', function(el){ this.animateSkillsH2(el); }.bind(this)); }; Animations.prototype.animateSkillsH2 = function (el) { const titleH2 = el.querySelector('[data-skills-title] h2'); this.skillsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterSkillsH2.bind(this)}); tl.to(this.skillsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.skillsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterSkillsH2 = function () { this.skillsCurtainH2.remove(); this.animateSkillsItems(); }; Animations.prototype.animateSkillsItems = function (el) { TweenMax.staggerTo(this.skillsItems, .41, {opacity: 1, yPercent: 0, delay: .55}, .18); }; //Experience Animations.prototype.addListenerExperienceH2 = function () { inView('[data-experience]') .once('enter', function(el){ this.animateExperienceH2(el); }.bind(this)); }; Animations.prototype.animateExperienceH2 = function (el) { const titleH2 = el.querySelector('[data-experience-title] h2'); this.experienceCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterExperienceH2.bind(this)}); tl.to(this.experienceCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.experienceCurtainH2, .66, {xPercent: 203, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterExperienceH2 = function () { this.experienceCurtainH2.remove(); TweenMax.to(this.experienceP, 1, {opacity: 1, ease: Power3.easeIn}); } //Travels Animations.prototype.addListenerTravelsH2 = function () { inView('[data-travels]') .once('enter', function(el) { this.animateTravelsH2(el); }.bind(this)); }; Animations.prototype.animateTravelsH2 = function (el) { const titleH2 = el.querySelector('[data-travels-title] h2'); this.arrows = document.getElementById('freccette'); this.travelsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterTravelsH2.bind(this)}); tl.to(this.travelsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.travelsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterTravelsH2 = function () { this.travelsCurtainH2.remove(); TweenMax.to(this.map, .33, {opacity: 1}); this.arrows.classList.add('visible'); TweenMax.to(this.travelsDescription, .44, {opacity: 1, ease: Power3.easeOut}); }; //Portfolio Animations.prototype.addListenerPortfolioH2 = function () { inView('[data-portfolio]') .once('enter', function(el) { this.animatePortfolioH2(el); }.bind(this)); }; Animations.prototype.animatePortfolioH2 = function (el) { const titleH2 = el.querySelector('[data-portfolio-title] h2'); this.portfolioCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterPortfolioH2.bind(this)}); tl.to(this.portfolioCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.portfolioCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterPortfolioH2 = function () { this.portfolioCurtainH2.remove(); this.animatePortfolioItems(); }; Animations.prototype.animatePortfolioItems = function (el) { TweenMax.staggerTo(this.portfolioItems, .88, {opacity: 1, yPercent: 0, ease: Power3.easeOut}, .28); }; //Contact Animations.prototype.addListenerContactH2 = function () { inView('[data-contact]') .once('enter', function(el) { this.animateContactH2(el); }.bind(this)); }; Animations.prototype.animateContactH2 = function (el) { const titleH2 = el.querySelector('[data-contact-title] h2'); this.contactCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterContactH2.bind(this)}); tl.to(this.contactCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.contactCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterContactH2 = function () { this.contactCurtainH2.remove(); TweenMax.to(this.contactContainer, .33, {opacity: 1, yPercent: 0}); }; Animations.prototype.destroy = function () { TweenMax.set(this.skillsItems, {clearProps: 'all'}); TweenMax.set(this.portfolioItems, {clearProps: 'all'}); TweenMax.set(this.map, {clearProps: 'all'}); TweenMax.set(this.experienceP, {clearProps: 'all'}); if(this.textSpanned) { this.clearTextFromSpan(); } }; Animations.prototype.clearTextFromSpan = function () { forEach(this.h2ToBeSpanned, function (title) { let titleInner = title.querySelectorAll('[data-letter-box]'); let tmparray = []; forEach(titleInner, function(el, index){ tmparray[index] = el.innerText; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = false; }; module.exports = Animations;
dnlml/myvc
src/assets/scripts/parts/animations.js
JavaScript
mit
9,136
<?php namespace Quoty\QuoteBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Category * * @ORM\Table() * @ORM\Entity(repositoryClass="Quoty\QuoteBundle\Entity\CategoryRepository") */ class Category { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, unique=true) */ private $name; public function __construct($name = "Inconnu") { $this->name = $name; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Category */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } }
Elfhir/quoty
src/Quoty/QuoteBundle/Entity/Category.php
PHP
mit
903
"use strict"; var notify = require("gulp-notify"); module.exports = function(error) { if( !global.isProd ) { var args = Array.prototype.slice.call(arguments); // Send error to notification center with gulp-notify notify.onError({ title: "Compile Error", message: "<%= error.message %>" }).apply(this, args); // Keep gulp from hanging on this task this.emit("end"); } else { // Log the error and stop the process // to prevent broken code from building console.log(error); process.exit(1); } };
polygon-city/citygml-visual-debugger
gulp/util/handleErrors.js
JavaScript
mit
560
<?php namespace Olegf13\Jivochat\Webhooks\Request; use Olegf13\Jivochat\Webhooks\PopulateObjectViaArray; /** * Holds data on completed chatting (chat rank and messages list). * * @package Olegf13\Jivochat\Webhooks\Request */ class Chat { use PopulateObjectViaArray; /** * @var Message[] Messages list. See {@link Message} for details. * @todo: create MessageCollection with aggregated data (messages count, etc) */ public $messages; /** @var string|null User chat rank ("positive"|"negative"|null). */ public $rate; /** @var bool|null A sign that the user was added to the black list (e.g. false). */ public $blacklisted; // todo: add `chat_started_at` and `chat_ended_at` properties /** * Setter for {@link messages} property. * * @param array $messages * @throws \InvalidArgumentException */ public function setMessages(array $messages) { /** @var Agent $agent */ foreach ($messages as $data) { if (!is_array($data) && !($data instanceof Message)) { throw new \InvalidArgumentException('Invalid data given.'); } if (is_array($data)) { $message = new Message(); $message->populate($data); $this->messages[] = $message; continue; } if ($data instanceof Message) { $this->messages[] = $data; continue; } } } }
Olegf13/jivochat-webhooks-api
src/Request/Chat.php
PHP
mit
1,516
/* colorstrip.js, a plugin for jQuery Copyright (C) 2011 John Watson <john@flagrantdisregard.com> flagrantdisregard.com 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. */ (function($) { var colorstrip = new Object; var settings = { maxInterval: 8000, /* milliseconds */ minInterval: 4000, /* milliseconds */ opacity: 0.5, /* 0..1 */ minWidth: 10, /* percent */ maxWidth: 80, /* percent */ colors: ['#c00', '#0c0', '#00c'] }; var strips = []; var timeouts = []; colorstrip.start = function() { var s = colorstrip.target; for(var i=0; i<settings.colors.length; i++) { var e = $('<div>'); e.css( { height: '100%', width: '30%', position: 'absolute', top: 0, left: Math.random()*$(s).width(), opacity: settings.opacity, 'background-color': settings.colors[i] } ); strips.push(e); colorstrip.target.append(e); colorstrip.animate(e); } } colorstrip.animate = function(e) { if (e == undefined) return; var s = colorstrip.target; var n = strips.length; var left = $(e).position().left; var right = $(e).position().left + $(e).width(); $(e).stop(); if (left > $(s).width()) { $(e).css({left: -$(e).width(), 'z-index': Math.random()*n}); } if (right < 0) { $(e).css({left: $(s).width(), 'z-index': Math.random()*n}); } var range = $(s).width() + $(e).width(); var timeout = Math.random()*(settings.maxInterval-settings.minInterval)+settings.minInterval; $(e).animate( { left: Math.random()*range - $(e).width(), width: (Math.random()*(settings.maxWidth-settings.minWidth)+settings.minWidth) + '%' }, timeout, 'easeInOutSine'); timeouts.push(setTimeout(function(){colorstrip.animate(e)}, timeout)); } colorstrip.stop = function() { for(var i=0;i<timeouts.length;i++) { clearTimeout(timeouts[i]); } for(var i=0;i<strips.length;i++) { strips[i].stop(); } } $.fn.colorstrip = function(method, options) { if (typeof method == 'object') { $.extend(settings, method); } if (typeof options == 'object') { $.extend(settings, options); } if (colorstrip[method]) { colorstrip[method](); } else { colorstrip.target = this; colorstrip.start(); } } })(jQuery);
Overdriven-Labs/Mexicoen140
app_server/public/js/colorstrip.js
JavaScript
mit
3,808
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("K8055Simulator.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("K8055Simulator.Tests")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("886129f2-c575-429b-8727-20caade13d28")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bbartels/K8055Simulator
K8055Simulator.Tests/Properties/AssemblyInfo.cs
C#
mit
641
<?php defined('SYSPATH') OR die('No direct script access.'); return array( // Leave this alone 'modules' => array( // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' 'functest' => array( // Whether this modules userguide pages should be shown 'enabled' => TRUE, // The name that should show up on the userguide index page 'name' => 'Functiaonl Test', ) ) );
OpenBuildings/functest
config/userguide.php
PHP
mit
464
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using Komires.MataliPhysics; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Menu { Demo demo; PhysicsScene scene; string instanceIndexName; public Menu(Demo demo, int instanceIndex) { this.demo = demo; instanceIndexName = " " + instanceIndex.ToString(); } public void Initialize(PhysicsScene scene) { this.scene = scene; } public static void CreateShapes(Demo demo, PhysicsScene scene) { } public void Create() { Shape sphere = scene.Factory.ShapeManager.Find("Sphere"); Shape box = scene.Factory.ShapeManager.Find("Box"); Shape coneY = scene.Factory.ShapeManager.Find("ConeY"); PhysicsObject objectRoot = null; PhysicsObject objectBase = null; Constraint constraint = null; string switchInstanceName = null; Vector3 position1 = Vector3.Zero; Quaternion orientation1 = Quaternion.Identity; for (int i = 0; i < 5; i++) { switchInstanceName = "Switch " + i.ToString(); objectBase = scene.Factory.PhysicsObjectManager.Create(switchInstanceName + instanceIndexName); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-22.0f + 11.0f * i, 25.0f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 4.0f, 0.4f); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); } for (int i = 0; i < 5; i++) { switchInstanceName = "Switch " + (i + 5).ToString(); objectBase = scene.Factory.PhysicsObjectManager.Create(switchInstanceName + instanceIndexName); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-22.0f + 11.0f * i, 16.0f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 4.0f, 0.4f); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); } objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Right Light" + instanceIndexName); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(0.5f, 0.5f, 0.5f); objectBase.Light.Range = 20.0f; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(34.0f, 20.5f, 10.0f); objectBase.InitLocalTransform.SetScale(20.0f); objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Right" + instanceIndexName); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.UserDataStr = "Yellow"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(32.0f, 20.5f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 3.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-10.0f))); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create("Switch Right Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Right" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create("Switch Right Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Right" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Left Light" + instanceIndexName); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(0.5f, 0.5f, 0.5f); objectBase.Light.Range = 20.0f; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(-34.0f, 20.5f, 10.0f); objectBase.InitLocalTransform.SetScale(20.0f); objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Left" + instanceIndexName); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.UserDataStr = "Yellow"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-32.0f, 20.5f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 3.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(-90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(10.0f))); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create("Switch Left Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Left" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create("Switch Left Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Left" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); objectRoot = scene.Factory.PhysicsObjectManager.Create("Info" + instanceIndexName); objectRoot.EnableMoving = false; objectRoot.DrawPriority = 1; objectBase = scene.Factory.PhysicsObjectManager.Create("Info Description" + instanceIndexName); objectRoot.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.Material.SetAmbient(0.51f, 0.52f, 0.51f); objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(0.0f, -6.0f, 20.0f); objectBase.InitLocalTransform.SetScale(15.0f, 27.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f))); objectBase.Integral.SetDensity(1.0f); objectBase.EnableDrawing = false; objectBase.EnableCollisionResponse = false; objectBase.EnableMoving = false; objectBase = scene.Factory.PhysicsObjectManager.Create("Info Screen" + instanceIndexName); objectRoot.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(18.2f, 1.6f, 20.0f - 0.4f - 0.01f); objectBase.InitLocalTransform.SetScale(7.0f, 6.0f, 0.01f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableDrawing = false; objectBase.EnableCollisionResponse = false; objectBase.EnableMoving = false; scene.UpdateFromInitLocalTransform(objectRoot); } } }
stomppah/KAOS-Engine
Dependencies/MataliPhysicsBasic/MataliPhysicsOpenTK/Mono/MataliPhysicsDemo/MataliPhysicsDemo/Objects/Menu.cs
C#
mit
15,509
<?php // FrontendBundle:Pedido:reporteGeneral.html.twig return array ( 'b9ccb8c' => array ( 0 => array ( 0 => 'bundles/frontend/css/jquery.dataTables.css', ), 1 => array ( 0 => 'cssrewrite', ), 2 => array ( 'output' => '_controller/css/b9ccb8c.css', 'name' => 'b9ccb8c', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '1c983ea' => array ( 0 => array ( 0 => 'bundles/frontend/css/bootstrap.min.css', 1 => '@FrontendBundle/Resources/public/css/bootstrap-theme.min.css', 2 => '@FrontendBundle/Resources/public/css/main.css', ), 1 => array ( 0 => 'cssrewrite', ), 2 => array ( 'output' => '_controller/css/1c983ea.css', 'name' => '1c983ea', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '25d9041' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/jquery-1.10.2.js', 1 => '@FrontendBundle/Resources/public/js/main.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/25d9041.js', 'name' => '25d9041', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '0d49e82' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/css/jquery-ui-1.10.3.custom.min.css', ), 1 => array ( ), 2 => array ( 'output' => '_controller/css/0d49e82.css', 'name' => '0d49e82', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '3b8dad4' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/jquery.dataTables-1.9.4.min.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/3b8dad4.js', 'name' => '3b8dad4', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), 5114111 => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/bootstrap-3.0.0.min.js', 1 => '@FrontendBundle/Resources/public/js/jquery.dataTables-1.9.4.min.js', 2 => '@FrontendBundle/Resources/public/js/jquery.mixitup.min.js', 3 => '@FrontendBundle/Resources/public/js/jquery.scrollTo.min.js', 4 => '@FrontendBundle/Resources/public/js/modal.js', 5 => '@FrontendBundle/Resources/public/js/popover.js', 6 => '@FrontendBundle/Resources/public/js/button.js', 7 => '@FrontendBundle/Resources/public/js/jquery-ui-1.10.3.custom.min.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/5114111.js', 'name' => '5114111', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), );
pacordovad/project3
app/cache/dev/assetic/config/5/5ea803aa63bdc4efbcdc7be159654a7b.php
PHP
mit
2,903
asc.component('asc-combobox', function(){ this.afterInit = function (combobox) { var div = eDOM.el('div.dropdown-list'); while (combobox.children.length) { var item = combobox.children[0]; if (item.tagName === "ITEM") { item.innerText += item.getAttribute("text"); div.appendChild(item); } } combobox.appendChild(div); var innerText = eDOM.el('span'); var selectedValue = combobox.getAttribute("data-selected-value"); var previouslySelected; if (selectedValue) { for (var i = 0; i < div.children.length; i++) { var child = div.children[i]; if (child.getAttribute("value") === selectedValue) { child.classList.add('selected'); previouslySelected = child; innerText.innerHTML = child.getAttribute("text"); break; } } } if (innerText.innerHTML.length === 0) { innerText.innerHTML = combobox.getAttribute('data-placeholder'); } combobox.insertBefore(innerText, div); combobox.style.width = combobox.offsetWidth + "px"; div.style.width = (combobox.offsetWidth + 14) + "px"; var closeBackClick = function () { combobox.classList.remove('active'); document.body.removeEventListener('click', closeBackClick); }; combobox.addEventListener('click', function (e) { if (combobox.classList.contains('active')) { if (e.target.tagName === "ITEM") { previouslySelected.classList.remove('selected'); previouslySelected = e.target; e.target.classList.add('selected'); innerText.innerHTML = e.target.getAttribute("text"); combobox.setAttribute("data-selected-value", e.target.getAttribute("value")); } closeBackClick(); } else { combobox.classList.add('active'); setTimeout(function () { document.body.addEventListener('click', closeBackClick); }, 0); } }); } });
vestlirik/apple-style-controls
src/combobox/code.js
JavaScript
mit
2,304
package ic2.api.item; import net.minecraft.item.ItemStack; import java.util.ArrayList; import java.util.List; /** * Allows for charging, discharging and using electric items (IElectricItem). */ public final class ElectricItem { /** * IElectricItemManager to use for interacting with IElectricItem ItemStacks. * * This manager will act as a gateway and delegate the tasks to the final implementation * (rawManager or a custom one) as necessary. */ public static IElectricItemManager manager; /** * Standard IElectricItemManager implementation, only call it directly from another * IElectricItemManager. Use manager instead. */ public static IElectricItemManager rawManager; /** * Register an electric item manager for items not implementing IElectricItem. * * This method is only designed for special purposes, implementing IElectricItem or * ISpecialElectricItem instead of using this is faster. * * Managers used with ISpecialElectricItem shouldn't be registered. * * @param manager Manager to register. */ public static void registerBackupManager(IBackupElectricItemManager manager) { backupManagers.add(manager); } /** * Get the electric item manager suitable for the supplied item stack. * * This method is for internal use only. * * @param stack ItemStack to be handled. * @return First suitable electric item manager. */ public static IBackupElectricItemManager getBackupManager(ItemStack stack) { for (IBackupElectricItemManager manager : backupManagers) { if (manager.handles(stack)) return manager; } return null; } private static final List<IBackupElectricItemManager> backupManagers = new ArrayList<IBackupElectricItemManager>(); }
planetguy32/TurboCraftingTable
src/api/java/ic2/api/item/ElectricItem.java
Java
mit
1,731
package me.zhongmingmao.connection; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; public class ConnectionTest { private static final String HOST = "localhost"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST); Connection connection = factory.newConnection(); connection.close(); } }
zhongmingmao/rabbitmq_demo
basic-tutorial/src/main/java/me/zhongmingmao/connection/ConnectionTest.java
Java
mit
556
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("キャプチャされるのは変数という問題")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("キャプチャされるのは変数という問題")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("258b9e9a-bd47-499e-89e6-9550b66eba58")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
autumn009/TanoCSharpSamples
Chap2/キャプチャされるのは変数という問題/キャプチャされるのは変数という問題/Properties/AssemblyInfo.cs
C#
mit
1,748
require "spec_helper" describe ChunkyPNG::Datastream do describe ".from_io" do it "should raise an error when loading a file with a bad signature" do filename = resource_file("damaged_signature.png") expect { ChunkyPNG::Datastream.from_file(filename) }.to raise_error(ChunkyPNG::SignatureMismatch) end it "should raise an error if the CRC of a chunk is incorrect" do filename = resource_file("damaged_chunk.png") expect { ChunkyPNG::Datastream.from_file(filename) }.to raise_error(ChunkyPNG::CRCMismatch) end it "should raise an error for a stream that is too short" do stream = StringIO.new expect { ChunkyPNG::Datastream.from_io(stream) }.to raise_error(ChunkyPNG::SignatureMismatch) end it "should read a stream with trailing data without failing" do filename = resource_file("trailing_bytes_after_iend_chunk.png") image = ChunkyPNG::Datastream.from_file(filename) expect(image).to be_instance_of(ChunkyPNG::Datastream) end end describe "#metadata" do it "should load uncompressed tXTt chunks correctly" do filename = resource_file("text_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata["Title"]).to eql "My amazing icon!" expect(ds.metadata["Author"]).to eql "Willem van Bergen" end it "should load compressed zTXt chunks correctly" do filename = resource_file("ztxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata["Title"]).to eql "PngSuite" expect(ds.metadata["Copyright"]).to eql "Copyright Willem van Schaik, Singapore 1995-96" end it "ignores iTXt chunks" do filename = resource_file("itxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata).to be_empty end end describe "#physical_chunk" do it "should read and write pHYs chunks correctly" do filename = resource_file("clock.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.physical_chunk.unit).to eql :meters expect(ds.physical_chunk.dpix.round).to eql 72 expect(ds.physical_chunk.dpiy.round).to eql 72 ds = ChunkyPNG::Datastream.from_blob(ds.to_blob) expect(ds.physical_chunk).not_to be_nil end it "should raise ChunkyPNG::UnitsUnknown if we request dpi but the units are unknown" do physical_chunk = ChunkyPNG::Chunk::Physical.new(2835, 2835, :unknown) expect { physical_chunk.dpix }.to raise_error(ChunkyPNG::UnitsUnknown) expect { physical_chunk.dpiy }.to raise_error(ChunkyPNG::UnitsUnknown) end end describe "#iTXt_chunk" do it "should read iTXt chunks correctly" do filename = resource_file("itxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) int_text_chunks = ds.chunks.select { |chunk| chunk.is_a?(ChunkyPNG::Chunk::InternationalText) } expect(int_text_chunks.length).to eq(2) coach_uk = int_text_chunks.find { |chunk| chunk.language_tag == "en-gb" } coach_us = int_text_chunks.find { |chunk| chunk.language_tag == "en-us" } expect(coach_uk).to_not be_nil expect(coach_us).to_not be_nil expect(coach_uk.keyword).to eq("coach") expect(coach_uk.text).to eq("bus with of higher standard of comfort, usually chartered or used for longer journeys") expect(coach_uk.translated_keyword).to eq("bus") expect(coach_uk.compressed).to eq(ChunkyPNG::UNCOMPRESSED_CONTENT) expect(coach_uk.compression).to eq(ChunkyPNG::COMPRESSION_DEFAULT) expect(coach_us.keyword).to eq("coach") expect(coach_us.text).to eq("US extracurricular sports teacher at a school (UK: PE teacher) lowest class on a passenger aircraft (UK: economy)") expect(coach_us.translated_keyword).to eq("trainer") expect(coach_us.compressed).to eq(ChunkyPNG::COMPRESSED_CONTENT) expect(coach_us.compression).to eq(ChunkyPNG::COMPRESSION_DEFAULT) end it "should write iTXt chunks correctly" do expected_hex = %w[0000 001d 6954 5874 436f 6d6d 656e 7400 0000 0000 4372 6561 7465 6420 7769 7468 2047 494d 5064 2e65 07].join("") stream = StringIO.new itext = ChunkyPNG::Chunk::InternationalText.new("Comment", "Created with GIMP") itext.write(stream) generated_hex = stream.string.unpack("H*").join("") expect(generated_hex).to eq(expected_hex) end it "should handle incorrect UTF-8 encoding in iTXt chunks" do incorrect_text_encoding = [0, 0, 0, 14, 105, 84, 88, 116, 67, 111, 109, 109, 101, 110, 116, 0, 0, 0, 0, 0, 195, 40, 17, 87, 97, 213].pack("C*") incorrect_translated_keyword_encoding = [0, 0, 0, 19, 105, 84, 88, 116, 67, 111, 109, 109, 101, 110, 116, 0, 0, 0, 0, 226, 130, 40, 0, 116, 101, 115, 116, 228, 53, 113, 182].pack("C*") expect { ChunkyPNG::Chunk.read(StringIO.new(incorrect_text_encoding)) }.to raise_error(ChunkyPNG::InvalidUTF8) expect { ChunkyPNG::Chunk.read(StringIO.new(incorrect_translated_keyword_encoding)) }.to raise_error(ChunkyPNG::InvalidUTF8) end it "should handle UTF-8 in iTXt compressed chunks correctly" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "✨", "", "💩", ChunkyPNG::COMPRESSED_CONTENT)) expect(parsed.text).to eq("✨") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("💩") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end it "should handle UTF-8 in iTXt chunks correctly" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "✨", "", "💩")) expect(parsed.text).to eq("✨") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("💩") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end it "should transform non UTF-8 iTXt fields to UTF-8 on write" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "®".encode("Windows-1252"), "", "ƒ".encode("Windows-1252"))) expect(parsed.text).to eq("®") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("ƒ") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end end end
wvanbergen/chunky_png
spec/chunky_png/datastream_spec.rb
Ruby
mit
6,371
<?php namespace Platformsh\Cli\Tests\Service; use Platformsh\Cli\Service\Filesystem; use Platformsh\Cli\Tests\HasTempDirTrait; class FilesystemServiceTest extends \PHPUnit_Framework_TestCase { use HasTempDirTrait; /** @var Filesystem */ protected $fs; /** * @{inheritdoc} */ public function setUp() { $this->fs = new Filesystem(); $this->tempDirSetUp(); } /** * Test our own self::tempDir(). */ public function testTempDir() { $tempDir = $this->tempDir(); $this->assertTrue(is_dir($tempDir)); $tempDir = $this->tempDir(true); $this->assertFileExists($tempDir . '/test-file'); $this->assertFileExists($tempDir . '/test-dir/test-file'); $this->assertFileExists($tempDir . '/test-nesting/1/2/3/test-file'); } /** * Test FilesystemHelper::remove() on directories. */ public function testRemoveDir() { // Create a test directory containing some files in several levels. $testDir = $this->tempDir(true); // Check that the directory can be removed. $this->assertTrue($this->fs->remove($testDir)); $this->assertFileNotExists($testDir); } /** * Test FilesystemHelper::copyAll(). */ public function testCopyAll() { $source = $this->tempDir(true); $destination = $this->tempDir(); touch($source . '/.donotcopy'); // Copy files. $this->fs->copyAll($source, $destination, ['.*']); // Check that they have been copied. $this->assertFileExists($destination . '/test-file'); $this->assertFileExists($destination . '/test-dir/test-file'); $this->assertFileNotExists($destination . '/.donotcopy'); } /** * Test FilesystemHelper::symlinkDir(). */ public function testSymlinkDir() { $testTarget = $this->tempDir(); $testLink = $this->tempDir() . '/link'; $this->fs->symlink($testTarget, $testLink); $this->assertTrue(is_link($testLink)); touch($testTarget . '/test-file'); $this->assertFileExists($testLink . '/test-file'); } /** * Test FilesystemHelper::makePathAbsolute(). */ public function testMakePathAbsolute() { $testDir = $this->tempDir(); chdir($testDir); $path = $this->fs->makePathAbsolute('test.txt'); $this->assertEquals($testDir . '/' . 'test.txt', $path); $childDir = $testDir . '/test'; mkdir($childDir); chdir($childDir); $path = $this->fs->makePathAbsolute('../test.txt'); $this->assertEquals($testDir . '/' . 'test.txt', $path); $path = $this->fs->makePathAbsolute('..'); $this->assertEquals($testDir, $path); $this->setExpectedException('InvalidArgumentException'); $this->fs->makePathAbsolute('nonexistent/test.txt'); } /** * Test FilesystemHelper::symlinkAll(). */ public function testSymlinkAll() { $testSource = $this->tempDir(true); $testDestination = $this->tempDir(); // Test plain symlinking. $this->fs->symlinkAll($testSource, $testDestination); $this->assertFileExists($testDestination . '/test-file'); $this->assertFileExists($testDestination . '/test-dir/test-file'); $this->assertFileExists($testDestination . '/test-nesting/1/2/3/test-file'); // Test with skipping an existing file. $testDestination = $this->tempDir(); touch($testDestination . '/test-file'); $this->fs->symlinkAll($testSource, $testDestination); $this->assertFileExists($testDestination . '/test-file'); $this->assertFileExists($testDestination . '/test-dir/test-file'); $this->assertFileExists($testDestination . '/test-nesting/1/2/3/test-file'); // Test with relative links. This has no effect on Windows. $testDestination = $this->tempDir(); $this->fs->setRelativeLinks(true); $this->fs->symlinkAll($testSource, $testDestination); $this->fs->setRelativeLinks(false); $this->assertFileExists($testDestination . '/test-file'); $this->assertFileExists($testDestination . '/test-dir/test-file'); $this->assertFileExists($testDestination . '/test-nesting/1/2/3/test-file'); // Test with a list of excluded files. $testDestination = $this->tempDir(); touch($testSource . '/test-file2'); $this->fs->symlinkAll($testSource, $testDestination, true, false, ['test-file']); $this->assertFileNotExists($testDestination . '/test-file'); $this->assertFileExists($testDestination . '/test-dir/test-file'); $this->assertFileExists($testDestination . '/test-nesting/1/2/3/test-file'); } public function testCanWrite() { $testDir = $this->createTempSubDir(); touch($testDir . '/test-file'); $this->assertTrue($this->fs->canWrite($testDir . '/test-file')); chmod($testDir . '/test-file', 0500); $this->assertFalse($this->fs->canWrite($testDir . '/test-file')); mkdir($testDir . '/test-dir', 0700); $this->assertTrue($this->fs->canWrite($testDir . '/test-dir')); $this->assertTrue($this->fs->canWrite($testDir . '/test-dir/1')); $this->assertTrue($this->fs->canWrite($testDir . '/test-dir/1/2/3')); mkdir($testDir . '/test-ro-dir', 0500); $this->assertFalse(is_writable($testDir . '/test-ro-dir')); $this->assertFalse($this->fs->canWrite($testDir . '/test-ro-dir')); $this->assertFalse($this->fs->canWrite($testDir . '/test-ro-dir/1')); } /** * Create a test directory with a unique name. * * @param bool $fill Fill the directory with some files. * * @return string */ protected function tempDir($fill = false) { $testDir = $this->createTempSubDir(); if ($fill) { touch($testDir . '/test-file'); mkdir($testDir . '/test-dir'); touch($testDir . '/test-dir/test-file'); mkdir($testDir . '/test-nesting/1/2/3', 0755, true); touch($testDir . '/test-nesting/1/2/3/test-file'); } return $testDir; } }
platformsh/platformsh-cli
tests/Service/FilesystemServiceTest.php
PHP
mit
6,295
using AutoMapper; using Volo.SqliteDemo.Authorization.Users; namespace Volo.SqliteDemo.Users.Dto { public class UserMapProfile : Profile { public UserMapProfile() { CreateMap<UserDto, User>(); CreateMap<UserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); CreateMap<CreateUserDto, User>(); CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); } } }
aspnetboilerplate/aspnetboilerplate-samples
SqliteDemo/aspnet-core/src/Volo.SqliteDemo.Application/Users/Dto/UserMapProfile.cs
C#
mit
474
from __future__ import division def run () : import libtbx.load_env # import dependency for module in libtbx.env.module_list : print module.name if (__name__ == "__main__") : run()
hickerson/bbn
fable/fable_sources/libtbx/command_line/list_modules.py
Python
mit
194
var context; var plainCanvas; var log; var pointerDown = {}; var lastPositions = {}; var colors = ["rgb(100, 255, 100)", "rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(255, 0, 0)", "rgb(0, 255, 100)", "rgb(10, 255, 255)", "rgb(255, 0, 100)"]; var onPointerMove = function(evt) { if (pointerDown[evt.pointerId]) { var color = colors[evt.pointerId % colors.length]; context.strokeStyle = color; context.beginPath(); context.lineWidth = 2; context.moveTo(lastPositions[evt.pointerId].x, lastPositions[evt.pointerId].y); context.lineTo(evt.clientX, evt.clientY); context.closePath(); context.stroke(); lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; } }; var pointerLog = function (evt) { var pre = document.querySelector("pre"); pre.innerHTML = evt.type + "\t\t(" + evt.clientX + ", " + evt.clientY + ")\n" + pre.innerHTML; }; var onPointerUp = function (evt) { pointerDown[evt.pointerId] = false; pointerLog(evt); }; var onPointerDown = function (evt) { pointerDown[evt.pointerId] = true; lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; pointerLog(evt); }; var onPointerEnter = function (evt) { pointerLog(evt); }; var onPointerLeave = function (evt) { pointerLog(evt); }; var onPointerOver = function (evt) { pointerLog(evt); }; var onload = function() { plainCanvas = document.getElementById("plainCanvas"); log = document.getElementById("log"); plainCanvas.width = plainCanvas.clientWidth; plainCanvas.height = plainCanvas.clientHeight; context = plainCanvas.getContext("2d"); context.fillStyle = "rgba(50, 50, 50, 1)"; context.fillRect(0, 0, plainCanvas.width, plainCanvas.height); plainCanvas.addEventListener("pointerdown", onPointerDown, false); plainCanvas.addEventListener("pointermove", onPointerMove, false); plainCanvas.addEventListener("pointerup", onPointerUp, false); plainCanvas.addEventListener("pointerout", onPointerUp, false); plainCanvas.addEventListener("pointerenter", onPointerEnter, false); plainCanvas.addEventListener("pointerleave", onPointerLeave, false); plainCanvas.addEventListener("pointerover", onPointerOver, false); }; if (document.addEventListener !== undefined) { document.addEventListener("DOMContentLoaded", onload, false); } ;
rtillery/html5demos
draw/index.js
JavaScript
mit
2,482
# Set up gems listed in the Gemfile. # See: http://gembundler.com/bundler_setup.html # http://stackoverflow.com/questions/7243486/why-do-you-need-require-bundler-setup ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) # Require gems we care about require 'rubygems' require 'uri' require 'pathname' require 'pg' require 'active_record' require 'logger' require 'oauth' require 'json' # require 'dotenv' # Dotenv.load require 'yelp' require 'httparty' require 'sinatra' require "sinatra/reloader" if development? require 'dotenv' Dotenv.load require 'erb' # Some helper constants for path-centric logic APP_ROOT = Pathname.new(File.expand_path('../../', __FILE__)) APP_NAME = APP_ROOT.basename.to_s configure do # By default, Sinatra assumes that the root is the file that calls the configure block. # Since this is not the case for us, we set it manually. set :root, APP_ROOT.to_path # See: http://www.sinatrarb.com/faq.html#sessions enable :sessions set :session_secret, ENV['SESSION_SECRET'] || 'this is a secret shhhhh' # Set the views to set :views, File.join(Sinatra::Application.root, "app", "views") end # Set up the controllers and helpers Dir[APP_ROOT.join('app', 'controllers', '*.rb')].each { |file| require file } Dir[APP_ROOT.join('app', 'helpers', '*.rb')].each { |file| require file } # Set up the database and models require APP_ROOT.join('config', 'database')
gardoroman/yick
config/environment.rb
Ruby
mit
1,495
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx; using NUnit.Framework; using SJP.Schematic.Core; using SJP.Schematic.Core.Extensions; using SJP.Schematic.Tests.Utilities; namespace SJP.Schematic.PostgreSql.Tests.Integration { internal sealed class PostgreSqlDatabaseQueryViewProviderTests : PostgreSqlTest { private IDatabaseViewProvider ViewProvider => new PostgreSqlDatabaseQueryViewProvider(Connection, IdentifierDefaults, IdentifierResolver); [OneTimeSetUp] public async Task Init() { await DbConnection.ExecuteAsync("create view query_db_test_view_1 as select 1 as dummy", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create view query_view_test_view_1 as select 1 as test", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create table query_view_test_table_1 (table_id int primary key not null)", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create view query_view_test_view_2 as select table_id as test from query_view_test_table_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create materialized view query_view_test_matview_1 as select table_id as test from query_view_test_table_1", CancellationToken.None).ConfigureAwait(false); } [OneTimeTearDown] public async Task CleanUp() { await DbConnection.ExecuteAsync("drop view query_db_test_view_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop view query_view_test_view_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop view query_view_test_view_2", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop materialized view query_view_test_matview_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop table query_view_test_table_1", CancellationToken.None).ConfigureAwait(false); } private Task<IDatabaseView> GetViewAsync(Identifier viewName) { if (viewName == null) throw new ArgumentNullException(nameof(viewName)); return GetViewAsyncCore(viewName); } private async Task<IDatabaseView> GetViewAsyncCore(Identifier viewName) { using (await _lock.LockAsync().ConfigureAwait(false)) { if (!_viewsCache.TryGetValue(viewName, out var lazyView)) { lazyView = new AsyncLazy<IDatabaseView>(() => ViewProvider.GetView(viewName).UnwrapSomeAsync()); _viewsCache[viewName] = lazyView; } return await lazyView.ConfigureAwait(false); } } private readonly AsyncLock _lock = new(); private readonly Dictionary<Identifier, AsyncLazy<IDatabaseView>> _viewsCache = new(); [Test] public async Task GetView_WhenViewPresent_ReturnsView() { var viewIsSome = await ViewProvider.GetView("query_db_test_view_1").IsSome.ConfigureAwait(false); Assert.That(viewIsSome, Is.True); } [Test] public async Task GetView_WhenViewPresent_ReturnsViewWithCorrectName() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(viewName)); } [Test] public async Task GetView_WhenViewPresentGivenLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Schema, "query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenDatabaseAndSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedName_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedNameWithDifferentServer_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewPresentGivenFullyQualifiedNameWithDifferentServerAndDatabase_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", "B", IdentifierDefaults.Schema, "query_db_test_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "query_db_test_view_1"); var view = await ViewProvider.GetView(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(view.Name, Is.EqualTo(expectedViewName)); } [Test] public async Task GetView_WhenViewMissing_ReturnsNone() { var viewIsNone = await ViewProvider.GetView("view_that_doesnt_exist").IsNone.ConfigureAwait(false); Assert.That(viewIsNone, Is.True); } [Test] public async Task GetView_WhenGivenNameOfMaterializedView_ReturnsNone() { var viewIsNone = await ViewProvider.GetView("query_view_test_matview_1").IsNone.ConfigureAwait(false); Assert.That(viewIsNone, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_ContainsViews() { var hasViews = await ViewProvider.GetAllViews() .AnyAsync() .ConfigureAwait(false); Assert.That(hasViews, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_ContainsTestView() { const string viewName = "query_db_test_view_1"; var containsTestView = await ViewProvider.GetAllViews() .AnyAsync(v => string.Equals(v.Name.LocalName, viewName, StringComparison.Ordinal)) .ConfigureAwait(false); Assert.That(containsTestView, Is.True); } [Test] public async Task GetAllViews_WhenEnumerated_DoesNotContainMaterializedView() { const string viewName = "query_view_test_matview_1"; var containsTestView = await ViewProvider.GetAllViews() .AnyAsync(v => string.Equals(v.Name.LocalName, viewName, StringComparison.Ordinal)) .ConfigureAwait(false); Assert.That(containsTestView, Is.False); } [Test] public async Task Definition_PropertyGet_ReturnsCorrectDefinition() { var viewName = new Identifier(IdentifierDefaults.Schema, "query_view_test_view_1"); var view = await GetViewAsync(viewName).ConfigureAwait(false); var definition = view.Definition; const string expected = " SELECT 1 AS test;"; Assert.That(definition, Is.EqualTo(expected)); } [Test] public async Task IsMaterialized_WhenViewIsNotMaterialized_ReturnsFalse() { var view = await GetViewAsync("query_view_test_view_1").ConfigureAwait(false); Assert.That(view.IsMaterialized, Is.False); } [Test] public async Task Columns_WhenViewContainsSingleColumn_ContainsOneValueOnly() { var viewName = new Identifier(IdentifierDefaults.Schema, "query_view_test_view_1"); var view = await GetViewAsync(viewName).ConfigureAwait(false); Assert.That(view.Columns, Has.Exactly(1).Items); } [Test] public async Task Columns_WhenViewContainsSingleColumn_ContainsColumnName() { var viewName = new Identifier(IdentifierDefaults.Schema, "query_view_test_view_1"); var view = await GetViewAsync(viewName).ConfigureAwait(false); var containsColumn = view.Columns.Any(c => c.Name == "test"); Assert.That(containsColumn, Is.True); } } }
sjp/Schematic
src/SJP.Schematic.PostgreSql.Tests/Integration/PostgreSqlDatabaseQueryViewProviderTests.cs
C#
mit
10,531
namespace Bolt { internal static class StringExensions { public static bool EqualsNoCase(this string first, string second) { if (Equals(first, second)) { return true; } return string.CompareOrdinal(first?.ToLowerInvariant() ?? first, second?.ToLowerInvariant() ?? second) == 0; } } }
yonglehou/Bolt
src/Bolt.Sources/StringExensions.cs
C#
mit
387
/** * @fileOverview Cross */ import React, { PureComponent, SVGProps } from 'react'; import classNames from 'classnames'; import { isNumber } from '../util/DataUtils'; import { filterProps } from '../util/types'; interface CrossProps { x?: number; y?: number; width?: number; height?: number; top?: number; left?: number; className?: number; } export type Props = SVGProps<SVGPathElement> & CrossProps; export class Cross extends PureComponent<Props> { static defaultProps = { x: 0, y: 0, top: 0, left: 0, width: 0, height: 0, }; static getPath(x: number, y: number, width: number, height: number, top: number, left: number) { return `M${x},${top}v${height}M${left},${y}h${width}`; } render() { const { x, y, width, height, top, left, className } = this.props; if (!isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height) || !isNumber(top) || !isNumber(left)) { return null; } return ( <path {...filterProps(this.props, true)} className={classNames('recharts-cross', className)} d={Cross.getPath(x, y, width, height, top, left)} /> ); } }
recharts/recharts
src/shape/Cross.tsx
TypeScript
mit
1,177
import http from 'http'; function upsertState(state) { var postData = JSON.stringify(state); var options = { hostname: 'localhost', port: 3000, path: '/application', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; var req = http.request(options, (res) => { res.setEncoding('utf8'); }); req.write(postData); req.end(); } let defaultState = { excitement: 0, poc: { name: '', email: '' }, contributors: [], popover: false }; let savedState = JSON.parse(localStorage.getItem('appState')); export default function application(state = savedState || defaultState, action) { let newState switch (action.type) { case 'GET_EXCITED': { newState = Object.assign({}, state, { excitement: state.excitement += 1 }); break; } case 'UPDATE_POC': { newState = Object.assign({}, state, { poc: { name: action.name, email: action.email } }); break; } case 'PERSIST_STATE': { upsertState(state); newState = state; break; } case 'SHOW_POPOVER': { newState = Object.assign({}, state, { popover: true }); break; } case 'UPDATE_ESSAY': { newState = Object.assign({}, state, { [action.prompt]: action.response }); break; } case 'UPDATE_COMPANY_NAME': { newState = Object.assign({}, state, { companyName: action.name }); break; } case 'UPDATE_COMPANY_TYPE': { newState = Object.assign({}, state, { companyType: action.companyType }); break; } case 'REMOVE_CONTRIBUTOR': { const contributors = state.contributors.slice(0, state.contributors.length - 1) newState = Object.assign({}, state, { contributors: contributors }); break; } case 'UPDATE_CONTRIBUTOR': { let updated = false; const contributors = state.contributors.map((contributor) => { if (contributor.id === action.id) { updated = true; return { id: contributor.id, name: action.name, email: action.email } } else { return contributor; } }); if (!updated) { contributors.push({ id: action.id, name: action.name, email: action.email }); } newState = Object.assign({}, state, { contributors: contributors }); break; } default: { newState = state; } } localStorage.setItem('appState', JSON.stringify(newState)) return newState; }
doug-wade/incubator-application
browser/reducers/index.js
JavaScript
mit
2,674
version https://git-lfs.github.com/spec/v1 oid sha256:00be998e9791a319bc3751b20c19ce0fa3cb25a87c8dbf9030a728c92af8d95c size 100787
yogeshsaroya/new-cdnjs
ajax/libs/rxjs/2.3.24/rx.all.compat.min.js
JavaScript
mit
131
require_relative 'game_element' class GamePackage include GameElement attr_reader :items attr_reader :capacity def initialize(capacity) @capacity = capacity @items = [] end def add(item) @items << item end def discard() @item end def [](i) @items[i] end def []=(i, item) @items[i] = item end def << item add(item) end end
HungryAnt/ruby-demo
src/game_package.rb
Ruby
mit
419
import PropTypes from 'prop-types' import React from 'react' const Card = ({title}) => <h3>{title}</h3> Card.propTypes = { title: PropTypes.string.isRequired } export default Card
dustinspecker/the-x-effect
app/components/card/index.js
JavaScript
mit
187
namespace FoldAndSum { using System; using System.Collections.Generic; using System.Linq; class FoldAndSum { static void Main(string[] args) { var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int k = input.Length / 2 / 2; var secondFirst = input.Reverse().Take(k).ToArray(); var firstFirst = input.Take(k).Reverse().ToArray(); var first = firstFirst.Concat(secondFirst); var second = input.Skip(k).Take(2 * k).ToArray(); var result = first.Select((x, index) => x + second[index]); Console.WriteLine(string.Join(" ", result)); } } }
davidvaleff/ProgrammingFundamentals-Sept2017
07.DictionariesLambda&LINQ/Lab/FoldAndSum/FoldAndSum.cs
C#
mit
705
package com.bijoykochar.launcher.view; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.CalendarContract; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.bijoykochar.launcher.R; import com.bijoykochar.launcher.items.SerialEvent; import com.bijoykochar.launcher.util.TimeUtilities; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import me.everything.providers.android.calendar.Calendar; import me.everything.providers.android.calendar.CalendarProvider; import me.everything.providers.android.calendar.Event; /** * The view for the home recent apps * Created by bijoy on 10/17/15. */ public class CalendarView extends LinearLayout { View rootView; TextView title, description, dateTime; SerialEvent event; public CalendarView(Context context) { super(context); } public CalendarView(Context context, AttributeSet attrs) { super(context, attrs); } public CalendarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public List<SerialEvent> getSerialEvents(Context context) { CalendarProvider provider = new CalendarProvider(context); List<Calendar> calendars = provider.getCalendars().getList(); List<Event> events = new ArrayList<>(); for (Calendar calendar : calendars) { events.addAll(provider.getEvents(calendar.id).getList()); } List<SerialEvent> sEvents = new ArrayList<>(); for (Event event : events) { sEvents.add(new SerialEvent(event)); } return sEvents; } public SerialEvent getNextEvent(Context context) { List<SerialEvent> events = getSerialEvents(context); if (!events.isEmpty()) { long timeInMillis = java.util.Calendar.getInstance().getTimeInMillis(); long minTimeInMillis = timeInMillis + 1000 * 60 * 60 * 24 * 7 * 52; SerialEvent nextEvent = null; for (SerialEvent event : events) { if (event.dTStart > timeInMillis && event.dTStart < minTimeInMillis) { nextEvent = event; minTimeInMillis = event.dTStart; } } return nextEvent; } return null; } public void init(final Context context) { LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rootView = mInflater.inflate(R.layout.calendar_view, this, true); title = (TextView) rootView.findViewById(R.id.title); description = (TextView) rootView.findViewById(R.id.description); dateTime = (TextView) rootView.findViewById(R.id.date_time); } public void getData(Context context) { event = getNextEvent(context); } public void displayEvents(final Context context) { try { title.setText(event.title); description.setText(event.description); java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.setTimeInMillis(event.dTStart); SimpleDateFormat dateFormat = TimeUtilities.getFullTimeFormat(context); String dateAndTime = dateFormat.format(calendar.getTime()); dateTime.setText(dateAndTime); rootView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, event.id); Intent intent = new Intent(Intent.ACTION_VIEW) .setData(uri); context.startActivity(intent); } }); } catch (Exception e) { Log.e("CalendarView", e.getMessage(), e); setVisibility(View.GONE); } } }
BijoySingh/One-Launcher
app/src/main/java/com/bijoykochar/launcher/view/CalendarView.java
Java
mit
4,170
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The VCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "tinyformat.h" const std::string CURRENCY_UNIT = "BTC"; CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) { if (nSize > 0) nSatoshisPerK = nFeePaid*1000/nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nSize) const { CAmount nFee = nSatoshisPerK*nSize / 1000; if (nFee == 0 && nSatoshisPerK > 0) nFee = nSatoshisPerK; return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT); }
vcoin-project/v
src/amount.cpp
C++
mit
815
using System; using System.Globalization; namespace SharpRemote.WebApi.Routes.Parsers { internal sealed class Int64Parser : IntegerParser { public override Type Type => typeof(long); public override bool TryExtract(string str, int startIndex, out object value, out int consumed) { string digits; if (TryGetDigits(str, startIndex, out digits)) { long number; if (long.TryParse(digits, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) { value = number; consumed = digits.Length; return true; } } consumed = 0; value = null; return false; } } }
Kittyfisto/SharpRemote
SharpRemote.WebApi/Routes/Parsers/Int64Parser.cs
C#
mit
634
<?php namespace App\Core\Contracts; interface CartInterface { }
storecamp/storecamp
app/Core/Contracts/CartInterface.php
PHP
mit
66
require "json" require "sinatra/base" require "github-trello/version" require "github-trello/http" module GithubTrello class Server < Sinatra::Base #Recieves payload post "/posthook-github" do #Get environment variables for configuration oauth_token = ENV["oauth_token"] api_key = ENV["api_key"] board_id = ENV["board_id"] inprogress_list_target_id = ENV["inprogress_list_target_id"] merged_list_target_id = ENV["merged_list_target_id"] staging_list_target_id = ENV["staging_list_target_id"] deployed_list_target_id = ENV["deployed_list_target_id"] #Set up HTTP Wrapper http = GithubTrello::HTTP.new(oauth_token, api_key) #Get payload payload = JSON.parse(params[:payload]) #Get branch branch = payload["ref"].gsub("refs/heads/", "") payload["commits"].each do |commit| # Figure out the card short id match = commit["message"].match(/((start|card|close|fix)e?s? \D?([0-9]+))/i) next unless match and match[3].to_i > 0 results = http.get_card(board_id, match[3].to_i) unless results puts "[ERROR] Cannot find card matching ID #{match[3]}" next end results = JSON.parse(results) # Add the commit comment message = "#{commit["author"]["name"]}: #{commit["message"]}\n\n[#{branch}] #{commit["url"]}" message.gsub!(match[1], "") message.gsub!(/\(\)$/, "") http.add_comment(results["id"], message) #Determine the action to take if branch.include? "master" then new_list_id = merged_list_target_id elsif branch.include? "staging" then new_list_id = staging_list_target_id elsif branch.include? "production" then new_list_id = deployed_list_target_id else new_list_id = inprogress_list_target_id end next unless !new_list_id.nil? #Modify it if needed to_update = {} unless results["idList"] == new_list_id to_update[:idList] = new_list_id end unless to_update.empty? http.update_card(results["id"], to_update) end end "" end get "/" do "" end def self.http; @http end end end
makoetting/github-trello
lib/github-trello/server.rb
Ruby
mit
2,318
#include <node.h> #include <node_buffer.h> #include <iostream> #include <cstdlib> using namespace v8; using namespace std; using namespace node; /* Random number generators */ static Handle<Value> UniformRandom(const Arguments& args) { HandleScope scope; double d_min = 0, d_max = 1.0; Local<Object> that = args.This()->ToObject(); Local<Value> min = that->Get(String::New("min")); Local<Value> max = that->Get(String::New("max")); Local<Object> seed = that->Get(String::New("seed"))->ToObject(); if (Buffer::Length(seed) < 6) { return ThrowException(Exception::Error( String::New("Length is extends beyond buffer"))); } union { char *seed_data_c; uint16_t *seed_data_us; } seed_data; seed_data.seed_data_c = Buffer::Data(seed); if (min->IsNumber()) { d_min = min->NumberValue(); } else { d_min = 0.0; } if (max->IsNumber()) { d_max = max->NumberValue(); } else { d_max = 1.0; } /* Magic happens here */ /* TODO: Port this to windows, since erand48 and friends * are not in windows */ double result = (erand48(seed_data.seed_data_us) * (d_max - d_min)) + d_min; return scope.Close(Number::New(result)); } extern "C" void init (Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "UniformNext", UniformRandom); }
ashgti/node-math-utils
math_utils.cc
C++
mit
1,424
module Admin class FeedbackReportCSVWriter < CSVWriter columns :id, :service, :feedbackable_type, :rating, :created_at, :review, :acknowledged, :email, :phone, :traveler associations :user def traveler @record.user && @record.user.email end def service return nil if @record.feedbackable_id.nil? if @record.feedbackable_type == 'Service' my_service = Service.find_by(id: @record.feedbackable_id) if my_service return my_service.name else return nil end elsif @record.feedbackable_type == 'OneclickRefernet::Service' my_service = OneclickRefernet::Service.find_by(id: @record.feedbackable_id) if my_service return my_service.agency_name else return nil end end end end end
camsys/oneclick-core
app/serializers/admin/feedback_report_csv_writer.rb
Ruby
mit
845
require 'spec_helper' require 'guard/plugin' describe Guard::Commander do describe '.start' do before do ::Guard.stub(:setup) ::Guard.instance_variable_set('@watchdirs', []) ::Guard.stub(listener: double('listener', start: true)) ::Guard.stub(runner: double('runner', run: true)) ::Guard.stub(:within_preserved_state).and_yield end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup).with(foo: 'bar') ::Guard.start(foo: 'bar') end end it "displays an info message" do ::Guard.instance_variable_set('@watchdirs', ['/foo/bar']) expect(::Guard::UI).to receive(:info).with("Guard is now watching at '/foo/bar'") ::Guard.start end it "tell the runner to run the :start task" do expect(::Guard.runner).to receive(:run).with(:start) ::Guard.start end it "start the listener" do expect(::Guard.listener).to receive(:start) ::Guard.start end end describe '.stop' do before do ::Guard.stub(:setup) ::Guard.stub(listener: double('listener', stop: true)) ::Guard.stub(runner: double('runner', run: true)) ::Guard.stub(:within_preserved_state).and_yield end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.stop end end it "turns the notifier off" do expect(::Guard::Notifier).to receive(:turn_off) ::Guard.stop end it "tell the runner to run the :stop task" do expect(::Guard.runner).to receive(:run).with(:stop) ::Guard.stop end it "stops the listener" do expect(::Guard.listener).to receive(:stop) ::Guard.stop end it "sets the running state to false" do ::Guard.running = true ::Guard.stop expect(::Guard.running).to be_false end end describe '.reload' do let(:runner) { double(run: true) } let(:group) { ::Guard::Group.new('frontend') } subject { ::Guard.setup } before do ::Guard.stub(:runner) { runner } ::Guard.stub(:within_preserved_state).and_yield ::Guard::UI.stub(:info) ::Guard::UI.stub(:clear) end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.reload end end it 'clears the screen' do expect(::Guard::UI).to receive(:clear) subject.reload end context 'with a given scope' do it 'does not re-evaluate the Guardfile' do ::Guard::Guardfile::Evaluator.any_instance.should_not_receive(:reevaluate_guardfile) subject.reload({ groups: [group] }) end it 'reloads Guard' do expect(runner).to receive(:run).with(:reload, { groups: [group] }) subject.reload({ groups: [group] }) end end context 'with an empty scope' do it 'does re-evaluate the Guardfile' do ::Guard::Guardfile::Evaluator.any_instance.should_receive(:reevaluate_guardfile) subject.reload end it 'does not reload Guard' do expect(runner).to_not receive(:run).with(:reload, {}) subject.reload end end end describe '.run_all' do let(:runner) { double(run: true) } let(:group) { ::Guard::Group.new('frontend') } subject { ::Guard.setup } before do ::Guard.stub(runner: runner) ::Guard.stub(:within_preserved_state).and_yield ::Guard::UI.stub(:action_with_scopes) ::Guard::UI.stub(:clear) end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.run_all end end context 'with a given scope' do it 'runs all with the scope' do expect(runner).to receive(:run).with(:run_all, { groups: [group] }) subject.run_all({ groups: [group] }) end end context 'with an empty scope' do it 'runs all' do expect(runner).to receive(:run).with(:run_all, {}) subject.run_all end end end describe '.within_preserved_state' do subject { ::Guard.setup } before { subject.interactor = double('interactor').as_null_object } it 'disallows running the block concurrently to avoid inconsistent states' do expect(subject.lock).to receive(:synchronize) subject.within_preserved_state &Proc.new {} end it 'runs the passed block' do @called = false subject.within_preserved_state { @called = true } expect(@called).to be_true end context '@running is true' do it 'stops the interactor before running the block and starts it again when done' do expect(subject.interactor).to receive(:stop) expect(subject.interactor).to receive(:start) subject.within_preserved_state &Proc.new {} end end context '@running is false' do before { ::Guard.stub(:running) { false } } it 'stops the interactor before running the block and do not starts it again when done' do expect(subject.interactor).to receive(:stop) expect(subject.interactor).to_not receive(:start) subject.within_preserved_state &Proc.new {} end end end end
yujinakayama/guard
spec/guard/commander_spec.rb
Ruby
mit
5,527
/** * 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. */ package com.microsoft.azure.management.storage.v2019_04_01.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import com.microsoft.rest.RestClient; /** * Initializes a new instance of the StorageManagementClientImpl class. */ public class StorageManagementClientImpl extends AzureServiceClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The ID of the target subscription. */ private String subscriptionId; /** * Gets The ID of the target subscription. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public StorageManagementClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The API version to use for this operation. */ private String apiVersion; /** * Gets The API version to use for this operation. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** The preferred language for the response. */ private String acceptLanguage; /** * Gets The preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets The preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public StorageManagementClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public StorageManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public StorageManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The OperationsInner object to access its operations. */ private OperationsInner operations; /** * Gets the OperationsInner object to access its operations. * @return the OperationsInner object. */ public OperationsInner operations() { return this.operations; } /** * The SkusInner object to access its operations. */ private SkusInner skus; /** * Gets the SkusInner object to access its operations. * @return the SkusInner object. */ public SkusInner skus() { return this.skus; } /** * The StorageAccountsInner object to access its operations. */ private StorageAccountsInner storageAccounts; /** * Gets the StorageAccountsInner object to access its operations. * @return the StorageAccountsInner object. */ public StorageAccountsInner storageAccounts() { return this.storageAccounts; } /** * The UsagesInner object to access its operations. */ private UsagesInner usages; /** * Gets the UsagesInner object to access its operations. * @return the UsagesInner object. */ public UsagesInner usages() { return this.usages; } /** * The ManagementPoliciesInner object to access its operations. */ private ManagementPoliciesInner managementPolicies; /** * Gets the ManagementPoliciesInner object to access its operations. * @return the ManagementPoliciesInner object. */ public ManagementPoliciesInner managementPolicies() { return this.managementPolicies; } /** * The BlobServicesInner object to access its operations. */ private BlobServicesInner blobServices; /** * Gets the BlobServicesInner object to access its operations. * @return the BlobServicesInner object. */ public BlobServicesInner blobServices() { return this.blobServices; } /** * The BlobContainersInner object to access its operations. */ private BlobContainersInner blobContainers; /** * Gets the BlobContainersInner object to access its operations. * @return the BlobContainersInner object. */ public BlobContainersInner blobContainers() { return this.blobContainers; } /** * The FileServicesInner object to access its operations. */ private FileServicesInner fileServices; /** * Gets the FileServicesInner object to access its operations. * @return the FileServicesInner object. */ public FileServicesInner fileServices() { return this.fileServices; } /** * The FileSharesInner object to access its operations. */ private FileSharesInner fileShares; /** * Gets the FileSharesInner object to access its operations. * @return the FileSharesInner object. */ public FileSharesInner fileShares() { return this.fileShares; } /** * Initializes an instance of StorageManagementClient client. * * @param credentials the management credentials for Azure */ public StorageManagementClientImpl(ServiceClientCredentials credentials) { this("https://management.azure.com", credentials); } /** * Initializes an instance of StorageManagementClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public StorageManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) { super(baseUrl, credentials); initialize(); } /** * Initializes an instance of StorageManagementClient client. * * @param restClient the REST client to connect to Azure. */ public StorageManagementClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2019-04-01"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.operations = new OperationsInner(restClient().retrofit(), this); this.skus = new SkusInner(restClient().retrofit(), this); this.storageAccounts = new StorageAccountsInner(restClient().retrofit(), this); this.usages = new UsagesInner(restClient().retrofit(), this); this.managementPolicies = new ManagementPoliciesInner(restClient().retrofit(), this); this.blobServices = new BlobServicesInner(restClient().retrofit(), this); this.blobContainers = new BlobContainersInner(restClient().retrofit(), this); this.fileServices = new FileServicesInner(restClient().retrofit(), this); this.fileShares = new FileSharesInner(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "StorageManagementClient", "2019-04-01"); } }
navalev/azure-sdk-for-java
sdk/storage/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/storage/v2019_04_01/implementation/StorageManagementClientImpl.java
Java
mit
9,641
package by.trapecia.dao; import by.trapecia.Main; import by.trapecia.model.Client; import by.trapecia.model.Rent; import java.sql.*; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Denis on 15.12.2015. */ public class RentDaoImpl implements RentDao { private static Logger log = Logger.getLogger(Main.class.getName()); private ConnectionPool cp; public RentDaoImpl() throws Exception { cp = ConnectionPool.getInstance(); } @Override public Integer saveRent(Rent rent, Integer clientId) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet result = null; try { connection = cp.getConnection(); ps = connection.prepareStatement( "INSERT INTO rent VALUES (DEFAULT, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); ps.setInt(1, clientId); ps.setInt(2, rent.climbingShoes); ps.setInt(3, rent.harness); ps.setInt(4, rent.magnesia); ps.setInt(5, rent.carabine); ps.setInt(6, rent.griGri); ps.executeUpdate(); result = ps.getGeneratedKeys(); result.next(); rent.rentId = result.getInt(1); return rent.rentId; } catch (SQLException e) { log.log(Level.SEVERE, "Exception: ", e); throw new Exception("Can't execute sql", e); } finally { if(result != null)result.close(); if(ps != null)ps.close(); cp.returnConnection(connection); } } @Override public Rent loadRent(Integer clientId) throws Exception { Connection connection = null; Statement st = null; ResultSet result = null; Rent rent = new Rent(); PreparedStatement ps = null; try { connection = cp.getConnection(); String selectStatement = "SELECT * FROM rent" + " WHERE rent_id IN (SELECT rent_id FROM service" + " WHERE check_out = '0000-00-00 00:00:00'" + "AND client_id = ?)"; ps = connection.prepareStatement(selectStatement); ps.setInt(1, clientId); result = ps.executeQuery(); while (result.next()) { rent.clientId = result.getInt("client_id"); rent.rentId = result.getInt("rent_id"); rent.climbingShoes = result.getInt("climbing_shoes"); rent.magnesia = result.getInt("magnesia"); rent.carabine = result.getInt("carabine"); rent.griGri = result.getInt("gri_gri"); rent.harness = result.getInt("harness"); } result.close(); } catch (SQLException se) { log.log(Level.SEVERE, "Exception: ", se); } catch (Exception e) { log.log(Level.SEVERE, "Exception: ", e); } finally { if(result != null)result.close(); if(ps != null)ps.close(); cp.returnConnection(connection); } return rent; } }
Maximenya/Trapezia-1.01
src/main/java/by/trapecia/dao/RentDaoImpl.java
Java
mit
3,231
import { IAppToken, createToken } from '../lib/authorization' import * as KoaRouter from 'koa-router' import { User } from '../models' import { IsomorphicRenderController } from '../controllers/IsomorphicRender' import { clearCookieToken, restrictIdentifiedAccess, restrictUnidentifiedAccess } from '../lib/authorization' const convert = require('koa-convert') const body = require('koa-body') export class UserController { private router = new KoaRouter() private errorMessages = { authFailed: 'Authorization failed.', incompleteAttributes: 'Incomplete attributes.', emailTaken: 'Email already taken.' } constructor(app) { const parseBody = convert(body({ multipart: true })) this.router.get('/login', restrictIdentifiedAccess, IsomorphicRenderController.renderRoute) this.router.post('/login', restrictIdentifiedAccess, parseBody, async (ctx) => { const fields = ctx.request.body.fields if (!fields || !fields.email || !fields.password) { return ctx.throw(401, this.errorMessages.authFailed) } const user = await User.getByEmailAndPass(fields.email, fields.password) if (!user) { return ctx.throw(401, this.errorMessages.authFailed) } this.authenticateUser(ctx, user, fields.rememberMe) ctx.body = 'OK' }) this.router.get('/sign_up', restrictIdentifiedAccess, IsomorphicRenderController.renderRoute) this.router.post('/sign_up', restrictIdentifiedAccess, parseBody, async (ctx) => { const fields = ctx.request.body.fields if (!fields || !fields.name || !fields.password || !fields.email || !fields.password) { return ctx.throw(403, this.errorMessages.incompleteAttributes) } if (await User.getByEmail(fields.email)) { return ctx.throw(403, this.errorMessages.emailTaken) } try { let user = await new User({ name: fields.name, email: fields.email, password: fields.password }).save() this.authenticateUser(ctx, user) ctx.body = 'OK' } catch (e) { ctx.throw(403, e.message) } }) this.router.get('/logout', (ctx) => { clearCookieToken(ctx) ctx.accepts('html', 'json', 'text') === 'json' ? ctx.status = 200 : ctx.redirect('/login') }) // this route is used by native apps this.router.get('/ping', restrictUnidentifiedAccess, (ctx, next) => { ctx.type = 'application/json' ctx.body = JSON.stringify({status: 'OK'}) }) } private authenticateUser(ctx, user, rememberMe?): void { // NOTE, we store the entire User object on the JWT payload without the crypted pass let payload = JSON.parse(JSON.stringify(user)) delete payload.cryptedPassword const appToken: IAppToken = createToken(payload) const cookieData: any = { signed: false, httpOnly: true, overwrite: true, } if (rememberMe === 'true') { cookieData.expires = appToken.expires } ctx.cookies.set('token', appToken.token, cookieData) } }
rodrigopivi/PlayApp
src/server/controllers/User.ts
TypeScript
mit
3,330
from django.core.management.base import BaseCommand from openkamer.verslagao import create_verslagen_algemeen_overleg class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('year', nargs='+', type=int) parser.add_argument('--max', type=int, help='The max number of documents to create, used for testing.', default=None) def handle(self, *args, **options): year = options['year'][0] max_n = options['max'] create_verslagen_algemeen_overleg(year, max_n, skip_if_exists=False)
openkamer/openkamer
openkamer/management/commands/create_verslagen_ao.py
Python
mit
553
var arr = 'ciao come va'.split(' '); var filtered = arr.filter(function(item) { return item != 'va'; }); Array.prototype.filtroMio = function() { if (arr.length == 2) { return this } return []; }; var ar2 = arr.filtroMio(); console.log(ar2); console.log(filtered);
brugnara/node-lessons
lessons/05-filtered.js
JavaScript
mit
280
#ifndef SERVER_BASE_HPP #define SERVER_BASE_HPP #include <boost/asio.hpp> #include <regex> #include <unordered_map> #include <thread> #include <iostream> #include <ctime> #include "Request.h" #include "Response.h" namespace MyWeb { typedef std::map<std::string, std::unordered_map<std::string, std::function<void(Response&, Request&)>>> resource_type; template <typename socket_type> class ServerBase{ public: resource_type resource; resource_type default_resource; ServerBase(unsigned short port,size_t num_threads=1): endpoint(boost::asio::ip::tcp::v4(),port), acceptor(m_io_service,endpoint), num_threads(num_threads){} void start(){ for(auto it=resource.begin();it!=resource.end();++it){ all_resources.push_back(it); } for(auto it=default_resource.begin();it!=default_resource.end();++it){ all_resources.push_back(it); } accept(); for(size_t i=1;i<num_threads;i++){ threads.emplace_back([this](){ m_io_service.run(); }); } m_io_service.run(); for(auto& t:threads){ t.join(); } }; protected: boost::asio::io_service m_io_service; boost::asio::ip::tcp::endpoint endpoint; boost::asio::ip::tcp::acceptor acceptor; std::vector<resource_type::iterator> all_resources; size_t num_threads; std::vector<std::thread> threads; virtual void accept(){} void process_request_and_respond(std::shared_ptr<socket_type> socket) const{ auto read_buffer = std::make_shared<boost::asio::streambuf>(); boost::asio::async_read_until(*socket,*read_buffer,"\r\n\r\n", [this,socket,read_buffer](const boost::system::error_code& ec,size_t bytes_transferred){ if(!ec){ size_t total = read_buffer->size(); std::istream stream(read_buffer.get()); std::shared_ptr<Request> request = parseRequest(stream); size_t num_additional_bytes = total - bytes_transferred; if(request->getHeader("Content-Length").size()>0){ boost::asio::async_read(*socket,*read_buffer, boost::asio::transfer_exactly(std::stoull(request->getHeader("Content-Length"))- num_additional_bytes), [this,socket,read_buffer,request](const boost::system::error_code& ec,size_t bytes_transferred){ if(!ec){ auto bodyStream = std::shared_ptr<std::istream>(new std::istream(read_buffer.get())); //解析body std::string rawstr; std::string strTemp; while(std::getline(*bodyStream,strTemp)) { rawstr.append(strTemp); } request->setRawBody(rawstr); respond(socket,request); } }); }else{ respond(socket,request); } } }); }; void respond(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) const { // 对请求路径和方法进行匹配查找,并生成响应 std::string path = request->getPath(); for(auto res_it: all_resources) { std::regex e(res_it->first); std::smatch sm_res; if(std::regex_match(path, sm_res, e)) { if(res_it->second.count(request->getMethod())>0) { //request->path_match = move(sm_res); // 会被推导为 std::shared_ptr<boost::asio::streambuf> auto write_buffer = std::make_shared<boost::asio::streambuf>(); std::ostream wb(write_buffer.get()); auto response = std::make_shared<Response>(); res_it->second[request->getMethod()](*response, *request); *response >> wb; // 在 lambda 中捕获 write_buffer 使其不会再 async_write 完成前被销毁 boost::asio::async_write(*socket, *write_buffer, [this, socket, request, write_buffer](const boost::system::error_code& ec, size_t bytes_transferred) { //HTTP 持久连接(HTTP 1.1): if(!ec && stof(request->getHttpVersion())>1.05) process_request_and_respond(socket); }); return; } } } } }; template<typename socket_type> class Server : public ServerBase<socket_type>{}; } #endif /* SERVER_BASE_HPP */
neveis/WebNote
server_base.hpp
C++
mit
4,506
// Search index songs package song import ( "github.com/ambientsound/pms/song" ) // Song is a Bleve document representing a song.Song object. type Song struct { Album string Albumartist string Artist string File string Genre string Title string Year string } // New generates a indexable Song document, containing some fields from the song.Song type. func New(s *song.Song) (is Song) { is.Album = s.StringTags["album"] is.Albumartist = s.StringTags["albumartist"] is.Artist = s.StringTags["artist"] is.File = s.StringTags["file"] is.Genre = s.StringTags["genre"] is.Title = s.StringTags["title"] is.Year = s.StringTags["year"] return }
ambientsound/pms
index/song/song.go
GO
mit
693
'use strict'; const test = require('tape'); const Postman = require('../fixtures/postman'); test('`it` without any args', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(); }); postman.checkTests({ '1. my test suite - test #1 (this.fn is not a function)': false, }); t.end(); }); test('`it` with only a name', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test'); }); postman.checkTests({ '1. my test suite - my test (this.fn is not a function)': false, }); t.end(); }); test('`it` with only a function', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(() => { }); }); postman.checkTests({ '1. my test suite - test #1': true }); t.end(); }); test('`it` outside of `describe` block', (t) => { let postman = new Postman(t); let i = 0; it('my first test', () => { assert.equal(++i, 1); }); describe('my test suite', () => { it('my second test', () => { assert.equal(++i, 2); }); }); it('my third test', () => { assert.equal(++i, 3); }); t.equal(i, 3); postman.checkTests({ '1. my first test': true, '2. my test suite - my second test': true, '3. my third test': true, }); t.end(); }); test('Error in `it`', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { throw new Error('BOOM!'); }); }); postman.checkTests({ '1. my test suite - my test (BOOM!)': false, }); t.end(); }); test('Error in unnamed `it`', (t) => { let postman = new Postman(t); describe('my test suite', () => { it(() => { throw new Error('BOOM!'); }); }); postman.checkTests({ '1. my test suite - test #1 (BOOM!)': false, }); t.end(); }); test('`it` with successful assertions', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { assert(true); assert.ok(42); assert.equal('hello', 'hello'); expect(new Date()).not.to.equal(new Date()); new Date().should.be.a('Date'); }); }); postman.checkTests({ '1. my test suite - my test': true }); t.end(); }); test('`it` with failed assertions', (t) => { let postman = new Postman(t); describe('my test suite', () => { it('my test', () => { assert.equal('hello', 'world'); }); }); postman.checkTests({ '1. my test suite - my test (expected \'hello\' to equal \'world\')': false, }); t.end(); }); test('`it` runs in the corret order', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 2); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test': true, '3. my test suite - my third test': true, }); t.end(); }); test('`it` runs in the corret order even if there are failed assertions', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 9999); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test (expected 2 to equal 9999)': false, '3. my test suite - my third test': true, }); t.end(); }); test('`it` runs in the corret order even if an error occurs', (t) => { let postman = new Postman(t); let i = 0; describe('my test suite', () => { it('my first test', () => { assert.equal(++i, 1); }); it('my second test', () => { assert.equal(++i, 2); throw new Error('BOOM'); }); it('my third test', () => { assert.equal(++i, 3); }); }); t.equal(i, 3); postman.checkTests({ '1. my test suite - my first test': true, '2. my test suite - my second test (BOOM)': false, '3. my test suite - my third test': true, }); t.end(); }); test('`it` can be nested', (t) => { let postman = new Postman(t); let i = 0; it('my first test', () => { assert.equal(++i, 1); }); describe('my test suite', () => { it('my second test', () => { assert.equal(++i, 2); }); describe(() => { it('my third test', () => { assert.equal(++i, 3); }); describe(() => { it('my fourth test', () => { assert.equal(++i, 4); }); }); it('my fifth test', () => { assert.equal(++i, 5); }); }); it('my sixth test', () => { assert.equal(++i, 6); }); }); it('my seventh test', () => { assert.equal(++i, 7); }); t.equal(i, 7); postman.checkTests({ '1. my first test': true, '2. my test suite - my second test': true, '3. my test suite - describe #2 - my third test': true, '4. my test suite - describe #2 - describe #3 - my fourth test': true, '5. my test suite - describe #2 - my fifth test': true, '6. my test suite - my sixth test': true, '7. my seventh test': true, }); t.end(); });
BigstickCarpet/postman-bdd
test/specs/it.spec.js
JavaScript
mit
5,442
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\AopBundle\JMSAopBundle(), new JMS\DiExtraBundle\JMSDiExtraBundle($this), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), new Wfl\BaseBundle\WflBaseBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
fferz/lapagina
app/AppKernel.php
PHP
mit
1,567
#include "Mutex.h" /* Library C++ Mutex - Mutex fot threads. Copyright 2013 Eduardo Moura Sales Martins (edimartin@gmail.com) 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. */ edk::multi::Mutex::Mutex(){ #if defined( WIN32) || defined( WIN64) this->mut = CreateMutex( NULL, FALSE, NULL); if (this->mut == NULL) { // } #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS if (pthread_mutex_init(&this->mut, NULL) != 0) { // } #endif } edk::multi::Mutex::~Mutex(){ #if defined( WIN32) || defined( WIN64) if(this->mut) CloseHandle(this->mut); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_destroy(&this->mut); #endif } //lock this mutex to another don't run the code void edk::multi::Mutex::lock(){ #if defined( WIN32) || defined( WIN64) WaitForSingleObject(this->mut,INFINITE); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_lock(&this->mut); #endif } //unlock this mutex void edk::multi::Mutex::unlock(){ #if defined( WIN32) || defined( WIN64) ReleaseMutex(this->mut); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_unlock(&this->mut); #endif } //try lock the mutex (if true it's locked) bool edk::multi::Mutex::tryLock(){ #if defined( WIN32) || defined( WIN64) if(!WaitForSingleObject(this->mut,0u)){ return true; } #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS if(!pthread_mutex_trylock(&this->mut)){ return true; } #endif return false; }
Edimartin/edk-source
edk/thread/Mutex.cpp
C++
mit
2,587
"""group_mod tests.""" from unittest import TestCase from pyof.v0x04.controller2switch.group_mod import GroupMod from pyof.v0x04.common.action import ( ActionExperimenter, ActionSetField, ListOfActions) from pyof.v0x04.common.flow_match import OxmClass, OxmOfbMatchField, OxmTLV from pyof.v0x04.common.port import PortNo from pyof.v0x04.controller2switch.common import Bucket from pyof.v0x04.controller2switch.group_mod import ListOfBuckets class TestGroupMod(TestCase): """group_mod tests.""" def test_min_size(self): """Test minimum struct size.""" self.assertEqual(16, GroupMod().get_size()) class TestBucket(TestCase): """bucket tests.""" def test_min_size(self): """Test minimum struct size.""" self.assertEqual(16, Bucket().get_size()) class TestListBuckets(TestCase): def setUp(self): """Configure raw file and its object in parent class (TestDump).""" super().setUp() self.oxmtlv1 = OxmTLV(oxm_class=OxmClass.OFPXMC_OPENFLOW_BASIC, oxm_field=OxmOfbMatchField.OFPXMT_OFB_METADATA, oxm_hasmask=False, oxm_value=b'\x00\x00\x00\x00\x00\x00\x00\x01') self.oxmtlv2 = OxmTLV(oxm_class=OxmClass.OFPXMC_OPENFLOW_BASIC, oxm_field=OxmOfbMatchField.OFPXMT_OFB_METADATA, oxm_hasmask=False, oxm_value=b'\x00\x00\x00\x00\x00\x00\x00\x02') self.action1 = ActionSetField(field=self.oxmtlv1) self.action2 = ActionSetField(field=self.oxmtlv2) self.action3 = ActionExperimenter(length=16, experimenter=0x00002320, body=b'\x00\x0e\xff\xf8\x28\x00\x00\x00') self.action4 = ActionExperimenter(length=16, experimenter=0x00001223, body=b'\x00\x0e\xff\xff\x28\x00\x00\x00') def test_bucket_list(self): bucket1 = Bucket(length=48, weight=1, watch_port=PortNo.OFPP_ANY, watch_group=PortNo.OFPP_ANY, actions=ListOfActions([self.action1, self.action2])) bucket2 = Bucket(length=80, weight=2, watch_port=PortNo.OFPP_ANY, watch_group=PortNo.OFPP_ANY, actions=ListOfActions([self.action1, self.action2, self.action3, self.action4])) bucket3 = Bucket(length=48, weight=3, watch_port=PortNo.OFPP_ANY, watch_group=PortNo.OFPP_ANY, actions=ListOfActions([self.action3, self.action4])) # Packing buckets buckets = ListOfBuckets([bucket1, bucket2, bucket3]) buff = packed_buff = buckets.pack() # Unpacking buckets bytes unpacked_buckets = ListOfBuckets() unpacked_buckets.unpack(buff) self.assertEqual(len(unpacked_buckets), 3) self.assertEqual(unpacked_buckets[0].length, 48) self.assertEqual(unpacked_buckets[0].weight, 1) self.assertEqual(len(unpacked_buckets[0].actions), 2) self.assertEqual(unpacked_buckets[0].actions[0].field.oxm_value, self.oxmtlv1.oxm_value) self.assertEqual(unpacked_buckets[0].actions[1].field.oxm_value, self.oxmtlv2.oxm_value) self.assertEqual(unpacked_buckets[1].length, 80) self.assertEqual(unpacked_buckets[1].weight, 2) self.assertEqual(len(unpacked_buckets[1].actions), 4) self.assertEqual(unpacked_buckets[1].actions[0].field.oxm_value, self.oxmtlv1.oxm_value) self.assertEqual(unpacked_buckets[1].actions[1].field.oxm_value, self.oxmtlv2.oxm_value) self.assertEqual(unpacked_buckets[1].actions[2].body, self.action3.body) self.assertEqual(unpacked_buckets[1].actions[3].body, self.action4.body) self.assertEqual(unpacked_buckets[2].length, 48) self.assertEqual(unpacked_buckets[2].weight, 3) self.assertEqual(len(unpacked_buckets[2].actions), 2) self.assertEqual(unpacked_buckets[2].actions[0].body, self.action3.body) self.assertEqual(unpacked_buckets[2].actions[1].body, self.action4.body) def test_buckets_one_item(self): bucket1 = Bucket(length=48, weight=1, watch_port=PortNo.OFPP_ANY, watch_group=PortNo.OFPP_ANY, actions=ListOfActions([self.action1, self.action2])) # Packing buckets buckets = ListOfBuckets([bucket1]) buff = packed_buff = buckets.pack() # Unpacking buckets bytes unpacked_buckets = ListOfBuckets() unpacked_buckets.unpack(buff) self.assertEqual(len(unpacked_buckets), 1) self.assertEqual(unpacked_buckets[0].length, 48) self.assertEqual(unpacked_buckets[0].weight, 1) self.assertEqual(len(unpacked_buckets[0].actions), 2) self.assertEqual(unpacked_buckets[0].actions[0].field.oxm_value, self.oxmtlv1.oxm_value) self.assertEqual(unpacked_buckets[0].actions[1].field.oxm_value, self.oxmtlv2.oxm_value) def test_buckets_no_action(self): bucket1 = Bucket(length=48, weight=1, watch_port=PortNo.OFPP_ANY, watch_group=PortNo.OFPP_ANY, actions=ListOfActions([self.action1])) # Packing buckets buckets = ListOfBuckets([bucket1]) buff = packed_buff = buckets.pack() # Unpacking buckets bytes unpacked_buckets = ListOfBuckets() unpacked_buckets.unpack(buff) self.assertEqual(len(unpacked_buckets), 1) self.assertEqual(unpacked_buckets[0].length, 48) self.assertEqual(unpacked_buckets[0].weight, 1) self.assertEqual(len(unpacked_buckets[0].actions), 1) self.assertEqual(unpacked_buckets[0].actions[0].field.oxm_value, self.oxmtlv1.oxm_value)
kytos/python-openflow
tests/unit/v0x04/test_controller2switch/test_group_mod.py
Python
mit
6,137
#-*- coding: utf-8 -*- """ EOSS catalog system Implementation of urthecast catalog access https://developers.urthecast.com/sign-in """ __author__ = "Thilo Wehrmann, Steffen Gebhardt" __copyright__ = "Copyright 2016, EOSS GmbH" __credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Thilo Wehrmann" __email__ = "twehrmann@eoss.cloud" __status__ = "Production" import requests from manage import ICatalog from model.plain_models import Catalog_Dataset from shapely.geometry import Polygon from shapely.wkt import dumps as wkt_dumps class UrthecastCatalog(ICatalog): def __init__(self): # api_key = os.environ['UC_API_KEY'] # api_secret = os.environ['UC_API_SECRET'] self.api_key = 'B47EAFC6559748D4AD62' self.api_secret = 'D796AF0410DB4580876C66B72F790192' self.url = 'https://api.urthecast.com/v1/archive/scenes' def find(self, platforms, aoi, date_start, date_stop, cloud_ratio=0.2): url = self.url poly = Polygon(aoi) geometry = wkt_dumps(poly) params = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'cloud_coverage_lte': cloud_ratio, 'acquired_gte': date_start.isoformat(), 'acquired_lte': date_stop.isoformat(), 'geometry_intersects': geometry, # 'sensor_platform': 'deimos-1,deimos-2,theia' 'sensor_platform': ",".join(platforms) } result = requests.get(url, params=params) datasets = set() for r in result.json()['payload']: ds = Catalog_Dataset() ds.entity_id = r['owner_scene_id'] ds.acq_time = r['acquired'] ds.sensor = r['sensor_platform'] # ds.tile_identifier = r['tile_identifier'] ds.clouds = r['cloud_coverage'] # ds.level = r['level'] if int(ds.clouds) > 0: ds.daynight = 'day' else: ds.daynight = 'night' datasets.add(ds) return datasets def register(self, ds): raise Exception('Cannot register dataset in repository %s' % self.__class__.__name__)
eoss-cloud/madxxx_catalog_api
catalog/manage/urthecastcatalog.py
Python
mit
2,226
require 'test_helper' class ConfirmationsControllerTest < ActionController::TestCase test "should get new" do get :new assert_response :success end test "should get create" do get :create assert_response :success end end
helmlogic/catalyst
test/functional/confirmations_controller_test.rb
Ruby
mit
248
import sqlalchemy class Connection(object): def __init__(self, auth): url = self._build_url(auth) self.engine = sqlalchemy.create_engine(url, convert_unicode=True) self.connection = None self.transaction = None def connect(self): self.connection = self.engine.connect() def disconnect(self): self.connection.close() self.connection = None def execute(self, sql_query): if not self.is_connected(): self.connect() return self.connection.execute(sql_query) def begin_transaction(self): if not self.is_connected(): self.connect() self.transaction = self.connection.begin() def end_transaction(self): self.transaction.commit() self.transaction = None def is_connected(self): return self.connection is not None def _build_url(self, auth): def get_value(data, keys, default=None): result = None for k in keys: result = data.get(k) if result is not None: return result if result is None: return default db_type = get_value(auth, ['type', 'db_type'], 'pgsql') if db_type == 'mysql': default_port = 3306 elif db_type == 'pgsql': default_port = 5432 ctx = (get_value(auth, ['user']), get_value(auth, ['passwd', 'password', 'pass']), get_value(auth, ['host', 'server'], 'localhost'), get_value(auth, ['port'], default_port), get_value(auth, ['database', 'db_name', 'database_name', 'db'])) if db_type == 'pgsql': url_tpl = 'postgresql+psycopg2://%s:%s@%s:%s/%s' % ctx elif db_type == 'mysql': url_tpl = 'mysql+mysqldb://%s:%s@%s:%s/%s' % ctx else: RaiseValue('db_type must be eighter "mysql" or "pgsql"') return url_tpl % auth
trackingwire/witchcraft
witchcraft/connection.py
Python
mit
2,023
// Copyright (c) 2011-2013 The mitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "mitcoinunits.h" #include "primitives/transaction.h" #include <QStringList> mitcoinUnits::mitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<mitcoinUnits::Unit> mitcoinUnits::availableUnits() { QList<mitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool mitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString mitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("BTC"); case mBTC: return QString("mBTC"); case uBTC: return QString::fromUtf8("μBTC"); default: return QString("???"); } } QString mitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("mitcoins"); case mBTC: return QString("Milli-mitcoins (1 / 1" THIN_SP_UTF8 "000)"); case uBTC: return QString("Micro-mitcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } qint64 mitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int mitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString mitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } // TODO: Review all remaining calls to mitcoinUnits::formatWithUnit to // TODO: determine whether the output is used in a plain text context // TODO: or an HTML context (and replace with // TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully // TODO: there aren't instances where the result could be used in // TODO: either context. // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString mitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + name(unit); } QString mitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } bool mitcoinUnits::parse(int unit, const QString &value, CAmount *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if(val_out) { *val_out = retvalue; } return ok; } QString mitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (mitcoinUnits::valid(unit)) { amountTitle += " ("+mitcoinUnits::name(unit) + ")"; } return amountTitle; } int mitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant mitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } CAmount mitcoinUnits::maxMoney() { return MAX_MONEY; }
anders94/mitcoin
src/qt/mitcoinunits.cpp
C++
mit
5,957
<?php function build_order_no(){ $year_code = array('a','b','c','d','e','f','g','h','i','j'); $order_sn = (intval(date('Y'))- 2014) . strtoupper(dechex(date('m'))) . strtoupper(dechex(date('d'))). substr(time(),-5).substr(microtime(),2,5).sprintf('%d',rand(0,99)); return $order_sn; } $num = 0; while($num < 20){ echo @build_order_no() . "\r\n"; $num ++; }
z32556601/90ping
doc/test.php
PHP
mit
388
'use strict'; var Promise = require('bluebird'); var util = require('./util'); module.exports = function (bookshelf) { var BaseModel = bookshelf.Model.extend({ initialize: function () { this.on('saving', this.validate); }, validate: function (model, attrs, options) { return Promise.resolve(null) .then(util.collectAndCheckMissingAttributes.bind(this, options)) .then(util.validateAttributes.bind(this)) .then(util.setValidatedAttributes.bind(this)); } }); bookshelf.Model = BaseModel; };
murmur76/bookshelf-validation
index.js
JavaScript
mit
545
require 'spec_helper' describe "User", :type => :model do before(:all) do self.class.fixtures :categories, :departments, :notes, :things, :brokens, :users end describe "hierarchical structure" do it "roots_class_method" do found_by_us = User.where(:parent_uuid => nil).to_a found_by_roots = User.roots.to_a expect(found_by_us.length).to eq(found_by_roots.length) found_by_us.each do |root| expect(found_by_roots).to include(root) end end it "root_class_method" do expect(User.root).to eq(users(:top_level)) end it "root" do expect(users(:child_3).root).to eq(users(:top_level)) end it "root when not persisted and parent_column_name value is self" do new_user = User.new expect(new_user.root).to eq(new_user) end it "root?" do expect(users(:top_level).root?).to be_truthy expect(users(:top_level_2).root?).to be_truthy end it "leaves_class_method" do expect(User.where("#{User.right_column_name} - #{User.left_column_name} = 1").to_a.sort_by(&:id)).to eq(User.leaves.to_a) expect(User.leaves.count).to eq(4) expect(User.leaves).to include(users(:child_1)) expect(User.leaves).to include(users(:child_2_1)) expect(User.leaves).to include(users(:child_3)) expect(User.leaves).to include(users(:top_level_2)) end it "leaf" do expect(users(:child_1).leaf?).to be_truthy expect(users(:child_2_1).leaf?).to be_truthy expect(users(:child_3).leaf?).to be_truthy expect(users(:top_level_2).leaf?).to be_truthy expect(users(:top_level).leaf?).to be_falsey expect(users(:child_2).leaf?).to be_falsey expect(User.new.leaf?).to be_falsey end it "parent" do expect(users(:child_2_1).parent).to eq(users(:child_2)) end it "self_and_ancestors" do child = users(:child_2_1) self_and_ancestors = [users(:top_level), users(:child_2), child] expect(child.self_and_ancestors).to eq(self_and_ancestors) end it "ancestors" do child = users(:child_2_1) ancestors = [users(:top_level), users(:child_2)] expect(ancestors).to eq(child.ancestors) end it "self_and_siblings" do child = users(:child_2) self_and_siblings = [users(:child_1), child, users(:child_3)] expect(self_and_siblings).to eq(child.self_and_siblings) expect do tops = [users(:top_level), users(:top_level_2)] assert_equal tops, users(:top_level).self_and_siblings end.not_to raise_exception end it "siblings" do child = users(:child_2) siblings = [users(:child_1), users(:child_3)] expect(siblings).to eq(child.siblings) end it "leaves" do leaves = [users(:child_1), users(:child_2_1), users(:child_3)] expect(users(:top_level).leaves).to eq(leaves) end end describe "level" do it "returns the correct level" do expect(users(:top_level).level).to eq(0) expect(users(:child_1).level).to eq(1) expect(users(:child_2_1).level).to eq(2) end context "given parent associations are loaded" do it "returns the correct level" do child = users(:child_1) if child.respond_to?(:association) child.association(:parent).load_target child.parent.association(:parent).load_target expect(child.level).to eq(1) else skip 'associations not used where child#association is not a method' end end end end describe "depth" do context "in general" do let(:ceo) { User.create!(:name => "CEO") } let(:district_manager) { User.create!(:name => "District Manager") } let(:store_manager) { User.create!(:name => "Store Manager") } let(:cashier) { User.create!(:name => "Cashier") } before(:each) do # ceo > district_manager > store_manager > cashier district_manager.move_to_child_of(ceo) store_manager.move_to_child_of(district_manager) cashier.move_to_child_of(store_manager) [ceo, district_manager, store_manager, cashier].each(&:reload) end it "updates depth when moved into child position" do expect(ceo.depth).to eq(0) expect(district_manager.depth).to eq(1) expect(store_manager.depth).to eq(2) expect(cashier.depth).to eq(3) end it "updates depth of all descendants when parent is moved" do # ceo # district_manager > store_manager > cashier district_manager.move_to_right_of(ceo) [ceo, district_manager, store_manager, cashier].each(&:reload) expect(district_manager.depth).to eq(0) expect(store_manager.depth).to eq(1) expect(cashier.depth).to eq(2) end end it "is magic and does not apply when column is missing" do expect { NoDepth.create!(:name => "shallow") }.not_to raise_error expect { NoDepth.first.save }.not_to raise_error expect { NoDepth.rebuild! }.not_to raise_error expect(NoDepth.method_defined?(:depth)).to be_falsey expect(NoDepth.first.respond_to?(:depth)).to be_falsey end end it "has_children?" do expect(users(:child_2_1).children.empty?).to be_truthy expect(users(:child_2).children.empty?).to be_falsey expect(users(:top_level).children.empty?).to be_falsey end it "self_and_descendants" do parent = users(:top_level) self_and_descendants = [ parent, users(:child_1), users(:child_2), users(:child_2_1), users(:child_3) ] expect(self_and_descendants).to eq(parent.self_and_descendants) expect(self_and_descendants.count).to eq(parent.self_and_descendants.count) end it "descendants" do lawyers = User.create!(:name => "lawyers") us = User.create!(:name => "United States") us.move_to_child_of(lawyers) patent = User.create!(:name => "Patent Law") patent.move_to_child_of(us) lawyers.reload expect(lawyers.children.size).to eq(1) expect(us.children.size).to eq(1) expect(lawyers.descendants.size).to eq(2) end it "self_and_descendants" do parent = users(:top_level) descendants = [ users(:child_1), users(:child_2), users(:child_2_1), users(:child_3) ] expect(descendants).to eq(parent.descendants) end it "children" do user = users(:top_level) user.children.each {|c| expect(user.uuid).to eq(c.parent_uuid) } end it "order_of_children" do users(:child_2).move_left expect(users(:child_2)).to eq(users(:top_level).children[0]) expect(users(:child_1)).to eq(users(:top_level).children[1]) expect(users(:child_3)).to eq(users(:top_level).children[2]) end it "is_or_is_ancestor_of?" do expect(users(:top_level).is_or_is_ancestor_of?(users(:child_1))).to be_truthy expect(users(:top_level).is_or_is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2).is_or_is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2_1).is_or_is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_or_is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_or_is_ancestor_of?(users(:child_1))).to be_truthy end it "is_ancestor_of?" do expect(users(:top_level).is_ancestor_of?(users(:child_1))).to be_truthy expect(users(:top_level).is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2).is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2_1).is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_ancestor_of?(users(:child_1))).to be_falsey end it "is_or_is_ancestor_of_with_scope" do root = ScopedUser.root child = root.children.first expect(root.is_or_is_ancestor_of?(child)).to be_truthy child.update_attribute :organization_id, 999999999 expect(root.is_or_is_ancestor_of?(child)).to be_falsey end it "is_or_is_descendant_of?" do expect(users(:child_1).is_or_is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_or_is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_or_is_descendant_of?(users(:child_2))).to be_truthy expect(users(:child_2).is_or_is_descendant_of?(users(:child_2_1))).to be_falsey expect(users(:child_2).is_or_is_descendant_of?(users(:child_1))).to be_falsey expect(users(:child_1).is_or_is_descendant_of?(users(:child_1))).to be_truthy end it "is_descendant_of?" do expect(users(:child_1).is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_descendant_of?(users(:child_2))).to be_truthy expect(users(:child_2).is_descendant_of?(users(:child_2_1))).to be_falsey expect(users(:child_2).is_descendant_of?(users(:child_1))).to be_falsey expect(users(:child_1).is_descendant_of?(users(:child_1))).to be_falsey end it "is_or_is_descendant_of_with_scope" do root = ScopedUser.root child = root.children.first expect(child.is_or_is_descendant_of?(root)).to be_truthy child.update_attribute :organization_id, 999999999 expect(child.is_or_is_descendant_of?(root)).to be_falsey end it "same_scope?" do root = ScopedUser.root child = root.children.first expect(child.same_scope?(root)).to be_truthy child.update_attribute :organization_id, 999999999 expect(child.same_scope?(root)).to be_falsey end it "left_sibling" do expect(users(:child_1)).to eq(users(:child_2).left_sibling) expect(users(:child_2)).to eq(users(:child_3).left_sibling) end it "left_sibling_of_root" do expect(users(:top_level).left_sibling).to be_nil end it "left_sibling_without_siblings" do expect(users(:child_2_1).left_sibling).to be_nil end it "left_sibling_of_leftmost_node" do expect(users(:child_1).left_sibling).to be_nil end it "right_sibling" do expect(users(:child_3)).to eq(users(:child_2).right_sibling) expect(users(:child_2)).to eq(users(:child_1).right_sibling) end it "right_sibling_of_root" do expect(users(:top_level_2)).to eq(users(:top_level).right_sibling) expect(users(:top_level_2).right_sibling).to be_nil end it "right_sibling_without_siblings" do expect(users(:child_2_1).right_sibling).to be_nil end it "right_sibling_of_rightmost_node" do expect(users(:child_3).right_sibling).to be_nil end it "move_left" do users(:child_2).move_left expect(users(:child_2).left_sibling).to be_nil expect(users(:child_1)).to eq(users(:child_2).right_sibling) expect(User.valid?).to be_truthy end it "move_right" do users(:child_2).move_right expect(users(:child_2).right_sibling).to be_nil expect(users(:child_3)).to eq(users(:child_2).left_sibling) expect(User.valid?).to be_truthy end it "move_to_left_of" do users(:child_3).move_to_left_of(users(:child_1)) expect(users(:child_3).left_sibling).to be_nil expect(users(:child_1)).to eq(users(:child_3).right_sibling) expect(User.valid?).to be_truthy end it "move_to_right_of" do users(:child_1).move_to_right_of(users(:child_3)) expect(users(:child_1).right_sibling).to be_nil expect(users(:child_3)).to eq(users(:child_1).left_sibling) expect(User.valid?).to be_truthy end it "move_to_root" do users(:child_2).move_to_root expect(users(:child_2).parent).to be_nil expect(users(:child_2).level).to eq(0) expect(users(:child_2_1).level).to eq(1) expect(users(:child_2).left).to eq(9) expect(users(:child_2).right).to eq(12) expect(User.valid?).to be_truthy end it "move_to_child_of" do users(:child_1).move_to_child_of(users(:child_3)) expect(users(:child_3).uuid).to eq(users(:child_1).parent_uuid) expect(User.valid?).to be_truthy end describe "#move_to_child_with_index" do it "move to a node without child" do users(:child_1).move_to_child_with_index(users(:child_3), 0) expect(users(:child_3).uuid).to eq(users(:child_1).parent_uuid) expect(users(:child_1).left).to eq(7) expect(users(:child_1).right).to eq(8) expect(users(:child_3).left).to eq(6) expect(users(:child_3).right).to eq(9) expect(User.valid?).to be_truthy end it "move to a node to the left child" do users(:child_1).move_to_child_with_index(users(:child_2), 0) expect(users(:child_1).parent_uuid).to eq(users(:child_2).uuid) expect(users(:child_2_1).left).to eq(5) expect(users(:child_2_1).right).to eq(6) expect(users(:child_1).left).to eq(3) expect(users(:child_1).right).to eq(4) users(:child_2).reload expect(users(:child_2).left).to eq(2) expect(users(:child_2).right).to eq(7) end it "move to a node to the right child" do users(:child_1).move_to_child_with_index(users(:child_2), 1) expect(users(:child_1).parent_uuid).to eq(users(:child_2).uuid) expect(users(:child_2_1).left).to eq(3) expect(users(:child_2_1).right).to eq(4) expect(users(:child_1).left).to eq(5) expect(users(:child_1).right).to eq(6) users(:child_2).reload expect(users(:child_2).left).to eq(2) expect(users(:child_2).right).to eq(7) end end it "move_to_child_of_appends_to_end" do child = User.create! :name => 'New Child' child.move_to_child_of users(:top_level) expect(child).to eq(users(:top_level).children.last) end it "subtree_move_to_child_of" do expect(users(:child_2).left).to eq(4) expect(users(:child_2).right).to eq(7) expect(users(:child_1).left).to eq(2) expect(users(:child_1).right).to eq(3) users(:child_2).move_to_child_of(users(:child_1)) expect(User.valid?).to be_truthy expect(users(:child_1).uuid).to eq(users(:child_2).parent_uuid) expect(users(:child_2).left).to eq(3) expect(users(:child_2).right).to eq(6) expect(users(:child_1).left).to eq(2) expect(users(:child_1).right).to eq(7) end it "slightly_difficult_move_to_child_of" do expect(users(:top_level_2).left).to eq(11) expect(users(:top_level_2).right).to eq(12) # create a new top-level node and move single-node top-level tree inside it. new_top = User.create(:name => 'New Top') expect(new_top.left).to eq(13) expect(new_top.right).to eq(14) users(:top_level_2).move_to_child_of(new_top) expect(User.valid?).to be_truthy expect(new_top.uuid).to eq(users(:top_level_2).parent_uuid) expect(users(:top_level_2).left).to eq(12) expect(users(:top_level_2).right).to eq(13) expect(new_top.left).to eq(11) expect(new_top.right).to eq(14) end it "difficult_move_to_child_of" do expect(users(:top_level).left).to eq(1) expect(users(:top_level).right).to eq(10) expect(users(:child_2_1).left).to eq(5) expect(users(:child_2_1).right).to eq(6) # create a new top-level node and move an entire top-level tree inside it. new_top = User.create(:name => 'New Top') users(:top_level).move_to_child_of(new_top) users(:child_2_1).reload expect(User.valid?).to be_truthy expect(new_top.uuid).to eq(users(:top_level).parent_uuid) expect(users(:top_level).left).to eq(4) expect(users(:top_level).right).to eq(13) expect(users(:child_2_1).left).to eq(8) expect(users(:child_2_1).right).to eq(9) end #rebuild swaps the position of the 2 children when added using move_to_child twice onto same parent it "move_to_child_more_than_once_per_parent_rebuild" do root1 = User.create(:name => 'Root1') root2 = User.create(:name => 'Root2') root3 = User.create(:name => 'Root3') root2.move_to_child_of root1 root3.move_to_child_of root1 output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.roots.last.to_text).to eq(output) end # doing move_to_child twice onto same parent from the furthest right first it "move_to_child_more_than_once_per_parent_outside_in" do node1 = User.create(:name => 'Node-1') node2 = User.create(:name => 'Node-2') node3 = User.create(:name => 'Node-3') node2.move_to_child_of node1 node3.move_to_child_of node1 output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.roots.last.to_text).to eq(output) end it "should_move_to_ordered_child" do node1 = User.create(:name => 'Node-1') node2 = User.create(:name => 'Node-2') node3 = User.create(:name => 'Node-3') node2.move_to_ordered_child_of(node1, "name") assert_equal node1, node2.parent assert_equal 1, node1.children.count node3.move_to_ordered_child_of(node1, "name", true) # ascending expect(node3.parent).to eq(node1) expect(node1.children.count).to be(2) expect(node1.children[0].name).to eq(node2.name) expect(node1.children[1].name).to eq(node3.name) node3.move_to_ordered_child_of(node1, "name", false) # descending node1.reload expect(node3.parent).to eq(node1) expect(node1.children.count).to be(2) expect(node1.children[0].name).to eq(node3.name) expect(node1.children[1].name).to eq(node2.name) end it "should be able to rebuild without validating each record" do root1 = User.create(:name => 'Root1') root2 = User.create(:name => 'Root2') root3 = User.create(:name => 'Root3') root2.move_to_child_of root1 root3.move_to_child_of root1 root2.name = nil root2.save!(:validate => false) output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild!(false) expect(User.roots.last.to_text).to eq(output) end it "valid_with_null_lefts" do expect(User.valid?).to be_truthy User.update_all('lft = null') expect(User.valid?).to be_falsey end it "valid_with_null_rights" do expect(User.valid?).to be_truthy User.update_all('rgt = null') expect(User.valid?).to be_falsey end it "valid_with_missing_intermediate_node" do # Even though child_2_1 will still exist, it is a sign of a sloppy delete, not an invalid tree. expect(User.valid?).to be_truthy User.where(uuid: users(:child_2).uuid).delete_all expect(User.valid?).to be_truthy end it "valid_with_overlapping_and_rights" do expect(User.valid?).to be_truthy users(:top_level_2)['lft'] = 0 users(:top_level_2).save expect(User.valid?).to be_falsey end it "rebuild" do expect(User.valid?).to be_truthy before_text = User.root.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.valid?).to be_truthy expect(before_text).to eq(User.root.to_text) end it "move_possible_for_sibling" do expect(users(:child_2).move_possible?(users(:child_1))).to be_truthy end it "move_not_possible_to_self" do expect(users(:top_level).move_possible?(users(:top_level))).to be_falsey end it "move_not_possible_to_parent" do users(:top_level).descendants.each do |descendant| expect(users(:top_level).move_possible?(descendant)).to be_falsey expect(descendant.move_possible?(users(:top_level))).to be_truthy end end it "is_or_is_ancestor_of?" do [:child_1, :child_2, :child_2_1, :child_3].each do |c| expect(users(:top_level).is_or_is_ancestor_of?(users(c))).to be_truthy end expect(users(:top_level).is_or_is_ancestor_of?(users(:top_level_2))).to be_falsey end it "left_and_rights_valid_with_blank_left" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:lft] = nil users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_blank_right" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:rgt] = nil users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_equal" do expect(User.left_and_rights_valid?).to be_truthy users(:top_level_2)[:lft] = users(:top_level_2)[:rgt] users(:top_level_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_left_equal_to_parent" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:lft] = users(:top_level)[:lft] users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_right_equal_to_parent" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:rgt] = users(:top_level)[:rgt] users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "moving_dirty_objects_doesnt_invalidate_tree" do r1 = User.create :name => "Test 1" r2 = User.create :name => "Test 2" r3 = User.create :name => "Test 3" r4 = User.create :name => "Test 4" nodes = [r1, r2, r3, r4] r2.move_to_child_of(r1) expect(User.valid?).to be_truthy r3.move_to_child_of(r1) expect(User.valid?).to be_truthy r4.move_to_child_of(r2) expect(User.valid?).to be_truthy end it "delete_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :delete users(:child_2).destroy expect(User.valid?).to be_truthy end it "destroy_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :destroy users(:child_2).destroy expect(User.valid?).to be_truthy end it "destroy_multiple_times_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :destroy users(:child_2).destroy users(:child_2).destroy expect(User.valid?).to be_truthy end it "assigning_parent_uuid_on_create" do user = User.create!(:name => "Child", :parent_uuid => users(:child_2).uuid) expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_on_create" do user = User.create!(:name => "Child", :parent => users(:child_2)) expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_uuid_to_nil_on_create" do user = User.create!(:name => "New Root", :parent_uuid => nil) expect(user.parent).to be_nil expect(user.parent_uuid).to be_nil expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_uuid_on_update" do user = users(:child_2_1) user.parent_uuid = users(:child_3).uuid user.save user.reload users(:child_3).reload expect(users(:child_3)).to eq(user.parent) expect(users(:child_3).uuid).to eq(user.parent_uuid) expect(User.valid?).to be_truthy end it "assigning_parent_on_update" do user = users(:child_2_1) user.parent = users(:child_3) user.save user.reload users(:child_3).reload expect(users(:child_3)).to eq(user.parent) expect(users(:child_3).uuid).to eq(user.parent_uuid) expect(User.valid?).to be_truthy end it "assigning_parent_uuid_to_nil_on_update" do user = users(:child_2_1) user.parent_uuid = nil user.save expect(user.parent).to be_nil expect(user.parent_uuid).to be_nil expect(User.valid?).to be_truthy end it "creating_child_from_parent" do user = users(:child_2).children.create!(:name => "Child") expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it 'creates user when clause where provided' do parent = User.first expect do User.where(name: "Chris-#{Time.current.to_f}").first_or_create! do |user| user.parent = parent end end.to change { User.count }.by 1 end def check_structure(entries, structure) structure = structure.dup User.each_with_level(entries) do |user, level| expected_level, expected_name = structure.shift expect(expected_name).to eq(user.name) expect(expected_level).to eq(level) end end it "each_with_level" do levels = [ [0, "Top Level"], [1, "Child 1"], [1, "Child 2"], [2, "Child 2.1"], [1, "Child 3" ] ] check_structure(User.root.self_and_descendants, levels) # test some deeper structures user = User.find_by_name("Child 1") c1 = User.new(:name => "Child 1.1") c2 = User.new(:name => "Child 1.1.1") c3 = User.new(:name => "Child 1.1.1.1") c4 = User.new(:name => "Child 1.2") [c1, c2, c3, c4].each(&:save!) c1.move_to_child_of(user) c2.move_to_child_of(c1) c3.move_to_child_of(c2) c4.move_to_child_of(user) levels = [ [0, "Top Level"], [1, "Child 1"], [2, "Child 1.1"], [3, "Child 1.1.1"], [4, "Child 1.1.1.1"], [2, "Child 1.2"], [1, "Child 2"], [2, "Child 2.1"], [1, "Child 3" ] ] check_structure(User.root.self_and_descendants, levels) end describe "before_move_callback" do it "should fire the callback" do expect(users(:child_2)).to receive(:custom_before_move) users(:child_2).move_to_root end it "should stop move when callback returns false" do User.test_allows_move = false expect(users(:child_3).move_to_root).to be_falsey expect(users(:child_3).root?).to be_falsey end it "should not halt save actions" do User.test_allows_move = false users(:child_3).parent_uuid = nil expect(users(:child_3).save).to be_truthy end end describe 'associate_parents' do it 'assigns parent' do root = User.root users = root.self_and_descendants users = User.associate_parents users expect(users[1].parent).to be users.first end it 'adds children on inverse of association' do root = User.root users = root.self_and_descendants users = User.associate_parents users expect(users[0].children.first).to be users[1] end end describe 'option dependent' do it 'destroy should destroy children and node' do User.acts_as_nested_set_options[:dependent] = :destroy root = User.root root.destroy! expect(User.where(uuid: root.uuid)).to be_empty expect(User.where(parent_uuid: root.uuid)).to be_empty end it 'delete should delete children and node' do User.acts_as_nested_set_options[:dependent] = :delete root = User.root root.destroy! expect(User.where(uuid: root.uuid)).to be_empty expect(User.where(parent_uuid: root.uuid)).to be_empty end describe 'restrict_with_exception' do it 'raises an exception' do User.acts_as_nested_set_options[:dependent] = :restrict_with_exception root = User.root expect { root.destroy! }.to raise_error ActiveRecord::DeleteRestrictionError, 'Cannot delete record because of dependent children' end it 'deletes the leaf' do User.acts_as_nested_set_options[:dependent] = :restrict_with_exception leaf = User.last expect(leaf.destroy).to eq(leaf) end end describe 'restrict_with_error' do it 'adds the error to the parent' do User.acts_as_nested_set_options[:dependent] = :restrict_with_error root = User.root root.destroy expect(root.errors[:base]).to eq(["Cannot delete record because dependent children exist"]) end it 'deletes the leaf' do User.acts_as_nested_set_options[:dependent] = :restrict_with_error leaf = User.last expect(leaf.destroy).to eq(leaf) end end end end
collectiveidea/awesome_nested_set
spec/models/users_spec.rb
Ruby
mit
28,195
#dice guideline from random import randint #FOR program module moduleName="Dice Module" #moduleName="The Lusty Orc Dice Module" #FOR dice rolls #mulligan_yes_or_no=True not implemented the_lowest_possible_roll=1 the_number_of_sides_on_a_die=6 the_number_of_rolls_in_a_set=4 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=1 #Rules for attribute rolls, Do not alter anything past this line ''' def dicerollbatch(): WorkingBatch=[] for setNumber in range(self.dieSets): rolls=[] dropped=[] #creates another recursion loop that runs for die_number_per_set times and addes a random roll result to the rolls and dropped lists using the x variable, each roll is between the values lowest_possible_roll and number_of_sides_on_die for roll in range(self.setDieNumber): r=(randint(lowest_possible_roll, self.dieSides)) rolls.append(r) dropped.append(r) #after the rolls are done, normally 4 of them, the set is added to the rollBatch variable container as well as adding to the dropped sets container self.rollBatch.append(rolls) dropped.remove(min(dropped)) self.droppedBatch.append(dropped) #after the roll sets have been added to the batch the batch count is incremented up one self.batch+=1 #after the numbers have been generated and appended to the batch the sets are printed out vertically print("number of batch attempts:"+str(self.batch)+"\nStat Rolls") for batchSets in range(len(self.rollBatch)): at=0 for batchRolls in range(len(self.droppedBatch[batchSets])):at+=self.droppedBatch[batchSets][batchRolls] self.attributeResults.append(at) print((self.rollBatch[batchSets]), (self.attributeResults[batchSets])) ''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls_print from random import randint The_number_of_rolls_in_a_set=4 The_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 #the followign 6 lines of code roll 4 numbers between 1 and 6 and then prints them out vertically def roll_set_of_dice(): for roll in range(The_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, The_number_of_sides_on_a_die)) print("%s" % roll_result) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls_output_to_list_print_list from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 #the following 8 lines of code rolls 4 6 sided dice and copies the reuslts to a lsit and then print's the list def roll_set_of_dice(): set_of_dice_rolls=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) set_of_dice_rolls.append(roll_result) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls with reroll and output from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=5 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls if drop lowest or highest is greater than zero copy set_of_dice_rolls to set_of_dice_rolls_adjusted from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=0 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] set_of_dice_rolls_adjusted=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) if (number_of_lowest_rolls_to_drop_in_a_set>0) or (number_of_highest_rolls_to_drop_in_a_set>0): for roll_results in range(len(set_of_dice_rolls)): set_of_dice_rolls_adjusted.append(set_of_dice_rolls[roll_results]) print(set_of_dice_rolls_adjusted) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls drop highest and lowest from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=1 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] set_of_dice_rolls_adjusted=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) for roll_results in range(len(set_of_dice_rolls)): set_of_dice_rolls_adjusted.append(set_of_dice_rolls[roll_results]) print("\n////Break////\n%s\n%s\n////Break////\n" % (set_of_dice_rolls, set_of_dice_rolls_adjusted)) if (number_of_lowest_rolls_to_drop_in_a_set>0) or (number_of_highest_rolls_to_drop_in_a_set>0): if number_of_lowest_rolls_to_drop_in_a_set>0: drop_counter=0 drop_counter+=number_of_lowest_rolls_to_drop_in_a_set #print(set_of_dice_rolls_adjusted) #print(drop_counter) while drop_counter>0: set_of_dice_rolls_adjusted.remove(min(set_of_dice_rolls_adjusted)) #print(set_of_dice_rolls_adjusted) drop_counter-=1 #print(drop_counter) if number_of_highest_rolls_to_drop_in_a_set>0: drop_counter=0 drop_counter+=number_of_highest_rolls_to_drop_in_a_set #print(set_of_dice_rolls_adjusted) #print(drop_counter) while drop_counter>0: set_of_dice_rolls_adjusted.remove(max(set_of_dice_rolls_adjusted)) #print(set_of_dice_rolls_adjusted) drop_counter-=1 #print(drop_counter) print("\n////Break////\n%s\n%s\n////Break////\n" % (set_of_dice_rolls, set_of_dice_rolls_adjusted)) return roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
RZMC/dndCharGen
dice guideline.py
Python
mit
7,477
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, name: { type: Sequelize.STRING }, username: { type: Sequelize.STRING, allowNull: false, unique: true }, password: { type: Sequelize.STRING, allowNull: false }, salt: { type: Sequelize.STRING, allowNull: false }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('users'); } };
geanjunior/cracha
migrations/20170127020036-create-user.js
JavaScript
mit
1,093