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
'use strict'; // Disable eval and Buffer. window.eval = global.eval = global.Buffer = function() { throw new Error("Can't use eval and Buffer."); } const Electron = require('electron') const IpcRenderer = Electron.ipcRenderer; var Urlin = null; // element of input text window.addEventListener('load', ()=> { Urlin = document.getElementById('input-url'); Urlin.addEventListener("keypress", (event)=>{ if(13!=event.keyCode) return; Urlin.blur(); IpcRenderer.sendToHost('url-input', Urlin.value); }, false); }, false); IpcRenderer.on('url-input', (event, s_url)=>{ Urlin.value = s_url; });
yujakudo/glasspot
app/header.js
JavaScript
mit
639
var roshamboApp = angular.module('roshamboApp', []), roshambo= [ { name:'Rock', src:'img/rock.png' }, { name:'Paper', src:'img/paper.png' }, { name:'Scissors', src:'img/scissors.png' } ], roshamboMap=roshambo.reduce(function(roshamboMap,thro){ roshamboMap[thro.name.toLowerCase()]=thro.src; return roshamboMap; },{}); roshamboApp.controller('RoshamboCtrl', function ($scope,$http) { $scope.roshambo=roshambo; $scope.selection=roshambo[0]; $scope.outcome=void 0; $scope.selectThrow=function(selected){ $scope.outcome=void 0; $scope.selection=selected; }; $scope.throwSelected=function(){ $http.post('http://localhost:8080/api/throw',{playerThrow:$scope.selection.name}) .then(function(successResponse){ $scope.outcome=successResponse.data; $scope.outcome.playerSrc=roshamboMap[$scope.outcome.playerThrow]; $scope.outcome.opponentSrc=roshamboMap[$scope.outcome.opponentThrow]; $scope.outcome.announce=function(){ if($scope.outcome.outcome==='draw'){ return 'It\'s a Draw!'; }else{ return $scope.outcome.outcome.charAt(0).toUpperCase()+$scope.outcome.outcome.slice(1)+' Wins!'; } } },function(errorResponse){ alert('Error!'); console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2)); }); }; });
timfulmer/jswla-advanced
app/app.js
JavaScript
mit
1,479
"use strict"; module.exports = { "wires.json": { ":path/": `./path-`, }, "path-test.js"() { module.exports = `parent`; }, "/child": { "wires-defaults.json": { ":path/": `./defaults-`, }, "wires.json": { ":path/": `./child-`, }, "defaults-test.js"() { module.exports = `defaults`; }, "child-test.js"() { module.exports = `child`; }, "dirRouteOverride.unit.js"() { module.exports = { "dir route override"( __ ) { __.expect( 1 ); __.strictEqual( require( `:path/test` ), `child` ); __.done(); }, }; }, }, };
jaubourg/wires
test/units/common/dirRoutesOverride.dirunit.js
JavaScript
mit
790
import random class ai: def __init__(self, actions, responses): self.IN = actions self.OUT = responses def get_act(self, action, valres): if action in self.IN: mList = {} for response in self.OUT: if self.IN[self.OUT.index(response)] == action and not response in mList: mList[response] = 1 elif response in mList: mList[response] += 1 print mList keys = [] vals = [] for v in sorted(mList.values(), reverse = True): for k in mList.keys(): if mList[k] == v: keys.append(k) vals.append(v) print keys print vals try: resp = keys[valres] except: resp = random.choice(self.OUT) else: resp = random.choice(self.OUT) return resp def update(ins, outs): self.IN = ins self.OUT = outs def test(): stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'], ['run', 'cheer', 'share lunch', 'fall', 'run']) print stix.get_act('attack', 0) #test()
iTecAI/Stixai
Module/Stixai.py
Python
mit
1,343
<?php return array ( 'id' => 'mot_e398b_ver2', 'fallback' => 'mot_e398_ver1', 'capabilities' => array ( 'model_name' => 'E398B', ), );
cuckata23/wurfl-data
data/mot_e398b_ver2.php
PHP
mit
150
/** moduleBank constants * */ import { ModuleCode } from '../types/modules'; export const FETCH_MODULE = 'FETCH_MODULE' as const; // Action to fetch modules export const FETCH_MODULE_LIST = 'FETCH_MODULE_LIST' as const; export const UPDATE_MODULE_TIMESTAMP = 'UPDATE_MODULE_TIMESTAMP' as const; export const REMOVE_LRU_MODULE = 'REMOVE_LRU_MODULE' as const; export const FETCH_ARCHIVE_MODULE = 'FETCH_ARCHIVE_MODULE' as const; // Action to fetch module from previous years export type RequestType = | typeof FETCH_MODULE | typeof FETCH_MODULE_LIST | typeof UPDATE_MODULE_TIMESTAMP | typeof REMOVE_LRU_MODULE | typeof FETCH_ARCHIVE_MODULE; export function fetchModuleRequest(moduleCode: ModuleCode) { return `${FETCH_MODULE}/${moduleCode}`; } export function getRequestModuleCode(key: string): ModuleCode | null { const parts = key.split('/'); if (parts.length === 2 && parts[0] === FETCH_MODULE) return parts[1]; return null; } export function fetchArchiveRequest(moduleCode: ModuleCode, year: string) { return `${FETCH_ARCHIVE_MODULE}_${moduleCode}_${year}`; } /** undoHistory constants * */ export const UNDO = 'UNDO' as const; export const REDO = 'REDO' as const; /** export constant(s) * */ export const SET_EXPORTED_DATA = 'SET_EXPORTED_DATA' as const;
nusmodifications/nusmods
website/src/actions/constants.ts
TypeScript
mit
1,288
# pylint: disable-msg=too-many-lines """OPP Hardware interface. Contains the hardware interface and drivers for the Open Pinball Project platform hardware, including the solenoid, input, incandescent, and neopixel boards. """ import asyncio from collections import defaultdict from typing import Dict, List, Set, Union, Tuple, Optional # pylint: disable-msg=cyclic-import,unused-import from mpf.core.platform_batch_light_system import PlatformBatchLightSystem from mpf.core.utility_functions import Util from mpf.platforms.base_serial_communicator import HEX_FORMAT from mpf.platforms.interfaces.driver_platform_interface import PulseSettings, HoldSettings from mpf.platforms.opp.opp_coil import OPPSolenoidCard from mpf.platforms.opp.opp_incand import OPPIncandCard from mpf.platforms.opp.opp_modern_lights import OPPModernLightChannel, OPPNeopixelCard, OPPModernMatrixLightsCard from mpf.platforms.opp.opp_serial_communicator import OPPSerialCommunicator, BAD_FW_VERSION from mpf.platforms.opp.opp_switch import OPPInputCard from mpf.platforms.opp.opp_switch import OPPMatrixCard from mpf.platforms.opp.opp_rs232_intf import OppRs232Intf from mpf.core.platform import SwitchPlatform, DriverPlatform, LightsPlatform, SwitchSettings, DriverSettings, \ DriverConfig, SwitchConfig, RepulseSettings MYPY = False if MYPY: # pragma: no cover from mpf.platforms.opp.opp_coil import OPPSolenoid # pylint: disable-msg=cyclic-import,unused-import from mpf.platforms.opp.opp_incand import OPPIncand # pylint: disable-msg=cyclic-import,unused-import from mpf.platforms.opp.opp_switch import OPPSwitch # pylint: disable-msg=cyclic-import,unused-import # pylint: disable-msg=too-many-instance-attributes class OppHardwarePlatform(LightsPlatform, SwitchPlatform, DriverPlatform): """Platform class for the OPP hardware. Args: ---- machine: The main ``MachineController`` instance. """ __slots__ = ["opp_connection", "serial_connections", "opp_incands", "opp_solenoid", "sol_dict", "opp_inputs", "inp_dict", "inp_addr_dict", "matrix_inp_addr_dict", "read_input_msg", "neo_card_dict", "num_gen2_brd", "gen2_addr_arr", "bad_crc", "min_version", "_poll_task", "config", "_poll_response_received", "machine_type", "opp_commands", "_incand_task", "_light_system", "matrix_light_cards"] def __init__(self, machine) -> None: """Initialise OPP platform.""" super().__init__(machine) self.opp_connection = {} # type: Dict[str, OPPSerialCommunicator] self.serial_connections = set() # type: Set[OPPSerialCommunicator] self.opp_incands = dict() # type: Dict[str, OPPIncandCard] self.opp_solenoid = [] # type: List[OPPSolenoidCard] self.sol_dict = dict() # type: Dict[str, OPPSolenoid] self.opp_inputs = [] # type: List[Union[OPPInputCard, OPPMatrixCard]] self.inp_dict = dict() # type: Dict[str, OPPSwitch] self.inp_addr_dict = dict() # type: Dict[str, OPPInputCard] self.matrix_inp_addr_dict = dict() # type: Dict[str, OPPMatrixCard] self.read_input_msg = {} # type: Dict[str, bytes] self.neo_card_dict = dict() # type: Dict[str, OPPNeopixelCard] self.matrix_light_cards = dict() # type: Dict[str, OPPModernMatrixLightsCard] self.num_gen2_brd = 0 self.gen2_addr_arr = {} # type: Dict[str, Dict[int, Optional[int]]] self.bad_crc = defaultdict(lambda: 0) self.min_version = defaultdict(lambda: 0xffffffff) # type: Dict[str, int] self._poll_task = {} # type: Dict[str, asyncio.Task] self._incand_task = None # type: Optional[asyncio.Task] self._light_system = None # type: Optional[PlatformBatchLightSystem] self.features['tickless'] = True self.config = self.machine.config_validator.validate_config("opp", self.machine.config.get('opp', {})) self._configure_device_logging_and_debug("OPP", self.config) self._poll_response_received = {} # type: Dict[str, asyncio.Event] assert self.log is not None if self.config['driverboards']: self.machine_type = self.config['driverboards'] else: self.machine_type = self.machine.config['hardware']['driverboards'].lower() if self.machine_type == 'gen1': raise AssertionError("Original OPP boards not currently supported.") if self.machine_type == 'gen2': self.debug_log("Configuring the OPP Gen2 boards") else: self.raise_config_error('Invalid driverboards type: {}'.format(self.machine_type), 15) # Only including responses that should be received self.opp_commands = { ord(OppRs232Intf.INV_CMD): self.inv_resp, ord(OppRs232Intf.EOM_CMD): self.eom_resp, ord(OppRs232Intf.GET_GEN2_CFG): self.get_gen2_cfg_resp, ord(OppRs232Intf.READ_GEN2_INP_CMD): self.read_gen2_inp_resp_initial, ord(OppRs232Intf.GET_VERS_CMD): self.vers_resp, ord(OppRs232Intf.READ_MATRIX_INP): self.read_matrix_inp_resp_initial, } async def initialize(self): """Initialise connections to OPP hardware.""" await self._connect_to_hardware() self.opp_commands[ord(OppRs232Intf.READ_GEN2_INP_CMD)] = self.read_gen2_inp_resp self.opp_commands[ord(OppRs232Intf.READ_MATRIX_INP)] = self.read_matrix_inp_resp self._light_system = PlatformBatchLightSystem(self.machine.clock, self._send_multiple_light_update, self.machine.config['mpf']['default_light_hw_update_hz'], 128) async def _send_multiple_light_update(self, sequential_brightness_list: List[Tuple[OPPModernLightChannel, float, int]]): first_light, _, common_fade_ms = sequential_brightness_list[0] number_leds = len(sequential_brightness_list) msg = bytearray() msg.append(int(ord(OppRs232Intf.CARD_ID_GEN2_CARD) + first_light.addr)) msg.append(OppRs232Intf.SERIAL_LED_CMD_FADE) msg.append(int(first_light.pixel_num / 256)) msg.append(int(first_light.pixel_num % 256)) msg.append(int(number_leds / 256)) msg.append(int(number_leds % 256)) msg.append(int(common_fade_ms / 256)) msg.append(int(common_fade_ms % 256)) for _, brightness, _ in sequential_brightness_list: msg.append(int(brightness * 255)) msg.extend(OppRs232Intf.calc_crc8_whole_msg(msg)) cmd = bytes(msg) if self.debug: self.debug_log("Set color on %s: %s", first_light.chain_serial, "".join(HEX_FORMAT % b for b in cmd)) self.send_to_processor(first_light.chain_serial, cmd) async def start(self): """Start polling and listening for commands.""" # start polling for chain_serial in self.read_input_msg: self._poll_task[chain_serial] = self.machine.clock.loop.create_task(self._poll_sender(chain_serial)) self._poll_task[chain_serial].add_done_callback(Util.raise_exceptions) # start listening for commands for connection in self.serial_connections: await connection.start_read_loop() if [version for version in self.min_version.values() if version < 0x02010000]: # if we run any CPUs with firmware prior to 2.1.0 start incands updater self._incand_task = self.machine.clock.schedule_interval(self.update_incand, 1 / self.config['incand_update_hz']) self._light_system.start() def stop(self): """Stop hardware and close connections.""" if self._light_system: self._light_system.stop() for task in self._poll_task.values(): task.cancel() self._poll_task = {} if self._incand_task: self._incand_task.cancel() self._incand_task = None for connections in self.serial_connections: connections.stop() self.serial_connections = [] def __repr__(self): """Return string representation.""" return '<Platform.OPP>' def process_received_message(self, chain_serial, msg): """Send an incoming message from the OPP hardware to the proper method for servicing. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ if len(msg) >= 1: # Verify valid Gen2 address if (msg[0] & 0xe0) == 0x20: if len(msg) >= 2: cmd = msg[1] else: cmd = OppRs232Intf.ILLEGAL_CMD # Look for EOM or INV commands elif msg[0] == ord(OppRs232Intf.INV_CMD) or msg[0] == ord(OppRs232Intf.EOM_CMD): cmd = msg[0] else: cmd = OppRs232Intf.ILLEGAL_CMD else: # No messages received, fake an EOM cmd = OppRs232Intf.EOM_CMD # Can't use try since it swallows too many errors for now if cmd in self.opp_commands: self.opp_commands[cmd](chain_serial, msg) else: self.log.warning("Received unknown serial command?%s. (This is " "very worrisome.)", "".join(HEX_FORMAT % b for b in msg)) # TODO: This means synchronization is lost. Send EOM characters # until they come back self.opp_connection[chain_serial].lost_synch() @staticmethod def _get_numbers(mask): number = 0 ref = 1 result = [] while mask > ref: if mask & ref: result.append(number) number += 1 ref = ref << 1 return result def get_info_string(self): """Dump infos about boards.""" if not self.serial_connections: return "No connection to any CPU board." infos = "Connected CPUs:\n" for connection in sorted(self.serial_connections, key=lambda x: x.chain_serial): infos += " - Port: {} at {} baud. Chain Serial: {}\n".format(connection.port, connection.baud, connection.chain_serial) for board_id, board_firmware in self.gen2_addr_arr[connection.chain_serial].items(): if board_firmware is None: infos += " -> Board: 0x{:02x} Firmware: broken\n".format(board_id) else: infos += " -> Board: 0x{:02x} Firmware: 0x{:02x}\n".format(board_id, board_firmware) infos += "\nIncand cards:\n" if self.opp_incands else "" card_format_string = " - Chain: {} Board: 0x{:02x} Card: {} Numbers: {}\n" for incand in self.opp_incands.values(): infos += card_format_string.format(incand.chain_serial, incand.addr, incand.card_num, self._get_numbers(incand.mask)) infos += "\nInput cards:\n" for inputs in self.opp_inputs: infos += card_format_string.format(inputs.chain_serial, inputs.addr, inputs.card_num, self._get_numbers(inputs.mask)) infos += "\nSolenoid cards:\n" for outputs in self.opp_solenoid: infos += card_format_string.format(outputs.chain_serial, outputs.addr, outputs.card_num, self._get_numbers(outputs.mask)) infos += "\nLEDs:\n" if self.neo_card_dict else "" for leds in self.neo_card_dict.values(): infos += " - Chain: {} Board: 0x{:02x} Card: {}\n".format(leds.chain_serial, leds.addr, leds.card_num) infos += "\nMatrix lights:\n" if self.matrix_light_cards else '' for matrix_light in self.matrix_light_cards.values(): infos += " - Chain: {} Board: 0x{:02x} Card: {} Numbers: 0 - 63\n".format( matrix_light.chain_serial, matrix_light.addr, matrix_light.card_num) return infos async def _connect_to_hardware(self): """Connect to each port from the config. This process will cause the OPPSerialCommunicator to figure out which chains they've connected to and to register themselves. """ port_chain_serial_map = {v: k for k, v in self.config['chains'].items()} for port in self.config['ports']: # overwrite serial if defined for port overwrite_chain_serial = port_chain_serial_map.get(port, None) if overwrite_chain_serial is None and len(self.config['ports']) == 1: overwrite_chain_serial = port comm = OPPSerialCommunicator(platform=self, port=port, baud=self.config['baud'], overwrite_serial=overwrite_chain_serial) await comm.connect() self.serial_connections.add(comm) for chain_serial, versions in self.gen2_addr_arr.items(): for chain_id, version in versions.items(): if not version: self.raise_config_error("Could not read version for board {}-{}.".format(chain_serial, chain_id), 16) if self.min_version[chain_serial] != version: self.raise_config_error("Version mismatch. Board {}-{} has version {:d}.{:d}.{:d}.{:d} which is not" " the minimal version " "{:d}.{:d}.{:d}.{:d}".format(chain_serial, chain_id, (version >> 24) & 0xFF, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF, (self.min_version[chain_serial] >> 24) & 0xFF, (self.min_version[chain_serial] >> 16) & 0xFF, (self.min_version[chain_serial] >> 8) & 0xFF, self.min_version[chain_serial] & 0xFF), 1) def register_processor_connection(self, serial_number, communicator): """Register the processors to the platform. Args: ---- serial_number: Serial number of chain. communicator: Instance of OPPSerialCommunicator """ self.opp_connection[serial_number] = communicator def send_to_processor(self, chain_serial, msg): """Send message to processor with specific serial number. Args: ---- chain_serial: Serial of the processor. msg: Message to send. """ self.opp_connection[chain_serial].send(msg) def update_incand(self): """Update all the incandescents connected to OPP hardware. This is done once per game loop if changes have been made. It is currently assumed that the UART oversampling will guarantee proper communication with the boards. If this does not end up being the case, this will be changed to update all the incandescents each loop. This is used for board with firmware < 2.1.0 """ for incand in self.opp_incands.values(): if self.min_version[incand.chain_serial] >= 0x02010000: continue whole_msg = bytearray() # Check if any changes have been made if incand.old_state is None or (incand.old_state ^ incand.new_state) != 0: # Update card incand.old_state = incand.new_state msg = bytearray() msg.append(incand.addr) msg.extend(OppRs232Intf.INCAND_CMD) msg.extend(OppRs232Intf.INCAND_SET_ON_OFF) msg.append((incand.new_state >> 24) & 0xff) msg.append((incand.new_state >> 16) & 0xff) msg.append((incand.new_state >> 8) & 0xff) msg.append(incand.new_state & 0xff) msg.extend(OppRs232Intf.calc_crc8_whole_msg(msg)) whole_msg.extend(msg) if whole_msg: # Note: No need to send EOM at end of cmds send_cmd = bytes(whole_msg) if self.debug: self.debug_log("Update incand on %s cmd:%s", incand.chain_serial, "".join(HEX_FORMAT % b for b in send_cmd)) self.send_to_processor(incand.chain_serial, send_cmd) @classmethod def get_coil_config_section(cls): """Return coil config section.""" return "opp_coils" async def get_hw_switch_states(self): """Get initial hardware switch states. This changes switches from active low to active high """ hw_states = dict() for opp_inp in self.opp_inputs: if not opp_inp.is_matrix: curr_bit = 1 for index in range(0, 32): if (curr_bit & opp_inp.mask) != 0: if (curr_bit & opp_inp.old_state) == 0: hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index)] = 1 else: hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index)] = 0 curr_bit <<= 1 else: for index in range(0, 64): if ((1 << index) & opp_inp.old_state) == 0: hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index + 32)] = 1 else: hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index + 32)] = 0 return hw_states def inv_resp(self, chain_serial, msg): """Parse inventory response. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ self.debug_log("Received Inventory Response: %s for %s", "".join(HEX_FORMAT % b for b in msg), chain_serial) index = 1 self.gen2_addr_arr[chain_serial] = {} while msg[index] != ord(OppRs232Intf.EOM_CMD): if (msg[index] & ord(OppRs232Intf.CARD_ID_TYPE_MASK)) == ord(OppRs232Intf.CARD_ID_GEN2_CARD): self.num_gen2_brd += 1 self.gen2_addr_arr[chain_serial][msg[index]] = None else: self.log.warning("Invalid inventory response %s for %s.", msg[index], chain_serial) index += 1 self.debug_log("Found %d Gen2 OPP boards on %s.", self.num_gen2_brd, chain_serial) # pylint: disable-msg=too-many-statements @staticmethod def eom_resp(chain_serial, msg): """Process an EOM. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # An EOM command can be used to resynchronize communications if message synch is lost def _parse_gen2_board(self, chain_serial, msg, read_input_msg): has_neo = False has_sw_matrix = False has_lamp_matrix = False wing_index = 0 sol_mask = 0 inp_mask = 0 incand_mask = 0 while wing_index < OppRs232Intf.NUM_G2_WING_PER_BRD: if msg[2 + wing_index] == ord(OppRs232Intf.WING_SOL): sol_mask |= (0x0f << (4 * wing_index)) inp_mask |= (0x0f << (8 * wing_index)) elif msg[2 + wing_index] == ord(OppRs232Intf.WING_INP): inp_mask |= (0xff << (8 * wing_index)) elif msg[2 + wing_index] == ord(OppRs232Intf.WING_INCAND): incand_mask |= (0xff << (8 * wing_index)) elif msg[2 + wing_index] in (ord(OppRs232Intf.WING_SW_MATRIX_OUT), ord(OppRs232Intf.WING_SW_MATRIX_OUT_LOW_WING)): has_sw_matrix = True elif msg[2 + wing_index] == ord(OppRs232Intf.WING_NEO): has_neo = True inp_mask |= (0xef << (8 * wing_index)) elif msg[2 + wing_index] == ord(OppRs232Intf.WING_HI_SIDE_INCAND): incand_mask |= (0xff << (8 * wing_index)) elif msg[2 + wing_index] == ord(OppRs232Intf.WING_NEO_SOL): inp_mask |= (0x0e << (8 * wing_index)) sol_mask |= (0x0f << (4 * wing_index)) has_neo = True elif msg[2 + wing_index] in (ord(OppRs232Intf.WING_LAMP_MATRIX_COL_WING), ord(OppRs232Intf.WING_LAMP_MATRIX_ROW_WING)): has_lamp_matrix = True wing_index += 1 if incand_mask != 0: card = OPPIncandCard(chain_serial, msg[0], incand_mask, self.machine) self.opp_incands["{}-{}".format(chain_serial, card.card_num)] = card if sol_mask != 0: self.opp_solenoid.append( OPPSolenoidCard(chain_serial, msg[0], sol_mask, self.sol_dict, self)) if inp_mask != 0: # Create the input object, and add to the command to read all inputs self.opp_inputs.append(OPPInputCard(chain_serial, msg[0], inp_mask, self.inp_dict, self.inp_addr_dict, self)) # Add command to read all inputs to read input message inp_msg = bytearray() inp_msg.append(msg[0]) inp_msg.extend(OppRs232Intf.READ_GEN2_INP_CMD) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.extend(OppRs232Intf.calc_crc8_whole_msg(inp_msg)) read_input_msg.extend(inp_msg) if has_sw_matrix: # Create the matrix object, and add to the command to read all matrix inputs self.opp_inputs.append(OPPMatrixCard(chain_serial, msg[0], self.inp_dict, self.matrix_inp_addr_dict, self)) # Add command to read all matrix inputs to read input message inp_msg = bytearray() inp_msg.append(msg[0]) inp_msg.extend(OppRs232Intf.READ_MATRIX_INP) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.append(0) inp_msg.extend(OppRs232Intf.calc_crc8_whole_msg(inp_msg)) read_input_msg.extend(inp_msg) if has_neo: card = OPPNeopixelCard(chain_serial, msg[0], self) self.neo_card_dict[chain_serial + '-' + card.card_num] = card if has_lamp_matrix: card = OPPModernMatrixLightsCard(chain_serial, msg[0], self) self.matrix_light_cards[chain_serial + '-' + card.card_num] = card def _bad_crc(self, chain_serial, msg): """Show warning and increase counter.""" self.bad_crc[chain_serial] += 1 self.log.warning("Chain: %sMsg contains bad CRC: %s.", chain_serial, "".join(HEX_FORMAT % b for b in msg)) def get_gen2_cfg_resp(self, chain_serial, msg): """Process cfg response. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Multiple get gen2 cfg responses can be received at once self.debug_log("Received Gen2 Cfg Response:%s", "".join(HEX_FORMAT % b for b in msg)) curr_index = 0 read_input_msg = bytearray() while True: # check that message is long enough, must include crc8 if len(msg) < curr_index + 7: self.log.warning("Msg is too short: %s.", "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() break # Verify the CRC8 is correct crc8 = OppRs232Intf.calc_crc8_part_msg(msg, curr_index, 6) if msg[curr_index + 6] != ord(crc8): self._bad_crc(chain_serial, msg) break self._parse_gen2_board(chain_serial, msg[curr_index:curr_index + 6], read_input_msg) if (len(msg) > curr_index + 7) and (msg[curr_index + 7] == ord(OppRs232Intf.EOM_CMD)): break if (len(msg) > curr_index + 8) and (msg[curr_index + 8] == ord(OppRs232Intf.GET_GEN2_CFG)): curr_index += 7 else: self.log.warning("Malformed GET_GEN2_CFG response:%s.", "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() break read_input_msg.extend(OppRs232Intf.EOM_CMD) self.read_input_msg[chain_serial] = bytes(read_input_msg) self._poll_response_received[chain_serial] = asyncio.Event() self._poll_response_received[chain_serial].set() def vers_resp(self, chain_serial, msg): """Process version response. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Multiple get version responses can be received at once self.debug_log("Received Version Response (Chain: %s): %s", chain_serial, "".join(HEX_FORMAT % b for b in msg)) curr_index = 0 while True: # check that message is long enough, must include crc8 if len(msg) < curr_index + 7: self.log.warning("Msg is too short (Chain: %s): %s.", chain_serial, "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() break # Verify the CRC8 is correct crc8 = OppRs232Intf.calc_crc8_part_msg(msg, curr_index, 6) if msg[curr_index + 6] != ord(crc8): self._bad_crc(chain_serial, msg) break version = (msg[curr_index + 2] << 24) | \ (msg[curr_index + 3] << 16) | \ (msg[curr_index + 4] << 8) | \ msg[curr_index + 5] self.debug_log("Firmware version of board 0x%02x (Chain: %s): %d.%d.%d.%d", msg[curr_index], chain_serial, msg[curr_index + 2], msg[curr_index + 3], msg[curr_index + 4], msg[curr_index + 5]) if msg[curr_index] not in self.gen2_addr_arr[chain_serial]: self.log.warning("Got firmware response for %s but not in inventory at %s", msg[curr_index], chain_serial) else: self.gen2_addr_arr[chain_serial][msg[curr_index]] = version if version < self.min_version[chain_serial]: self.min_version[chain_serial] = version if version == BAD_FW_VERSION: raise AssertionError("Original firmware sent only to Brian before adding " "real version numbers. The firmware must be updated before " "MPF will work.") if (len(msg) > curr_index + 7) and (msg[curr_index + 7] == ord(OppRs232Intf.EOM_CMD)): break if (len(msg) > curr_index + 8) and (msg[curr_index + 8] == ord(OppRs232Intf.GET_VERS_CMD)): curr_index += 7 else: self.log.warning("Malformed GET_VERS_CMD response (Chain %s): %s.", chain_serial, "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() break def read_gen2_inp_resp_initial(self, chain_serial, msg): """Read initial switch states. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Verify the CRC8 is correct if len(msg) < 7: raise AssertionError("Received too short initial input response: " + "".join(HEX_FORMAT % b for b in msg)) crc8 = OppRs232Intf.calc_crc8_part_msg(msg, 0, 6) if msg[6] != ord(crc8): self._bad_crc(chain_serial, msg) else: if chain_serial + '-' + str(msg[0]) not in self.inp_addr_dict: self.log.warning("Got input response for invalid card at initial request: %s. Msg: %s.", msg[0], "".join(HEX_FORMAT % b for b in msg)) return opp_inp = self.inp_addr_dict[chain_serial + '-' + str(msg[0])] new_state = (msg[2] << 24) | \ (msg[3] << 16) | \ (msg[4] << 8) | \ msg[5] opp_inp.old_state = new_state def read_gen2_inp_resp(self, chain_serial, msg): """Read switch changes. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Single read gen2 input response. Receive function breaks them down # Verify the CRC8 is correct if len(msg) < 7: self.log.warning("Msg too short: %s.", "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() return crc8 = OppRs232Intf.calc_crc8_part_msg(msg, 0, 6) if msg[6] != ord(crc8): self._bad_crc(chain_serial, msg) else: if chain_serial + '-' + str(msg[0]) not in self.inp_addr_dict: self.log.warning("Got input response for invalid card: %s. Msg: %s.", msg[0], "".join(HEX_FORMAT % b for b in msg)) return opp_inp = self.inp_addr_dict[chain_serial + '-' + str(msg[0])] new_state = (msg[2] << 24) | \ (msg[3] << 16) | \ (msg[4] << 8) | \ msg[5] # Update the state which holds inputs that are active changes = opp_inp.old_state ^ new_state if changes != 0: curr_bit = 1 for index in range(0, 32): if (curr_bit & changes) != 0: if (curr_bit & new_state) == 0: self.machine.switch_controller.process_switch_by_num( state=1, num=opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index), platform=self) else: self.machine.switch_controller.process_switch_by_num( state=0, num=opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index), platform=self) curr_bit <<= 1 opp_inp.old_state = new_state # we can continue to poll self._poll_response_received[chain_serial].set() def read_matrix_inp_resp_initial(self, chain_serial, msg): """Read initial matrix switch states. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Verify the CRC8 is correct if len(msg) < 11: raise AssertionError("Received too short initial input response: " + "".join(HEX_FORMAT % b for b in msg)) crc8 = OppRs232Intf.calc_crc8_part_msg(msg, 0, 10) if msg[10] != ord(crc8): self._bad_crc(chain_serial, msg) else: if chain_serial + '-' + str(msg[0]) not in self.matrix_inp_addr_dict: self.log.warning("Got input response for invalid matrix card at initial request: %s. Msg: %s.", msg[0], "".join(HEX_FORMAT % b for b in msg)) return opp_inp = self.matrix_inp_addr_dict[chain_serial + '-' + str(msg[0])] opp_inp.old_state = ((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40) | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]) # pylint: disable-msg=too-many-nested-blocks def read_matrix_inp_resp(self, chain_serial, msg): """Read matrix switch changes. Args: ---- chain_serial: Serial of the chain which received the message. msg: Message to parse. """ # Single read gen2 input response. Receive function breaks them down # Verify the CRC8 is correct if len(msg) < 11: self.log.warning("Msg too short: %s.", "".join(HEX_FORMAT % b for b in msg)) self.opp_connection[chain_serial].lost_synch() return crc8 = OppRs232Intf.calc_crc8_part_msg(msg, 0, 10) if msg[10] != ord(crc8): self._bad_crc(chain_serial, msg) else: if chain_serial + '-' + str(msg[0]) not in self.matrix_inp_addr_dict: self.log.warning("Got input response for invalid matrix card: %s. Msg: %s.", msg[0], "".join(HEX_FORMAT % b for b in msg)) return opp_inp = self.matrix_inp_addr_dict[chain_serial + '-' + str(msg[0])] new_state = ((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40) | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]) changes = opp_inp.old_state ^ new_state if changes != 0: curr_bit = 1 for index in range(32, 96): if (curr_bit & changes) != 0: if (curr_bit & new_state) == 0: self.machine.switch_controller.process_switch_by_num( state=1, num=opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index), platform=self) else: self.machine.switch_controller.process_switch_by_num( state=0, num=opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index), platform=self) curr_bit <<= 1 opp_inp.old_state = new_state # we can continue to poll self._poll_response_received[chain_serial].set() def _get_dict_index(self, input_str): if not isinstance(input_str, str): self.raise_config_error("Invalid number format for OPP. Number should be card-number or chain-card-number " "(e.g. 0-1)", 2) try: chain_str, card_str, number_str = input_str.split("-") except ValueError: if len(self.serial_connections) > 1: self.raise_config_error("You need to specify a chain as chain-card-number in: {}".format(input_str), 17) else: chain_str = list(self.serial_connections)[0].chain_serial try: card_str, number_str = input_str.split("-") except ValueError: card_str = '0' number_str = input_str if chain_str not in self.opp_connection: self.raise_config_error("Chain {} does not exist. Existing chains: {}".format( chain_str, list(self.opp_connection.keys())), 3) return chain_str + "-" + card_str + "-" + number_str def configure_driver(self, config: DriverConfig, number: str, platform_settings: dict): """Configure a driver. Args: ---- config: Config dict. number: Number of this driver. platform_settings: Platform specific settings. """ if not self.opp_connection: self.raise_config_error("A request was made to configure an OPP solenoid, " "but no OPP connection is available", 4) number = self._get_dict_index(number) if number not in self.sol_dict: self.raise_config_error("A request was made to configure an OPP solenoid " "with number {} which doesn't exist".format(number), 5) # Use new update individual solenoid command opp_sol = self.sol_dict[number] opp_sol.config = config opp_sol.platform_settings = platform_settings if self.debug: self.debug_log("Configure driver %s", number) default_pulse = PulseSettings(config.default_pulse_power, config.default_pulse_ms) default_hold = HoldSettings(config.default_hold_power) opp_sol.reconfigure_driver(default_pulse, default_hold) # Removing the default input is not necessary since the # CFG_SOL_USE_SWITCH is not being set return opp_sol def configure_switch(self, number: str, config: SwitchConfig, platform_config: dict): """Configure a switch. Args: ---- number: Number of this switch. config: Config dict. platform_config: Platform specific settings. """ del platform_config del config # A switch is termed as an input to OPP if not self.opp_connection: self.raise_config_error("A request was made to configure an OPP switch, " "but no OPP connection is available", 6) number = self._get_dict_index(number) if number not in self.inp_dict: self.raise_config_error("A request was made to configure an OPP switch " "with number {} which doesn't exist".format(number), 7) return self.inp_dict[number] def parse_light_number_to_channels(self, number: str, subtype: str): """Parse number and subtype to channel.""" if subtype in ("matrix", "incand"): return [ { "number": self._get_dict_index(number) } ] if not subtype or subtype == "led": full_index = self._get_dict_index(number) chain_serial, card, index = full_index.split('-') number_format = "{}-{}-{}" return [ { "number": number_format.format(chain_serial, card, int(index) * 3) }, { "number": number_format.format(chain_serial, card, int(index) * 3 + 1) }, { "number": number_format.format(chain_serial, card, int(index) * 3 + 2) }, ] self.raise_config_error("Unknown subtype {}".format(subtype), 8) return [] def configure_light(self, number, subtype, config, platform_settings): """Configure a led or matrix light.""" del config if not self.opp_connection: self.raise_config_error("A request was made to configure an OPP light, " "but no OPP connection is available", 9) chain_serial, card, light_num = number.split('-') index = chain_serial + '-' + card if not subtype or subtype == "led": if index not in self.neo_card_dict: self.raise_config_error("A request was made to configure an OPP neopixel " "with card number {} which doesn't exist".format(card), 10) if not self.neo_card_dict[index].is_valid_light_number(light_num): self.raise_config_error("A request was made to configure an OPP neopixel " "with card number {} but number '{}' is " "invalid".format(card, light_num), 22) light = OPPModernLightChannel(chain_serial, int(card), int(light_num), self._light_system) self._light_system.mark_dirty(light) return light if subtype == "matrix" and self.min_version[chain_serial] >= 0x02010000: # modern matrix lights if index not in self.matrix_light_cards: self.raise_config_error("A request was made to configure an OPP matrix light " "with card number {} which doesn't exist".format(card), 18) if not self.matrix_light_cards[index].is_valid_light_number(light_num): self.raise_config_error("A request was made to configure an OPP matrix light " "with card number {} but number '{}' is " "invalid".format(card, light_num), 19) light = OPPModernLightChannel(chain_serial, int(card), int(light_num) + 0x2000, self._light_system) self._light_system.mark_dirty(light) return light if subtype in ("incand", "matrix"): if index not in self.opp_incands: self.raise_config_error("A request was made to configure an OPP incand light " "with card number {} which doesn't exist".format(card), 20) if not self.opp_incands[index].is_valid_light_number(light_num): self.raise_config_error("A request was made to configure an OPP incand light " "with card number {} but number '{}' is " "invalid".format(card, light_num), 21) if self.min_version[chain_serial] >= 0x02010000: light = self.opp_incands[index].configure_modern_fade_incand(light_num, self._light_system) self._light_system.mark_dirty(light) return light # legacy incands with new or old subtype return self.opp_incands[index].configure_software_fade_incand(light_num) self.raise_config_error("Unknown subtype {}".format(subtype), 12) return None async def _poll_sender(self, chain_serial): """Poll switches.""" if len(self.read_input_msg[chain_serial]) <= 1: # there is no point in polling without switches return while True: # wait for previous poll response timeout = 1 / self.config['poll_hz'] * 25 try: await asyncio.wait_for(self._poll_response_received[chain_serial].wait(), timeout) except asyncio.TimeoutError: self.log.warning("Poll took more than %sms for %s", timeout * 1000, chain_serial) else: self._poll_response_received[chain_serial].clear() # send poll self.send_to_processor(chain_serial, self.read_input_msg[chain_serial]) await self.opp_connection[chain_serial].writer.drain() # the line above saturates the link and seems to overwhelm the hardware. limit it to 100Hz await asyncio.sleep(1 / self.config['poll_hz']) def _verify_coil_and_switch_fit(self, switch, coil): chain_serial, card, solenoid = coil.hw_driver.number.split('-') sw_chain_serial, sw_card, sw_num = switch.hw_switch.number.split('-') if self.min_version[chain_serial] >= 0x20000: if chain_serial != sw_chain_serial or card != sw_card: self.raise_config_error('Invalid switch being configured for driver. Driver = {} ' 'Switch = {}. Driver and switch have to be on the same ' 'board.'.format(coil.hw_driver.number, switch.hw_switch.number), 13) else: matching_sw = ((int(solenoid) & 0x0c) << 1) | (int(solenoid) & 0x03) if chain_serial != sw_chain_serial or card != sw_card or matching_sw != int(sw_num): self.raise_config_error('Invalid switch being configured for driver. Driver = {} ' 'Switch = {}. For Firmware < 0.2.0 they have to be on the same board and ' 'have the same number'.format(coil.hw_driver.number, switch.hw_switch.number), 14) def set_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): """Set pulse on hit rule on driver. Pulses a driver when a switch is hit. When the switch is released the pulse continues. Typically used for autofire coils such as pop bumpers. """ self._write_hw_rule(enable_switch, coil, use_hold=False, can_cancel=False) def set_delayed_pulse_on_hit_rule(self, enable_switch: SwitchSettings, coil: DriverSettings, delay_ms: int): """Set pulse on hit and release rule to driver. When a switch is hit and a certain delay passed it pulses a driver. When the switch is released the pulse continues. Typically used for kickbacks. """ if delay_ms <= 0: raise AssertionError("set_delayed_pulse_on_hit_rule should be used with a positive delay " "not {}".format(delay_ms)) if delay_ms > 255: raise AssertionError("set_delayed_pulse_on_hit_rule is limited to max 255ms " "(was {})".format(delay_ms)) self._write_hw_rule(enable_switch, coil, use_hold=False, can_cancel=False, delay_ms=int(delay_ms)) def set_pulse_on_hit_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): """Set pulse on hit and release rule to driver. Pulses a driver when a switch is hit. When the switch is released the pulse is canceled. Typically used on the main coil for dual coil flippers without eos switch. """ self._write_hw_rule(enable_switch, coil, use_hold=False, can_cancel=True) def set_pulse_on_hit_and_enable_and_release_rule(self, enable_switch: SwitchSettings, coil: DriverSettings): """Set pulse on hit and enable and relase rule on driver. Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released the pulse is canceled and the driver gets disabled. Typically used for single coil flippers. """ self._write_hw_rule(enable_switch, coil, use_hold=True, can_cancel=True) def set_pulse_on_hit_and_release_and_disable_rule(self, enable_switch: SwitchSettings, eos_switch: SwitchSettings, coil: DriverSettings, repulse_settings: Optional[RepulseSettings]): """Set pulse on hit and release and disable rule on driver. Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released the pulse is canceled and the driver gets disabled. When the second disable_switch is hit the pulse is canceled and the driver gets disabled. Typically used on the main coil for dual coil flippers with eos switch. """ raise AssertionError("Not implemented in OPP currently") def set_pulse_on_hit_and_enable_and_release_and_disable_rule(self, enable_switch: SwitchSettings, eos_switch: SwitchSettings, coil: DriverSettings, repulse_settings: Optional[RepulseSettings]): """Set pulse on hit and enable and release and disable rule on driver. Pulses a driver when a switch is hit. Then enables the driver (may be with pwm). When the switch is released the pulse is canceled and the driver becomes disabled. When the eos_switch is hit the pulse is canceled and the driver becomes enabled (likely with PWM). Typically used on the coil for single-wound coil flippers with eos switch. """ raise AssertionError("Not implemented in OPP currently") # pylint: disable-msg=too-many-arguments def _write_hw_rule(self, switch_obj: SwitchSettings, driver_obj: DriverSettings, use_hold, can_cancel, delay_ms=None): if switch_obj.invert: raise AssertionError("Cannot handle inverted switches") if driver_obj.hold_settings and not use_hold: raise AssertionError("Invalid call") self._verify_coil_and_switch_fit(switch_obj, driver_obj) self.debug_log("Setting HW Rule. Driver: %s", driver_obj.hw_driver.number) driver_obj.hw_driver.switches.append(switch_obj.hw_switch.number) driver_obj.hw_driver.set_switch_rule(driver_obj.pulse_settings, driver_obj.hold_settings, driver_obj.recycle, can_cancel, delay_ms) _, _, switch_num = switch_obj.hw_switch.number.split("-") switch_num = int(switch_num) self._add_switch_coil_mapping(switch_num, driver_obj.hw_driver) def _remove_switch_coil_mapping(self, switch_num, driver: "OPPSolenoid"): """Remove mapping between switch and coil.""" if self.min_version[driver.sol_card.chain_serial] < 0x20000: return _, _, coil_num = driver.number.split('-') # mirror switch matrix columns to handle the fact that OPP matrix is in reverse column order if switch_num >= 32: switch_num = 8 * (15 - (switch_num // 8)) + switch_num % 8 msg = bytearray() msg.append(driver.sol_card.addr) msg.extend(OppRs232Intf.SET_SOL_INP_CMD) msg.append(int(switch_num)) msg.append(int(coil_num) + ord(OppRs232Intf.CFG_SOL_INP_REMOVE)) msg.extend(OppRs232Intf.calc_crc8_whole_msg(msg)) msg.extend(OppRs232Intf.EOM_CMD) final_cmd = bytes(msg) if self.debug: self.debug_log("Unmapping input %s and coil %s on %s", switch_num, coil_num, driver.sol_card.chain_serial) self.send_to_processor(driver.sol_card.chain_serial, final_cmd) def _add_switch_coil_mapping(self, switch_num, driver: "OPPSolenoid"): """Add mapping between switch and coil.""" if self.min_version[driver.sol_card.chain_serial] < 0x20000: return _, _, coil_num = driver.number.split('-') # mirror switch matrix columns to handle the fact that OPP matrix is in reverse column order if switch_num >= 32: switch_num = 8 * (15 - (switch_num // 8)) + switch_num % 8 msg = bytearray() msg.append(driver.sol_card.addr) msg.extend(OppRs232Intf.SET_SOL_INP_CMD) msg.append(int(switch_num)) msg.append(int(coil_num)) msg.extend(OppRs232Intf.calc_crc8_whole_msg(msg)) msg.extend(OppRs232Intf.EOM_CMD) final_cmd = bytes(msg) if self.debug: self.debug_log("Mapping input %s and coil %s on %s", switch_num, coil_num, driver.sol_card.chain_serial) self.send_to_processor(driver.sol_card.chain_serial, final_cmd) def clear_hw_rule(self, switch: SwitchSettings, coil: DriverSettings): """Clear a hardware rule. This is used if you want to remove the linkage between a switch and some driver activity. For example, if you wanted to disable your flippers (so that a player pushing the flipper buttons wouldn't cause the flippers to flip), you'd call this method with your flipper button as the *sw_num*. """ if switch.hw_switch.number in coil.hw_driver.switches: if self.debug: self.debug_log("Clearing HW Rule for switch: %s, coils: %s", switch.hw_switch.number, coil.hw_driver.number) coil.hw_driver.switches.remove(switch.hw_switch.number) _, _, switch_num = switch.hw_switch.number.split("-") switch_num = int(switch_num) self._remove_switch_coil_mapping(switch_num, coil.hw_driver) # disable rule if there are no more switches # Technically not necessary unless the solenoid parameters are # changing. MPF may not know when initial kick and hold values # are changed, so this might need to be called each time. if not coil.hw_driver.switches: coil.hw_driver.remove_switch_rule()
missionpinball/mpf
mpf/platforms/opp/opp.py
Python
mit
53,276
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.client.gui; import net.minecraft.client.gui.GuiOptions; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.storage.WorldInfo; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.world.WorldManager; /** * In Sponge's Multi-World implementation, we give each world its own {@link WorldInfo}. While this is a great idea all around (allows us to * make things world-specific), it has some unintended consequences, such as breaking being able to change your difficulty in SinglePlayer. While * most people would tell us to not worry about it as Sponge isn't really client-side oriented, I have no tolerance for breaking Vanilla * functionality (barring some exceptions) so this cannot stand. */ @Mixin(GuiOptions.class) public abstract class GuiOptionsMixin_Forge { @Redirect(method = "actionPerformed", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setDifficulty(Lnet/minecraft/world/EnumDifficulty;)V")) private void syncDifficulty(final WorldInfo worldInfo, final EnumDifficulty newDifficulty) { // Sync server WorldManager.getWorlds().forEach(worldServer -> WorldManager.adjustWorldForDifficulty(worldServer, newDifficulty, true)); // Sync client worldInfo.setDifficulty(newDifficulty); } @Redirect(method = "confirmClicked", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setDifficultyLocked(Z)V")) private void syncDifficultyLocked(final WorldInfo worldInfo, final boolean locked) { // Sync server WorldManager.getWorlds().forEach(worldServer -> worldServer.getWorldInfo().setDifficultyLocked(locked)); // Sync client worldInfo.setDifficultyLocked(locked); } }
SpongePowered/SpongeForge
src/main/java/org/spongepowered/mod/mixin/core/client/gui/GuiOptionsMixin_Forge.java
Java
mit
3,185
from django.db import models from constituencies.models import Constituency from uk_political_parties.models import Party from elections.models import Election class Person(models.Model): name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property def current_party(self): parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0] @property def current_election(self): return self.elections.filter(active=True)[0] @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return "%s (%s)" % (self.name, self.remote_id) class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election)
JustinWingChungHui/electionleaflets
electionleaflets/apps/people/models.py
Python
mit
1,603
// // IsExtraAttribute.cs // // Author: // Aaron Bockover <aaron.bockover@gmail.com> // // Copyright 2015 Aaron Bockover. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace Conservatorio.Rdio { [AttributeUsage (AttributeTargets.Property)] class IsExtraAttribute : Attribute { } }
abock/conservatorio
Conservatorio/Rdio/IsExtraAttribute.cs
C#
mit
1,359
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n= 20; label: cout << n << endl; n--; if(n > 0){ goto label; } std::cout << "endle" << '\n'; std::cout << "string euqals: " << (strcmp("hello", "hello")) << '\n'; if(strcmp("hello", "hello") == 0){ printf("hello equals hello\n"); } return 0; }
gubaojian/trylearn
cplus/1/go.cpp
C++
mit
386
using System; using System.Collections.Generic; using System.Linq; namespace Slack.Api { public static class ProfileHelper { public static User GetProfile(ICollection<User> users, string userId) { if (users == null) { throw new ArgumentNullException(nameof(users)); } if (userId == null) { throw new ArgumentNullException(nameof(userId)); } if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentException(nameof(userId)); } var user = users.FirstOrDefault(x => x.UserId == userId); if (user == null) { throw new ArgumentNullException(nameof(user)); } return user; } } }
vamone/Slack-Notification-Desktop-App
Slack.Api/ProfileHelper.cs
C#
mit
850
package com.integpg.synapse.actions; import com.integpg.logger.FileLogger; import java.io.IOException; import java.util.Json; public class CompositeAction extends Action { private String[] _actions; public CompositeAction(Json json) { _actions = (String[]) json.get("Actions"); ActionHash.put((String) json.get("ID"), this); } public void execute() throws IOException { Thread thd = new Thread(new Runnable() { public void run() { FileLogger.debug("Executing Composite Action in " + Thread.currentThread().getName()); for (int i = 0; i < _actions.length; i++) { try { Action.execute(_actions[i]); } catch (Exception ex) { FileLogger.error("Error executing action: " + ex.getMessage()); } } } }); thd.setDaemon(true); thd.start(); } }
kmcloutier/synapse
src/com/integpg/synapse/actions/CompositeAction.java
Java
mit
998
package be.idoneus.hipchat.buildbot.hipchat.server; public class Paths { public static String PATH_CAPABILITIES = ""; public static String PATH_INSTALL = "install"; public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message"; public static String PATH_GLANCES = "glances"; }
Idoneus/buildbot
buildbot-core/src/main/java/be/idoneus/hipchat/buildbot/hipchat/server/Paths.java
Java
mit
305
using WJStore.Domain.Interfaces.Validation; namespace WJStore.Domain.Validation { public class ValidationRule<TEntity> : IValidationRule<TEntity> { private readonly ISpecification<TEntity> _specificationRule; public ValidationRule(ISpecification<TEntity> specificationRule, string errorMessage) { _specificationRule = specificationRule; ErrorMessage = errorMessage; } public string ErrorMessage { get; private set; } public bool Valid(TEntity entity) { return _specificationRule.IsSatisfiedBy(entity); } } }
MrWooJ/WJStore
WJStore.Domain/Validation/ValidationRule.cs
C#
mit
626
using CharacterGen.Feats; using CharacterGen.Abilities; using CharacterGen.Races; using System.Collections.Generic; using System.Linq; namespace CharacterGen.Domain.Selectors.Selections { internal class RacialFeatSelection { public string Feat { get; set; } public int MinimumHitDieRequirement { get; set; } public int MaximumHitDieRequirement { get; set; } public string SizeRequirement { get; set; } public Frequency Frequency { get; set; } public string FocusType { get; set; } public int Power { get; set; } public Dictionary<string, int> MinimumAbilities { get; set; } public string RandomFociQuantity { get; set; } public IEnumerable<RequiredFeatSelection> RequiredFeats { get; set; } public RacialFeatSelection() { Feat = string.Empty; SizeRequirement = string.Empty; Frequency = new Frequency(); FocusType = string.Empty; MinimumAbilities = new Dictionary<string, int>(); RandomFociQuantity = string.Empty; RequiredFeats = Enumerable.Empty<RequiredFeatSelection>(); } public bool RequirementsMet(Race race, int monsterHitDice, Dictionary<string, Ability> abilities, IEnumerable<Feat> feats) { if (string.IsNullOrEmpty(SizeRequirement) == false && SizeRequirement != race.Size) return false; if (MaximumHitDieRequirement > 0 && monsterHitDice > MaximumHitDieRequirement) return false; if (MinimumAbilityMet(abilities) == false) return false; foreach (var requirement in RequiredFeats) { var requirementFeats = feats.Where(f => f.Name == requirement.Feat); if (requirementFeats.Any() == false) return false; if (requirement.Focus != string.Empty && requirementFeats.Any(f => f.Foci.Contains(requirement.Focus)) == false) return false; } return monsterHitDice >= MinimumHitDieRequirement; } private bool MinimumAbilityMet(Dictionary<string, Ability> stats) { if (MinimumAbilities.Any() == false) return true; foreach (var stat in MinimumAbilities) if (stats[stat.Key].Value >= stat.Value) return true; return false; } } }
DnDGen/CharacterGen
CharacterGen.Domain/Selectors/Selections/RacialFeatSelection.cs
C#
mit
2,497
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @name mdBackdrop * @module material.components.backdrop * * @restrict E * * @description * `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet. * Apply class `opaque` to make the backdrop use the theme backdrop color. * */ angular .module('material.components.backdrop', ['material.core']) .directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) { var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container."; return { restrict: 'E', link: postLink }; function postLink(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10)); element.css({ height: hViewport + 'px' }); } // backdrop may be outside the $rootElement, tell ngAnimate to animate regardless if ($animate.pin) $animate.pin(element, $rootElement); $$rAF(function () { // Often $animate.enter() is used to append the backDrop element // so let's wait until $animate is done... var parent = element.parent()[0]; if (parent) { if ( parent.nodeName == 'BODY' ) { element.css({position : 'fixed'}); } var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent position:static (default) $log.warn(ERROR_CSS_POSITION); } } $mdTheming.inherit(element, element.parent()); }); } }]); ng.material.components.backdrop = angular.module("material.components.backdrop");
devMonkies/FSwebApp
bower_components/angular-material/modules/closure/backdrop/backdrop.js
JavaScript
mit
2,440
<?php namespace Oreades\PaymentPayplugBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class OreadesPaymentPayplugBundle extends Bundle { }
Oreades/PaymentPayplugBundle
OreadesPaymentPayplugBundle.php
PHP
mit
150
#ifndef __tc_function_h__ #define __tc_function_h__ #include <atomic> namespace tc { #define TC_FUNCTION_TD_0 typename R #define TC_FUNCTION_TD_1 TC_FUNCTION_TD_0 , typename A1 #define TC_FUNCTION_TD_2 TC_FUNCTION_TD_1 , typename A2 #define TC_FUNCTION_TD_3 TC_FUNCTION_TD_2 , typename A3 #define TC_FUNCTION_TD_4 TC_FUNCTION_TD_3 , typename A4 #define TC_FUNCTION_TD_5 TC_FUNCTION_TD_4 , typename A5 // template specialization parameter #define TC_FUNCTION_TSP_0 #define TC_FUNCTION_TSP_1 A1 #define TC_FUNCTION_TSP_2 TC_FUNCTION_TSP_1 , A2 #define TC_FUNCTION_TSP_3 TC_FUNCTION_TSP_2 , A3 #define TC_FUNCTION_TSP_4 TC_FUNCTION_TSP_3 , A4 #define TC_FUNCTION_TSP_5 TC_FUNCTION_TSP_4 , A5 // template specialization #define TC_FUNCTION_TS_0 R ( TC_FUNCTION_TSP_0 ) #define TC_FUNCTION_TS_1 R ( TC_FUNCTION_TSP_1 ) #define TC_FUNCTION_TS_2 R ( TC_FUNCTION_TSP_2 ) #define TC_FUNCTION_TS_3 R ( TC_FUNCTION_TSP_3 ) #define TC_FUNCTION_TS_4 R ( TC_FUNCTION_TSP_4 ) #define TC_FUNCTION_TS_5 R ( TC_FUNCTION_TSP_5 ) // template parameter #define TC_FUNCTION_TP_0 #define TC_FUNCTION_TP_1 typename forward_traits< A1 >::type p1 #define TC_FUNCTION_TP_2 TC_FUNCTION_TP_1 , typename forward_traits< A2 >::type p2 #define TC_FUNCTION_TP_3 TC_FUNCTION_TP_2 , typename forward_traits< A3 >::type p3 #define TC_FUNCTION_TP_4 TC_FUNCTION_TP_3 , typename forward_traits< A4 >::type p4 #define TC_FUNCTION_TP_5 TC_FUNCTION_TP_4 , typename forward_traits< A5 >::type p5 // template forward #define TC_FUNCTION_TF_0 #define TC_FUNCTION_TF_1 p1 #define TC_FUNCTION_TF_2 TC_FUNCTION_TF_1 , p2 #define TC_FUNCTION_TF_3 TC_FUNCTION_TF_2 , p3 #define TC_FUNCTION_TF_4 TC_FUNCTION_TF_3 , p4 #define TC_FUNCTION_TF_5 TC_FUNCTION_TF_4 , p5 #define TC_FUNCTION_TP2_0 void* ctx #define TC_FUNCTION_TP2_1 TC_FUNCTION_TP2_0 , typename forward_traits< A1 >::type p1 #define TC_FUNCTION_TP2_2 TC_FUNCTION_TP2_1 , typename forward_traits< A2 >::type p2 #define TC_FUNCTION_TP2_3 TC_FUNCTION_TP2_2 , typename forward_traits< A3 >::type p3 #define TC_FUNCTION_TP2_4 TC_FUNCTION_TP2_3 , typename forward_traits< A4 >::type p4 #define TC_FUNCTION_TP2_5 TC_FUNCTION_TP2_4 , typename forward_traits< A5 >::type p5 #define TC_FUNCTION_TF2_0 _context #define TC_FUNCTION_TF2_1 TC_FUNCTION_TF2_0 , p1 #define TC_FUNCTION_TF2_2 TC_FUNCTION_TF2_1 , p2 #define TC_FUNCTION_TF2_3 TC_FUNCTION_TF2_2 , p3 #define TC_FUNCTION_TF2_4 TC_FUNCTION_TF2_3 , p4 #define TC_FUNCTION_TF2_5 TC_FUNCTION_TF2_4 , p5 template < typename T > struct forward_traits { typedef const T& type; }; template < typename T > struct forward_traits < const T > { typedef const T& type; }; template < typename T > struct forward_traits < T& > { typedef T& type; }; template < typename T > struct forward_traits < const T& > { typedef const T& type; }; template < typename T > struct forward_traits < T* > { typedef T* type; }; template < typename T > struct forward_traits < const T* > { typedef const T* type; }; /*! * @class function * @brief */ template < typename Handler > class function; #define TC_FUNCTION_DECLARE_FUNCTION( TD , TS , TP , TF , TP2 , TF2 )\ template < TD >\ class function< TS > {\ typedef R (*raw_handler_type)( TP ); \ enum handler_ops { DUPLICATE , CLONE , RELEASE };\ \ template < typename Handler >\ class handler_impl {\ public:\ handler_impl( const Handler& handler ) \ : _handler( handler ){\ _ref_count.store(1);\ }\ handler_impl( const handler_impl& rhs ) \ : _handler( rhs._handler ){\ _ref_count.store(1);\ }\ void release( void ) {\ if ( _ref_count.fetch_sub( 1 , std::memory_order_release ) == 1 ) {\ delete this;\ }\ }\ handler_impl* duplicate( void ) {\ _ref_count.fetch_add(1);\ return this;\ }\ handler_impl* clone( void ) {\ return new handler_impl( *this );\ }\ \ R operator()( TP ){ \ return _handler( TF ); \ }\ static R call( TP2 ) {\ return (*reinterpret_cast<handler_impl*>(ctx))( TF );\ }\ static void* control( handler_ops op , void* ctx ){\ handler_impl* impl = reinterpret_cast< handler_impl* >(ctx);\ if ( op == handler_ops::DUPLICATE ) return impl->duplicate();\ if ( op == handler_ops::CLONE) return impl->clone();\ if ( op == handler_ops::RELEASE) impl->release();\ return nullptr;\ }\ private:\ std::atomic< int > _ref_count;\ Handler _handler;\ };\ public:\ function( void )\ : _context(nullptr)\ , _call( &function::function_ptr_call)\ , _control( &function::function_ptr_control )\ {\ }\ function( raw_handler_type raw_handler ) \ : _context( reinterpret_cast< void* >(raw_handler))\ , _call( &function::function_ptr_call)\ , _control( &function::function_ptr_control )\ {\ }\ \ template < typename Handler > \ function( const Handler& handler ) {\ _context = reinterpret_cast<void*>(\ new handler_impl<Handler>(handler));\ _call = handler_impl<Handler>::call;\ _control = handler_impl<Handler>::control; \ }\ \ function( const function& rhs ){\ _context = rhs._control( handler_ops::DUPLICATE , rhs._context );\ _control= rhs._control;\ _call = rhs._call;\ } \ \ function( function&& rhs )\ : _context( nullptr )\ , _call( nullptr )\ , _control( nullptr )\ {\ swap( rhs );\ }\ \ function& operator=( raw_handler_type raw_handler ){\ function f(raw_handler);\ this->swap(f);\ return *this;\ }\ \ template < typename Handler >\ function& operator=( const Handler& handler ){\ function f(handler);\ this->swap(f);\ return *this;\ }\ \ function& operator=( const function& rhs ) {\ if ( _context == rhs._context )\ return *this;\ function f(std::move(*this));\ _context = rhs._control( handler_ops::DUPLICATE , rhs._context );\ _control= rhs._control;\ _call = rhs._call;\ return *this;\ }\ \ function& operator=( function&& rhs ) {\ if ( _context == rhs._context )\ return *this;\ function f(std::move(*this));\ swap(rhs);\ return *this;\ }\ \ ~function( void ) {\ if ( _context && _control )\ _control( handler_ops::RELEASE , _context);\ }\ \ void swap( function& f ) {\ std::swap( _context , f._context );\ std::swap( _call , f._call);\ std::swap( _control , f._control );\ }\ \ R operator()( TP ) {\ if ( _context )\ return _call(TF2);\ return R();\ }\ \ static void* function_ptr_control( handler_ops op , void* ctx ) {\ return ctx;\ }\ \ static R function_ptr_call( TP2 ) {\ return (reinterpret_cast<raw_handler_type>(ctx))(TF);\ }\ private:\ function( void* c , R (*call)(TP2) , void* (*ctrl )( handler_ops , void* ))\ : _context(c) , _call(call) , _control( ctrl ) {\ }\ function clone( void ) {\ return function( _control( handler_ops::CLONE , _context ) , _call , _control);\ }\ private:\ void* _context;\ R (*_call)( TP2 );\ void* (*_control)( handler_ops , void* );\ };\ #define TC_FUNCTION_DECLARE_FUNCTION_PARAM_N( n ) \ TC_FUNCTION_DECLARE_FUNCTION( \ TC_FUNCTION_TD_##n , \ TC_FUNCTION_TS_##n , \ TC_FUNCTION_TP_##n , \ TC_FUNCTION_TF_##n , \ TC_FUNCTION_TP2_##n, \ TC_FUNCTION_TF2_##n ) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(0) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(1) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(2) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(3) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(4) TC_FUNCTION_DECLARE_FUNCTION_PARAM_N(5) } #endif
aoziczero/deprecated-libtc
srcs/tc.common/function.hpp
C++
mit
8,097
const errors = require('@tryghost/errors'); const should = require('should'); const sinon = require('sinon'); const fs = require('fs-extra'); const moment = require('moment'); const Promise = require('bluebird'); const path = require('path'); const LocalFileStore = require('../../../../../core/server/adapters/storage/LocalFileStorage'); let localFileStore; const configUtils = require('../../../../utils/configUtils'); describe('Local File System Storage', function () { let image; let momentStub; function fakeDate(mm, yyyy) { const month = parseInt(mm, 10); const year = parseInt(yyyy, 10); momentStub.withArgs('YYYY').returns(year.toString()); momentStub.withArgs('MM').returns(month < 10 ? '0' + month.toString() : month.toString()); } beforeEach(function () { // Fake a date, do this once for all tests in this file momentStub = sinon.stub(moment.fn, 'format'); }); afterEach(function () { sinon.restore(); configUtils.restore(); }); beforeEach(function () { sinon.stub(fs, 'mkdirs').resolves(); sinon.stub(fs, 'copy').resolves(); sinon.stub(fs, 'stat').rejects(); sinon.stub(fs, 'unlink').resolves(); image = { path: 'tmp/123456.jpg', name: 'IMAGE.jpg', type: 'image/jpeg' }; localFileStore = new LocalFileStore(); fakeDate(9, 2013); }); it('should send correct path to image when date is in Sep 2013', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); it('should send correct path to image when original file has spaces', function (done) { image.name = 'AN IMAGE.jpg'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/AN-IMAGE.jpg'); done(); }).catch(done); }); it('should allow "@" symbol to image for Apple hi-res (retina) modifier', function (done) { image.name = 'photo@2x.jpg'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/photo@2x.jpg'); done(); }).catch(done); }); it('should send correct path to image when date is in Jan 2014', function (done) { fakeDate(1, 2014); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2014/01/IMAGE.jpg'); done(); }).catch(done); }); it('should create month and year directory', function (done) { localFileStore.save(image).then(function () { fs.mkdirs.calledOnce.should.be.true(); fs.mkdirs.args[0][0].should.equal(path.resolve('./content/images/2013/09')); done(); }).catch(done); }); it('should copy temp file to new location', function (done) { localFileStore.save(image).then(function () { fs.copy.calledOnce.should.be.true(); fs.copy.args[0][0].should.equal('tmp/123456.jpg'); fs.copy.args[0][1].should.equal(path.resolve('./content/images/2013/09/IMAGE.jpg')); done(); }).catch(done); }); it('can upload two different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).rejects(); // if on windows need to setup with back slashes // doesn't hurt for the test to cope with both fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-1.jpg'); done(); }).catch(done); }); it('can upload five different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-4.jpg')).rejects(); // windows setup fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-4.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-4.jpg'); done(); }).catch(done); }); describe('read image', function () { beforeEach(function () { // we have some example images in our test utils folder localFileStore.storagePath = path.join(__dirname, '../../../../utils/fixtures/images/'); }); it('success', function (done) { localFileStore.read({path: 'ghost-logo.png'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('success', function (done) { localFileStore.read({path: '/ghost-logo.png/'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('image does not exist', function (done) { localFileStore.read({path: 'does-not-exist.png'}) .then(function () { done(new Error('image should not exist')); }) .catch(function (err) { (err instanceof errors.NotFoundError).should.eql(true); err.code.should.eql('ENOENT'); done(); }); }); }); describe('validate extentions', function () { it('name contains a .\d as extension', function (done) { localFileStore.save({ name: 'test-1.1.1' }).then(function (url) { should.exist(url.match(/test-1.1.1/)); done(); }).catch(done); }); it('name contains a .zip as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.zip' }).then(function (url) { should.exist(url.match(/test-1.1.1.zip/)); done(); }).catch(done); }); it('name contains a .jpeg as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.jpeg' }).then(function (url) { should.exist(url.match(/test-1.1.1.jpeg/)); done(); }).catch(done); }); }); describe('when a custom content path is used', function () { beforeEach(function () { const configPaths = configUtils.defaultConfig.paths; configUtils.set('paths:contentPath', configPaths.appRoot + '/var/ghostcms'); }); it('should send the correct path to image', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); }); // @TODO: remove path.join mock... describe('on Windows', function () { const truePathSep = path.sep; beforeEach(function () { sinon.stub(path, 'join'); sinon.stub(configUtils.config, 'getContentPath').returns('content/images/'); }); afterEach(function () { path.sep = truePathSep; }); it('should return url in proper format for windows', function (done) { path.sep = '\\'; path.join.returns('content\\images\\2013\\09\\IMAGE.jpg'); localFileStore.save(image).then(function (url) { if (truePathSep === '\\') { url.should.equal('/content/images/2013/09/IMAGE.jpg'); } else { // if this unit test is run on an OS that uses forward slash separators, // localfilesystem.save() will use a path.relative() call on // one path with backslash separators and one path with forward // slashes and it returns a path that needs to be normalized path.normalize(url).should.equal('/content/images/2013/09/IMAGE.jpg'); } done(); }).catch(done); }); }); });
janvt/Ghost
test/unit/server/adapters/storage/LocalFileStorage.test.js
JavaScript
mit
9,369
import { ReactElement } from "react"; import Heading from "components/Heading"; import styles from "./PackageSassDoc.module.scss"; export interface SectionTitleProps { packageName: string; type: "Variables" | "Functions" | "Mixins"; } export default function SectionTitle({ packageName, type, }: SectionTitleProps): ReactElement { return ( <Heading id={`${packageName}-${type.toLowerCase()}`} level={1} className={styles.title} > {type} </Heading> ); }
mlaursen/react-md
packages/documentation/src/components/PackageSassDoc/SectionTitle.tsx
TypeScript
mit
505
package in.clayfish.printful.models; import java.io.Serializable; import java.util.List; import in.clayfish.printful.models.info.AddressInfo; import in.clayfish.printful.models.info.ItemInfo; /** * @author shuklaalok7 * @since 24/12/2016 */ public class ShippingRequest implements Serializable { /** * Recipient location information */ private AddressInfo recipient; /** * List of order items */ private List<ItemInfo> items; /** * 3 letter currency code (optional), required if the rates need to be converted to another currency instead of USD */ private String currency; public AddressInfo getRecipient() { return recipient; } public void setRecipient(AddressInfo recipient) { this.recipient = recipient; } public List<ItemInfo> getItems() { return items; } public void setItems(List<ItemInfo> items) { this.items = items; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } }
clayfish/printful4j
client/src/main/java/in/clayfish/printful/models/ShippingRequest.java
Java
mit
1,115
import UnexpectedHtmlLike from 'unexpected-htmllike'; import React from 'react'; import REACT_EVENT_NAMES from '../reactEventNames'; const PENDING_TEST_EVENT_TYPE = { dummy: 'Dummy object to identify a pending event on the test renderer' }; function getDefaultOptions(flags) { return { diffWrappers: flags.exactly || flags.withAllWrappers, diffExtraChildren: flags.exactly || flags.withAllChildren, diffExtraAttributes: flags.exactly || flags.withAllAttributes, diffExactClasses: flags.exactly, diffExtraClasses: flags.exactly || flags.withAllClasses }; } /** * * @param options {object} * @param options.ActualAdapter {function} constructor function for the HtmlLike adapter for the `actual` value (usually the renderer) * @param options.ExpectedAdapter {function} constructor function for the HtmlLike adapter for the `expected` value * @param options.QueryAdapter {function} constructor function for the HtmlLike adapter for the query value (`queried for` and `on`) * @param options.actualTypeName {string} name of the unexpected type for the `actual` value * @param options.expectedTypeName {string} name of the unexpected type for the `expected` value * @param options.queryTypeName {string} name of the unexpected type for the query value (used in `queried for` and `on`) * @param options.actualRenderOutputType {string} the unexpected type for the actual output value * @param options.getRenderOutput {function} called with the actual value, and returns the `actualRenderOutputType` type * @param options.getDiffInputFromRenderOutput {function} called with the value from `getRenderOutput`, result passed to HtmlLike diff * @param options.rewrapResult {function} called with the `actual` value (usually the renderer), and the found result * @param options.wrapResultForReturn {function} called with the `actual` value (usually the renderer), and the found result * from HtmlLike `contains()` call (usually the same type returned from `getDiffInputFromRenderOutput`. Used to create a * value that can be passed back to the user as the result of the promise. Used by `queried for` when no further assertion is * provided, therefore the return value is provided as the result of the promise. If this is not present, `rewrapResult` is used. * @param options.triggerEvent {function} called the `actual` value (renderer), the optional target (or null) as the result * from the HtmlLike `contains()` call target, the eventName, and optional eventArgs when provided (undefined otherwise) * @constructor */ function AssertionGenerator(options) { this._options = Object.assign({}, options); this._PENDING_EVENT_IDENTIFIER = (options.mainAssertionGenerator && options.mainAssertionGenerator.getEventIdentifier()) || { dummy: options.actualTypeName + 'PendingEventIdentifier' }; this._actualPendingEventTypeName = options.actualTypeName + 'PendingEvent'; } AssertionGenerator.prototype.getEventIdentifier = function () { return this._PENDING_EVENT_IDENTIFIER; }; AssertionGenerator.prototype.installInto = function installInto(expect) { this._installEqualityAssertions(expect); this._installQueriedFor(expect); this._installPendingEventType(expect); this._installWithEvent(expect); this._installWithEventOn(expect); this._installEventHandlerAssertions(expect); }; AssertionGenerator.prototype.installAlternativeExpected = function (expect) { this._installEqualityAssertions(expect); this._installEventHandlerAssertions(expect); } AssertionGenerator.prototype._installEqualityAssertions = function (expect) { const { actualTypeName, expectedTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, ActualAdapter, ExpectedAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualTypeName}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput) .then(() => subject); }); expect.addAssertion([ `<${actualRenderOutputType}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualRenderOutputType}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>` ], function (expect, subject, renderOutput) { const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const actualAdapter = new ActualAdapter(); const expectedAdapter = new ExpectedAdapter(); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { expectedAdapter.setOptions({concatTextContent: true}); actualAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const diffResult = testHtmlLike.diff(expectedAdapter, getDiffInputFromRenderOutput(subject), renderOutput, expect, options); return testHtmlLike.withResult(diffResult, result => { if (result.weight !== 0) { return expect.fail({ diff: function (output, diff, inspect) { return output.append(testHtmlLike.render(result, output.clone(), diff, inspect)); } }); } return result; }); }); expect.addAssertion([`<${actualTypeName}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput); }); expect.addAssertion([`<${actualRenderOutputType}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualRenderOutputType}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, expected) { var not = this.flags.not; var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var expectedAdapter = new ExpectedAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); expectedAdapter.setOptions({concatTextContent: true}); } var options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const containsResult = testHtmlLike.contains(expectedAdapter, getDiffInputFromRenderOutput(subject), expected, expect, options); return testHtmlLike.withResult(containsResult, result => { if (not) { if (result.found) { expect.fail({ diff: (output, diff, inspect) => { return output.error('but found the following match').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } return; } if (!result.found) { expect.fail({ diff: function (output, diff, inspect) { return output.error('the best match was').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } }); }); // More generic assertions expect.addAssertion(`<${actualTypeName}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to equal', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have exactly rendered', expected); }); expect.addAssertion(`<${actualTypeName}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to satisfy', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have rendered', expected); }); }; AssertionGenerator.prototype._installQueriedFor = function (expect) { const { actualTypeName, queryTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, rewrapResult, wrapResultForReturn, ActualAdapter, QueryAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualTypeName}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>` ], function (expect, subject, query, assertion) { return expect.apply(expect, [ getRenderOutput(subject), 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', query ].concat(Array.prototype.slice.call(arguments, 3))); }); expect.addAssertion([`<${actualRenderOutputType}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualRenderOutputType}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, query) { var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var queryAdapter = new QueryAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); queryAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'queryTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(subject), query, expect, options); const args = arguments; return testHtmlLike.withResult(containsResult, function (result) { if (!result.found) { expect.fail({ diff: (output, diff, inspect) => { const resultOutput = output.error('`queried for` found no match.'); if (result.bestMatch) { resultOutput.error(' The best match was') .nl() .append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return resultOutput; } }); } if (args.length > 3) { // There is an assertion continuation... expect.errorMode = 'nested' const s = rewrapResult(subject, result.bestMatch.target || result.bestMatchItem); return expect.apply(null, [ rewrapResult(subject, result.bestMatch.target || result.bestMatchItem) ].concat(Array.prototype.slice.call(args, 3))) return expect.shift(rewrapResult(subject, result.bestMatch.target || result.bestMatchItem)); } // There is no assertion continuation, so we need to wrap the result for public consumption // i.e. create a value that we can give back from the `expect` promise return expect.shift((wrapResultForReturn || rewrapResult)(subject, result.bestMatch.target || result.bestMatchItem)); }); }); }; AssertionGenerator.prototype._installPendingEventType = function (expect) { const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addType({ name: actualPendingEventTypeName, base: 'object', identify(value) { return value && typeof value === 'object' && value.$$typeof === PENDING_EVENT_IDENTIFIER; }, inspect(value, depth, output, inspect) { return output.append(inspect(value.renderer)).red(' with pending event \'').cyan(value.eventName).red('\''); } }); }; AssertionGenerator.prototype._installWithEvent = function (expect) { const { actualTypeName, actualRenderOutputType, triggerEvent, canTriggerEventsOnOutputType } = this._options; let { wrapResultForReturn = (value) => value } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addAssertion(`<${actualTypeName}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualTypeName}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject, null, eventName, eventArgs); return expect.shift(subject); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); if (canTriggerEventsOnOutputType) { expect.addAssertion(`<${actualRenderOutputType}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, isOutputType: true }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualRenderOutputType}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, args) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: args, isOutputType: true }); } else { triggerEvent(subject, null, eventName, args); return expect.shift(subject); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); } expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <assertion?>`, function (expect, subject, eventName) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 3) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName }); } else { triggerEvent(subject.renderer, null, eventName); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject.renderer, null, eventName, eventArgs); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); }; AssertionGenerator.prototype._installWithEventOn = function (expect) { const { actualTypeName, queryTypeName, expectedTypeName, getRenderOutput, getDiffInputFromRenderOutput, triggerEvent, ActualAdapter, QueryAdapter } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion(`<${actualPendingEventTypeName}> on [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]<${queryTypeName}> <assertion?>`, function (expect, subject, target) { const actualAdapter = new ActualAdapter({ convertToString: true, concatTextContent: true }); const queryAdapter = new QueryAdapter({ convertToString: true, concatTextContent: true }); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const options = getDefaultOptions({ exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'eventTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(getRenderOutput(subject.renderer)), target, expect, options); return testHtmlLike.withResult(containsResult, result => { if (!result.found) { return expect.fail({ diff: function (output, diff, inspect) { output.error('Could not find the target for the event. '); if (result.bestMatch) { output.error('The best match was').nl().nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return output; } }); } const newSubject = Object.assign({}, subject, { target: result.bestMatch.target || result.bestMatchItem }); if (arguments.length > 3) { return expect.shift(newSubject); } else { triggerEvent(newSubject.renderer, newSubject.target, newSubject.eventName, newSubject.eventArgs); return expect.shift(newSubject.renderer); } }); }); expect.addAssertion([`<${actualPendingEventTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualPendingEventTypeName}> queried for [with all children] [with all wrappers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect.apply(expect, [subject.renderer, 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected] .concat(Array.prototype.slice.call(arguments, 3))); } ); }; AssertionGenerator.prototype._installEventHandlerAssertions = function (expect) { const { actualTypeName, expectedTypeName, triggerEvent } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion([`<${actualPendingEventTypeName}> [not] to contain [exactly] <${expectedTypeName}>`, `<${actualPendingEventTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); expect.addAssertion(`<${actualPendingEventTypeName}> to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`, function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); }; export default AssertionGenerator;
bruderstein/unexpected-react
src/assertions/AssertionGenerator.js
JavaScript
mit
22,599
class MakeDagJsonLongText < ActiveRecord::Migration[5.1] def change change_column :phylo_trees, :dag_json, :longtext end end
chanzuckerberg/idseq-web
db/migrate/20181113172609_make_dag_json_long_text.rb
Ruby
mit
133
// Generated by CoffeeScript 1.7.1 (function() { var $, CSV, ES, TEXT, TRM, TYPES, alert, badge, create_readstream, debug, echo, help, info, log, njs_fs, rainbow, route, rpr, urge, warn, whisper; njs_fs = require('fs'); TYPES = require('coffeenode-types'); TEXT = require('coffeenode-text'); TRM = require('coffeenode-trm'); rpr = TRM.rpr.bind(TRM); badge = 'TIMETABLE/read-gtfs-data'; log = TRM.get_logger('plain', badge); info = TRM.get_logger('info', badge); whisper = TRM.get_logger('whisper', badge); alert = TRM.get_logger('alert', badge); debug = TRM.get_logger('debug', badge); warn = TRM.get_logger('warn', badge); help = TRM.get_logger('help', badge); urge = TRM.get_logger('urge', badge); echo = TRM.echo.bind(TRM); rainbow = TRM.rainbow.bind(TRM); create_readstream = require('../create-readstream'); /* http://c2fo.github.io/fast-csv/index.html, https://github.com/C2FO/fast-csv */ CSV = require('fast-csv'); ES = require('event-stream'); $ = ES.map.bind(ES); this.$count = function(input_stream, title) { var count; count = 0; input_stream.on('end', function() { return info((title != null ? title : 'Count') + ':', count); }); return $((function(_this) { return function(record, handler) { count += 1; return handler(null, record); }; })(this)); }; this.$skip_empty = function() { return $((function(_this) { return function(record, handler) { if (record.length === 0) { return handler(); } return handler(null, record); }; })(this)); }; this.$show = function() { return $((function(_this) { return function(record, handler) { urge(rpr(record.toString())); return handler(null, record); }; })(this)); }; this.read_trips = function(route, handler) { var input; input = CSV.fromPath(route); input.on('end', function() { log('ok: trips'); return handler(null); }); input.setMaxListeners(100); input.pipe(this.$count(input, 'trips A')).pipe(this.$show()); return null; }; if (!module.parent) { route = '/Volumes/Storage/cnd/node_modules/timetable-data/germany-berlin-2014/agency.txt'; this.read_trips(route, function(error) { if (error != null) { throw error; } return log('ok'); }); } }).call(this);
loveencounterflow/timetable
lib/scratch/test-fast-csv.js
JavaScript
mit
2,430
"use strict"; var request = require(__dirname + "/request"); var db = require(__dirname + "/db"); /** * Steam utils */ var steamapi = {}; /** * Request to our api * @param {string} type * @param {string[]} ids * @param {function} callback */ steamapi.request = function (type, ids, callback) { if (!ids.length) { callback({}); return; } var res = {}; var missingIds = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; var steamData = steamapi.getDataForId(type, id); if (steamData) { res[id] = steamData; } else { missingIds.push(id); } } if (missingIds.length) { request.get("https://scripts.0x.at/steamapi/api.php?action=" + type + "&ids=" + missingIds.join(","), false, function (result) { if (result !== null) { var steamData = null; var data = JSON.parse(result); if (type == "bans") { for (var i = 0; i < data.players.length; i++) { steamData = data.players[i]; steamapi.saveDataForId(type, steamData.SteamId, steamData); res[steamData.SteamId] = steamData; } } if (type == "summaries") { if(data.response){ for (var playerIndex in data.response.players) { if (data.response.players.hasOwnProperty(playerIndex)) { steamData = data.response.players[playerIndex]; steamapi.saveDataForId(type, steamData.steamid, steamData); res[steamData.steamid] = steamData; } } } } } callback(res); }); } else { callback(res); } }; /** * Get db data for steamid * @param {string} type * @param {string} id * @returns {*} */ steamapi.getDataForId = function (type, id) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData || !playerData[type]) return null; if (playerData[type].timestamp < (new Date().getTime() / 1000 - 86400)) { delete playerData[type]; } return playerData[type] || null; }; /** * Save db data for steamid * @param {string} type * @param {string} id * @param {object} data * @returns {*} */ steamapi.saveDataForId = function (type, id, data) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData) playerData = {}; data.timestamp = new Date().getTime() / 1000; playerData[type] = data; sdb.set(id, playerData).value(); }; /** * Delete old entries */ steamapi.cleanup = function () { try { var data = db.get("steamapi").value(); var timeout = new Date() / 1000 - 86400; for (var steamId in data) { if (data.hasOwnProperty(steamId)) { var entries = data[steamId]; for (var entryIndex in entries) { if (entries.hasOwnProperty(entryIndex)) { var entryRow = entries[entryIndex]; if (entryRow.timestamp < timeout) { delete entries[entryIndex]; } } } } } db.get("steamapi").setState(data); } catch (e) { console.error(new Date(), "Steamapi cleanup failed", e, e.stack); } }; // each 30 minutes cleanup the steamapi db and remove old entries setInterval(steamapi.cleanup, 30 * 60 * 1000); steamapi.cleanup(); module.exports = steamapi;
brainfoolong/rcon-web-admin
src/steamapi.js
JavaScript
mit
3,790
//THREEJS RELATED VARIABLES var scene, camera, fieldOfView, aspectRatio, nearPlane, farPlane, gobalLight, shadowLight, backLight, renderer, container, controls; //SCREEN & MOUSE VARIABLES var HEIGHT, WIDTH, windowHalfX, windowHalfY, mousePos = { x: 0, y: 0 }, oldMousePos = {x:0, y:0}, ballWallDepth = 28; //3D OBJECTS VARIABLES var hero; //INIT THREE JS, SCREEN AND MOUSE EVENTS function initScreenAnd3D() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; scene = new THREE.Scene(); aspectRatio = WIDTH / HEIGHT; fieldOfView = 50; nearPlane = 1; farPlane = 2000; camera = new THREE.PerspectiveCamera( fieldOfView, aspectRatio, nearPlane, farPlane ); camera.position.x = 0; camera.position.z = 300; camera.position.y = 250; camera.lookAt(new THREE.Vector3(0, 60, 0)); renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize(WIDTH, HEIGHT); renderer.shadowMapEnabled = true; container = document.getElementById('world'); container.appendChild(renderer.domElement); window.addEventListener('resize', handleWindowResize, false); document.addEventListener('mousemove', handleMouseMove, false); document.addEventListener('touchmove', handleTouchMove, false); /* controls = new THREE.OrbitControls(camera, renderer.domElement); controls.minPolarAngle = -Math.PI / 2; controls.maxPolarAngle = Math.PI / 2; controls.noZoom = true; controls.noPan = true; //*/ } function handleWindowResize() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; renderer.setSize(WIDTH, HEIGHT); camera.aspect = WIDTH / HEIGHT; camera.updateProjectionMatrix(); } function handleMouseMove(event) { mousePos = {x:event.clientX, y:event.clientY}; } function handleTouchMove(event) { if (event.touches.length == 1) { event.preventDefault(); mousePos = {x:event.touches[0].pageX, y:event.touches[0].pageY}; } } function createLights() { globalLight = new THREE.HemisphereLight(0xffffff, 0xffffff, .5) shadowLight = new THREE.DirectionalLight(0xffffff, .9); shadowLight.position.set(200, 200, 200); shadowLight.castShadow = true; shadowLight.shadowDarkness = .2; shadowLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; backLight = new THREE.DirectionalLight(0xffffff, .4); backLight.position.set(-100, 100, 100); backLight.castShadow = true; backLight.shadowDarkness = .1; backLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; scene.add(globalLight); scene.add(shadowLight); scene.add(backLight); } function createFloor(){ floor = new THREE.Mesh(new THREE.PlaneBufferGeometry(1000,1000), new THREE.MeshBasicMaterial({color: 0x004F65})); floor.rotation.x = -Math.PI/2; floor.position.y = 0; floor.receiveShadow = true; scene.add(floor); } function createHero() { hero = new Cat(); scene.add(hero.threeGroup); } function createBall() { ball = new Ball(); scene.add(ball.threeGroup); } // BALL RELATED CODE var woolNodes = 10, woolSegLength = 2, gravity = -.8, accuracy =1; Ball = function(){ var redMat = new THREE.MeshLambertMaterial ({ color: 0x630d15, shading:THREE.FlatShading }); var stringMat = new THREE.LineBasicMaterial({ color: 0x630d15, linewidth: 3 }); this.threeGroup = new THREE.Group(); this.ballRay = 8; this.verts = []; // string var stringGeom = new THREE.Geometry(); for (var i=0; i< woolNodes; i++ ){ var v = new THREE.Vector3(0, -i*woolSegLength, 0); stringGeom.vertices.push(v); var woolV = new WoolVert(); woolV.x = woolV.oldx = v.x; woolV.y = woolV.oldy = v.y; woolV.z = 0; woolV.fx = woolV.fy = 0; woolV.isRootNode = (i==0); woolV.vertex = v; if (i > 0) woolV.attach(this.verts[(i - 1)]); this.verts.push(woolV); } this.string = new THREE.Line(stringGeom, stringMat); // body var bodyGeom = new THREE.SphereGeometry(this.ballRay, 5,4); this.body = new THREE.Mesh(bodyGeom, redMat); this.body.position.y = -woolSegLength*woolNodes; var wireGeom = new THREE.TorusGeometry( this.ballRay, .5, 3, 10, Math.PI*2 ); this.wire1 = new THREE.Mesh(wireGeom, redMat); this.wire1.position.x = 1; this.wire1.rotation.x = -Math.PI/4; this.wire2 = this.wire1.clone(); this.wire2.position.y = 1; this.wire2.position.x = -1; this.wire1.rotation.x = -Math.PI/4 + .5; this.wire1.rotation.y = -Math.PI/6; this.wire3 = this.wire1.clone(); this.wire3.rotation.x = -Math.PI/2 + .3; this.wire4 = this.wire1.clone(); this.wire4.position.x = -1; this.wire4.rotation.x = -Math.PI/2 + .7; this.wire5 = this.wire1.clone(); this.wire5.position.x = 2; this.wire5.rotation.x = -Math.PI/2 + 1; this.wire6 = this.wire1.clone(); this.wire6.position.x = 2; this.wire6.position.z = 1; this.wire6.rotation.x = 1; this.wire7 = this.wire1.clone(); this.wire7.position.x = 1.5; this.wire7.rotation.x = 1.1; this.wire8 = this.wire1.clone(); this.wire8.position.x = 1; this.wire8.rotation.x = 1.3; this.wire9 = this.wire1.clone(); this.wire9.scale.set(1.2,1.1,1.1); this.wire9.rotation.z = Math.PI/2; this.wire9.rotation.y = Math.PI/2; this.wire9.position.y = 1; this.body.add(this.wire1); this.body.add(this.wire2); this.body.add(this.wire3); this.body.add(this.wire4); this.body.add(this.wire5); this.body.add(this.wire6); this.body.add(this.wire7); this.body.add(this.wire8); this.body.add(this.wire9); this.threeGroup.add(this.string); this.threeGroup.add(this.body); this.threeGroup.traverse( function ( object ) { if ( object instanceof THREE.Mesh ) { object.castShadow = true; object.receiveShadow = true; }}); } /* The next part of the code is largely inspired by this codepen : http://codepen.io/dissimulate/pen/KrAwx?editors=001 thanks to dissimulate for his great work */ /* Copyright (c) 2013 dissimulate at Codepen 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. */ WoolVert = function(){ this.x = 0; this.y = 0; this.z = 0; this.oldx = 0; this.oldy = 0; this.fx = 0; this.fy = 0; this.isRootNode = false; this.constraints = []; this.vertex = null; } WoolVert.prototype.update = function(){ var wind = 0;//.1+Math.random()*.5; this.add_force(wind, gravity); nx = this.x + ((this.x - this.oldx)*.9) + this.fx; ny = this.y + ((this.y - this.oldy)*.9) + this.fy; this.oldx = this.x; this.oldy = this.y; this.x = nx; this.y = ny; this.vertex.x = this.x; this.vertex.y = this.y; this.vertex.z = this.z; this.fy = this.fx = 0 } WoolVert.prototype.attach = function(point) { this.constraints.push(new Constraint(this, point)); }; WoolVert.prototype.add_force = function(x, y) { this.fx += x; this.fy += y; }; Constraint = function(p1, p2) { this.p1 = p1; this.p2 = p2; this.length = woolSegLength; }; Ball.prototype.update = function(posX, posY, posZ){ var i = accuracy; while (i--) { var nodesCount = woolNodes; while (nodesCount--) { var v = this.verts[nodesCount]; if (v.isRootNode) { v.x = posX; v.y = posY; v.z = posZ; } else { var constraintsCount = v.constraints.length; while (constraintsCount--) { var c = v.constraints[constraintsCount]; var diff_x = c.p1.x - c.p2.x, diff_y = c.p1.y - c.p2.y, dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y), diff = (c.length - dist) / dist; var px = diff_x * diff * .5; var py = diff_y * diff * .5; c.p1.x += px; c.p1.y += py; c.p2.x -= px; c.p2.y -= py; c.p1.z = c.p2.z = posZ; } if (nodesCount == woolNodes-1){ this.body.position.x = this.verts[nodesCount].x; this.body.position.y = this.verts[nodesCount].y; this.body.position.z = this.verts[nodesCount].z; this.body.rotation.z += (v.y <= this.ballRay)? (v.oldx-v.x)/10 : Math.min(Math.max( diff_x/2, -.1 ), .1); } } if (v.y < this.ballRay) { v.y = this.ballRay; } } } nodesCount = woolNodes; while (nodesCount--) this.verts[nodesCount].update(); this.string.geometry.verticesNeedUpdate = true; } Ball.prototype.receivePower = function(tp){ this.verts[woolNodes-1].add_force(tp.x, tp.y); } // Enf of the code inspired by dissmulate // Make everything work together : var t=0; function loop(){ render(); t+=.05; hero.updateTail(t); var ballPos = getBallPos(); ball.update(ballPos.x,ballPos.y, ballPos.z); ball.receivePower(hero.transferPower); hero.interactWithBall(ball.body.position); requestAnimationFrame(loop); } function getBallPos(){ var vector = new THREE.Vector3(); vector.set( ( mousePos.x / window.innerWidth ) * 2 - 1, - ( mousePos.y / window.innerHeight ) * 2 + 1, 0.1 ); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = (ballWallDepth - camera.position.z) / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance ) ); return pos; } function render(){ if (controls) controls.update(); renderer.render(scene, camera); } window.addEventListener('load', init, false); function init(event){ initScreenAnd3D(); createLights(); createFloor() createHero(); createBall(); loop(); }
exildev/webpage
exile_ui/static/404/js/index.js
JavaScript
mit
10,479
import { Widget, startAppLoop, Url, History } from 'cx/ui'; import { Timing, Debug } from 'cx/util'; import { Store } from 'cx/data'; import Routes from './routes'; import 'whatwg-fetch'; import "./index.scss"; let stop; const store = new Store(); if(module.hot) { // accept itself module.hot.accept(); // remember data on dispose module.hot.dispose(function (data) { data.state = store.getData(); if (stop) stop(); }); //apply data on hot replace if (module.hot.data) store.load(module.hot.data.state); } Url.setBaseFromScript('app.js'); History.connect(store, 'url'); Widget.resetCounter(); Timing.enable('app-loop'); Debug.enable('app-data'); stop = startAppLoop(document.getElementById('app'), store, Routes);
codaxy/employee-directory-demo
client/app/index.js
JavaScript
mit
755
require 'thor' module EcsDeployer class CLI < Thor class_option :profile, type: :string class_option :region, type: :string no_commands do def prepare @aws_options = {} @aws_options[:profile] = options[:profile] if options[:profile] @aws_options[:region] = options[:region] if options[:region] @logger = Logger.new(STDOUT) nil end def invoke_command(command, *args) prepare super end end desc 'task-register', 'Create new task definition' option :path, required: true option :replace_variables, type: :hash, default: {} def task_register path = File.expand_path(options[:path], Dir.pwd) task_client = EcsDeployer::Task::Client.new(@aws_options) result = task_client.register(path, options[:replace_variables]) puts "Registered task: #{result.task_definition_arn}" end desc 'update-service', 'Update service difinition.' option :cluster, required: true option :service, required: true option :wait, type: :boolean, default: true option :wait_timeout, type: :numeric, default: 600 def update_service deploy_client = EcsDeployer::Client.new(options[:cluster], @logger, @aws_options) service_client = deploy_client.service service_client.wait_timeout = options[:wait_timeout] result = service_client.update(options[:service], nil, options[:wait]) puts "Service has been successfully updated: #{result.service_arn}" end desc 'encrypt', 'Encrypt value of argument with KMS.' option :master_key, required: true option :value, required: true def encrypt cipher = EcsDeployer::Util::Cipher.new(@aws_options) puts "Encrypted value: #{cipher.encrypt(options[:master_key], options[:value])}" end desc 'decrypt', 'Decrypt value of argument with KMS.' option :value, required: true def decrypt cipher = EcsDeployer::Util::Cipher.new(@aws_options) puts "Decrypted value: #{cipher.decrypt(options[:value])}" end end end
naomichi-y/ecs_deployer
lib/ecs_deployer/cli.rb
Ruby
mit
2,077
from settings.common import Common class Dev(Common): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } }
Critical-Impact/ffrpg-gen
django/settings/dev.py
Python
mit
650
package pl.edu.uwm.wmii.visearch.clustering; /* * * Z linii poleceń * /usr/local/mahout/bin/mahout kmeans -i kmeans/data1/in -c kmeans/data1/cl -o kmeans/data1/out -x 10 -k 2 -ow -cl * opcja -ow nadpisuje katalog wyjściowy (nie trzeba ręcznie kasować) * opcja -cl generuje katalog clusteredPoints, zawierający informację o tym który punt do którego klastra * /usr/local/mahout/bin/mahout clusterdump -i kmeans/data1/out/clusters-*-final * * */ import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.StringTokenizer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.mahout.clustering.Cluster; import org.apache.mahout.clustering.conversion.InputDriver; import org.apache.mahout.clustering.iterator.ClusterWritable; import org.apache.mahout.clustering.kmeans.KMeansDriver; import org.apache.mahout.clustering.kmeans.RandomSeedGenerator; import org.apache.mahout.common.HadoopUtil; import org.apache.mahout.common.Pair; import org.apache.mahout.common.distance.DistanceMeasure; import org.apache.mahout.common.distance.EuclideanDistanceMeasure; import org.apache.mahout.common.iterator.sequencefile.PathFilters; import org.apache.mahout.common.iterator.sequencefile.PathType; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterable; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterator; import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirValueIterable; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.NamedVector; import org.apache.mahout.math.RandomAccessSparseVector; import org.apache.mahout.math.SequentialAccessSparseVector; import org.apache.mahout.math.VectorWritable; import org.apache.mahout.math.Vector; import org.apache.mahout.utils.clustering.ClusterDumper; import org.apache.mahout.vectorizer.SparseVectorsFromSequenceFiles; import org.apache.mahout.clustering.classify.ClusterClassificationDriver; import org.apache.mahout.clustering.classify.WeightedVectorWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import pl.edu.uwm.wmii.visearch.core.ConfigFile; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class KMeans { private static final Logger log = LoggerFactory.getLogger(KMeans.class); private static final Path BASE_DIR = new Path("visearch"); private static final Path DESCRIPTORS_DIR = new Path("visearch/descriptors"); private static final Path DICTIONARY_DIR = new Path("visearch/dictionary"); private static final Path VISUAL_WORDS_DIR = new Path( "visearch/visualwords"); private static final Path REPRESENTATIONS_DIR = new Path( "visearch/representations"); private static void createInput(Configuration conf, ConfigFile configFile, Path outputDir) throws Exception { String descriptorsDir = configFile.get("descriptorsDir") + "/SIFT"; File files = new File(descriptorsDir); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // wyczysc katalog z deskryptorami FileSystem fs = outputDir.getFileSystem(conf); fs.delete(outputDir, true); fs.mkdirs(outputDir); Path outputFile = new Path(outputDir, "all-descriptors"); SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, outputFile, Text.class, VectorWritable.class); // key:value pair for output file Text key = new Text(); VectorWritable val = new VectorWritable(); // procedura tworzaca pojedynczy duzy plik z deskryptorami dla kazdego // obrazka // k: [hash obrazka]:[kolejny numer deskryptora] // v: [deskryptor, 128 elementow dla SIFT'a] int totalFiles = 0; int badFiles = 0; for (File f : files.listFiles()) { totalFiles++; String docId = f.getName().split("\\.")[0]; log.info(String.valueOf(totalFiles)); try { Document doc = dBuilder.parse(f); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("desc"); for (int i = 0; i < nList.getLength(); i++) { String csv = nList.item(i).getTextContent(); String[] csvParts = csv.split(","); double[] data = new double[csvParts.length]; for (int j = 0; j < csvParts.length; j++) { data[j] = Integer.parseInt(csvParts[j].trim()); } StringBuilder sb = new StringBuilder(); sb.append(docId).append(":").append(i); key.set(sb.toString()); val.set(new DenseVector(data)); writer.append(key, val); } } catch (Exception e) { badFiles++; System.out.println(badFiles+"/"+totalFiles+" "+e); } } writer.close(); System.out.println("Done making a bigfile, #files: "+(totalFiles-badFiles)); } private static void runClustering(Configuration conf, ConfigFile configFile) throws IOException, ClassNotFoundException, InterruptedException { FileSystem fs = FileSystem.get(conf); Path clusters = new Path(BASE_DIR, new Path("initial-clusters")); fs.delete(DICTIONARY_DIR, true); fs.mkdirs(DICTIONARY_DIR); DistanceMeasure measure = new EuclideanDistanceMeasure(); int k = configFile.get("dictionarySize",100); double convergenceDelta = configFile.get("dictionaryConvergenceDelta",0.001); int maxIterations = configFile.get("dictionaryMaxIterations",10); // Random clusters clusters = RandomSeedGenerator.buildRandom(conf, DESCRIPTORS_DIR, clusters, k, measure); log.info("Random clusters generated, running K-Means, k="+k+" maxIter="+maxIterations); log.info("KMeansDriver.run(..."); log.info(DESCRIPTORS_DIR.toString()); log.info(clusters.toString()); log.info(DICTIONARY_DIR.toString()); log.info("....)"); KMeansDriver.run(conf, DESCRIPTORS_DIR, clusters, DICTIONARY_DIR, measure, convergenceDelta, maxIterations, true, 0.0, VM.RunSequential()); log.info("KMeans done"); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); /* * TODO: musze jakos ustawic sciezki dla jar'a do /usr/local/hadoop/conf * bo KMeansDriver nie widzi ustawien hdfs i zapisuje wyniki klasteryzacji * do lokalnego katalogu * File files = new File("/usr/local/hadoop/conf"); for (File f : files.listFiles()) { System.out.println(f.getAbsolutePath()); conf.addResource(f.getAbsolutePath()); }*/ log.info("Configuration: "+conf.toString()); log.info("fs.default.name: "+conf.get("fs.default.name")); FileSystem fs = FileSystem.get(conf); ConfigFile configFile = new ConfigFile("settings.cfg"); boolean skipCreatingDictionary = false; try { List<String> largs = Arrays.asList(args); if (largs.contains("skipdict")) { skipCreatingDictionary = true; } } catch (Exception e) { } if (!skipCreatingDictionary) { if (VM.RunSequential()) { System.out.println("Running as SEQ"); } else { System.out.println("Running as MR"); } // stworz pliki z deskryptorami na podstawie xml'i // TODO: najlepiej zeby Anazyler zapisywal pliki od razu do hdfs (daily basis?) createInput(conf, configFile, DESCRIPTORS_DIR); // uruchom K-Means dla deskryptorow runClustering(conf, configFile); } else { log.info("Skipped creating dictionary"); } ImageToTextDriver.run(conf, DESCRIPTORS_DIR, DICTIONARY_DIR, VISUAL_WORDS_DIR, VM.RunSequential()); String dbUrl = configFile.get("dbUrl"); String dbUser = configFile.get("dbUser"); String dbPass = configFile.get("dbPass"); Connection dbConnection = DriverManager.getConnection("jdbc:" + dbUrl, dbUser, dbPass); log.info("Connected to {}", dbUrl); Statement statement = dbConnection.createStatement(); statement.executeUpdate("DELETE FROM ImageRepresentations"); statement.executeUpdate("DELETE FROM IFS"); for (Pair<Text, Text> entry : new SequenceFileDirIterable<Text, Text>( VISUAL_WORDS_DIR, PathType.LIST, conf)) { String docId = entry.getFirst().toString(); String line = entry.getSecond().toString(); StringTokenizer tokenizer = new StringTokenizer(line); Map<Integer, Integer> termFreq = new TreeMap<Integer, Integer>(); while (tokenizer.hasMoreTokens()) { int key = Integer.parseInt(tokenizer.nextToken()); if (termFreq.containsKey(key)) { termFreq.put(key, termFreq.get(key) + 1); } else { termFreq.put(key, 1); } } saveToDb(docId, termFreq, dbConnection); } dbConnection.close(); /* * MyClusterClassificationDriver .run(conf, DESCRIPTORS_DIR, * DICTIONARY_DIR, VISUAL_WORDS_DIR, 0.0, true, VM.RunSequential()); */ /* * Albo stworze wlasny map-reduce, ktory utworzy histogramy TF * * Albo zapisze obrazki jako tekst, i zapuszce na nich narzedzia * dostepne w Mahout org.apache.mahout.text.SequenceFilesFromDirectory * org.apache.mahout.vectorizer.SparseVectorsFromSequenceFiles */ // BagOfWordsDriver.run(conf, VISUAL_WORDS_DIR, REPRESENTATIONS_DIR, // VM.RunSequential()); /* * Path representationsFile = new Path(REPRESENTATIONS_DIR, "part-0"); * SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf, * representationsFile, Text.class, VectorWritable.class); Text key = * new Text(); VectorWritable val = new VectorWritable(); * * RandomAccessSparseVector freq = new RandomAccessSparseVector(10); for * (Pair<IntWritable, Text> entry : new * SequenceFileDirIterable<IntWritable, Text>( VISUAL_WORDS_DIR, * PathType.LIST, conf)) { int idx = entry.getFirst().get(); * freq.incrementQuick(idx, 1); } */ /* * // stworzenie histogramu i zapisanie do pliku jako sparse vector for * (FileStatus f : fs.listStatus(VISUAL_WORDS_DIR)) { if (f.isDir()) { * RandomAccessSparseVector freq = new RandomAccessSparseVector(10); for * (Pair<IntWritable, WeightedVectorWritable> entry : new * SequenceFileDirIterable<IntWritable, WeightedVectorWritable>( new * Path(f.getPath(), "part-*"), PathType.GLOB, conf)) { int idx = * entry.getFirst().get(); freq.incrementQuick(idx, 1); } * key.set(f.getPath().getName()); val.set(freq); writer.append(key, * val); * * log.info("REP: {}",key); } } writer.close(); */ // saveToDb(conf, configFile); log.info("Done"); } private static void saveToDb(String docId, Map<Integer, Integer> termFreq, Connection dbConnection) throws InvalidKeyException, SQLException, IOException { String sql; PreparedStatement ps; // build json string and IFS Iterator<Entry<Integer, Integer>> it = termFreq.entrySet().iterator(); Map.Entry<Integer, Integer> e; String json = "{"; while (it.hasNext()) { e = it.next(); json += "\"" + e.getKey() + "\":\"" + e.getValue() + "\""; if (it.hasNext()) { json += ", "; } // save to IFS as well sql = "INSERT INTO IFS SELECT ?, ImageId FROM Images WHERE FileName LIKE ?"; ps = dbConnection.prepareStatement(sql); ps.setInt(1, e.getKey()); ps.setString(2, docId + "%"); ps.executeUpdate(); } json += "}"; System.out.println(termFreq); System.out.println(json); sql = "INSERT INTO ImageRepresentations SELECT ImageId, ? FROM Images WHERE FileName LIKE ?"; ps = dbConnection.prepareStatement(sql); ps.setString(1, json); ps.setString(2, docId.toString() + "%"); ps.executeUpdate(); } }
pgorecki/visearch
projects/clustering/src/pl/edu/uwm/wmii/visearch/clustering/KMeans.java
Java
mit
12,415
<?php defined('BASEPATH') or exit('No direct script access allowed'); use Omnipay\Omnipay; class Authorize_sim_gateway extends App_gateway { public function __construct() { /** * Call App_gateway __construct function */ parent::__construct(); /** * REQUIRED * Gateway unique id * The ID must be alpha/alphanumeric */ $this->setId('authorize_sim'); /** * REQUIRED * Gateway name */ $this->setName('Authorize.net SIM'); /** * Add gateway settings */ $this->setSettings([ [ 'name' => 'api_login_id', 'encrypted' => true, 'label' => 'settings_paymentmethod_authorize_api_login_id', ], [ 'name' => 'api_transaction_key', 'label' => 'settings_paymentmethod_authorize_api_transaction_key', 'encrypted' => true, ], [ 'name' => 'api_secret_key', 'label' => 'settings_paymentmethod_authorize_secret_key', 'encrypted' => true, ], [ 'name' => 'description_dashboard', 'label' => 'settings_paymentmethod_description', 'type' => 'textarea', 'default_value' => 'Payment for Invoice {invoice_number}', ], [ 'name' => 'currencies', 'label' => 'currency', 'default_value' => 'USD', ], [ 'name' => 'test_mode_enabled', 'type' => 'yes_no', 'default_value' => 0, 'label' => 'settings_paymentmethod_testing_mode', ], [ 'name' => 'developer_mode_enabled', 'type' => 'yes_no', 'default_value' => 1, 'label' => 'settings_paymentmethod_developer_mode', ], ]); /** * REQUIRED * Hook gateway with other online payment modes */ add_action('before_add_online_payment_modes', [ $this, 'initMode' ]); add_action('before_render_payment_gateway_settings', 'authorize_sim_notice'); } public function process_payment($data) { $gateway = Omnipay::create('AuthorizeNet_SIM'); $gateway->setApiLoginId($this->decryptSetting('api_login_id')); $gateway->setTransactionKey($this->decryptSetting('api_transaction_key')); $gateway->setHashSecret($this->decryptSetting('api_secret_key')); $gateway->setTestMode($this->getSetting('test_mode_enabled')); $gateway->setDeveloperMode($this->getSetting('developer_mode_enabled')); $billing_data['billingCompany'] = $data['invoice']->client->company; $billing_data['billingAddress1'] = $data['invoice']->billing_street; $billing_data['billingName'] = ''; $billing_data['billingCity'] = $data['invoice']->billing_city; $billing_data['billingState'] = $data['invoice']->billing_state; $billing_data['billingPostcode'] = $data['invoice']->billing_zip; $_country = ''; $country = get_country($data['invoice']->billing_country); if ($country) { $_country = $country->short_name; } $billing_data['billingCountry'] = $_country; $trans_id = time(); $requestData = [ 'amount' => number_format($data['amount'], 2, '.', ''), 'currency' => $data['invoice']->currency_name, 'returnUrl' => site_url('gateways/authorize_sim/complete_purchase'), 'description' => str_replace('{invoice_number}', format_invoice_number($data['invoice']->id), $this->getSetting('description_dashboard')), 'transactionId' => $trans_id, 'invoiceNumber' => format_invoice_number($data['invoice']->id), 'card' => $billing_data, ]; $oResponse = $gateway->purchase($requestData)->send(); if ($oResponse->isRedirect()) { $this->ci->db->where('id', $data['invoice']->id); $this->ci->db->update('tblinvoices', ['token' => $trans_id]); // redirect to offsite payment gateway $oResponse->redirect(); } else { // payment failed: display message to customer echo $oResponse->getMessage(); } } } function authorize_sim_notice($gateway) { if ($gateway['id'] == 'authorize_sim') { echo '<p class="text-dark"><b>' . _l('currently_supported_currencies') . '</b>: USD, AUD, GBP, CAD, EUR, NZD</p>'; } }
cmaciasg/test
application/libraries/gateways/Authorize_sim_gateway.php
PHP
mit
4,944
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.Linq; namespace Cassette { class AssetSerializer : IBundleVisitor { readonly XElement container; public AssetSerializer(XElement container) { this.container = container; } void IBundleVisitor.Visit(Bundle bundle) { } void IBundleVisitor.Visit(IAsset asset) { Serialize(asset); } public void Serialize(IAsset asset) { container.Add(AssetElement(asset)); } XElement AssetElement(IAsset asset) { return new XElement( "Asset", new XAttribute("Path", asset.Path), new XAttribute("AssetCacheValidatorType", asset.AssetCacheValidatorType.AssemblyQualifiedName), ReferenceElements(asset.References) ); } IEnumerable<XElement> ReferenceElements(IEnumerable<AssetReference> references) { return references.Select(ReferenceElement); } XElement ReferenceElement(AssetReference reference) { return new XElement( "Reference", new XAttribute("Path", reference.ToPath), new XAttribute("Type", Enum.GetName(typeof(AssetReferenceType), reference.Type)), new XAttribute("SourceLineNumber", reference.SourceLineNumber.ToString(CultureInfo.InvariantCulture)) ); } } }
BluewireTechnologies/cassette
src/Cassette/AssetSerializer.cs
C#
mit
1,634
# google_search.rb # Author: William Woodruff # ------------------------ # A Cinch plugin that provides Google interaction for yossarian-bot. # ------------------------ # This code is licensed by William Woodruff under the MIT License. # http://opensource.org/licenses/MIT require 'json' require 'open-uri' require_relative 'yossarian_plugin' class GoogleSearch < YossarianPlugin include Cinch::Plugin def usage '!g <search> - Search Google. Alias: !google.' end def match?(cmd) cmd =~ /^(!)?(google)|(g)$/ end match /g(?:oogle)? (.+)/, method: :google_search def google_search(m, search) url = URI.encode("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q=#{search}&max-results=1&v=2&prettyprint=false&alt=json") hash = JSON.parse(open(url).read) unless hash['responseData']['results'].empty? site = hash['responseData']['results'][0]['url'] content = hash['responseData']['results'][0]['content'].gsub(/([\t\r\n])|(<(\/)?b>)/, '') content.gsub!(/(&amp;)|(&quot;)|(&lt;)|(&gt;)|(&#39;)/, '&amp;' => '&', '&quot;' => '"', '&lt;' => '<', '&gt;' => '>', '&#39;' => '\'') m.reply "#{m.user.nick}: #{site} - #{content}" else m.reply "#{m.user.nick}: No Google results for #{search}." end end end
lightarrow47/yossarian-bot
plugins/google_search.rb
Ruby
mit
1,278
import React from 'react'; import { default as TriggersContainer } from './TriggersContainer'; import { mount } from 'enzyme'; const emptyDispatch = () => null; const emptyActions = { setGeoJSON: () => null }; describe('(Container) TriggersContainer', () => { it('Renders a TriggersContainer', () => { const _component = mount(<TriggersContainer dispatch={emptyDispatch} actions={emptyActions} />); expect(_component.type()).to.eql(TriggersContainer); }); });
maartenlterpstra/GeoWeb-FrontEnd
src/containers/TriggersContainer.spec.js
JavaScript
mit
474
module Pageflow class EntryDuplicate < Struct.new(:original_entry) def create! create_entry copy_draft copy_memberships new_entry end def self.of(entry) new(entry) end private attr_reader :new_entry def create_entry @new_entry = Entry.create!(new_attributes) end def copy_draft original_entry.draft.copy do |revision| revision.entry = new_entry end end def copy_memberships original_entry.users.each do |member| new_entry.memberships.create(user: member) end end def new_attributes { title: new_title, account: original_entry.account, theming: original_entry.theming, features_configuration: original_entry.features_configuration, skip_draft_creation: true } end def new_title I18n.t('pageflow.entry.duplicated_title', title: original_entry.title) end end end
grgr/pageflow
app/models/pageflow/entry_duplicate.rb
Ruby
mit
973
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'page_object_on_demand'
tomazy/page_object_on_demand
spec/spec_helper.rb
Ruby
mit
91
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Student_records_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_stud_assessment($stud_id, $course, $stud_year, $semester, $scheme) { $array = array('stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_sem' => $semester, 'stud_schm' => $scheme); if ($scheme == 'CSHPYMNT') { $this->db->select('rsrvtn_fee, upon_fee'); $this->db->from('tbl_stud_pybles_csh'); $this->db->where($array); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->row(); } return FALSE; } else if ($scheme == 'INSTLMNT') { // $array = array('stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_sem' => $semester, 'stud_schm' => $scheme); $this->db->select('rsrvtn_fee, upon_fee, prelim_fee, midterm_fee, finals_fee'); $this->db->from('tbl_stud_pybles_inst'); $this->db->where($array); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->row(); } return FALSE; } else if ($scheme == 'MNTHLY') { // $array = array('stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_sem' => $semester, 'stud_schm' => $scheme); $this->db->select('pymnt_for, amount'); $this->db->from('tbl_stud_pybles_mnth'); $this->db->where($array); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->result(); } return FALSE; } } public function update_student_payment($stud_status,$stud_id,$course,$stud_year,$semester,$scheme,$trans_date,$pymnt_for,$amount,$receipt_no,$cashier_id) { $this->db->set('stud_status', $stud_status); $this->db->where('stud_id', $stud_id); if ($this->db->update('tbl_stud_info')) { $data = array ( 'stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_semester' => $semester, 'pymnt_scheme' => $scheme, 'trans_date' => $trans_date, 'trans_name' => $pymnt_for, 'trans_amount' => $amount, 'trans_receipt_no' => $receipt_no, 'cashier_id' => $cashier_id, ); if ($this->db->insert('tbl_transactions', $data)) { return TRUE; } else { return FALSE; } } else { return FALSE; } } public function student_other_payment($stud_id,$course,$stud_year,$semester,$trans_date,$pymnt_for,$amount,$receipt_no,$cashier_id) { $data = array( 'trans_date' => $trans_date, 'stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_sem' => $semester, 'fee_name' => $pymnt_for, 'amount_pd' => $amount, 'receipt_no' => $receipt_no, 'cashier_id' => $cashier_id, ); if ($this->db->insert('tbl_other_payments', $data)) { $data2 = array( 'stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_semester' => $semester, 'pymnt_scheme' => 'Other Payment', 'trans_date' => $trans_date, 'trans_name' => $pymnt_for, 'trans_amount' => $amount, 'trans_receipt_no' => $receipt_no, 'cashier_id' => $cashier_id, ); if ($this->db->insert('tbl_transactions', $data2)) { return TRUE; } else { return FALSE; } } else { return FALSE; } } public function get_other_payments($stud_id) { $this->db->select('*'); $this->db->from('tbl_other_payments'); $this->db->where('stud_id', $stud_id); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->result(); } return FALSE; } public function get_payment_history($stud_id) { $this->db->select('*'); $this->db->from('tbl_transactions'); $this->db->where('stud_id', $stud_id); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->result(); } return FALSE; } public function get_total_payment($stud_id, $course, $stud_year, $semester, $scheme, $pymnt_for) { // $array = array('stud_id' => $stud_id, 'stud_course' => $course, 'stud_year' => $stud_year, 'stud_sem' => $semester, 'stud_schm' => $scheme, 'trans_name' => $pymnt_for); $sql = "SELECT trans_name, SUM(trans_amount) as total_amount FROM tbl_transactions WHERE stud_id = '$stud_id' AND stud_course = '$course' AND stud_year = '$stud_year' AND stud_semester = '$semester' AND pymnt_scheme = '$scheme' AND trans_name = '$pymnt_for'"; $query = $this->db->query($sql); if ($query->num_rows() > 0) { return $query->row(); } return FALSE; } } /* End of file Student_records_model.php */ /* Location: ./application/modules/Cashier/models/Student_Records/Student_records_model.php */
dyunas/Stdnt-Assmnt
application/modules/Cashier/models/Student_Records/Student_records_model.php
PHP
mit
4,725
<?php namespace Main\MainBundle\Entity; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\NoResultException; class UserRepository extends EntityRepository implements UserProviderInterface { public function loadUserByUsername($username) { $q = $this ->createQueryBuilder('u') ->select('u, r') ->leftJoin('u.roles', 'r') ->where("u.username = :username OR u.email = :email") ->setParameter("username", $username) ->setParameter("email", $username) ->getQuery(); try { $user = $q->getSingleResult(); } catch (NoResultException $e) { $message = sprintf('Unable to find an active admin MainMainBundle:User object identified by "%s".', $username); throw new UsernameNotFoundException($message, 0, $e); } return $user; } public function refreshUser(UserInterface $user) { $class = get_class($user); if (!$this->supportsClass($class)) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class)); } return $this->find($user->getId()); } public function supportsClass($class) { return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName()); } }
riki343/main
src/Main/MainBundle/Entity/UserRepository.php
PHP
mit
1,615
// The command line tool for running Revel apps. package main import ( "flag" "fmt" "io" "os" "strings" "text/template" ) // Cribbed from the genius organization of the "go" command. type Command struct { Run func(args []string) UsageLine, Short, Long string } func (cmd *Command) Name() string { name := cmd.UsageLine i := strings.Index(name, " ") if i >= 0 { name = name[:i] } return name } var commands = []*Command{ cmdNew, cmdRun, cmdBuild, cmdPackage, cmdClean, cmdTest, } func main() { fmt.Fprintf(os.Stdout, header) flag.Usage = func() { usage(1) } flag.Parse() args := flag.Args() if len(args) < 1 || args[0] == "help" { if len(args) == 1 { usage(0) } if len(args) > 1 { for _, cmd := range commands { if cmd.Name() == args[1] { tmpl(os.Stdout, helpTemplate, cmd) return } } } usage(2) } if args[0] == "flags" { fmt.Println("Available flags:") flag.PrintDefaults() return } // Commands use panic to abort execution when something goes wrong. // Panics are logged at the point of error. Ignore those. defer func() { if err := recover(); err != nil { if _, ok := err.(LoggedError); !ok { // This panic was not expected / logged. panic(err) } os.Exit(1) } }() for _, cmd := range commands { if cmd.Name() == args[0] { cmd.Run(args[1:]) return } } errorf("unknown command %q\nRun 'revel help' for usage.\n", args[0]) } func errorf(format string, args ...interface{}) { // Ensure the user's command prompt starts on the next line. if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(os.Stderr, format, args...) panic(LoggedError{}) // Panic instead of os.Exit so that deferred will run. } const header = `~ ~ revel! http://robfig.github.com/revel ~ ` const usageTemplate = `usage: revel [flags] command [arguments] The commands are: {{range .}} {{.Name | printf "%-11s"}} {{.Short}}{{end}} Use "revel help [command]" for more information. The flags are: ` var helpTemplate = `usage: revel {{.UsageLine}} {{.Long}} ` func usage(exitCode int) { tmpl(os.Stderr, usageTemplate, commands) flag.PrintDefaults() fmt.Println() os.Exit(exitCode) } func tmpl(w io.Writer, text string, data interface{}) { t := template.New("top") template.Must(t.Parse(text)) if err := t.Execute(w, data); err != nil { panic(err) } }
yext/revel
revel/rev.go
GO
mit
2,397
Rails.application.routes.draw do root 'application#index' # resources :mylist, defaults: { format: :json } resources :mylist, only: [:show, :index, :create], param: :res_id, defaults: { format: :json } resources :mylist, only: [:destroy], param: :res_id # resources :mylist, param: :res_id, defaults: { format: :json } # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
mystycs/My-Favorite-Taco-Joint
config/routes.rb
Ruby
mit
1,900
using com.microsoft.dx.officewopi.Models; using com.microsoft.dx.officewopi.Models.Wopi; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Runtime.Caching; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; namespace com.microsoft.dx.officewopi.Utils { public static class WopiUtil { //WOPI protocol constants public const string WOPI_BASE_PATH = @"/wopi/"; public const string WOPI_CHILDREN_PATH = @"/children"; public const string WOPI_CONTENTS_PATH = @"/contents"; public const string WOPI_FILES_PATH = @"files/"; public const string WOPI_FOLDERS_PATH = @"folders/"; /// <summary> /// Populates a list of files with action details from WOPI discovery /// </summary> public async static Task PopulateActions(this IEnumerable<DetailedFileModel> files) { if (files.Count() > 0) { foreach (var file in files) { await file.PopulateActions(); } } } /// <summary> /// Populates a file with action details from WOPI discovery based on the file extension /// </summary> public async static Task PopulateActions(this DetailedFileModel file) { // Get the discovery informations var actions = await GetDiscoveryInfo(); var fileExt = file.BaseFileName.Substring(file.BaseFileName.LastIndexOf('.') + 1).ToLower(); file.Actions = actions.Where(i => i.ext == fileExt).OrderBy(i => i.isDefault).ToList(); } /// <summary> /// Gets the discovery information from WOPI discovery and caches it appropriately /// </summary> public async static Task<List<WopiAction>> GetDiscoveryInfo() { List<WopiAction> actions = new List<WopiAction>(); // Determine if the discovery data is cached MemoryCache memoryCache = MemoryCache.Default; if (memoryCache.Contains("DiscoData")) actions = (List<WopiAction>)memoryCache["DiscoData"]; else { // Data isn't cached, so we will use the Wopi Discovery endpoint to get the data HttpClient client = new HttpClient(); using (HttpResponseMessage response = await client.GetAsync(ConfigurationManager.AppSettings["WopiDiscovery"])) { if (response.IsSuccessStatusCode) { // Read the xml string from the response string xmlString = await response.Content.ReadAsStringAsync(); // Parse the xml string into Xml var discoXml = XDocument.Parse(xmlString); // Convert the discovery xml into list of WopiApp var xapps = discoXml.Descendants("app"); foreach (var xapp in xapps) { // Parse the actions for the app var xactions = xapp.Descendants("action"); foreach (var xaction in xactions) { actions.Add(new WopiAction() { app = xapp.Attribute("name").Value, favIconUrl = xapp.Attribute("favIconUrl").Value, checkLicense = Convert.ToBoolean(xapp.Attribute("checkLicense").Value), name = xaction.Attribute("name").Value, ext = (xaction.Attribute("ext") != null) ? xaction.Attribute("ext").Value : String.Empty, progid = (xaction.Attribute("progid") != null) ? xaction.Attribute("progid").Value : String.Empty, isDefault = (xaction.Attribute("default") != null) ? true : false, urlsrc = xaction.Attribute("urlsrc").Value, requires = (xaction.Attribute("requires") != null) ? xaction.Attribute("requires").Value : String.Empty }); } // Cache the discovey data for an hour memoryCache.Add("DiscoData", actions, DateTimeOffset.Now.AddHours(1)); } } } } return actions; } /// <summary> /// Forms the correct action url for the file and host /// </summary> public static string GetActionUrl(WopiAction action, FileModel file, string authority) { // Initialize the urlsrc var urlsrc = action.urlsrc; // Look through the action placeholders var phCnt = 0; foreach (var p in WopiUrlPlaceholders.Placeholders) { if (urlsrc.Contains(p)) { // Replace the placeholder value accordingly var ph = WopiUrlPlaceholders.GetPlaceholderValue(p); if (!String.IsNullOrEmpty(ph)) { urlsrc = urlsrc.Replace(p, ph + "&"); phCnt++; } else urlsrc = urlsrc.Replace(p, ph); } } // Add the WOPISrc to the end of the request urlsrc += ((phCnt > 0) ? "" : "?") + String.Format("WOPISrc=https://{0}/wopi/files/{1}", authority, file.id.ToString()); return urlsrc; } /// <summary> /// Validates the WOPI Proof on an incoming WOPI request /// </summary> public async static Task<bool> ValidateWopiProof(HttpContext context) { // Make sure the request has the correct headers if (context.Request.Headers[WopiRequestHeaders.PROOF] == null || context.Request.Headers[WopiRequestHeaders.TIME_STAMP] == null) return false; // Set the requested proof values var requestProof = context.Request.Headers[WopiRequestHeaders.PROOF]; var requestProofOld = String.Empty; if (context.Request.Headers[WopiRequestHeaders.PROOF_OLD] != null) requestProofOld = context.Request.Headers[WopiRequestHeaders.PROOF_OLD]; // Get the WOPI proof info from discovery var discoProof = await getWopiProof(context); // Encode the values into bytes var accessTokenBytes = Encoding.UTF8.GetBytes(context.Request.QueryString["access_token"]); var hostUrl = context.Request.Url.OriginalString.Replace(":44300", "").Replace(":443", ""); var hostUrlBytes = Encoding.UTF8.GetBytes(hostUrl.ToUpperInvariant()); var timeStampBytes = BitConverter.GetBytes(Convert.ToInt64(context.Request.Headers[WopiRequestHeaders.TIME_STAMP])).Reverse().ToArray(); // Build expected proof List<byte> expected = new List<byte>( 4 + accessTokenBytes.Length + 4 + hostUrlBytes.Length + 4 + timeStampBytes.Length); // Add the values to the expected variable expected.AddRange(BitConverter.GetBytes(accessTokenBytes.Length).Reverse().ToArray()); expected.AddRange(accessTokenBytes); expected.AddRange(BitConverter.GetBytes(hostUrlBytes.Length).Reverse().ToArray()); expected.AddRange(hostUrlBytes); expected.AddRange(BitConverter.GetBytes(timeStampBytes.Length).Reverse().ToArray()); expected.AddRange(timeStampBytes); byte[] expectedBytes = expected.ToArray(); return (verifyProof(expectedBytes, requestProof, discoProof.value) || verifyProof(expectedBytes, requestProof, discoProof.oldvalue) || verifyProof(expectedBytes, requestProofOld, discoProof.value)); } /// <summary> /// Verifies the proof against a specified key /// </summary> private static bool verifyProof(byte[] expectedProof, string proofFromRequest, string proofFromDiscovery) { using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider()) { try { rsaProvider.ImportCspBlob(Convert.FromBase64String(proofFromDiscovery)); return rsaProvider.VerifyData(expectedProof, "SHA256", Convert.FromBase64String(proofFromRequest)); } catch (FormatException) { return false; } catch (CryptographicException) { return false; } } } /// <summary> /// Gets the WOPI proof details from the WOPI discovery endpoint and caches it appropriately /// </summary> internal async static Task<WopiProof> getWopiProof(HttpContext context) { WopiProof wopiProof = null; // Check cache for this data MemoryCache memoryCache = MemoryCache.Default; if (memoryCache.Contains("WopiProof")) wopiProof = (WopiProof)memoryCache["WopiProof"]; else { HttpClient client = new HttpClient(); using (HttpResponseMessage response = await client.GetAsync(ConfigurationManager.AppSettings["WopiDiscovery"])) { if (response.IsSuccessStatusCode) { // Read the xml string from the response string xmlString = await response.Content.ReadAsStringAsync(); // Parse the xml string into Xml var discoXml = XDocument.Parse(xmlString); // Convert the discovery xml into list of WopiApp var proof = discoXml.Descendants("proof-key").FirstOrDefault(); wopiProof = new WopiProof() { value = proof.Attribute("value").Value, modulus = proof.Attribute("modulus").Value, exponent = proof.Attribute("exponent").Value, oldvalue = proof.Attribute("oldvalue").Value, oldmodulus = proof.Attribute("oldmodulus").Value, oldexponent = proof.Attribute("oldexponent").Value }; // Add to cache for 20min memoryCache.Add("WopiProof", wopiProof, DateTimeOffset.Now.AddMinutes(20)); } } } return wopiProof; } } /// <summary> /// Contains valid WOPI response headers /// </summary> public class WopiResponseHeaders { //WOPI Header Consts public const string HOST_ENDPOINT = "X-WOPI-HostEndpoint"; public const string INVALID_FILE_NAME_ERROR = "X-WOPI-InvalidFileNameError"; public const string LOCK = "X-WOPI-Lock"; public const string LOCK_FAILURE_REASON = "X-WOPI-LockFailureReason"; public const string LOCKED_BY_OTHER_INTERFACE = "X-WOPI-LockedByOtherInterface"; public const string MACHINE_NAME = "X-WOPI-MachineName"; public const string PREF_TRACE = "X-WOPI-PerfTrace"; public const string SERVER_ERROR = "X-WOPI-ServerError"; public const string SERVER_VERSION = "X-WOPI-ServerVersion"; public const string VALID_RELATIVE_TARGET = "X-WOPI-ValidRelativeTarget"; } /// <summary> /// Contains valid WOPI request headers /// </summary> public class WopiRequestHeaders { //WOPI Header Consts public const string APP_ENDPOINT = "X-WOPI-AppEndpoint"; public const string CLIENT_VERSION = "X-WOPI-ClientVersion"; public const string CORRELATION_ID = "X-WOPI-CorrelationId"; public const string LOCK = "X-WOPI-Lock"; public const string MACHINE_NAME = "X-WOPI-MachineName"; public const string MAX_EXPECTED_SIZE = "X-WOPI-MaxExpectedSize"; public const string OLD_LOCK = "X-WOPI-OldLock"; public const string OVERRIDE = "X-WOPI-Override"; public const string OVERWRITE_RELATIVE_TARGET = "X-WOPI-OverwriteRelativeTarget"; public const string PREF_TRACE_REQUESTED = "X-WOPI-PerfTraceRequested"; public const string PROOF = "X-WOPI-Proof"; public const string PROOF_OLD = "X-WOPI-ProofOld"; public const string RELATIVE_TARGET = "X-WOPI-RelativeTarget"; public const string REQUESTED_NAME = "X-WOPI-RequestedName"; public const string SESSION_CONTEXT = "X-WOPI-SessionContext"; public const string SIZE = "X-WOPI-Size"; public const string SUGGESTED_TARGET = "X-WOPI-SuggestedTarget"; public const string TIME_STAMP = "X-WOPI-TimeStamp"; } /// <summary> /// Contains all valid URL placeholders for different WOPI actions /// </summary> public class WopiUrlPlaceholders { public static List<string> Placeholders = new List<string>() { BUSINESS_USER, DC_LLCC, DISABLE_ASYNC, DISABLE_CHAT, DISABLE_BROADCAST, EMBDDED, FULLSCREEN, PERFSTATS, RECORDING, THEME_ID, UI_LLCC, VALIDATOR_TEST_CATEGORY }; public const string BUSINESS_USER = "<IsLicensedUser=BUSINESS_USER&>"; public const string DC_LLCC = "<rs=DC_LLCC&>"; public const string DISABLE_ASYNC = "<na=DISABLE_ASYNC&>"; public const string DISABLE_CHAT = "<dchat=DISABLE_CHAT&>"; public const string DISABLE_BROADCAST = "<vp=DISABLE_BROADCAST&>"; public const string EMBDDED = "<e=EMBEDDED&>"; public const string FULLSCREEN = "<fs=FULLSCREEN&>"; public const string PERFSTATS = "<showpagestats=PERFSTATS&>"; public const string RECORDING = "<rec=RECORDING&>"; public const string THEME_ID = "<thm=THEME_ID&>"; public const string UI_LLCC = "<ui=UI_LLCC&>"; public const string VALIDATOR_TEST_CATEGORY = "<testcategory=VALIDATOR_TEST_CATEGORY>"; /// <summary> /// Sets a specific WOPI URL placeholder with the correct value /// Most of these are hard-coded in this WOPI implementation /// </summary> public static string GetPlaceholderValue(string placeholder) { var ph = placeholder.Substring(1, placeholder.IndexOf("=")); string result = ""; switch (placeholder) { case BUSINESS_USER: result = ph + "1"; break; case DC_LLCC: case UI_LLCC: result = ph + "1033"; break; case DISABLE_ASYNC: case DISABLE_BROADCAST: case EMBDDED: case FULLSCREEN: case RECORDING: case THEME_ID: // These are all broadcast related actions result = ph + "true"; break; case DISABLE_CHAT: result = ph + "false"; break; case PERFSTATS: result = ""; // No documentation break; case VALIDATOR_TEST_CATEGORY: result = ph + "OfficeOnline"; //This value can be set to All, OfficeOnline or OfficeNativeClient to activate tests specific to Office Online and Office for iOS. If omitted, the default value is All. break; default: result = ""; break; } return result; } } }
OfficeDev/PnP-WOPI
com.microsoft.dx.officewopi/Utils/WopiUtil.cs
C#
mit
16,313
window.NavigationStore = function() { function isSet(menu) { return localStorage["navigation_" + menu] !== undefined; } function fetch(menu) { return localStorage["navigation_" + menu] == "true" || false; } function set(menu, value) { localStorage["navigation_" + menu] = value; } return { isSet: isSet, fetch: fetch, set: set } }();
appsignal/appsignal-docs
source/assets/javascripts/navigation_store.js
JavaScript
mit
377
<?php class Productos_model extends CI_Model{ function __construct() { parent::__construct(); $this->load->database(); } function get_destacados($por_pagina,$segmento) { $consulta = $this->db->query("SELECT * FROM Producto WHERE Destacado=1 LIMIT $segmento, $por_pagina"); $data=array(); foreach($consulta->result() as $fila) { $data[] = $fila; } return $data; } function get_prod_id($id) { $consulta = $this->db->query("SELECT * FROM Producto WHERE idProducto='$id'"); return $consulta->row(); } function get_prod_categoria($prod_categoria, $por_pagina,$segmento) { $producto = $this->db->query("SELECT * FROM Producto WHERE Categoria='$prod_categoria' LIMIT $segmento, $por_pagina"); return $producto->result(); } function get_categorias() { $categoria = $this->db->query("SELECT * FROM Categoria"); return $categoria->result(); } //obtenemos el total de filas para hacer la paginación function filas() { $consulta = $this->db->query("SELECT * FROM Producto WHERE Destacado=1"); return $consulta->num_rows() ; } //obtenemos el total de filas para hacer la paginación function filas_categoria($categoria) { $consulta = $this->db->query("SELECT * FROM Producto WHERE Categoria=$categoria"); return $consulta->num_rows() ; } /** * Comprobar si hay disponibilidad de las unidades del producto solicitado * @param type $id: id del producto * @param type $und: unidades solicitadas * @return boolean */ function check_stock($id) { $consulta = $this->db->query("SELECT * FROM Producto WHERE idProducto=$id"); return $consulta->row()->Stock; } function AddPedido($data) { $this->db->insert('Pedido', $data); } function UltimoPedido() { $consulta=$this->db->query("SELECT MAX(idPedido) as id FROM Pedido"); return $consulta->row()->id; } function AddLinea($data) { $this->db->insert('LineaPedido', $data); } function GetLineas($idPedido) { $consulta=$this->db->query("SELECT * FROM LineaPedido WHERE Pedido_idPedido=$idPedido"); return $consulta->result(); } function GetPedido($idPedido) { $consulta=$this->db->query("SELECT * FROM Pedido WHERE idPedido=$idPedido"); return $consulta->row(); } public function estado_pedido($n) { switch($n) { case 1: return "Pendiente de envío"; break; case 2: return "Enviado"; break; case 3: return "Entregado"; break; } } public function DeletePedido($idPedido) { $this->db->delete('LineaPedido', array('Pedido_idPedido'=>$idPedido)); $this->db->delete('Pedido', array('idPedido' => $idPedido)); } public function SetProducto($id,$data) { $this->db->where('idProducto', $id); $this->db->update('Producto', $data); } public function Productos_Agregador($por_pagina,$segmento) { $resultados=$this->get_destacados($por_pagina, $segmento); $dest=array(); foreach($resultados as $resultado) { $dest[]=array( 'nombre'=>$resultado->Nombre, 'descripcion'=>$resultado->Descripcion, 'precio'=>$resultado->PrecioVenta, 'img'=>base_url().$resultado->Imagen, 'url'=>site_url('compras/agregar/'.$resultado->idProducto) ); } return $dest; } } ?>
dfergar/PHP_practica2
application/models/Productos_model.php
PHP
mit
3,985
import { describe, it, beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import startApp from 'my-app/tests/helpers/start-app'; import { run } from '@ember/runloop'; describe('Acceptance | foo', function () { let application; beforeEach(function () { application = startApp(); }); afterEach(function () { run(application, 'destroy'); }); it('can visit /foo', function () { visit('/foo'); return andThen(() => { expect(currentURL()).to.equal('/foo'); }); }); });
emberjs/ember.js
node-tests/fixtures/acceptance-test/mocha.js
JavaScript
mit
526
<?php namespace ShopBundle\Entity; use Doctrine\ORM\EntityRepository; /** * CustomerRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class CustomerRepository extends EntityRepository { }
GitHubTai/MijnPizza
src/ShopBundle/Entity/CustomerRepository.php
PHP
mit
258
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Red_Folder.com.Models.Activity { public class PluralsightActivity: IActivity { [JsonProperty("courses")] public List<Course> Courses; } }
Red-Folder/red-folder.com
src/Red-Folder.com/Models/Activity/PluralsightActivity.cs
C#
mit
300
#include "3d/Base.h" #include "3d/C3DEffect.h" #include "3d/C3DElementNode.h" #include "3d/C3DEffectManager.h" #include "3d/C3DElementNode.h" namespace cocos3d { static C3DEffectManager* __effectManagerInstance = NULL; C3DEffectManager::C3DEffectManager() { } C3DEffectManager::~C3DEffectManager() { __effectManagerInstance = NULL; } C3DEffectManager* C3DEffectManager::getInstance() { if (!__effectManagerInstance) { __effectManagerInstance = new C3DEffectManager(); __effectManagerInstance->autorelease(); } return __effectManagerInstance; } void C3DEffectManager::preload(const std::string& fileName) { if(fileName.c_str() != NULL) { C3DElementNode* doc = C3DElementNode::create(fileName.c_str()); if (!doc) { LOG_ERROR_VARG("Error loading effect: Could not load file: %s", fileName.c_str()); return; } loadAllEffect((strlen(doc->getNodeType()) > 0) ? doc : doc->getNextChild()); SAFE_DELETE(doc); } } void C3DEffectManager::loadAllEffect(C3DElementNode* effectNodes) { if( effectNodes != NULL ) { if (strcmp(effectNodes->getNodeType(), "Effects") != 0) { LOG_ERROR("Error proLoading Effects: No 'Effects' namespace found"); return; } else { effectNodes->rewind(); C3DElementNode* effectNode = NULL; while ((effectNode = effectNodes->getNextChild())) { if (strcmp(effectNode->getNodeType(), "Effect") == 0) { const char* vspath = effectNode->getElement("vertexShader"); assert(vspath); const char* fspath = effectNode->getElement("fragmentShader"); assert(fspath); std::vector<std::string> flags; flags.push_back(""); C3DElementNode* flagsNode = effectNode->getNextChild(); if (flagsNode != NULL && strcmp(flagsNode->getNodeType(), "flags") == 0) { flagsNode->rewind(); const char* defines = NULL; const char* value = NULL; while (defines = flagsNode->getNextElement()) { value = flagsNode->getElement(); std::string flag; if (defines != NULL) { flag = value; flag.insert(0, "#define "); unsigned int pos; while ((pos = flag.find(';')) != std::string::npos) { flag.replace(pos, 1, "\n#define "); } flag += "\n"; } flags.push_back(flag); } } C3DElementNode* elementNode = C3DElementNode::createEmptyNode("test", "effect"); elementNode->setElement("vertexShader", (vspath == NULL) ? "" : vspath); elementNode->setElement("fragmentShader", (fspath == NULL) ? "" : fspath); const char* define; for(std::vector<std::string>::iterator iter = flags.begin();iter!=flags.end();++iter) { define = (*iter).c_str(); if(define != NULL) elementNode->setElement("defines", define); preload(elementNode); } SAFE_DELETE(elementNode); } } } } } C3DResource* C3DEffectManager::createResource(const std::string& name,C3DElementNode* node) { C3DResource* effect = new C3DEffect(name); effect->autorelease(); if(effect->load(node) == true) { this->setResourceState(effect,C3DResource::State_Used); } effect->retain(); return effect; } std::string C3DEffectManager::generateID( std::string& vshPath, std::string& fshPath, std::string& defines,C3DElementNode* outNode ) { assert(vshPath.c_str()); assert(fshPath.c_str()); std::string define; if (defines.size() != 0) { define = defines; define.insert(0, "#define "); unsigned int pos; while ((pos = define.find(';')) != std::string::npos) { define.replace(pos, 1, "\n#define "); } define += "\n"; } std::string uniqueId = vshPath; uniqueId += ';'; uniqueId += fshPath; uniqueId += ';'; if (define.c_str() != 0) { uniqueId += define; } if(outNode != NULL) { outNode->setElement("vertexShader", vshPath.c_str()); outNode->setElement("fragmentShader", fshPath.c_str()); if(define.c_str() != NULL) outNode->setElement("defines", define.c_str()); } return uniqueId; } C3DResource* C3DEffectManager::getResource(const std::string& name) { C3DResource* effect = this->findResource(name); if(effect != NULL) { effect->retain(); this->setResourceState(effect,C3DResource::State_Used); return effect; } return NULL; } void C3DEffectManager::preload(C3DElementNode* node) { const char* vshPath = node->getElement("vertexShader"); const char* fshPath = node->getElement("fragmentShader"); const char* defines = node->getElement("defines"); std::string uniqueId = vshPath; uniqueId += ';'; uniqueId += fshPath; uniqueId += ';'; if (defines != 0) { uniqueId += defines; } C3DResource* effect = this->findResource(uniqueId); if(effect != NULL) return; else { C3DEffect* effect = new C3DEffect(uniqueId); effect->autorelease(); if(effect->load(node) == true) { this->setResourceState(effect,C3DResource::State_Used); } } } }
mcodegeeks/OpenKODE-Framework
01_Develop/libXMCocos2D-v3/Source/3d/C3DEffectManager.cpp
C++
mit
5,124
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACCOUNT_SID" auth_token = "your_auth_token" client = Client(account_sid, auth_token) number = client.lookups.phone_numbers("+16502530000").fetch( type="caller-name", ) print(number.carrier['type']) print(number.carrier['name'])
teoreteetik/api-snippets
lookups/lookup-get-cname-example-1/lookup-get-cname-example-1.6.x.py
Python
mit
417
class CreateLaDepartmentWatcherEvents < ActiveRecord::Migration def change create_table :la_department_watcher_events do |t| t.string :type t.datetime :start_at t.datetime :end_at t.text :text_description t.datetime :notify_sent_at t.string :notify_sent_to t.text :agents_statuses_json t.timestamps end end end
luigi-sk/la-department-watcher
db/migrate/20140205165029_create_la_department_watcher_events.rb
Ruby
mit
372
# encoding: utf-8 module Humanoid #:nodoc: module Criterion #:nodoc: module Inclusion # Adds a criterion to the +Criteria+ that specifies values that must all # be matched in order to return results. Similar to an "in" clause but the # underlying conditional logic is an "AND" and not an "OR". The MongoDB # conditional operator that will be used is "$all". # # Options: # # attributes: A +Hash+ where the key is the field name and the value is an # +Array+ of values that must all match. # # Example: # # <tt>criteria.all(:field => ["value1", "value2"])</tt> # # <tt>criteria.all(:field1 => ["value1", "value2"], :field2 => ["value1"])</tt> # # Returns: <tt>self</tt> def all(attributes = {}) update_selector(attributes, "$all") end # Adds a criterion to the +Criteria+ that specifies values that must # be matched in order to return results. This is similar to a SQL "WHERE" # clause. This is the actual selector that will be provided to MongoDB, # similar to the Javascript object that is used when performing a find() # in the MongoDB console. # # Options: # # selectior: A +Hash+ that must match the attributes of the +Document+. # # Example: # # <tt>criteria.and(:field1 => "value1", :field2 => 15)</tt> # # Returns: <tt>self</tt> def and(selector = nil) where(selector) end # Adds a criterion to the +Criteria+ that specifies values where any can # be matched in order to return results. This is similar to an SQL "IN" # clause. The MongoDB conditional operator that will be used is "$in". # # Options: # # attributes: A +Hash+ where the key is the field name and the value is an # +Array+ of values that any can match. # # Example: # # <tt>criteria.in(:field => ["value1", "value2"])</tt> # # <tt>criteria.in(:field1 => ["value1", "value2"], :field2 => ["value1"])</tt> # # Returns: <tt>self</tt> def in(attributes = {}) update_selector(attributes, "$in") end # Adds a criterion to the +Criteria+ that specifies values that must # be matched in order to return results. This is similar to a SQL "WHERE" # clause. This is the actual selector that will be provided to MongoDB, # similar to the Javascript object that is used when performing a find() # in the MongoDB console. # # Options: # # selectior: A +Hash+ that must match the attributes of the +Document+. # # Example: # # <tt>criteria.where(:field1 => "value1", :field2 => 15)</tt> # # Returns: <tt>self</tt> def where(selector = nil) case selector when String @selector.update("$where" => selector) else @selector.update(selector ? selector.expand_complex_criteria : {}) end self end end end end
delano/humanoid
lib/humanoid/criterion/inclusion.rb
Ruby
mit
3,086
import {IFilesystem} from './Filesystem'; export type Node = Directory | string; export type Directory = {[name: string]: Node}; export class MockFilesystem implements IFilesystem { files: Directory = {}; constructor(files?: Directory) { this.files = files || {}; } private get(path: string, create?: boolean): [Directory | undefined, string] { if (!path.startsWith('/')) throw new Error(`Path not absolute: '${path}'`); let ret: string[] | undefined; let node: Node = this.files; const names = path.substr(1).split('/'); for (let i = 0; i < names.length - 1; i ++) { let nextNode: Node | string; if (names[i] in node) { nextNode = node[names[i]]; if (typeof nextNode == 'string') return [undefined, '']; } else if (create) { nextNode = node[names[i]] = {} as Directory; } else { return [undefined, '']; } node = nextNode; } return [node, names[names.length-1]]; } private getNode(path: string) { let [dir, name] = this.get(path); if (typeof dir == 'undefined' || !(name in dir)) return undefined; return dir[name]; } listFolders(path: string) { let node = this.getNode(path); if (typeof node == 'undefined' || typeof node == 'string') return Promise.resolve(undefined); const ret: string[] = []; for (let name in node) { if (typeof node[name] != 'string') ret.push(name); } return Promise.resolve(ret); } // exists(path: string) { // const node = this.getNode(path); // return Promise.resolve(typeof node != 'undefined'); // } read(path: string) { const node = this.getNode(path); if (typeof node == 'string') return Promise.resolve(node); if (typeof node == 'undefined') return Promise.resolve(undefined); return Promise.reject(new Error('cannot read folder')); } write(path: string, data: string) { const [dir, name] = this.get(path, true); if (typeof dir == 'undefined') return Promise.reject(new Error('cannot make parents')); dir[name] = data; return Promise.resolve(); } moveFolder(oldPath: string, newPath: string) { const [oldDir, oldName] = this.get(oldPath); if (typeof oldDir == 'undefined' || !(oldName in oldDir)) return Promise.reject(new Error('no such node')); const [newDir, newName] = this.get(newPath, true); if (typeof newDir == 'undefined') return Promise.reject(new Error('cannot make parents')); if (newName in newDir) return Promise.reject(new Error('target already exists')); newDir[newName] = oldDir[oldName]; delete oldDir[oldName]; return Promise.resolve(); } delete(path: string) { const [dir, name] = this.get(path); if (typeof dir == 'undefined' || !(name in dir)) return Promise.reject(new Error('no such node')); delete dir[name]; return Promise.resolve(); } }
sbj42/roze
src/db/MockFilesystem.test.ts
TypeScript
mit
3,297
#include <progress_bar.hh> PROGRESS_BAR :: PROGRESS_BAR(int x, int y, int w, int h, void(*opf)(void), void(*orf)(void), int ea, int ia, int l) : WIDGET(x,y,w,h,opf,orf) { this->ext_angle = ea; this->int_angle = ia; this->level = l; }
oktail/borealos
libs/lib_ihm/src/progress_bar.cpp
C++
mit
247
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * This module provides a set of common Pipes. */ import {AsyncPipe} from './async_pipe'; import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from './case_conversion_pipes'; import {DatePipe} from './date_pipe'; import {I18nPluralPipe} from './i18n_plural_pipe'; import {I18nSelectPipe} from './i18n_select_pipe'; import {JsonPipe} from './json_pipe'; import {KeyValue, KeyValuePipe} from './keyvalue_pipe'; import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe'; import {SlicePipe} from './slice_pipe'; export { AsyncPipe, CurrencyPipe, DatePipe, DecimalPipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValue, KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe, }; /** * A collection of Angular pipes that are likely to be used in each and every application. */ export const COMMON_PIPES = [ AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe, ];
matsko/angular
packages/common/src/pipes/index.ts
TypeScript
mit
1,312
package net.crowmagnumb.database; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; public class SqlColumn implements SqlComponent { private final String _name; private final SqlColumnType _type; private SqlTable _table; private final String _alias; private String _properName; private String _constraints; // // Used for char and varchars // private Integer _charMaxLength; private String _prefix = null; private String _suffix = null; public SqlColumn(final SqlTable table, final String name) { this(table, name, SqlColumnType.OTHER, null); } public SqlColumn(final SqlTable table, final String name, final String alias) { this(table, name, SqlColumnType.OTHER, alias); } public SqlColumn(final String name, final SqlColumnType type) { this(null, name, type, null); } public SqlColumn(final SqlTable table, final String name, final SqlColumnType type) { this(table, name, type, null); } public SqlColumn(final SqlTable table, final String name, final String properName, final SqlColumnType type) { this(table, name, type, null); _properName = properName; } public SqlColumn(final SqlTable table, final String name, final SqlColumnType type, final String alias) { _table = table; _name = name; _type = type; _alias = alias; } public SqlTable getTable() { return _table; } public void setTable( final SqlTable table) { _table = table; } public String getName() { return _name; } public SqlColumnType getType() { return _type; } public String getProperName() { if (_properName == null) { return _name; } return _properName; } public void setCharMaxLength(final Integer charMaxLength) { _charMaxLength = charMaxLength; } public Integer getCharMaxLength() { return _charMaxLength; } public void setConstraints(final String constraints) { _constraints = constraints; } public String getConstraints() { return _constraints; } /** * The prefix and suffix are simply mechanisms to cheat * in case you have an usual column (like a function * call that you need to shoehorn into this structure. * When the column is formatted for output the prefix * and suffix are tacked on. * * @param prefix value */ public void setPrefix(final String prefix) { _prefix = prefix; } public String getPrefix() { return _prefix; } public void setSuffix(final String suffix) { _suffix = suffix; } public String formatValue(final String value) { if (_type == SqlColumnType.TEXT) { // // TODO: Fix this so that we can search on question marks if need be. // To fix a problem I had trying to use this to make parameterized queries I // check for a question mark and if so do not wrap quotes. I guess we // need to pass in that it is a parameterized query in which case we don't // even specify the value. // if (value == "?") { return "?"; } return DbUtils.wrapQuotes(value); } return value; } public String getSqlReference() { String value; if (! StringUtils.isBlank(_alias)) { value = _alias; } else { value = getStandardSqlReference(); } if (_prefix != null) { value = _prefix + value; } if (_suffix != null) { value += _suffix; } return value; } private String getStandardSqlReference() { if (_table == null) { return _name; } return DbUtils.buildDbRef(_table.getSqlReference(), _name); } @Override public void appendToSqlBuffer(final StringBuilder buffer) { buffer.append(getStandardSqlReference()); if (! StringUtils.isBlank(_alias)) { buffer.append(" AS ").append(_alias); } } //======================================== // // Standard common methods // //======================================== @Override public String toString() { return new ToStringBuilder(this).append("table", _table) .append("name", _name) .append("alias", _alias) .append("type", _type) .append("charMaxLength", _charMaxLength) .toString(); } }
SamSix/s6-db
src/main/java/net/crowmagnumb/database/SqlColumn.java
Java
mit
4,933
 namespace VocaDb.Model.Domain.Tags { public interface ITagUsageFactory<T> where T : TagUsage { T CreateTagUsage(Tag tag); } }
cazzar/VocaDbTagger
VocaDbModel/Domain/Tags/ITagUsageFactory.cs
C#
mit
137
import json f = open('text-stripped-3.json') out = open('text-lines.json', 'w') start_obj = json.load(f) end_obj = {'data': []} characters_on_stage = [] currently_speaking = None last_scene = '1.1' for i in range(len(start_obj['data'])): obj = start_obj['data'][i] if obj['type'] == 'entrance': if obj['characters'] in characters_on_stage: raise Exception('Character tried to enter stage when already on stage at object ' + str(i)) characters_on_stage = characters_on_stage + obj['characters'] elif obj['type'] == 'exeunt': characters_on_stage = [] elif obj['type'] == 'exit': characters_on_stage = [char for char in characters_on_stage if char not in obj['characters']] elif obj['type'] == 'speaker tag': if obj['speaker'] not in characters_on_stage: raise Exception('Character tried to speak when not on stage at object ' + str(i), start_obj['data'][i + 1]) currently_speaking = obj['speaker'] elif obj['type'] == 'line': if currently_speaking == None: raise Exception('A line did not have an associated speaker at object ' + str(i)) identifier_info = obj['identifier'].split('.') scene = identifier_info[0] + '.' + identifier_info[1] #if scene != last_scene: # if len(characters_on_stage) != 0: # print('Warning: scene ' + scene + ' just started with ' + str(characters_on_stage) + ' still on stage') last_scene = scene end_obj['data'].append({ 'type': 'line', 'identifier': obj['identifier'], 'text': obj['text'].strip(), 'speaker': currently_speaking, 'characters': characters_on_stage }) if len(characters_on_stage) == 0: currently_speaking = None json.dump(end_obj, out)
SyntaxBlitz/syntaxblitz.github.io
mining-lear/process/step6.py
Python
mit
1,654
import removeClass from 'tui-code-snippet/domUtil/removeClass'; import addClass from 'tui-code-snippet/domUtil/addClass'; import { HookCallback } from '@t/editor'; import { Emitter } from '@t/event'; import { ExecCommand, HidePopup, TabInfo } from '@t/ui'; import i18n from '@/i18n/i18n'; import { cls } from '@/utils/dom'; import { Component } from '@/ui/vdom/component'; import html from '@/ui/vdom/template'; import { Tabs } from '../tabs'; const TYPE_UI = 'ui'; type TabType = 'url' | 'file'; interface Props { show: boolean; eventEmitter: Emitter; execCommand: ExecCommand; hidePopup: HidePopup; } interface State { activeTab: TabType; file: File | null; fileNameElClassName: string; } export class ImagePopupBody extends Component<Props, State> { private tabs: TabInfo[]; constructor(props: Props) { super(props); this.state = { activeTab: 'file', file: null, fileNameElClassName: '' }; this.tabs = [ { name: 'file', text: 'File' }, { name: 'url', text: 'URL' }, ]; } private initialize = (activeTab: TabType = 'file') => { const urlEl = this.refs.url as HTMLInputElement; urlEl.value = ''; (this.refs.altText as HTMLInputElement).value = ''; (this.refs.file as HTMLInputElement).value = ''; removeClass(urlEl, 'wrong'); this.setState({ activeTab, file: null, fileNameElClassName: '' }); }; private emitAddImageBlob() { const { files } = this.refs.file as HTMLInputElement; const altTextEl = this.refs.altText as HTMLInputElement; let fileNameElClassName = ' wrong'; if (files?.length) { fileNameElClassName = ''; const imageFile = files.item(0)!; const hookCallback: HookCallback = (url, text) => this.props.execCommand('addImage', { imageUrl: url, altText: text || altTextEl.value }); this.props.eventEmitter.emit('addImageBlobHook', imageFile, hookCallback, TYPE_UI); } this.setState({ fileNameElClassName }); } private emitAddImage() { const imageUrlEl = this.refs.url as HTMLInputElement; const altTextEl = this.refs.altText as HTMLInputElement; const imageUrl = imageUrlEl.value; const altText = altTextEl.value || 'image'; removeClass(imageUrlEl, 'wrong'); if (!imageUrl.length) { addClass(imageUrlEl, 'wrong'); return; } if (imageUrl) { this.props.execCommand('addImage', { imageUrl, altText }); } } private execCommand = () => { if (this.state.activeTab === 'file') { this.emitAddImageBlob(); } else { this.emitAddImage(); } }; private toggleTab = (_: MouseEvent, activeTab: TabType) => { if (activeTab !== this.state.activeTab) { this.initialize(activeTab); } }; private showFileSelectBox = () => { this.refs.file.click(); }; private changeFile = (ev: Event) => { const { files } = ev.target as HTMLInputElement; if (files?.length) { this.setState({ file: files[0] }); } }; private preventSelectStart(ev: Event) { ev.preventDefault(); } updated() { if (!this.props.show) { this.initialize(); } } render() { const { activeTab, file, fileNameElClassName } = this.state; return html` <div aria-label="${i18n.get('Insert image')}"> <${Tabs} tabs=${this.tabs} activeTab=${activeTab} onClick=${this.toggleTab} /> <div style="display:${activeTab === 'url' ? 'block' : 'none'}"> <label for="toastuiImageUrlInput">${i18n.get('Image URL')}</label> <input id="toastuiImageUrlInput" type="text" ref=${(el: HTMLInputElement) => (this.refs.url = el)} /> </div> <div style="display:${activeTab === 'file' ? 'block' : 'none'};position: relative;"> <label for="toastuiImageFileInput">${i18n.get('Select image file')}</label> <span class="${cls('file-name')}${file ? ' has-file' : fileNameElClassName}" onClick=${this.showFileSelectBox} onSelectstart=${this.preventSelectStart} > ${file ? file.name : i18n.get('No file')} </span> <button type="button" class="${cls('file-select-button')}" onClick=${this.showFileSelectBox} > ${i18n.get('Choose a file')} </button> <input id="toastuiImageFileInput" type="file" accept="image/*" onChange=${this.changeFile} ref=${(el: HTMLInputElement) => (this.refs.file = el)} /> </div> <label for="toastuiAltTextInput">${i18n.get('Description')}</label> <input id="toastuiAltTextInput" type="text" ref=${(el: HTMLInputElement) => (this.refs.altText = el)} /> <div class="${cls('button-container')}"> <button type="button" class="${cls('close-button')}" onClick=${this.props.hidePopup}> ${i18n.get('Cancel')} </button> <button type="button" class="${cls('ok-button')}" onClick=${this.execCommand}> ${i18n.get('OK')} </button> </div> </div> `; } }
nhnent/tui.editor
apps/editor/src/ui/components/toolbar/imagePopupBody.ts
TypeScript
mit
5,214
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("p04.UnunionLists")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("p04.UnunionLists")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1bbfd535-aace-42c7-a5b7-efdfebc10e87")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
stefankon/CShomeworkAndLabIssues
CSharp-List-More-Exercises/p04.UnunionLists/Properties/AssemblyInfo.cs
C#
mit
1,403
let mongoose = require('mongoose') let userSchema = mongoose.Schema({ // userModel properties here... local: { email: { type: String, required: true }, password: { type: String, required: true } }, facebook: { id: String, token: String, email: String, name: String } }) userSchema.methods.generateHash = async function(password) { return await bcrypt.promise.hash(password, 8) } userSchema.methods.validatePassword = async function(password) { return await bcrypt.promise.compare(password, this.password) } userSchema.methods.linkAccount = function(type, values) { // linkAccount('facebook', ...) => linkFacebookAccount(values) return this['link' + _.capitalize(type) + 'Account'](values) } userSchema.methods.linkLocalAccount = function({ email, password }) { throw new Error('Not Implemented.') } userSchema.methods.linkFacebookAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkTwitterAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkGoogleAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkLinkedinAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.unlinkAccount = function(type) { throw new Error('Not Implemented.') } module.exports = mongoose.model('User', userSchema)
linghuaj/node-social-auth
app/models/user.js
JavaScript
mit
1,581
using DragonSpark.Sources.Parameterized; using System; namespace DragonSpark.Aspects.Specifications { sealed class SpecificationConstructor : AdapterConstructorSource<ISpecification> { public static IParameterizedSource<Type, Func<object, ISpecification>> Default { get; } = new SpecificationConstructor().ToCache(); SpecificationConstructor() : base( GenericSpecificationTypeDefinition.Default.DeclaringType, typeof(SpecificationAdapter<>) ) {} } }
DevelopersWin/VoteReporter
Framework/DragonSpark/Aspects/Specifications/SpecificationConstructor.cs
C#
mit
460
// File auto generated by STUHashTool using static STULib.Types.Generic.Common; namespace STULib.Types.Dump { [STU(0xF92E0197)] public class STU_F92E0197 : STUInstance { [STUField(0xDAE04657)] public float m_DAE04657; [STUField(0x96960C7F)] public float m_96960C7F; [STUField(0xA3659A33)] public float m_A3659A33; [STUField(0x131257CD)] public float m_131257CD; } }
kerzyte/OWLib
STULib/Types/Dump/STU_F92E0197.cs
C#
mit
446
package com.sunnyface.popularmovies; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.util.Pair; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.sunnyface.popularmovies.databinding.ActivityMainBinding; import com.sunnyface.popularmovies.libs.Constants; import com.sunnyface.popularmovies.models.Movie; /** * Root Activity. * Loads */ public class MainActivity extends AppCompatActivity implements MainActivityFragment.Callback { private boolean isTableLayout; private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); Toolbar toolbar = binding.actionBar.toolbar; setSupportActionBar(toolbar); fragmentManager = getSupportFragmentManager(); isTableLayout = binding.movieDetailContainer != null; } @Override public void onItemSelected(Movie movie, View view) { if (isTableLayout) { Bundle args = new Bundle(); args.putBoolean("isTabletLayout", true); args.putParcelable("movie", movie); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.movie_detail_container, fragment, Constants.MOVIE_DETAIL_FRAGMENT_TAG); //Replace its key. fragmentTransaction.commit(); } else { Intent intent = new Intent(this, DetailActivity.class); intent.putExtra("movie", movie); String movieID = "" + movie.getId(); Log.i("movieID: ", movieID); // Doing some view transitions with style, // But, we must check if we're running on Android 5.0 or higher to work. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //KK Bind this to remove findViewByID?????? ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail); TextView titleTextView = (TextView) view.findViewById(R.id.title); Pair<View, String> transition_a = Pair.create((View) thumbnailImageView, "movie_cover"); Pair<View, String> transition_b = Pair.create((View) titleTextView, "movie_title"); ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, transition_a, transition_b); startActivity(intent, options.toBundle()); } else { startActivity(intent); } } } }
kikoseijo/AndroidPopularMovies
app/src/main/java/com/sunnyface/popularmovies/MainActivity.java
Java
mit
3,149
Photos = new orion.collection('photos', { singularName: 'photo', pluralName: 'photos', link: { title: 'Photos' }, tabular: { columns: [ {data: 'title', title: 'Title'}, {data: 'state', title: 'State'}, //ToDo: Thumbnail orion.attributeColumn('markdown', 'body', 'Content'), orion.attributeColumn('createdAt', 'createdAt', 'Created At'), orion.attributeColumn('createdBy', 'createdBy', 'Created By') ] } }); Photos.attachSchema(new SimpleSchema({ title: {type: String}, state: { type: String, allowedValues: [ "draft", "published", "archived" ], label: "State" }, userId: orion.attribute('hasOne', { type: String, label: 'Author', optional: false }, { collection: Meteor.users, // the key whose value you want to show for each Post document on the Update form titleField: 'profile.name', publicationName: 'PB_Photos_Author', }), image: orion.attribute('image', { optional: true, label: 'Image' }), body: orion.attribute('markdown', { label: 'Body' }), createdBy: orion.attribute('createdBy', { label: 'Created By' }), createdAt: orion.attribute('createdAt', { label: 'Created At' }), lockedBy: { type: String, autoform: { type: 'hidden' }, optional: true } }));
JavaScript-NZ/javascript-website-v2
app/lib/collections/2_photos.js
JavaScript
mit
1,358
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Rajdeep's Programs Repository</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/bootstrap-responsive.css" rel="stylesheet"> <link href="assets/css/bootstrap-fileupload.css" rel="stylesheet"> <link href="assets/css/bootstrap-fileupload.min.css" rel="stylesheet"> <link href="assets/css/docs.css" rel="stylesheet"> <link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet"> <style type="text/css"> .footer{ background-color: #d8d8d8; } </style> <script src="assets/js/jquery-1.9.0.js"></script> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="assets/js/html5shiv.js"></script> <![endif]--> </head> <body > <a href="https://github.com/rajdeep26/MyProgramRepository"><img style="position: absolute; top: 15; left: 0; border: 0;" src="./assets/img/forkme_left_red.png" alt="Fork me on GitHub"></a> <!-- Navbar ================================================== --> <div id="nav" class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="./index.html">My Program Repository</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"> <a href="index.html">Home</a> </li> <li><a href="ShowPrograms.php" >Programs</a></li> <li><a href="AddProgram.php" >Add Programs</a></li> <li><a href="Feedback.html" >Feedback</a></li> </ul> </div> </div> </div> </div> <br><br> <div class="container"> <div class="row-fluid"> <a href="AddProgram.php" class="btn btn-primary">Add Program</a> <div class="span8 offset2"> <legend>Programs</legend> <p align="center"><span class="label label-info">Just a Start. More Programs will be added soon.</span></p> <div class="span11"> <div class="accordion" id="accordion2"> <?php include 'mysql.php'; $res = mysql_query("SELECT id,program_title,program_language,program FROM programs"); $i=1; while($row = mysql_fetch_assoc($res)) { // <================= will replace each occurance of '<' with '&lt;' =========> $programdata = $row['program']; $search = "<"; $replace = "&lt;"; $programdata = str_replace($search, $replace, $programdata); // <======================================================================> echo '<div class="accordion-group">'; echo '<div class="accordion-heading">'; echo '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse'.$i.'">'; echo ' '.$row['program_title'].'<p class="pull-right">Language: '.$row['program_language'].' </p>'; echo '</a>'; echo '</div>'; echo '<div id="collapse'.$i.'" class="accordion-body collapse '; if($i==1) echo 'in'; echo '">'; echo '<div class="accordion-inner">'; echo '<pre class="prettyprint linenums">'.$programdata.'</pre>'; echo '<p>'; echo '<a href="EditProgram.php?id='.$row['id'].'" class="btn btn-primary">Edit</a>'; echo '<a href="#myModal'.$i.'" role="button" class="btn btn-danger pull-right" data-toggle="modal">Delete</a>'; // echo '<a href="DeleteProgram.php?id='.$row['id'].'" class="btn btn-danger pull-right">Delete</a>'; echo '<div id="myModal'.$i.'" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'; echo '<div class="modal-header">'; echo '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'; echo '<h3 id="myModalLabel">Delete</h3>'; echo '</div>'; echo '<div class="modal-body">'; echo '<h4 align="center">Are you sure you want to delete this program??</h4>'; echo '<div class="span10 offset2">'; echo '<div class="span4 offset2">'; echo '<a href="DeleteProgram.php?id='.$row['id'].'" class="btn">Yes</a>'; echo '</div>'; echo '<div class="span6">'; echo '<button class="btn" data-dismiss="modal" aria-hidden="true">No</button>'; echo '</div>'; echo '</div>'; echo '</div>'; echo '</div>'; echo '</p>'; echo '</div>'; echo '</div>'; echo '</div>'; $i++; } mysql_close($dbhandle); ?> </div> </div> </div> </div> </div> <!-- Footer ================================================== --> <footer class="footer"> <div class="container"> <p></p> <p>&copy; Copyrights by Rajdeep Mandrekar</p> </div> </footer> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script src="assets/js/jquery.js"></script> <script src="assets/js/bootstrap-transition.js"></script> <script src="assets/js/bootstrap-alert.js"></script> <script src="assets/js/bootstrap-modal.js"></script> <script src="assets/js/bootstrap-dropdown.js"></script> <script src="assets/js/bootstrap-scrollspy.js"></script> <script src="assets/js/bootstrap-tab.js"></script> <script src="assets/js/bootstrap-tooltip.js"></script> <script src="assets/js/bootstrap-popover.js"></script> <script src="assets/js/bootstrap-button.js"></script> <script src="assets/js/bootstrap-collapse.js"></script> <script src="assets/js/bootstrap-carousel.js"></script> <script src="assets/js/bootstrap-typeahead.js"></script> <script src="assets/js/bootstrap-affix.js"></script> <script src="assets/js/bootstrap-fileupload.js"></script> <script src="assets/js/holder/holder.js"></script> <script src="assets/js/google-code-prettify/prettify.js"></script> <script src="assets/js/application.js"></script> </body> </html>
rajdeep26/MyProgramRepository
ShowPrograms.php
PHP
mit
7,658
/** * \file NETGeographicLib\PolyPanel.cs * \brief NETGeographicLib.PolygonArea example * * NETGeographicLib is copyright (c) Scott Heiman (2013) * GeographicLib is Copyright (c) Charles Karney (2010-2012) * <charles@karney.com> and licensed under the MIT/X11 License. * For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using NETGeographicLib; namespace Projections { public partial class PolyPanel : UserControl { PolygonArea m_poly = null; public PolyPanel() { InitializeComponent(); m_poly = new PolygonArea(false); m_majorRadiusTextBox.Text = m_poly.EquatorialRadius.ToString(); m_flatteningTextBox.Text = m_poly.Flattening.ToString(); m_lengthTextBox.Text = m_areaTextBox.Text = m_numPointsTextBox.Text = "0"; m_currLatTextBox.Text = m_currLonTextBox.Text = ""; } private void OnSet(object sender, EventArgs e) { try { double a = Double.Parse(m_majorRadiusTextBox.Text); double f = Double.Parse(m_flatteningTextBox.Text); m_poly = new PolygonArea(new Geodesic(a, f), m_polylineCheckBox.Checked); m_lengthTextBox.Text = m_areaTextBox.Text = m_numPointsTextBox.Text = "0"; m_currLatTextBox.Text = m_currLonTextBox.Text = ""; m_edgeButton.Enabled = false; } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnAddPoint(object sender, EventArgs e) { try { double lat = Double.Parse(m_latitudeTextBox.Text); double lon = Double.Parse(m_longitudeTextBox.Text); double length, area; m_poly.AddPoint(lat, lon); m_edgeButton.Enabled = true; m_currLatTextBox.Text = m_latitudeTextBox.Text; m_currLonTextBox.Text = m_longitudeTextBox.Text; m_numPointsTextBox.Text = m_poly.Compute(false, false, out length, out area).ToString(); m_lengthTextBox.Text = length.ToString(); if ( !m_polylineCheckBox.Checked ) m_areaTextBox.Text = area.ToString(); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnAddEdge(object sender, EventArgs e) { try { double azi = Double.Parse(m_azimuthTextBox.Text); double dist = Double.Parse(m_distanceTextBox.Text); m_poly.AddEdge(azi, dist); double lat, lon, length, area; m_poly.CurrentPoint(out lat, out lon); m_currLatTextBox.Text = lat.ToString(); m_currLonTextBox.Text = lon.ToString(); m_numPointsTextBox.Text = m_poly.Compute(false, false, out length, out area).ToString(); m_lengthTextBox.Text = length.ToString(); if (!m_polylineCheckBox.Checked) m_areaTextBox.Text = area.ToString(); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnClear(object sender, EventArgs e) { m_poly.Clear(); m_edgeButton.Enabled = false; m_lengthTextBox.Text = m_areaTextBox.Text = m_numPointsTextBox.Text = "0"; m_currLatTextBox.Text = m_currLonTextBox.Text = ""; } private void OnValidate(object sender, EventArgs e) { try { double lat, lon, perim, area; PolygonArea pa = new PolygonArea(new Geodesic(50000.0, 0.001), true); pa = new PolygonArea(false); pa.AddPoint(32.0, -86.0); pa.AddEdge(20.0, 10000.0); pa.AddEdge(-45.0, 10000.0); pa.CurrentPoint(out lat, out lon); pa.Compute(false, false, out perim, out area); pa.TestEdge(-70.0, 5000.0, false, false, out perim, out area); pa.TestPoint(31.0, -86.5, false, false, out perim, out area); PolygonAreaExact p2 = new PolygonAreaExact(new GeodesicExact(), false); p2.AddPoint(32.0, -86.0); p2.AddEdge(20.0, 10000.0); p2.AddEdge(-45.0, 10000.0); p2.CurrentPoint(out lat, out lon); p2.Compute(false, false, out perim, out area); p2.TestEdge(-70.0, 5000.0, false, false, out perim, out area); p2.TestPoint(31.0, -86.5, false, false, out perim, out area); PolygonAreaRhumb p3 = new PolygonAreaRhumb(Rhumb.WGS84(), false); p3.AddPoint(32.0, -86.0); p3.AddEdge(20.0, 10000.0); p3.AddEdge(-45.0, 10000.0); p3.CurrentPoint(out lat, out lon); p3.Compute(false, false, out perim, out area); p3.TestEdge(-70.0, 5000.0, false, false, out perim, out area); p3.TestPoint(31.0, -86.5, false, false, out perim, out area); MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
geographiclib/geographiclib
dotnet/Projections/PolyPanel.cs
C#
mit
6,048
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.decorators import login_required from .views import UploadBlackListView, DemoView, UdateBlackListView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^upload-blacklist$', login_required(UploadBlackListView.as_view()), name='upload-blacklist'), url(r'^update-blacklist$', UdateBlackListView.as_view(), name='update-blacklist'), url(r'^profile/', include('n_profile.urls')), url(r'^demo$', DemoView.as_view(), name='demo'), ]
nirvaris/nirvaris-djangofence
djangofence/urls.py
Python
mit
566
'use strict'; module.exports.name = 'cssnano/postcss-minify-font-values'; module.exports.tests = [{ message: 'should unquote font names', fixture: 'h1{font-family:"Helvetica Neue"}', expected: 'h1{font-family:Helvetica Neue}' }, { message: 'should unquote and join identifiers with a slash, if numeric', fixture: 'h1{font-family:"Bond 007"}', expected: 'h1{font-family:Bond\\ 007}' }, { message: 'should not unquote if it would produce a bigger identifier', fixture: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}', expected: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}' }, { message: 'should not unquote font names if they contain keywords', fixture: 'h1{font-family:"slab serif"}', expected: 'h1{font-family:"slab serif"}' }, { message: 'should minimise space inside a legal font name', fixture: 'h1{font-family:Lucida Grande}', expected: 'h1{font-family:Lucida Grande}' }, { message: 'should minimise space around a list of font names', fixture: 'h1{font-family:Arial, Helvetica, sans-serif}', expected: 'h1{font-family:Arial,Helvetica,sans-serif}' }, { message: 'should dedupe font family names', fixture: 'h1{font-family:Helvetica,Arial,Helvetica,sans-serif}', expected: 'h1{font-family:Helvetica,Arial,sans-serif}' }, { message: 'should discard the rest of the declaration after a keyword', fixture: 'h1{font-family:Arial,sans-serif,Arial,"Trebuchet MS"}', expected: 'h1{font-family:Arial,sans-serif}' }, { message: 'should convert the font shorthand property', fixture: 'h1{font:italic small-caps normal 13px/150% "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/150% Helvetica Neue,sans-serif}' }, { message: 'should convert shorthand with zero unit line height', fixture: 'h1{font:italic small-caps normal 13px/1.5 "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/1.5 Helvetica Neue,sans-serif}', }, { message: 'should convert the font shorthand property, unquoted', fixture: 'h1{font:italic Helvetica Neue,sans-serif,Arial}', expected: 'h1{font:italic Helvetica Neue,sans-serif}' }, { message: 'should join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007",sans-serif}', expected: 'h1{font:italic Bond\\ 007,sans-serif}' }, { message: 'should join non-digit identifiers in the shorthand property', fixture: 'h1{font:italic "Bond !",serif}', expected: 'h1{font:italic Bond\\ !,serif}' }, { message: 'should correctly escape special characters at the start', fixture: 'h1{font-family:"$42"}', expected: 'h1{font-family:\\$42}' }, { message: 'should not escape legal characters', fixture: 'h1{font-family:€42}', expected: 'h1{font-family:€42}', options: {normalizeCharset: false} }, { message: 'should not join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007 008 009",sans-serif}', expected: 'h1{font:italic "Bond 007 008 009",sans-serif}' }, { message: 'should escape special characters if unquoting', fixture: 'h1{font-family:"Ahem!"}', expected: 'h1{font-family:Ahem\\!}' }, { message: 'should not escape multiple special characters', fixture: 'h1{font-family:"Ahem!!"}', expected: 'h1{font-family:"Ahem!!"}' }, { message: 'should not mangle legal unquoted values', fixture: 'h1{font-family:\\$42}', expected: 'h1{font-family:\\$42}' }, { message: 'should not mangle font names', fixture: 'h1{font-family:Glyphicons Halflings}', expected: 'h1{font-family:Glyphicons Halflings}' }];
pieter-lazzaro/cssnano
tests/modules/postcss-font-family.js
JavaScript
mit
3,673
#include <cstdlib> #include <stdexcept> #include <vector> #include <algorithm> #include "Platform.h" #include "T3000.h" #include "Position.h" #include "Selection.h" using namespace T3000; void CTstat8HelySystem::MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length) { if (insertion) { if (position == startChange) { Sci::Position virtualLengthRemove = std::min(length, virtualSpace); virtualSpace -= virtualLengthRemove; position += virtualLengthRemove; } else if (position > startChange) { position += length; } } else { if (position == startChange) { virtualSpace = 0; } if (position > startChange) { const Sci::Position endDeletion = startChange + length; if (position > endDeletion) { position -= length; } else { position = startChange; virtualSpace = 0; } } } } bool CTstat8HelySystem::operator <(const CTstat8HelySystem &other) const { if (position == other.position) return virtualSpace < other.virtualSpace; else return position < other.position; } bool CTstat8HelySystem::operator >(const CTstat8HelySystem &other) const { if (position == other.position) return virtualSpace > other.virtualSpace; else return position > other.position; } bool CTstat8HelySystem::operator <=(const CTstat8HelySystem &other) const { if (position == other.position && virtualSpace == other.virtualSpace) return true; else return other > *this; } bool CTstat8HelySystem::operator >=(const CTstat8HelySystem &other) const { if (position == other.position && virtualSpace == other.virtualSpace) return true; else return *this > other; } Sci::Position SelectionRange::Length() const { if (anchor > caret) { return anchor.Position() - caret.Position(); } else { return caret.Position() - anchor.Position(); } } void SelectionRange::MoveForInsertDelete(bool insertion, Sci::Position startChange, Sci::Position length) { caret.MoveForInsertDelete(insertion, startChange, length); anchor.MoveForInsertDelete(insertion, startChange, length); } bool SelectionRange::Contains(Sci::Position pos) const { if (anchor > caret) return (pos >= caret.Position()) && (pos <= anchor.Position()); else return (pos >= anchor.Position()) && (pos <= caret.Position()); } bool SelectionRange::Contains(CTstat8HelySystem sp) const { if (anchor > caret) return (sp >= caret) && (sp <= anchor); else return (sp >= anchor) && (sp <= caret); } bool SelectionRange::ContainsCharacter(Sci::Position posCharacter) const { if (anchor > caret) return (posCharacter >= caret.Position()) && (posCharacter < anchor.Position()); else return (posCharacter >= anchor.Position()) && (posCharacter < caret.Position()); } SelectionSegment SelectionRange::Intersect(SelectionSegment check) const { SelectionSegment inOrder(caret, anchor); if ((inOrder.start <= check.end) || (inOrder.end >= check.start)) { SelectionSegment portion = check; if (portion.start < inOrder.start) portion.start = inOrder.start; if (portion.end > inOrder.end) portion.end = inOrder.end; if (portion.start > portion.end) return SelectionSegment(); else return portion; } else { return SelectionSegment(); } } void SelectionRange::Swap() { std::swap(caret, anchor); } bool SelectionRange::Trim(SelectionRange range) { const CTstat8HelySystem startRange = range.Start(); const CTstat8HelySystem endRange = range.End(); CTstat8HelySystem start = Start(); CTstat8HelySystem end = End(); PLATFORM_ASSERT(start <= end); PLATFORM_ASSERT(startRange <= endRange); if ((startRange <= end) && (endRange >= start)) { if ((start > startRange) && (end < endRange)) { // Completely covered by range -> empty at start end = start; } else if ((start < startRange) && (end > endRange)) { // Completely covers range -> empty at start end = start; } else if (start <= startRange) { // Trim end end = startRange; } else { // PLATFORM_ASSERT(end >= endRange); // Trim start start = endRange; } if (anchor > caret) { caret = start; anchor = end; } else { anchor = start; caret = end; } return Empty(); } else { return false; } } // If range is all virtual collapse to start of virtual space void SelectionRange::MinimizeVirtualSpace() { if (caret.Position() == anchor.Position()) { Sci::Position virtualSpace = caret.VirtualSpace(); if (virtualSpace > anchor.VirtualSpace()) virtualSpace = anchor.VirtualSpace(); caret.SetVirtualSpace(virtualSpace); anchor.SetVirtualSpace(virtualSpace); } } Selection::Selection() : mainRange(0), moveExtends(false), tentativeMain(false), selType(selStream) { AddSelection(SelectionRange(CTstat8HelySystem(0))); } Selection::~Selection() { } bool Selection::IsRectangular() const { return (selType == selRectangle) || (selType == selThin); } Sci::Position Selection::MainCaret() const { return ranges[mainRange].caret.Position(); } Sci::Position Selection::MainAnchor() const { return ranges[mainRange].anchor.Position(); } SelectionRange &Selection::Rectangular() { return rangeRectangular; } SelectionSegment Selection::Limits() const { if (ranges.empty()) { return SelectionSegment(); } else { SelectionSegment sr(ranges[0].anchor, ranges[0].caret); for (size_t i=1; i<ranges.size(); i++) { sr.Extend(ranges[i].anchor); sr.Extend(ranges[i].caret); } return sr; } } SelectionSegment Selection::LimitsForRectangularElseMain() const { if (IsRectangular()) { return Limits(); } else { return SelectionSegment(ranges[mainRange].caret, ranges[mainRange].anchor); } } size_t Selection::Count() const { return ranges.size(); } size_t Selection::Main() const { return mainRange; } void Selection::SetMain(size_t r) { PLATFORM_ASSERT(r < ranges.size()); mainRange = r; } SelectionRange &Selection::Range(size_t r) { return ranges[r]; } const SelectionRange &Selection::Range(size_t r) const { return ranges[r]; } SelectionRange &Selection::RangeMain() { return ranges[mainRange]; } const SelectionRange &Selection::RangeMain() const { return ranges[mainRange]; } CTstat8HelySystem Selection::Start() const { if (IsRectangular()) { return rangeRectangular.Start(); } else { return ranges[mainRange].Start(); } } bool Selection::MoveExtends() const { return moveExtends; } void Selection::SetMoveExtends(bool moveExtends_) { moveExtends = moveExtends_; } bool Selection::Empty() const { for (const SelectionRange &range : ranges) { if (!range.Empty()) return false; } return true; } CTstat8HelySystem Selection::Last() const { CTstat8HelySystem lastPosition; for (const SelectionRange &range : ranges) { if (lastPosition < range.caret) lastPosition = range.caret; if (lastPosition < range.anchor) lastPosition = range.anchor; } return lastPosition; } Sci::Position Selection::Length() const { Sci::Position len = 0; for (const SelectionRange &range : ranges) { len += range.Length(); } return len; } void Selection::MovePositions(bool insertion, Sci::Position startChange, Sci::Position length) { for (SelectionRange &range : ranges) { range.MoveForInsertDelete(insertion, startChange, length); } if (selType == selRectangle) { rangeRectangular.MoveForInsertDelete(insertion, startChange, length); } } void Selection::TrimSelection(SelectionRange range) { for (size_t i=0; i<ranges.size();) { if ((i != mainRange) && (ranges[i].Trim(range))) { // Trimmed to empty so remove for (size_t j=i; j<ranges.size()-1; j++) { ranges[j] = ranges[j+1]; if (j == mainRange-1) mainRange--; } ranges.pop_back(); } else { i++; } } } void Selection::TrimOtherSelections(size_t r, SelectionRange range) { for (size_t i = 0; i<ranges.size(); ++i) { if (i != r) { ranges[i].Trim(range); } } } void Selection::SetSelection(SelectionRange range) { ranges.clear(); ranges.push_back(range); mainRange = ranges.size() - 1; } void Selection::AddSelection(SelectionRange range) { TrimSelection(range); ranges.push_back(range); mainRange = ranges.size() - 1; } void Selection::AddSelectionWithoutTrim(SelectionRange range) { ranges.push_back(range); mainRange = ranges.size() - 1; } void Selection::DropSelection(size_t r) { if ((ranges.size() > 1) && (r < ranges.size())) { size_t mainNew = mainRange; if (mainNew >= r) { if (mainNew == 0) { mainNew = ranges.size() - 2; } else { mainNew--; } } ranges.erase(ranges.begin() + r); mainRange = mainNew; } } void Selection::DropAdditionalRanges() { SetSelection(RangeMain()); } void Selection::TentativeSelection(SelectionRange range) { if (!tentativeMain) { rangesSaved = ranges; } ranges = rangesSaved; AddSelection(range); TrimSelection(ranges[mainRange]); tentativeMain = true; } void Selection::CommitTentative() { rangesSaved.clear(); tentativeMain = false; } int Selection::CharacterInSelection(Sci::Position posCharacter) const { for (size_t i=0; i<ranges.size(); i++) { if (ranges[i].ContainsCharacter(posCharacter)) return i == mainRange ? 1 : 2; } return 0; } int Selection::InSelectionForEOL(Sci::Position pos) const { for (size_t i=0; i<ranges.size(); i++) { if (!ranges[i].Empty() && (pos > ranges[i].Start().Position()) && (pos <= ranges[i].End().Position())) return i == mainRange ? 1 : 2; } return 0; } Sci::Position Selection::VirtualSpaceFor(Sci::Position pos) const { Sci::Position virtualSpace = 0; for (const SelectionRange &range : ranges) { if ((range.caret.Position() == pos) && (virtualSpace < range.caret.VirtualSpace())) virtualSpace = range.caret.VirtualSpace(); if ((range.anchor.Position() == pos) && (virtualSpace < range.anchor.VirtualSpace())) virtualSpace = range.anchor.VirtualSpace(); } return virtualSpace; } void Selection::Clear() { ranges.clear(); ranges.push_back(SelectionRange()); mainRange = ranges.size() - 1; selType = selStream; moveExtends = false; ranges[mainRange].Reset(); rangeRectangular.Reset(); } void Selection::RemoveDuplicates() { for (size_t i=0; i<ranges.size()-1; i++) { if (ranges[i].Empty()) { size_t j=i+1; while (j<ranges.size()) { if (ranges[i] == ranges[j]) { ranges.erase(ranges.begin() + j); if (mainRange >= j) mainRange--; } else { j++; } } } } } void Selection::RotateMain() { mainRange = (mainRange + 1) % ranges.size(); }
temcocontrols/T3000_Building_Automation_System
T3000/Tstat8HelpSystem/CTstat8HelpSystem.cpp
C++
mit
10,412
using AlgorithmsLibrary; using Xunit; namespace Tests { public class QuickFindTests { [Fact] public void IsConnected_NotConnectedByDefault() { var algorithm = new QuickFind(2); Assert.Equal(0, algorithm.Result[0]); Assert.Equal(1, algorithm.Result[1]); Assert.False(algorithm.IsConnected(0, 1)); } [Fact] public void IsConnected_TrueForConnected() { var algorithm = new QuickFind(10); algorithm.Union(1, 8); algorithm.Union(3, 5); algorithm.Union(0, 2); algorithm.Union(8, 9); algorithm.Union(6, 1); Assert.True(algorithm.IsConnected(3, 5)); } [Fact] public void IsConnected_FalseForNotConnected() { var algorithm = new QuickFind(10); algorithm.Union(1, 8); algorithm.Union(3, 5); algorithm.Union(0, 2); algorithm.Union(8, 9); algorithm.Union(6, 1); Assert.False(algorithm.IsConnected(0, 1)); } } }
Sufflavus/Algorithms
Source/Tests/QuickFindTests.cs
C#
mit
1,178
function Tw2VectorSequencer() { this.name = ''; this.start = 0; this.value = vec3.create(); this.operator = 0; this.functions = []; this._tempValue = vec3.create(); } Tw2VectorSequencer.prototype.GetLength = function () { var length = 0; for (var i = 0; i < this.functions.length; ++i) { if ('GetLength' in this.functions[i]) { length = Math.max(length, this.functions[i].GetLength()); } } return length; } Tw2VectorSequencer.prototype.UpdateValue = function (t) { this.GetValueAt(t, this.value); } Tw2VectorSequencer.prototype.GetValueAt = function (t, value) { if (this.operator == 0) { value[0] = 1; value[1] = 1; value[2] = 1; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] *= tempValue[0]; value[1] *= tempValue[1]; value[2] *= tempValue[2]; } } else { value[0] = 0; value[1] = 0; value[2] = 0; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] += tempValue[0]; value[1] += tempValue[1]; value[2] += tempValue[2]; } } return value; }
reactormonk/ccpwgl
src/curves/Tw2VectorSequencer.js
JavaScript
mit
1,489
using commercetools.Common; namespace commercetools.Zones { /// <summary> /// Extensions /// </summary> public static class Extensions { /// <summary> /// Creates an instance of the ZoneManager. /// </summary> /// <returns>ZoneManager</returns> public static ZoneManager Zones(this IClient client) { return new ZoneManager(client); } } }
commercetools/commercetools-dotnet-sdk
commercetools.NET/Zones/Extensions.cs
C#
mit
434
#region License // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. // // 1. Definitions // // The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. // // A "contribution" is the original software, or any additions or changes to the software. // // A "contributor" is any person that distributes its contribution under this license. // // "Licensed patents" are a contributor's patent claims that read directly on its contribution. // // 2. Grant of Rights // // (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. // // (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. // // 3. Conditions and Limitations // // (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. // // (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. // // (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. // // (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. // // (E ) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. #endregion using System; namespace Funq { /// <summary> /// The key that identifies a service entry. /// </summary> internal sealed class ServiceKey { int hash; public ServiceKey(Type factoryType, string serviceName) { FactoryType = factoryType; Name = serviceName; hash = factoryType.GetHashCode(); if (serviceName != null) hash ^= serviceName.GetHashCode(); } public Type FactoryType; public string Name; #region Equality public bool Equals(ServiceKey other) { return ServiceKey.Equals(this, other); } public override bool Equals(object obj) { return ServiceKey.Equals(this, obj as ServiceKey); } public static bool Equals(ServiceKey obj1, ServiceKey obj2) { if (Object.Equals(null, obj1) || Object.Equals(null, obj2)) return false; return obj1.FactoryType == obj2.FactoryType && obj1.Name == obj2.Name; } public override int GetHashCode() { return hash; } #endregion } }
Julien-Mialon/StormXamarin
StormXamarin/Storm.Mvvm/Funq/ServiceKey.cs
C#
mit
3,739
// Include gulp var gulp = require('gulp'); // Include Our Plugins var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var header = require('gulp-header'); var footer = require('gulp-footer'); // Build Task gulp.task('default', function() { gulp.src([ "src/promises.js", "src/util.js", "src/request.js", "src/legends.js", "src/static.js" ]) .pipe(concat('legends.js', { newLine: "\n\n" })) .pipe(header("/*!\n" + " * Legends.js\n" + " * Copyright (c) {{year}} Tyler Johnson\n" + " * MIT License\n" + " */\n\n" + "(function() {\n")) .pipe(footer("\n// API Factory\n" + "if (typeof module === \"object\" && module.exports != null) {\n" + "\tmodule.exports = Legends;\n" + "} else if (typeof window != \"undefined\") {\n" + "\twindow.Legends = Legends;\n" + "}\n\n" + "})();")) .pipe(gulp.dest('./dist')) .pipe(rename('legends.min.js')) .pipe(uglify({ output: { comments: /^!/i } })) .pipe(gulp.dest('./dist')); });
tyler-johnson/Legends
gulpfile.js
JavaScript
mit
1,023
import requests from flask import session, Blueprint, redirect from flask import request from grano import authz from grano.lib.exc import BadRequest from grano.lib.serialisation import jsonify from grano.views.cache import validate_cache from grano.core import db, url_for, app from grano.providers import github, twitter, facebook from grano.model import Account from grano.logic import accounts blueprint = Blueprint('sessions_api', __name__) @blueprint.route('/api/1/sessions', methods=['GET']) def status(): permissions = {} if authz.logged_in(): for permission in request.account.permissions: permissions[permission.project.slug] = { 'reader': permission.reader, 'editor': permission.editor, 'admin': permission.admin } keys = { 'p': repr(permissions), 'i': request.account.id if authz.logged_in() else None } validate_cache(keys=keys) return jsonify({ 'logged_in': authz.logged_in(), 'api_key': request.account.api_key if authz.logged_in() else None, 'account': request.account if request.account else None, 'permissions': permissions }) def provider_not_enabled(name): return jsonify({ 'status': 501, 'name': 'Provider not configured: %s' % name, 'message': 'There are no OAuth credentials given for %s' % name, }, status=501) @blueprint.route('/api/1/sessions/logout', methods=['GET']) def logout(): #authz.require(authz.logged_in()) session.clear() return redirect(request.args.get('next_url', '/')) @blueprint.route('/api/1/sessions/login/github', methods=['GET']) def github_login(): if not app.config.get('GITHUB_CLIENT_ID'): return provider_not_enabled('github') callback=url_for('sessions_api.github_authorized') session.clear() if not request.args.get('next_url'): raise BadRequest("No 'next_url' is specified.") session['next_url'] = request.args.get('next_url') return github.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback/github', methods=['GET']) @github.authorized_handler def github_authorized(resp): next_url = session.get('next_url', '/') if resp is None or not 'access_token' in resp: return redirect(next_url) access_token = resp['access_token'] session['access_token'] = access_token, '' res = requests.get('https://api.github.com/user?access_token=%s' % access_token, verify=False) data = res.json() account = Account.by_github_id(data.get('id')) data_ = { 'full_name': data.get('name'), 'login': data.get('login'), 'email': data.get('email'), 'github_id': data.get('id') } account = accounts.save(data_, account=account) db.session.commit() session['id'] = account.id return redirect(next_url) @blueprint.route('/api/1/sessions/login/twitter', methods=['GET']) def twitter_login(): if not app.config.get('TWITTER_API_KEY'): return provider_not_enabled('twitter') callback=url_for('sessions_api.twitter_authorized') session.clear() if not request.args.get('next_url'): raise BadRequest("No 'next_url' is specified.") session['next_url'] = request.args.get('next_url') return twitter.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback/twitter', methods=['GET']) @twitter.authorized_handler def twitter_authorized(resp): next_url = session.get('next_url', '/') if resp is None or not 'oauth_token' in resp: return redirect(next_url) session['twitter_token'] = (resp['oauth_token'], resp['oauth_token_secret']) res = twitter.get('users/show.json?user_id=%s' % resp.get('user_id')) account = Account.by_twitter_id(res.data.get('id')) data_ = { 'full_name': res.data.get('name'), 'login': res.data.get('screen_name'), 'twitter_id': res.data.get('id') } account = accounts.save(data_, account=account) db.session.commit() session['id'] = account.id return redirect(next_url) @blueprint.route('/api/1/sessions/login/facebook', methods=['GET']) def facebook_login(): if not app.config.get('FACEBOOK_APP_ID'): return provider_not_enabled('facebook') callback=url_for('sessions_api.facebook_authorized') session.clear() if not request.args.get('next_url'): raise BadRequest("No 'next_url' is specified.") session['next_url'] = request.args.get('next_url') return facebook.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback/facebook', methods=['GET']) @facebook.authorized_handler def facebook_authorized(resp): next_url = session.get('next_url', '/') if resp is None or not 'access_token' in resp: return redirect(next_url) session['facebook_token'] = (resp.get('access_token'), '') data = facebook.get('/me').data account = Account.by_facebook_id(data.get('id')) data_ = { 'full_name': data.get('name'), 'login': data.get('username'), 'email': data.get('email'), 'facebook_id': data.get('id') } account = accounts.save(data_, account=account) db.session.commit() session['id'] = account.id return redirect(next_url)
clkao/grano
grano/views/sessions_api.py
Python
mit
5,328
package com.dasa.approval.service; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import com.dasa.approval.dao.ApprovalDao; import com.dasa.approval.vo.ApprovalVo; import com.dasa.communication.vo.BusinessOrderVo; import com.dasa.communication.vo.Notification; import com.dasa.communication.vo.SendNotification; import com.vertexid.vo.NaviVo; public class ApprovalService extends SqlSessionDaoSupport implements ApprovalDao { @Autowired private SendNotification sendNotification; @Override public NaviVo selectApprovalListCount(NaviVo naviVo) throws SQLException { naviVo.setTotRow( (Integer) getSqlSession().selectOne("approval.selectApprovalListCount", naviVo) ); return naviVo; } @Override public List<ApprovalVo> selectApprovalList(NaviVo naviVo) throws SQLException { return getSqlSession().selectList("approval.selectApprovalList", naviVo); } @Override public List<ApprovalVo> selectRejectList(String am_code) throws SQLException { return getSqlSession().selectList("approval.selectRejectList", am_code); } @Override public ApprovalVo selectApprovalRow(ApprovalVo vo) throws SQLException { return getSqlSession().selectOne("approval.selectApprovalRow", vo); } @Override public int getCheckCount(ApprovalVo vo) throws SQLException { int checkCount = (Integer) getSqlSession().selectOne("approval.dupCheckCount", vo); return checkCount; } @Override public void saveApproval(ApprovalVo p_vo) throws SQLException { getSqlSession().update("approval.SP_SAVE_30100", p_vo); System.out.println("p_vo.getAm_code() : " + p_vo.getAm_code()); System.out.println("p_vo.getRes_code() : " + p_vo.getRes_code()); System.out.println("p_vo.getRes_am_code() : " + p_vo.getRes_am_code()); System.out.println("p_vo.getFlag() : " + p_vo.getFlag()); System.out.println("p_vo.getRes_msg : " + p_vo.getRes_msg()); if(p_vo.getRes_code().equals("0") && (p_vo.getFlag().equals("INSERT") || p_vo.getFlag().equals("UPDATE")) ){ //상신 ApprovalVo resVo = new ApprovalVo(); List<Notification> bizNoti1 = new ArrayList<Notification>(); List<Notification> bizNoti2 = new ArrayList<Notification>(); Notification noti1 = new Notification(); Notification noti2 = new Notification(); resVo = getSqlSession().selectOne("approval.selectPushList", p_vo); if(resVo !=null && resVo.getEm_push_id().trim() != ""){ String em_push_id = resVo.getEm_push_id(); String em_device_type = resVo.getEm_device_type(); String subject = "[전자결재] " + resVo.getEm_nm() + " 상신" ; System.out.println("em_device_type:" +em_device_type ); if(em_device_type.equals("A")){ System.out.println("em_push_id:" +em_push_id ); System.out.println("em_device_type:" +em_device_type ); System.out.println("vo.getEm_nm:" +resVo.getEm_nm() ); System.out.println("subject:" +subject); noti1.setStringPropRegId(em_push_id); noti1.setDeviceType(em_device_type); bizNoti1.add(noti1); }else if(em_device_type.equals("I")){ noti2.setStringPropRegId(em_push_id); noti2.setDeviceType(em_device_type); noti2.setRunMode("REAL"); noti2.setCertificatePath("C:\\DASA\\iphone_rel.p12"); noti2.setCertificatePassword("vertexid"); bizNoti2.add(noti2); } try { sendNotification.sendPushMessage(bizNoti1, bizNoti2, subject); } catch (Exception e) { e.printStackTrace(); } } } } @Override public int amNoUpdate(ApprovalVo vo) throws SQLException { return getSqlSession().update("approval.amNoUpdate", vo); } }
GenSolutionRep/Note
src/main/java/com/dasa/approval/service/ApprovalService.java
Java
mit
3,931
var myTimeout = 12000; Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { var value = this.getItem(key); return value && JSON.parse(value); }; // Обеспечиваем поддержу XMLHttpRequest`а в IE var xmlVersions = new Array( "Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ); if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() { for(var i in xmlVersions) { try { return new ActiveXObject(xmlVersions[i]); } catch(e) {} } throw new Error( "This browser does not support XMLHttpRequest." ); }; // Собственно, сам наш обработчик. function myErrHandler(message, url, line) { var tmp = window.location.toString().split("/"); var server_url = tmp[0] + '//' + tmp[2]; var params = "logJSErr=logJSErr&message="+message+'&url='+url+'&line='+line; var req = new XMLHttpRequest(); req.open('POST', server_url+'/jslogerror?ajax=1', true); req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); req.setRequestHeader("Content-length", params.length); req.setRequestHeader("Connection", "close"); req.send(params); // Чтобы подавить стандартный диалог ошибки JavaScript, // функция должна возвратить true return true; } // window.onerror = myErrHandler; //назначаем обработчик для события onerror // ПОТОМ ВКЛЮЧИТЬ window.onerror = myErrHandler; function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function nl2br(str) { return str.replace(/([^>])\n/g, '$1<br>'); } function htmlspecialchars(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
schoolphp/library
Core/fw.js
JavaScript
mit
2,095
/** * grunt-webfont: fontforge engine * * @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py * @author Artem Sapegin (http://sapegin.me) */ module.exports = function(o, allDone) { 'use strict'; var fs = require('fs'); var path = require('path'); var temp = require('temp'); var async = require('async'); var glob = require('glob'); var exec = require('exec'); var chalk = require('chalk'); var _ = require('lodash'); var logger = o.logger || require('winston'); var wf = require('../util/util'); // Copy source files to temporary directory var tempDir = temp.mkdirSync(); o.files.forEach(function(file) { fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file)); }); // Run Fontforge var args = [ 'fontforge', '-script', path.join(__dirname, 'fontforge/generate.py') ]; var proc = exec(args, function(err, out, code) { if (err instanceof Error && err.code === 'ENOENT') { return error('fontforge not found. Please install fontforge and all other requirements.'); } else if (err) { if (err instanceof Error) { return error(err.message); } // Skip some fontforge output such as copyrights. Show warnings only when no font files was created // or in verbose mode. var success = !!generatedFontFiles(); var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/; var lines = err.split('\n'); var warn = []; lines.forEach(function(line) { if (!line.match(notError) && !success) { warn.push(line); } else { logger.verbose(chalk.grey('fontforge: ') + line); } }); if (warn.length) { return error(warn.join('\n')); } } // Trim fontforge result var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, ''); // Parse json var result; try { result = JSON.parse(json); } catch (e) { return error('Webfont did not receive a proper JSON result.\n' + e + '\n' + out); } allDone({ fontName: path.basename(result.file) }); }); // Send JSON with params if (!proc) return; var params = _.extend(o, { inputDir: tempDir }); proc.stdin.write(JSON.stringify(params)); proc.stdin.end(); function generatedFontFiles() { return glob.sync(path.join(o.dest, o.fontBaseName + wf.fontFileMask)); } function error() { logger.error.apply(null, arguments); allDone(false); return false; } };
jnaO/grunt-webfont
tasks/engines/fontforge.js
JavaScript
mit
2,457
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (t1 == NULL) return t2; if (t2 == NULL) return t1; TreeNode *root = new TreeNode(t1 -> val + t2 -> val); root -> left = mergeTrees(t1 -> left, t2 -> left); root -> right = mergeTrees(t1 -> right, t2 -> right); return root; } };
chasingegg/Online_Judge
leetcode/617_Merge-Two-Binary-Trees/MergeTrees.cpp
C++
mit
558
<?php /* * The MIT License (MIT) * * Copyright (c) 2013 Christian Zenker <dev@xopn.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ namespace Czenker\Wichtlr\ConsoleHelper; use Czenker\Wichtlr\Graph\Graph; use Czenker\Wichtlr\Graph\Node; use Symfony\Component\Console\Helper\Helper; use Symfony\Component\Console\Output\OutputInterface; class Reindeer extends Helper { /** * @var array lines of text making up an ASCII art reindeer */ protected $reindeer = array(); /** * @var int lines needed to show the reindeer */ protected $reindeerWidth = 0; /** * @var int columns needed to show the reindeer */ protected $reindeerHeight = 0; /** * @var int number of ASCII chars between reindeer and the text */ protected $gutterWidth = 2; /** * @var int width of the text */ protected $textWidth = 80; /** * @var OutputInterface */ protected $output; public function __construct() { $this->initReindeer(__DIR__ . '/../Resources/reindeer.txt'); } public function setOutput(OutputInterface $output) { $this->output = $output; } protected function initReindeer($filePath) { $reindeer = file_get_contents($filePath); $this->reindeer = explode("\n", $reindeer); foreach($this->reindeer as $line) { if(strlen($line) > $this->reindeerWidth) { $this->reindeerWidth = strlen($line); } } $this->reindeerHeight = count($this->reindeer); $this->textWidth = $this->textWidth - $this->gutterWidth - $this->reindeerWidth; } public function say($message, OutputInterface $output = NULL) { $output = $output ?: $this->output; $message = wordwrap($message, $this->textWidth); $message = explode("\n", $message); array_unshift($message, ''); $reindeer = $this->reindeer; $output->writeln(''); while(count($reindeer) > 0 || count($message) > 0) { $line = str_pad(array_shift($reindeer) ?: '', $this->reindeerWidth) . str_pad(' ', $this->gutterWidth) . array_shift($message) ?: '' ; $output->writeln($line); } $output->writeln(''); } /** * Returns the canonical name of this helper. * * @return string The canonical name * * @api */ public function getName() { return 'reindeer'; } public function sayHello() { $this->say(<<<EOF Hi there. I am the reindeer with the name that I can't tell you for legal reasons. But I think you know me quite well. Santa asked me to help you figuring out how to give presents without everyone knowing it was YOU who gave away this crappy gift. EOF ); } public function sayBye() { $this->say(<<<EOF Sorry, but I just can't work like that! You know where to find me if you need help. EOF ); } public function sayCreateParticipantsYaml($fileName) { $this->say(<<<EOF I need a list of people who should participate in this fun little game. Let me just create a list for you where you fill in all your friends and I take care of the rest. Please edit <comment>$fileName</comment> and let me know when you are done. I'll just wait here. EOF ); } public function sayCreateMailYaml($fileName) { $this->say(<<<EOF There are not many post offices here at the north pole. Please tell my how to send the mail I'll write for you. I created a file for you where you could write everything down. Please edit <comment>$fileName</comment> and let me know when you are done. I'll just wait here. EOF ); } public function sayCreateDefaultTemplate($fileName) { $this->say(<<<EOF Now is the time to tell me how the mails should look like. I created a file for you where you could write everything down. Please edit <comment>$fileName</comment> and let me know when you are done. I'll just wait here. EOF ); } public function sayParticipants(Graph $graph) { $participantNames = array(); foreach($graph->getNodes() as $node) { /** @var $node Node */ $participantNames[] = $node->getParticipant()->getName(); } $participantNames = implode(', ', $participantNames); $participantCount = count($graph->getNodes()); $this->say(<<<EOF So you have $participantCount people who want to join: $participantNames EOF ); } public function saySendMails() { $this->say(<<<EOF The elves are writing your letters now. Do you want me to send the letters right away or do you want to catch a peek into them? EOF ); } public function saySendMailDummies() { $this->say(<<<EOF Hah, I thought so. Just remember that the elves will write new letters the next time - so you will probably get a different result when you call me again. If you give me your address I'll send all the mails to you instead. I promise I won't give your address to Santa! EOF ); } public function sayCreateRecoveryData() { $this->say(<<<EOF I have to confess something: Sometimes mails get lost during the transit. If you want I can create some recovery data that can help you if one mail gets lost. The risk is of course that if two people combine their knowledge they can potentially reveal the identity of a giver. EOF ); } }
czenker/wichtlr
lib/Czenker/Wichtlr/ConsoleHelper/Reindeer.php
PHP
mit
6,574
<?php /** * MarkaCategory form base class. * * @method MarkaCategory getObject() Returns the current form's model object * * @package sf_sandbox * @subpackage form * @author Your name here * @version SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $ */ abstract class BaseMarkaCategoryForm extends BaseFormDoctrine { public function setup() { $this->setWidgets(array( 'id' => new sfWidgetFormInputHidden(), 'name' => new sfWidgetFormInputText(), 'slug' => new sfWidgetFormInputText(), )); $this->setValidators(array( 'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)), 'name' => new sfValidatorString(array('max_length' => 100)), 'slug' => new sfValidatorString(array('max_length' => 100)), )); $this->validatorSchema->setPostValidator( new sfValidatorAnd(array( new sfValidatorDoctrineUnique(array('model' => 'MarkaCategory', 'column' => array('name'))), new sfValidatorDoctrineUnique(array('model' => 'MarkaCategory', 'column' => array('slug'))), )) ); $this->widgetSchema->setNameFormat('marka_category[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'MarkaCategory'; } }
verkri/designermarka
lib/form/doctrine/base/BaseMarkaCategoryForm.class.php
PHP
mit
1,491
require 'csv' @file_name = ARGV[0] file = File.new('inputs/' + @file_name, 'r') n_lines = 0 @headers = nil @contents = {} @dates = [] def parse_headers(fields) @headers = fields.slice(1..(fields.length-1)) @headers = @headers.map(&:chomp) @headers.each do |name| @contents[name] = [] end end def parse_line(fields) @dates << fields[0] @headers.each_with_index do |name, i| @contents[name] << fields[i + 1].chomp.to_f end end file.each_line do |line| fields = line.split(',') if (@headers) break unless fields.length == (@headers.length + 1) next if fields.last =~ /^\s*$/ parse_line(fields) elsif (fields[0] == 'Day') parse_headers(fields) end end def normalize_for_ebola return unless @headers.include?('ebola') peak_ebola = @contents['ebola'].max @contents.keys.each do |key| @contents[key] = @contents[key].map { |value| value * 100 / peak_ebola } end end def header ['Name'] + @dates end def write_contents CSV.open("outputs/#{@file_name}", 'w') do |writer| writer << header @contents.each do |key, values| writer << [key] + values end end end normalize_for_ebola write_contents
cyrusinnovation/american_ebola_response
data_sources/parse_individual.rb
Ruby
mit
1,137
package com.github.programmerr47.chords.representation.adapter.item; /** * Simple expansion of interface {@link AdapterItem} for organization of * "selection mode". * * @author Michael Spitsin * @since 2014-10-08 */ public abstract class SelectionModeAdapterItem implements AdapterItem { protected boolean isSelected; /** * Selects/deselects element. It is needed for selection mode to keep the "selection" * state in element. * * @param isSelected true if need to select element, false if need to deselect element */ public final void setElementSelected(boolean isSelected) { this.isSelected = isSelected; // setViewSelected(); } /** * Retrieves "selection" state of concrete element. * * @return true if element is selected and false if elements is deselected */ public final boolean isElementSelected() { return isSelected; } // /** // * Changes view when calls {@link SelectionModeAdapterItem#setElementSelected(boolean)}. // */ // protected abstract void setViewSelected(); }
programmerr47/guitar-chords
app/src/main/java/com/github/programmerr47/chords/representation/adapter/item/SelectionModeAdapterItem.java
Java
mit
1,102
package br.com.trustsystems.demo.provider; import br.com.trustsystems.persistence.Persistent; import br.com.trustsystems.persistence.dao.IUnitOfWork; import br.com.trustsystems.persistence.provider.jpa.JpaPersistenceProvider; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Collection; import java.util.List; @Service public class DatabasePersistenceProvider extends JpaPersistenceProvider { @PersistenceContext private EntityManager em; @Override public EntityManager entityManager() { return em; } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> D persist(Class<D> domainClass, D domainObject) { return super.persist(domainClass, domainObject); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> List<D> persistAll(Class<D> domainClass, List<D> domainObjects) { return super.persistAll(domainClass, domainObjects); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> boolean deleteAll(Class<D> domainClass, Collection<D> domainObjects) { return super.deleteAll(domainClass, domainObjects); } @Transactional(propagation = Propagation.REQUIRED) public <D extends Persistent<?>> boolean delete(Class<D> domainClass, D domainObject) { return super.delete(domainClass, domainObject); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void runInTransaction(IUnitOfWork t) { super.runInTransaction(t); } }
trust-wenderson/super-dao-demo
src/main/java/br/com/trustsystems/demo/provider/DatabasePersistenceProvider.java
Java
mit
1,812
// <copyright file="Size2D.cs" company="Shkyrockett" > // Copyright © 2005 - 2020 Shkyrockett. All rights reserved. // </copyright> // <author id="shkyrockett">Shkyrockett</author> // <license> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </license> // <date></date> // <summary></summary> // <remarks></remarks> using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Xml.Serialization; using static Engine.Maths; using static Engine.Operations; using static System.Math; namespace Engine { /// <summary> /// The size2d struct. /// </summary> /// <seealso cref="IVector{T}" /> [DataContract, Serializable] [TypeConverter(typeof(Size2DConverter))] [DebuggerDisplay("{" + nameof(GetDebuggerDisplay) + "(),nq}")] public struct Size2D : IVector<Size2D> { #region Implementations /// <summary> /// Represents a <see cref="Size2D" /> that has <see cref="Width" />, and <see cref="Height" /> values set to zero. /// </summary> public static readonly Size2D Empty = new Size2D(0d, 0d); /// <summary> /// Represents a <see cref="Size2D" /> that has <see cref="Width" />, and <see cref="Height" /> values set to 1. /// </summary> public static readonly Size2D Unit = new Size2D(1d, 1d); /// <summary> /// Represents a <see cref="Size2D" /> that has <see cref="Width" />, and <see cref="Height" /> values set to NaN. /// </summary> public static readonly Size2D NaN = new Size2D(double.NaN, double.NaN); #endregion Implementations #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Size2D" /> class. /// </summary> /// <param name="size">The size.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Size2D(Size2D size) : this(size.Width, size.Height) { } /// <summary> /// Initializes a new instance of the <see cref="Size2D" /> class. /// </summary> /// <param name="point">The point.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Size2D(Point2D point) : this(point.X, point.Y) { } /// <summary> /// Initializes a new instance of the <see cref="Size2D" /> class. /// </summary> /// <param name="width">The Width component of the Size.</param> /// <param name="height">The Height component of the Size.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Size2D(double width, double height) : this() { (Width, Height) = (width, height); } /// <summary> /// Initializes a new instance of the <see cref="Size2D" /> class. /// </summary> /// <param name="tuple">The tuple.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Size2D((double Width, double Height) tuple) : this() { (Width, Height) = tuple; } #endregion Constructors #region Deconstructors /// <summary> /// Deconstruct this <see cref="Size2D" /> to a <see cref="ValueTuple{T1, T2}" />. /// </summary> /// <param name="width">The width.</param> /// <param name="height">The height.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out double width, out double height) => (width, height) = (Width, Height); #endregion Deconstructors #region Properties /// <summary> /// Gets or sets the Width component of a <see cref="Size2D" /> coordinate. /// </summary> /// <value> /// The width. /// </value> [DataMember(Name = nameof(Width)), XmlAttribute(nameof(Width)), SoapAttribute(nameof(Width))] public double Width { get; set; } /// <summary> /// Gets or sets the Height component of a <see cref="Size2D" /> coordinate. /// </summary> /// <value> /// The height. /// </value> [DataMember(Name = nameof(Height)), XmlAttribute(nameof(Height)), SoapAttribute(nameof(Height))] public double Height { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="Point2D" /> is empty. /// </summary> /// <value> /// <see langword="true"/> if this instance is empty; otherwise, <see langword="false"/>. /// </value> [IgnoreDataMember, XmlIgnore, SoapIgnore] [Browsable(false)] public bool IsEmpty => Abs(Width) < double.Epsilon && Abs(Height) < double.Epsilon; /// <summary> /// Gets the number of components in the Vector. /// </summary> /// <value> /// The count. /// </value> [IgnoreDataMember, XmlIgnore, SoapIgnore] public int Count => 2; #endregion Properties #region Operators /// <summary> /// The operator +. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The <see cref="Size2D" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator +(Size2D value) => Plus(value); /// <summary> /// Add an amount to both values in the <see cref="Point2D" /> classes. /// </summary> /// <param name="augend">The original value</param> /// <param name="addend">The amount to add.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator +(Size2D augend, double addend) => Add(augend, addend); /// <summary> /// Add an amount to both values in the <see cref="Point2D" /> classes. /// </summary> /// <param name="augend">The original value</param> /// <param name="addend">The amount to add.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator +(double augend, Size2D addend) => Add(augend, addend); /// <summary> /// Add two <see cref="Size2D" /> classes together. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator +(Size2D augend, Size2D addend) => Add(augend, addend); /// <summary> /// Add two <see cref="Size2D" /> classes together. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator +(Size2D augend, Point2D addend) => Add(augend, addend); /// <summary> /// Add a <see cref="Point2D" /> and a <see cref="Size2D" /> classes together. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator +(Point2D augend, Size2D addend) => Add(augend, addend); /// <summary> /// Add a <see cref="Size2D" /> to a <see cref="Vector2D" /> class. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator +(Size2D augend, Vector2D addend) => Add(augend, addend); /// <summary> /// Add a <see cref="Vector2D" /> and a <see cref="Size2D" /> classes together. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator +(Vector2D augend, Size2D addend) => Add(augend, addend); /// <summary> /// The operator -. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The <see cref="Size2D" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator -(Size2D value) => Negate(value); /// <summary> /// Subtract a <see cref="Size2D" /> from a <see cref="double" /> value. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator -(Size2D minuend, double subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="double" /> value from a <see cref="Size2D" />. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator -(double minuend, Size2D subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="Size2D" /> from another <see cref="Size2D" /> class. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator -(Size2D minuend, Size2D subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="Size2D" /> from a <see cref="Point2D" /> class. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator -(Size2D minuend, Point2D subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="Point2D" /> from another <see cref="Size2D" /> class. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator -(Point2D minuend, Size2D subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="Size2D" /> from a <see cref="Vector2D" /> class. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator -(Size2D minuend, Vector2D subend) => Subtract(minuend, subend); /// <summary> /// Subtract a <see cref="Vector2D" /> from another <see cref="Size2D" /> class. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator -(Vector2D minuend, Size2D subend) => Subtract(minuend, subend); /// <summary> /// Scale a point. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator *(Size2D multiplicand, double multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a point /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator *(double multiplicand, Size2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a Size2D /// </summary> /// <param name="multiplicand">The Point</param> /// <param name="multiplier">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator *(Size2D multiplicand, Size2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a Point /// </summary> /// <param name="multiplicand">The Point</param> /// <param name="multiplier">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator *(Size2D multiplicand, Point2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a Point /// </summary> /// <param name="multiplicand">The Point</param> /// <param name="multiplier">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator *(Point2D multiplicand, Size2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a Vector /// </summary> /// <param name="multiplicand">The Point</param> /// <param name="multiplier">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator *(Size2D multiplicand, Vector2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Scale a Vector /// </summary> /// <param name="multiplicand">The Point</param> /// <param name="multiplier">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator *(Vector2D multiplicand, Size2D multiplier) => Multiply(multiplicand, multiplier); /// <summary> /// Divide a <see cref="Size2D" /> by a <see cref="double" /> value. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator /(Size2D dividend, double divisor) => Divide(dividend, divisor); /// <summary> /// Divide a <see cref="double" /> by a <see cref="Size2D" /> value. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator /(double dividend, Size2D divisor) => Divide(dividend, divisor); /// <summary> /// Divide a Size2D /// </summary> /// <param name="dividend">The Point</param> /// <param name="divisor">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D operator /(Size2D dividend, Size2D divisor) => Divide(dividend, divisor); /// <summary> /// Divide a Point /// </summary> /// <param name="dividend">The Point</param> /// <param name="divisor">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator /(Size2D dividend, Point2D divisor) => Divide(dividend, divisor); /// <summary> /// Divide a Point /// </summary> /// <param name="dividend">The Point</param> /// <param name="divisor">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D operator /(Point2D dividend, Size2D divisor) => Divide(dividend, divisor); /// <summary> /// Divide a Vector /// </summary> /// <param name="dividend">The Point</param> /// <param name="divisor">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator /(Size2D dividend, Vector2D divisor) => Divide(dividend, divisor); /// <summary> /// Divide a Vector /// </summary> /// <param name="dividend">The Point</param> /// <param name="divisor">The Multiplier</param> /// <returns> /// A Point Multiplied by the Multiplier /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D operator /(Vector2D dividend, Size2D divisor) => Divide(dividend, divisor); /// <summary> /// Compares two <see cref="Size2D" /> objects. /// The result specifies whether the values of the <see cref="Width" /> and <see cref="Height" /> /// values of the two <see cref="Size2D" /> objects are equal. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Size2D left, Size2D right) => Equals(left, right); /// <summary> /// Compares two <see cref="Size2D" /> objects. /// The result specifies whether the values of the <see cref="Width" /> or <see cref="Height" /> /// values of the two <see cref="Size2D" /> objects are unequal. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns> /// The result of the operator. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Size2D left, Size2D right) => !Equals(left, right); /// <summary> /// Explicit conversion to Size2D. /// </summary> /// <param name="size">The size.</param> /// <returns> /// Size - A Size equal to this Size /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Size2D(Vector2D size) => new Size2D(size.I, size.J); /// <summary> /// Explicit conversion to Vector. /// </summary> /// <param name="size">Size - the Size to convert to a Vector</param> /// <returns> /// Vector - A Vector equal to this Size /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector2D(Size2D size) => new Vector2D(size.Width, size.Height); /// <summary> /// Converts the specified <see cref="Point2D" /> to a <see cref="Size2D" />. /// </summary> /// <param name="size">The size.</param> /// <returns> /// Size - A Vector equal to this Size /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Size2D(Point2D size) => new Size2D(size.X, size.Y); /// <summary> /// Converts the specified <see cref="Size2D" /> to a <see cref="Point2D" />. /// </summary> /// <param name="size">The size.</param> /// <returns> /// The result of the conversion. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Point2D(Size2D size) => new Point2D(size.Width, size.Height); /// <summary> /// Implicit conversion from tuple. /// </summary> /// <param name="tuple">Size - the Size to convert to a Vector</param> /// <returns> /// The result of the conversion. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Size2D((double Width, double Height) tuple) => new Size2D(tuple); /// <summary> /// Converts the specified <see cref="Point2D" /> structure to a <see cref="ValueTuple{T1, T2}" /> structure. /// </summary> /// <param name="point">The <see cref="Point2D" /> to be converted.</param> /// <returns> /// The result of the conversion. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator (double Width, double Height)(Size2D point) => (point.Width, point.Height); #endregion Operators #region Operator Backing Methods /// <summary> /// Pluses the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Plus(Size2D value) => Operations.Plus(value.Width, value.Height); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Add(Size2D augend, double addend) => AddVectorUniform(augend.Width, augend.Height, addend); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Add(double augend, Size2D addend) => AddVectorUniform(addend.Width, addend.Height, augend); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Add(Size2D augend, Size2D addend) => AddVectors(augend.Width, augend.Height, addend.Width, addend.Height); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Add(Size2D augend, Point2D addend) => AddVectors(augend.Width, augend.Height, addend.X, addend.Y); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Add(Point2D augend, Size2D addend) => AddVectors(augend.X, augend.Y, addend.Width, addend.Height); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Add(Size2D augend, Vector2D addend) => AddVectors(augend.Width, augend.Height, addend.I, addend.J); /// <summary> /// Adds the specified augend. /// </summary> /// <param name="augend">The augend.</param> /// <param name="addend">The addend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Add(Vector2D augend, Size2D addend) => AddVectors(augend.I, augend.J, addend.Width, addend.Height); /// <summary> /// Negates the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Negate(Size2D value) => Operations.Negate(value.Width, value.Height); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Subtract(Size2D minuend, double subend) => SubtractVectorUniform(minuend.Width, minuend.Height, subend); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Subtract(double minuend, Size2D subend) => SubtractVectorUniform(minuend, subend.Width, subend.Height); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Subtract(Size2D minuend, Size2D subend) => SubtractVector(minuend.Width, minuend.Height, subend.Width, subend.Height); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Subtract(Size2D minuend, Point2D subend) => SubtractVector(minuend.Width, minuend.Height, subend.X, subend.Y); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Subtract(Point2D minuend, Size2D subend) => SubtractVector(minuend.X, minuend.Y, subend.Width, subend.Height); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Subtract(Size2D minuend, Vector2D subend) => SubtractVector(minuend.Width, minuend.Height, subend.I, subend.J); /// <summary> /// Subtracts the specified minuend. /// </summary> /// <param name="minuend">The minuend.</param> /// <param name="subend">The subend.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Subtract(Vector2D minuend, Size2D subend) => SubtractVector(minuend.I, minuend.J, subend.Width, subend.Height); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Multiply(Size2D multiplicand, double multiplier) => ScaleVector(multiplicand.Width, multiplicand.Height, multiplier); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Multiply(double multiplicand, Size2D multiplier) => ScaleVector(multiplier.Width, multiplier.Height, multiplicand); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Multiply(Size2D multiplicand, Size2D multiplier) => ScaleVectorParametric(multiplicand.Width, multiplicand.Height, multiplier.Width, multiplier.Height); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Multiply(Size2D multiplicand, Point2D multiplier) => ScaleVectorParametric(multiplicand.Width, multiplicand.Height, multiplier.X, multiplier.Y); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Multiply(Point2D multiplicand, Size2D multiplier) => ScaleVectorParametric(multiplicand.X, multiplicand.Y, multiplier.Width, multiplier.Height); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Multiply(Size2D multiplicand, Vector2D multiplier) => ScaleVectorParametric(multiplicand.Width, multiplicand.Height, multiplier.I, multiplier.J); /// <summary> /// Multiplies the specified multiplicand. /// </summary> /// <param name="multiplicand">The multiplicand.</param> /// <param name="multiplier">The multiplier.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Multiply(Vector2D multiplicand, Size2D multiplier) => ScaleVectorParametric(multiplicand.I, multiplicand.J, multiplier.Width, multiplier.Height); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Divide(Size2D dividend, double divisor) => DivideVectorUniform(dividend.Width, dividend.Height, divisor); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Divide(double dividend, Size2D divisor) => DivideByVectorUniform(dividend, divisor.Width, divisor.Height); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D Divide(Size2D dividend, Size2D divisor) => DivideVectorParametric(dividend.Width, dividend.Height, divisor.Width, divisor.Height); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Divide(Size2D dividend, Point2D divisor) => DivideVectorParametric(dividend.Width, dividend.Height, divisor.X, divisor.Y); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D Divide(Point2D dividend, Size2D divisor) => DivideVectorParametric(dividend.X, dividend.Y, divisor.Width, divisor.Height); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Divide(Size2D dividend, Vector2D divisor) => ScaleVectorParametric(dividend.Width, dividend.Height, divisor.I, divisor.J); /// <summary> /// Divides the specified dividend. /// </summary> /// <param name="dividend">The dividend.</param> /// <param name="divisor">The divisor.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D Divide(Vector2D dividend, Size2D divisor) => DivideVectorParametric(dividend.I, dividend.J, divisor.Width, divisor.Height); /// <summary> /// Determines whether the specified <see cref="object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object" /> to compare with this instance.</param> /// <returns> /// <see langword="true"/> if the specified <see cref="object" /> is equal to this instance; otherwise, <see langword="false"/>. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals([AllowNull] object obj) => obj is Point2D d && Equals(d); /// <summary> /// The equals. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// The <see cref="bool" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Size2D other) => (Width == other.Width) && (Height == other.Height); /// <summary> /// Converts to valuetuple. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public (double Width, double Height) ToValueTuple() => (Width, Height); /// <summary> /// Froms the value tuple. /// </summary> /// <param name="tuple">The tuple.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D FromValueTuple((double Width, double Height) tuple) => new Size2D(tuple.Width, tuple.Height); /// <summary> /// Converts to size2d. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Size2D ToSize2D() => new Size2D(Width, Height); /// <summary> /// Converts to size2d. /// </summary> /// <param name="size">The size.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Size2D FromSize2D(Size2D size) => new Size2D(size.Width, size.Height); /// <summary> /// Converts to vector2d. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector2D ToVector2D() => new Vector2D(Width, Height); /// <summary> /// Converts to Vector2D. /// </summary> /// <param name="vector">The vector.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2D FromVector2D(Vector2D vector) => new Vector2D(vector.I, vector.J); /// <summary> /// Converts to point2d. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public Point2D ToPoint2D() => new Point2D(Width, Height); /// <summary> /// Converts to Point2D. /// </summary> /// <param name="point">The point.</param> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Point2D FromPoint2D(Point2D point) => new Point2D(point.X, point.Y); #endregion #region Factories /// <summary> /// Parse a string for a <see cref="Size2D" /> value. /// </summary> /// <param name="source"><see cref="string" /> with <see cref="Size2D" /> data</param> /// <returns> /// Returns an instance of the <see cref="Size2D" /> struct converted /// from the provided string using the <see cref="CultureInfo.InvariantCulture" />. /// </returns> [ParseMethod] public static Size2D Parse(string source) => Parse(source, CultureInfo.InvariantCulture); /// <summary> /// Parse a string for a <see cref="Size2D" /> value. /// </summary> /// <param name="source"><see cref="string" /> with <see cref="Size2D" /> data</param> /// <param name="formatProvider">The provider.</param> /// <returns> /// Returns an instance of the <see cref="Size2D" /> struct converted /// from the provided string using the <see cref="CultureInfo.InvariantCulture" />. /// </returns> public static Size2D Parse(string source, IFormatProvider formatProvider) { var tokenizer = new Tokenizer(source, formatProvider); var firstToken = tokenizer.NextTokenRequired(); // The token will already have had whitespace trimmed so we can do a simple string compare. var value = firstToken == nameof(Empty) ? Empty : new Size2D( Convert.ToDouble(firstToken, formatProvider), Convert.ToDouble(tokenizer.NextTokenRequired(), formatProvider) ); // There should be no more tokens in this string. tokenizer.LastTokenRequired(); return value; } /// <summary> /// The truncate. /// </summary> /// <returns> /// The <see cref="Size2D" />. /// </returns> public Size2D Truncate() => new Size2D((int)Width, (int)Height); #endregion Factories #region Standard Methods /// <summary> /// Get the hash code. /// </summary> /// <returns> /// The <see cref="int" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() => HashCode.Combine(Width, Height); /// <summary> /// Creates a human-readable string that represents this <see cref="Size2D" /> struct. /// </summary> /// <returns> /// A string representation of this <see cref="Size2D" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() => ToString("R" /* format string */, CultureInfo.InvariantCulture /* format provider */); /// <summary> /// Creates a string representation of this <see cref="Size2D" /> struct based on the IFormatProvider /// passed in. If the provider is null, the CurrentCulture is used. /// </summary> /// <param name="formatProvider">The <see cref="CultureInfo" /> provider.</param> /// <returns> /// A string representation of this <see cref="Size2D" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(IFormatProvider formatProvider) => ToString("R" /* format string */, formatProvider); /// <summary> /// Creates a string representation of this <see cref="Size2D" /> struct based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The <see cref="CultureInfo"/> provider.</param> /// <returns> /// A string representation of this <see cref="Size2D" />. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(string format, IFormatProvider formatProvider) { if (this == null) return nameof(Size2D); var s = Tokenizer.GetNumericListSeparator(formatProvider); return $"{nameof(Size2D)}({nameof(Width)}: {Width.ToString(format, formatProvider)}{s} {nameof(Height)}: {Height.ToString(format, formatProvider)})"; } /// <summary> /// Gets the debugger display. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] private string GetDebuggerDisplay() => ToString(); #endregion } }
Shkyrockett/engine
Engine.Geometry/Primitives/Size2D.cs
C#
mit
46,593
class Model < ActiveRecord::Base # Relationships to other Entities has_many :products validates_presence_of :name validates_length_of :name, :within => 2..32 validates_uniqueness_of :name end
joshcarr/minimal-commerce
app/models/model.rb
Ruby
mit
211
'use strict'; var fs = require('fs'), path = require('path'); // path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux // path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/ // path.parse('/home/user/dir/file.txt') // returns // { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } var walk = function(dir, done){ var results = {}; fs.readdir(dir, function(err, list){ if (err) { return done(err); } var pending = list.length; if (!pending) { return done(null, results); } list.forEach(function(layer){ var target = path.resolve(dir, layer); fs.stat(target, function(err, stat){ if (stat && stat.isDirectory()) { console.log(layer); results[layer] = []; walk(target, function(err, file){ console.log(file); if (!--pending) { done(null, results); } }); } else { var file = path.basename(target); if (file[0] === '_') { // results[layer][].push(file); null; } if (!--pending) { done(null, results); } } }); }); }); }; var walking = function(config, done){ var results = {}; var pending = config.layers.length; config.layers.forEach(function(layer){ results[layer] = []; if (!pending) { return done(null, results); } fs.readdir(config.src.scss + '/' + layer, function(err, files){ if (err) { return 'error #1'; } files.forEach(function(file){ if (file[0] !== '.') { if (file[0] !== '_') { results[layer].push(file); } else { results[layer].push(file.slice(1, -5)); } } }); }); if (pending === 1) { done(null, results); } else { --pending; } }); }; var layers = function(dir){ var results = walk(dir, function(err, results){ if (err) { throw err; } results = JSON.stringify(results, null, 4); console.log(results); fs.writeFile('guide/app.json', results); return results; }); } module.exports = layers;
hanakin/rotory
src/model/layers/index.js
JavaScript
mit
2,763
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }
mohayonao/libogg.js
include/stdlib.js
JavaScript
mit
777
var _ = require('../../util') var handlers = { text: require('./text'), radio: require('./radio'), select: require('./select'), checkbox: require('./checkbox') } module.exports = { priority: 800, twoWay: true, handlers: handlers, /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number * - TODO: more types may be supplied as a plugin */ bind: function () { // friendly warning... this.checkFilters() if (this.hasRead && !this.hasWrite) { process.env.NODE_ENV !== 'production' && _.warn( 'It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.' ) } var el = this.el var tag = el.tagName var handler if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text } else if (tag === 'SELECT') { handler = handlers.select } else if (tag === 'TEXTAREA') { handler = handlers.text } else { process.env.NODE_ENV !== 'production' && _.warn( 'v-model does not support element type: ' + tag ) return } handler.bind.call(this) this.update = handler.update this.unbind = handler.unbind }, /** * Check read/write filter stats. */ checkFilters: function () { var filters = this.filters if (!filters) return var i = filters.length while (i--) { var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name) if (typeof filter === 'function' || filter.read) { this.hasRead = true } if (filter.write) { this.hasWrite = true } } } }
goforward01/follow_vue
src/directives/model/index.js
JavaScript
mit
1,765
var classes = [ { "name": "Hal\\Report\\Html\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "renderPage", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTrend", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 1, "nbMethodsPublic": 3, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 360, "vocabulary": 90, "volume": 2337.07, "difficulty": 12.54, "effort": 29298.84, "level": 0.08, "bugs": 0.78, "time": 1628, "intelligentContent": 186.42, "number_operators": 103, "number_operands": 257, "number_operators_unique": 8, "number_operands_unique": 82, "cloc": 30, "loc": 151, "lloc": 124, "mi": 60.71, "mIwoC": 28.86, "commentWeight": 31.85, "kanDefect": 1.36, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.68, "relativeSystemComplexity": 81.68, "totalStructuralComplexity": 324, "totalDataComplexity": 2.7, "totalSystemComplexity": 326.7, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Violations\\Xml\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "DOMDocument" ], "lcom": 1, "length": 96, "vocabulary": 40, "volume": 510.91, "difficulty": 5.71, "effort": 2919.46, "level": 0.18, "bugs": 0.17, "time": 162, "intelligentContent": 89.41, "number_operators": 16, "number_operands": 80, "number_operators_unique": 5, "number_operands_unique": 35, "cloc": 15, "loc": 61, "lloc": 47, "mi": 78.36, "mIwoC": 43.62, "commentWeight": 34.74, "kanDefect": 0.75, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.23, "relativeSystemComplexity": 100.23, "totalStructuralComplexity": 200, "totalDataComplexity": 0.45, "totalSystemComplexity": 200.45, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Cli\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 168, "vocabulary": 68, "volume": 1022.69, "difficulty": 7.75, "effort": 7921.69, "level": 0.13, "bugs": 0.34, "time": 440, "intelligentContent": 132.03, "number_operators": 33, "number_operands": 135, "number_operators_unique": 7, "number_operands_unique": 61, "cloc": 14, "loc": 105, "lloc": 85, "mi": 62.43, "mIwoC": 35.63, "commentWeight": 26.8, "kanDefect": 1.03, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 36.36, "totalStructuralComplexity": 72, "totalDataComplexity": 0.71, "totalSystemComplexity": 72.71, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Consolidated", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAvg", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getSum", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getClasses", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFiles", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getProject", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 6, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 5, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 181, "vocabulary": 53, "volume": 1036.75, "difficulty": 10.5, "effort": 10885.91, "level": 0.1, "bugs": 0.35, "time": 605, "intelligentContent": 98.74, "number_operators": 43, "number_operands": 138, "number_operators_unique": 7, "number_operands_unique": 46, "cloc": 37, "loc": 123, "lloc": 86, "mi": 73.03, "mIwoC": 35.47, "commentWeight": 37.55, "kanDefect": 1.67, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.29, "relativeSystemComplexity": 10.29, "totalStructuralComplexity": 54, "totalDataComplexity": 7.75, "totalSystemComplexity": 61.75, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\InterfaceMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\ClassMetric" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FunctionMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 2, "instability": 0.33, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FileMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Metrics", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "jsonSerialize", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "JsonSerializable" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 25, "loc": 51, "lloc": 26, "mi": 101.39, "mIwoC": 57.18, "commentWeight": 44.21, "kanDefect": 0.15, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.4, "relativeSystemComplexity": 10.4, "totalStructuralComplexity": 45, "totalDataComplexity": 7, "totalSystemComplexity": 52, "pageRank": 0.02, "afferentCoupling": 18, "efferentCoupling": 1, "instability": 0.05, "numberOfUnitTests": 12, "violations": {} }, { "name": "Hal\\Metric\\ProjectMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Helper\\RoleOfMethodDetector", "interface": false, "methods": [ { "name": "detects", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [], "lcom": 1, "length": 52, "vocabulary": 21, "volume": 228.4, "difficulty": 8.75, "effort": 1998.5, "level": 0.11, "bugs": 0.08, "time": 111, "intelligentContent": 26.1, "number_operators": 17, "number_operands": 35, "number_operators_unique": 7, "number_operands_unique": 14, "cloc": 15, "loc": 44, "lloc": 29, "mi": 90.35, "mIwoC": 51.05, "commentWeight": 39.31, "kanDefect": 0.66, "relativeStructuralComplexity": 0, "relativeDataComplexity": 6, "relativeSystemComplexity": 6, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 10, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "LogicException", "LogicException", "LogicException", "LogicException", "LogicException" ], "lcom": 1, "length": 111, "vocabulary": 36, "volume": 573.86, "difficulty": 10.14, "effort": 5820.6, "level": 0.1, "bugs": 0.19, "time": 323, "intelligentContent": 56.58, "number_operators": 40, "number_operands": 71, "number_operators_unique": 8, "number_operands_unique": 28, "cloc": 31, "loc": 77, "lloc": 46, "mi": 84.67, "mIwoC": 43.07, "commentWeight": 41.61, "kanDefect": 0.78, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 9, "instability": 0.9, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 20, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 102, "vocabulary": 25, "volume": 473.67, "difficulty": 14.97, "effort": 7091.94, "level": 0.07, "bugs": 0.16, "time": 394, "intelligentContent": 31.64, "number_operators": 25, "number_operands": 77, "number_operators_unique": 7, "number_operands_unique": 18, "cloc": 27, "loc": 102, "lloc": 75, "mi": 73.44, "mIwoC": 37.67, "commentWeight": 35.77, "kanDefect": 2.66, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 2, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 218, "vocabulary": 50, "volume": 1230.36, "difficulty": 11.97, "effort": 14721.41, "level": 0.08, "bugs": 0.41, "time": 818, "intelligentContent": 102.83, "number_operators": 71, "number_operands": 147, "number_operators_unique": 7, "number_operands_unique": 43, "cloc": 29, "loc": 88, "lloc": 59, "mi": 78.03, "mIwoC": 39.2, "commentWeight": 38.83, "kanDefect": 0.57, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\LengthVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 5, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 1, "length": 80, "vocabulary": 25, "volume": 371.51, "difficulty": 7.75, "effort": 2879.19, "level": 0.13, "bugs": 0.12, "time": 160, "intelligentContent": 47.94, "number_operators": 18, "number_operands": 62, "number_operators_unique": 5, "number_operands_unique": 20, "cloc": 20, "loc": 55, "lloc": 36, "mi": 87.59, "mIwoC": 47.38, "commentWeight": 40.21, "kanDefect": 0.59, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 50, "vocabulary": 21, "volume": 219.62, "difficulty": 7, "effort": 1537.31, "level": 0.14, "bugs": 0.07, "time": 85, "intelligentContent": 31.37, "number_operators": 15, "number_operands": 35, "number_operators_unique": 6, "number_operands_unique": 15, "cloc": 15, "loc": 48, "lloc": 33, "mi": 88.3, "mIwoC": 50.21, "commentWeight": 38.09, "kanDefect": 0.44, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 68, "vocabulary": 19, "volume": 288.86, "difficulty": 18.91, "effort": 5462.06, "level": 0.05, "bugs": 0.1, "time": 303, "intelligentContent": 15.28, "number_operators": 16, "number_operands": 52, "number_operators_unique": 8, "number_operands_unique": 11, "cloc": 27, "loc": 80, "lloc": 53, "mi": 83.79, "mIwoC": 44.62, "commentWeight": 39.17, "kanDefect": 1.04, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 18, "totalDataComplexity": 1, "totalSystemComplexity": 19, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 3, "instability": 0.6, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\ClassEnumVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\InterfaceMetric", "Hal\\Metric\\ClassMetric", "Hal\\Metric\\Helper\\RoleOfMethodDetector", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 113, "vocabulary": 35, "volume": 579.61, "difficulty": 12.59, "effort": 7298.78, "level": 0.08, "bugs": 0.19, "time": 405, "intelligentContent": 46.03, "number_operators": 28, "number_operands": 85, "number_operators_unique": 8, "number_operands_unique": 27, "cloc": 8, "loc": 73, "lloc": 65, "mi": 64.56, "mIwoC": 40.03, "commentWeight": 24.53, "kanDefect": 1.09, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.13, "relativeSystemComplexity": 49.13, "totalStructuralComplexity": 98, "totalDataComplexity": 0.25, "totalSystemComplexity": 98.25, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 11, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 98, "vocabulary": 27, "volume": 465.98, "difficulty": 8.3, "effort": 3865.51, "level": 0.12, "bugs": 0.16, "time": 215, "intelligentContent": 56.17, "number_operators": 25, "number_operands": 73, "number_operators_unique": 5, "number_operands_unique": 22, "cloc": 23, "loc": 63, "lloc": 40, "mi": 86.09, "mIwoC": 45.83, "commentWeight": 40.26, "kanDefect": 0.74, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverse", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 111, "vocabulary": 23, "volume": 502.12, "difficulty": 20.53, "effort": 10310.1, "level": 0.05, "bugs": 0.17, "time": 573, "intelligentContent": 24.45, "number_operators": 34, "number_operands": 77, "number_operators_unique": 8, "number_operands_unique": 15, "cloc": 27, "loc": 89, "lloc": 62, "mi": 78.59, "mIwoC": 40.91, "commentWeight": 37.67, "kanDefect": 1.47, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 81.5, "totalStructuralComplexity": 243, "totalDataComplexity": 1.5, "totalSystemComplexity": 244.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 8, "instability": 0.89, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\System\\Changes\\GitChanges", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "doesThisFileShouldBeCounted", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Metric\\Metrics", "Hal\\Application\\Config\\ConfigException", "DateTime", "Hal\\Metric\\ProjectMetric", "Hal\\Metric\\FileMetric" ], "lcom": 1, "length": 256, "vocabulary": 49, "volume": 1437.37, "difficulty": 16.17, "effort": 23237.41, "level": 0.06, "bugs": 0.48, "time": 1291, "intelligentContent": 88.91, "number_operators": 62, "number_operands": 194, "number_operators_unique": 7, "number_operands_unique": 42, "cloc": 36, "loc": 142, "lloc": 106, "mi": 66.99, "mIwoC": 31.83, "commentWeight": 35.17, "kanDefect": 1.82, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.54, "relativeSystemComplexity": 49.54, "totalStructuralComplexity": 147, "totalDataComplexity": 1.63, "totalSystemComplexity": 148.63, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 6, "instability": 0.86, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\PageRank", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculatePageRank", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 12, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 136, "vocabulary": 40, "volume": 723.78, "difficulty": 24.31, "effort": 17598.63, "level": 0.04, "bugs": 0.24, "time": 978, "intelligentContent": 29.77, "number_operators": 35, "number_operands": 101, "number_operators_unique": 13, "number_operands_unique": 27, "cloc": 20, "loc": 75, "lloc": 55, "mi": 76.27, "mIwoC": 40.4, "commentWeight": 35.87, "kanDefect": 2.13, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 16.5, "totalStructuralComplexity": 32, "totalDataComplexity": 1, "totalSystemComplexity": 33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\Coupling", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 84, "vocabulary": 23, "volume": 379.98, "difficulty": 11.12, "effort": 4224.47, "level": 0.09, "bugs": 0.13, "time": 235, "intelligentContent": 34.18, "number_operators": 21, "number_operands": 63, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 12, "loc": 56, "lloc": 44, "mi": 77.06, "mIwoC": 44.2, "commentWeight": 32.86, "kanDefect": 1.56, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.09, "relativeSystemComplexity": 100.09, "totalStructuralComplexity": 100, "totalDataComplexity": 0.09, "totalSystemComplexity": 100.09, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\ClassMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Ast\\NodeTraverser", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverseArray", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "PhpParser\\NodeTraverser", "parent" ], "lcom": 1, "length": 93, "vocabulary": 19, "volume": 395.06, "difficulty": 17.79, "effort": 7028.73, "level": 0.06, "bugs": 0.13, "time": 390, "intelligentContent": 22.2, "number_operators": 32, "number_operands": 61, "number_operators_unique": 7, "number_operands_unique": 12, "cloc": 5, "loc": 65, "lloc": 60, "mi": 63.05, "mIwoC": 42.22, "commentWeight": 20.83, "kanDefect": 1.63, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.75, "relativeSystemComplexity": 25.75, "totalStructuralComplexity": 50, "totalDataComplexity": 1.5, "totalSystemComplexity": 51.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\CliOutput", "interface": false, "methods": [ { "name": "writeln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "write", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "err", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clearln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setQuietMode", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 2, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 2, "length": 30, "vocabulary": 11, "volume": 103.78, "difficulty": 6.29, "effort": 652.35, "level": 0.16, "bugs": 0.03, "time": 36, "intelligentContent": 16.51, "number_operators": 8, "number_operands": 22, "number_operators_unique": 4, "number_operands_unique": 7, "cloc": 25, "loc": 54, "lloc": 31, "mi": 96.55, "mIwoC": 53.08, "commentWeight": 43.47, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.93, "relativeSystemComplexity": 5.93, "totalStructuralComplexity": 20, "totalDataComplexity": 9.67, "totalSystemComplexity": 29.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\ProgressBar", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "start", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "advance", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "hasAnsi", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 1, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 1, "length": 66, "vocabulary": 29, "volume": 320.63, "difficulty": 12.83, "effort": 4114.71, "level": 0.08, "bugs": 0.11, "time": 229, "intelligentContent": 24.98, "number_operators": 24, "number_operands": 42, "number_operators_unique": 11, "number_operands_unique": 18, "cloc": 40, "loc": 83, "lloc": 43, "mi": 90.27, "mIwoC": 46.28, "commentWeight": 43.99, "kanDefect": 0.36, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.6, "relativeSystemComplexity": 9.6, "totalStructuralComplexity": 45, "totalDataComplexity": 3, "totalSystemComplexity": 48, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Issue\\Issuer", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "onError", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "enable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "disable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "terminate", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "log", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 8, "nbMethodsPrivate": 2, "nbMethodsPublic": 6, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Component\\Output\\Output", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 3, "length": 123, "vocabulary": 49, "volume": 690.61, "difficulty": 6.77, "effort": 4673.66, "level": 0.15, "bugs": 0.23, "time": 260, "intelligentContent": 102.05, "number_operators": 26, "number_operands": 97, "number_operators_unique": 6, "number_operands_unique": 43, "cloc": 44, "loc": 152, "lloc": 95, "mi": 73.05, "mIwoC": 36.04, "commentWeight": 37.01, "kanDefect": 0.89, "relativeStructuralComplexity": 16, "relativeDataComplexity": 1.48, "relativeSystemComplexity": 17.48, "totalStructuralComplexity": 128, "totalDataComplexity": 11.8, "totalSystemComplexity": 139.8, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\Edge", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFrom", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTo", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 16, "vocabulary": 6, "volume": 41.36, "difficulty": 2.75, "effort": 113.74, "level": 0.36, "bugs": 0.01, "time": 6, "intelligentContent": 15.04, "number_operators": 5, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 47, "lloc": 24, "mi": 102.62, "mIwoC": 58.44, "commentWeight": 44.19, "kanDefect": 0.15, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 2.75, "totalStructuralComplexity": 4, "totalDataComplexity": 7, "totalSystemComplexity": 11, "pageRank": 0.37, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Component\\Tree\\Node", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getKey", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAdjacents", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getData", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setData", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 7, "nbMethods": 3, "nbMethodsPrivate": 0, "nbMethodsPublic": 3, "nbMethodsGetter": 3, "nbMethodsSetters": 1, "ccn": 4, "externals": [ "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 47, "vocabulary": 9, "volume": 148.99, "difficulty": 12.4, "effort": 1847.43, "level": 0.08, "bugs": 0.05, "time": 103, "intelligentContent": 12.02, "number_operators": 16, "number_operands": 31, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 40, "loc": 89, "lloc": 49, "mi": 90.46, "mIwoC": 47.38, "commentWeight": 43.08, "kanDefect": 0.52, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.64, "relativeSystemComplexity": 10.64, "totalStructuralComplexity": 63, "totalDataComplexity": 11.5, "totalSystemComplexity": 74.5, "pageRank": 0.35, "afferentCoupling": 13, "efferentCoupling": 1, "instability": 0.07, "numberOfUnitTests": 42, "violations": {} }, { "name": "Hal\\Component\\Tree\\Graph", "interface": false, "methods": [ { "name": "insert", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 6, "nbMethodsPrivate": 0, "nbMethodsPublic": 6, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Countable", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 67, "vocabulary": 16, "volume": 268, "difficulty": 8.5, "effort": 2278, "level": 0.12, "bugs": 0.09, "time": 127, "intelligentContent": 31.53, "number_operators": 16, "number_operands": 51, "number_operators_unique": 4, "number_operands_unique": 12, "cloc": 35, "loc": 94, "lloc": 59, "mi": 84.1, "mIwoC": 43.56, "commentWeight": 40.53, "kanDefect": 0.82, "relativeStructuralComplexity": 36, "relativeDataComplexity": 1.23, "relativeSystemComplexity": 37.23, "totalStructuralComplexity": 288, "totalDataComplexity": 9.86, "totalSystemComplexity": 297.86, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 8, "instability": 0.73, "numberOfUnitTests": 10, "violations": {} }, { "name": "Hal\\Component\\Tree\\Operator\\CycleDetector", "interface": false, "methods": [ { "name": "isCyclic", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "detectCycle", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 64, "vocabulary": 12, "volume": 229.44, "difficulty": 14.29, "effort": 3277.68, "level": 0.07, "bugs": 0.08, "time": 182, "intelligentContent": 16.06, "number_operators": 24, "number_operands": 40, "number_operators_unique": 5, "number_operands_unique": 7, "cloc": 23, "loc": 64, "lloc": 41, "mi": 87.12, "mIwoC": 47.08, "commentWeight": 40.04, "kanDefect": 1.12, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.79, "relativeSystemComplexity": 36.79, "totalStructuralComplexity": 72, "totalDataComplexity": 1.57, "totalSystemComplexity": 73.57, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 4, "violations": {} }, { "name": "Hal\\Component\\Tree\\GraphException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "LogicException" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\HashMap", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 0, "nbMethodsPublic": 5, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Countable", "IteratorAggregate", "Hal\\Component\\Tree\\Node", "ArrayIterator" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 21, "loc": 47, "lloc": 26, "mi": 100.19, "mIwoC": 57.18, "commentWeight": 43.01, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.87, "relativeSystemComplexity": 5.87, "totalStructuralComplexity": 20, "totalDataComplexity": 9.33, "totalSystemComplexity": 29.33, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 4, "instability": 1, "numberOfUnitTests": 3, "violations": {} }, { "name": "Hal\\Component\\File\\Finder", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fetch", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "RecursiveDirectoryIterator", "RecursiveIteratorIterator", "RegexIterator" ], "lcom": 1, "length": 64, "vocabulary": 25, "volume": 297.21, "difficulty": 4.38, "effort": 1302.05, "level": 0.23, "bugs": 0.1, "time": 72, "intelligentContent": 67.84, "number_operators": 18, "number_operands": 46, "number_operators_unique": 4, "number_operands_unique": 21, "cloc": 35, "loc": 68, "lloc": 33, "mi": 93.84, "mIwoC": 49.02, "commentWeight": 44.82, "kanDefect": 0.68, "relativeStructuralComplexity": 0, "relativeDataComplexity": 3, "relativeSystemComplexity": 3, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Violations", "interface": false, "methods": [ { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "add", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "__toString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "IteratorAggregate", "Countable", "ArrayIterator", "Hal\\Violation\\Violation" ], "lcom": 1, "length": 20, "vocabulary": 9, "volume": 63.4, "difficulty": 5.2, "effort": 329.67, "level": 0.19, "bugs": 0.02, "time": 18, "intelligentContent": 12.19, "number_operators": 7, "number_operands": 13, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 19, "loc": 44, "lloc": 25, "mi": 99.17, "mIwoC": 56.62, "commentWeight": 42.55, "kanDefect": 0.38, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.63, "relativeSystemComplexity": 2.63, "totalStructuralComplexity": 4, "totalDataComplexity": 6.5, "totalSystemComplexity": 10.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\Blob", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 47, "vocabulary": 19, "volume": 199.65, "difficulty": 4.27, "effort": 851.85, "level": 0.23, "bugs": 0.07, "time": 47, "intelligentContent": 46.79, "number_operators": 15, "number_operands": 32, "number_operators_unique": 4, "number_operands_unique": 15, "cloc": 12, "loc": 56, "lloc": 42, "mi": 80.54, "mIwoC": 47.68, "commentWeight": 32.86, "kanDefect": 0.5, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooComplexCode", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 15, "volume": 109.39, "difficulty": 3.45, "effort": 377.9, "level": 0.29, "bugs": 0.04, "time": 21, "intelligentContent": 31.67, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 46, "lloc": 32, "mi": 88.05, "mIwoC": 52.49, "commentWeight": 35.56, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooDependent", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 14, "volume": 106.61, "difficulty": 3.8, "effort": 405.1, "level": 0.26, "bugs": 0.04, "time": 23, "intelligentContent": 28.05, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 10, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.73, "mIwoC": 52.87, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooLong", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 27, "vocabulary": 15, "volume": 105.49, "difficulty": 3.45, "effort": 364.41, "level": 0.29, "bugs": 0.04, "time": 20, "intelligentContent": 30.54, "number_operators": 8, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.77, "mIwoC": 52.9, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\ProbablyBugged", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 31, "vocabulary": 17, "volume": 126.71, "difficulty": 3.23, "effort": 409.38, "level": 0.31, "bugs": 0.04, "time": 23, "intelligentContent": 39.22, "number_operators": 10, "number_operands": 21, "number_operators_unique": 4, "number_operands_unique": 13, "cloc": 13, "loc": 48, "lloc": 34, "mi": 87.55, "mIwoC": 51.46, "commentWeight": 36.08, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\ViolationParser", "interface": false, "methods": [ { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Violation\\Class_\\Blob", "Hal\\Violation\\Class_\\TooComplexCode", "Hal\\Violation\\Class_\\ProbablyBugged", "Hal\\Violation\\Class_\\TooLong", "Hal\\Violation\\Class_\\TooDependent", "Hal\\Violation\\Violations" ], "lcom": 1, "length": 13, "vocabulary": 7, "volume": 36.5, "difficulty": 2.2, "effort": 80.29, "level": 0.45, "bugs": 0.01, "time": 4, "intelligentContent": 16.59, "number_operators": 2, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 5, "cloc": 4, "loc": 19, "lloc": 15, "mi": 95.62, "mIwoC": 63, "commentWeight": 32.62, "kanDefect": 0.61, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 9, "totalDataComplexity": 0.5, "totalSystemComplexity": 9.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Analyze", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Component\\Issue\\Issuer", "Hal\\Metric\\Metrics", "PhpParser\\ParserFactory", "Hal\\Component\\Ast\\NodeTraverser", "PhpParser\\NodeVisitor\\NameResolver", "Hal\\Metric\\Class_\\ClassEnumVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "Hal\\Metric\\Class_\\Text\\LengthVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "Hal\\Component\\Output\\ProgressBar", "Hal\\Metric\\System\\Coupling\\PageRank", "Hal\\Metric\\System\\Coupling\\Coupling", "Hal\\Metric\\System\\Changes\\GitChanges", "Hal\\Metric\\System\\UnitTesting\\UnitTesting" ], "lcom": 1, "length": 88, "vocabulary": 21, "volume": 386.52, "difficulty": 6.25, "effort": 2415.77, "level": 0.16, "bugs": 0.13, "time": 134, "intelligentContent": 61.84, "number_operators": 13, "number_operands": 75, "number_operators_unique": 3, "number_operands_unique": 18, "cloc": 27, "loc": 86, "lloc": 59, "mi": 81.14, "mIwoC": 42.99, "commentWeight": 38.15, "kanDefect": 0.38, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 100.36, "totalStructuralComplexity": 200, "totalDataComplexity": 0.73, "totalSystemComplexity": 200.73, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 22, "instability": 0.96, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Application", "interface": false, "methods": [ { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Component\\Output\\CliOutput", "Hal\\Component\\Issue\\Issuer", "Hal\\Application\\Config\\Parser", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Component\\File\\Finder", "Hal\\Application\\Analyze", "Hal\\Violation\\ViolationParser", "Hal\\Report\\Cli\\Reporter", "Hal\\Report\\Html\\Reporter", "Hal\\Report\\Violations\\Xml\\Reporter" ], "lcom": 1, "length": 71, "vocabulary": 23, "volume": 321.17, "difficulty": 4.5, "effort": 1445.28, "level": 0.22, "bugs": 0.11, "time": 80, "intelligentContent": 71.37, "number_operators": 11, "number_operands": 60, "number_operators_unique": 3, "number_operands_unique": 20, "cloc": 13, "loc": 55, "lloc": 43, "mi": 80.74, "mIwoC": 46.55, "commentWeight": 34.2, "kanDefect": 0.36, "relativeStructuralComplexity": 144, "relativeDataComplexity": 0.08, "relativeSystemComplexity": 144.08, "totalStructuralComplexity": 144, "totalDataComplexity": 0.08, "totalSystemComplexity": 144.08, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 12, "instability": 1, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Validator", "interface": false, "methods": [ { "name": "validate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "help", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException" ], "lcom": 2, "length": 57, "vocabulary": 23, "volume": 257.84, "difficulty": 8.12, "effort": 2093.08, "level": 0.12, "bugs": 0.09, "time": 116, "intelligentContent": 31.76, "number_operators": 11, "number_operands": 46, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 15, "loc": 81, "lloc": 54, "mi": 75.17, "mIwoC": 44.25, "commentWeight": 30.92, "kanDefect": 0.96, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.38, "relativeSystemComplexity": 9.38, "totalStructuralComplexity": 18, "totalDataComplexity": 0.75, "totalSystemComplexity": 18.75, "pageRank": 0, "afferentCoupling": 3, "efferentCoupling": 4, "instability": 0.57, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\ConfigException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Exception" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 1, "instability": 0.2, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Parser", "interface": false, "methods": [ { "name": "parse", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config" ], "lcom": 1, "length": 67, "vocabulary": 23, "volume": 303.08, "difficulty": 9.18, "effort": 2781.19, "level": 0.11, "bugs": 0.1, "time": 155, "intelligentContent": 33.03, "number_operators": 15, "number_operands": 52, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 3, "loc": 36, "lloc": 33, "mi": 70.05, "mIwoC": 48.42, "commentWeight": 21.62, "kanDefect": 0.96, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.5, "relativeSystemComplexity": 2.5, "totalStructuralComplexity": 1, "totalDataComplexity": 1.5, "totalSystemComplexity": 2.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Application\\Config\\Config", "interface": false, "methods": [ { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fromArray", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 2, "externals": [], "lcom": 1, "length": 29, "vocabulary": 6, "volume": 74.96, "difficulty": 5.75, "effort": 431.04, "level": 0.17, "bugs": 0.02, "time": 24, "intelligentContent": 13.04, "number_operators": 6, "number_operands": 23, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 52, "lloc": 29, "mi": 97.58, "mIwoC": 54.7, "commentWeight": 42.87, "kanDefect": 0.38, "relativeStructuralComplexity": 4, "relativeDataComplexity": 2, "relativeSystemComplexity": 6, "totalStructuralComplexity": 20, "totalDataComplexity": 10, "totalSystemComplexity": 30, "pageRank": 0.01, "afferentCoupling": 7, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 0, "violations": {} }, { "name": "MyVisitor", "interface": false, "methods": [ { "name": "__construct", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 1, "externals": [ "PhpParser\\NodeVisitorAbstract", "PhpParser\\Node" ], "lcom": 1, "length": 7, "vocabulary": 4, "volume": 14, "difficulty": 1, "effort": 14, "level": 1, "bugs": 0, "time": 1, "intelligentContent": 14, "number_operators": 1, "number_operands": 6, "number_operators_unique": 1, "number_operands_unique": 3, "cloc": 13, "loc": 26, "lloc": 13, "mi": 112, "mIwoC": 67.54, "commentWeight": 44.46, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 1, "relativeSystemComplexity": 1, "totalStructuralComplexity": 0, "totalDataComplexity": 2, "totalSystemComplexity": 2, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 0, "violations": {} } ]
phpmetrics/website
report/v2/js/classes.js
JavaScript
mit
98,017
(function() { 'use strict'; var jhiAlert = { template: '<div class="alerts" ng-cloak="">' + '<div ng-repeat="alert in $ctrl.alerts" ng-class="[alert.position, {\'toast\': alert.toast}]">' + '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close($ctrl.alerts)"><pre ng-bind-html="alert.msg"></pre></uib-alert>' + '</div>' + '</div>', controller: jhiAlertController }; angular .module('noctemApp') .component('jhiAlert', jhiAlert); jhiAlertController.$inject = ['$scope', 'AlertService']; function jhiAlertController($scope, AlertService) { var vm = this; vm.alerts = AlertService.get(); $scope.$on('$destroy', function () { vm.alerts = []; }); } })();
gcorreageek/noctem
src/main/webapp/app/components/alert/alert.directive.js
JavaScript
mit
864
<header class="main-header"> <!-- Logo --> <a href="" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>G'</b>GO</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Gaspi'</b>GO</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="hidden-xs"><?php echo $_SESSION['user']->prenom . ' ' . $_SESSION['famille']->nom_fam; ?></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <p> <?php echo $_SESSION['user']->prenom . ' ' . $_SESSION['famille']->nom_fam; ?> </p> <p> Vos points de chasses : <?php echo $_SESSION['userPoints']; ?> </p> </li> <!-- Menu Footer--> <li class="user-footer"> <center> <a href="deconnexion" class="btn btn-default btn-flat">Se déconnecter</a> </center> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header>
Theo-Drappier/dip-purple
views/base/header.php
PHP
mit
1,870
<h2>Listing <span class='muted'>Names</span></h2> <br> <?php if ($names): ?> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>&nbsp;</th> </tr> </thead> <tbody> <?php foreach ($names as $item): ?> <tr> <td><?php echo $item->name; ?></td> <td> <div class="btn-toolbar"> <div class="btn-group"> <?php echo Html::anchor('name/view/'.$item->id, '<i class="icon-eye-open"></i> View', array('class' => 'btn btn-small')); ?> <?php echo Html::anchor('name/edit/'.$item->id, '<i class="icon-wrench"></i> Edit', array('class' => 'btn btn-small')); ?> <?php echo Html::anchor('name/delete/'.$item->id, '<i class="icon-trash icon-white"></i> Delete', array('class' => 'btn btn-small btn-danger', 'onclick' => "return confirm('Are you sure?')")); ?> </div> </div> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <p>No Names.</p> <?php endif; ?><p> <?php echo Html::anchor('name/create', 'Add new Name', array('class' => 'btn btn-success')); ?> </p>
miyahira/fuelphp_test
fuel/app/views/name/index.php
PHP
mit
1,036
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Controller class for LAB_Temp_ResultadoEncabezado /// </summary> [System.ComponentModel.DataObject] public partial class LabTempResultadoEncabezadoController { // Preload our schema.. LabTempResultadoEncabezado thisSchemaLoad = new LabTempResultadoEncabezado(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public LabTempResultadoEncabezadoCollection FetchAll() { LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection(); Query qry = new Query(LabTempResultadoEncabezado.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public LabTempResultadoEncabezadoCollection FetchByID(object IdProtocolo) { LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection().Where("idProtocolo", IdProtocolo).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public LabTempResultadoEncabezadoCollection FetchByQuery(Query qry) { LabTempResultadoEncabezadoCollection coll = new LabTempResultadoEncabezadoCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdProtocolo) { return (LabTempResultadoEncabezado.Delete(IdProtocolo) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdProtocolo) { return (LabTempResultadoEncabezado.Destroy(IdProtocolo) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(int IdProtocolo,int IdEfector) { Query qry = new Query(LabTempResultadoEncabezado.Schema); qry.QueryType = QueryType.Delete; qry.AddWhere("IdProtocolo", IdProtocolo).AND("IdEfector", IdEfector); qry.Execute(); return (true); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdProtocolo,int IdEfector,string Apellido,string Nombre,int Edad,string UnidadEdad,string FechaNacimiento,string Sexo,int NumeroDocumento,string Fecha,DateTime Fecha1,string Domicilio,int Hc,string Prioridad,string Origen,string Numero,bool? Hiv,string Solicitante,string Sector,string Sala,string Cama,string Embarazo,string EfectorSolicitante,int? IdSolicitudScreening,DateTime? FechaRecibeScreening,string ObservacionesResultados,string TipoMuestra) { LabTempResultadoEncabezado item = new LabTempResultadoEncabezado(); item.IdProtocolo = IdProtocolo; item.IdEfector = IdEfector; item.Apellido = Apellido; item.Nombre = Nombre; item.Edad = Edad; item.UnidadEdad = UnidadEdad; item.FechaNacimiento = FechaNacimiento; item.Sexo = Sexo; item.NumeroDocumento = NumeroDocumento; item.Fecha = Fecha; item.Fecha1 = Fecha1; item.Domicilio = Domicilio; item.Hc = Hc; item.Prioridad = Prioridad; item.Origen = Origen; item.Numero = Numero; item.Hiv = Hiv; item.Solicitante = Solicitante; item.Sector = Sector; item.Sala = Sala; item.Cama = Cama; item.Embarazo = Embarazo; item.EfectorSolicitante = EfectorSolicitante; item.IdSolicitudScreening = IdSolicitudScreening; item.FechaRecibeScreening = FechaRecibeScreening; item.ObservacionesResultados = ObservacionesResultados; item.TipoMuestra = TipoMuestra; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdProtocolo,int IdEfector,string Apellido,string Nombre,int Edad,string UnidadEdad,string FechaNacimiento,string Sexo,int NumeroDocumento,string Fecha,DateTime Fecha1,string Domicilio,int Hc,string Prioridad,string Origen,string Numero,bool? Hiv,string Solicitante,string Sector,string Sala,string Cama,string Embarazo,string EfectorSolicitante,int? IdSolicitudScreening,DateTime? FechaRecibeScreening,string ObservacionesResultados,string TipoMuestra) { LabTempResultadoEncabezado item = new LabTempResultadoEncabezado(); item.MarkOld(); item.IsLoaded = true; item.IdProtocolo = IdProtocolo; item.IdEfector = IdEfector; item.Apellido = Apellido; item.Nombre = Nombre; item.Edad = Edad; item.UnidadEdad = UnidadEdad; item.FechaNacimiento = FechaNacimiento; item.Sexo = Sexo; item.NumeroDocumento = NumeroDocumento; item.Fecha = Fecha; item.Fecha1 = Fecha1; item.Domicilio = Domicilio; item.Hc = Hc; item.Prioridad = Prioridad; item.Origen = Origen; item.Numero = Numero; item.Hiv = Hiv; item.Solicitante = Solicitante; item.Sector = Sector; item.Sala = Sala; item.Cama = Cama; item.Embarazo = Embarazo; item.EfectorSolicitante = EfectorSolicitante; item.IdSolicitudScreening = IdSolicitudScreening; item.FechaRecibeScreening = FechaRecibeScreening; item.ObservacionesResultados = ObservacionesResultados; item.TipoMuestra = TipoMuestra; item.Save(UserName); } } }
saludnqn/consultorio
DalSic/generated/LabTempResultadoEncabezadoController.cs
C#
mit
7,089
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Cosmosdb::Mgmt::V2015_04_08 module Models # # An Azure Cosmos DB MongoDB database. # class MongoDBDatabase < Resource include MsRestAzure # @return [String] Name of the Cosmos DB MongoDB database attr_accessor :mongo_dbdatabase_id # # Mapper for MongoDBDatabase class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'MongoDBDatabase', type: { name: 'Composite', class_name: 'MongoDBDatabase', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, mongo_dbdatabase_id: { client_side_validation: true, required: true, serialized_name: 'properties.id', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_cosmosdb/lib/2015-04-08/generated/azure_mgmt_cosmosdb/models/mongo_dbdatabase.rb
Ruby
mit
2,741
<?php namespace r7r\ste; /** * Class Calc contains static methods needed by <ste:calc /> */ class Calc { private function __construct() { } /** * Parse a mathematical expression with the shunting yard algorithm (https://en.wikipedia.org/wiki/Shunting-yard_algorithm) * * We could also just eval() the $infix_math code, but this is much cooler :-D (Parser inception) * @param string $infix_math * @return array * @throws RuntimeError */ private static function shunting_yard(string $infix_math): array { $operators = [ "+" => ["l", 2], "-" => ["l", 2], "*" => ["l", 3], "/" => ["l", 3], "^" => ["r", 4], "_" => ["r", 5], "(" => ["", 0], ")" => ["", 0] ]; preg_match_all("/\s*(?:(?:[+\\-\\*\\/\\^\\(\\)])|(\\d*[\\.]?\\d*))\\s*/s", $infix_math, $tokens, PREG_PATTERN_ORDER); $tokens_raw = array_filter(array_map('trim', $tokens[0]), function ($x) { return ($x === "0") || (!empty($x)); }); $output_queue = []; $op_stack = []; $lastpriority = null; /* Make - unary, if neccessary */ $tokens = []; foreach ($tokens_raw as $token) { $priority = isset($operators[$token]) ? $operators[$token][1] : -1; if (($token == "-") && (($lastpriority === null) || ($lastpriority >= 0))) { $priority = $operators["_"][1]; $tokens[] = "_"; } else { $tokens[] = $token; } $lastpriority = $priority; } while (!empty($tokens)) { $token = array_shift($tokens); if (is_numeric($token)) { $output_queue[] = $token; } elseif ($token == "(") { $op_stack[] = $token; } elseif ($token == ")") { $lbr_found = false; while (!empty($op_stack)) { $op = array_pop($op_stack); if ($op == "(") { $lbr_found = true; break; } $output_queue[] = $op; } if (!$lbr_found) { throw new RuntimeError("Bracket mismatch."); } } elseif (!isset($operators[$token])) { throw new RuntimeError("Invalid token ($token): Not a number, bracket or operator. Stop."); } else { $priority = $operators[$token][1]; if ($operators[$token][0] == "l") { while ( !empty($op_stack) && $priority <= $operators[$op_stack[count($op_stack)-1]][1] ) { $output_queue[] = array_pop($op_stack); } } else { while ( !empty($op_stack) && $priority < $operators[$op_stack[count($op_stack)-1]][1] ) { $output_queue[] = array_pop($op_stack); } } $op_stack[] = $token; } } while (!empty($op_stack)) { $op = array_pop($op_stack); if ($op == "(") { throw new RuntimeError("Bracket mismatch..."); } $output_queue[] = $op; } return $output_queue; } /** * @param array $array * @return array * @throws RuntimeError */ private static function pop2(array &$array): array { $rv = [array_pop($array), array_pop($array)]; if (array_search(null, $rv, true) !== false) { throw new RuntimeError("Not enough numbers on stack. Invalid formula."); } return $rv; } /** * @param array $rpn A mathematical expression in reverse polish notation * @return int|float * @throws RuntimeError */ private static function calc_rpn(array $rpn) { $stack = []; foreach ($rpn as $token) { switch ($token) { case "+": list($b, $a) = self::pop2($stack); $stack[] = $a + $b; break; case "-": list($b, $a) = self::pop2($stack); $stack[] = $a - $b; break; case "*": list($b, $a) = self::pop2($stack); $stack[] = $a * $b; break; case "/": list($b, $a) = self::pop2($stack); $stack[] = $a / $b; break; case "^": list($b, $a) = self::pop2($stack); $stack[] = pow($a, $b); break; case "_": $a = array_pop($stack); if ($a === null) { throw new RuntimeError("Not enough numbers on stack. Invalid formula."); } $stack[] = -$a; break; default: $stack[] = $token; break; } } return array_pop($stack); } /** * Calculate a simple mathematical expression. Supported operators are +, -, *, /, ^. * You can use ( and ) to group expressions together. * * @param string $expr * @return float|int * @throws RuntimeError */ public static function calc(string $expr) { return self::calc_rpn(self::shunting_yard($expr)); } }
kch42/ste
src/ste/Calc.php
PHP
mit
5,679
var EVENTS, ProxyClient, _r, bindSocketSubscriber, getSystemAddresses, io, mazehallGridRegister; _r = require('kefir'); io = require('socket.io-client'); EVENTS = require('./events'); ProxyClient = function(server, hosts) { server.on('listening', function() { return bindSocketSubscriber(server, hosts); }); return this; }; bindSocketSubscriber = function(server, hosts) { var socket; socket = io.connect(process.env.MAZEHALL_PROXY_MASTER || 'ws://localhost:3300/proxy'); socket.on(EVENTS.HELLO, function() { return mazehallGridRegister(server, socket, hosts); }); socket.on(EVENTS.MESSAGE, function(x) { return console.log('proxy-message: ' + x); }); socket.on(EVENTS.ERROR, function(err) { return console.error(err); }); socket.on('connect_timeout', function() { return console.log('proxy-connection: timeout'); }); socket.on('reconnect_failed', function() { return console.log('proxy-connection: couldn’t reconnect within reconnectionAttempts'); }); }; module.exports = ProxyClient; /* helper */ getSystemAddresses = function() { var address, addresses, interfaces, k, k2, os; os = require('os'); interfaces = os.networkInterfaces(); addresses = []; for (k in interfaces) { for (k2 in interfaces[k]) { address = interfaces[k][k2]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } return addresses; }; mazehallGridRegister = function(server, socket, hosts) { var addresses, port; port = server.address().port; addresses = getSystemAddresses(); hosts = hosts || ['localhost']; if (!Array.isArray(hosts)) { hosts = [hosts]; } return hosts.forEach(function(host) { var msg; msg = { target: host, port: port, addresses: addresses }; return socket.emit(EVENTS.REGISTER, msg); }); };
mazehall/mazehall-proxy
lib/client.js
JavaScript
mit
1,895
var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; item["No"] = index; item["Sales"] = order._id.sales; item["Januari"] = order.jan.toFixed(2); item["Februari"] = order.feb.toFixed(2); item["Maret"] = order.mar.toFixed(2); item["April"] = order.apr.toFixed(2); item["Mei"] = order.mei.toFixed(2); item["Juni"] = order.jun.toFixed(2); item["Juli"] = order.jul.toFixed(2); item["Agustus"] = order.agu.toFixed(2); item["September"] = order.sep.toFixed(2); item["Oktober"] = order.okt.toFixed(2); item["November"] = order.nov.toFixed(2); item["Desember"] = order.des.toFixed(2); item["Total"] = order.totalOrder.toFixed(2); data.push(item); } var options = { "No": "number", "Sales": "string", "Januari": "string", "Februari": "string", "Maret": "string", "April": "string", "Mei": "string", "Juni": "string", "Juli": "string", "Agustus": "string", "September": "string", "Oktober": "string", "November": "string", "Desember": "string", "Total": "string", }; response.xls(`Sales Monthly Report.xlsx`, data, options); } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; /* SUKSES var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; if(!query.page){ query.page=1; }if(!query.size){ query.size=20; } manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; var firstname = ""; var lastname = ""; if (order.firstname) firstname = order.firstname; if (order.lastname) lastname = order.lastname; item["No"] = index; item["Nomor Sales Contract"] = order.salesContractNo; item["Tanggal Surat Order Produksi"] = moment(new Date(order._createdDate)).format(dateFormat); item["Nomor Surat Order Produksi"] = order.orderNo; item["Jenis Order"] = order.orderType; item["Jenis Proses"] = order.processType; item["Buyer"] = order.buyer; item["Tipe Buyer"] = order.buyerType; item["Jumlah Order"] = order.orderQuantity; item["Satuan"] = order.uom; item["Acuan Warna / Desain"] = order.colorTemplate; item["Warna Yang Diminta"] = order.colorRequest; item["Jenis Warna"] = order.colorType; item["Jumlah"] = order.quantity; item["Satuan Detail"] = order.uomDetail; item["Tanggal Delivery"] = moment(new Date(order.deliveryDate)).format(dateFormat); item["Staff Penjualan"] = `${firstname} ${lastname}`; item["Status"] = order.status; item["Detail"] = order.detail; data.push(item); } var options = { "No": "number", "Nomor Sales Contract": "string", "Tanggal Surat Order Produksi": "string", "Nomor Surat Order Produksi": "string", "Jenis Order": "string", "Jenis Proses": "string", "Buyer": "string", "Tipe Buyer": "string", "Jumlah Order": "number", "Satuan": "string", "Acuan Warna / Desain": "string", "Warna Yang Diminta": "string", "Jenis Warna": "string", "Jumlah": "number", "Satuan Detail": "string", "Tanggal Delivery": "string", "Staff Penjualan": "string", "Status": "string", "Detail": "string" }; response.xls(`Sales Monthly Report.xlsx`, data, options); // } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; */
danliris/dl-production-webapi
src/routers/v1/sales/reports/sales-monthly-report-router.js
JavaScript
mit
9,361
<?php namespace Audith\Providers\Nexway\Data\Response\OrderApi; /** * @author Shahriyar Imanov <shehi@imanov.me> */ class getCrossUpSell extends \Audith\Providers\Nexway\Data\Response\OrderApi { /** * @var array * @see http://wsdocs.nexway.com/APIGuide/index.html?url=responsecodetype1.html */ public static $exceptionCodeMapping = array( 100 => "ProductListIsMissingException", 110 => "ProductRefIsMissingException", 111 => "ProductRefIsInvalidException", 120 => "QuantityIsMissingException", 121 => "QuantityIsNotValidException", 130 => "LanguageIsMissingException", 131 => "LanguageIsNotValidException", 1000 => "InternalErrorException", 1010 => "ProductReferenceDoesntExistException" ); /** * @var getCrossUpSell\productsReturn[] */ public $productsReturn = array(); /** * @var integer */ public $responseCode; /** * @var string */ public $responseMessage; }
AudithSoftworks/Nexway-Merchant-API-PHP-Client
src/Audith/Providers/Nexway/Data/Response/OrderApi/getCrossUpSell.php
PHP
mit
1,028
package pl.edu.mimuw.cloudatlas.agent.modules.network; import java.net.InetAddress; import pl.edu.mimuw.cloudatlas.agent.modules.framework.SimpleMessage; public final class SendDatagramMessage extends SimpleMessage<byte[]> { private InetAddress target; private int port; public SendDatagramMessage(byte[] content, InetAddress target, int port) { super(content); this.target = target; this.port = port; } public InetAddress getTarget() { return target; } public int getPort() { return port; } }
konradxyz/cloudatlas
src/pl/edu/mimuw/cloudatlas/agent/modules/network/SendDatagramMessage.java
Java
mit
518