repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
butla/PyDAS
data_acquisition/cf_app_utils/logs.py
1189
""" Delivers standard logging configuration for CloudFoundry app. """ import logging import sys NEGATIVE_LEVEL = logging.ERROR def configure_logging(log_level): """ Sets up the logging so that only the negative messages go to error output. Rest goes to standard output. This is useful when looking through Cloud Foundry logs. :param int log_level: One of the log levels from `logging` module. """ log_formatter = logging.Formatter('%(levelname)s:%(name)s: %(message)s') positive_handler = logging.StreamHandler(sys.stdout) positive_handler.addFilter(_PositiveMessageFilter()) positive_handler.setFormatter(log_formatter) negative_handler = logging.StreamHandler(sys.stderr) negative_handler.setLevel(NEGATIVE_LEVEL) negative_handler.setFormatter(log_formatter) root_logger = logging.getLogger() root_logger.setLevel(log_level) root_logger.addHandler(positive_handler) root_logger.addHandler(negative_handler) class _PositiveMessageFilter(logging.Filter): """ Logging filter that allows only positive messages to pass """ def filter(self, record): return record.levelno < NEGATIVE_LEVEL
mit
techird/ruler
src/render.js
8122
/** * @fileOverview * * 渲染 Ruler 对象中每一步产生的结果 * * @author: techird * @copyright: Baidu FEX, 2014 */ Ruler.defaultStyle = { 'point-fill': 'gray', 'point-stroke': null, 'point-stroke-width': 0, 'point-size': 3, 'point-label': '#666', 'draggable-point-fill': 'white', 'draggable-point-stroke': 'red', 'draggable-point-stroke-width': 4, 'draggable-point-size': 4, 'draggable-point-label': '#666', 'path-stroke': 'gray', 'path-stroke-width': 1, 'path-label': false }; Ruler.hotStyle = { 'point-fill': 'blue', 'point-stroke': 'rgba(200, 100, 100, .3)', 'point-stroke-width': 6, 'point-size': 3, 'draggable-point-fill': 'white', 'draggable-point-stroke': 'red', 'draggable-point-stroke-width': 4, 'draggable-point-size': 6, 'path-stroke': 'blue', 'path-stroke-width': 1, 'path-hightlight': 'rgba(200, 100, 100, .3)', 'path-hightlight-width': 6, 'path-label': '#999' }; Ruler.hotPrevStyle = { 'point-stroke': 'rgba(150, 150, 150, .4)', 'point-stroke-width': 6, 'draggable-point-stroke': 'rgba(150, 150, 150, .4)', 'draggable-point-size': 6, 'path-stroke': 'gray', 'path-stroke-width': 1, 'path-hightlight': 'rgba(150, 150, 150, .3)', 'path-hightlight-width': 6 }; function renderPoint(point, step, ctx, style) { var draggable = step.name == 'define_point'; var size = draggable ? style['draggable-point-size'] : style['point-size']; var fill = draggable ? style['draggable-point-fill'] : style['point-fill']; var stroke = draggable ? style['draggable-point-stroke'] : style['point-stroke']; var strokeWidth = draggable ? style['draggable-point-stroke-width'] : style['point-stroke-width']; var label = style['point-label']; ctx.beginPath(); ctx.arc(point.x, point.y, size, 0, Math.PI * 2); ctx.closePath(); if (stroke) { ctx.strokeStyle = stroke; ctx.lineWidth = strokeWidth; ctx.stroke(); } if (fill) { ctx.fillStyle = fill; ctx.fill(); } if (label && step.resultName) { ctx.font = '14px Arial'; ctx.fillStyle = label; ctx.textBaseline = 'middle'; ctx.fillText(step.resultName, point.x + 10, point.y); } } function renderLine(line, step, ctx, style, bounding) { var top = bounding[0]; var right = bounding[1]; var bottom = bounding[2]; var left = bounding[3]; ctx.beginPath(); if (!Ruler.isZero(line.dx)) { ctx.moveTo(left, line.getYForX(left)); ctx.lineTo(right, line.getYForX(right)); } else { ctx.moveTo(line.x1, top); ctx.lineTo(line.x1, bottom); } var label = style['path-label']; if (label && step.resultName) { var xm = (line.x1 + line.x2) / 2; var ym = (line.y1 + line.y2) / 2; var dx = line.dx; var dy = line.dy; var dr = Math.sqrt(dx * dx + dy * dy); var r = 20; var x = xm + r * dy / dr; var y = ym + r * dx / dr; labelPath(ctx, step, x, y, label); } stylizedPath(ctx, style); } function renderCircle(circle, step, ctx, style) { ctx.beginPath(); ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2); ctx.closePath(); var label = style['path-label']; if (label && step.resultName) { var cx = circle.x; var cy = circle.y; var r = circle.r + 20; var x = cx + r * 0.717; var y = cy - r * 0.717; labelPath(ctx, step, x, y, label); } stylizedPath(ctx, style); } function labelPath(ctx, step, x, y, style) { ctx.font = '12px Arial'; ctx.fillStyle = style; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(step.resultName, x, y); } function stylizedPath(ctx, style) { var stroke = style['path-stroke']; var strokeWidth = style['path-stroke-width']; var highlight = style['path-hightlight']; var highlightWidth = style['path-hightlight-width']; if (highlight) { ctx.strokeStyle = highlight; ctx.lineWidth = highlightWidth; ctx.stroke(); } if (stroke) { ctx.strokeStyle = stroke; ctx.lineWidth = strokeWidth; ctx.stroke(); } } var rendererMap = { 'Point': renderPoint, 'Line': renderLine, 'Circle': renderCircle }; var pseudos = { 'default': 'defaultStyle', 'hot': 'hotStyle', 'prev-hot': 'hotPrevStyle' }; function addStyle(ruler, selector, defines) { defines = parseStyleDefines(defines); var pseudoName = pseudos[selector.toLowerCase().split('::')[1]]; if (pseudoName) { ruler[pseudoName] = defines; } else { var parts = selector.split(':'); var name = parts[0]; if (parts.length == 2) { pseudoName = pseudos[parts[1]]; } var step = ruler.findStep(name); if (!step) return; if (pseudoName) { step[pseudoName] = defines; } else { step.style = extend({}, step.style, defines); } } } function parseStyleDefines(defines) { var result = {}; function match(all, name, value) { var intValue = parseInt(value, 10); result[name] = isNaN(intValue) ? value : intValue; } String(defines).replace(/\s+([\w-]+)\:\s*([\w\d#\(\)\.]+)/g, match); return result; } Ruler.prototype.loadStyleSheet = function(text) { var ruler = this; function match(all, selectors, defines) { selectors.split(',').forEach(function(selector) { addStyle(ruler, selector.trim(), defines); }); } // clear up style var cleanTargets = [this].concat(this.steps); cleanTargets.forEach(function(target) { target.style = null; target.defaultStyle = null; target.hotStyle = null; target.hotPrevStyle = null; }); String(text).replace(/^([^()\n]+?)(\{[^]+?\})/gm, match); }; Ruler.prototype.render = function(bounding) { var canvas = this.canvas; if (!canvas) throw new Error('ruler canvas missing'); if (!this.canvasOffset) { this.canvasOffset = [canvas.width / 2, canvas.height / 2]; } var ctx = canvas.getContext('2d'); var ruler = this; var offset = this.canvasOffset; canvas.width = canvas.width; ctx.save(); ctx.translate.apply(ctx, offset); bounding = [-offset[1], canvas.width - offset[0], canvas.height - offset[1], -offset[0]]; var hotStep = this.hotStep, hotPrevs = hotStep && hotStep.prevs; if (hotPrevs && hotPrevs[0].resultType == TYPE_POINTS) { hotPrevs = hotPrevs[0].prevs; } var renderSteps = this.getAvailableSteps(); renderSteps.sort(function(a, b) { var ah = a.result().hotPriority || 99999; var bh = b.result().hotPriority || 99999; if (a == hotStep) ah = 0; if (hotPrevs && hotPrevs.indexOf(a) != -1) ah = 1; if (b == hotStep) bh = 0; if (hotPrevs && hotPrevs.indexOf(b) != -1) bh = 1; return bh - ah; }); renderSteps.forEach(function(step) { var result = step.result(); var style = extend({}, Ruler.defaultStyle, ruler.defaultStyle, step.style); if (hotStep == step) { style = extend(style, Ruler.hotStyle, ruler.hotStyle, step.hotStyle); } else if (hotPrevs && hotPrevs.indexOf(step) != -1) { style = extend(style, Ruler.hotPrevStyle, ruler.hotPrevs, step.hotPrevStyle); } var renderer = rendererMap[step.resultType]; if (renderer) { ctx.save(); renderer(result, step, ctx, style, bounding); ctx.restore(); } }); ctx.restore(); }; Ruler.prototype.getDrawingPosition = function(clientX, clientY) { var canvas = this.canvas; var rect = canvas.getBoundingClientRect(); var offset = this.canvasOffset || [0, 0]; var tx = offset[0]; var ty = offset[1]; return { x: clientX - rect.left - tx, y: clientY - rect.top - ty }; };
mit
graphql/graphql-js
src/__tests__/starWarsData.ts
3290
/** * These are types which correspond to the schema. * They represent the shape of the data visited during field resolution. */ export interface Character { id: string; name: string; friends: ReadonlyArray<string>; appearsIn: ReadonlyArray<number>; } export interface Human { type: 'Human'; id: string; name: string; friends: ReadonlyArray<string>; appearsIn: ReadonlyArray<number>; homePlanet?: string; } export interface Droid { type: 'Droid'; id: string; name: string; friends: ReadonlyArray<string>; appearsIn: ReadonlyArray<number>; primaryFunction: string; } /** * This defines a basic set of data for our Star Wars Schema. * * This data is hard coded for the sake of the demo, but you could imagine * fetching this data from a backend service rather than from hardcoded * JSON objects in a more complex demo. */ const luke: Human = { type: 'Human', id: '1000', name: 'Luke Skywalker', friends: ['1002', '1003', '2000', '2001'], appearsIn: [4, 5, 6], homePlanet: 'Tatooine', }; const vader: Human = { type: 'Human', id: '1001', name: 'Darth Vader', friends: ['1004'], appearsIn: [4, 5, 6], homePlanet: 'Tatooine', }; const han: Human = { type: 'Human', id: '1002', name: 'Han Solo', friends: ['1000', '1003', '2001'], appearsIn: [4, 5, 6], }; const leia: Human = { type: 'Human', id: '1003', name: 'Leia Organa', friends: ['1000', '1002', '2000', '2001'], appearsIn: [4, 5, 6], homePlanet: 'Alderaan', }; const tarkin: Human = { type: 'Human', id: '1004', name: 'Wilhuff Tarkin', friends: ['1001'], appearsIn: [4], }; const humanData: { [id: string]: Human } = { [luke.id]: luke, [vader.id]: vader, [han.id]: han, [leia.id]: leia, [tarkin.id]: tarkin, }; const threepio: Droid = { type: 'Droid', id: '2000', name: 'C-3PO', friends: ['1000', '1002', '1003', '2001'], appearsIn: [4, 5, 6], primaryFunction: 'Protocol', }; const artoo: Droid = { type: 'Droid', id: '2001', name: 'R2-D2', friends: ['1000', '1002', '1003'], appearsIn: [4, 5, 6], primaryFunction: 'Astromech', }; const droidData: { [id: string]: Droid } = { [threepio.id]: threepio, [artoo.id]: artoo, }; /** * Helper function to get a character by ID. */ function getCharacter(id: string): Promise<Character | null> { // Returning a promise just to illustrate that GraphQL.js supports it. return Promise.resolve(humanData[id] ?? droidData[id]); } /** * Allows us to query for a character's friends. */ export function getFriends( character: Character, ): Array<Promise<Character | null>> { // Notice that GraphQL accepts Arrays of Promises. return character.friends.map((id) => getCharacter(id)); } /** * Allows us to fetch the undisputed hero of the Star Wars trilogy, R2-D2. */ export function getHero(episode: number): Character { if (episode === 5) { // Luke is the hero of Episode V. return luke; } // Artoo is the hero otherwise. return artoo; } /** * Allows us to query for the human with the given id. */ export function getHuman(id: string): Human | null { return humanData[id]; } /** * Allows us to query for the droid with the given id. */ export function getDroid(id: string): Droid | null { return droidData[id]; }
mit
alaingilbert/ttdashboard
server/gatherer/doc/js/scripts.js
918
var scrollDown = false; document.addEventListener('mousewheel', function (evt) { var menu = document.getElementById('menu'); // Scroll down if (evt.wheelDelta < 0) { if (!scrollDown) { menu.style.position = 'absolute'; menu.style.top = (window.scrollY + menu.offsetTop) + 'px'; } scrollDown = true; if (window.scrollY + window.innerHeight > menu.offsetTop + menu.offsetHeight) { menu.style.position = 'fixed'; menu.style.top = ''; menu.style.bottom = '0px'; } // Scroll up } else { if (scrollDown) { menu.style.position = 'absolute'; menu.style.top = (window.scrollY + menu.offsetTop) + 'px'; } scrollDown = false; if (window.scrollY < menu.offsetTop) { menu.style.position = 'fixed'; menu.style.top = '0px'; menu.style.bottom = ''; } } }, false);
mit
haveagit/TranslatorDemo
Assets/MRDesignLab/HUX/Scripts/Input/InputSourceTouch6D.cs
1548
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; using System.Collections; using HUX; public class InputSourceTouch6D : InputSourceSixDOFBase { // SixDOF comes from InputSourceSixDOFRay public override Vector3 position { get { return InputSources.Instance.netMouse.Connected() ? InputSources.Instance.sixDOFRay.controllerGOoffset.transform.position : InputSources.Instance.sixDOFRay.position; } } public override Quaternion rotation { get { return InputSources.Instance.netMouse.Connected() ? InputSources.Instance.sixDOFRay.controllerGOoffset.transform.rotation : InputSources.Instance.sixDOFRay.rotation; } } // Buttons come from InputSourceNetMouse public override bool buttonSelectPressed { get { return InputSources.Instance.netMouse.Connected() ? (InputSources.Instance.netMouse.buttonSelectPressed || InputSources.Instance.netMouse.buttonLeftPressed) : (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.LeftArrow)); } } public override bool buttonMenuPressed { get { return InputSources.Instance.netMouse.Connected() ? InputSources.Instance.netMouse.buttonDownArrowPressed : Input.GetKey(KeyCode.DownArrow); } } public override bool buttonAltSelectPressed { get { return InputSources.Instance.netMouse.Connected() ? InputSources.Instance.netMouse.buttonUpArrowPressed : false; } } }
mit
DJCordhose/react-workshop
code/sandbox/typescript-react/src/store.ts
427
import { createStore, combineReducers, applyMiddleware } from "redux"; import { reducer as greetingReducer } from "./greeting"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; export type State = { greeting: string; }; const store = createStore( combineReducers({ greeting: greetingReducer }), composeWithDevTools(applyMiddleware(thunk)) ); export default store;
mit
Flagbit/Magento-FACTFinder
src/shell/factfinder.php
5894
<?php require_once 'abstract.php'; class Mage_Shell_FactFinder extends Mage_Shell_Abstract { const EXPORT_ALL_TYPES_FOR_STORE = 'exportAllTypesForStore'; const EXPORT_ALL_TYPES_FOR_ALL_STORES = 'exportAllTypesForAllStores'; const EXPORT_STORE_PRICE = 'exportStorePrice'; const EXPORT_STORE_STOCK = 'exportStoreStock'; const EXPORT_STORE = 'exportStore'; const EXPORT_CMS_FOR_STORE = 'exportCmsForStore'; /** * Mage_Shell_FactFinder constructor. */ public function __construct() { parent::__construct(); // Additionally add module autoloader $autoloaderClass = new FACTFinder_Core_Model_Autoloader(); $autoloaderClass->addAutoloader(new Varien_Event_Observer()); } /** * @return void */ public function run() { if ($this->getArg('exportAll') || $this->getArg('exportall')) { $this->exportAll(); } elseif ($this->getArg(self::EXPORT_STORE)) { $this->exportStore(); } elseif ($this->getArg(self::EXPORT_STORE_PRICE)) { $this->exportStorePrice(); } elseif ($this->getArg(self::EXPORT_STORE_STOCK)) { $this->exportStoreStock(); } elseif ($this->getArg(self::EXPORT_ALL_TYPES_FOR_STORE)) { $this->exportAllTypesForStore(); } elseif ($this->getArg(self::EXPORT_ALL_TYPES_FOR_ALL_STORES)) { $this->exportAllTypesForAllStores(); } elseif ($this->getArg(self::EXPORT_CMS_FOR_STORE)) { $this->exportCmsForStore(); } else { echo $this->usageHelp(); } } /** * Retrieve Usage Help Message * * @return string */ public function usageHelp() { return <<<USAGE Usage: php factfinder.php -- [options] --exportAll Export products for every store --exportStore <storeId> Export Product CSV for store --exportStorePrice <storeId> Export Price CSV for store --exportStoreStock <storeId> Export Stock CSV for store --exportAllTypesForStore <storeId> Export Stock, Price and Products for store --exportAllTypesForAllStores Export Stock, Price and Products for all stores --exportCmsForStore <storeId> Export CMS Sites for store exportall Export Product CSV for all stores help Show this help message <storeId> Id of the store you want to export USAGE; } /** * Export all types for specified store * * @return void */ private function exportAllTypesForStore() { if (!is_numeric($this->getArg(self::EXPORT_ALL_TYPES_FOR_STORE))) { echo $this->usageHelp(); return; } foreach (Mage::helper('factfinder/export')->getExportTypes() as $type => $model) { $file = $model->saveExport($this->getArg(self::EXPORT_ALL_TYPES_FOR_STORE)); printf("Successfully generated %s export to: %s\n", $type, $file); } } /** * Export all types for all stores * * @return void */ private function exportAllTypesForAllStores() { foreach (Mage::helper('factfinder/export')->getExportTypes() as $type => $model) { $files = $model->saveAll(); foreach ($files as $file) { printf("Successfully generated %s export to: %s\n", $type, $file); } } } /** * Export stock for store * * @return void */ private function exportStoreStock() { if (!is_numeric($this->getArg(self::EXPORT_STORE_STOCK))) { echo $this->usageHelp(); return; } $file = Mage::getModel('factfinder/export_type_stock')->saveExport($this->getArg(self::EXPORT_STORE_STOCK)); printf("Successfully generated stock export to: %s\n", $file); } /** * Export price for store * * @return void */ private function exportStorePrice() { if (!is_numeric($this->getArg(self::EXPORT_STORE_PRICE))) { echo $this->usageHelp(); return; } $file = Mage::getModel('factfinder/export_type_price')->saveExport($this->getArg(self::EXPORT_STORE_PRICE)); printf("Successfully generated price export to: %s\n", $file); } /** * Export products for store * * @return void */ private function exportStore() { if (!is_numeric($this->getArg(self::EXPORT_STORE))) { echo $this->usageHelp(); return; } $file = Mage::getModel('factfinder/export_type_product')->saveExport($this->getArg(self::EXPORT_STORE)); printf("Successfully generated export to: %s\n", $file); } /** * Export products for all stores * * @return void */ private function exportAll() { $files = Mage::getModel('factfinder/export_type_product')->saveAll(); echo "Successfully generated the following files:\n"; foreach ($files as $file) { echo $file . "\n"; } } /** * Export CMS pages for store * * @return void */ private function exportCmsForStore() { if (!is_numeric($this->getArg(self::EXPORT_CMS_FOR_STORE))) { echo $this->usageHelp(); return; } try { $model = Mage::getModel('factfinder/export_config')->getExportModel('cms'); $file = $model->saveExport($this->getArg(self::EXPORT_CMS_FOR_STORE)); printf("Successfully generated export to: %s\n", $file); } catch (Exception $e) { printf($e->getMessage()); } } } $shell = new Mage_Shell_FactFinder(); $shell->run();
mit
ozonx/ozon
src/qt/bitcoinstrings.cpp
13136
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" " %s\n" "It is recommended you use the following random password:\n" "rpcuser=Ozoncoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Ozoncoin Alert\" admin@foo." "com\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "Ozoncoin version"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or Ozoncoind"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "Ozoncoin"), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: Ozoncoin.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: Ozoncoind.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 15714 or testnet: 25714)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using internet relay chat (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Stake your coins to support network and gain reward (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Sync time with other nodes. Disable if time on your system is precise e.g. " "syncing with NTP (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Sync checkpoints policy (default: strict)"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Detach block and address databases. Increases shutdown time (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "" "When creating transactions, ignore inputs with value less than this " "(default: 0.01)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Enforce transaction scripts to use canonical PUSH operators (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 2500, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: " "27000)"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:" "@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. Ozoncoin is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error initializing database environment %s! To recover, BACKUP THAT " "DIRECTORY, then remove everything from it except for wallet.dat."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to sign checkpoint, wrong checkpointkey?\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading blkindex.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Ozoncoin"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Ozoncoin to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot initialize keypool"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Importing blockchain data file."), QT_TRANSLATE_NOOP("bitcoin-core", "Importing bootstrap blockchain data file."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error: could not start node"), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. Ozoncoin is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction "), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds "), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed "), QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected. This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Ozoncoin will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "WARNING: syncronized checkpoint violation detected, but skipped!"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "WARNING: Invalid checkpoint found! Displayed transactions may not be " "correct! You may need to upgrade, or notify developers."), };
mit
gvonline/gvo_helper_web
quote/index.php
8174
<?php require_once('../assets/common.php'); if (isset($_POST['server']) && isset($_POST['city_name'])) { $server = isset($_POST['server']) ? trim($_POST['server']) : ''; $cityName = isset($_POST['city_name']) ? trim($_POST['city_name']) : ''; $cityStatus = isset($_POST['city_status']) ? trim($_POST['city_status']) : ''; $itemName = isset($_POST['item_name']) ? trim($_POST['item_name']) : ''; $saleQuote = isset($_POST['sale_quote']) ? trim($_POST['sale_quote']) : ''; $saleStatus = isset($_POST['sale_status']) ? trim($_POST['sale_status']) : ''; $ttl = 60 * 60 * 3; // 3시간 후 자동 삭제 $redis = NULL; $db = new Database; if (!in_array($cityName, $db->getHasTraderCities())) { exit(); } unset($_POST['server']); $temp = implode('', $_POST); if (preg_match('/[:;<>&_a-zA-Z]/', $temp) != 0) { exit(); } switch ($server) { case 'eirene': $redis = new Redis(); $redis->connect('127.0.0.1','6379', 1, NULL, 100); break; case 'polaris': $redis = new Redis(); $redis->connect('127.0.0.1','6380', 1, NULL, 100); break; case 'helen': $redis = new Redis(); $redis->connect('127.0.0.1','6381', 1, NULL, 100); break; default: break; } if (is_null($redis)) { exit(); } if ((strlen($cityName) != 0) && (strlen($cityStatus) == 0)) { $key = '도시:'.$cityName; $value = unserialize($redis->get($key)); if (!is_array($value)) { $value = serialize(array('TIME'=>0, 'NAME'=>$cityName, 'SALESTATUS'=>'')); $redis->setex($key, $ttl, $value); } } if ((strlen($cityName) != 0) && (preg_match('/(남아돌고|대폭락|대폭등|잘 팔려|잘팔리고|잘 팔리고|어서 오세요)/', $cityStatus) != 0)) { $key = '도시:'.$cityName; $value = serialize(array('TIME'=>time(), 'NAME'=>$cityName, 'SALESTATUS'=>$cityStatus)); $redis->setex($key, $ttl, $value); } if ((strlen($cityName) != 0) && (strlen($itemName) != 0) && is_numeric($saleQuote) && is_numeric($saleStatus)) { $key = $cityName.':'.$itemName; $value = serialize(array('TIME'=>time(), 'NAME'=>$itemName, 'SALEQUOTE'=>$saleQuote, 'SALESTATUS'=>$saleStatus)); $redis->setex($key, $ttl, $value); } $redis->close(); exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title>GVOnline Quote Helper :: 시세 도우미</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div class="container" style="padding-bottom: 10px"> <h2>GVOnline Quote Helper :: 시세 도우미</h2> </div> <div class="container" style="padding-bottom: 10px"> <div class="center-block"> <p>이 프로그램은 게임화면을 분석하여 <strong class="text-success">도시명</strong>, <strong class="text-primary">교역소 주인의 대화</strong>, <strong class="text-danger">교역품명 및 매각시세(인근도시시세 포함)</strong> 정보를 수집합니다.</p> <p>수집은 상기 정보를 제외한 어떠한 내용도 수집하지 않습니다.</p> <p>과거 DHOAgent 와 유사한 동작을 하는 프로그램입니다.<br />다른 점은 이 프로그램은 자동으로 수집만 하며 실제 자료는 <a href="http://gvonline.ga/">이곳 Site</a> 에서 확인 하게 됩니다.<br />모바일로 확인할 수도 있으며, 프로그램이 없어도 확인은 가능합니다.</p> <p>일반 네비 프로그램 처럼 게임 실행 시 아래 파일을 다운로드 받아 실행하면 시세 데이터는 자동으로 수집됩니다.</p> <p>Windows 10 기준으로 제작되어 있으며 아직은 많은 기간 테스트가 필요합니다.</p> <p><br /></p> </div> <div class="center-block"> <h4>1. 다운로드 화면</h4> <p><img src="/images/image001.jpg" style="border: 1px solid #000;" /></p> <p>아래 <a href="https://github.com/gvonline/gvo_quote/releases/latest" target="_blank"><strong class="text-warning">[프로그램 다운로드]</strong></a> 버튼을 클릭후 GitHub 사이트에서 최신버전을 다운로드 해 주시기 바랍니다.<br /> <strong class="text-danger">(GitHub 사이트가 아닌 다른곳에서 받으셨다면 프로그램이 변조 되었을 가능성이 있으니 꼭 이곳에서 다운로드 하시기 바랍니다.)</strong></p> <p><br /></p> </div> <div class="center-block"> <h4>2. 프로그램 동작 전 화면</h4> <img src="/images/image_20171103_01.png" /> <p>네비게이션 프로그램 과 동일 한 방식으로 동작함으로 프로그램 실행후 게임을 진행 하시면 되겠습니다.<br /> 서버를 선택 하기 전에는 동작 하지 않습니다.<br /> <strong class="text-danger" style="font-size: 200%;">서버 선택에 주의 해 주시기 바랍니다.</strong></p> <p><br /></p> </div> <div class="center-block"> <h4>3. 수집기 동작 화면</h4> <img src="/images/image_20171103_02.png" /> <p><strong class="text-success">매각</strong> 화면 및 <strong class="text-success">인근도시시세</strong> 화면을 읽어 자동으로 갱신 하며, 화면을 읽어 분석하는데 대략 1초 정도의 시간이 걸립니다.<br /> 수집된 결과는 프로그램내부 검색 또는 각 서버 페이지에서 확인 하도록 되어 있어 모바일 및 PC 에서 확인 하실 수 있습니다.<br /> Clear 버튼을 누르면 서버를 변경 하거나 새로운 정보로 갱신 할 수 있습니다.</p> <p><br /></p> </div> <div class="center-block"> <h4>4. 검색 동작 화면</h4> <img src="/images/image_20171103_03.png" /> <p>필요한 도시 또는 교역품을 검색하여 결과를 볼 수 있습니다.<br /> 검색어는 , 로 구분 되며 여러개를 넣을 수 있습니다.<br /> 검색된 결과에서 도시명 또는 교역품 명을 더블클릭하여 바로 해당 내용을 확인 할 수 있습니다.<br /> 검색어를 입력 후 Enter 키를 누르면 바로 검색이 실행 됩니다.<br /> 검색된 결과에서 상단 분류명을 누르면 정순/역순 으로 정렬 할 수 있습니다.</p> <p><br /></p> </div> <div class="center-block"> <h4>5. 즐겨찾기 편집 화면</h4> <img src="/images/image_20171103_04.png" /> <p><strong>SearchShortcuts.txt</strong> 파일을 편집 하면 나만의 즐겨찾기를 만들 수 있습니다.<br /> <strong class="text-success">즐겨찾기이름</strong> = <strong class="text-primary">도시명</strong> + <strong class="text-danger">교역품명</strong><br /> 위 양식으로 다양하게 구성 할 수 있습니다.<br /> 이미 등록되어있는 내용은 지워도 상관 없으니 마음껏 수정 하여 나만의 목록을 만들어 보시기 바랍니다.</p> <p><br /></p> </div> <div class="center-block"> <h4>6. 즐겨찾기 동작 화면</h4> <img src="/images/image_20171103_05.png" /> <p>즐겨찾기를 수정 후 프로그램을 다시 시작하면 해당 내용을 선택 하여 결과를 볼 수 있습니다.</p> <p><br /></p> </div> <div class="center-block"> <br /> <a class="btn btn-warning btn-lg btn-block" href="https://github.com/gvonline/gvo_quote/releases/latest" role="button" target="_blank">프로그램 다운로드</a> <br /> <a class="btn btn-primary btn-lg btn-block" href="http://gvonline.ga" role="button">돌아가기</a> <br /> </div> </div> </body> </html>
mit
andchir/shopkeeper4
src/App/Service/DataBaseUtilService.php
6394
<?php namespace App\Service; use Doctrine\ODM\MongoDB\DocumentManager; use MongoDB\Client; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; class DataBaseUtilService { /** @var ParameterBagInterface */ protected $params; /** @var DocumentManager */ protected $dm; public function __construct( ParameterBagInterface $params, DocumentManager $dm ) { $this->params = $params; $this->dm = $dm; } /** * @param string $zipFilePath * @param string $mongoExportToolPath * @return bool * @throws \Exception */ public function databaseExport($zipFilePath, $mongoExportToolPath = 'mongoexport') { $dataBasePassword = $this->params->get('mongodb_password'); $dataBaseName = $this->params->get('mongodb_database'); $targetDirPath = dirname($zipFilePath) . DIRECTORY_SEPARATOR . pathinfo($zipFilePath, PATHINFO_FILENAME); if (strpos(exec($mongoExportToolPath . " 2>&1"), 'mongoexport --help') === false) { throw new \Exception('mongoexport tool not found.'); } if (!is_dir($targetDirPath)) { mkdir($targetDirPath); } self::cleanDirectory($targetDirPath); /** @var \MongoDB\Database $dataBase */ $dataBase = $this->getClient()->selectDatabase($dataBaseName); $collections = $dataBase->listCollections(); foreach ($collections as $collection) { $outputFilePath = $targetDirPath . DIRECTORY_SEPARATOR . "{$collection->getName()}.json"; $cmd = "{$mongoExportToolPath} --db {$dataBaseName}"; $cmd .= ' \\' . PHP_EOL . "--collection {$collection->getName()} --type json"; $cmd .= ' \\' . PHP_EOL . "--jsonArray --pretty"; if ($dataBasePassword) { $cmd .= ' \\' . PHP_EOL . "--authenticationDatabase admin"; $cmd .= ' \\' . PHP_EOL . "--username \"{$dataBaseName}\""; $cmd .= ' \\' . PHP_EOL . "--password \"{$dataBasePassword}\""; } // $cmd .= ' \\' . PHP_EOL . "--out {$outputFilePath}"; $cmd .= " --quiet > {$outputFilePath}"; exec($cmd . ' 2>&1'); } if (!self::zipFolder($targetDirPath, $zipFilePath)) { throw new \Exception('Data is empty.'); } // Delete temporary files $dir = new \DirectoryIterator($targetDirPath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { if (is_file($fileinfo->getPathname())) { if ($fileinfo->getExtension() !== 'zip') { unlink($fileinfo->getPathname()); } } } } rmdir($targetDirPath); return true; } /** * @param string $collectionName * @param string $filePath * @param string $mode * @param string $mongoImportToolPath * @return bool * @throws \Exception */ public function databaseImport($collectionName, $filePath, $mode = 'insert', $mongoImportToolPath = 'mongoimport') { $dataBasePassword = $this->params->get('mongodb_password'); $dataBaseName = $this->params->get('mongodb_database'); if (strpos(exec($mongoImportToolPath . " 2>&1"), 'mongoimport --help') === false) { throw new \Exception('mongoimport tool not found.'); } $cmd = "{$mongoImportToolPath} --db \"{$dataBaseName}\""; $cmd .= ' \\' . PHP_EOL . "--collection \"{$collectionName}\" --type json"; $cmd .= ' \\' . PHP_EOL . "--file \"{$filePath}\""; $cmd .= ' \\' . PHP_EOL . "--jsonArray"; $cmd .= ' \\' . PHP_EOL . "--mode {$mode}"; if ($dataBasePassword) { $cmd .= ' \\' . PHP_EOL . "--authenticationDatabase \"admin\""; $cmd .= ' \\' . PHP_EOL . "--username \"{$dataBaseName}\""; $cmd .= ' \\' . PHP_EOL . "--password \"{$dataBasePassword}\""; } exec($cmd . ' 2>&1'); return true; } /** * @param string $dirPath * @param string $mode * @param string $mongoImportToolPath * @return bool * @throws \Exception */ public function databaseImportFromDir($dirPath, $mode = 'insert', $mongoImportToolPath = 'mongoimport') { $count = 0; $dir = new \DirectoryIterator($dirPath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot() && $fileinfo->isFile()) { $this->databaseImport( pathinfo($fileinfo->getPathname(), PATHINFO_FILENAME), $fileinfo->getPathname(), $mode, $mongoImportToolPath ); $count++; } } return $count; } /** * @return Client */ public function getClient() { return $this->dm->getClient(); } /** * @param $dirPath */ public static function cleanDirectory($dirPath) { if (!is_dir($dirPath)) { return; } $dir = new \DirectoryIterator($dirPath); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot()) { if (is_file($fileinfo->getPathname())) { unlink($fileinfo->getPathname()); } } } } /** * @param $dirPath * @param $zipFilePath * @return bool */ public static function zipFolder($dirPath, $zipFilePath) { if (!is_dir($dirPath)) { return false; } $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($dirPath), \RecursiveIteratorIterator::LEAVES_ONLY ); if (count(iterator_to_array($files)) === 2) { return false; } $zip = new \ZipArchive(); $zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE); foreach ($files as $name => $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($dirPath) + 1); $zip->addFile($filePath, $relativePath); } } return $zip->close(); } }
mit
zenlinTechnofreak/vessel
Godeps/_workspace/src/github.com/pingcap/go-hbase/del_test.go
2186
package hbase import ( "bytes" "github.com/ngaut/log" . "github.com/pingcap/check" "github.com/pingcap/go-hbase/proto" ) type HBaseDelTestSuit struct { cli HBaseClient } var _ = Suite(&HBaseDelTestSuit{}) func (s *HBaseDelTestSuit) SetUpTest(c *C) { var err error s.cli, err = NewClient(getTestZkHosts(), "/hbase") c.Assert(err, Equals, nil) tblDesc := NewTableDesciptor(NewTableNameWithDefaultNS("t2")) cf := NewColumnFamilyDescriptor("cf") tblDesc.AddColumnDesc(cf) s.cli.CreateTable(tblDesc, nil) } func (s *HBaseDelTestSuit) TestDel(c *C) { d := NewDelete([]byte("hello")) d.AddFamily([]byte("cf")) d.AddFamily([]byte("cf1")) msg := d.ToProto() p, ok := msg.(*proto.MutationProto) c.Assert(ok, Equals, true) c.Assert(bytes.Compare(p.Row, []byte("hello")), Equals, 0) c.Assert(*p.MutateType, Equals, *proto.MutationProto_DELETE.Enum()) cv := p.GetColumnValue() c.Assert(len(cv), Equals, 2) for _, v := range cv { c.Assert(len(v.QualifierValue), Equals, 1) c.Assert(*v.QualifierValue[0].DeleteType, Equals, *proto.MutationProto_DELETE_FAMILY.Enum()) } d = NewDelete([]byte("hello")) d.AddStringColumn("cf\x00", "q") d.AddStringColumn("cf", "q") d.AddStringColumn("cf", "q") msg = d.ToProto() p, _ = msg.(*proto.MutationProto) cv = p.GetColumnValue() c.Assert(len(cv), Equals, 2) for _, v := range cv { c.Assert(len(v.QualifierValue), Equals, 1) c.Assert(*v.QualifierValue[0].DeleteType, Equals, *proto.MutationProto_DELETE_MULTIPLE_VERSIONS.Enum()) } } func (s *HBaseDelTestSuit) TestWithClient(c *C) { // create new p := NewPut([]byte("test")) p.AddValue([]byte("cf"), []byte("q"), []byte("val")) s.cli.Put("t2", p) // check it g := NewGet([]byte("test")) g.AddStringFamily("cf") r, err := s.cli.Get("t2", g) c.Assert(err, Equals, nil) c.Assert(string(r.Columns["cf:q"].Value), Equals, "val") log.Info(string(r.Columns["cf:q"].Value)) // delete it d := NewDelete([]byte("test")) d.AddColumn([]byte("cf"), []byte("q")) b, err := s.cli.Delete("t2", d) c.Assert(err, Equals, nil) c.Assert(b, Equals, true) // check it r, err = s.cli.Get("t2", g) c.Assert(err, Equals, nil) c.Assert(r == nil, Equals, true) }
mit
mike10004/selenium-help
src/main/java/com/github/mike10004/seleniumhelp/CookieAttributeHandlers.java
4313
package com.github.mike10004.seleniumhelp; import com.google.common.collect.ImmutableList; import org.apache.http.Header; import org.apache.http.conn.util.InetAddressUtils; import org.apache.http.cookie.CommonCookieAttributeHandler; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieSpec; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.cookie.SetCookie; import org.apache.http.impl.cookie.BasicDomainHandler; import org.apache.http.impl.cookie.BasicPathHandler; import org.apache.http.impl.cookie.BasicSecureHandler; import org.apache.http.impl.cookie.CookieSpecBase; import org.apache.http.impl.cookie.DefaultCookieSpecProvider; import org.apache.http.impl.cookie.LaxExpiresHandler; import org.apache.http.impl.cookie.LaxMaxAgeHandler; import org.apache.http.protocol.BasicHttpContext; import java.util.List; import java.util.Locale; import static java.util.Objects.requireNonNull; class CookieAttributeHandlers { private CookieAttributeHandlers() {} private static final CommonCookieAttributeHandler[] handlersArray = { new BasicPathHandler(), // similar to RFC6265LaxSpec new BetterDomainHandler(), // with the exception of domain handling new LaxMaxAgeHandler(), new BasicSecureHandler(), new LaxExpiresHandler() }; private static final ImmutableList<CommonCookieAttributeHandler> handlersList = ImmutableList.copyOf(handlersArray); static ImmutableList<CommonCookieAttributeHandler> getDefaultAttributeHandlers() { return handlersList; } public static CookieSpec makeNonparsingCookieSpec() { return new DelegatingCookieSpec(); } private static class DelegatingCookieSpec extends CookieSpecBase { private final CookieSpec delegate; private DelegatingCookieSpec() { super(handlersArray); this.delegate = new DefaultCookieSpecProvider().create(new BasicHttpContext()); } @Override public int getVersion() { return delegate.getVersion(); } @Override public List<Cookie> parse(Header header, CookieOrigin origin) { throw new UnsupportedOperationException("this spec does not parse"); } @Override public List<Header> formatCookies(List<Cookie> cookies) { return delegate.formatCookies(cookies); } @Override public Header getVersionHeader() { return delegate.getVersionHeader(); } } private static class BetterDomainHandler extends BasicDomainHandler { @Override public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { // does nothing } static boolean domainMatch(final String domain, final String host) { if (InetAddressUtils.isIPv4Address(host) || InetAddressUtils.isIPv6Address(host)) { return false; } final String normalizedDomain = domain.startsWith(".") ? domain.substring(1) : domain; if (host.endsWith(normalizedDomain)) { final int prefix = host.length() - normalizedDomain.length(); // Either a full match or a prefix ending with a '.' if (prefix == 0) { return true; } if (prefix > 1 && host.charAt(prefix - 1) == '.') { return true; } } return false; } @Override public boolean match(final Cookie cookie, final CookieOrigin origin) { requireNonNull(cookie, "Cookie"); requireNonNull(origin, "Cookie origin"); final String host = origin.getHost(); String domain = cookie.getDomain(); if (domain == null) { return false; } if (domain.startsWith(".")) { domain = domain.substring(1); } domain = domain.toLowerCase(Locale.ROOT); if (host.equals(domain)) { return true; } return domainMatch(domain, host); } } }
mit
rfillaudeau/inkPics
app/site/ajax/global/add_friend.php
1864
<?php require_once '../../../tools/config.php'; require_once '../../../tools/functions.php'; $link_db = connect_db($database_host, $database_user, $database_pass, $database_name); $user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_MAGIC_QUOTES); if (isset($_SESSION['pm_user']) && isset($user_id)) { $result_following = mysqli_query($link_db, ' SELECT * FROM following WHERE user_id = ' . $_SESSION['pm_user'] . ' AND following_user_id = ' . $user_id); if (mysqli_num_rows($result_following) == 0) { mysqli_query($link_db, ' INSERT INTO following (user_id, following_user_id, following_friend) VALUES (' . $_SESSION['pm_user'] . ', ' . $user_id . ', 1);'); $result_notification = mysqli_query($link_db, ' SELECT * FROM user WHERE user_id = ' . $user_id); $row_notification = mysqli_fetch_array($result_notification); if ($row_notification['notification_follower'] == 1) { mysqli_query($link_db, ' INSERT INTO notification (notification_user_id, notification_type_id, notification_element_id) VALUES (' . $user_id . ', 1, ' . $_SESSION['pm_user'] . ');'); } mysqli_free_result($result_notification); mysqli_query($link_db, ' UPDATE user SET user_xp = user_xp + ' . $xp_following . ' WHERE user_id = ' . $_SESSION['pm_user']); mysqli_query($link_db, ' UPDATE user SET user_xp = user_xp + ' . $xp_follower . ' WHERE user_id = ' . $user_id); } else { mysqli_query($link_db, ' UPDATE following SET following_friend = 1 WHERE user_id = ' . $_SESSION['pm_user'] . ' AND following_user_id = ' . $user_id); } echo 'SUCCESS'; mysqli_free_result($result_following); } close_db($link_db);
mit
PHP-DI/Kernel
tests/Fixture/FakeComposerLocator.php
269
<?php namespace DI\Kernel\Test\Fixture; class FakeComposerLocator extends \ComposerLocator { public static $paths = []; public static $rootPath; public static function getRootPath() { return self::$rootPath ?: parent::getRootPath(); } }
mit
johnduhart/MineAPI
MineAPI.Protocol/PacketInfo.cs
1451
using System; using System.Collections.Generic; using MineAPI.Protocol.IO; namespace MineAPI.Protocol { internal class PacketInfo : IPacketInfo { public NetworkState State { get; internal set; } public PacketDirection Direction { get; internal set; } public byte Id { get; internal set; } public Type Type { get; internal set; } internal List<PacketFieldAction> FieldActions { get; set; } public IPacket ReadPacketFromStream(IMinecraftStreamReader reader) { var packet = (IPacket)Activator.CreateInstance(Type); var manualPacket = packet as IManualPacket; if (manualPacket != null) { manualPacket.ReadPacket(reader); return packet; } foreach (var packetFieldAction in FieldActions) { packetFieldAction.ReaderAction(packet, reader); } return packet; } public void WritePacketToStream(IPacket packet, IMinecraftStreamWriter writer) { var manualPacket = packet as IManualPacket; if (manualPacket != null) { manualPacket.WritePacket(writer); return; } foreach (var packetFieldAction in FieldActions) { packetFieldAction.WriterAction(packet, writer); } } } }
mit
SFSUser/IPS
src/Acme/SiteBundle/Entity/HCRiesgo.php
1624
<?php namespace Acme\SiteBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * HCGeneral10Recomendaciones * * @ORM\Table() * @ORM\Entity */ class HCRiesgo { /** * @ORM\ManyToOne(targetEntity="HCRiesgoTipo", inversedBy="riesgos") * @ORM\JoinColumn(name="tipo", referencedColumnName="id") **/ public $reftipo; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="tipo", type="integer") */ private $tipo; /** * @var string * * @ORM\Column(name="descripcion", type="string", length=500) */ private $descripcion; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set tipo * * @param string $tipo * @return HCGeneral10Recomendaciones */ public function setTipo($tipo) { $this->tipo = $tipo; return $this; } /** * Get tipo * * @return string */ public function getTipo() { return $this->tipo; } /** * Set descripcion * * @param string $descripcion * @return HCGeneral10Recomendaciones */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } }
mit
hidnarola/osos
application/views/company/Employees/Leave/employee_leave_display.php
9341
<script src="<?php echo DEFAULT_FRONT_JS_PATH . "app-tables-datatables.js" ?>" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="<?php echo DEFAULT_FRONT_LIB_PATH . "font-awesome/css/font-awesome.min.css" ?>"/> <?php if ($this->session->flashdata('success')) { ?> <div class="content pt0 flashmsg"> <div class="alert alert-success"> <a class="close" data-dismiss="alert">X</a> <strong><?= $this->session->flashdata('success') ?></strong> </div> </div> <?php $this->session->set_flashdata('success', false); } else if ($this->session->flashdata('error')) { ?> <div class="content pt0 flashmsg"> <div class="alert alert-danger"> <a class="close" data-dismiss="alert">X</a> <strong><?= $this->session->flashdata('error') ?></strong> </div> </div> <?php $this->session->set_flashdata('error', false); } else { if (!empty(validation_errors())) { ?> <div class="content pt0 flashmsg"> <div class = "alert alert-danger"> <a class="close" data-dismiss="alert">X</a> <strong><?php echo validation_errors(); ?></strong> </div> </div> <?php } } $controller = $this->router->fetch_class(); ?> <div class="row"> <!-- Left Column--> <div class="col-md-12"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="<?php echo base_url() . "dashboard" ?>"><span class="icon icon-home2"><span class="front_breadcrum"> Home</span></span></a></li> <li class="breadcrumb-item active"><span class="icon-calendar52"><span class="front_breadcrum"> Employee Leaves</span></span></li> </ol> <div class="panel panel-default"> <div class="panel-heading panel-heading-color panel-heading-color-primary">Employee Leaves List <?php if (!empty(MY_Controller::$access_method) && array_key_exists('add_vacation', MY_Controller::$access_method[$controller]) || ($this->data['user_data']['role_id'] == 2 || $this->data['user_data']['role_id'] == 11)) { ?> <span class="text-right-btn"><a class="btn btn-space btn-secondary btn-lg" href="<?= isset($emp_id) ? base_url('employees/employeeleave/add/' . base64_encode($emp_id)) : base_url('employees/employeeleave/add') ?>"><i class="icon icon-left icon-plus3"></i> Add New Leave</a></span> <?php } ?> </div> <div class="panel-body"> <table id="table1" class="table table-striped table-hover table-fw-widget"> <thead> <tr> <th>#</th> <th style="width:15%;">Name</th> <th style="width:12%;">Leave Type</th> <th style="width:15%;">From Date</th> <th style="width:10%;">To Date</th> <th style="width:8%;">No Of Days</th> <th style="width:15%;">Department</th> <th style="width:10%;">Position</th> <th style="width:20%;text-align: left;">Action</th> </tr> </thead> <tbody> <?php if (isset($employee_leaves) && !empty($employee_leaves)) { foreach ($employee_leaves as $key => $record) { ?> <tr> <td><?php echo $key + 1; ?></td> <td><?php echo $record['emp_fname'] . " " . $record['emp_lname'] ?></td> <td><?php echo $record['leave_name']; ?></td> <td><?php echo date('Y-m-d', strtotime($record['from_date'])) ?></td> <td><?php echo date('Y-m-d', strtotime($record['to_date'])) ?></td> <td><?php echo $record['no_of_days'] ?></td> <td><?php echo $record['dept_name']; ?></td> <td><?php echo $record['property_name']; ?></td> <td> <?php if (!empty(MY_Controller::$access_method) && array_key_exists('edit_vacation', MY_Controller::$access_method[$controller]) || ($this->data['user_data']['role_id'] == 2 || $this->data['user_data']['role_id'] == 11)) { ?> <a href="<?php echo base_url() . "employees/employeeleave/edit/" . base64_encode($record['id']) ?>" id="edit_<?php echo base64_encode($record['id']); ?>" title='Edit Leave' class="edit btn btn-secondary"><i class="s7-note icon text-success btn-bold"></i></a> <?php } if (!empty(MY_Controller::$access_method) && array_key_exists('view_vacation', MY_Controller::$access_method[$controller]) || ($this->data['user_data']['role_id'] == 2 || $this->data['user_data']['role_id'] == 11)) { ?> <a href="<?php echo base_url() . "employees/employeeleave/view/" . base64_encode($record['id']) ?>" id="view_<?php echo base64_encode($record['id']); ?>" data-record="<?php echo base64_encode($record['id']); ?>" title='View Leave' class="view btn btn-secondary"><i class="s7-look icon text-info btn-bold"></i></a> <?php }if (!empty(MY_Controller::$access_method) && in_array('delete', MY_Controller::$access_method[$controller]) || ($this->data['user_data']['role_id'] == 2 || $this->data['user_data']['role_id'] == 11)) { ?> <a data-record="<?php echo base64_encode($record['id']); ?>" id="delete_<?php echo base64_encode($record['id']); ?>" title='Delete Leave' class="delete btn btn-secondary"><i class="icon s7-trash text-danger btn-bold"></i></a> <?php } ?> </td> </tr> <?php } } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript"> var base_url = '<?php echo base_url(); ?>'; // $(document).on('click', '.edit', function () { // var id = $(this).attr('id').replace('edit_', ''); // var url = base_url + 'expenses/get_detail'; // $.ajax({ // type: 'POST', // url: url, // async: false, // dataType: 'JSON', // data: {id: id, type: 'expense_type'}, // success: function (data) { // if (data.is_delete == 0) { // $('#name').val(data.name); // $('#record_id').val(data.id); // } // } // }); // }); $(document).on('click', '.delete', function () { var id = $(this).attr('id').replace('delete_', ''); var url = base_url + 'employees/delete'; swal({ title: "Are you sure?", text: "You will not be able to recover this Agent!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", cancelButtonText: "No, cancel plz!", reverseButtons: true, }).then(function (isConfirm) { if (isConfirm) { $.ajax({ type: 'POST', url: url, async: false, dataType: 'JSON', data: {id: id, type: 'employee_leave', title: 'Employee Leave'}, success: function (data) { window.location.reload(); if (data.status == 1) { $("div.div_alert_error").addClass('alert-success'); } else if (data.status == 0) { $("div.div_alert_error").addClass('alert-danger'); } $("p.alert_error_msg").text(data.msg); $("div.div_alert_error").show(); } }); } }, function (dismiss) { // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer' if (dismiss === 'cancel') { swal("Cancelled", "Your Agent is safe :)", "error"); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { //initialize the javascript App.init(); App.dataTables(); }); </script>
mit
jsuggs/CollegeCrazies
src/SofaChamps/Bundle/FacebookBundle/DependencyInjection/SofaChampsFacebookExtension.php
901
<?php namespace SofaChamps\Bundle\FacebookBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class SofaChampsFacebookExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
mit
SonarSource-VisualStudio/sonar-scanner-msbuild
Tests/SonarScanner.MSBuild.PostProcessor.Tests/Infrastructure/MockTeamBuildSettings.cs
1626
/* * SonarScanner for MSBuild * Copyright (C) 2016-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using SonarScanner.MSBuild.Common.Interfaces; using SonarScanner.MSBuild.Common.TFS; namespace SonarScanner.MSBuild.PostProcessor.Tests { internal class MockTeamBuildSettings : ITeamBuildSettings { public BuildEnvironment BuildEnvironment { get; set; } public string TfsUri { get; set; } public string BuildUri { get; set; } public string SourcesDirectory { get; set; } public string AnalysisBaseDirectory { get; set; } public string BuildDirectory { get; set; } public string SonarConfigDirectory { get; set; } public string SonarOutputDirectory { get; set; } public string SonarBinDirectory { get; set; } public string AnalysisConfigFilePath { get; set; } } }
mit
asherwunk/primus2
Falcraft/tests/Data/Types/OrderedNode.php
10868
<?php require_once('../../../Data/Types/Restrictions.php'); require_once('../../../Data/Types/Type.php'); require_once('../../../Data/Types/RestrictedSet.php'); require_once('../../../Data/Types/UnorderedNode.php'); require_once('../../../Data/Types/OrderedNode.php'); use Falcraft\Data\Types; use Falcraft\Data\Types\Type; echo "Falcraft\\Data\\Types\\OrderedNode.php Test\n"; echo "----------------------------------------\n\n"; echo "Empty Instantiation -> "; $success = true; $testOrderedNode1 = null; try { $testOrderedNode1 = new Types\OrderedNode(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo "Instantiating Incorrect Ordered Node (correctSet1, incorrectSet1) -> "; $failure = true; $testIncorrectRestrictions = $testIncorrectRestrictedSet = $testIncorrectOrderedNode = null; try { $testIncorrectRestrictions = new Types\Restrictions(array(Types\Type::BASIC_BOOL)); $testIncorrectRestrictedSet = Types\RestrictedSet::build(array(), $testIncorrectRestrictions); $testIncorrectOrderedNode = new Types\OrderedNode( $testCorrectRestrictedSet1, array(), $testIncorrectRestrictedSet ); $failure = false; } catch ( \InvalidArgumentException $e ) { $failure = true; } if ($failure) { echo "Failure!\n"; } else { echo "Success...\n"; } echo "Instantiating Incorrect Ordered Node (correctSet2, incorrectSet2) -> "; $failure = true; $testIncorrectRestrictions2 = $testIncorrectRestrictedSet2 = $testIncorrectOrderedNode2 = null; try { $testIncorrectRestrictions2 = new Types\Restrictions( array(Types\Type::TYPED_OBJECT ), array( 'Falcraft\Data\Types\Edge') ); $testIncorrectRestrictedSet2 = Types\RestrictedSet::build(array(), $testIncorrectRestrictions2); $testIncorrectOrderedNode2 = new Types\OrderedNode( $testCorrectRestrictedSet2, array(), $testIncorrectRestrictedSet2 ); $failure = false; } catch ( \InvalidArgumentException $e ) { $failure = true; } if ($failure) { echo "Failure!\n"; } else { echo "Success...\n"; } echo "Instantiating Correct Ordered Node -> "; $testCorrectRestrictions = $testCorrectRestrictedSet1 = null; $testCorrectRestrictedSet2 = $testCorrectOrderedNode = null; $success = true; try { $testCorrectRestrictions = new Types\Restrictions( array(Types\Type::TYPED_OBJECT), array( 'Falcraft\Data\Types\Resource\VertexInterface') ); $testCorrectRestrictedSet1 = Types\RestrictedSet::build(array(), $testCorrectRestrictions); $testCorrectRestrictedSet2 = Types\RestrictedSet::build(array(), $testCorrectRestrictions); $testCorrectOrderedNode = new Types\OrderedNode( $testCorrectRestrictedSet1, array(), $testCorrectRestrictedSet2 ); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } echo "Retrieving Restrictions -> \n\n"; var_dump($testCorrectOrderedNode->getRestrictions()); echo "\n\n"; echo "Creating Vertices -- \n"; echo "UnorderedNodes: parentNode, rightNode, middleNode, leftNode, offsideNode, auxiliaryNode\n"; $success = true; $parentNode = $rightNode = $middleNode = $leftNode = $offsideNode = $auxiliaryNode = null; try { echo " \$parentNode = new Types\\UnorderedNode(): identifier = "; $parentNode = new Types\UnorderedNode(); echo $parentNode->getIdentifier() . "\n"; echo " \$rightNode = new Types\\UnorderedNode(): identifier = "; $rightNode = new Types\UnorderedNode(); echo $rightNode->getIdentifier() . "\n"; echo " \$middleNode = new Types\\UnorderedNode(): identifier = "; $middleNode = new Types\UnorderedNode(); echo $middleNode->getIdentifier() . "\n"; echo " \$leftNode = new Types\\UnorderedNode(): identifier = "; $leftNode = new Types\UnorderedNode(); echo $leftNode->getIdentifier() . "\n"; echo " \$offsideNode = new Types\\UnorderedNode(): identifier = "; $offsideNode = new Types\UnorderedNode(); echo $offsideNode->getIdentifier() . "\n"; echo " \$auxiliaryNode = new Types\\UnorderedNode(): identifier = " ; $auxiliaryNode = new Types\UnorderedNode(); echo $auxiliaryNode->getIdentifier() . "\n"; } catch (\Exception $e) { $success = false; } if ($success) { echo "\n Success!\n\n"; } else { echo "\n Failure...\n\n"; } echo "Attaching parentNode As Parent (Incoming) [Reciprocate As Well] -> "; $success = true; try { $testCorrectOrderedNode->connectIncoming($parentNode); $parentNode->connectOutgoing($testCorrectOrderedNode); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo " Test Result: "; if ($parentNode->isOutgoing($testCorrectOrderedNode) && $testCorrectOrderedNode->isIncoming($parentNode)) { echo "Successful Bidirectional Link\n\n"; } else { echo "Failure To Establish Bidirectional Link\n\n"; } echo "Attaching offsideNode as Sibling (Mutual) -> "; $success = true; try { $testCorrectOrderedNode->connectMutual($offsideNode); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo " Test Result: "; if ($offsideNode->isConnected($testCorrectOrderedNode) && $testCorrectOrderedNode->isConnected($offsideNode)) { echo "Successful Bidirectional Link\n\n"; } else { echo "Failure to Establish Bidirectional Link\n\n"; } echo "Attaching Children: Right, Middle, Left -> "; $success = true; try { $testCorrectOrderedNode->connectOutgoing($rightNode); $rightNode->connectIncoming($testCorrectOrderedNode); $testCorrectOrderedNode->connectOutgoing($middleNode); $middleNode->connectIncoming($testCorrectOrderedNode); $testCorrectOrderedNode->connectOutgoing($leftNode); $leftNode->connectIncoming($testCorrectOrderedNode); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo " Test Result:\n"; if ($testCorrectOrderedNode->isConnected($rightNode) && $rightNode->isConnected($testCorrectOrderedNode)) { echo " rightNode parent-child link successful\n"; } else { echo " rightNode parent-child link unsuccessful\n"; } if ($testCorrectOrderedNode->isConnected($middleNode) && $middleNode->isConnected($testCorrectOrderedNode)) { echo " middleNode parent-child link successful\n"; } else { echo " middleNode parent-child link unsuccessful\n"; } if ($testCorrectOrderedNode->isConnected($leftNode) && $leftNode->isConnected($testCorrectOrderedNode)) { echo " leftNode parent-child link succssful\n\n"; } else { echo " leftNode parent-child link unsuccessful\n\n"; } echo "OrderedNode Specific Functionality Tests --\n"; echo " Retrieval:\n"; $retrieval = null; echo " getFirstOutgoing -> "; $success = true; try { $retrieval = $testCorrectOrderedNode->getFirstOutgoing(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo " \$rightNode: " . $rightNode->getIdentifier() . " retrieved node: " . $retrieval->getIdentifier() . "\n"; echo " reference sanity check -- "; $retrieval = new Types\UnorderedNode(); echo " \$rightNode: " . $rightNode->getIdentifier() . " retrieved node: " . $retrieval->getIdentifier() . "\n"; $retrieval = null; echo " getLastOutgoing -> "; $success = true; try { $retrieval = $testCorrectOrderedNode->getLastOutgoing(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n"; } else { echo "Failure...\n"; } echo " \$leftNode: " . $leftNode->getIdentifier() . " retrieved node: " . $retrieval->getIdentifier() . "\n\n"; echo "Vertices -- \n\n"; var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "\nPush - "; $success = true; try { $testCorrectOrderedNode->push(new Types\UnorderedNode()); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); $retrieval = null; echo "\nPop - "; $success = true; try { $retrieval = $testCorrectOrderedNode->pop(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success! Identifier: " . $retrieval->getIdentifier() . "\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); $retrieval = null; echo "\nShift - "; $success = true; try { $retrieval = $testCorrectOrderedNode->shift(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success! Identifier: " . $retrieval->getIdentifier() . "\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "Unshift -> "; $success = true; try { $testCorrectOrderedNode->unshift(new Types\UnorderedNode()); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "insertAfter 7 -> "; $success = true; try { $testCorrectOrderedNode->insertAfter(new Types\UnorderedNode, 7); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "insertBefore 14 -> "; $success = true; try { $testCorrectOrderedNode->insertBefore(new Types\UnorderedNode, 14); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "delete 15 -> "; $success = true; try { $testCorrectOrderedNode->delete(15); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } var_dump($testCorrectOrderedNode->getOutgoingArrayIdentifiers()); echo "Count -> " . $testCorrectOrderedNode->count() . "\n"; echo "Is Empty? " . ($testCorrectOrderedNode->isEmpty() ? "true\n" : "false\n"); echo "Clear Outgoing -> "; $success = true; try { $testCorrectOrderedNode->clearOutgoing(); } catch (\Exception $e) { $success = false; } if ($success) { echo "Success!\n\n"; } else { echo "Failure...\n\n"; } echo "Is Empty? " . ($testCorrectOrderedNode->isEmpty() ? "true\n" : "false\n");
mit
viktor-kolosek/sample_app_rails_4
vendor/bundle/ruby/2.0.0/gems/airbrake-4.2.1/lib/airbrake/cli/options.rb
1918
class Options ATTRIBUTES = [:error, :message, :api_key, :host, :port, :auth_token, :name, :account, :rails_env, :scm_revision, :scm_repository, :local_username] ATTRIBUTES.each do |attribute| attr_reader attribute end private # You should not write to this from outside ATTRIBUTES.each do |attribute| attr_writer attribute end public # Parses all the options passed and stores them in attributes def initialize(array = []) opts = Hash[*array] self.error = opts.delete("-e") || opts.delete("--error") { RuntimeError } self.message = opts.delete("-m") || opts.delete("--message") { "I've made a huge mistake" } self.api_key = opts.delete("-k") || opts.delete("--api-key") || config_from_file.api_key || ENV["AIRBRAKE_API_KEY"] self.host = opts.delete("-h") || opts.delete("--host") || config_from_file.host self.port = opts.delete("-p") || opts.delete("--port") || config_from_file.port self.auth_token = opts.delete("-t") || opts.delete("--auth-token") || ENV["AIRBRAKE_AUTH_TOKEN"] self.name = opts.delete("-n") || opts.delete("--name") self.account = opts.delete("-a") || opts.delete("--account") || ENV["AIRBRAKE_ACCOUNT"] self.rails_env = opts.delete("-E") || opts.delete("--rails-env") || ENV["RAILS_ENV"] || "production" self.scm_revision = opts.delete("-r") || opts.delete("--scm-revision") || ENV["REVISION"] self.scm_repository = opts.delete("-R") || opts.delete("--scm-repository") || ENV["REPO"] self.local_username = opts.delete("-u") || opts.delete("--local-username") || ENV["USER"] opts end # Fallback to read from the initializer def config_from_file begin load "config/initializers/airbrake.rb" rescue LoadError end Airbrake.configuration end end
mit
onlabsorg/olowc
jspm_packages/npm/lodash@4.17.4/fp/mergeAllWith.js
172
/* */ var convert = require('./convert'), func = convert('mergeAllWith', require('../mergeWith')); func.placeholder = require('./placeholder'); module.exports = func;
mit
antFB/antFB
components/layout/col.tsx
2461
import React from 'react'; import { PropTypes } from 'react'; import classNames from 'classnames'; import assign from 'object-assign'; import splitObject from '../_util/splitObject'; const stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); const objectOrNumber = PropTypes.oneOfType([PropTypes.object, PropTypes.number]); export interface ColSize { span?: number; order?: number; offset?: number; push?: number; pull?: number; } export interface ColProps { className?: string; span?: number; order?: number; offset?: number; push?: number; pull?: number; xs?: number | ColSize; sm?: number | ColSize; md?: number | ColSize; lg?: number | ColSize; prefixCls?: string; style?: React.CSSProperties; } const Col: React.StatelessComponent<ColProps> = (props) => { const [{ span, order, offset, push, pull, className, children, prefixCls = 'ant-col' }, others] = splitObject(props, ['span', 'order', 'offset', 'push', 'pull', 'className', 'children', 'prefixCls']); let sizeClassObj = {}; ['xs', 'sm', 'md', 'lg'].forEach(size => { let sizeProps: ColSize = {}; if (typeof props[size] === 'number') { sizeProps.span = props[size]; } else if (typeof props[size] === 'object') { sizeProps = props[size] || {}; } delete others[size]; sizeClassObj = assign({}, sizeClassObj, { [`${prefixCls}-${size}-${sizeProps.span}`]: sizeProps.span !== undefined, [`${prefixCls}-${size}-order-${sizeProps.order}`]: sizeProps.order, [`${prefixCls}-${size}-offset-${sizeProps.offset}`]: sizeProps.offset, [`${prefixCls}-${size}-push-${sizeProps.push}`]: sizeProps.push, [`${prefixCls}-${size}-pull-${sizeProps.pull}`]: sizeProps.pull, }); }); const classes = classNames(assign({}, { [`${prefixCls}-${span}`]: span !== undefined, [`${prefixCls}-order-${order}`]: order, [`${prefixCls}-offset-${offset}`]: offset, [`${prefixCls}-push-${push}`]: push, [`${prefixCls}-pull-${pull}`]: pull, [className]: !!className, }, sizeClassObj)); return <div {...others} className={classes}>{children}</div>; }; Col.propTypes = { span: stringOrNumber, order: stringOrNumber, offset: stringOrNumber, push: stringOrNumber, pull: stringOrNumber, className: PropTypes.string, children: PropTypes.node, xs: objectOrNumber, sm: objectOrNumber, md: objectOrNumber, lg: objectOrNumber, }; export default Col;
mit
rajendrav5/webpack2.0
node_modules/react-hot-loader/lib/babel/index.js
4376
'use strict'; var _babelTemplate = require('babel-template'); var _babelTemplate2 = _interopRequireDefault(_babelTemplate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var buildRegistration = (0, _babelTemplate2.default)('__REACT_HOT_LOADER__.register(ID, NAME, FILENAME);'); var buildSemi = (0, _babelTemplate2.default)(';'); var buildTagger = (0, _babelTemplate2.default)('\n(function () {\n if (typeof __REACT_HOT_LOADER__ === \'undefined\') {\n return;\n }\n\n REGISTRATIONS\n})();\n'); module.exports = function (args) { // This is a Babel plugin, but the user put it in the Webpack config. if (this && this.callback) { throw new Error('React Hot Loader: You are erroneously trying to use a Babel plugin ' + 'as a Webpack loader. We recommend that you use Babel, ' + 'remove "react-hot-loader/babel" from the "loaders" section ' + 'of your Webpack configuration, and instead add ' + '"react-hot-loader/babel" to the "plugins" section of your .babelrc file. ' + 'If you prefer not to use Babel, replace "react-hot-loader/babel" with ' + '"react-hot-loader/webpack" in the "loaders" section of your Webpack configuration. '); } var t = args.types; // No-op in production. if (process.env.NODE_ENV === 'production') { return { visitor: {} }; } // Gather top-level variables, functions, and classes. // Try our best to avoid variables from require(). // Ideally we only want to find components defined by the user. function shouldRegisterBinding(binding) { var _binding$path = binding.path; var type = _binding$path.type; var node = _binding$path.node; switch (type) { case 'FunctionDeclaration': case 'ClassDeclaration': case 'VariableDeclaration': return true; case 'VariableDeclarator': var init = node.init; if (t.isCallExpression(init) && init.callee.name === 'require') { return false; } return true; default: return false; } } var REGISTRATIONS = Symbol(); return { visitor: { ExportDefaultDeclaration: function ExportDefaultDeclaration(path, _ref) { var file = _ref.file; // Default exports with names are going // to be in scope anyway so no need to bother. if (path.node.declaration.id) { return; } // Move export default right hand side to a variable // so we can later refer to it and tag it with __source. var id = path.scope.generateUidIdentifier('default'); var expression = t.isExpression(path.node.declaration) ? path.node.declaration : t.toExpression(path.node.declaration); path.insertBefore(t.variableDeclaration('const', [t.variableDeclarator(id, expression)])); path.node.declaration = id; // It won't appear in scope.bindings // so we'll manually remember it exists. path.parent[REGISTRATIONS].push(buildRegistration({ ID: id, NAME: t.stringLiteral('default'), FILENAME: t.stringLiteral(file.opts.filename) })); }, Program: { enter: function enter(_ref2, _ref3) { var node = _ref2.node; var scope = _ref2.scope; var file = _ref3.file; node[REGISTRATIONS] = []; // Everything in the top level scope, when reasonable, // is going to get tagged with __source. for (var id in scope.bindings) { var binding = scope.bindings[id]; if (shouldRegisterBinding(binding)) { node[REGISTRATIONS].push(buildRegistration({ ID: binding.identifier, NAME: t.stringLiteral(id), FILENAME: t.stringLiteral(file.opts.filename) })); } } }, exit: function exit(_ref4) { var node = _ref4.node; var scope = _ref4.scope; var registrations = node[REGISTRATIONS]; node[REGISTRATIONS] = null; // Inject the generated tagging code at the very end // so that it is as minimally intrusive as possible. node.body.push(buildSemi()); node.body.push(buildTagger({ REGISTRATIONS: registrations })); node.body.push(buildSemi()); } } } }; };
mit
moneyice/hope
analyzer-microservice/src/main/java/hope/analyzer/model/Account.java
5948
package hope.analyzer.model; import hope.analyzer.util.BusinessException; import hope.analyzer.util.Utils; import java.time.LocalDate; import java.util.*; /** * Created by bing.a.qian on 10/2/2017. */ public class Account { //模拟base 100万 static double base=1000000; static double fee_rate=0.0003; public double getAvailableValue() { return availableValue; } public void setAvailableValue(double availableValue) { this.availableValue = availableValue; } //可用金额 double availableValue=base; //证券市值 double marketValue=0; //总市值 double totalValue=availableValue; List<TradeItem> tradeItemList=new LinkedList<>(); Map<String,PositionItem> positionItemMap=new HashMap<>(); public Account() { } public Account(double availableValue) { this.availableValue = availableValue; } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public double getTotalValue() { return totalValue; } public void setTotalValue(double totalValue) { this.totalValue = totalValue; } public double getMarketValue() { return marketValue; } public PositionItem getPosition(String code){ return positionItemMap.get(code); } public List<TradeItem> getTradeItemList() { return tradeItemList; } public void setTradeItemList(List<TradeItem> tradeItemList) { this.tradeItemList = tradeItemList; } public void deal(String code, double tradeQuantity, double tradePrice, ETradeType tradeType, LocalDate tradeDate) throws BusinessException { String ok=validate(code,tradeType,tradeQuantity,tradePrice); if(ok!=null){ throw new BusinessException(ok); } TradeItem tradeItem=new TradeItem(); getTradeItemList().add(tradeItem); tradeItem.setCode(code); tradeItem.setTradeType(tradeType); tradeItem.setDate(tradeDate); tradeItem.setTradePrice(tradePrice); tradeItem.setQuantity(tradeQuantity); double tradeValue=tradeQuantity*tradePrice; double fee=tradeValue*fee_rate; if(tradeType==ETradeType.Buy){ availableValue=availableValue-tradeValue-fee; //set position,计算仓位 PositionItem positionItem= positionItemMap.get(code); if(positionItem==null){ positionItem=new PositionItem(); positionItem.setCode(code); positionItemMap.put(code,positionItem); } positionItem.setQuantity(positionItem.getQuantity()+tradeQuantity); positionItem.setValue(positionItem.getQuantity()*tradePrice); marketValue=calcMarketValue(code,tradePrice); totalValue=availableValue+marketValue; //set this deal's trading record tradeItem.setTradeValue(tradeValue); tradeItem.setFee(fee); tradeItem.setAvailableValue(availableValue); tradeItem.setMarketValue(marketValue); tradeItem.setTotalValue(totalValue); }if(tradeType==ETradeType.Sell) { availableValue=availableValue+tradeValue-fee; //set position,计算仓位 PositionItem positionItem= positionItemMap.get(code); positionItem.setQuantity(positionItem.getQuantity()-tradeQuantity); positionItem.setValue(positionItem.getQuantity()*tradePrice); marketValue=calcMarketValue(code,tradePrice); totalValue=availableValue+marketValue; //set this deal's trading record tradeItem.setTradeValue(tradeValue); tradeItem.setFee(fee); tradeItem.setAvailableValue(availableValue); tradeItem.setMarketValue(marketValue); tradeItem.setTotalValue(totalValue); }else{ //hode current positions } } /** * The holding securities number is only one at one time * @param code * @param tradePrice */ public double calcMarketValue( String code, double tradePrice) { PositionItem positionItem= positionItemMap.get(code); if(positionItem==null){ return 0; } return positionItem.getQuantity()*tradePrice; } private String validate(String code, ETradeType tradeType, double tradeQuantity,double tradePrice) { String result=null; if(tradeType==ETradeType.Buy){ double tradeValue=tradeQuantity*tradePrice; double fee=tradeValue *fee_rate; if(availableValue<tradeValue+fee){ result="可用资金额不够"; } }if(tradeType==ETradeType.Sell) { //因为目前一次只买一个标的 PositionItem positionItem= positionItemMap.get(code); if(positionItem==null||positionItem.getQuantity()<tradeQuantity){ result=code + " 可卖份数不足"; } }else{ } return result; } //Sell to 0% position public void clear(String code, double price,LocalDate tradeDate) throws BusinessException { PositionItem positionItem= positionItemMap.get(code); if(positionItem!=null){ deal(code, positionItem.getQuantity(),price,ETradeType.Sell , tradeDate); } }; //buy to 100% position public void allIn(String code,double price,LocalDate tradeDate) throws BusinessException { double availableNetValue=availableValue-availableValue*fee_rate; double tradeQuantity = Utils.get2Double(availableNetValue / price) ; deal(code,tradeQuantity,price,ETradeType.Buy,tradeDate); } public void deposit(double fixedInvestimentValue) { availableValue=availableValue+fixedInvestimentValue; } }
mit
ctjacobs/cxqwatch
jobbook.py
3616
# This file is part of cxqwatch, released under the MIT license. # The MIT License (MIT) # Copyright (c) 2014, 2016 Christian T. Jacobs # 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. from gi.repository import Gtk, GObject from jobs import * from cx import * from download_dialog import * class JobBook(Gtk.Notebook): def __init__(self, parent, cx): Gtk.Notebook.__init__(self) self.parent = parent self.cx = cx self.jobs = Jobs(cx) self.treeview = Gtk.TreeView(self.jobs) self.treeview.set_grid_lines(Gtk.TreeViewGridLines.BOTH) self.treeview.connect("row-activated", self.query_callback) self.treeselection = self.treeview.get_selection() self.treeselection.set_mode(Gtk.SelectionMode.SINGLE) sw = Gtk.ScrolledWindow() sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN) sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) sw.add(self.treeview) vbox = Gtk.VBox() vbox.pack_start(sw, True, True, 0) hbox = Gtk.HBox(False, 0) label = Gtk.Label("Jobs") hbox.pack_start(label, False, False, 0) hbox.show_all() self.insert_page(vbox, hbox, 0) for i in range(0, len(FIELD_NAMES)): renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn(FIELD_NAMES[i], renderer, text=i, foreground=len(FIELD_NAMES), background=len(FIELD_NAMES)+1) column.set_resizable(True) column.set_min_width(50) column.set_clickable(True) self.treeview.append_column(column) self.show_all() return def query_callback(self, widget, path, view_column): (model, path) = self.treeselection.get_selected_rows() # Get the selected row in the jobbook. job_id = self.jobs.get_value(model.get_iter(path[0]),0) if(self.jobs.get_current_job_by_id(job_id)["STATUS"] == "E" or self.jobs.get_current_job_by_id(job_id)["STATUS"] == "Q"): # Can't download data from a complete or queued job. return # List all files on the first compute node nodes = self.cx.get_nodes_list(job_id) logging.info(self.cx.ls_on_node(job_id, nodes[0])) dialog = DownloadDialog(self.parent) response = dialog.run() if(response == Gtk.ResponseType.OK): user_details = dialog.get_sources() pattern = user_details["PATTERN"].get_text() dialog.destroy() else: dialog.destroy() return self.jobs.get_data(job_id, pattern) return
mit
ProximoSrl/WebDAVSharp.Server
WebDAVServer.cs
23451
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading; using WebDAVSharp.Server.Adapters; using WebDAVSharp.Server.Adapters.AuthenticationTypes; using WebDAVSharp.Server.Exceptions; using WebDAVSharp.Server.MethodHandlers; using WebDAVSharp.Server.Stores; using WebDAVSharp.Server.Stores.Locks; using System.Xml; using WebDAVSharp.Server.Utilities; using System.Diagnostics; using Serilog; using Serilog.Core; namespace WebDAVSharp.Server { /// <summary> /// This class implements the core WebDAV server. /// /// These are the codes allowed by the webdav protocl /// https://msdn.microsoft.com/en-us/library/aa142868(v=exchg.65).aspx /// </summary> public class WebDavServer : WebDavDisposableBase { #region Variables /// <summary> /// The HTTP user /// </summary> public const string HttpUser = "HTTP.User"; private readonly IHttpListener _listener; private readonly bool _ownsListener; private readonly IWebDavStore _store; private readonly Dictionary<string, IWebDavMethodHandler> _methodHandlers; private readonly object _threadLock = new object(); private ManualResetEvent _stopEvent; private Thread _thread; private const string DavHeaderVersion1_2_3 = "1, 2, 3"; private const string DavHeaderVersion1_2_and1Extended = "1,2,1#extend"; private string _davHader = DavHeaderVersion1_2_and1Extended; #endregion #region Properties /// <summary> /// Allow users to have Indefinite Locks /// </summary> public bool AllowInfiniteCheckouts { get { return WebDavStoreItemLock.AllowInfiniteCheckouts; } set { WebDavStoreItemLock.AllowInfiniteCheckouts = value; } } /// <summary> /// Allow users to have Indefinite Locks /// </summary> public bool LockEnabled { get { return WebDavStoreItemLock.LockEnabled; } set { WebDavStoreItemLock.LockEnabled = value; UpdateDavHeader(); } } private void UpdateDavHeader() { _davHader = WebDavStoreItemLock.LockEnabled ? DavHeaderVersion1_2_3 : DavHeaderVersion1_2_and1Extended; } /// <summary> /// The maximum number of seconds a person can check an item out for. /// </summary> public long MaxCheckOutSeconds { get { return WebDavStoreItemLock.MaxCheckOutSeconds; } set { WebDavStoreItemLock.MaxCheckOutSeconds = value; } } /// <summary> /// Logging Interface /// </summary> public static ILogger Log { get { return Serilog.Log.Logger; } } /// <summary> /// Gets the <see cref="IWebDavStore" /> this <see cref="WebDavServer" /> is hosting. /// </summary> /// <value> /// The store. /// </value> public IWebDavStore Store { get { return _store; } } /// <summary> /// Gets the /// <see cref="IHttpListener" /> that this /// <see cref="WebDavServer" /> uses for /// the web server portion. /// </summary> /// <value> /// The listener. /// </value> internal protected IHttpListener Listener { get { return _listener; } } #endregion #region Constructor /// <summary> /// Constructors /// </summary> /// <param name="store"></param> /// <param name="authtype"></param> /// <param name="methodHandlers"></param> public WebDavServer(IWebDavStore store, AuthType authtype, IEnumerable<IWebDavMethodHandler> methodHandlers = null) { _ownsListener = true; switch (authtype) { case AuthType.Basic: _listener = new HttpListenerBasicAdapter(); break; case AuthType.Negotiate: _listener = new HttpListenerNegotiateAdapter(); break; case AuthType.Anonymous: _listener = new HttpListenerAnyonymousAdapter(); break; case AuthType.Smart: _listener = new HttpListenerSmartAdapter(); break; } methodHandlers = methodHandlers ?? WebDavMethodHandlers.BuiltIn; IWebDavMethodHandler[] webDavMethodHandlers = methodHandlers as IWebDavMethodHandler[] ?? methodHandlers.ToArray(); if (!webDavMethodHandlers.Any()) throw new ArgumentException("The methodHandlers collection is empty", "methodHandlers"); if (webDavMethodHandlers.Any(methodHandler => methodHandler == null)) throw new ArgumentException("The methodHandlers collection contains a null-reference", "methodHandlers"); //_negotiateListener = listener; _store = store; var handlersWithNames = from methodHandler in webDavMethodHandlers from name in methodHandler.Names select new { name, methodHandler }; _methodHandlers = handlersWithNames.ToDictionary(v => v.name, v => v.methodHandler); UpdateDavHeader(); } /// <summary> /// This constructor uses a Negotiate Listener if one isn't passed. /// /// Initializes a new instance of the <see cref="WebDavServer" /> class. /// </summary> /// <param name="store">The /// <see cref="IWebDavStore" /> store object that will provide /// collections and documents for this /// <see cref="WebDavServer" />.</param> /// <param name="listener">The /// <see cref="IHttpListener" /> object that will handle the web server portion of /// the WebDAV server; or /// <c>null</c> to use a fresh one.</param> /// <param name="methodHandlers">A collection of HTTP method handlers to use by this /// <see cref="WebDavServer" />; /// or /// <c>null</c> to use the built-in method handlers.</param> /// <exception cref="System.ArgumentNullException"><para> /// <paramref name="listener" /> is <c>null</c>.</para> /// <para>- or -</para> /// <para> /// <paramref name="store" /> is <c>null</c>.</para></exception> /// <exception cref="System.ArgumentException"><para> /// <paramref name="methodHandlers" /> is empty.</para> /// <para>- or -</para> /// <para> /// <paramref name="methodHandlers" /> contains a <c>null</c>-reference.</para></exception> public WebDavServer(IWebDavStore store, IHttpListener listener = null, IEnumerable<IWebDavMethodHandler> methodHandlers = null) { if (store == null) throw new ArgumentNullException("store"); if (listener == null) { listener = new HttpListenerNegotiateAdapter(); _ownsListener = true; } methodHandlers = methodHandlers ?? WebDavMethodHandlers.BuiltIn; IWebDavMethodHandler[] webDavMethodHandlers = methodHandlers as IWebDavMethodHandler[] ?? methodHandlers.ToArray(); if (!webDavMethodHandlers.Any()) throw new ArgumentException("The methodHandlers collection is empty", "methodHandlers"); if (webDavMethodHandlers.Any(methodHandler => methodHandler == null)) throw new ArgumentException("The methodHandlers collection contains a null-reference", "methodHandlers"); _listener = listener; _store = store; var handlersWithNames = from methodHandler in webDavMethodHandlers from name in methodHandler.Names select new { name, methodHandler }; _methodHandlers = handlersWithNames.ToDictionary(v => v.name, v => v.methodHandler); } #endregion #region Functions /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { lock (_threadLock) { if (_thread != null) Stop(); } if (_ownsListener) _listener.Dispose(); } /// <summary> /// Starts this /// <see cref="WebDavServer" /> and returns once it has /// been started successfully. /// </summary> /// <exception cref="System.InvalidOperationException">This WebDAVServer instance is already running, call to Start is invalid at this point</exception> /// <exception cref="ObjectDisposedException">This <see cref="WebDavServer" /> instance has been disposed of.</exception> /// <exception cref="InvalidOperationException">The server is already running.</exception> public void Start(String url, LoggerConfiguration serilogConfiguration) { Listener.Prefixes.Add(url); EnsureNotDisposed(); lock (_threadLock) { if (_thread != null) { throw new InvalidOperationException( "This WebDAVServer instance is already running, call to Start is invalid at this point"); } _stopEvent = new ManualResetEvent(false); _thread = new Thread(BackgroundThreadMethod) { Name = "WebDAVServer.Thread", Priority = ThreadPriority.Highest }; _thread.Start(); } } /// <summary> /// Starts this /// <see cref="WebDavServer" /> and returns once it has /// been stopped successfully. /// </summary> /// <exception cref="System.InvalidOperationException">This WebDAVServer instance is not running, call to Stop is invalid at this point</exception> /// <exception cref="ObjectDisposedException">This <see cref="WebDavServer" /> instance has been disposed of.</exception> /// <exception cref="InvalidOperationException">The server is not running.</exception> public void Stop() { EnsureNotDisposed(); lock (_threadLock) { if (_thread == null) { throw new InvalidOperationException( "This WebDAVServer instance is not running, call to Stop is invalid at this point"); } _stopEvent.Set(); _thread.Join(); _stopEvent.Close(); _stopEvent = null; _thread = null; } } /// <summary> /// The background thread method. /// </summary> private void BackgroundThreadMethod() { Log.Information("WebDAVServer background thread has started"); try { _listener.Start(); Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { Log.Debug("BackgroundThreadMethod poll ms: {0}", sw.ElapsedMilliseconds); if (_stopEvent.WaitOne(0)) return; sw.Reset(); IHttpListenerContext context = Listener.GetContext(_stopEvent); if (context == null) { Log.Debug("Exiting thread"); return; } Log.Debug("Queued Context request: {0}", context.Request.HttpMethod); ThreadPool.QueueUserWorkItem(ProcessRequest, context); } } catch (Exception ex) { //This error occours if we are not able to queue a request, the whole webdav server //is terminating. Log.Error(String.Format("Web dav ended unexpectedly with error {0}", ex.Message), ex); } finally { _listener.Stop(); Log.Information("WebDAVServer background thread has terminated"); } } /// <summary> /// Called before actual processing is done, useful to do some preliminary /// check or whatever the real implementation need to do. /// </summary> /// <param name="context"></param> protected virtual void OnProcessRequestStarted(IHttpListenerContext context) { } /// <summary> /// Give to derived class the option to do further filtering of users. Even /// if user authentication went good at protocol level (NTLM, Basic, Etc) /// we can still throw an unhautorized exception. /// </summary> /// <param name="context"></param> /// <returns></returns> protected virtual Boolean OnValidateUser(IHttpListenerContext context) { return true; //Default return value, user is always valid. } /// <summary> /// Called after everything was processed, it can be used for doing specific /// cleanup for the real implementation. /// It can also be used to log executed call with something different from the /// standard log4net logger used by the library; this is the reason why this method /// is accepting some information that can be directly used to log information /// as <paramref name="callInfo"/> /// </summary> /// <param name="context"></param> /// <param name="callInfo">String with call information for better logging</param> /// <param name="request">Xml document that contains the full request of the client</param> /// <param name="response">Xml document that contains the full response returned to the client </param> /// <param name="requestHeader">StringBuilder that contains the full request header</param> protected virtual void OnProcessRequestCompleted( IHttpListenerContext context, string callInfo, XmlDocument request, XmlDocument response, StringBuilder requestHeader) { } /// <summary> /// Processes the request. /// </summary> /// <param name="state">The state.</param> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavMethodNotAllowedException">If the method to process is not allowed</exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException">If the user is unauthorized or has no access</exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavNotFoundException">If the item was not found</exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavNotImplementedException">If a method is not yet implemented</exception> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavInternalServerException">If the server had an internal problem</exception> private void ProcessRequest(object state) { IHttpListenerContext context = (IHttpListenerContext)state; XmlDocument request = null; XmlDocument response = null; String xLitmusTest = ""; var xLitmus = context.Request.Headers["X-litmus"]; if (xLitmus != null) { xLitmusTest = String.Format("X-LITMUS[{0}]: ", xLitmus); } OnProcessRequestStarted(context); Thread.SetData(Thread.GetNamedDataSlot(HttpUser), Listener.GetIdentity(context)); String callInfo = String.Format("{0} : {1} : {2}", context.Request.HttpMethod, context.Request.RemoteEndPoint, context.Request.Url); Serilog.Context.LogContext.PushProperty("webdav-request", callInfo); StringBuilder requestHeader = new StringBuilder(); if (WebDavServer.Log.IsEnabled(Serilog.Events.LogEventLevel.Debug)) { foreach (String header in context.Request.Headers) { requestHeader.AppendFormat("{0}: {1}\r\n", header, context.Request.Headers[header]); } } try { try { string method = context.Request.HttpMethod; IWebDavMethodHandler methodHandler; if (!_methodHandlers.TryGetValue(method, out methodHandler)) throw new WebDavMethodNotAllowedException(string.Format(CultureInfo.InvariantCulture, "%s ({0})", context.Request.HttpMethod)); context.Response.AppendHeader("DAV", _davHader); if (!OnValidateUser(context)) { throw new WebDavUnauthorizedException(); } methodHandler.ProcessRequest(this, context, Store, out request, out response); if (WebDavServer.Log.IsEnabled(Serilog.Events.LogEventLevel.Debug)) { string message = CreateLogMessage(context, callInfo, request, response, requestHeader, xLitmusTest); Log.Debug(message); } } catch (WebDavException) { throw; } catch (UnauthorizedAccessException ex) { Log.Information("Unauthorized: " + ex.Message); throw new WebDavUnauthorizedException(); } catch (FileNotFoundException ex) { Log.Warning("(FAILED) WEB-DAV-CALL-ENDED:" + callInfo + ": " + ex.Message, ex); throw new WebDavNotFoundException("FileNotFound", innerException: ex); } catch (DirectoryNotFoundException ex) { Log.Warning("(FAILED) WEB-DAV-CALL-ENDED:" + callInfo + ": " + ex.Message, ex); throw new WebDavNotFoundException("DirectoryNotFound", innerException: ex); } catch (NotImplementedException ex) { Log.Warning("(FAILED) WEB-DAV-CALL-ENDED:" + callInfo + ": " + ex.Message, ex); throw new WebDavNotImplementedException(innerException: ex); } catch (Exception ex) { Log.Error("(FAILED) WEB-DAV-CALL-ENDED:" + callInfo + ": " + ex.Message, ex); throw new WebDavInternalServerException(innerException: ex); } } catch (WebDavException ex) { if (ex is WebDavNotFoundException) { //not found exception is quite common, Windows explorer often ask for files that are not there if (WebDavServer.Log.IsEnabled(Serilog.Events.LogEventLevel.Debug)) { string message = CreateLogMessage(context, callInfo, request, response, requestHeader, xLitmusTest); Log.Debug(message); } } else { string message = CreateLogMessage(context, callInfo, request, response, requestHeader, xLitmusTest); Log.Warning(message, ex); } SendResponseForException(context, ex); } finally { Serilog.Context.LogContext.PushProperty("webdav-request", null); OnProcessRequestCompleted(context, callInfo, request, response, requestHeader); } } private static string CreateLogMessage(IHttpListenerContext context, string callInfo, XmlDocument request, XmlDocument response, StringBuilder requestHeader, String xLitmusTest) { var message = String.Format("{5}WEB-DAV-CALL-ENDED: {0}\r\nREQUEST HEADER\r\n{1}\r\nRESPONSE HEADER\r\n{2}\r\nrequest:{3}\r\nresponse{4}", callInfo, requestHeader, context.Response.DumpHeaders(), request.Beautify(), response.Beautify(), xLitmusTest); return message; } private void SendResponseForException(IHttpListenerContext context, WebDavException ex) { try { context.Response.StatusCode = ex.StatusCode; context.Response.StatusDescription = ex.StatusDescription; var response = ex.GetResponse(context); if (!(context.Request.HttpMethod == "HEAD")) { if (response != context.Response.StatusDescription) { byte[] buffer = Encoding.UTF8.GetBytes(response); context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentLength64 = buffer.Length; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Flush(); } } context.Response.Close(); } catch (Exception innerEx) { Log.Error("Exception cannot be returned to caller: " + ex.Message, ex); Log.Error("Unable to send response for exception: " + innerEx.Message, innerEx); } } #endregion } }
mit
liemqv/EventFlow
Source/EventFlow.Autofac/Properties/AssemblyInfo.cs
960
using System.Reflection; 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("EventFlow.Autofac")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EventFlow.Autofac")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("e9aa6719-9bb0-40d2-aa45-dc024286a2d9")]
mit
xaviersierra/digit-guesser
drawer/src/main/java/xsierra/digitguesser/drawer/pipeline/BinarizeImageStep.java
584
package xsierra.digitguesser.drawer.pipeline; import java.awt.*; import java.awt.image.BufferedImage; public class BinarizeImageStep extends OrderablePipelineStep { public BinarizeImageStep(int stepOpder) { super(stepOpder); } @Override public BufferedImage processImage(BufferedImage img) { BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_BINARY); Graphics g = image.getGraphics(); g.drawImage(img, 0, 0, null); g.dispose(); return image; } }
mit
cmd430/TuneDB
index.js
1713
var cluster = require( 'cluster' ); var cpuCount = require( 'os' ).cpus().length; var cron = require( 'cron' ); var domain = require( 'domain' ); //Deprecated! var app = require( 'express' )(); var config = require( './config.js' ); require( './setup.js' )( config, app ); require( './routes.js' )( app ); if( cluster.isMaster ) { // Fork the child threads for ( var i = 0; i < Math.min( cpuCount, config.threads ); i++ ) { cluster.fork(); } cluster.on('disconnect', function( worker ) { console.error( 'worker ' + worker.process.pid + 'disconnected, spinning up another!' ); cluster.fork(); }); //Only scan for new music on master thread... var scope = domain.create(); scope.run(function() { var helpers = require( './lib/helpers.js' ); try { var job = new cron.CronJob( config.update, function(){ helpers.refreshDatabase(); }, function () { // This function is executed // when the job stops }, true ); console.info( 'Cron job started' ); } catch( ex ) { console.error( 'Cron pattern not valid' ); } // Start update as soon as server launches.. helpers.refreshDatabase(); }); scope.on( 'error', function( err ) { console.error( 'error', er.stack ); //this is not inherently good, and will leak resources //but since this is in the master im not sure how to //handle restarting it without killing the whole server.... }); } else { app.listen( config.port ); }
mit
JohnJosuaPaderon/Citicon
Citicon/DataManager/SupplierManager.cs
6711
using Citicon.Data; using Citicon.DataProcess; using Sorschia; using Sorschia.Extensions; using Sorschia.Queries; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace Citicon.DataManager { public sealed class SupplierManager : DataManager<Supplier>, IDataManager<Supplier> { static SupplierManager() { SupplierDict = new Dictionary<ulong, Supplier>(); } private static Dictionary<ulong, Supplier> SupplierDict { get; } public void Add(Supplier data) { using (var query = new MySqlQuery(Supports.ConnectionString, "_suppliers_add")) { query.AddParameter("@_SupplierId"); query.AddParameter("@_Address", data.Address); query.AddParameter("@_Code", data.Code); query.AddParameter("@_ContactNumber", data.ContactNumber); query.AddParameter("@_Description", data.Description); query.AddParameter("@_CreatedBy", User.CurrentUser?.DisplayName); query.ExceptionCatched += OnExceptionCatched; query.Execute(); if (query.AffectedRows == 1) { data.Id = query.ParameterValues.GetUInt64("@_SupplierId"); OnAdded(data); } else OnAddedUnsuccessful(data); } } public Task AddAsync(Supplier data) { return Task.Factory.StartNew(() => Add(data)); } public Supplier ExtractFromDictionary(Dictionary<string, object> dictionary) { if (dictionary != null) { var supplier = new Supplier { Address = dictionary.GetString("Address"), Code = dictionary.GetString("Code"), ContactNumber = dictionary.GetString("ContactNumber"), Description = dictionary.GetString("Description"), Id = dictionary.GetUInt64("SupplierId") }; if (!SupplierDict.ContainsKey(supplier.Id)) { SupplierDict.Add(supplier.Id, supplier); } return supplier; } else { return null; } } public string GenerateCode() { using (var query = new MySqlQuery(Supports.ConnectionString, "SELECT _suppliers_generatecode();", CommandType.Text)) { query.ExceptionCatched += OnExceptionCatched; return query.GetValue().ToString(); } } public Supplier GetById(ulong id) { if (SupplierDict.ContainsKey(id)) { return SupplierDict[id]; } if (id != 0) { using (var query = new MySqlQuery(Supports.ConnectionString, "_suppliers_getbyid")) { query.AddParameter("@_SupplierId", id); query.ExceptionCatched += OnExceptionCatched; return ExtractFromDictionary(query.GetRecord()); } } return null; } public async Task<Supplier> GetByIdAsync(ulong id) { if (id > 0) { if (SupplierDict.ContainsKey(id)) { return SupplierDict[id]; } else { using (var process = new GetSupplierById(id)) { var result = await process.ExecuteAsync(); if (result != null) { SupplierDict.Add(result.Id, result); } return result; } } } else { return null; } } public Supplier[] GetList() { List<Supplier> suppliers = null; using (var query = new MySqlQuery(Supports.ConnectionString, "_suppliers_getlist")) { query.ExceptionCatched += OnExceptionCatched; query.ActiveRecordChanged += Query_ActiveRecordChanged; var result = query.GetResult(); if (result != null) { suppliers = new List<Supplier>(); foreach (var item in result) { suppliers.Add(ExtractFromDictionary(item)); } } } return suppliers?.ToArray(); } private void Query_ActiveRecordChanged(Dictionary<string, object> e) { OnNewItemGenerated(ExtractFromDictionary(e)); } public async Task<Supplier[]> GetListAsync() { var process = new GetSupplierList(); return (await process.ExecuteAsync()).ToArray(); } public void Remove(Supplier data) { using (var query = new MySqlQuery(Supports.ConnectionString, "_suppliers_remove")) { query.AddParameter("@_SupplierId", data.Id); query.ExceptionCatched += OnExceptionCatched; query.Execute(); if (query.AffectedRows == 1) OnRemoved(data); else OnRemovedUnsuccessful(data); } } public Task RemoveAsync(Supplier data) { return Task.Factory.StartNew(() => Remove(data)); } public void Update(Supplier data) { using (var query = new MySqlQuery(Supports.ConnectionString, "_suppliers_update")) { query.AddParameter("@_SupplierId", data.Id); query.AddParameter("@_Address", data.Address); query.AddParameter("@_Code", data.Code); query.AddParameter("@_ContactNumber", data.ContactNumber); query.AddParameter("@_Description", data.Description); query.AddParameter("@_ModifiedBy", User.CurrentUser?.DisplayName); query.ExceptionCatched += OnExceptionCatched; query.Execute(); if (query.AffectedRows == 1) OnUpdated(data); else OnUpdatedUnsuccessful(data); } } public Task UpdateAsync(Supplier data) { return Task.Factory.StartNew(() => Update(data)); } } }
mit
gauthierm/Cme
www/javascript/cme-disclosure.js
3886
function CMEDisclosure(id, class_name, server, title, content, cancel_uri) { this.id = id; this.class_name = class_name; this.server = server; this.content = content; this.title = title; this.cancel_uri = cancel_uri; YAHOO.util.Event.onDOMReady(this.init, this, true); } CMEDisclosure.confirm_text = 'Before you view %s, please attest to reading the following:'; CMEDisclosure.prototype.init = function() { var header = document.createElement('div'); header.className = 'cme-disclosure-header'; header.appendChild( document.createTextNode( CMEDisclosure.confirm_text.replace(/%s/, this.title) ) ); var continue_button = document.createElement('input'); continue_button.type = 'button'; continue_button.value = 'I Have Read the CME Information / Continue'; continue_button.className = 'button swat-primary-button'; YAHOO.util.Event.on(continue_button, 'click', function(e) { continue_button.disabled = true; this.submitCMEPiece(); }, this, true); var cancel_button = document.createElement('input'); cancel_button.type = 'button'; cancel_button.value = 'Cancel and Return to Episode Guide'; cancel_button.className = 'button cancel-button'; YAHOO.util.Event.on(cancel_button, 'click', function(e) { var base = document.getElementsByTagName('base')[0]; window.location = base.href + this.cancel_uri; }, this, true); var footer = document.createElement('div'); footer.className = 'cme-disclosure-footer'; footer.appendChild(continue_button); footer.appendChild(cancel_button); var content = document.createElement('div'); content.className = 'cme-disclosure-content'; content.innerHTML = this.content; this.scroll_content = document.createElement('div'); this.scroll_content.className = 'cme-disclosure-scroll-content'; this.scroll_content.appendChild(content); this.scroll_content.style.height = (YAHOO.util.Dom.getViewportHeight() - 200) + 'px'; this.container = document.createElement('div'); this.container.id = this.id; this.container.className = this.class_name; this.container.appendChild(header); this.container.appendChild(this.scroll_content); this.container.appendChild(footer); this.overlay = document.createElement('div'); this.overlay.className = 'cme-piece-overlay'; this.overlay.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px'; // Bit of a hack to get the initial height of the overlay correctly. The // page draws slowly and doesn't have the final height when the DOM is // ready. var that = this; setTimeout(function() { that.overlay.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px'; }, 500); YAHOO.util.Event.on(window, 'resize', this.handleResize, this, true); document.body.appendChild(this.overlay); document.body.appendChild(this.container); SwatZIndexManager.raiseElement(this.overlay); SwatZIndexManager.raiseElement(this.container); }; CMEDisclosure.prototype.handleResize = function(e) { this.scroll_content.style.height = (YAHOO.util.Dom.getViewportHeight() - 200) + 'px'; this.overlay.style.height = YAHOO.util.Dom.getDocumentHeight() + 'px'; }; CMEDisclosure.prototype.close = function() { var animation = new YAHOO.util.Anim( this.container, { opacity: { to: 0 }, top: { to: -100 } }, 0.25, YAHOO.util.Easing.easeIn); animation.onComplete.subscribe(function() { this.container.style.display = 'none'; var animation = new YAHOO.util.Anim( this.overlay, { opacity: { to: 0 } }, 0.25, YAHOO.util.Easing.easeOut); animation.onComplete.subscribe(function() { this.overlay.style.display = 'none'; }, this, true); animation.animate(); }, this, true); animation.animate(); }; CMEDisclosure.prototype.submitCMEPiece = function() { var callback = { success: function(o) {}, failure: function(o) {} }; YAHOO.util.Connect.asyncRequest('POST', this.server, callback); this.close(); };
mit
impromptu/impromptu
lib/Log.js
5251
var fs = require('fs') // Required for type checking. var State = require('./State') /** * @constructor * @param {State} state */ function Log(state) { /** @private {State} */ this._state = state /** @private {Log.Level} */ this._verbosity = Log.Level.NOTICE /** * The default destinations of the logs. * @type {Log.Destinations} */ this.defaultDestinations = { file: true, server: false, stdout: false } } /** * The log verbosity level. * * Do not refer to these numbers directly, use their corresponding key-names instead. * Inspired by the Redis log levels. * * Log levels: * warning (only very important / critical messages are logged) * notice (moderately verbose, what you want in production probably) * debug (a lot of information, useful for development/testing) * * @enum {number} */ Log.Level = { WARNING: 1, NOTICE: 2, DEBUG: 3 } /** * The delimiter for each log level. * @enum {string} */ Log.Delimiter = { 1: '#', 2: '*', 3: '-' } /** * Indicates where to send a given message. * * @typedef {{ * file: (boolean|undefined), * server: (boolean|undefined), * stdout: (boolean|undefined) * }} */ Log.Destinations /** * Options that can be passed to the low-level `write` method. * * options.level - Specifies the log level of the message. * Messages without a specified level will always be written. * * options.format - Whether the message should be formatted. * * options.destinations - Whether the message should be written to various destiations. * Defaults to `this.defaultDestinations`. * * @typedef {{ * level: Log.Level, * format: boolean, * destinations: Log.Destinations * }} */ Log.Options /** * @return {Log.Level} The verbosity of the logger. */ Log.prototype.getVerbosity = function() { return this._verbosity } /** * @param {Log.Level|string|number} level The verbosity of the logger. */ Log.prototype.setVerbosity = function(level) { if (level === 'warning' || level === Log.Level.WARNING) { this._verbosity = Log.Level.WARNING } if (level === 'notice' || level === Log.Level.NOTICE) { this._verbosity = Log.Level.NOTICE } if (level === 'debug' || level === Log.Level.DEBUG) { this._verbosity = Log.Level.DEBUG } } /** * Prints a message to stdout. Useful for debugging. * @param {string} message */ Log.prototype.output = function(message) { this.write(message, { level: Log.Level.WARNING, format: false, destinations: { file: false, server: false, stdout: true } }) } /** * Logs a warning message with a corresponding error stack. * @param {string} message * @param {Error} error */ Log.prototype.error = function(message, error) { this.warning(message + "\n\n" + error.stack + "\n----------------------------------------") } /** * Logs a warning message. * @param {string} message */ Log.prototype.warning = function(message) { this.write(message, { level: Log.Level.WARNING, format: true, destinations: this.defaultDestinations }) } /** * Logs a notice. * @param {string} message */ Log.prototype.notice = function(message) { this.write(message, { level: Log.Level.NOTICE, format: true, destinations: this.defaultDestinations }) } /** * Logs a debug message. * @param {string} message */ Log.prototype.debug = function(message) { this.write(message, { level: Log.Level.DEBUG, format: true, destinations: this.defaultDestinations }) } /** * Low-level method to write output and logs. * Accepts a message and an options object. * * @param {string} message * @param {Log.Options} options */ Log.prototype.write = function(message, options) { var destinations if (options.level && options.level > this._verbosity) { return } destinations = options.destinations || this.defaultDestinations if (options.format) { message = this.format(message, options.level) } if (destinations.stdout) { this._writeToStdoutRaw(message) } if (destinations.server) { this._writeToServerRaw(message) } if (destinations.file) { this._writeToFileRaw(message) } } /** * Formats a log message with the process PID and date, with a delimiter that indicates the log level. * @param {string} message * @param {Log.Level} level */ Log.prototype.format = function(message, level) { var delimiter delimiter = Log.Delimiter[level] ? "" + Log.Delimiter[level] + " " : '' return "[" + process.pid + "] " + (new Date().toISOString()) + " " + delimiter + message } /** * Writes a message to a file. * @param {string} message * @private */ Log.prototype._writeToFileRaw = function(message) { fs.appendFileSync(this._state.get('path.log'), message) } /** * Writes a message to a stdout. * @param {string} message * @private */ Log.prototype._writeToStdoutRaw = function(message) { if (process.send && process.connected) { process.send({ type: 'write', data: message + '\n' }) } else { console.log(message) } } /** * Writes a message to the server. * @param {string} message * @private */ Log.prototype._writeToServerRaw = function(message) { console.log(message) } module.exports = Log
mit
NeutronProject/NeutronMvcBundle
Model/Category/CategoryManagerInterface.php
305
<?php namespace Neutron\MvcBundle\Model\Category; interface CategoryManagerInterface { public function findOneBy(array $criteria); public function findBy(array $criteria); public function getQueryBuilderForDataGrid(); public function findCategoryBySlug($slug, $useCache); }
mit
Alfalfamale/P
themes/theme_bootswatch/blocks/form/templates/horizontal.php
5296
<?php /************************************************************ * DESIGNERS: SCROLL DOWN! (IGNORE ALL THIS STUFF AT THE TOP) ************************************************************/ defined('C5_EXECUTE') or die("Access Denied."); $survey = $controller; $miniSurvey = new MiniSurvey($b); $miniSurvey->frontEndMode = true; //Clean up variables from controller so html is easier to work with... $bID = intval($bID); $qsID = intval($survey->questionSetId); $formAction = $this->action('submit_form').'#'.$qsID; $questionsRS = $miniSurvey->loadQuestions($qsID, $bID); $questions = array(); while ($questionRow = $questionsRS->fetchRow()) { $question = $questionRow; $question['input'] = $miniSurvey->loadInputType($questionRow, false); //Make type names common-sensical if ($questionRow['inputType'] == 'text') { $question['type'] = 'textarea'; } else if ($questionRow['inputType'] == 'field') { $question['type'] = 'text'; } else { $question['type'] = $questionRow['inputType']; } //Construct label "for" (and misc. hackery for checkboxlist / radio lists) if ($question['type'] == 'checkboxlist') { $question['input'] = str_replace('<div class="checkboxPair">', '<div class="checkboxPair"><label class="checkbox">', $question['input']); $question['input'] = str_replace("</div>\n", "</label></div>\n", $question['input']); //include linebreak in find/replace string so we don't replace the very last closing </div> (the one that closes the "checkboxList" wrapper div that's around this whole question) } else if ($question['type'] == 'radios') { //Put labels around each radio items (super hacky string replacement -- this might break in future versions of C5) $question['input'] = str_replace('<div class="radioPair">', '<div class="radioPair"><label class="radio">', $question['input']); $question['input'] = str_replace('</div>\n', '</label></div>\n', $question['input']); //Make radioList wrapper consistent with checkboxList wrapper $question['input'] = "<div class=\"radioList\">\n{$question['input']}\n</div>\n"; } else { $question['labelFor'] = 'for="Question' . $questionRow['msqID'] . '"'; } //Remove hardcoded style on textareas if ($question['type'] == 'textarea') { $question['input'] = str_replace('style="width:95%"', '', $question['input']); } $questions[] = $question; } //Prep thank-you message $success = ($_GET['surveySuccess'] && $_GET['qsid'] == intval($qsID)); $thanksMsg = $survey->thankyouMsg; //Collate all errors and put them into divs $errorHeader = $formResponse; $errors = is_array($errors) ? $errors : array(); if ($invalidIP) { $errors[] = $invalidIP; } $errorDivs = ''; foreach ($errors as $error) { $errorDivs .= '<div class="text-error">'.$error."</div>\n"; } //Prep captcha $surveyBlockInfo = $miniSurvey->getMiniSurveyBlockInfoByQuestionId($qsID, $bID); $captcha = $surveyBlockInfo['displayCaptcha'] ? Loader::helper('validation/captcha') : false; //Localized labels $translatedCaptchaLabel = t('Please type the letters and numbers shown in the image.'); $translatedSubmitLabel = t('Submit'); /****************************************************************************** * DESIGNERS: CUSTOMIZE THE FORM HTML STARTING HERE... */?> <div name="<?php echo $survey->questionSetId ?>"></a></div> <?php if ($invalidIP) { ?> <div class="text-error"><?php echo $invalidIP?></div> <?php } ?> <form name="<?php echo $survey->surveyName; ?>" enctype="multipart/form-data" id="form<?php echo $bID; ?>" class="form-horizontal" method="post" action="<?php echo $formAction ?>"> <?php if ($success): ?> <div class="text-success"><?php echo $thanksMsg; ?></div> <?php elseif ($errors): ?> <div class="text-error"> <?php echo $errorHeader; ?><?php echo $errorDivs; ?> </div> <?php endif; ?> <?php foreach ($questions as $question): ?> <div class="control-group"> <label class="control-label" <?php echo $question['labelFor']; ?>> <?php if ($question['required']): ?> <i class="text-error">*</i> <?php endif; ?> <?php echo $question['question']; ?> </label> <div class="controls"> <?php if ($question['required']): ?> <?php $question['input'] = str_replace('<input', '<input required="required"', $question['input']); ?> <?php $question['input'] = str_replace('<textarea', '<textarea required="required"', $question['input']); ?> <?php endif; ?> <?php echo $question['input']; ?> </div> </div> <?php endforeach; ?> <?php if ($captcha): ?> <div class="control-group captcha"> <label class="control-label"><i class="text-error">* </i><?php echo $translatedCaptchaLabel; ?></label> <div class="controls"> <?php $captcha->display(); ?> <?php $captcha->showInput(); ?> </div> </div> <?php endif; ?> <div class="control-group"> <div class="controls"> <button type="submit" class="btn"><?php echo $translatedSubmitLabel; ?></button> </div> </div> <input name="qsID" type="hidden" value="<?php echo $qsID; ?>" /> <input name="pURI" type="hidden" value="<?php echo $pURI; ?>" /> </form>
mit
jbatonnet/system
Source/[Tools]/[Libraries]/SharpFont/Face.cs
83320
#region MIT License /*Copyright (c) 2012-2015 Robert Rouhani <robert.rouhani@gmail.com> SharpFont based on Tao.FreeType, Copyright (c) 2003-2007 Tao Framework Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #endregion using System; using System.Collections.Generic; using System.Runtime.InteropServices; using SharpFont.Bdf; using SharpFont.Internal; using SharpFont.MultipleMasters; using SharpFont.PostScript; using SharpFont.TrueType; namespace SharpFont { /// <summary> /// FreeType root face class structure. A face object models a typeface in a font file. /// </summary> /// <remarks> /// Fields may be changed after a call to <see cref="AttachFile"/> or <see cref="AttachStream"/>. /// </remarks> public sealed class Face : IDisposable { #region Fields private IntPtr reference; private FaceRec rec; private bool disposed; private GCHandle memoryFaceHandle; private Library parentLibrary; private List<FTSize> childSizes; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Face"/> class with a default faceIndex of 0. /// </summary> /// <param name="library">The parent library.</param> /// <param name="path">The path of the font file.</param> public Face(Library library, string path) : this(library, path, 0) { } /// <summary> /// Initializes a new instance of the <see cref="Face"/> class. /// </summary> /// <param name="library">The parent library.</param> /// <param name="path">The path of the font file.</param> /// <param name="faceIndex">The index of the face to take from the file.</param> public Face(Library library, string path, int faceIndex) : this(library) { IntPtr reference; Error err = FT.FT_New_Face(library.Reference, path, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; } //TODO make an overload with a FileStream instead of a byte[] /// <summary> /// Initializes a new instance of the <see cref="Face"/> class from a file that's already loaded into memory. /// </summary> /// <param name="library">The parent library.</param> /// <param name="file">The loaded file.</param> /// <param name="faceIndex">The index of the face to take from the file.</param> public unsafe Face(Library library, byte[] file, int faceIndex) : this(library) { memoryFaceHandle = GCHandle.Alloc(file, GCHandleType.Pinned); IntPtr reference; Error err = FT.FT_New_Memory_Face(library.Reference, memoryFaceHandle.AddrOfPinnedObject(), file.Length, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; } /// <summary> /// Initializes a new instance of the <see cref="Face"/> class from a file that's already loaded into memory. /// </summary> /// <param name="library">The parent library.</param> /// <param name="bufferPtr"></param> /// <param name="length"></param> /// <param name="faceIndex">The index of the face to take from the file.</param> public Face(Library library, IntPtr bufferPtr, int length, int faceIndex) : this(library) { Error err = FT.FT_New_Memory_Face(library.Reference, bufferPtr, length, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; } /// <summary> /// Initializes a new instance of the <see cref="Face"/> class. /// </summary> /// <param name="reference">A pointer to the unmanaged memory containing the Face.</param> /// <param name="parent">The parent <see cref="Library"/>.</param> internal Face(IntPtr reference, Library parent) : this(parent) { Reference = reference; } private Face(Library parent) { childSizes = new List<FTSize>(); if (parent != null) { parentLibrary = parent; parentLibrary.AddChildFace(this); } else { //if there's no parent, this is a marshalled duplicate. FT.FT_Reference_Face(Reference); } } /// <summary> /// Finalizes an instance of the <see cref="Face"/> class. /// </summary> ~Face() { Dispose(false); } #endregion #region Events /// <summary> /// Occurs when the face is disposed. /// </summary> public event EventHandler Disposed; #endregion #region Properties /// <summary> /// Gets a value indicating whether the object has been disposed. /// </summary> public bool IsDisposed { get { return disposed; } } /// <summary> /// Gets the number of faces in the font file. Some font formats can have multiple faces in a font file. /// </summary> public int FaceCount { get { if (disposed) throw new ObjectDisposedException("FaceCount", "Cannot access a disposed object."); return (int)rec.num_faces; } } /// <summary> /// Gets the index of the face in the font file. It is set to 0 if there is only one face in the font file. /// </summary> public int FaceIndex { get { if (disposed) throw new ObjectDisposedException("FaceIndex", "Cannot access a disposed object."); return (int)rec.face_index; } } /// <summary> /// Gets a set of bit flags that give important information about the face. /// </summary> /// <see cref="FaceFlags"/> public FaceFlags FaceFlags { get { if (disposed) throw new ObjectDisposedException("FaceFlags", "Cannot access a disposed object."); return (FaceFlags)rec.face_flags; } } /// <summary> /// Gets a set of bit flags indicating the style of the face. /// </summary> /// <see cref="StyleFlags"/> public StyleFlags StyleFlags { get { if (disposed) throw new ObjectDisposedException("StyleFlags", "Cannot access a disposed object."); return (StyleFlags)rec.style_flags; } } /// <summary><para> /// Gets the number of glyphs in the face. If the face is scalable and has sbits (see ‘num_fixed_sizes’), it is /// set to the number of outline glyphs. /// </para><para> /// For CID-keyed fonts, this value gives the highest CID used in the font. /// </para></summary> public int GlyphCount { get { if (disposed) throw new ObjectDisposedException("GlyphCount", "Cannot access a disposed object."); return (int)rec.num_glyphs; } } /// <summary> /// Gets the face's family name. This is an ASCII string, usually in English, which describes the typeface's /// family (like ‘Times New Roman’, ‘Bodoni’, ‘Garamond’, etc). This is a least common denominator used to list /// fonts. Some formats (TrueType &amp; OpenType) provide localized and Unicode versions of this string. /// Applications should use the format specific interface to access them. Can be NULL (e.g., in fonts embedded /// in a PDF file). /// </summary> public string FamilyName { get { if (disposed) throw new ObjectDisposedException("FamilyName", "Cannot access a disposed object."); return Marshal.PtrToStringAnsi(rec.family_name); } } /// <summary> /// Gets the face's style name. This is an ASCII string, usually in English, which describes the typeface's /// style (like ‘Italic’, ‘Bold’, ‘Condensed’, etc). Not all font formats provide a style name, so this field /// is optional, and can be set to NULL. As for ‘family_name’, some formats provide localized and Unicode /// versions of this string. Applications should use the format specific interface to access them. /// </summary> public string StyleName { get { if (disposed) throw new ObjectDisposedException("StyleName", "Cannot access a disposed object."); return Marshal.PtrToStringAnsi(rec.style_name); } } /// <summary> /// Gets the number of bitmap strikes in the face. Even if the face is scalable, there might still be bitmap /// strikes, which are called ‘sbits’ in that case. /// </summary> public int FixedSizesCount { get { if (disposed) throw new ObjectDisposedException("FixedSizesCount", "Cannot access a disposed object."); return rec.num_fixed_sizes; } } /// <summary> /// Gets an array of FT_Bitmap_Size for all bitmap strikes in the face. It is set to NULL if there is no bitmap /// strike. /// </summary> public BitmapSize[] AvailableSizes { get { if (disposed) throw new ObjectDisposedException("AvailableSizes", "Cannot access a disposed object."); int count = FixedSizesCount; if (count == 0) return null; BitmapSize[] sizes = new BitmapSize[count]; IntPtr array = rec.available_sizes; for (int i = 0; i < count; i++) { sizes[i] = new BitmapSize(new IntPtr(array.ToInt64() + IntPtr.Size * i)); } return sizes; } } /// <summary> /// Gets the number of charmaps in the face. /// </summary> public int CharmapsCount { get { if (disposed) throw new ObjectDisposedException("CharmapsCount", "Cannot access a disposed object."); return rec.num_charmaps; } } /// <summary> /// Gets an array of the charmaps of the face. /// </summary> public CharMap[] CharMaps { get { if (disposed) throw new ObjectDisposedException("CharMaps", "Cannot access a disposed object."); int count = CharmapsCount; if (count == 0) return null; CharMap[] charmaps = new CharMap[count]; unsafe { IntPtr* array = (IntPtr*)rec.charmaps; for (int i = 0; i < count; i++) { charmaps[i] = new CharMap(*array, this); array++; } } return charmaps; } } /// <summary> /// Gets or sets a field reserved for client uses. /// </summary> /// <see cref="Generic"/> [Obsolete("Use the Tag property and Disposed event.")] public Generic Generic { get { if (disposed) throw new ObjectDisposedException("Generic", "Cannot access a disposed object."); return new Generic(rec.generic); } set { if (disposed) throw new ObjectDisposedException("Generic", "Cannot access a disposed object."); //rec.generic = value; value.WriteToUnmanagedMemory(PInvokeHelper.AbsoluteOffsetOf<FaceRec>(Reference, "generic")); Reference = reference; } } /// <summary><para> /// Gets the font bounding box. Coordinates are expressed in font units (see ‘units_per_EM’). The box is large /// enough to contain any glyph from the font. Thus, ‘bbox.yMax’ can be seen as the ‘maximal ascender’, and /// ‘bbox.yMin’ as the ‘minimal descender’. Only relevant for scalable formats. /// </para><para> /// Note that the bounding box might be off by (at least) one pixel for hinted fonts. See FT_Size_Metrics for /// further discussion. /// </para></summary> public BBox BBox { get { if (disposed) throw new ObjectDisposedException("BBox", "Cannot access a disposed object."); return rec.bbox; } } /// <summary> /// Gets the number of font units per EM square for this face. This is typically 2048 for TrueType fonts, and /// 1000 for Type 1 fonts. Only relevant for scalable formats. /// </summary> [CLSCompliant(false)] public ushort UnitsPerEM { get { if (disposed) throw new ObjectDisposedException("UnitsPerEM", "Cannot access a disposed object."); return rec.units_per_EM; } } /// <summary> /// Gets the typographic ascender of the face, expressed in font units. For font formats not having this /// information, it is set to ‘bbox.yMax’. Only relevant for scalable formats. /// </summary> public short Ascender { get { if (disposed) throw new ObjectDisposedException("Ascender", "Cannot access a disposed object."); return rec.ascender; } } /// <summary> /// Gets the typographic descender of the face, expressed in font units. For font formats not having this /// information, it is set to ‘bbox.yMin’.Note that this field is usually negative. Only relevant for scalable /// formats. /// </summary> public short Descender { get { if (disposed) throw new ObjectDisposedException("Descender", "Cannot access a disposed object."); return rec.descender; } } /// <summary> /// Gets the height is the vertical distance between two consecutive baselines, expressed in font units. It is /// always positive. Only relevant for scalable formats. /// </summary> public short Height { get { if (disposed) throw new ObjectDisposedException("Height", "Cannot access a disposed object."); return rec.height; } } /// <summary> /// Gets the maximal advance width, in font units, for all glyphs in this face. This can be used to make word /// wrapping computations faster. Only relevant for scalable formats. /// </summary> public short MaxAdvanceWidth { get { if (disposed) throw new ObjectDisposedException("MaxAdvanceWidth", "Cannot access a disposed object."); return rec.max_advance_width; } } /// <summary> /// Gets the maximal advance height, in font units, for all glyphs in this face. This is only relevant for /// vertical layouts, and is set to ‘height’ for fonts that do not provide vertical metrics. Only relevant for /// scalable formats. /// </summary> public short MaxAdvanceHeight { get { if (disposed) throw new ObjectDisposedException("MaxAdvanceHeight", "Cannot access a disposed object."); return rec.max_advance_height; } } /// <summary> /// Gets the position, in font units, of the underline line for this face. It is the center of the underlining /// stem. Only relevant for scalable formats. /// </summary> public short UnderlinePosition { get { if (disposed) throw new ObjectDisposedException("UnderlinePosition", "Cannot access a disposed object."); return rec.underline_position; } } /// <summary> /// Gets the thickness, in font units, of the underline for this face. Only relevant for scalable formats. /// </summary> public short UnderlineThickness { get { if (disposed) throw new ObjectDisposedException("UnderlineThickness", "Cannot access a disposed object."); return rec.underline_thickness; } } /// <summary> /// Gets the face's associated glyph slot(s). /// </summary> public GlyphSlot Glyph { get { if (disposed) throw new ObjectDisposedException("Glyph", "Cannot access a disposed object."); return new GlyphSlot(rec.glyph, this, parentLibrary); } } /// <summary> /// Gets the current active size for this face. /// </summary> public FTSize Size { get { if (disposed) throw new ObjectDisposedException("Size", "Cannot access a disposed object."); return new FTSize(rec.size, false, this); } } /// <summary> /// Gets the current active charmap for this face. /// </summary> public CharMap CharMap { get { if (disposed) throw new ObjectDisposedException("CharMap", "Cannot access a disposed object."); if (rec.charmap == IntPtr.Zero) return null; return new CharMap(rec.charmap, this); } } /// <summary> /// Gets a value indicating whether a face object contains horizontal metrics (this is true for all font /// formats though). /// </summary> public bool HasHoriziontal { get { return (FaceFlags & FaceFlags.Horizontal) == FaceFlags.Horizontal; } } /// <summary> /// Gets a value indicating whether a face object contains vertical metrics. /// </summary> public bool HasVertical { get { return (FaceFlags & FaceFlags.Vertical) == FaceFlags.Vertical; } } /// <summary> /// Gets a value indicating whether a face object contains kerning data that can be accessed with /// <see cref="GetKerning"/>. /// </summary> public bool HasKerning { get { return (FaceFlags & FaceFlags.Kerning) == FaceFlags.Kerning; } } /// <summary> /// Gets a value indicating whether a face object contains a scalable font face (true for TrueType, Type 1, /// Type 42, CID, OpenType/CFF, and PFR font formats. /// </summary> public bool IsScalable { get { return (FaceFlags & FaceFlags.Scalable) == FaceFlags.Scalable; } } /// <summary><para> /// Gets a value indicating whether a face object contains a font whose format is based on the SFNT storage /// scheme. This usually means: TrueType fonts, OpenType fonts, as well as SFNT-based embedded bitmap fonts. /// </para><para> /// If this macro is true, all functions defined in FT_SFNT_NAMES_H and FT_TRUETYPE_TABLES_H are available. /// </para></summary> public bool IsSfnt { get { return (FaceFlags & FaceFlags.Sfnt) == FaceFlags.Sfnt; } } /// <summary> /// Gets a value indicating whether a face object contains a font face that contains fixed-width (or /// ‘monospace’, ‘fixed-pitch’, etc.) glyphs. /// </summary> public bool IsFixedWidth { get { return (FaceFlags & FaceFlags.FixedWidth) == FaceFlags.FixedWidth; } } /// <summary> /// Gets a value indicating whether a face object contains some embedded bitmaps. /// </summary> /// <see cref="Face.AvailableSizes"/> public bool HasFixedSizes { get { return (FaceFlags & FaceFlags.FixedSizes) == FaceFlags.FixedSizes; } } /// <summary> /// Gets a value indicating whether a face object contains some glyph names that can be accessed through /// <see cref="GetGlyphName(uint, int)"/>. /// </summary> public bool HasGlyphNames { get { return (FaceFlags & FaceFlags.GlyphNames) == FaceFlags.GlyphNames; } } /// <summary> /// Gets a value indicating whether a face object contains some multiple masters. The functions provided by /// FT_MULTIPLE_MASTERS_H are then available to choose the exact design you want. /// </summary> public bool HasMultipleMasters { get { return (FaceFlags & FaceFlags.MultipleMasters) == FaceFlags.MultipleMasters; } } /// <summary><para> /// Gets a value indicating whether a face object contains a CID-keyed font. See the discussion of /// FT_FACE_FLAG_CID_KEYED for more details. /// </para><para> /// If this macro is true, all functions defined in FT_CID_H are available. /// </para></summary> public bool IsCidKeyed { get { return (FaceFlags & FaceFlags.CidKeyed) == FaceFlags.CidKeyed; } } /// <summary> /// Gets a value indicating whether a face represents a ‘tricky’ font. See the discussion of /// FT_FACE_FLAG_TRICKY for more details. /// </summary> public bool IsTricky { get { return (FaceFlags & FaceFlags.Tricky) == FaceFlags.Tricky; } } /// <summary> /// Gets a value indicating whether the font has color glyph tables. /// </summary> public bool HasColor { get { return (FaceFlags & FaceFlags.Color) == FaceFlags.Color; } } /// <summary> /// Gets or sets ser data to identify this instance. Ignored by both FreeType and SharpFont. /// </summary> /// <remarks>This is a replacement for FT_Generic in FreeType.</remarks> public object Tag { get; set; } internal IntPtr Reference { get { if (disposed) throw new ObjectDisposedException("Reference", "Cannot access a disposed object."); return reference; } set { if (disposed) throw new ObjectDisposedException("Reference", "Cannot access a disposed object."); reference = value; rec = PInvokeHelper.PtrToStructure<FaceRec>(reference); } } #endregion #region Methods #region FreeType Version /// <summary><para> /// Parse all bytecode instructions of a TrueType font file to check whether any of the patented opcodes are /// used. This is only useful if you want to be able to use the unpatented hinter with fonts that do not use /// these opcodes. /// </para><para> /// Note that this function parses all glyph instructions in the font file, which may be slow. /// </para></summary> /// <remarks> /// Since May 2010, TrueType hinting is no longer patented. /// </remarks> /// <returns>True if this is a TrueType font that uses one of the patented opcodes, false otherwise.</returns> public bool CheckTrueTypePatents() { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Face_CheckTrueTypePatents(Reference); } /// <summary> /// Enable or disable the unpatented hinter for a given <see cref="Face"/>. Only enable it if you have /// determined that the face doesn't use any patented opcodes. /// </summary> /// <remarks> /// Since May 2010, TrueType hinting is no longer patented. /// </remarks> /// <param name="value">New boolean setting.</param> /// <returns> /// The old setting value. This will always be false if this is not an SFNT font, or if the unpatented hinter /// is not compiled in this instance of the library. /// </returns> /// <see cref="CheckTrueTypePatents"/> public bool SetUnpatentedHinting(bool value) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Face_SetUnpatentedHinting(Reference, value); } #endregion #region Base Interface /// <summary> /// This function calls <see cref="AttachStream"/> to attach a file. /// </summary> /// <param name="path">The pathname.</param> public void AttachFile(string path) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Attach_File(Reference, path); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// ‘Attach’ data to a face object. Normally, this is used to read additional information for the face object. /// For example, you can attach an AFM file that comes with a Type 1 font to get the kerning values and other /// metrics. /// </summary> /// <remarks><para> /// The meaning of the ‘attach’ (i.e., what really happens when the new file is read) is not fixed by FreeType /// itself. It really depends on the font format (and thus the font driver). /// </para><para> /// Client applications are expected to know what they are doing when invoking this function. Most drivers /// simply do not implement file attachments. /// </para></remarks> /// <param name="parameters">A pointer to <see cref="OpenArgs"/> which must be filled by the caller.</param> public void AttachStream(OpenArgs parameters) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Attach_Stream(Reference, parameters.Reference); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Select a bitmap strike. /// </summary> /// <param name="strikeIndex"> /// The index of the bitmap strike in the <see cref="Face.AvailableSizes"/> field of <see cref="Face"/> /// structure. /// </param> public void SelectSize(int strikeIndex) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Select_Size(Reference, strikeIndex); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Resize the scale of the active <see cref="FTSize"/> object in a face. /// </summary> /// <param name="request">A pointer to a <see cref="SizeRequest"/>.</param> public unsafe void RequestSize(SizeRequest request) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Request_Size(Reference, (IntPtr)(&request)); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// This function calls <see cref="RequestSize"/> to request the nominal size (in points). /// </summary> /// <remarks><para> /// If either the character width or height is zero, it is set equal to the other value. /// </para><para> /// If either the horizontal or vertical resolution is zero, it is set equal to the other value. /// </para><para> /// A character width or height smaller than 1pt is set to 1pt; if both resolution values are zero, they are /// set to 72dpi. /// </para></remarks> /// <param name="width">The nominal width, in 26.6 fractional points.</param> /// <param name="height">The nominal height, in 26.6 fractional points.</param> /// <param name="horizontalResolution">The horizontal resolution in dpi.</param> /// <param name="verticalResolution">The vertical resolution in dpi.</param> [CLSCompliant(false)] public void SetCharSize(Fixed26Dot6 width, Fixed26Dot6 height, uint horizontalResolution, uint verticalResolution) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Set_Char_Size(Reference, (IntPtr)width.Value, (IntPtr)height.Value, horizontalResolution, verticalResolution); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// This function calls <see cref="RequestSize"/> to request the nominal size (in pixels). /// </summary> /// <param name="width">The nominal width, in pixels.</param> /// <param name="height">The nominal height, in pixels</param> [CLSCompliant(false)] public void SetPixelSizes(uint width, uint height) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Set_Pixel_Sizes(Reference, width, height); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// A function used to load a single glyph into the glyph slot of a face object. /// </summary> /// <remarks><para> /// The loaded glyph may be transformed. See <see cref="SetTransform()"/> for the details. /// </para><para> /// For subsetted CID-keyed fonts, <see cref="Error.InvalidArgument"/> is returned for invalid CID values (this /// is, for CID values which don't have a corresponding glyph in the font). See the discussion of the /// <see cref="SharpFont.FaceFlags.CidKeyed"/> flag for more details. /// </para></remarks> /// <param name="glyphIndex"> /// The index of the glyph in the font file. For CID-keyed fonts (either in PS or in CFF format) this argument /// specifies the CID value. /// </param> /// <param name="flags"> /// A flag indicating what to load for this glyph. The <see cref="LoadFlags"/> constants can be used to control /// the glyph loading process (e.g., whether the outline should be scaled, whether to load bitmaps or not, /// whether to hint the outline, etc). /// </param> /// <param name="target">The target to OR with the flags.</param> [CLSCompliant(false)] public void LoadGlyph(uint glyphIndex, LoadFlags flags, LoadTarget target) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Load_Glyph(Reference, glyphIndex, (int)flags | (int)target); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// A function used to load a single glyph into the glyph slot of a face object, according to its character /// code. /// </summary> /// <remarks> /// This function simply calls <see cref="GetCharIndex"/> and <see cref="LoadGlyph"/> /// </remarks> /// <param name="charCode"> /// The glyph's character code, according to the current charmap used in the face. /// </param> /// <param name="flags"> /// A flag indicating what to load for this glyph. The <see cref="LoadFlags"/> constants can be used to control /// the glyph loading process (e.g., whether the outline should be scaled, whether to load bitmaps or not, /// whether to hint the outline, etc). /// </param> /// <param name="target">The target to OR with the flags.</param> [CLSCompliant(false)] public void LoadChar(uint charCode, LoadFlags flags, LoadTarget target) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Load_Char(Reference, charCode, (int)flags | (int)target); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// A function used to set the transformation that is applied to glyph images when they are loaded into a glyph /// slot through <see cref="LoadGlyph"/>. /// </summary> /// <remarks><para> /// The transformation is only applied to scalable image formats after the glyph has been loaded. It means that /// hinting is unaltered by the transformation and is performed on the character size given in the last call to /// <see cref="SetCharSize"/> or <see cref="SetPixelSizes"/>. /// </para><para> /// Note that this also transforms the ‘face.glyph.advance’ field, but not the values in ‘face.glyph.metrics’. /// </para></remarks> /// <param name="matrix"> /// A pointer to the transformation's 2x2 matrix. Use the method overloads for the identity matrix. /// </param> /// <param name="delta"> /// A pointer to the translation vector. Use the method overloads for the null vector. /// </param> public unsafe void SetTransform(FTMatrix matrix, FTVector delta) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); FT.FT_Set_Transform(Reference, (IntPtr)(&matrix), (IntPtr)(&delta)); } /// <summary> /// A function used to set the transformation that is applied to glyph images when they are loaded into a glyph /// slot through <see cref="LoadGlyph"/> with the identity matrix. /// </summary> /// <remarks><para> /// The transformation is only applied to scalable image formats after the glyph has been loaded. It means that /// hinting is unaltered by the transformation and is performed on the character size given in the last call to /// <see cref="SetCharSize"/> or <see cref="SetPixelSizes"/>. /// </para><para> /// Note that this also transforms the ‘face.glyph.advance’ field, but not the values in ‘face.glyph.metrics’. /// </para></remarks> /// <param name="delta"> /// A pointer to the translation vector. Use the method overloads for the null vector. /// </param> public unsafe void SetTransform(FTVector delta) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); FT.FT_Set_Transform(Reference, IntPtr.Zero, (IntPtr)(&delta)); } /// <summary> /// A function used to set the transformation that is applied to glyph images when they are loaded into a glyph /// slot through <see cref="LoadGlyph"/> with the null vector. /// </summary> /// <remarks><para> /// The transformation is only applied to scalable image formats after the glyph has been loaded. It means that /// hinting is unaltered by the transformation and is performed on the character size given in the last call to /// <see cref="SetCharSize"/> or <see cref="SetPixelSizes"/>. /// </para><para> /// Note that this also transforms the ‘face.glyph.advance’ field, but not the values in ‘face.glyph.metrics’. /// </para></remarks> /// <param name="matrix"> /// A pointer to the transformation's 2x2 matrix. Use the method overloads for the identity matrix. /// </param> public unsafe void SetTransform(FTMatrix matrix) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); FT.FT_Set_Transform(Reference, (IntPtr)(&matrix), IntPtr.Zero); } /// <summary> /// A function used to set the transformation that is applied to glyph images when they are loaded into a glyph /// slot through <see cref="LoadGlyph"/> with the null vector and the identity matrix. /// </summary> /// <remarks><para> /// The transformation is only applied to scalable image formats after the glyph has been loaded. It means that /// hinting is unaltered by the transformation and is performed on the character size given in the last call to /// <see cref="SetCharSize"/> or <see cref="SetPixelSizes"/>. /// </para><para> /// Note that this also transforms the ‘face.glyph.advance’ field, but not the values in ‘face.glyph.metrics’. /// </para></remarks> public unsafe void SetTransform() { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); FT.FT_Set_Transform(Reference, IntPtr.Zero, IntPtr.Zero); } /// <summary> /// Return the kerning vector between two glyphs of a same face. /// </summary> /// <remarks> /// Only horizontal layouts (left-to-right &amp; right-to-left) are supported by this method. Other layouts, or /// more sophisticated kernings, are out of the scope of this API function -- they can be implemented through /// format-specific interfaces. /// </remarks> /// <param name="leftGlyph">The index of the left glyph in the kern pair.</param> /// <param name="rightGlyph">The index of the right glyph in the kern pair.</param> /// <param name="mode">Determines the scale and dimension of the returned kerning vector.</param> /// <returns> /// The kerning vector. This is either in font units or in pixels (26.6 format) for scalable formats, and in /// pixels for fixed-sizes formats. /// </returns> [CLSCompliant(false)] public FTVector26Dot6 GetKerning(uint leftGlyph, uint rightGlyph, KerningMode mode) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); FTVector26Dot6 kern; Error err = FT.FT_Get_Kerning(Reference, leftGlyph, rightGlyph, (uint)KerningMode.Unscaled, out kern); if (err != Error.Ok) throw new FreeTypeException(err); return kern; } /// <summary> /// Return the track kerning for a given face object at a given size. /// </summary> /// <param name="pointSize">The point size in 16.16 fractional points.</param> /// <param name="degree">The degree of tightness.</param> /// <returns>The kerning in 16.16 fractional points.</returns> public Fixed16Dot16 GetTrackKerning(Fixed16Dot16 pointSize, int degree) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); IntPtr kerning; Error err = FT.FT_Get_Track_Kerning(Reference, (IntPtr)pointSize.Value, degree, out kerning); if (err != Error.Ok) throw new FreeTypeException(err); return Fixed16Dot16.FromRawValue((int)kerning); } /// <summary> /// Retrieve the ASCII name of a given glyph in a face. This only works for those faces where /// <see cref="HasGlyphNames"/> returns 1. /// </summary> /// <remarks><para> /// An error is returned if the face doesn't provide glyph names or if the glyph index is invalid. In all cases /// of failure, the first byte of ‘buffer’ is set to 0 to indicate an empty name. /// </para><para> /// The glyph name is truncated to fit within the buffer if it is too long. The returned string is always /// zero-terminated. /// </para><para> /// Be aware that FreeType reorders glyph indices internally so that glyph index 0 always corresponds to the /// ‘missing glyph’ (called ‘.notdef’). /// </para><para> /// This function is not compiled within the library if the config macro ‘FT_CONFIG_OPTION_NO_GLYPH_NAMES’ is /// defined in ‘include/freetype/config/ftoptions.h’. /// </para></remarks> /// <param name="glyphIndex">The glyph index.</param> /// <param name="bufferSize">The maximal number of bytes available in the buffer.</param> /// <returns>The ASCII name of a given glyph in a face.</returns> [CLSCompliant(false)] public string GetGlyphName(uint glyphIndex, int bufferSize) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return GetGlyphName(glyphIndex, new byte[bufferSize]); } /// <summary> /// Retrieve the ASCII name of a given glyph in a face. This only works for those faces where /// <see cref="HasGlyphNames"/> returns 1. /// </summary> /// <remarks><para> /// An error is returned if the face doesn't provide glyph names or if the glyph index is invalid. In all cases /// of failure, the first byte of ‘buffer’ is set to 0 to indicate an empty name. /// </para><para> /// The glyph name is truncated to fit within the buffer if it is too long. The returned string is always /// zero-terminated. /// </para><para> /// Be aware that FreeType reorders glyph indices internally so that glyph index 0 always corresponds to the /// ‘missing glyph’ (called ‘.notdef’). /// </para><para> /// This function is not compiled within the library if the config macro ‘FT_CONFIG_OPTION_NO_GLYPH_NAMES’ is /// defined in ‘include/freetype/config/ftoptions.h’. /// </para></remarks> /// <param name="glyphIndex">The glyph index.</param> /// <param name="buffer">The target buffer where the name is copied to.</param> /// <returns>The ASCII name of a given glyph in a face.</returns> [CLSCompliant(false)] public unsafe string GetGlyphName(uint glyphIndex, byte[] buffer) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); fixed (byte* ptr = buffer) { IntPtr intptr = new IntPtr(ptr); Error err = FT.FT_Get_Glyph_Name(Reference, glyphIndex, intptr, (uint)buffer.Length); if (err != Error.Ok) throw new FreeTypeException(err); return Marshal.PtrToStringAnsi(intptr); } } /// <summary> /// Retrieve the ASCII Postscript name of a given face, if available. This only works with Postscript and /// TrueType fonts. /// </summary> /// <remarks> /// The returned pointer is owned by the face and is destroyed with it. /// </remarks> /// <returns>A pointer to the face's Postscript name. NULL if unavailable.</returns> public string GetPostscriptName() { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return Marshal.PtrToStringAnsi(FT.FT_Get_Postscript_Name(Reference)); } /// <summary> /// Select a given charmap by its encoding tag (as listed in ‘freetype.h’). /// </summary> /// <remarks><para> /// This function returns an error if no charmap in the face corresponds to the encoding queried here. /// </para><para> /// Because many fonts contain more than a single cmap for Unicode encoding, this function has some special /// code to select the one which covers Unicode best. It is thus preferable to <see cref="SetCharmap"/> in /// this case. /// </para></remarks> /// <param name="encoding">A handle to the selected encoding.</param> [CLSCompliant(false)] public void SelectCharmap(Encoding encoding) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Select_Charmap(Reference, encoding); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Select a given charmap for character code to glyph index mapping. /// </summary> /// <remarks> /// This function returns an error if the charmap is not part of the face (i.e., if it is not listed in the /// <see cref="Face.CharMaps"/>’ table). /// </remarks> /// <param name="charmap">A handle to the selected charmap.</param> public void SetCharmap(CharMap charmap) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); Error err = FT.FT_Set_Charmap(Reference, charmap.Reference); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Return the glyph index of a given character code. This function uses a charmap object to do the mapping. /// </summary> /// <remarks> /// If you use FreeType to manipulate the contents of font files directly, be aware that the glyph index /// returned by this function doesn't always correspond to the internal indices used within the file. This is /// done to ensure that value 0 always corresponds to the ‘missing glyph’. /// </remarks> /// <param name="charCode">The character code.</param> /// <returns>The glyph index. 0 means ‘undefined character code’.</returns> [CLSCompliant(false)] public uint GetCharIndex(uint charCode) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Get_Char_Index(Reference, charCode); } /// <summary> /// This function is used to return the first character code in the current charmap of a given face. It also /// returns the corresponding glyph index. /// </summary> /// <remarks><para> /// You should use this function with <see cref="GetNextChar"/> to be able to parse all character codes /// available in a given charmap. /// </para><para> /// Note that ‘agindex’ is set to 0 if the charmap is empty. The result itself can be 0 in two cases: if the /// charmap is empty or when the value 0 is the first valid character code. /// </para></remarks> /// <param name="glyphIndex">Glyph index of first character code. 0 if charmap is empty.</param> /// <returns>The charmap's first character code.</returns> [CLSCompliant(false)] public uint GetFirstChar(out uint glyphIndex) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Get_First_Char(Reference, out glyphIndex); } /// <summary> /// This function is used to return the next character code in the current charmap of a given face following /// the value ‘charCode’, as well as the corresponding glyph index. /// </summary> /// <remarks><para> /// You should use this function with <see cref="GetFirstChar"/> to walk over all character codes available /// in a given charmap. See the note for this function for a simple code example. /// </para><para> /// Note that ‘*agindex’ is set to 0 when there are no more codes in the charmap. /// </para></remarks> /// <param name="charCode">The starting character code.</param> /// <param name="glyphIndex">Glyph index of first character code. 0 if charmap is empty.</param> /// <returns>The charmap's next character code.</returns> [CLSCompliant(false)] public uint GetNextChar(uint charCode, out uint glyphIndex) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Get_Next_Char(Reference, charCode, out glyphIndex); } /// <summary> /// Return the glyph index of a given glyph name. This function uses driver specific objects to do the /// translation. /// </summary> /// <param name="name">The glyph name.</param> /// <returns>The glyph index. 0 means ‘undefined character code’.</returns> [CLSCompliant(false)] public uint GetNameIndex(string name) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Get_Name_Index(Reference, Marshal.StringToHGlobalAuto(name)); } /// <summary> /// Return the <see cref="EmbeddingTypes"/> flags for a font. /// </summary> /// <remarks> /// Use this function rather than directly reading the ‘fs_type’ field in the <see cref="PostScript.FontInfo"/> /// structure which is only guaranteed to return the correct results for Type 1 fonts. /// </remarks> /// <returns>The fsType flags, <see cref="EmbeddingTypes"/>.</returns> [CLSCompliant(false)] public EmbeddingTypes GetFSTypeFlags() { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Get_FSType_Flags(Reference); } #endregion #region Glyph Variants /// <summary> /// Return the glyph index of a given character code as modified by the variation selector. /// </summary> /// <remarks><para> /// If you use FreeType to manipulate the contents of font files directly, be aware that the glyph index /// returned by this function doesn't always correspond to the internal indices used within the file. This is /// done to ensure that value 0 always corresponds to the ‘missing glyph’. /// </para><para> /// This function is only meaningful if a) the font has a variation selector cmap sub table, and b) the current /// charmap has a Unicode encoding. /// </para></remarks> /// <param name="charCode">The character code point in Unicode.</param> /// <param name="variantSelector">The Unicode code point of the variation selector.</param> /// <returns> /// The glyph index. 0 means either ‘undefined character code’, or ‘undefined selector code’, or ‘no variation /// selector cmap subtable’, or ‘current CharMap is not Unicode’. /// </returns> [CLSCompliant(false)] public uint GetCharVariantIndex(uint charCode, uint variantSelector) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Face_GetCharVariantIndex(Reference, charCode, variantSelector); } /// <summary> /// Check whether this variant of this Unicode character is the one to be found in the ‘cmap’. /// </summary> /// <remarks> /// This function is only meaningful if the font has a variation selector cmap subtable. /// </remarks> /// <param name="charCode">The character codepoint in Unicode.</param> /// <param name="variantSelector">The Unicode codepoint of the variation selector.</param> /// <returns> /// 1 if found in the standard (Unicode) cmap, 0 if found in the variation selector cmap, or -1 if it is not a /// variant. /// </returns> [CLSCompliant(false)] public int GetCharVariantIsDefault(uint charCode, uint variantSelector) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); return FT.FT_Face_GetCharVariantIsDefault(Reference, charCode, variantSelector); } /// <summary> /// Return a zero-terminated list of Unicode variant selectors found in the font. /// </summary> /// <remarks> /// The last item in the array is 0; the array is owned by the <see cref="Face"/> object but can be overwritten /// or released on the next call to a FreeType function. /// </remarks> /// <returns> /// A pointer to an array of selector code points, or NULL if there is no valid variant selector cmap subtable. /// </returns> [CLSCompliant(false)] public uint[] GetVariantSelectors() { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); IntPtr ptr = FT.FT_Face_GetVariantSelectors(Reference); List<uint> list = new List<uint>(); //temporary non-zero value to prevent complaining about uninitialized variable. uint curValue = 1; for (int i = 0; curValue != 0; i++) { curValue = (uint)Marshal.ReadInt32(Reference, sizeof(uint) * i); list.Add(curValue); } return list.ToArray(); } /// <summary> /// Return a zero-terminated list of Unicode variant selectors found in the font. /// </summary> /// <remarks> /// The last item in the array is 0; the array is owned by the <see cref="Face"/> object but can be overwritten /// or released on the next call to a FreeType function. /// </remarks> /// <param name="charCode">The character codepoint in Unicode.</param> /// <returns> /// A pointer to an array of variant selector code points which are active for the given character, or NULL if /// the corresponding list is empty. /// </returns> [CLSCompliant(false)] public uint[] GetVariantsOfChar(uint charCode) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); IntPtr ptr = FT.FT_Face_GetVariantsOfChar(Reference, charCode); List<uint> list = new List<uint>(); //temporary non-zero value to prevent complaining about uninitialized variable. uint curValue = 1; for (int i = 0; curValue != 0; i++) { curValue = (uint)Marshal.ReadInt32(Reference, sizeof(uint) * i); list.Add(curValue); } return list.ToArray(); } /// <summary> /// Return a zero-terminated list of Unicode character codes found for the specified variant selector. /// </summary> /// <remarks> /// The last item in the array is 0; the array is owned by the <see cref="Face"/> object but can be overwritten /// or released on the next call to a FreeType function. /// </remarks> /// <param name="variantSelector">The variant selector code point in Unicode.</param> /// <returns> /// A list of all the code points which are specified by this selector (both default and non-default codes are /// returned) or NULL if there is no valid cmap or the variant selector is invalid. /// </returns> [CLSCompliant(false)] public uint[] GetCharsOfVariant(uint variantSelector) { if (disposed) throw new ObjectDisposedException("face", "Cannot access a disposed object."); IntPtr ptr = FT.FT_Face_GetCharsOfVariant(Reference, variantSelector); List<uint> list = new List<uint>(); //temporary non-zero value to prevent complaining about uninitialized variable. uint curValue = 1; for (int i = 0; curValue != 0; i++) { curValue = (uint)Marshal.ReadInt32(Reference, sizeof(uint) * i); list.Add(curValue); } return list.ToArray(); } #endregion #region Size Management /// <summary> /// Create a new size object from a given face object. /// </summary> /// <remarks> /// You need to call <see cref="FTSize.Activate"/> in order to select the new size for upcoming calls to /// <see cref="SetPixelSizes"/>, <see cref="SetCharSize"/>, <see cref="LoadGlyph"/>, <see cref="LoadChar"/>, /// etc. /// </remarks> /// <returns>A handle to a new size object.</returns> public FTSize NewSize() { return new FTSize(this); } #endregion #region Multiple Masters /// <summary><para> /// Retrieve the Multiple Master descriptor of a given font. /// </para><para> /// This function can't be used with GX fonts. /// </para></summary> /// <returns>The Multiple Masters descriptor.</returns> public MultiMaster GetMultiMaster() { IntPtr masterRef; Error err = FT.FT_Get_Multi_Master(Reference, out masterRef); if (err != Error.Ok) throw new FreeTypeException(err); return new MultiMaster(masterRef); } /// <summary> /// Retrieve the Multiple Master/GX var descriptor of a given font. /// </summary> /// <returns> /// The Multiple Masters/GX var descriptor. Allocates a data structure, which the user must free (a single call /// to FT_FREE will do it). /// </returns> public MMVar GetMMVar() { IntPtr varRef; Error err = FT.FT_Get_MM_Var(Reference, out varRef); if (err != Error.Ok) throw new FreeTypeException(err); return new MMVar(varRef); } /// <summary><para> /// For Multiple Masters fonts, choose an interpolated font design through design coordinates. /// </para><para> /// This function can't be used with GX fonts. /// </para></summary> /// <param name="coords">An array of design coordinates.</param> public unsafe void SetMMDesignCoordinates(long[] coords) { fixed (void* ptr = coords) { IntPtr coordsPtr = (IntPtr)ptr; Error err = FT.FT_Set_MM_Design_Coordinates(Reference, (uint)coords.Length, coordsPtr); if (err != Error.Ok) throw new FreeTypeException(err); } } /// <summary> /// For Multiple Master or GX Var fonts, choose an interpolated font design through design coordinates. /// </summary> /// <param name="coords">An array of design coordinates.</param> public unsafe void SetVarDesignCoordinates(long[] coords) { fixed (void* ptr = coords) { IntPtr coordsPtr = (IntPtr)ptr; Error err = FT.FT_Set_Var_Design_Coordinates(Reference, (uint)coords.Length, coordsPtr); if (err != Error.Ok) throw new FreeTypeException(err); } } /// <summary> /// For Multiple Masters and GX var fonts, choose an interpolated font design through normalized blend /// coordinates. /// </summary> /// <param name="coords">The design coordinates array (each element must be between 0 and 1.0).</param> public unsafe void SetMMBlendCoordinates(long[] coords) { fixed (void* ptr = coords) { IntPtr coordsPtr = (IntPtr)ptr; Error err = FT.FT_Set_MM_Blend_Coordinates(Reference, (uint)coords.Length, coordsPtr); if (err != Error.Ok) throw new FreeTypeException(err); } } /// <summary> /// This is another name of <see cref="SetMMBlendCoordinates"/>. /// </summary> /// <param name="coords">The design coordinates array (each element must be between 0 and 1.0).</param> public unsafe void SetVarBlendCoordinates(long[] coords) { fixed (void* ptr = coords) { IntPtr coordsPtr = (IntPtr)ptr; Error err = FT.FT_Set_Var_Blend_Coordinates(Reference, (uint)coords.Length, coordsPtr); if (err != Error.Ok) throw new FreeTypeException(err); } } #endregion #region TrueType Tables /// <summary> /// Return a pointer to a given SFNT table within a face. /// </summary> /// <remarks><para> /// The table is owned by the face object and disappears with it. /// </para><para> /// This function is only useful to access SFNT tables that are loaded by the sfnt, truetype, and opentype /// drivers. See <see cref="SfntTag"/> for a list. /// </para></remarks> /// <param name="tag">The index of the SFNT table.</param> /// <returns><para> /// A type-less pointer to the table. This will be 0 in case of error, or if the corresponding table was not /// found OR loaded from the file. /// </para><para> /// Use a typecast according to ‘tag’ to access the structure elements. /// </para></returns> public object GetSfntTable(SfntTag tag) { IntPtr tableRef = FT.FT_Get_Sfnt_Table(Reference, tag); if (tableRef == IntPtr.Zero) return null; switch (tag) { case SfntTag.Header: return new Header(tableRef); case SfntTag.HorizontalHeader: return new HoriHeader(tableRef); case SfntTag.MaxProfile: return new MaxProfile(tableRef); case SfntTag.OS2: return new OS2(tableRef); case SfntTag.Pclt: return new Pclt(tableRef); case SfntTag.Postscript: return new Postscript(tableRef); case SfntTag.VertHeader: return new VertHeader(tableRef); default: return null; } } /// <summary> /// Load any font table into client memory. /// </summary> /// <remarks> /// If you need to determine the table's length you should first call this function with ‘*length’ set to 0, as /// in the following example: /// <code> /// FT_ULong length = 0; /// /// /// error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &amp;length ); /// if ( error ) { ... table does not exist ... } /// /// buffer = malloc( length ); /// if ( buffer == NULL ) { ... not enough memory ... } /// /// error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &amp;length ); /// if ( error ) { ... could not load table ... } /// </code> /// </remarks> /// <param name="tag"> /// The four-byte tag of the table to load. Use the value 0 if you want to access the whole font file. /// Otherwise, you can use one of the definitions found in the FT_TRUETYPE_TAGS_H file, or forge a new one with /// FT_MAKE_TAG. /// </param> /// <param name="offset">The starting offset in the table (or file if tag == 0).</param> /// <param name="buffer"> /// The target buffer address. The client must ensure that the memory array is big enough to hold the data. /// </param> /// <param name="length"><para> /// If the ‘length’ parameter is NULL, then try to load the whole table. Return an error code if it fails. /// </para><para> /// Else, if ‘*length’ is 0, exit immediately while returning the table's (or file) full size in it. /// </para><para> /// Else the number of bytes to read from the table or file, from the starting offset. /// </para></param> [CLSCompliant(false)] public void LoadSfntTable(uint tag, int offset, IntPtr buffer, ref uint length) { Error err = FT.FT_Load_Sfnt_Table(Reference, tag, offset, buffer, ref length); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Return information on an SFNT table. /// </summary> /// <param name="tableIndex"> /// The index of an SFNT table. The function returns <see cref="Error.TableMissing"/> for an invalid value. /// </param> /// <param name="tag"> /// The name tag of the SFNT table. If the value is NULL, ‘table_index’ is ignored, and ‘length’ returns the /// number of SFNT tables in the font. /// </param> /// <returns>The length of the SFNT table (or the number of SFNT tables, depending on ‘tag’).</returns> [CLSCompliant(false)] public unsafe uint SfntTableInfo(uint tableIndex, SfntTag tag) { uint length; Error err = FT.FT_Sfnt_Table_Info(Reference, tableIndex, &tag, out length); if (err != Error.Ok) throw new FreeTypeException(err); return length; } /// <summary> /// Only gets the number of SFNT tables. /// </summary> /// <returns>The number of SFNT tables.</returns> [CLSCompliant(false)] public unsafe uint SfntTableInfo() { uint length; Error err = FT.FT_Sfnt_Table_Info(Reference, 0, null, out length); if (err != Error.Ok) throw new FreeTypeException(err); return length; } #endregion #region Type 1 Tables /// <summary><para> /// Return true if a given face provides reliable PostScript glyph names. This is similar to using the /// <see cref="HasGlyphNames"/> macro, except that certain fonts (mostly TrueType) contain incorrect /// glyph name tables. /// </para><para> /// When this function returns true, the caller is sure that the glyph names returned by /// <see cref="GetGlyphName(uint, int)"/> are reliable. /// </para></summary> /// <returns>Boolean. True if glyph names are reliable.</returns> public bool HasPSGlyphNames() { return FT.FT_Has_PS_Glyph_Names(Reference); } /// <summary> /// Retrieve the <see cref="PostScript.FontInfo"/> structure corresponding to a given PostScript font. /// </summary> /// <remarks><para> /// The string pointers within the font info structure are owned by the face and don't need to be freed by the /// caller. /// </para><para> /// If the font's format is not PostScript-based, this function will return the /// <see cref="Error.InvalidArgument"/> error code. /// </para></remarks> /// <returns>Output font info structure pointer.</returns> public FontInfo GetPSFontInfo() { IntPtr fontInfoRef; Error err = FT.FT_Get_PS_Font_Info(Reference, out fontInfoRef); if (err != Error.Ok) throw new FreeTypeException(err); return new FontInfo(fontInfoRef); } /// <summary> /// Retrieve the <see cref="PostScript.Private"/> structure corresponding to a given PostScript font. /// </summary> /// <remarks><para> /// The string pointers within the <see cref="PostScript.Private"/> structure are owned by the face and don't /// need to be freed by the caller. /// </para><para> /// If the font's format is not PostScript-based, this function returns the <see cref="Error.InvalidArgument"/> /// error code. /// </para></remarks> /// <returns>Output private dictionary structure pointer.</returns> public Private GetPSFontPrivate() { IntPtr privateRef; Error err = FT.FT_Get_PS_Font_Private(Reference, out privateRef); if (err != Error.Ok) throw new FreeTypeException(err); return new Private(privateRef); } /// <summary> /// Retrieve the value for the supplied key from a PostScript font. /// </summary> /// <remarks><para> /// The values returned are not pointers into the internal structures of the face, but are ‘fresh’ copies, so /// that the memory containing them belongs to the calling application. This also enforces the ‘read-only’ /// nature of these values, i.e., this function cannot be used to manipulate the face. /// </para><para> /// ‘value’ is a void pointer because the values returned can be of various types. /// </para><para> /// If either ‘value’ is NULL or ‘value_len’ is too small, just the required memory size for the requested /// entry is returned. /// </para><para> /// The ‘idx’ parameter is used, not only to retrieve elements of, for example, the FontMatrix or FontBBox, but /// also to retrieve name keys from the CharStrings dictionary, and the charstrings themselves. It is ignored /// for atomic values. /// </para><para> /// <see cref="PostScript.DictionaryKeys.BlueScale"/> returns a value that is scaled up by 1000. To get the /// value as in the font stream, you need to divide by 65536000.0 (to remove the FT_Fixed scale, and the x1000 /// scale). /// </para><para> /// IMPORTANT: Only key/value pairs read by the FreeType interpreter can be retrieved. So, for example, /// PostScript procedures such as NP, ND, and RD are not available. Arbitrary keys are, obviously, not be /// available either. /// </para><para> /// If the font's format is not PostScript-based, this function returns the <see cref="Error.InvalidArgument"/> /// error code. /// </para></remarks> /// <param name="key">An enumeration value representing the dictionary key to retrieve.</param> /// <param name="idx">For array values, this specifies the index to be returned.</param> /// <param name="value">A pointer to memory into which to write the value.</param> /// <param name="valueLength">The size, in bytes, of the memory supplied for the value.</param> /// <returns> /// The amount of memory (in bytes) required to hold the requested value (if it exists, -1 otherwise). /// </returns> [CLSCompliant(false)] public int GetPSFontValue(DictionaryKeys key, uint idx, ref IntPtr value, int valueLength) { return FT.FT_Get_PS_Font_Value(Reference, key, idx, ref value, valueLength); } #endregion #region SFNT Names /// <summary> /// Retrieve the number of name strings in the SFNT ‘name’ table. /// </summary> /// <returns>The number of strings in the ‘name’ table.</returns> [CLSCompliant(false)] public uint GetSfntNameCount() { return FT.FT_Get_Sfnt_Name_Count(Reference); } /// <summary> /// Retrieve a string of the SFNT ‘name’ table for a given index. /// </summary> /// <remarks><para> /// The ‘string’ array returned in the ‘aname’ structure is not null-terminated. The application should /// deallocate it if it is no longer in use. /// </para><para> /// Use <see cref="GetSfntNameCount"/> to get the total number of available ‘name’ table entries, then do a /// loop until you get the right platform, encoding, and name ID. /// </para></remarks> /// <param name="idx">The index of the ‘name’ string.</param> /// <returns>The indexed <see cref="SfntName"/> structure.</returns> [CLSCompliant(false)] public SfntName GetSfntName(uint idx) { IntPtr nameRef; Error err = FT.FT_Get_Sfnt_Name(Reference, idx, out nameRef); if (err != Error.Ok) throw new FreeTypeException(err); return new SfntName(nameRef); } #endregion #region BDF and PCF Files /// <summary> /// Retrieve a BDF font character set identity, according to the BDF specification. /// </summary> /// <remarks> /// This function only works with BDF faces, returning an error otherwise. /// </remarks> /// <param name="encoding">Charset encoding, as a C string, owned by the face.</param> /// <param name="registry">Charset registry, as a C string, owned by the face.</param> public void GetBdfCharsetId(out string encoding, out string registry) { Error err = FT.FT_Get_BDF_Charset_ID(Reference, out encoding, out registry); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Retrieve a BDF property from a BDF or PCF font file. /// </summary> /// <remarks><para> /// This function works with BDF and PCF fonts. It returns an error otherwise. It also returns an error if the /// property is not in the font. /// </para><para> /// A ‘property’ is a either key-value pair within the STARTPROPERTIES ... ENDPROPERTIES block of a BDF font or /// a key-value pair from the ‘info->props’ array within a ‘FontRec’ structure of a PCF font. /// </para><para> /// Integer properties are always stored as ‘signed’ within PCF fonts; consequently, /// <see cref="PropertyType.Cardinal"/> is a possible return value for BDF fonts only. /// </para><para> /// In case of error, ‘aproperty->type’ is always set to <see cref="PropertyType.None"/>. /// </para></remarks> /// <param name="propertyName">The property name.</param> /// <returns>The property.</returns> public Property GetBdfProperty(string propertyName) { IntPtr propertyRef; Error err = FT.FT_Get_BDF_Property(Reference, propertyName, out propertyRef); if (err != Error.Ok) throw new FreeTypeException(err); return new Property(propertyRef); } #endregion #region CID Fonts /// <summary> /// Retrieve the Registry/Ordering/Supplement triple (also known as the "R/O/S") from a CID-keyed font. /// </summary> /// <remarks> /// This function only works with CID faces, returning an error otherwise. /// </remarks> /// <param name="registry">The registry, as a C string, owned by the face.</param> /// <param name="ordering">The ordering, as a C string, owned by the face.</param> /// <param name="supplement">The supplement.</param> public void GetCidRegistryOrderingSupplement(out string registry, out string ordering, out int supplement) { Error err = FT.FT_Get_CID_Registry_Ordering_Supplement(Reference, out registry, out ordering, out supplement); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Retrieve the type of the input face, CID keyed or not. In constrast to the /// <see cref="IsCidKeyed"/> macro this function returns successfully also for CID-keyed fonts in an /// SNFT wrapper. /// </summary> /// <remarks> /// This function only works with CID faces and OpenType fonts, returning an error otherwise. /// </remarks> /// <returns>The type of the face as an FT_Bool.</returns> public bool GetCidIsInternallyCidKeyed() { byte is_cid; Error err = FT.FT_Get_CID_Is_Internally_CID_Keyed(Reference, out is_cid); if (err != Error.Ok) throw new FreeTypeException(err); return is_cid == 1; } /// <summary> /// Retrieve the CID of the input glyph index. /// </summary> /// <remarks> /// This function only works with CID faces and OpenType fonts, returning an error otherwise. /// </remarks> /// <param name="glyphIndex">The input glyph index.</param> /// <returns>The CID as an uint.</returns> [CLSCompliant(false)] public uint GetCidFromGlyphIndex(uint glyphIndex) { uint cid; Error err = FT.FT_Get_CID_From_Glyph_Index(Reference, glyphIndex, out cid); if (err != Error.Ok) throw new FreeTypeException(err); return cid; } #endregion #region PFR Fonts /// <summary> /// Return the outline and metrics resolutions of a given PFR face. /// </summary> /// <remarks> /// If the input face is not a PFR, this function will return an error. However, in all cases, it will return /// valid values. /// </remarks> /// <param name="outlineResolution"> /// Outline resolution. This is equivalent to ‘face->units_per_EM’ for non-PFR fonts. Optional (parameter can /// be NULL). /// </param> /// <param name="metricsResolution"> /// Metrics resolution. This is equivalent to ‘outline_resolution’ for non-PFR fonts. Optional (parameter can /// be NULL). /// </param> /// <param name="metricsXScale"> /// A 16.16 fixed-point number used to scale distance expressed in metrics units to device sub-pixels. This is /// equivalent to ‘face->size->x_scale’, but for metrics only. Optional (parameter can be NULL). /// </param> /// <param name="metricsYScale"> /// Same as ‘ametrics_x_scale’ but for the vertical direction. optional (parameter can be NULL). /// </param> [CLSCompliant(false)] public void GetPfrMetrics(out uint outlineResolution, out uint metricsResolution, out Fixed16Dot16 metricsXScale, out Fixed16Dot16 metricsYScale) { IntPtr tmpXScale, tmpYScale; Error err = FT.FT_Get_PFR_Metrics(Reference, out outlineResolution, out metricsResolution, out tmpXScale, out tmpYScale); metricsXScale = Fixed16Dot16.FromRawValue((int)tmpXScale); metricsYScale = Fixed16Dot16.FromRawValue((int)tmpYScale); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Return the kerning pair corresponding to two glyphs in a PFR face. The distance is expressed in metrics /// units, unlike the result of <see cref="GetKerning"/>. /// </summary> /// <remarks><para> /// This function always return distances in original PFR metrics units. This is unlike /// <see cref="GetKerning"/> with the <see cref="KerningMode.Unscaled"/> mode, which always returns /// distances converted to outline units. /// </para><para> /// You can use the value of the ‘x_scale’ and ‘y_scale’ parameters returned by <see cref="GetPfrMetrics"/> to /// scale these to device sub-pixels. /// </para></remarks> /// <param name="left">Index of the left glyph.</param> /// <param name="right">Index of the right glyph.</param> /// <returns>A kerning vector.</returns> [CLSCompliant(false)] public FTVector GetPfrKerning(uint left, uint right) { FTVector vector; Error err = FT.FT_Get_PFR_Kerning(Reference, left, right, out vector); if (err != Error.Ok) throw new FreeTypeException(err); return vector; } /// <summary> /// Return a given glyph advance, expressed in original metrics units, from a PFR font. /// </summary> /// <remarks> /// You can use the ‘x_scale’ or ‘y_scale’ results of <see cref="GetPfrMetrics"/> to convert the advance to /// device sub-pixels (i.e., 1/64th of pixels). /// </remarks> /// <param name="glyphIndex">The glyph index.</param> /// <returns>The glyph advance in metrics units.</returns> [CLSCompliant(false)] public int GetPfrAdvance(uint glyphIndex) { int advance; Error err = FT.FT_Get_PFR_Advance(Reference, glyphIndex, out advance); if (err != Error.Ok) throw new FreeTypeException(err); return advance; } #endregion #region Windows FNT Files /// <summary> /// Retrieve a Windows FNT font info header. /// </summary> /// <remarks> /// This function only works with Windows FNT faces, returning an error otherwise. /// </remarks> /// <returns>The WinFNT header.</returns> public Fnt.Header GetWinFntHeader() { IntPtr headerRef; Error err = FT.FT_Get_WinFNT_Header(Reference, out headerRef); if (err != Error.Ok) throw new FreeTypeException(err); return new Fnt.Header(headerRef); } #endregion #region Font Formats /// <summary> /// Return a string describing the format of a given face, using values which can be used as an X11 /// FONT_PROPERTY. Possible values are ‘TrueType’, ‘Type 1’, ‘BDF’, ‘PCF’, ‘Type 42’, ‘CID Type 1’, ‘CFF’, /// ‘PFR’, and ‘Windows FNT’. /// </summary> /// <returns>Font format string. NULL in case of error.</returns> public string GetX11FontFormat() { return Marshal.PtrToStringAnsi(FT.FT_Get_X11_Font_Format(Reference)); } #endregion #region Gasp Table /// <summary> /// Read the ‘gasp’ table from a TrueType or OpenType font file and return the entry corresponding to a given /// character pixel size. /// </summary> /// <param name="ppem">The vertical character pixel size.</param> /// <returns> /// Bit flags (see <see cref="Gasp"/>), or <see cref="Gasp.NoTable"/> if there is no ‘gasp’ table in the face. /// </returns> [CLSCompliant(false)] public Gasp GetGasp(uint ppem) { return FT.FT_Get_Gasp(Reference, ppem); } #endregion #region Quick retrieval of advance values /// <summary> /// Retrieve the advance value of a given glyph outline in a <see cref="Face"/>. By default, the unhinted /// advance is returned in font units. /// </summary> /// <remarks><para> /// This function may fail if you use <see cref="LoadFlags.AdvanceFlagFastOnly"/> and if the corresponding font /// backend doesn't have a quick way to retrieve the advances. /// </para><para> /// A scaled advance is returned in 16.16 format but isn't transformed by the affine transformation specified /// by <see cref="SetTransform()"/>. /// </para></remarks> /// <param name="glyphIndex">The glyph index.</param> /// <param name="flags"> /// A set of bit flags similar to those used when calling <see cref="LoadGlyph"/>, used to determine what kind /// of advances you need. /// </param> /// <returns><para> /// The advance value, in either font units or 16.16 format. /// </para><para> /// If <see cref="LoadFlags.VerticalLayout"/> is set, this is the vertical advance corresponding to a vertical /// layout. Otherwise, it is the horizontal advance in a horizontal layout. /// </para></returns> [CLSCompliant(false)] public Fixed16Dot16 GetAdvance(uint glyphIndex, LoadFlags flags) { IntPtr padvance; Error err = FT.FT_Get_Advance(Reference, glyphIndex, flags, out padvance); if (err != Error.Ok) throw new FreeTypeException(err); return Fixed16Dot16.FromRawValue((int)padvance); } /// <summary> /// Retrieve the advance values of several glyph outlines in an /// <see cref="Face"/>. By default, the unhinted advances are returned /// in font units. /// </summary> /// <remarks><para> /// This function may fail if you use /// <see cref="LoadFlags.AdvanceFlagFastOnly"/> and if the /// corresponding font backend doesn't have a quick way to retrieve the /// advances. /// </para><para> /// Scaled advances are returned in 16.16 format but aren't transformed /// by the affine transformation specified by /// <see cref="SetTransform()"/>. /// </para></remarks> /// <param name="start">The first glyph index.</param> /// <param name="count">The number of advance values you want to retrieve.</param> /// <param name="flags">A set of bit flags similar to those used when calling <see cref="LoadGlyph"/>.</param> /// <returns><para>The advances, in either font units or 16.16 format. This array must contain at least ‘count’ elements. /// </para><para> /// If <see cref="LoadFlags.VerticalLayout"/> is set, these are the vertical advances corresponding to a vertical layout. Otherwise, they are the horizontal advances in a horizontal layout.</para></returns> [CLSCompliant(false)] public unsafe Fixed16Dot16[] GetAdvances(uint start, uint count, LoadFlags flags) { IntPtr advPtr; Error err = FT.FT_Get_Advances(Reference, start, count, flags, out advPtr); if (err != Error.Ok) throw new FreeTypeException(err); //create a new array and copy the data from the pointer over Fixed16Dot16[] advances = new Fixed16Dot16[count]; IntPtr* ptr = (IntPtr*)advPtr; for (int i = 0; i < count; i++) advances[i] = Fixed16Dot16.FromRawValue((int)ptr[i]); return advances; } #endregion #region OpenType Validation /// <summary> /// Validate various OpenType tables to assure that all offsets and indices are valid. The idea is that a /// higher-level library which actually does the text layout can access those tables without error checking /// (which can be quite time consuming). /// </summary> /// <remarks><para> /// This function only works with OpenType fonts, returning an error otherwise. /// </para><para> /// After use, the application should deallocate the five tables with <see cref="OpenTypeFree"/>. A NULL value /// indicates that the table either doesn't exist in the font, or the application hasn't asked for validation. /// </para></remarks> /// <param name="flags">A bit field which specifies the tables to be validated.</param> /// <param name="baseTable">A pointer to the BASE table.</param> /// <param name="gdefTable">A pointer to the GDEF table.</param> /// <param name="gposTable">A pointer to the GPOS table.</param> /// <param name="gsubTable">A pointer to the GSUB table.</param> /// <param name="jstfTable">A pointer to the JSTF table.</param> [CLSCompliant(false)] public void OpenTypeValidate(OpenTypeValidationFlags flags, out IntPtr baseTable, out IntPtr gdefTable, out IntPtr gposTable, out IntPtr gsubTable, out IntPtr jstfTable) { Error err = FT.FT_OpenType_Validate(Reference, flags, out baseTable, out gdefTable, out gposTable, out gsubTable, out jstfTable); if (err != Error.Ok) throw new FreeTypeException(err); } /// <summary> /// Free the buffer allocated by OpenType validator. /// </summary> /// <remarks> /// This function must be used to free the buffer allocated by <see cref="OpenTypeValidate"/> only. /// </remarks> /// <param name="table">The pointer to the buffer that is allocated by <see cref="OpenTypeValidate"/>.</param> public void OpenTypeFree(IntPtr table) { FT.FT_OpenType_Free(Reference, table); } #endregion #region TrueTypeGX/AAT Validation /// <summary> /// Validate various TrueTypeGX tables to assure that all offsets and indices are valid. The idea is that a /// higher-level library which actually does the text layout can access those tables without error checking /// (which can be quite time consuming). /// </summary> /// <remarks><para> /// This function only works with TrueTypeGX fonts, returning an error otherwise. /// </para><para> /// After use, the application should deallocate the buffers pointed to by each ‘tables’ element, by calling /// <see cref="TrueTypeGXFree"/>. A NULL value indicates that the table either doesn't exist in the font, the /// application hasn't asked for validation, or the validator doesn't have the ability to validate the sfnt /// table. /// </para></remarks> /// <param name="flags">A bit field which specifies the tables to be validated.</param> /// <param name="tables"> /// The array where all validated sfnt tables are stored. The array itself must be allocated by a client. /// </param> /// <param name="tableLength"> /// The size of the ‘tables’ array. Normally, FT_VALIDATE_GX_LENGTH should be passed. /// </param> [CLSCompliant(false)] public void TrueTypeGXValidate(TrueTypeValidationFlags flags, byte[][] tables, uint tableLength) { FT.FT_TrueTypeGX_Validate(Reference, flags, tables, tableLength); } /// <summary> /// Free the buffer allocated by TrueTypeGX validator. /// </summary> /// <remarks> /// This function must be used to free the buffer allocated by <see cref="TrueTypeGXValidate"/> only. /// </remarks> /// <param name="table">The pointer to the buffer allocated by <see cref="TrueTypeGXValidate"/>.</param> public void TrueTypeGXFree(IntPtr table) { FT.FT_TrueTypeGX_Free(Reference, table); } /// <summary><para> /// Validate classic (16-bit format) kern table to assure that the offsets and indices are valid. The idea is /// that a higher-level library which actually does the text layout can access those tables without error /// checking (which can be quite time consuming). /// </para><para> /// The ‘kern’ table validator in <see cref="TrueTypeGXValidate"/> deals with both the new 32-bit format and /// the classic 16-bit format, while <see cref="ClassicKernValidate"/> only supports the classic 16-bit format. /// </para></summary> /// <remarks> /// After use, the application should deallocate the buffers pointed to by ‘ckern_table’, by calling /// <see cref="ClassicKernFree"/>. A NULL value indicates that the table doesn't exist in the font. /// </remarks> /// <param name="flags">A bit field which specifies the dialect to be validated.</param> /// <returns>A pointer to the kern table.</returns> [CLSCompliant(false)] public IntPtr ClassicKernValidate(ClassicKernValidationFlags flags) { IntPtr ckernRef; FT.FT_ClassicKern_Validate(Reference, flags, out ckernRef); return ckernRef; } /// <summary> /// Free the buffer allocated by classic Kern validator. /// </summary> /// <remarks> /// This function must be used to free the buffer allocated by <see cref="ClassicKernValidate"/> only. /// </remarks> /// <param name="table"> /// The pointer to the buffer that is allocated by <see cref="ClassicKernValidate"/>. /// </param> public void ClassicKernFree(IntPtr table) { FT.FT_ClassicKern_Free(Reference, table); } #endregion /// <summary> /// Disposes the Face. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal void AddChildSize(FTSize child) { childSizes.Add(child); } internal void RemoveChildSize(FTSize child) { childSizes.Remove(child); } private void Dispose(bool disposing) { if (!disposed) { disposed = true; foreach (FTSize s in childSizes) s.Dispose(); childSizes.Clear(); Error err = FT.FT_Done_Face(reference); if (err != Error.Ok) throw new FreeTypeException(err); // removes itself from the parent Library, with a check to prevent this from happening when Library is // being disposed (Library disposes all it's children with a foreach loop, this causes an // InvalidOperationException for modifying a collection during enumeration) if (!parentLibrary.IsDisposed) parentLibrary.RemoveChildFace(this); reference = IntPtr.Zero; rec = null; if (memoryFaceHandle.IsAllocated) memoryFaceHandle.Free(); EventHandler handler = Disposed; if (handler != null) handler(this, EventArgs.Empty); } } #endregion } }
mit
shirobu2400/mmdpi
libmmdpi/model/mmdpi_shader.cpp
12153
#include "mmdpi_shader.h" const int _send_gpu_data_num_ = 4; int mmdpiShader::shader_on( void ) { if( program ) glUseProgram( program ); else { GLint length; GLchar* log; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &length ); log = new GLchar[ length ]; glGetShaderInfoLog( bone_size_id, length, &length, log ); fprintf( stderr, "Linked log = \"%s\"", log ); delete[] log; return -1; } return 0; } void mmdpiShader::shader_off( void ) { glUseProgram( 0 ); } int mmdpiShader::default_shader( void ) { static GLchar vertex_shader_src[ 0x1000 ] = { 0 }; sprintf( vertex_shader_src, #if defined( _MMDPI_OPENGL_ES_DEFINES_ ) || defined( _MMDPI_PRIJECTION_MATRIX_SELF_ ) "uniform mat4 ProjectionMatrix;\n" #else "mat4 ProjectionMatrix = gl_ModelViewProjectionMatrix;\n" #endif "attribute vec3 Vertex; \n" #ifdef _MMDPI_OUTLINE_ "attribute vec3 Normal; \n" "uniform float Edge_size; \n" // エッジサイズ "uniform vec4 Edge_color; \n" // エッジカラー #endif "attribute vec4 gUv; \n" "varying vec4 vUv; \n" "attribute vec3 SkinVertex; \n" "\n" //" Bone Info\n" //"ボーン姿勢情報\n" "uniform mat4 BoneMatrix[ %d ];\n" "attribute vec4 BoneWeights; \n" // 頂点ウェイト "attribute vec4 BoneIndices; \n" // ボーンインデックス "\n" "uniform vec4 gColor; \n" "varying vec4 Color; \n" "\n" // 頂点シェーダメイン関数 "void main( void )\n" "{\n" " mat4 skinTransform;\n" " vec3 vertex00;\n" "\n" "\n" "\n" " skinTransform = BoneWeights[ 0 ] * BoneMatrix[ int( BoneIndices[ 0 ] ) ];\n" " skinTransform += BoneWeights[ 1 ] * BoneMatrix[ int( BoneIndices[ 1 ] ) ];\n" " skinTransform += BoneWeights[ 2 ] * BoneMatrix[ int( BoneIndices[ 2 ] ) ];\n" " skinTransform += BoneWeights[ 3 ] * BoneMatrix[ int( BoneIndices[ 3 ] ) ];\n" "\n" #ifdef _MMDPI_OUTLINE_ " vertex00 = Vertex + SkinVertex + Normal * Edge_size * 0.02;\n" #else " vertex00 = Vertex;\n" #endif " gl_Position = ProjectionMatrix * skinTransform * vec4( vertex00, 1 );\n" " vUv = gUv;\n" " Color = gColor;\n" //" Color = vec4( 1.0, 1.0, 1.0, 0.0 );\n" #ifdef _MMDPI_OUTLINE_ " if( Edge_size > 0.00001 )\n" " Color = Edge_color;//vec4( 0.0, 0.0, 0.0, 1.0 );\n" #endif "}\n" "\n", _MMDPI_MATERIAL_USING_BONE_NUM_ ); static GLchar fragment_shader_src[] = "//precision lowp float;\n" "\n" "uniform sampler2D Tex01;\n" "uniform float TexToonFlag;\n" "uniform sampler2D TexToon;\n" "varying vec4 vUv;\n" "\n" "varying vec4 Color;\n" "uniform float Alpha;\n" "\n" "void main( void )\n" "{\n" " vec4 color = texture2D( Tex01, vUv.xy );\n" " color.a = color.a * Alpha;\n" //" if( TexToonFlag > 0.5 )\n" //" {\n" //" vec4 tc = texture2D( TexToon, vUv.xy );\n" //" tc.a = 1.0;\n" //" color = color * tc;\n" //" }\n" " gl_FragColor = color * ( 1.0 - Color.a ) + Color * ( Color.a );\n" //" gl_FragColor = color;\n" "}\n" ; #ifndef _MMDPI_OPENGL_ES_DEFINES_ glewInit(); #endif program = glCreateProgram(); int result; result = create_shader( GL_VERTEX_SHADER, vertex_shader_src ); result = create_shader( GL_FRAGMENT_SHADER, fragment_shader_src ) || result; // Link result = result || link(); if( result == 0 ) shader_setting(); return result; } void mmdpiShader::shader_setting( void ) { // 設定 shader_on(); // マトリックス pm_id = glGetUniformLocation( program, ( GLchar* )"ProjectionMatrix" ); // 頂点 vertex_id = glGetAttribLocation( program, ( GLchar* )"Vertex" ); glEnableVertexAttribArray( vertex_id ); // UV uv_id = glGetAttribLocation( program, ( GLchar* )"gUv" ); glEnableVertexAttribArray( uv_id ); // 法線 #ifdef _MMDPI_OUTLINE_ normal_id = glGetAttribLocation( program, ( GLchar* )"Normal" ); glEnableVertexAttribArray( normal_id ); #endif // 色 color_id = glGetUniformLocation( program, ( GLchar* )"gColor" ); mmdpiColor color; set_color( &color ); // 基本的なテクスチャ tex2d_01_id = glGetUniformLocation( program, ( GLchar* )"Tex01" ); // アルファ alpha_id = glGetUniformLocation( program, ( GLchar* )"Alpha" ); // テクスチャサイズ bone_size_id = glGetUniformLocation( program, ( GLchar* )"BoneTextureSize" ); // Attribute1にindices変数、Attribute2にweights変数を割り当てる bone_weights_id = glGetAttribLocation( program, ( GLchar* )"BoneWeights" ); glEnableVertexAttribArray( bone_weights_id ); bone_indices_id = glGetAttribLocation( program, ( GLchar* )"BoneIndices" ); glEnableVertexAttribArray( bone_indices_id ); bone_matrix_id = glGetUniformLocation( program, ( GLchar* )"BoneMatrix" ); tex2d_toon_id = glGetUniformLocation( program, ( GLchar* )"TexToon" ); glUniform1i( tex2d_toon_id, 0 ); tex2d_toon_flag = glGetUniformLocation( program, ( GLchar* )"TexToonFlag" ); glUniform1f( tex2d_toon_flag, 0 ); edge_size_id = glGetUniformLocation( program, ( GLchar* )"Edge_size" ); glUniform1f( edge_size_id, 0 ); edge_color_id = glGetUniformLocation( program, ( GLchar* )"Edge_color" ); glUniform4f( edge_color_id, 0, 0, 0, 0 ); // スキン skinvertex_id = glGetAttribLocation( program, ( GLchar* )"SkinVertex" ); glEnableVertexAttribArray( skinvertex_id ); // Uniform Variable glActiveTexture( GL_TEXTURE0 ); glUniform1i( tex2d_01_id, 0 ); glActiveTexture( GL_TEXTURE1 ); glUniform1i( tex2d_toon_id, 1 ); shader_off(); } // シェーダ生成 int mmdpiShader::create_shader( GLuint shader_type, const GLchar* src ) { int shader_size = strlen( ( const char * )src ); shader = glCreateShader( shader_type ); glShaderSource( shader, 1, ( const GLchar ** )&src, &shader_size ); glCompileShader( shader ); glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); if( compiled == 0 ) { GLint length; GLchar* log; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &length ); log = new GLchar[ length ]; glGetShaderInfoLog( shader, length, &length, log ); fprintf( stderr, "Compiled log = \"%s\"", log ); delete[] log; } glAttachShader( program, shader ); glDeleteShader( shader ); return 0; } // シェーダリンク int mmdpiShader::link( void ) { if( program ) glLinkProgram( program ); glGetProgramiv( program, GL_LINK_STATUS, &linked ); if( linked == 0 ) { // error GLint infoLen = 0; glGetProgramiv( program, GL_INFO_LOG_LENGTH, &infoLen ); if( infoLen > 0 ) { char* infoLog = new char[ infoLen ]; glGetProgramInfoLog( program, infoLen, 0x00, infoLog ); printf( "Error linking program:\n%s\n", infoLog ); delete[] infoLog; } glDeleteProgram( program ); return -1; } glGetProgramiv( program, GL_LINK_STATUS, &linked_fragment ); glGetProgramiv( program, GL_LINK_STATUS, &linked_vertex ); return 0; } // シェーダバッファに頂点データを設定 void mmdpiShader::set_vertex_buffers( int buffer_id, MMDPI_VERTEX_PTR a_vertex_p, dword vertex_num ) { this->vertex_num = vertex_num; // Buffer if( buffers.size() <= ( uint )buffer_id ) { buffers.push_back( new mmdpiShaderBuffer() ); if( buffers.size() <= ( uint )buffer_id ) { perror( "Buffer error!!" ); return ; } } /* バッファオブジェクトの名前を作る */ glBindBuffer( GL_ARRAY_BUFFER, buffers[ buffer_id ]->get_vertex() ); glBufferData( GL_ARRAY_BUFFER, sizeof( MMDPI_VERTEX ) * vertex_num, a_vertex_p, GL_STATIC_DRAW ); } // シェーダバッファに面データを設定 void mmdpiShader::set_face_buffers( int buffer_id, mmdpiShaderIndex* face_p, dword face_num ) { // Face glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, buffers[ buffer_id ]->get_face() ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( mmdpiShaderIndex ) * face_num, face_p, GL_STATIC_DRAW ); } // シェーダバッファにデータ領域を設定 void mmdpiShader::set_buffer( int buffer_id ) { dword vertex_start = 0; glBindBuffer( GL_ARRAY_BUFFER, buffers[ buffer_id ]->get_vertex() ); // vertex glVertexAttribPointer( vertex_id, 3, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector3d ); // uv glVertexAttribPointer( uv_id, 4, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector4d ); // bone index glVertexAttribPointer( bone_indices_id, 4, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector4d ); // bone weight glVertexAttribPointer( bone_weights_id, 4, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector4d ); #ifdef _MMDPI_OUTLINE_ // 法線ベクトル glVertexAttribPointer( normal_id, 3, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector4d ); #endif #ifdef _MMDPI_USINGSKIN_ // スキン glVertexAttribPointer( skinvertex_id, 3, GL_FLOAT, GL_FALSE, sizeof( MMDPI_VERTEX ), ( const void * )( ( uintptr_t )vertex_start ) ); vertex_start += sizeof( mmdpiVector3d ); #endif glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void mmdpiShader::init_material( void ) { glUniform1f( tex2d_toon_flag, 0 ); } void mmdpiShader::draw( int buffer_id, dword fver_num_base, dword face_num ) { set_buffer( buffer_id ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, buffers[ buffer_id ]->get_face() ); now_buffer_id = buffer_id; glDrawElements( GL_TRIANGLES, face_num, GL_UNSIGNED_SHORT, ( const void * )( sizeof( mmdpiShaderIndex ) * fver_num_base ) ); //glDrawElements( GL_TRIANGLES, face_num, GL_UNSIGNED_INT, ( const void * )( sizeof( mmdpiShaderIndex ) * fver_num_base ) ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } void mmdpiShader::send_bone( MMDPI_PIECE* piece ) { GLfloat matrix[ _MMDPI_MATERIAL_USING_BONE_NUM_ ][ 16 ] = { 0 }; for( uint i = 0; i < piece->bone_list_num; i ++ ) { for( int j = 0; j < 16; j ++ ) matrix[ i ][ j ] = piece->matrix[ i ][ j ]; } glUniformMatrix4fv( bone_matrix_id, piece->bone_list_num, GL_FALSE, ( GLfloat * )matrix ); } void mmdpiShader::set_projection_matrix( mmdpiMatrix_ptr projection_matrix ) { if( pm_id >= 0 ) glUniformMatrix4fv( pm_id, 1, GL_FALSE, ( const GLfloat* )projection_matrix ); } void mmdpiShader::set_alpha_for_shader( GLfloat alpha ) { glUniform1f( alpha_id, alpha ); } void mmdpiShader::set_color( mmdpiColor* color ) { glUniform4f( color_id, color->r, color->g, color->b, color->a ); } void mmdpiShader::set_edge_size( float edge ) { #ifdef _MMDPI_OUTLINE_ glUniform1f( edge_size_id, edge ); #endif } void mmdpiShader::set_edge_color( float* edge_color ) { #ifdef _MMDPI_OUTLINE_ float def_edge_color[ 4 ] = { 0, 0, 0, 1 }; if( edge_color == 0x00 ) edge_color = def_edge_color; glUniform4f( edge_color_id, edge_color[ 0 ], edge_color[ 1 ], edge_color[ 2 ], edge_color[ 3 ] ); #endif } mmdpiShader::mmdpiShader() { now_buffer_id = 0; vertex_id = 0; normal_id = 0; color_id = 0; uv_id = 0; bone_weights_id = 0; bone_indices_id = 0; skinvertex_id = 0; program = 0; } mmdpiShader::~mmdpiShader() { for( uint i = 0; i < buffers.size(); i ++ ) delete buffers[ i ]; if( vertex_id > 0 ) glDisableVertexAttribArray( vertex_id ); #ifdef _MMDPI_OUTLINE_ if( normal_id > 0 ) glDisableVertexAttribArray( normal_id ); #endif if( uv_id > 0 ) glDisableVertexAttribArray( uv_id ); if( bone_weights_id > 0 ) glDisableVertexAttribArray( bone_weights_id ); if( bone_indices_id > 0 ) glDisableVertexAttribArray( bone_indices_id ); #ifdef _MMDPI_USINGSKIN_ if( skinvertex_id > 0 ) glDisableVertexAttribArray( skinvertex_id ); #endif if( program ) glDeleteProgram( program ); }
mit
kristopolous/DRR
indycast.net/controls.php
2720
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="/assets/css/main.css" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="icon" href="favicon.ico" > <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Chris McKenzie"> <meta name="description" content="A free technology that sends you MP3s of any radio show - at any time, right now." /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:creator" content="@indycaster" /> <meta name="twitter:description" content="A free technology that sends you MP3s of any radio show - at any time, right now." /> <meta name="twitter:image:src" content="http://indycast.net/images/twit-image.png" /> <meta name="twitter:site" content="@indycaster" /> <meta name="twitter:title" content="incycast DVR: A free technology that sends you MP3s of any radio show - at any time, right now" /> <meta name="twitter:url" content="http://indycast.net" /> <meta property="og:description" content="A free technology that sends you MP3s of any radio show - at any time, right now." /> <meta property="og:image" content="http://indycast.net/og-image.php" /> <meta property="og:site_name" content="Indycast" /> <meta property="og:title" content="A free technology that sends you MP3s of any radio show - at any time, right now." /> <meta property="og:type" content="website" /> <meta property="og:url" content="http://indycast.net" /> <!--[if lt IE 9]> <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <h1><?= station ?></h1> <h2><?= timestamp ?></h2> <div id='html5-widget'> <audio id="radio-control" controls type='audio/mpeg'> </div> <div id="flash-widget"></div> <div id='short-controls'> <a href="<%= live_url %>" title="Download this to your device" class='btn btn-lg btn-link'><i class="fa fa-download"></i> Download </a> <a target=_blank class="btn btn-md btn-default" href="https://twitter.com/intent/tweet?text=<%=tweet_text%>" title="Share this on twitter"> </div> <div id="controls"> <div id="rewind"></div> <div id="pause"></div> <div id="forward"></div> </div> <div id="share"></div> <script src='/assets/js/common.js'></script> </body>
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_98/unsafe/CWE_98__exec__func_preg_match-no_filtering__require_file_name-interpretation_simple_quote.php
1362
<?php /* Unsafe sample input : use exec to execute the script /tmp/tainted.php and store the output in $tainted sanitize : regular expression accepts everything construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $script = "/tmp/tainted.php"; exec($script, $result, $return); $tainted = $result[0]; $re = "/^.*$/"; if(preg_match($re, $tainted) == 1){ $tainted = $tainted; } else{ $tainted = ""; } //flaw $var = require("'$tainted'.php"); ?>
mit
drewm/selecta
tests/ClassTest.php
381
<?php use DrewM\Selecta\Selecta; class ClassTest extends PHPUnit_Framework_TestCase { public function testSimpleClass() { $result = Selecta::build('div.foo'); $this->assertEquals('<div class="foo"></div>', $result); } public function testDoubleClass() { $result = Selecta::build('div.foo.bar'); $this->assertEquals('<div class="foo bar"></div>', $result); } }
mit
rougin/weasley
tests/Fixture/Templates/TestController.php
166
<?php namespace App\Http\Controllers; /** * TestController * * @package App * @author Rougin Gutib <rougingutib@gmail.com> */ class TestController { // }
mit
waxe/waxe.xml
waxe/xml/static/ckeditor/plugins/devtools/lang/km.js
507
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'devtools', 'km', { title: 'ព័ត៌មាន​នៃ​ធាតុ', dialogName: 'ឈ្មោះ​ប្រអប់​វីនដូ', tabName: 'ឈ្មោះ​ផ្ទាំង', elementId: 'អត្តលេខ​ធាតុ', elementType: 'ប្រភេទ​ធាតុ' } );
mit
rikbattum/pvApp
gulp.js
1132
// Base gulp file as known to internet :) // based oon 25-07-2015, while listening to the Passengers; // Include gulp var gulp = require('gulp'); // Include Our Plugins var jshint = require('gulp-jshint'); var sass = require('gulp-sass'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); // Lint Task gulp.task('lint', function() { return gulp.src('js/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); // Compile Our Sass gulp.task('sass', function() { return gulp.src('scss/*.scss') .pipe(sass()) .pipe(gulp.dest('css')); }); // Concatenate & Minify JS gulp.task('scripts', function() { return gulp.src('js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist')) .pipe(rename('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); }); // Watch Files For Changes gulp.task('watch', function() { gulp.watch('js/*.js', ['lint', 'scripts']); gulp.watch('scss/*.scss', ['sass']); }); // Default Task gulp.task('default', ['lint', 'sass', 'scripts', 'watch']);
mit
Q42/Q42.HueApi
src/Q42.HueApi.Streaming.Sample/Program.cs
1248
using System; using System.Collections.Generic; using System.Threading.Tasks; using Q42.HueApi.Streaming.Models; namespace Q42.HueApi.Streaming.Sample { class Program { public static async Task Main(string[] args) { Console.WriteLine("Q42.HueApi Streaming Sample App"); HueStreaming s = new HueStreaming(); await s.Start(); //HueLightDJ s = new HueLightDJ(); //await s.Start(); //BeatController b = new BeatController(null); //b.EffectFunction = Functiona; //b.StartAutoTimer(TimeSpan.FromSeconds(2)); //Console.ReadLine(); //b.ManualBeat(null); //Console.ReadLine(); //b.ManualBeat(null); //Console.ReadLine(); //b.ManualBeat(null); //Console.ReadLine(); //b.ManualBeat(null); //Console.ReadLine(); //b.ManualBeat(null); //Console.ReadLine(); //b.AutoContinueManualBeat(); Console.WriteLine("finished"); Console.ReadLine(); Console.ReadLine(); Console.ReadLine(); Console.ReadLine(); } private static Task Functiona(IEnumerable<EntertainmentLight> current, TimeSpan? timeSpan) { Console.WriteLine("now"); return Task.CompletedTask; } } }
mit
erwinvaneyk/Dragons-Arena
src/main/java/distributed/systems/network/AbstractNode.java
3182
package distributed.systems.network; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import distributed.systems.core.ExtendedSocket; import distributed.systems.core.IMessageReceivedHandler; import distributed.systems.core.LogType; import distributed.systems.core.Message; import distributed.systems.core.MessageFactory; import distributed.systems.network.logging.InfluxLogger; import distributed.systems.network.messagehandlers.MessageHandler; import distributed.systems.network.services.SocketService; import lombok.Getter; public abstract class AbstractNode extends UnicastRemoteObject implements IMessageReceivedHandler { // MessageHandlers private final transient Map<String, MessageHandler> messageHandlers = new HashMap<>(); // Services private final transient ExecutorService services = Executors.newCachedThreadPool(); private final transient InfluxLogger influxdbLogger = InfluxLogger.getInstance(); // Address @Getter private NodeAddress address; @Getter protected LocalSocket socket; @Getter protected transient MessageFactory messageFactory; protected AbstractNode() throws RemoteException {} public void addMessageHandler(MessageHandler messageHandler) { this.messageHandlers.put(messageHandler.getMessageType(), messageHandler); System.out.println("Added messagehandler for " + messageHandler.getMessageType() + " -> accepted messageTypes: " + getAcceptableMessageTypes()); } public void runService(SocketService socketService) { addMessageHandler(socketService); services.submit(socketService); } @Override public Message onMessageReceived(Message message) throws RemoteException { long start = System.currentTimeMillis(); message.setReceivedTimestamp(); Message response = null; MessageHandler messageHandler = messageHandlers.get(message.getMessageType()); if(messageHandler != null) { response = messageHandler.onMessageReceived(message); } else { safeLogMessage("Unable to handle received message: " + message + " (accepted messageTypes: "+ getAcceptableMessageTypes() +"). Ignoring the message!", LogType.WARN); } influxdbLogger.logMessageDuration(message, getAddress(),System.currentTimeMillis() - start); return response; } public void disconnect() throws RemoteException { // Remove old binding try { UnicastRemoteObject.unexportObject(this, true); socket = LocalSocket.connectTo(address); socket.unRegister(); } catch (ConnectionException e) { System.out.println("Trying to unbind from non-existent registry"); } } public void safeLogMessage(String message, LogType type) { if(socket != null) { try { socket.logMessage(message, type); return; } catch(RuntimeException e) {} } System.out.println("No socket present: " + message); } public Collection<String> getAcceptableMessageTypes() { return messageHandlers.keySet(); } public abstract NodeType getNodeType(); //public abstract void setAddress(NodeAddress newAddress); }
mit
chandlerkent/emberjs-feed-wrangler
tests/unit/controllers/newsfeed-test.js
333
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:newsfeed', 'NewsfeedController', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function() { var controller = this.subject(); ok(controller); });
mit
dtaniwaki/sidekiq-merger
lib/sidekiq/merger/logging_observer.rb
408
class Sidekiq::Merger::LoggingObserver def initialize(logger) @logger = logger end def update(time, _result, ex) if ex.is_a?(Concurrent::TimeoutError) @logger.error( "[#{Sidekiq::Merger::LOGGER_TAG}] Execution timed out\n" ) elsif ex.present? @logger.error( "[#{Sidekiq::Merger::LOGGER_TAG}] Execution failed with error #{ex}\n" ) end end end
mit
mikeshultz/pyqual
bin/pqweb.py
26632
#!/usr/bin/python import sys, os sys.path.append(os.getcwd()) import math, datetime, cherrypy, psycopg2, argparse, PyRSS2Gen from psycopg2 import extras as pg_extras from pyqual.auth import Auth, LoginPage from pyqual.utils import DB, Updated, Inserted from pyqual.templait import Templait from pyqual import settings def main(): """ Setup """ cherrypy.config.update(settings.CP_CONFIG) """ Init """ auth = Auth(DB) cherrypy.tools.is_authenticated = cherrypy.Tool("on_start_resource", auth.is_authenticated) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Run the Pyqual Web interface.') parser.add_argument( '-n', '--host', metavar='ADDR', type=str, nargs='?', default=settings.WEB_HOST, help="Hostname or IP address to bind to. '0.0.0.0' and '::' bind to all available IPv4 and IPv6 addresses respectively. Default: localhost" ) parser.add_argument( '-p', '--port', metavar='PORT', type=int, nargs='?', default=settings.WEB_PORT, help='TCP Port to bind to. Default: 8080' ) args = parser.parse_args() host = args.host or settings.WEB_HOST port = args.port or settings.WEB_PORT else: host = settings.WEB_HOST port = settings.WEB_PORT if not host or not port: print "Missing WEB_HOST or WEB_PORT in settings file for daemon mode." sys.exit() """ Views """ #@cherrypy.expose @cherrypy.tools.json_out() class Test: exposed = True def GET(self, test_id = None): """ Return JSON detail of a test """ db = DB() cur = db.connect(settings.DSN) def multiple(self): """ Return JSON of tests in the DB """ cur.execute("""SELECT test_id, t.name, lastrun, schedule_id, s.name AS schedule_name, database_id, d.name AS database_name FROM pq_test t LEFT JOIN pq_schedule s USING (schedule_id) LEFT JOIN pq_database d USING (database_id) WHERE deleted = false ORDER BY lastrun, test_id;""") tests = [] for test in cur.fetchall(): try: lastrun = test['lastrun'].isoformat() except AttributeError: lastrun = None t = { 'test_id': test['test_id'], 'name': test['name'], 'lastrun': lastrun, 'schedule_id': test['schedule_id'], 'schedule_name': test['schedule_name'], 'database_id': test['database_id'], 'database_name': test['database_name'], } tests.append(t) return tests def single(self, test_id): # Is test_id valid? if not test_id: raise cherrypy.HTTPError(404) else: try: test_id = int(test_id) except: raise cherrypy.HTTPError(404) cur.execute("""SELECT test_id, t.name, lastrun, schedule_id, database_id, test_type_id, user_id, cc, sql, python, fail_on_no_results FROM pq_test t LEFT JOIN pq_schedule s USING (schedule_id) LEFT JOIN pq_database d USING (database_id) WHERE test_id = %s AND deleted = false ORDER BY lastrun;""", (test_id, )) if cur.rowcount > 0: test = cur.fetchone() try: lastrun = test['lastrun'].isoformat() except AttributeError: lastrun = None t = { 'test_id': test['test_id'], 'name': test['name'], 'lastrun': lastrun, 'cc': test['cc'], 'schedule_id': test['schedule_id'], 'database_id': test['database_id'], 'test_type_id': test['test_type_id'], 'user_id': test['user_id'], 'sql': test['sql'], 'python': test['python'], 'fail_on_no_results': test['fail_on_no_results'], } else: raise cherrypy.HTTPError(404) db.disconnect() return t if test_id: return single(self, test_id) else: return multiple(self) def POST( self, test_id = None, name = None, cc = None, schedule_id = None, database_id = None, test_type_id = None, user_id = None, sql = None, python = None, fail_on_no_results = False): """ Insert/update a test """ # do action = None db = DB() cur = db.connect(settings.DSN) #cur.execute("""SELECT TRUE AS exist FROM pq_test WHERE test_id = %s""" % test_id) #res = cur.fetchone() #if res['exist']: if test_id: cur.execute( """UPDATE pq_test SET name = %s, schedule_id = %s, database_id = %s, test_type_id = %s, cc = %s, sql = %s, python = %s, user_id = %s, fail_on_no_results = %s WHERE test_id = %s;""", (name, schedule_id, database_id, test_type_id, cc, sql, python, user_id, fail_on_no_results, test_id) ) action = Updated() else: cur.execute( """INSERT INTO pq_test (name, schedule_id, database_id, test_type_id, cc, sql, python, user_id, fail_on_no_results) VALUES (%s,%s,%s,%s,%s,%s,%s,%s, %s);""", (name, schedule_id, database_id, test_type_id, cc, sql, python, user_id or auth.user_id, fail_on_no_results) ) action = Inserted() if cur.rowcount > 0: db.commit() db.disconnect() if type(action) == type(Updated()): return { 'result': 'success', 'message': 'Test updated successfully.'} elif type(action) == type(Inserted()): return { 'result': 'success', 'message': 'Test added successfully.'} else: return { 'result': 'failure', 'message': 'Something was successful? Add/update reported successful, but we have no idea what happened.'} else: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Add/update failed.' } def DELETE(self, test_id): """ Delete a test """ db = DB() cur = db.connect(settings.DSN) cur.execute("""UPDATE pq_test SET deleted = true WHERE test_id = %s""", (test_id, )) if cur.rowcount == 1: db.commit() db.disconnect() return { 'result': 'success', 'message': 'Test deleted successfully.', } elif cur.rowcount > 1: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Delete failed. Attempt was made to delete more than one record.' } else: db.rollback() db.disconnect() return { 'result': 'failed', 'message': 'Test delete failed.', } @cherrypy.tools.json_out() class Database: exposed = True def GET(self, database_id = None): def multiple(self): """ Return JSON of known databases """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT database_id, name, username, password, port, hostname, active FROM pq_database ORDER BY name, hostname;") dbs = [] for dbase in cur.fetchall(): d = { 'database_id': dbase['database_id'], 'name': dbase['name'], 'username': dbase['username'], 'password': dbase['password'], 'port': dbase['port'], 'hostname': dbase['hostname'], 'active': dbase['active'], } dbs.append(d) db.disconnect() return dbs def single(self, database_id): """ Return JSON of known databases """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT database_id, name, username, password, port, hostname, active FROM pq_database WHERE database_id = %s ORDER BY name, hostname;", (database_id, )) dbase = cur.fetchone() db.disconnect() return { 'database_id': dbase['database_id'], 'name': dbase['name'], 'username': dbase['username'], 'password': dbase['password'], 'port': dbase['port'], 'hostname': dbase['hostname'], 'active': dbase['active'], } if database_id: return single(self, database_id) else: return multiple(self) def POST( self, name, username, password, hostname, database_id = None, port = 5432, active = True ): # do action = None db = DB() cur = db.connect(settings.DSN) if database_id: cur.execute( """UPDATE pq_database SET name = %s, username = %s, password = %s, port = %s, hostname = %s, active = %s WHERE database_id = %s;""", (name, username, password, port, hostname, active, database_id) ) action = Updated() else: cur.execute( """INSERT INTO pq_database (name, username, password, port, hostname, active) VALUES (%s,%s,%s,%s,%s,%s);""", (name, username, password, port, hostname, active) ) action = Inserted() if cur.rowcount > 0: db.commit() db.disconnect() if type(action) == type(Updated()): return { 'result': 'success', 'message': 'Database updated successfully.'} elif type(action) == type(Inserted()): return { 'result': 'success', 'message': 'Database added successfully.'} else: return { 'result': 'failure', 'message': 'Something was successful? Add/update reported successful, but we have no idea what happened.'} else: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Add/update failed.' } def DELETE(self, database_id): """ Delete a database entry """ db = DB() cur = db.connect(settings.DSN) cur.execute("""DELETE FROM pq_database WHERE database_id = %s""", (database_id, )) if cur.rowcount > 0: db.commit() db.disconnect() return { 'result': 'success', 'message': 'Database deleted successfully.', } elif cur.rowcount > 1: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Delete failed. Attempt was made to delete more than one record.' } else: db.rollback() db.disconnect() return { 'result': 'failed', 'message': 'Database delete failed.', } @cherrypy.tools.json_out() class UserCheck: exposed = True def GET(self, username): """ Check if a username is unique/unused """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT true FROM pq_user WHERE username = %s", (username, )) if cur.rowcount > 0: return { 'available': False, } else: return { 'available': True, } @cherrypy.tools.json_out() class User: exposed = True def GET(self, user_id = None): """ Return JSON of users """ def multiple(self): db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT user_id, username, email FROM pq_user ORDER BY username;") users = [] for user in cur.fetchall(): u = { 'user_id': user['user_id'], 'username': user['username'], 'email': user['email'] } users.append(u) db.disconnect() return users def single(self, user_id): db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT user_id, username, email FROM pq_user WHERE user_id = %s ORDER BY username;", (user_id, )) user = cur.fetchone() db.disconnect() return { 'user_id': user['user_id'], 'username': user['username'], 'email': user['email'] } if user_id: return single(self, user_id) else: return multiple(self) def POST( self, username, email, password = None, user_id = None ): # clean if user_id: try: user_id = int(user_id) except: return { 'result': 'failure', 'message': 'Invalid user_id'} # do action = None db = DB() cur = db.connect(settings.DSN) if user_id: if password: pasSQL = 'password = %s,' vals = (username, auth.hash(password), email, user_id) else: pasSQL = '' vals = (username, email, user_id) cur.execute( """UPDATE pq_user SET username = %s, """ + pasSQL + """ email = %s WHERE user_id = %s;""", vals ) action = Updated() else: cur.execute( """INSERT INTO pq_user (username, password, email) VALUES (%s,%s,%s);""", (username, auth.hash(password), email) ) action = Inserted() if cur.rowcount > 0: db.commit() db.disconnect() if type(action) == type(Updated()): return { 'result': 'success', 'message': 'User updated successfully.'} elif type(action) == type(Inserted()): return { 'result': 'success', 'message': 'User added successfully.'} else: return { 'result': 'failure', 'message': 'Something was successful? Add/update reported successful, but we have no idea what happened.'} else: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Add/update failed.' } def DELETE(self, user_id): """ Delete a user """ db = DB() cur = db.connect(settings.DSN) cur.execute("""DELETE FROM pq_user WHERE user_id = %s""", (user_id, )) if cur.rowcount > 0: db.commit() db.disconnect() return { 'result': 'success', 'message': 'User deleted successfully.', } elif cur.rowcount > 1: db.rollback() db.disconnect() return { 'result': 'failure', 'message': 'Delete failed. Attempt was made to delete more than one record.' } else: db.rollback() db.disconnect() return { 'result': 'failed', 'message': 'User delete failed.', } @cherrypy.tools.json_out() class TestType: exposed = True def GET(self): """ Return JSON of test types """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT test_type_id, name FROM pq_test_type ORDER BY name;") types = [] for type in cur.fetchall(): t = { 'test_type_id': type['test_type_id'], 'name': type['name'] } types.append(t) db.disconnect() return types @cherrypy.tools.json_out() class Schedule: exposed = True def GET(self): """ Return JSON of schedules """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT schedule_id, name FROM pq_schedule ORDER BY name;") schedules = [] for schedule in cur.fetchall(): s = { 'schedule_id': schedule['schedule_id'], 'name': schedule['name'] } schedules.append(s) db.disconnect() return schedules @cherrypy.tools.json_out() class Log: exposed = True def GET(self, page = None, total = 100): """ Return JSON of logs """ db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT count(log_id) FROM pq_log;") row = cur.fetchone() log_count = row[0] pages = math.ceil(log_count / int(total)) pages = int(math.ceil(float(log_count) / float(total))) try: offset = (int(page) * int(total)) - int(total) except TypeError: offset = 0 cur.execute("""SELECT log_id, lt.log_type_id, lt.name AS log_type, test_id, t.name AS test_name, message, stamp, notify FROM pq_log l JOIN pq_log_type lt USING (log_type_id) JOIN pq_test t USING (test_id) ORDER BY stamp DESC, log_id DESC LIMIT %s OFFSET %s""", (total, offset, )) results = { 'meta': { 'totalLogs': log_count, 'pages': pages, }, 'logs': [], } for log in cur.fetchall(): l = { 'log_id': log['log_id'], 'log_type': log['log_type'], 'log_type_id': log['log_type_id'], 'test_id': log['test_id'], 'test_name': log['test_name'], 'message': log['message'], 'stamp': log['stamp'].isoformat(), 'notify': log['notify'], } results['logs'].append(l) db.disconnect() return results class JSON(object): def GET(self): raise HTTPError(404) class Static(object): def GET(self): return '' class RssLogs(object): exposed = True def GET(self, total = 100, page = None): db = DB() cur = db.connect(settings.DSN) cur.execute("SELECT count(log_id) FROM pq_log;") row = cur.fetchone() log_count = row[0] pages = math.ceil(log_count / int(total)) pages = int(math.ceil(float(log_count) / float(total))) try: offset = (int(page) * int(total)) - int(total) except TypeError: offset = 0 cur.execute("""SELECT log_id, lt.log_type_id, lt.name AS log_type, test_id, t.name AS test_name, message, stamp, notify FROM pq_log l JOIN pq_log_type lt USING (log_type_id) JOIN pq_test t USING (test_id) ORDER BY stamp DESC, log_id DESC LIMIT %s OFFSET %s""", (total, offset, )) results = { 'meta': { 'totalLogs': log_count, 'pages': pages, }, 'logs': [], } items = [] for log in cur.fetchall(): items.append( PyRSS2Gen.RSSItem( title = '[' + log['log_type'] + '] ' + log['test_name'], link = 'http://' + host + ':' + str(port) + '/pyqual#test:' + str(log['test_id']), description = log['message'], guid = PyRSS2Gen.Guid(str(log['log_id'])), pubDate = log['stamp'] ) ) rss = PyRSS2Gen.RSS2( title = "Pyqual Logs", link = "http://" + host + ':' + str(port) + '/', description = "Latest Pyqual logs.", lastBuildDate = datetime.datetime.now(), items = items ) db.disconnect() cherrypy.response.headers['Content-Type'] = 'application/rss+xml' return rss.to_xml() class Rss(object): exposed = True logs = RssLogs() def GET(self): return HTTPError(404) class Index(object): exposed = True @cherrypy.tools.is_authenticated() def GET(self): """ Main page """ t = Templait( settings.APP_ROOT + '/templates/main.html', { 'version': settings.VERSION, } ) return t.render() class Pyqual: exposed = True pyqual = Index() j = JSON() j.test = Test() j.database = Database() j.test_type = TestType() j.schedule = Schedule() j.user = User() j.check_user = UserCheck() j.log = Log() login = LoginPage(auth) rss = Rss() def GET(self): raise cherrypy.HTTPRedirect('/pyqual') cherrypy.server.socket_port = port or 8080 cherrypy.server.socket_host = host or '127.0.0.1' cherrypy.quickstart(Pyqual(), '', settings.CP_CONFIG) if __name__ == '__main__': main()
mit
gertjvr/ChatterBox
src/Client/ChatterBox.ChatClient/Infrastructure/Mappers/MessageDtoToMessageMapper.cs
818
using ChatterBox.ChatClient.Models; using ChatterBox.Core.Mapping; using ChatterBox.MessageContracts.Dtos; namespace ChatterBox.ChatClient.Infrastructure.Mappers { public class MessageDtoToMessageMapper : IMapToNew<MessageDto, Message> { private readonly IMapToNew<UserDto, User> _userMapper; public MessageDtoToMessageMapper(IMapToNew<UserDto, User> userMapper) { _userMapper = userMapper; } public Message Map(MessageDto source) { if (source == null) return null; return new Message { Id = source.Id, Content = source.Content, User = _userMapper.Map(source.User), CreatedAt = source.CreatedAt }; } } }
mit
meteorhacks/kadira
package.js
4266
Package.describe({ "summary": "Performance Monitoring for Meteor", "version": "2.30.2", "git": "https://github.com/meteorhacks/kadira.git", "name": "meteorhacks:kadira" }); var npmModules = { "debug": "0.7.4", "kadira-core": "1.3.2", "pidusage": "1.0.1", "evloop-monitor": "0.1.0", "pidusage": "0.1.1", "lru-cache": "4.0.0", "json-stringify-safe": "5.0.1" }; Npm.depends(npmModules); Package.on_use(function(api) { configurePackage(api); api.export(['Kadira']); }); Package.on_test(function(api) { configurePackage(api); api.use([ 'tinytest', 'test-helpers' ], ['client', 'server']); // common before api.add_files([ 'tests/models/base_error.js' ], ['client', 'server']); // common server api.add_files([ 'tests/utils.js', 'tests/ntp.js', 'tests/jobs.js', 'tests/_helpers/globals.js', 'tests/_helpers/helpers.js', 'tests/_helpers/init.js', 'tests/ping.js', 'tests/hijack/info.js', 'tests/hijack/user.js', 'tests/hijack/email.js', 'tests/hijack/base.js', 'tests/hijack/async.js', 'tests/hijack/http.js', 'tests/hijack/db.js', 'tests/hijack/subscriptions.js', 'tests/hijack/error.js', 'tests/models/methods.js', 'tests/models/pubsub.js', 'tests/models/system.js', 'tests/models/errors.js', 'tests/tracer/tracer_store.js', 'tests/tracer/tracer.js', 'tests/tracer/default_filters.js', 'tests/check_for_oplog.js', 'tests/error_tracking.js', 'tests/wait_time_builder.js', 'tests/hijack/set_labels.js', 'tests/environment_variables.js', 'tests/docsize_cache.js', ], 'server'); // common client api.add_files([ 'tests/client/utils.js', 'tests/client/error_tracking.js', 'tests/client/models/error.js', 'tests/client/error_reporters/window_error.js', 'tests/client/error_reporters/zone.js', 'tests/client/error_reporters/meteor_debug.js', ], 'client'); // common after api.add_files([ 'tests/common/default_error_filters.js', 'tests/common/send.js' ], ['client', 'server']); }); function configurePackage(api) { if(api.versionsFrom) { api.versionsFrom('METEOR@1.2'); api.use('meteorhacks:meteorx@1.4.1', ['server']); api.use('meteorhacks:zones@1.2.1', {weak: true}); } api.use([ 'minimongo', 'livedata', 'mongo-livedata', 'ejson', 'ddp-common', 'underscore', 'http', 'email', 'random' ], ['server']); api.use(['underscore', 'random', 'jquery', 'localstorage'], ['client']); // common before api.add_files([ 'lib/common/unify.js', 'lib/models/base_error.js' ], ['client', 'server']); // only server api.add_files([ 'lib/jobs.js', 'lib/retry.js', 'lib/utils.js', 'lib/ntp.js', 'lib/wait_time_builder.js', 'lib/check_for_oplog.js', 'lib/tracer/tracer.js', 'lib/tracer/default_filters.js', 'lib/tracer/tracer_store.js', 'lib/models/0model.js', 'lib/models/methods.js', 'lib/models/pubsub.js', 'lib/models/system.js', 'lib/models/errors.js', 'lib/docsize_cache.js', 'lib/kadira.js', 'lib/hijack/wrap_server.js', 'lib/hijack/wrap_session.js', 'lib/hijack/wrap_subscription.js', 'lib/hijack/wrap_observers.js', 'lib/hijack/wrap_ddp_stringify.js', 'lib/hijack/instrument.js', 'lib/hijack/db.js', 'lib/hijack/http.js', 'lib/hijack/email.js', 'lib/hijack/async.js', 'lib/hijack/error.js', 'lib/hijack/set_labels.js', 'lib/environment_variables.js', 'lib/auto_connect.js', ], 'server'); // only client api.add_files([ 'lib/retry.js', 'lib/ntp.js', 'lib/client/utils.js', 'lib/client/models/error.js', 'lib/client/error_reporters/zone.js', 'lib/client/error_reporters/window_error.js', 'lib/client/error_reporters/meteor_debug.js', 'lib/client/kadira.js' ], 'client'); api.add_files([ // It's possible to remove this file after some since this just contains // a notice to the user. // Actual implementation is in the meteorhacks:kadira-profiler package 'lib/profiler/client.js', ], 'client'); // common after api.add_files([ 'lib/common/default_error_filters.js', 'lib/common/send.js' ], ['client', 'server']); }
mit
osorubeki-fujita/odpt_tokyo_metro
lib/tokyo_metro/factory/save/api/station_facility/each_file.rb
196
class TokyoMetro::Factory::Save::Api::StationFacility::EachFile < TokyoMetro::Factory::Save::Api::MetaClass::EachFile::DataSearch include ::TokyoMetro::ClassNameLibrary::Api::StationFacility end
mit
jpush/aurora-imui
Android/chatinput/src/main/java/cn/jiguang/imui/chatinput/ChatInputStyle.java
8118
package cn.jiguang.imui.chatinput; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; public class ChatInputStyle extends Style { private static final int DEFAULT_MAX_LINES = 4; private int inputEditTextBg; private int inputMarginLeft; private int inputMarginRight; private int inputMarginBottom; private int inputMarginTop; private int inputMaxLines; private String inputText; private int inputTextSize; private int inputTextColor; private String inputHint; private int inputHintColor; private int inputPaddingLeft; private int inputPaddingRight; private int inputPaddingTop; private int inputPaddingBottom; private int inputCursorDrawable; private Drawable voiceBtnBg; private int voiceBtnIcon; private Drawable photoBtnBg; private int photoBtnIcon; private Drawable cameraBtnBg; private int cameraBtnIcon; private Drawable sendBtnBg; private int sendBtnIcon; private int sendBtnPressedIcon; private Drawable sendCountBg; private boolean showSelectAlbumBtn; private float cameraQuality; public static ChatInputStyle parse(Context context, AttributeSet attrs) { ChatInputStyle style = new ChatInputStyle(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChatInputView); style.inputEditTextBg = typedArray.getResourceId(R.styleable.ChatInputView_inputEditTextBg, R.drawable.aurora_edittext_bg); style.inputMarginLeft = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputMarginLeft, style.getDimension(R.dimen.aurora_margin_input_left)); style.inputMarginRight = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputMarginRight, style.getDimension(R.dimen.aurora_margin_input_right)); style.inputMarginBottom = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputMarginBottom, style.getDimension(R.dimen.aurora_margin_input_bottom)); style.inputMarginTop = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputMarginTop, style.getDimension(R.dimen.aurora_margin_input_top)); style.inputMaxLines = typedArray.getInt(R.styleable.ChatInputView_inputMaxLines, DEFAULT_MAX_LINES); style.inputHint = typedArray.getString(R.styleable.ChatInputView_inputHint); style.inputText = typedArray.getString(R.styleable.ChatInputView_inputText); style.inputTextSize = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputTextSize, style.getDimension(R.dimen.aurora_textsize_input)); style.inputTextColor = typedArray.getColor(R.styleable.ChatInputView_inputTextColor, style.getColor(R.color.aurora_text_color_input)); style.inputHintColor = typedArray.getColor(R.styleable.ChatInputView_inputHintColor, style.getColor(R.color.aurora_hint_color_input)); style.inputCursorDrawable = typedArray.getResourceId(R.styleable.ChatInputView_inputCursorDrawable, R.drawable.aurora_edittext_cursor_bg); style.voiceBtnBg = typedArray.getDrawable(R.styleable.ChatInputView_voiceBtnBg); style.voiceBtnIcon = typedArray.getResourceId(R.styleable.ChatInputView_voiceBtnIcon, R.drawable.aurora_menuitem_mic); style.photoBtnBg = typedArray.getDrawable(R.styleable.ChatInputView_photoBtnBg); style.photoBtnIcon = typedArray.getResourceId(R.styleable.ChatInputView_photoBtnIcon, R.drawable.aurora_menuitem_photo); style.cameraBtnBg = typedArray.getDrawable(R.styleable.ChatInputView_cameraBtnBg); style.cameraBtnIcon = typedArray.getResourceId(R.styleable.ChatInputView_cameraBtnIcon, R.drawable.aurora_menuitem_camera); style.sendBtnBg = typedArray.getDrawable(R.styleable.ChatInputView_sendBtnBg); style.sendBtnIcon = typedArray.getResourceId(R.styleable.ChatInputView_sendBtnIcon, R.drawable.aurora_menuitem_send); style.sendBtnPressedIcon = typedArray.getResourceId(R.styleable.ChatInputView_sendBtnPressedIcon, R.drawable.aurora_menuitem_send_pres); style.sendCountBg = typedArray.getDrawable(R.styleable.ChatInputView_sendCountBg); style.showSelectAlbumBtn = typedArray.getBoolean(R.styleable.ChatInputView_showSelectAlbum, true); style.inputPaddingLeft = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputPaddingLeft, style.getDimension(R.dimen.aurora_padding_input_left)); style.inputPaddingTop = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputPaddingTop, style.getDimension(R.dimen.aurora_padding_input_top)); style.inputPaddingRight = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputPaddingRight, style.getDimension(R.dimen.aurora_padding_input_right)); style.inputPaddingBottom = typedArray.getDimensionPixelSize(R.styleable.ChatInputView_inputPaddingBottom, style.getDimension(R.dimen.aurora_padding_input_bottom)); style.cameraQuality = typedArray.getFloat(R.styleable.ChatInputView_cameraQuality,0.5f); typedArray.recycle(); return style; } private ChatInputStyle(Context context, AttributeSet attrs) { super(context, attrs); } public Drawable getVoiceBtnBg() { return this.voiceBtnBg; } public int getVoiceBtnIcon() { return this.voiceBtnIcon; } public int getInputEditTextBg() { return this.inputEditTextBg; } public int getInputMarginLeft() { return this.inputMarginLeft; } public int getInputMarginRight() { return this.inputMarginRight; } public int getInputMarginTop() { return this.inputMarginTop; } public int getInputMarginBottom() { return this.inputMarginBottom; } public int getInputMaxLines() { return this.inputMaxLines; } public String getInputHint() { return this.inputHint; } public String getInputText() { return this.inputText; } public int getInputTextSize() { return this.inputTextSize; } public int getInputTextColor() { return this.inputTextColor; } public int getInputHintColor() { return this.inputHintColor; } public int getInputCursorDrawable() { return this.inputCursorDrawable; } public Drawable getPhotoBtnBg() { return photoBtnBg; } public int getPhotoBtnIcon() { return photoBtnIcon; } public Drawable getCameraBtnBg() { return cameraBtnBg; } public int getCameraBtnIcon() { return cameraBtnIcon; } public int getSendBtnIcon() { return sendBtnIcon; } public int getSendBtnPressedIcon() { return this.sendBtnPressedIcon; } public void setSendBtnPressedIcon(int resId) { this.sendBtnPressedIcon = resId; } public Drawable getSendBtnBg() { return this.sendBtnBg; } public Drawable getSendCountBg() { if (sendCountBg == null) { return ContextCompat.getDrawable(mContext, R.drawable.aurora_menuitem_send_count_bg); } return this.sendCountBg; } public int getInputPaddingLeft() { return inputPaddingLeft; } public int getInputPaddingRight() { return inputPaddingRight; } public int getInputPaddingTop() { return inputPaddingTop; } public int getInputPaddingBottom() { return inputPaddingBottom; } public boolean getShowSelectAlbum() { return this.showSelectAlbumBtn; } public float getCameraQuality() { return this.cameraQuality <= 0.01f ? 0.01f : this.cameraQuality; } public void setCameraQuality(float cameraQuality) { this.cameraQuality = cameraQuality; } }
mit
sparkdesignsystem/spark-design-system
angular/projects/spark-angular/src/lib/directives/inputs/sprk-helper-text/sprk-helper-text.directive.ts
938
import { Directive, ElementRef, OnInit, Input, HostBinding, Renderer2, } from '@angular/core'; @Directive({ selector: '[sprkHelperText]', }) export class SprkHelperTextDirective implements OnInit { /** * @ignore */ constructor(public ref: ElementRef, private renderer: Renderer2) {} /** * The value supplied will be assigned * to the `data-id` attribute on the * element. This is intended to be * used as a selector for automated * tools. This value should be unique * per page. */ @HostBinding('attr.data-id') @Input() idString: string; /** * The value supplied will be assigned to the * `data-analytics` attribute on the element. * Intended for an outside * library to capture data. */ @HostBinding('attr.data-analytics') @Input() analyticsString: string; ngOnInit(): void { this.renderer.addClass(this.ref.nativeElement, 'sprk-b-HelperText'); } }
mit
Trinovantes/MyAnimeList-Cover-CSS-Generator
src/tasks/scraper.js
4292
'use strict'; const request = require("request"); const vasync = require('vasync'); const logger = require('src/utils/logger'); const sleep = require('src/utils/sleep'); const Constants = require('src/utils/constants'); const MALCoverCSSDB = require('src/models/MALCoverCSSDB'); //----------------------------------------------------------------------------- // Scraper //----------------------------------------------------------------------------- module.exports = function scrapeUsers(onComplete) { logger.header('Starting to scrape users'); let dbmgr = MALCoverCSSDB.connect(); let jobBarrier = vasync.barrier(); jobBarrier.on('drain', function() { logger.info('Finished scraping users'); onComplete(); }); dbmgr.getUsersToScrape(async (users) => { logger.info('Found %d users to scrape', users.length); if (users.length === 0) { jobBarrier.start('dummy'); jobBarrier.done('dummy'); return; } for (let user of users) { let userIsValid = true; const username = user.username; let barrierKey = `update ${username}`; jobBarrier.start(barrierKey); let userBarrier = vasync.barrier(); userBarrier.on('drain', function() { if (userIsValid) { dbmgr.updateUserLastScraped(user, () => { jobBarrier.done(barrierKey); }); } else { jobBarrier.done(barrierKey); } }); let userBarrierKey = 'this ensures all the barriers inside scrapeUser has started before userBarrier can drain'; userBarrier.start(userBarrierKey); scrapeUser(dbmgr, userBarrier, user, 'anime', () => { userIsValid = false; }); await sleep(1000); scrapeUser(dbmgr, userBarrier, user, 'manga', () => { userIsValid = false; }); await sleep(1000); userBarrier.done(userBarrierKey); } }); } //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- function scrapeUser(dbmgr, barrier, user, mediaType, onDeleteUser, pageNum = 1) { const username = user.username; const barrierKey = `scrape:${username}:${mediaType}:${pageNum}`; const url = `https://api.jikan.moe/v3/user/${username}/${mediaType}list/all/${pageNum}`; const options = { url: url, }; logger.info('Fetching %s', url); barrier.start(barrierKey); request(options, function(error, response, body) { switch (response.statusCode) { case 400: { logger.warn('[%s] User %s does not exist on MyAnimeList.net', mediaType, username); dbmgr.deleteUserIfExists(user, () => { onDeleteUser(); barrier.done(barrierKey); }); break; } case 200: { let info = JSON.parse(body); let items = info[mediaType]; logger.info('[%s] Scraped %d items from "%s"', mediaType, items.length, username) for (let item of items) { const malId = item['mal_id']; const imgUrl = item['image_url']; const itemBarrierKey = `update mal item:${mediaType}:${malId}`; barrier.start(itemBarrierKey); dbmgr.updateMALItem(mediaType, malId, imgUrl, () => { barrier.done(itemBarrierKey); }); } if (items.length == Constants.MAX_ITEMS_PER_PAGE) { // If this page contains max num items, there might be another page scrapeUser(dbmgr, barrier, user, mediaType, onDeleteUser, pageNum + 1); } barrier.done(barrierKey); break; } default: { logger.error('[%s] Unknown failure when trying to scrape user %s : %s', mediaType, username, error); barrier.done(barrierKey); } } }); }
mit
gcubar/BlogBundle-Symfony
src/Rimed/BlogBundle/Entity/BaseTag.php
256
<?php namespace Rimed\BlogBundle\Entity; use Rimed\BlogBundle\Model\Tag as ModelTag; class BaseTag extends ModelTag { public function prePersist() { $this->setCreatedAt(new \DateTime); $this->setUpdatedAt(new \DateTime); } }
mit
xZ1mEFx/yii2-multilang
views/language/adminlte/_form.php
1637
<?php use xz1mefx\adminlte\helpers\Html; use xz1mefx\adminlte\widgets\ActiveForm; /* @var $this \yii\web\View */ /* @var $model \xz1mefx\multilang\models\Language */ /* @var $form ActiveForm */ ?> <div class="box box-primary"> <div class="box-body"> <div class="box-body-overflow"> <?php $form = ActiveForm::begin(['enableAjaxValidation' => TRUE, 'validateOnType' => TRUE]); ?> <?= $form->field($model, 'url')->textInput(['maxlength' => TRUE, 'placeholder' => Yii::t('multilang-tools', 'Enter a url...')]) ?> <?= $form->field($model, 'locale')->textInput(['maxlength' => TRUE, 'placeholder' => Yii::t('multilang-tools', 'Enter a locale...')]) ?> <?= $form->field($model, 'name')->textInput(['maxlength' => TRUE, 'placeholder' => Yii::t('multilang-tools', 'Enter a name...')]) ?> <?php if (!$model['default']): ?> <?= $form->field($model, 'default')->checkbox() ?> <p class="text-info" style="margin-top: -15px;"> <?= Html::icon('info-sign') . ' ' . Yii::t('multilang-tools', 'If you select this option here, it will be reset everywhere') ?> </p> <?php endif; ?> <div class="form-group"> <?= Html::submitButton( $model->isNewRecord ? Yii::t('multilang-tools', 'Add language') : Yii::t('multilang-tools', 'Update language'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'] ) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div>
mit
maceto/file_generator
spec/support/helpers.rb
353
require "ostruct" require "yaml" module Helpers def load_formats(path = "/spec/formats.yml") formats_file = File.join(Dir.pwd, path) if File.exists?(formats_file) conf = YAML.load(File.read("#{Dir.pwd}#{path}")) OpenStruct.new(conf) else "missing formats file." end end end RSpec.configuration.include Helpers
mit
Lallassu/VoxLords
js/vox.js
8556
//============================================================================== // Author: Nergal // http://webgl.nu // Date: 2014-11-17 //============================================================================== function VoxelData() { this.x; this.y; this.z; this.color; VoxelData.prototype.Create = function(buffer, i, subSample) { this.x = (subSample? buffer[i] & 0xFF / 2 : buffer[i++] & 0xFF); this.y = (subSample? buffer[i] & 0xFF / 2 : buffer[i++] & 0xFF); this.z = (subSample? buffer[i] & 0xFF / 2 : buffer[i++] & 0xFF); this.color = buffer[i] & 0xFF; }; } VoxelData.prototype = new VoxelData(); VoxelData.prototype.constructor = VoxelData; function Vox() { this.chunk = undefined; var voxColors = [0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff, 0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff, 0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, 0xff6699ff, 0xff3399ff, 0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff, 0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff, 0xff0033ff, 0xffff00ff, 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff, 0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc, 0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc, 0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc, 0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc, 0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, 0xff6633cc, 0xff3333cc, 0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc, 0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99, 0xff00ff99, 0xffffcc99, 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99, 0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999, 0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699, 0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399, 0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099, 0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, 0xff66ff66, 0xff33ff66, 0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66, 0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966, 0xff009966, 0xffff6666, 0xffcc6666, 0xff996666, 0xff666666, 0xff336666, 0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366, 0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066, 0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33, 0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33, 0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, 0xff669933, 0xff339933, 0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633, 0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333, 0xff003333, 0xffff0033, 0xffcc0033, 0xff990033, 0xff660033, 0xff330033, 0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00, 0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00, 0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900, 0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600, 0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, 0xff663300, 0xff333300, 0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000, 0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077, 0xff000055, 0xff000044, 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00, 0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400, 0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000, 0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000, 0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777, 0xff555555, 0xff444444, 0xff222222, 0xff111111]; Vox.prototype.getChunk = function() { return this.chunk; }; Vox.prototype.getMesh = function() { return this.chunk.mesh; }; Vox.prototype.readInt = function(buffer, from) { return buffer[from]| (buffer[from+1] << 8) | (buffer[from+2] << 16) | (buffer[from+3] << 24); }; Vox.prototype.LoadModel = function(filename, loadptr, name) { this.name = name; var oReq = new XMLHttpRequest(); oReq.open("GET", "models/"+filename, true); oReq.responseType = "arraybuffer"; var that = this; oReq.onload = function (oEvent) { var colors = []; var colors2 = undefined; var voxelData = []; that.chunk = new Chunk(); console.log("Loaded model: "+oReq.responseURL); var arrayBuffer = oReq.response; if (arrayBuffer) { var buffer = new Uint8Array(arrayBuffer); var voxId = that.readInt(buffer, 0); var version = that.readInt(buffer, 4); // TBD: Check version to support var i = 8; while(i < buffer.length) { var subSample = false; var sizex = 0, sizey = 0, sizez = 0; var id = String.fromCharCode(parseInt(buffer[i++]))+ String.fromCharCode(parseInt(buffer[i++]))+ String.fromCharCode(parseInt(buffer[i++]))+ String.fromCharCode(parseInt(buffer[i++])); var chunkSize = that.readInt(buffer, i) & 0xFF; i += 4; var childChunks = that.readInt(buffer, i) & 0xFF; i += 4; if(id == "SIZE") { sizex = that.readInt(buffer, i) & 0xFF; i += 4; sizey = that.readInt(buffer, i) & 0xFF; i += 4; sizez = that.readInt(buffer, i) & 0xFF; i += 4; if (sizex > 32 || sizey > 32) { subSample = true; } console.log(filename + " => Create VOX Chunk!"); that.chunk.Create(sizex, sizey, sizez); i += chunkSize - 4 * 3; } else if (id == "XYZI") { var numVoxels = Math.abs(that.readInt(buffer, i)); i += 4; voxelData = new Array(numVoxels); for (var n = 0; n < voxelData.length; n++) {; voxelData[n] = new VoxelData(); voxelData[n].Create(buffer, i, subSample); // Read 4 bytes i += 4; } } else if (id == "RGBA") { console.log(filename + " => Regular color chunk"); colors2 = new Array(256); for (var n = 0; n < 256; n++) { var r = buffer[i++] & 0xFF; var g = buffer[i++] & 0xFF; var b = buffer[i++] & 0xFF; var a = buffer[i++] & 0xFF; colors2[n] = {'r': r, 'g': g, 'b': b, 'a': a}; } } else { i += chunkSize; } } if (voxelData == null || voxelData.length == 0) { return null; } for (var n = 0; n < voxelData.length; n++) { if(colors2 == undefined) { var c = voxColors[Math.abs(voxelData[n].color-1)]; var cRGBA = { b: (c & 0xff0000) >> 16, g: (c & 0x00ff00) >> 8, r: (c & 0x0000ff), a: 1 }; that.chunk.ActivateBlock(voxelData[n].x, voxelData[n].y, voxelData[n].z, cRGBA); } else { that.chunk.ActivateBlock(voxelData[n].x, voxelData[n].y, voxelData[n].z, colors2[Math.abs(voxelData[n].color-1)]); } } loadptr(that, name); } }; oReq.send(null); }; } Vox.prototype = new Vox(); Vox.prototype.constructor = Vox;
mit
agraubert/Beymax
beymax/perms.py
17717
from .utils import DBView from agutil import hashfile import yaml from collections import namedtuple import warnings import sys import os Rule = namedtuple("Rule", ['allow', 'deny', 'underscore', 'type', 'data']) class PermissionsFile(object): _FALLBACK_DEFAULT = Rule(['$all'], [], False, None, {}) @staticmethod def validate_rule(obj, is_default=False): if is_default: if 'role' in obj or 'users' in obj: raise TypeError("role and users cannot be set on default permissions") else: if not (('role' in obj) ^ ('users' in obj)): raise TypeError("role or users must be set on each permissions object") if not ('allow' in obj or 'deny' in obj or 'underscore' in obj): raise TypeError("Permissions object must set some permission (allow, deny, or underscore)") # return Rule( # obj['allow'] if 'allow' in obj else None, # obj['deny'] if 'deny' in obj else None, # obj['underscore'] if 'underscore' in obj else None, # rule_type, # 0 if is_default else ( # bot.primary # ) # ) async def fingerprint(self, bot, filepath, users, roles): sha1 = hashfile(filepath).hex() async with DBView('permissions', permissions={}) as db: if not ('sha1' in db['permissions'] and db['permissions']['sha1'] == sha1): # File changed, reprint db['permissions'] = { 'sha1': sha1, 'users': {uname: uid for uname, uid in users.items()}, 'roles': {rname: [(gid, rid) for gid,rid in role_matches] for rname, role_matches in roles.items()} } return mismatch = [] if 'users' in db['permissions']: for uname, uid in db['permissions']['users'].items(): if not (uname in users and uid == users[uname]): mismatch.append( 'User Reference "{}" previously matched User ID {} but now matches User ID {}'.format( uname, uid, users[uname] if uname in users else '<None>' ) ) # if {*roles} != {*db['permissions']['roles']}: # mismatch.append( # "Different roles matched. Previously, these roles were matched {}, but now these roles are matched {}".format( # ', '.join(db['permissions']['roles']), # ', '.join(roles) # ) # ) for r in {*roles} | {*db['permissions']['roles']}: if r in roles and r in db['permissions']['roles']: new_matches = [ (gid, rid) for gid, rid in roles[r] if (gid, rid) not in db['permissions']['roles'][r] ] old_matches = [ (gid, rid) for gid, rid in db['permissions']['roles'][r] if (gid, rid) not in roles[r] ] changed_matches = [ (gid, rid) for gid, rid in db['permissions']['roles'][r] if (gid, rid) not in roles[r] and gid in {g for g,_ in roles[r]} ] if len(new_matches) + len(old_matches) + len(changed_matches) > 0: mismatch.append( 'Role "{}" has changed matches. New matches in new guilds: {}. ' 'Missing matches in old guilds: {}. Changed matches in old guilds: {}'.format( r, ', '.join( '{} in server {}'.format( rid, gid ) for gid, rid in new_matches ), ', '.join( '{} in server {}'.format( rid, gid ) for gid, rid in old_matches ), ', '.join( '{} in server {}'.format( rid, gid ) for gid, rid in changed_matches ) ) ) elif r not in roles: mismatch.append( 'Role "{}" no longer has any matches, but previously matched {}'.format( r, ', '.join( '{} in server {}'.format( rid, gid ) for gid, rid in db['permissions']['roles'][r] ) ) ) else: mismatch.append( 'Role "{}" previously had no matches but now matches {}'.format( r, ', '.join( '{} in server {}'.format( rid, gid ) for gid, rid in roles[r] ) ) ) if len(mismatch) > 0: handling = bot.config_get('permissions_matching', default='previous') print('\n'.join(mismatch)) if handling == 'strict': sys.exit("\nPlease update references in permissions file to match new entities") elif handling == 'previous': for uname, cid in db['permissions']['users'].items(): oid = users[uname] if cid != oid: for i in range(len(self.user_rules[oid])): if self.user_rules[oid][i].data['reference'] == uname: print("Moving rule referenced by", uname, "from", oid, "to", cid) if cid not in self.user_rules: self.user_rules[cid] = [] self.user_rules[cid].append(self.user_rules[oid][i]) self.user_rules[oid][i] = Rule( [], [], None, 'user', { 'reference': '<None>', 'priority': 1000 } ) for rname in db['permissions']['roles']: for cgid, crid in db['permissions']['roles'][rname]: o_guild = roles[rname] for ogid, orid in o_guild: if cgid != ogid or crid != orid: for i in range(len(self.guild_rules[ogid])): if self.guild_rules[ogid][i].data['name'] == rname and cgid in {g.id for g in bot.guilds}: print("Moving rule referenced by", rname, "from", ogid, orid, "to", cgid, crid) if cgid not in self.guild_rules: self.guild_rules[cgid] = [] self.guild_rules[cgid].append(self.guild_rules[ogid][i]) self.guild_rules[ogid][i] = Rule( [], [], None, 'role', { 'name': '<None>', 'gid': ogid, 'id': orid, 'priority': 1000 } ) elif handling == 'update': db['permissions'] = { 'sha1': sha1, 'users': {uname: uid for uname, uid in users.items()}, 'roles': {rname: [(gid, rid) for gid,rid in role_matches] for rname, role_matches in roles.items()} } @staticmethod async def load(bot, filepath): self = PermissionsFile() self.bot = bot self.default = PermissionsFile._FALLBACK_DEFAULT self.user_rules = {} #uid: [rules] self.guild_rules = { guild.id: [] for guild in bot.guilds } #gid: sorted(rules, key=guild's hierarchy) if os.path.exists(filepath): with open(filepath) as reader: permissions = yaml.load(reader, Loader=yaml.SafeLoader) if not isinstance(permissions, dict): raise TypeError("Permissions file '{}' must be a dictionary".format(filepath)) if 'defaults' not in permissions: raise TypeError("Permissions file '{}' must define a 'defaults' key".format(filepath)) PermissionsFile.validate_rule(permissions['defaults'], True) self.default = Rule( permissions['defaults']['allow'] if 'allow' in permissions['defaults'] else [], permissions['defaults']['deny'] if 'deny' in permissions['defaults'] else [], permissions['defaults']['underscore'] if 'underscore' in permissions['defaults'] else None, None, {} ) # load rules, validate each, and separate into user and role lists users = {} fingerprint_roles = {} guild_roles = { guild.id: [*guild.roles] for guild in bot.guilds } if 'rules' in permissions: if not isinstance(permissions['rules'], list): raise TypeError("Permissions file '{}' rules must be a list".format(filepath)) seen_roles = set() for i, rule in enumerate(permissions['rules']): PermissionsFile.validate_rule(rule) if 'role' in rule: if rule['role'] in seen_roles: raise TypeError( "Duplicate role '{}' encountered in permissions file '{}'".format( rule['role'], filepath ) ) seen_roles.add(rule['role']) matched = False for gid, roles in guild_roles.items(): # in hierarchy order for pri, r in enumerate(roles): if rule['role'] == r.id or rule['role'] == r.name: matched = True if rule['role'] not in fingerprint_roles: fingerprint_roles[rule['role']] = [] fingerprint_roles[rule['role']].append((gid, r.id)) self.guild_rules[gid].append( Rule( rule['allow'] if 'allow' in rule else [], rule['deny'] if 'deny' in rule else [], rule['underscore'] if 'underscore' in rule else None, 'role', { 'name': r.name, 'gid': gid, 'id': r.id, 'priority': pri } ) ) if matched is False: raise ValueError("Rule for role '{}' in permissions file '{}' did not match any guilds".format( rule['role'], filepath )) else: # Load user rules for reference in rule['users']: try: uid = bot.getid(reference) users[reference] = uid if uid not in self.user_rules: self.user_rules[uid] = [] self.user_rules[uid].append(Rule( rule['allow'] if 'allow' in rule else [], rule['deny'] if 'deny' in rule else [], rule['underscore'] if 'underscore' in rule else None, 'user', { 'priority': len(rule['users']), 'reference': reference } )) except NameError: raise ValueError("User reference '{}' in permissions file '{}' did not match any users".format( reference, filepath )) from e # check fingerprint await self.fingerprint( bot, filepath, users, fingerprint_roles ) # build permission chains: for gid in self.guild_rules: self.guild_rules[gid].sort(key = lambda r:r.data['priority']) for uid in self.user_rules: self.user_rules[uid].sort(key = lambda r:r.data['priority']) return self def query(self, user, cmd=None, *, _chain=None): """ Queries user permissions. If cmd is provided, returns the following tuple: * Allowed: Boolean indicating if use of the given command is allowed in the user's context * Rule: The rule used for this decision If cmd is not provided (default), return a list of rules which apply to the user, in order from highest priority to lowest. """ if _chain is None: _chain = [] if user.id in self.user_rules: _chain += [rule for rule in self.user_rules[user.id]] if self.bot.primary_guild is not None: u = self.bot.primary_guild.get_member(user.id) if u is not None: user = u if hasattr(user, 'roles') and hasattr(user, 'guild'): user_roles = {role.id for role in user.roles} if user.guild.id in self.guild_rules: for rule in self.guild_rules[user.guild.id]: if rule.data['id'] in user_roles: _chain.append(rule) _chain += [self.default, PermissionsFile._FALLBACK_DEFAULT] if cmd is not None: for rule in _chain: if cmd in rule.allow or (not cmd.startswith('_') and '$all' in rule.allow): return True, rule elif cmd in rule.deny or (not cmd.startswith('_') and '$all' in rule.deny): return False, rule elif cmd.startswith('_') and rule.underscore is not None: return rule.underscore, rule raise RuntimeError("There should always be a valid rule for any command") return _chain def query_underscore(self, user, *, _chain=None): """ Checks if the given user has admin privileges. Returns the following tuple: * Allowed: Boolean indicating if underscore commands are allowed * Rule: The rule used for this decision """ if _chain is None: _chain = self.query(user) for rule in _chain: if rule.underscore is not None: return rule.underscore, rule raise RuntimeError("There should always be a valid rule for any command")
mit
xguz/bravo
lib/bravo/constants.rb
3327
# encoding: utf-8 # Here we define Hashes # module Bravo # This constant contains the invoice types mappings between codes and names # used by WSFE. CBTE_TIPO = { '01' => 'Factura A', '02' => 'Nota de Débito A', '03' => 'Nota de Crédito A', '04' => 'Recibos A', '05' => 'Notas de Venta al contado A', '06' => 'Factura B', '07' => 'Nota de Debito B', '08' => 'Nota de Credito B', '09' => 'Recibos B', '10' => 'Notas de Venta al contado B', '34' => 'Cbtes. A del Anexo I, Apartado A,inc.f),R.G.Nro. 1415', '35' => 'Cbtes. B del Anexo I,Apartado A,inc. f),R.G. Nro. 1415', '39' => 'Otros comprobantes A que cumplan con R.G.Nro. 1415', '40' => 'Otros comprobantes B que cumplan con R.G.Nro. 1415', '60' => 'Cta de Vta y Liquido prod. A', '61' => 'Cta de Vta y Liquido prod. B', '63' => 'Liquidacion A', '64' => 'Liquidacion B' } # Name to code mapping for Sale types. # CONCEPTOS = { 'Productos' => '01', 'Servicios' => '02', 'Productos y Servicios' => '03' } # Name to code mapping for types of documents. # DOCUMENTOS = { 'CUIT' => '80', 'CUIL' => '86', 'CDI' => '87', 'LE' => '89', 'LC' => '90', 'CI Extranjera' => '91', 'en tramite' => '92', 'Acta Nacimiento' => '93', 'CI Bs. As. RNP' => '95', 'DNI' => '96', 'Pasaporte' => '94', 'Doc. (Otro)' => '99' } # Currency code and names hash identified by a symbol # MONEDAS = { peso: { codigo: 'PES', nombre: 'Pesos Argentinos' }, dolar: { codigo: 'DOL', nombre: 'Dolar Estadounidense' }, real: { codigo: '012', nombre: 'Real' }, euro: { codigo: '060', nombre: 'Euro' }, oro: { codigo: '049', nombre: 'Gramos de Oro Fino' } } # Tax percentage and codes according to each iva combination # ALIC_IVA = { iva_0: ['03', 0], iva_10: ['04', 0.105], iva_21: ['05', 0.21], iva_27: ['06', 0.27] } # This hash keeps the codes for A document types by operation # BILL_TYPE_A = { invoice: '01', debit: '02', credit: '03', receipt: '04' } # This hash keeps the codes for B document types by operation # BILL_TYPE_B = { invoice: '06', debit: '07', credit: '08', receipt: '09' } # This hash keeps the different types of bills # BILL_TYPE = { bill_a: BILL_TYPE_A, bill_b: BILL_TYPE_B } # This hash is used to validate the buyer condition and the bill type being issued. # Usage: # `BILL_TYPE[seller_iva_cond][buyer_iva_cond][invoice_type]` #=> invoice type as string # `BILL_TYPE[:responsable_inscripto][:responsable_inscripto][:invoice]` #=> '01' # IVA_CONDITION = { responsable_inscripto: { responsable_inscripto: BILL_TYPE_A, consumidor_final: BILL_TYPE_B, exento: BILL_TYPE_B, responsable_monotributo: BILL_TYPE_B }, } # This hash keeps the set of urls for wsaa and wsfe for production and testing envs # URLS = { test: { wsaa: 'https://wsaahomo.afip.gov.ar/ws/services/LoginCms', wsfe: 'https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL' }, production: { wsaa: 'https://wsaa.afip.gov.ar/ws/services/LoginCms', wsfe: 'https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL' } } end
mit
wearska/wearska
app/components/navigation/navigation.factory.js
2250
(function() { 'use strict'; angular.module('daksports') .factory('dakNav', function() { var obj = {}; obj.adminItems = [{ title: 'Items list', icon: 'assets/icons/ic_view_list_24px.svg', ref: '/admin/list', }, { title: 'Add item', icon: 'assets/icons/ic_playlist_add_24px.svg', ref: '/admin/add', }, { title: 'Orders', icon: 'assets/icons/ic_shopping_basket_24px.svg', ref: '/admin/orders', }, { title: 'Settings', icon: 'assets/icons/ic_settings_24px.svg', ref: '/admin/settings', }]; obj.accountItems = [{ title: 'Shopping lists', icon: 'assets/icons/ic_view_list_24px.svg', ref: '/account/lists', }, { title: 'Favourites', icon: 'assets/icons/ic_favorite_24px.svg', ref: '/account/favourites', }, { title: 'My reviews', icon: 'assets/icons/ic_rate_review_24px.svg', ref: '/account/reviews', }, { title: 'Settings', icon: 'assets/icons/ic_settings_24px.svg', ref: '/account/settings', }]; obj.menuItems = [{ title: 'View Cart', icon: 'assets/icons/ic_shopping_cart_24px.svg', ref: '/cart', }, { title: 'Store', icon: 'assets/icons/ic_store_24px.svg', ref: '/store' }]; obj.bottomItems = [{ title: 'View Cart', icon: 'assets/icons/ic_shopping_cart_24px.svg', ref: '/cart', }, { title: 'Store', icon: 'assets/icons/ic_store_24px.svg', ref: '/store' },{ title: 'Settings', icon: 'assets/icons/ic_settings_24px.svg', ref: '/account/settings', }]; return obj; }); })();
mit
earalov/Skylines-NoPillars
NoPillars/NoPillarsMonitor.cs
4854
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using ColossalFramework; using UnityEngine; namespace NoPillars { public class NoPillarsMonitor : MonoBehaviour { private const string GameObjectName = "NoPillarsMonitor"; private NetInfo currentPrefab; private FieldInfo finePrefab; private Type fineType; private List<NetInfoExtensions.Metadata> savedMetadata; private int currentPillars = -1; private int currentCollide = -1; private bool currentAlwaysVisible; public static void Initialize() { var gameObject = new GameObject(GameObjectName); var monitor = gameObject.AddComponent<NoPillarsMonitor>(); if (!Util.IsModActive("Fine Road Heights")) { return; } monitor.fineType = FineNetToolType(); if (monitor.fineType != null) { monitor.finePrefab = monitor.fineType.GetField("m_prefab", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); } } public static void Dispose() { var gameObject = GameObject.Find(GameObjectName); if (gameObject != null) { Destroy(gameObject); } } public void Awake() { currentAlwaysVisible = Options.OptionsHolder.Options.alwaysVisible; } public void Update() { var prefab = GetToolPrefab(); var alwaysVisible = Options.OptionsHolder.Options.alwaysVisible; if (prefab == null && !alwaysVisible) { NoPillarsUI.Hide(); if (currentPrefab == null && currentAlwaysVisible == alwaysVisible) { return; } Reset(); currentPrefab = null; if (Options.OptionsHolder.Options.resetOnHide) { NoPillarsUI.Reset(); } currentAlwaysVisible = alwaysVisible; } else { currentAlwaysVisible = alwaysVisible; NoPillarsUI.Show(); var collide = NoPillarsUI.Collide; var pillars = NoPillarsUI.Pillars; if (currentCollide == collide && currentPillars == pillars) { return; } Reset(); currentPrefab = prefab; currentPillars = pillars; currentCollide = collide; savedMetadata = new List<NetInfoExtensions.Metadata>(); foreach (var prefabToModify in Util.GetAllPrefabs()) { savedMetadata.Add(prefabToModify.GetMetadata()); prefabToModify.SetMetadata(collide, pillars); } } } private void Reset() { if (savedMetadata != null) { foreach (var metadata in savedMetadata) { metadata.info.SetMetadata(metadata); } } savedMetadata = null; currentPrefab = null; currentPillars = -1; currentCollide = -1; } private NetInfo GetToolPrefab() { var tool = ToolsModifierControl.GetCurrentTool<ToolBase>(); if (tool == null) { return null; } var netTool = tool as NetTool; if (netTool != null) { return netTool.m_prefab; } var buildingTool = tool as BuildingTool; if (buildingTool != null) { BuildingInfo building; if (buildingTool.m_relocate == 0) { building = buildingTool.m_prefab; } else { building = Singleton<BuildingManager>.instance.m_buildings.m_buffer[buildingTool.m_relocate].Info; } var paths = building?.m_paths; if (paths == null || paths.Length < 1) { return null; } return (from path in paths where path.m_netInfo != null select path.m_netInfo).FirstOrDefault(); } if (tool.GetType() == fineType) { return (NetInfo)finePrefab.GetValue(tool); } return null; } private static Type FineNetToolType() { return Util.FindType("NetToolFine"); } } }
mit
TrigenSoftware/i18n-for-browser
src/index.ts
236
import Config from './config'; import { globalConfig } from './methods/common'; export * from './types'; export * from './processors'; export * from './methods'; export type I18nConfigInstance = Config; export default globalConfig;
mit
klinster/School-Work
practice/lrn2laravel/config/app.php
7339
<?php return [ /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ // 'debug' => false, 'debug' => env('APP_DEBUG'), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY', 'SomeRandomString'), 'cipher' => MCRYPT_RIJNDAEL_128, /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => 'daily', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Bus\BusServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Foundation\Providers\FoundationServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Pipeline\PipelineServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Passwords\PasswordResetServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Html\HtmlServiceProvider', /* * Application Service Providers... */ 'App\Providers\AppServiceProvider', 'App\Providers\BusServiceProvider', 'App\Providers\ConfigServiceProvider', 'App\Providers\EventServiceProvider', 'App\Providers\RouteServiceProvider', 'Laracasts\Flash\FlashServiceProvider', ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Bus' => 'Illuminate\Support\Facades\Bus', 'Cache' => 'Illuminate\Support\Facades\Cache', 'Config' => 'Illuminate\Support\Facades\Config', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Hash' => 'Illuminate\Support\Facades\Hash', 'Input' => 'Illuminate\Support\Facades\Input', 'Inspiring' => 'Illuminate\Foundation\Inspiring', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Session' => 'Illuminate\Support\Facades\Session', 'Storage' => 'Illuminate\Support\Facades\Storage', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'Form' => 'Illuminate\Html\FormFacade', 'Html' => 'Illuminate\Html\HtmlFacade', 'Flash' => 'Laracasts\Flash\Flash' ], ];
mit
envato/stack_master
spec/stack_master/test_driver/cloud_formation_spec.rb
3049
require 'stack_master/test_driver/cloud_formation' RSpec.describe StackMaster::TestDriver::CloudFormation do subject(:test_cf_driver) { described_class.new } context 'stacks' do it 'creates and describes stacks' do test_cf_driver.create_stack(stack_id: "1", stack_name: 'stack-1') test_cf_driver.create_stack(stack_id: "2", stack_name: 'stack-2') expect(test_cf_driver.describe_stacks.stacks.map(&:stack_id)).to eq(["1", "2"]) end it 'adds and gets stack events' do test_cf_driver.add_stack_event(stack_name: 'stack-1', resource_status: "UPDATE_COMPLETE") test_cf_driver.add_stack_event(stack_name: 'stack-1', resource_status: "UPDATE_COMPLETE") test_cf_driver.add_stack_event(stack_name: 'stack-2') expect(test_cf_driver.describe_stack_events(stack_name: 'stack-1').stack_events.map(&:stack_name)).to eq ['stack-1', 'stack-1'] end it 'sets and gets templates' do test_cf_driver.set_template('stack-1', 'blah') expect(test_cf_driver.get_template(stack_name: 'stack-1').template_body).to eq 'blah' end it 'sets and gets stack policies' do stack_policy_body = '{}' test_cf_driver.set_stack_policy(stack_name: 'stack-1', stack_policy_body: stack_policy_body) expect(test_cf_driver.get_stack_policy(stack_name: 'stack-1').stack_policy_body).to eq(stack_policy_body) end end context 'change sets' do it 'creates and describes change sets' do change_set_id = test_cf_driver.create_change_set( stack_name: 'stack-1', change_set_name: 'change-set-1', template_body: '{}', parameters: [{ paramater_key: 'param_1', parameter_value: 'value_1'}] ).id change_set = test_cf_driver.describe_change_set(change_set_name: change_set_id) expect(change_set.change_set_id).to eq change_set_id expect(change_set.change_set_name).to eq 'change-set-1' change_set = test_cf_driver.describe_change_set(change_set_name: 'change-set-1') expect(change_set.change_set_id).to eq change_set_id expect(change_set.change_set_name).to eq 'change-set-1' end it 'creates stacks using change sets and describes stacks' do change_set1 = test_cf_driver.create_change_set(change_set_name: 'change-set-1', stack_name: 'stack-1', change_set_type: 'CREATE') change_set2 = test_cf_driver.create_change_set(change_set_name: 'change-set-2', stack_name: 'stack-2', change_set_type: 'CREATE') test_cf_driver.execute_change_set(change_set_name: change_set1.id) test_cf_driver.execute_change_set(change_set_name: change_set2.id) expect(test_cf_driver.describe_stacks.stacks.map(&:stack_name)).to eq(['stack-1', 'stack-2']) end end it 'deletes change sets' do change_set_id = test_cf_driver.create_change_set(stack_name: '1', change_set_name: '2').id test_cf_driver.delete_change_set(change_set_name: change_set_id) expect { test_cf_driver.describe_change_set(change_set_name: change_set_id) }.to raise_error(KeyError) end end
mit
Dans-labs/dariah
client/node_modules/caniuse-lite/data/features/insert-adjacent.js
962
module.exports={A:{A:{"1":"L H G E A B","16":"jB"},B:{"1":"8 C D e K I N J"},C:{"1":"0 1 2 3 9 r s t u v w x y z JB IB CB DB EB O GB HB","2":"4 5 7 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q aB ZB"},D:{"1":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"4 6 F L H G E A B C D SB KB UB VB WB XB YB p bB"},F:{"1":"0 1 2 3 5 6 7 B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z cB dB eB fB p AB hB","16":"E"},G:{"1":"G D KB iB FB kB lB MB nB oB pB qB rB sB tB uB vB"},H:{"1":"wB"},I:{"1":"BB F O zB 0B FB 1B 2B","16":"xB yB"},J:{"1":"H A"},K:{"1":"6 A B C M p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"1":"A B"},O:{"1":"3B"},P:{"1":"F 4B 5B 6B 7B 8B"},Q:{"1":"9B"},R:{"1":"AC"},S:{"1":"BC"}},B:1,C:"Element.insertAdjacentElement() & Element.insertAdjacentText()"};
mit
dhwanisanmukhani/competitive-coding
codeforces/Competitions/ED38/first.cpp
602
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; #define icin(x) scanf("%d", &x) #define lcin(x) scanf("%lld", &x) typedef long long ll; int icheck(char c){ if(c == 'a' | c=='e'|c=='i'|c=='o'|c=='u'|c=='y') return 1; else return 0; } int main(){ string s; int len; icin(len); cin >> s; int flag=0; if(icheck(s[0])) flag=1; printf("%c", s[0]); for(int i=1;i<len;i++){ if(icheck(s[i])){ if(flag==1) continue; else{ flag=1; printf("%c", s[i]); } } else{ flag=0; printf("%c", s[i]); } } printf("\n"); }
mit
l496501043/edpx-zhixin
lib/AssembleTemplate.js
2417
/*************************************************************************** * * Copyright (C) 2014 Baidu.com, Inc. All Rights Reserved * ***************************************************************************/ /** * @file AssembleTemplate.js ~ 2014-04-09 14:34 * @author sekiyika (px.pengxing@gmail.com) * @description * 1. 根据VUI的渲染结果,拼装模板 * 2. 拆解模板,将占位符塞进去 */ var util = require('./util'); /** * @type {string} * 左侧渲染结果的占位符 */ var LEFT_CONTENT = '{%LEFT_CONTENT%}'; /** * @type {string} * 右侧渲染结果的占位符 */ var RIGHT_CONTENT = '{%RIGHT_CONTENT%}'; /** * @param {string} template * @param {Obejct} result * * result的格式为 * { * 'left': { * 'ecl_ec_weigou': '<div>...</div>', * 'ecl_game': '<div>...</div>' * }, * 'right': { * 'ecl_ec_weigou': '<div>...</div>', * 'ecl_game': '<div>...</div>' * } * } * * @return {string} 返回拼装之后的html字符串 */ exports.assmeble = function(template, result) { result = result || {}; var lhtml = ''; var rhtml = ''; var keys = []; for(var key in result.left) { keys.push(key); lhtml += result.left[key]; } for(key in result.right) { keys.push(key); rhtml += result.right[key]; } if(false !== result.removeSameTpl && keys.length > 0) { //移除同名标签块 keys.forEach(function(key) { template = util.removeTplBlock(template, key); }); } template = template.replace(LEFT_CONTENT, lhtml); template = template.replace(RIGHT_CONTENT, rhtml); return template; }; /** * 拆解模板,替换占位符 * @param {string} platform pc or pad * @param {string} html * * @return {string} 返回拆解后的模板字符串 */ exports.disassemble = function(platform, html) { // TODO (by who) 考虑搜索没有结果的情况 if(platform === 'ipad') { html = html.replace(/(<ul\s*class=\"bds-result-lists\"[^>]*>)/, '$1' + LEFT_CONTENT); html = html.replace(/(<div\s*id=\"con-ar\"[^>]*>)/, '$1' + RIGHT_CONTENT); } else { html = html.replace(/(<div\s*id=\"content_left\"[^>]*>)/, '$1' + LEFT_CONTENT); html = html.replace(/(<div\s*id=\"content_right\"[^>]*>)/, '$1' + RIGHT_CONTENT); } return html; };
mit
exercism/xjavascript
exercises/meetup/meetup.spec.js
1931
var meetupDay = require('./meetup'); describe('meetupDay()', function () { it('monteenth of may 2013', function () { expect(meetupDay(2013, 4, 'Monday', 'teenth')).toEqual(new Date(2013, 4, 13)); }); xit('saturteenth of february 2013', function () { expect(meetupDay(2013, 1, 'Saturday', 'teenth')).toEqual(new Date(2013, 1, 16)); }); xit('first tuesday of may 2013', function () { expect(meetupDay(2013, 4, 'Tuesday', '1st')).toEqual(new Date(2013, 4, 7)); }); xit('second monday of april 2013', function () { expect(meetupDay(2013, 3, 'Monday', '2nd')).toEqual(new Date(2013, 3, 8)); }); xit('third thursday of september 2013', function () { expect(meetupDay(2013, 8, 'Thursday', '3rd')).toEqual(new Date(2013, 8, 19)); }); xit('fourth sunday of march 2013', function () { expect(meetupDay(2013, 2, 'Sunday', '4th')).toEqual(new Date(2013, 2, 24)); }); xit('last thursday of october 2013', function () { expect(meetupDay(2013, 9, 'Thursday', 'last')).toEqual(new Date(2013, 9, 31)); }); xit('last wednesday of february 2012', function () { expect(meetupDay(2012, 1, 'Wednesday', 'last')).toEqual(new Date(2012, 1, 29)); }); xit('last wednesday of december 2014', function () { expect(meetupDay(2014, 11, 'Wednesday', 'last')).toEqual(new Date(2014, 11, 31)); }); xit('last sunday of only four week february 2015', function () { expect(meetupDay(2015, 1, 'Sunday', 'last')).toEqual(new Date(2015, 1, 22)); }); xit('first friday of december 2012', function () { expect(meetupDay(2012, 11, 'Friday', '1st')).toEqual(new Date(2012, 11, 7)); }); xit('fifth monday of march 2015', function () { expect(meetupDay(2015, 2, 'Monday', '5th')).toEqual(new Date(2015, 2, 30)); }); xit('nonexistent fifth monday of february 2015', function () { expect(function () { meetupDay(2015, 1, 'Monday', '5th'); }).toThrow(); }); });
mit
dmcclory/moss
lib/moss/version.rb
35
class Moss VERSION = '0.0.2' end
mit
chinxianjun/autorepair
app/helpers/part_buyings_helper.rb
29
module PartBuyingsHelper end
mit
potproject/ikuradon
app/actions/actiontypes/currentuser.js
228
export const UPDATE_CURRENT_USER = "UPDATE_CURRENT_USER"; export const DELETED_CURRENT_USER = "DELETED_CURRENT_USER"; export const NOTIFICATION_PUSH = "NOTIFICATION_PUSH"; export const NOTIFICATION_CLEAR = "NOTIFICATION_CLEAR";
mit
shopzcoin/shopzcoin
src/qt/locale/bitcoin_fa_IR.ts
114540
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Shopzcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Shopzcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>برای ویرایش حساب و یا برچسب دوبار کلیک نمایید</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>گشایش حسابی جدید</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>کپی کردن حساب انتخاب شده به حافظه سیستم - کلیپ بورد</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your Shopzcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>و کپی آدرس</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>و حذف</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>کپی و برچسب</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>و ویرایش</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>سی.اس.وی. (فایل جداگانه دستوری)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>حساب</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>رمز/پَس فرِیز را وارد کنید</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>رمز/پَس فرِیز جدید را وارد کنید</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>رمز/پَس فرِیز را دوباره وارد کنید</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>wallet را رمزگذاری کنید</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>باز کردن قفل wallet </translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>کشف رمز wallet</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>رمزگذاری wallet را تایید کنید</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>تایید رمزگذاری</translation> </message> <message> <location line="-58"/> <source>Shopzcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>رمزگذاری تایید نشد</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>قفل wallet باز نشد</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>کشف رمز wallet انجام نشد</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+280"/> <source>Sign &amp;message...</source> <translation>امضا و پیام</translation> </message> <message> <location line="+242"/> <source>Synchronizing with network...</source> <translation>به روز رسانی با شبکه...</translation> </message> <message> <location line="-308"/> <source>&amp;Overview</source> <translation>و بازبینی</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>نمای کلی از wallet را نشان بده</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>و تراکنش</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>تاریخچه تراکنش را باز کن</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>خروج</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>از &quot;درخواست نامه&quot;/ application خارج شو</translation> </message> <message> <location line="+4"/> <source>Show information about Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>درباره و QT</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>نمایش اطلاعات درباره QT</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>و انتخابها</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>و رمزگذاری wallet</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>و گرفتن نسخه پیشتیبان از wallet</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message numerus="yes"> <location line="+250"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-247"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Send coins to a Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Modify configuration options for Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-200"/> <source>Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+178"/> <source>&amp;About Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;نمایش/ عدم نمایش و</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>&amp;File</source> <translation>و فایل</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>و تنظیمات</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>و راهنما</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>نوار ابزار</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>Shopzcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to Shopzcoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-284"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+288"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>روزآمد</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>در حال روزآمد سازی..</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>ارسال تراکنش</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>تراکنش دریافتی</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎ </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Shopzcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. Shopzcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>هشدار شبکه</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>میزان وجه:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>حساب</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>تایید شده</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>آدرس را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>برچسب را کپی کنید</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>ویرایش حساب</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>و برچسب</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>حساب&amp;</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>حساب دریافت کننده جدید </translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>حساب ارسال کننده جدید</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>ویرایش حساب دریافت کننده</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>ویرایش حساب ارسال کننده</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>حساب وارد شده «1%» از پیش در دفترچه حساب ها موجود است.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Shopzcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>عدم توانیی برای قفل گشایی wallet</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>عدم توانیی در ایجاد کلید جدید</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>Shopzcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>انتخاب/آپشن</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Shopzcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Shopzcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Shopzcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Shopzcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Shopzcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Shopzcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>و نمایش آدرسها در فهرست تراکنش</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>و تایید</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>و رد</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>پیش فرض</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Shopzcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>فرم</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Shopzcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>تراکنشهای اخیر</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>خارج از روزآمد سازی</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>نام کنسول RPC</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation>ویرایش کنسول RPC</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>شبکه</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>تعداد اتصال</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>زنجیره مجموعه تراکنش ها</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>تعداد زنجیره های حاضر</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Shopzcoin-Qt help message to get a list with possible Shopzcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Shopzcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Shopzcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Shopzcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the Shopzcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>سکه های ارسالی</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>میزان وجه:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>ارسال همزمان به گیرنده های متعدد</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>مانده حساب:</translation> </message> <message> <location line="+16"/> <source>123.456 BC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>تایید عملیات ارسال </translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>و ارسال</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>تایید ارسال بیت کوین ها</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>میزان پرداخت باید بیشتر از 0 باشد</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>مقدار مورد نظر از مانده حساب بیشتر است.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>و میزان وجه</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>پرداخت و به چه کسی</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>و برچسب</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>و امضای پیام </translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Shopzcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Shopzcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1 / تایید نشده</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 تایید</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>برچسب</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation>پیام</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 20 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>، هنوز با موفقیت ارسال نگردیده است</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>ناشناس</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>جزئیات تراکنش</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>این بخش جزئیات تراکنش را نشان می دهد</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>گونه</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>میزان وجه</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>تایید شده (%1 تاییدها)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>تولید شده اما قبول نشده است</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>قبول با </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>دریافت شده از</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>وجه برای شما </translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>خالی</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>زمان و تاریخی که تراکنش دریافت شده است</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>نوع تراکنش</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>آدرس مقصد در تراکنش</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>میزان وجه کم شده یا اضافه شده به حساب</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>همه</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>امروز</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>این هفته</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>این ماه</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>ماه گذشته</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>این سال</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>حدود..</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>دریافت با</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>به شما</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>دیگر</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>آدرس یا برچسب را برای جستجو وارد کنید</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>حداقل میزان وجه</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>آدرس را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>برچسب را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>برچسب را ویرایش کنید</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>تایید شده</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>شناسه کاربری</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>دامنه:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>به</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>Shopzcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>میزان استفاده:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or shopzcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>فهرست دستورها</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>درخواست کمک برای یک دستور</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>انتخابها:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: shopzcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: shopzcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>دایرکتوری داده را مشخص کن</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 7867 or testnet: 17867)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>نگهداری &lt;N&gt; ارتباطات برای قرینه سازی (پیش فرض:125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 7868 or testnet: 17868)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>command line و JSON-RPC commands را قبول کنید</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>از تستِ شبکه استفاده نمایید</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Shopzcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>رمز برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=shopzcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Shopzcoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>دستورات را به گره اجرا شده در&lt;ip&gt; ارسال کنید (پیش فرض:127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>wallet را به جدیدترین نسخه روزآمد کنید</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>حجم key pool را به اندازه &lt;n&gt; تنظیم کنید (پیش فرض:100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>فایل certificate سرور (پیش فرض server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>این پیام راهنما</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. Shopzcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>لود شدن آدرسها..</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Shopzcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Shopzcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>خطا در هنگام لود شدن wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>میزان اشتباه است for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>میزان اشتباه است</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>وجوه ناکافی</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>لود شدن نمایه بلاکها..</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. Shopzcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>wallet در حال لود شدن است...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>آدرس پیش فرض قابل ذخیره نیست</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>اسکنِ دوباره...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>اتمام لود شدن</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>برای استفاده از %s از اختیارات</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>خطا</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>شما باید یک رمز rpcpassword=&lt;password&gt; را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل &quot;فقط متنی&quot; ایجاد کنید. </translation> </message> </context> </TS>
mit
pntripathi9417/pntripathi9417.github.io
core/server/apps/subscribers/lib/helpers/index.js
662
// Dirty requires! const labs = require('../../../../services/labs'); module.exports = function registerHelpers(ghost) { ghost.helpers.register('input_email', require('./input_email')); ghost.helpers.register('subscribe_form', function labsEnabledHelper() { let self = this, args = arguments; return labs.enabledHelper({ flagKey: 'subscribers', flagName: 'Subscribers', helperName: 'subscribe_form', helpUrl: 'https://help.ghost.org/hc/en-us/articles/224089787-Subscribers-Beta' }, () => { return require('./subscribe_form').apply(self, args); }); }); };
mit
NimbusAPI/Nimbus
src/Nimbus.Tests.Integration/Tests/AuditingInterceptorTests/WhenSendingOneOfEachKindOfMessage.cs
5202
using System; using System.Linq; using System.Threading.Tasks; using Nimbus.Configuration; using Nimbus.Interceptors; using Nimbus.MessageContracts.ControlMessages; using Nimbus.Tests.Common.Extensions; using Nimbus.Tests.Integration.Tests.AuditingInterceptorTests.MessageTypes; using Nimbus.Tests.Integration.TestScenarioGeneration.ScenarioComposition; using Nimbus.Tests.Integration.TestScenarioGeneration.TestCaseSources; using NUnit.Framework; using Shouldly; namespace Nimbus.Tests.Integration.Tests.AuditingInterceptorTests { public class WhenSendingOneOfEachKindOfMessage : TestForBus { private SomeResponse _response; private SomeMulticastResponse[] _multicastResponse; protected override void Reconfigure() { Instance.Configuration .WithGlobalOutboundInterceptorTypes(typeof(OutboundAuditingInterceptor)) .WithMaxDeliveryAttempts(1) .WithHeartbeatInterval(TimeSpan.MaxValue) ; } protected override async Task When() { await Task.WhenAll( Bus.Send(new SomeCommand(42)), Bus.SendAt(new SomeCommandSentViaDelay(), DateTimeOffset.UtcNow), Bus.Publish(new SomeEvent()) ); _response = await Bus.Request(new SomeRequest()); // take just one so that we don't wait until the test times out. _multicastResponse = (await Bus.MulticastRequest(new SomeMulticastRequest(), TimeSpan.FromSeconds(TimeoutSeconds))) .Take(1) .ToArray(); } [Test] [TestCaseSource(typeof(AllBusConfigurations<WhenSendingOneOfEachKindOfMessage>))] public async Task Run(string testName, IConfigurationScenario<BusBuilderConfiguration> scenario) { await Given(scenario); await When(); await Then(); } [Then] public async Task TheRequestShouldHaveReceivedAResponse() { _response.ShouldBeOfType<SomeResponse>(); } [Then] public async Task TheMulticastRequestShouldHaveReceivedAResponse() { _multicastResponse.Length.ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeCommand() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeCommand>().Count() == 1); AllAuditedMessages().OfType<SomeCommand>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeCommandSentViaDelay() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeCommandSentViaDelay>().Count() == 1); AllAuditedMessages().OfType<SomeCommandSentViaDelay>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeRequest() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeRequest>().Count() == 1); AllAuditedMessages().OfType<SomeRequest>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeResponse() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeResponse>().Count() == 1); AllAuditedMessages().OfType<SomeResponse>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeMulticastRequest() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeMulticastRequest>().Count() == 1); AllAuditedMessages().OfType<SomeMulticastRequest>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeMulticastResponse() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeMulticastResponse>().Count() == 1); AllAuditedMessages().OfType<SomeMulticastResponse>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeAnAuditRecordForSomeEvent() { await Timeout.WaitUntil(() => AllAuditedMessages().OfType<SomeEvent>().Count() == 1); AllAuditedMessages().OfType<SomeEvent>().Count().ShouldBe(1); } [Then] public async Task ThereShouldBeATotalOfSevenAuditRecords() { await Timeout.WaitUntil(() => MethodCallCounter.AllReceivedMessages.Count() >= 7); MethodCallCounter.AllReceivedMessages.OfType<AuditEvent>().Count().ShouldBe(7); } [Then] public async Task ThereShouldBeATotalOfSevenRecordedHandlerCalls() { await Timeout.WaitUntil(() => MethodCallCounter.AllReceivedMessages.Count() >= 7); MethodCallCounter.AllReceivedCalls.Count().ShouldBe(7); } private object[] AllAuditedMessages() { return MethodCallCounter.AllReceivedMessages .OfType<AuditEvent>() .Select(ae => ae.MessageBody) .ToArray(); } } }
mit
cuckata23/wurfl-data
data/telpad_dual_s_ver1.php
446
<?php return array ( 'id' => 'telpad_dual_s_ver1', 'fallback' => 'generic_android_ver4_1', 'capabilities' => array ( 'is_tablet' => 'true', 'model_name' => 'Dual S', 'brand_name' => 'Telpad', 'can_assign_phone_number' => 'false', 'release_date' => '2012_december', 'physical_screen_height' => '90', 'physical_screen_width' => '154', 'resolution_width' => '1024', 'resolution_height' => '600', ), );
mit
laurentiustamate94/smart-wash
SmartWash.Service.Models/IPowerManagement.cs
287
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SmartWash.Service.Models { public interface IPowerManagement { Task<bool> On(string socket); Task<bool> Off(string socket); } }
mit
walterhiggins/pixenate
webroot/javascript/pxn8_xhairs.js
4296
/* ============================================================================ * * (c) Copyright SXOOP Technologies Ltd. 2005-2009 * All rights reserved. * * This file contains code for displaying cross-hairs on the selection * */ var PXN8 = PXN8 || {}; PXN8.crosshairs = {}; /************************************************************************* SECTION: Cross-Hairs functions ============================== The following functions are related to setting and getting the cross-hairs image (by default a white cross which is displayed in the center of the selection area), and also enabling and disabling the cross-hairs. ***/ PXN8.crosshairs.enabled = true; PXN8.crosshairs.image = null; /************************************************************************** PXN8.crosshairs.setEnabled() ============================ Enables or disables the display of the cross-hairs image at the center of the selected area. Parameters ---------- * enabled : A boolean (true or false) indicating whether or not cross-hairs should be displayed. Related ------- PXN8.crosshairs.isEnabled() ***/ PXN8.crosshairs.setEnabled = function(enabled){ PXN8.crosshairs.enabled = enabled; PXN8.crosshairs.refresh(); }; /************************************************************************** PXN8.crosshairs.isEnabled() =========================== Returns a boolean value indicating whether or not the crosshairs are displayed in the selected area. Returns ------- *true* if the crosshairs are displayed in selections. *false* otherwise. Related ------- PXN8.crosshairs.setEnabled() ***/ PXN8.crosshairs.isEnabled = function(){ return PXN8.crosshairs.enabled; }; /************************************************************************** PXN8.crosshairs.getImage() ========================== Get the Image URL currently used for displaying the cross-hairs at the center of the selected area. Returns ------- A URL to the image used as the cross-hairs image. The URL returned will be an absolute URL including the domain name and full URL path. Related ------- PXN8.crosshairs.setImage() ***/ PXN8.crosshairs.getImage = function() { if (PXN8.crosshairs.image == null){ PXN8.crosshairs.image = PXN8.server + PXN8.root + "/images/pxn8_xhairs_white.gif"; } return PXN8.crosshairs.image; }; /*************************************************************************** PXN8.crosshairs.setImage() ========================== You can change the cross-hairs image to suit your own tastes. Parameters ---------- * imageURL : A URL to the image which should be displayed in the center of the selection area. Related ------- PXN8.crosshairs.getImage() ***/ PXN8.crosshairs.setImage = function(imageURL) { PXN8.crosshairs.image = imageURL; PXN8.crosshairs.refresh(); }; /** * Called when the selection changes */ PXN8.crosshairs.refresh = function() { var _ = PXN8.dom; var xhairs = _.id("pxn8_crosshairs"); if (!PXN8.crosshairs.isEnabled()){ if (xhairs){ xhairs.style.display = "none"; } return; } var sel = PXN8.getSelection(); var _ = PXN8.dom; var selBounds = _.eb("pxn8_select_rect"); var canvas = _.id("pxn8_canvas"); if (!xhairs){ xhairs = _.ac(canvas,_.ce("img",{id: "pxn8_crosshairs", src: PXN8.crosshairs.getImage()})); } if (selBounds.width <= 0){ xhairs.style.display = "none"; return; } // // center the crosshairs on the selection area // var xhcx = xhairs.width/2; var xhcy = xhairs.height/2; xhairs.style.display = "inline"; xhairs.style.position = "absolute"; // // wph 20070613 : must use Math.floor or the xhairs will not be perfectly centered // (off by up to 2 pixels to the right and bottom) // xhairs.style.left = Math.floor((selBounds.x + (selBounds.width / 2)) - xhcx) + "px"; xhairs.style.top = Math.floor((selBounds.y + (selBounds.height / 2)) - xhcy) + "px"; }; PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,PXN8.crosshairs.refresh); PXN8.listener.add(PXN8.ON_ZOOM_CHANGE,PXN8.crosshairs.refresh);
mit
duhone/EteriumInput
REInputNative/REInputDeviceNative.cpp
4096
#include "stdafx.h" #include "REInputDeviceNative.h" #include "Util.h" using namespace std; using namespace RE::InputNative; InputDevice::InputDevice(DeviceInfo& _deviceInfo, CComPtr<IDirectInputDevice8> _device, HWND _hwnd) : m_DeviceInfo(_deviceInfo), m_Device(_device), m_hwnd(_hwnd) { Acquire(); Update(); } void InputDevice::Acquire() { auto hr = m_Device->SetDataFormat(&c_dfDIJoystick2); if(FAILED(hr)) return; hr = m_Device->SetCooperativeLevel(m_hwnd, DISCL_EXCLUSIVE | DISCL_BACKGROUND); if(FAILED(hr)) return; if(m_DeviceInfo.XAxis) XAxisRange = GetJoystickRange(DIJOFS_X); if(m_DeviceInfo.YAxis) YAxisRange = GetJoystickRange(DIJOFS_Y); if(m_DeviceInfo.ZAxis) ZAxisRange = GetJoystickRange(DIJOFS_Z); if(m_DeviceInfo.XRotation) XRotRange = GetJoystickRange(DIJOFS_RX); if(m_DeviceInfo.YRotation) YRotRange = GetJoystickRange(DIJOFS_RY); if(m_DeviceInfo.ZRotation) ZRotRange = GetJoystickRange(DIJOFS_RZ); if(m_DeviceInfo.NumSliders >= 1) SliderRange[0] = GetJoystickRange(DIJOFS_SLIDER(0)); if(m_DeviceInfo.NumSliders >= 2) SliderRange[1] = GetJoystickRange(DIJOFS_SLIDER(1)); m_Device->Acquire(); } void InputDevice::Update() { m_Device->Poll(); DIJOYSTATE2 data; auto hr = m_Device->GetDeviceState(sizeof(data), &data); if(FAILED(hr)) //hand waving. if we fail for any reason then just try to recreate/reaquire everything. { m_DeviceState = DeviceState(); //clear everything out so we dont get left turning. Acquire(); return; } if(m_DeviceInfo.XAxis) m_DeviceState.XAxis = CalcAxisValue(data.lX, XAxisRange); if(m_DeviceInfo.YAxis) m_DeviceState.YAxis = CalcAxisValue(data.lY, YAxisRange) * -1.0f; if(m_DeviceInfo.ZAxis) m_DeviceState.ZAxis = CalcAxisValue(data.lZ, ZAxisRange); if(m_DeviceInfo.XRotation) m_DeviceState.XRotation = CalcAxisValue(data.lRx, XRotRange); if(m_DeviceInfo.YRotation) m_DeviceState.YRotation = CalcAxisValue(data.lRy, YRotRange); if(m_DeviceInfo.ZRotation) m_DeviceState.ZRotation = CalcAxisValue(data.lRz, ZRotRange); if(m_DeviceInfo.NumSliders >= 1) m_DeviceState.Sliders[0] = CalcSliderValue(data.rglSlider[0], SliderRange[0]); if(m_DeviceInfo.NumSliders >= 2) m_DeviceState.Sliders[1] = CalcSliderValue(data.rglSlider[1], SliderRange[1]); if(m_DeviceInfo.NumPOVs >= 1) m_DeviceState.POVs[0] = CalcPOVValue(data.rgdwPOV[0]); if(m_DeviceInfo.NumPOVs >= 2) m_DeviceState.POVs[1] = CalcPOVValue(data.rgdwPOV[1]); if(m_DeviceInfo.NumPOVs >= 3) m_DeviceState.POVs[2] = CalcPOVValue(data.rgdwPOV[2]); if(m_DeviceInfo.NumPOVs >= 4) m_DeviceState.POVs[3] = CalcPOVValue(data.rgdwPOV[3]); for(int i = 0;i < m_DeviceInfo.NumButtons; ++i) { m_DeviceState.Buttons[i] = !(data.rgbButtons[i] == 0); } } pair<int, int> InputDevice::GetJoystickRange(DWORD _prop) { DIPROPRANGE range; range.diph.dwSize = sizeof(range); range.diph.dwHeaderSize = sizeof(DIPROPHEADER); range.diph.dwHow = DIPH_BYOFFSET; range.diph.dwObj = _prop; auto hr = m_Device->GetProperty(DIPROP_RANGE, &range.diph); if(FAILED(hr)) { return make_pair(0, 0); //todo not a good way to deal with this failure, but probably extremely rare for only this to fail. } return make_pair(range.lMin, range.lMax); } //axis is always -1 to 1 float InputDevice::CalcAxisValue(int _value, const std::pair<int,int>& _range) { return 2.0f*(static_cast<float>(_value-_range.first)/(_range.second-_range.first))-1.0f; } //slider is always 0 to 1 float InputDevice::CalcSliderValue(int _value, const std::pair<int,int>& _range) { return static_cast<float>(_value-_range.first)/(_range.second-_range.first); } POV_DIRECTION InputDevice::CalcPOVValue(int _value) { if((LOWORD(_value) == 0xFFFF)) return POV_DIRECTION::Null; if(_value > 290*DI_DEGREES || _value < 30*DI_DEGREES) return POV_DIRECTION::Up; if(_value > 60*DI_DEGREES && _value < 120*DI_DEGREES) return POV_DIRECTION::Right; if(_value > 150*DI_DEGREES && _value < 210*DI_DEGREES) return POV_DIRECTION::Down; if(_value > 240*DI_DEGREES && _value < 300*DI_DEGREES) return POV_DIRECTION::Left; return POV_DIRECTION::Null; }
mit
Doomedfajita/UPCI-CoSBBI
src/loaders/loaders.base.js
6506
/** Imports **/ import HelpersProgressBar from '../helpers/helpers.progressbar'; import EventEmitter from 'events'; /** * * It is typically used to load a DICOM image. Use loading manager for * advanced usage, such as multiple files handling. * * Demo: {@link https://fnndsc.github.io/vjs#loader_dicom} * * @module loaders/base * @extends EventEmitter * @example * var files = ['/data/dcm/fruit']; * * // Instantiate a dicom loader * var lDicomoader = new dicom(); * * // load a resource * loader.load( * // resource URL * files[0], * // Function when resource is loaded * function(object) { * //scene.add( object ); * window.console.log(object); * } * ); */ export default class LoadersBase extends EventEmitter { /** * Create a Loader. * @param {dom} container - The dom container of loader. * @param {object} ProgressBar - The progressbar of loader. */ constructor(container = null, ProgressBar = HelpersProgressBar) { super(); this._loaded = -1; this._totalLoaded = -1; this._parsed = -1; this._totalParsed = -1; this._data = []; this._container = container; this._progressBar = null; if (this._container && ProgressBar) { this._progressBar = new ProgressBar(this._container); } } /** * free the reference. */ free() { this._container = null; // this._helpersProgressBar = null; if (this._progressBar) { this._progressBar.free(); this._progressBar = null; } } /** * load the resource by url. * @param {string} url - resource url. * @return {promise} promise. */ fetch(url) { return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open('GET', url); request.crossOrigin = true; request.responseType = 'arraybuffer'; request.onloadstart = (event) => { // emit 'fetch-start' event this.emit('fetch-start', { file: url, time: new Date(), }); }; request.onload = (event) => { if (request.status === 200) { this._loaded = event.loaded; this._totalLoaded = event.total; // will be removed after eventer set up if (this._progressBar) { this._progressBar.update(this._loaded, this._totalLoaded, 'load'); } let buffer = request.response; let response = { url, buffer, }; // emit 'fetch-success' event this.emit('fetch-success', { file: url, time: new Date(), totalLoaded: event.total, }); resolve(response); } else { reject(request.statusText); } }; request.onerror = () => { // emit 'fetch-error' event this.emit('fetch-error', { file: url, time: new Date(), }); reject(request.statusText); }; request.onabort = (event) => { // emit 'fetch-start' event this.emit('fetch-abort', { file: url, time: new Date(), }); reject(request.statusText); }; request.ontimeout = () => { // emit 'fetch-timeout' event this.emit('fetch-timeout', { file: url, time: new Date(), }); reject(request.statusText); }; request.onprogress = (event) => { this._loaded = event.loaded; this._totalLoaded = event.total; // emit 'fetch-progress' event this.emit('fetch-progress', { file: url, total: event.total, loaded: event.loaded, time: new Date(), }); // will be removed after eventer set up if (this._progressBar) { this._progressBar.update(this._loaded, this._totalLoaded, 'load'); } }; request.onloadend = (event) => { // emit 'fetch-end' event this.emit('fetch-end', { file: url, time: new Date(), }); // just use onload when success and onerror when failure, etc onabort // reject(request.statusText); }; request.send(); }); } /** * parse the data loaded * SHOULD BE implementd by detail loader. * @param {object} response - loaded data. * @return {promise} promise. */ parse(response) { return new Promise((resolve, reject) => { resolve(response); }); } /** * default load sequence group promise. * @param {array} url - resource url. * @return {promise} promise. */ loadSequenceGroup(url) { const fetchSequence = []; url.forEach((file) => { fetchSequence.push( this.fetch(file) ); }); return Promise.all(fetchSequence) .then((rawdata) => { return this.parse(rawdata); }) .then((data) => { this._data.push(data); return data; }) .catch(function(error) { window.console.log('oops... something went wrong...'); window.console.log(error); }); } /** * default load sequence promise. * @param {string} url - resource url. * @return {promise} promise. */ loadSequence(url) { return this.fetch(url) .then((rawdata) => { return this.parse(rawdata); }) .then((data) => { this._data.push(data); return data; }) .catch(function(error) { window.console.log('oops... something went wrong...'); window.console.log(error); }); } /** * load the data by url(urls) * @param {string|array} url - resource url. * @return {promise} promise */ load(url) { // if we load a single file, convert it to an array if (!Array.isArray(url)) { url = [url]; } // emit 'load-start' event this.emit('load-start', { files: url, time: new Date(), }); const loadSequences = []; url.forEach((file) => { if (!Array.isArray(file)) { loadSequences.push( this.loadSequence(file) ); } else { loadSequences.push( this.loadSequenceGroup(file) ); } }); return Promise.all(loadSequences); } /** * Set data * @param {array} data */ set data(data) { this._data = data; } /** * Get data * @return {array} data loaded */ get data() { return this._data; } }
mit
mathiasbynens/unicode-data
4.1.0/blocks/Supplemental-Punctuation-symbols.js
1487
// All symbols in the Supplemental Punctuation block as per Unicode v4.1.0: [ '\u2E00', '\u2E01', '\u2E02', '\u2E03', '\u2E04', '\u2E05', '\u2E06', '\u2E07', '\u2E08', '\u2E09', '\u2E0A', '\u2E0B', '\u2E0C', '\u2E0D', '\u2E0E', '\u2E0F', '\u2E10', '\u2E11', '\u2E12', '\u2E13', '\u2E14', '\u2E15', '\u2E16', '\u2E17', '\u2E18', '\u2E19', '\u2E1A', '\u2E1B', '\u2E1C', '\u2E1D', '\u2E1E', '\u2E1F', '\u2E20', '\u2E21', '\u2E22', '\u2E23', '\u2E24', '\u2E25', '\u2E26', '\u2E27', '\u2E28', '\u2E29', '\u2E2A', '\u2E2B', '\u2E2C', '\u2E2D', '\u2E2E', '\u2E2F', '\u2E30', '\u2E31', '\u2E32', '\u2E33', '\u2E34', '\u2E35', '\u2E36', '\u2E37', '\u2E38', '\u2E39', '\u2E3A', '\u2E3B', '\u2E3C', '\u2E3D', '\u2E3E', '\u2E3F', '\u2E40', '\u2E41', '\u2E42', '\u2E43', '\u2E44', '\u2E45', '\u2E46', '\u2E47', '\u2E48', '\u2E49', '\u2E4A', '\u2E4B', '\u2E4C', '\u2E4D', '\u2E4E', '\u2E4F', '\u2E50', '\u2E51', '\u2E52', '\u2E53', '\u2E54', '\u2E55', '\u2E56', '\u2E57', '\u2E58', '\u2E59', '\u2E5A', '\u2E5B', '\u2E5C', '\u2E5D', '\u2E5E', '\u2E5F', '\u2E60', '\u2E61', '\u2E62', '\u2E63', '\u2E64', '\u2E65', '\u2E66', '\u2E67', '\u2E68', '\u2E69', '\u2E6A', '\u2E6B', '\u2E6C', '\u2E6D', '\u2E6E', '\u2E6F', '\u2E70', '\u2E71', '\u2E72', '\u2E73', '\u2E74', '\u2E75', '\u2E76', '\u2E77', '\u2E78', '\u2E79', '\u2E7A', '\u2E7B', '\u2E7C', '\u2E7D', '\u2E7E', '\u2E7F' ];
mit
kiergarlen/ppot
database/migrations/2017_03_09_212216_create_regiones_table.php
552
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRegionesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('regiones', function (Blueprint $table) { $table->increments('id'); $table->string('nombre'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('regiones'); } }
mit
johnazariah/orleans-architecture-patterns-code
Demo.SiloHost/SmartCacheDemo.cs
1861
using System; using System.Linq; using System.Threading.Tasks; using Demo.SmartCache.GrainInterfaces; using Demo.SmartCache.GrainInterfaces.State; using Orleans; using Patterns.DevBreadboard; namespace Patterns.SmartCache.Host { //internal class StateMachineDemo //{ // public static void Run() // { // InitializeStateMachine() // .ContinueWith(_ => ReadItems()) // .ContinueWith(_ => DevelopmentSiloHost.WaitForInteraction()) // .Wait(); // } //} internal class SmartCacheDemo { public static async Task CreateCatalogItem(Guid id, int index) { var grainId = id; var grainState = new CatalogItem { DisplayName = $"Item {index}", SKU = id.ToString(), ShortDescription = $"This is the {index}th item" }; var grain = GrainClient.GrainFactory.GetGrain<ICatalogItemGrain>(grainId); await grain.SetItem(grainState); } public static Task InitializeItems() { var createTasks = Constants.ItemIds.Select(CreateCatalogItem); return Task.WhenAll(createTasks.ToArray()); } public static async Task ReadItems() { foreach (var itemId in Constants.ItemIds) { var grain = GrainClient.GrainFactory.GetGrain<ICatalogItemGrain>(itemId); var state = await grain.GetItem(); Console.WriteLine(state); } } public static void Run() { InitializeItems() .ContinueWith(_ => ReadItems()) .ContinueWith(_ => DevelopmentSiloHost.WaitForInteraction()) .Wait(); } } }
mit
olzaragoza/vscode-icons
src/build/templates/checkAssociations.js
646
var checkAssociations = function checkAssociations(config, filename, additionalClass) { var ascs; var asc; var rx; var i = 0; var len; if (!config || !config.vsicons || !config.vsicons.useFileAssociations || !config.vsicons.associations) return null; ascs = config.vsicons.associations; for (len = ascs.length; i < len; i++) { asc = ascs[i]; rx = new RegExp(asc[0], 'gi'); if (rx.test(filename)) { var s = asc[1].replace(/\./g, '_'); if ((/^\d/).test(s)) s = 'n' + s; return s + (additionalClass || ''); } } return null; }; module.exports = checkAssociations.toString();
mit
pjcarly/ember-field-components
addon/components/input-field-select/component.ts
4956
import InputField, { InputFieldArguments } from "../input-field/component"; import SelectOption from "@getflights/ember-field-components/interfaces/SelectOption"; import { isArray } from "@ember/array"; import { action } from "@ember/object"; import Model from "@ember-data/model"; export interface InputFieldSelectArguments extends InputFieldArguments<string | string[]> {} export default class InputFieldSelectComponent extends InputField< InputFieldSelectArguments, string | string[] > { selectOptions?: SelectOption[]; protected dependencyOf = new Map<String, Map<string, string[]>>(); constructor(owner: any, args: InputFieldSelectArguments) { super(owner, args); this.fillDependencies(); } /** * Here we build a map of other select fields who are dependent on the value of this field * If the value of this field changes, and it is not allowed in the dependent fields, * we must clear the value of the dependent fiels as well */ protected fillDependencies(): void { const modelClass = <Model>this.modelClass; // @ts-ignore modelClass.eachAttribute((field: string, meta: any) => { if ( meta.type === "select" && meta.options?.dependentField && meta.options?.selectOptionDependencies ) { if (meta.options.dependentField === this.args.field) { this.dependencyOf.set(field, meta.options.selectOptionDependencies); } } }); } get dependentValue() { return ( this.args.model // @ts-ignore .get(this.dependentField) ); } get selectOptionsComputed(): SelectOption[] { const fieldOptions = this.fieldOptions; const selectOptions: SelectOption[] = []; if (this.selectOptions) { return this.selectOptions; } else if ( fieldOptions && fieldOptions.hasOwnProperty("selectOptions") && isArray(fieldOptions.selectOptions) ) { return this.getAllowedSelectOptions(fieldOptions.selectOptions); } return selectOptions; } /** * Returns the allowed selectOptions based if a dependency is present or not * @param selectOptions The selectOptions you want to filter */ getAllowedSelectOptions(selectOptions: SelectOption[]): SelectOption[] { if (!this.modelName) { return []; } const returnValues: SelectOption[] = []; let allowedValues: string[] | undefined = undefined; if (this.dependentField) { const dependencies = this.selectOptionDependencies; if ( dependencies && this.dependentValue && dependencies // @ts-ignore .has(this.dependentValue) ) { allowedValues = dependencies // @ts-ignore .get(this.dependentValue); } } for (const fieldSelectOption of selectOptions) { if (allowedValues && !allowedValues.includes(fieldSelectOption.value)) { continue; } const selectOption: SelectOption = { value: fieldSelectOption.value, }; selectOption.label = this.fieldInformation.getTranslatedSelectOptionLabel( this.modelName, this.args.field, fieldSelectOption.value ); returnValues.push(selectOption); } return returnValues; } get selectOptionDependencies(): Map<string, string[]> | undefined { const fieldOptions = this.fieldOptions; if ( !fieldOptions || !fieldOptions.hasOwnProperty("selectOptionDependencies") ) { return undefined; } return fieldOptions.selectOptionDependencies; } get dependentField(): string | undefined { const fieldOptions = this.fieldOptions; if (!fieldOptions || !fieldOptions.hasOwnProperty("dependentField")) { return undefined; } return fieldOptions.dependentField; } get noneLabel(): string { if (!this.modelName) { return "None"; } return this.fieldInformation.getTranslatedSelectNoneLabel( this.modelName, this.args.field ); } @action setSelectValue(value?: any) { // First we set the value on the field itself this.setNewValue(value); // Next we check for possible not allowed dependencies which we need to clear // in case the depenent value is no longer allowed this.dependencyOf.forEach((dependencies, field) => { if (dependencies.has(value)) { const dependentValue: any = this.args.model // @ts-ignore .get(field); if (dependencies.get(value)?.indexOf(dependentValue) !== -1) { // The current value exists in the allowed mapping, nothing needs to happen } else { this.args.model // @ts-ignore .set(field, undefined); } } else { // The value does not exists in the allowed mapping, we clear the dependency this.args.model // @ts-ignore .set(field, undefined); } }); } }
mit
inoio/Rocket.Chat
app/ui/client/components/header/headerRoom.js
5740
import toastr from 'toastr'; import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { FlowRouter } from 'meteor/kadira:flow-router'; import s from 'underscore.string'; import { t, roomTypes, handleError } from '../../../../utils'; import { TabBar, fireGlobalEvent, call } from '../../../../ui-utils'; import { ChatSubscription, Rooms, ChatRoom } from '../../../../models'; import { settings } from '../../../../settings'; import { emoji } from '../../../../emoji'; import { Markdown } from '../../../../markdown/client'; import { hasAllPermission } from '../../../../authorization'; const isSubscribed = (_id) => ChatSubscription.find({ rid: _id }).count() > 0; const favoritesEnabled = () => settings.get('Favorite_Rooms'); const isDiscussion = ({ _id }) => { const room = ChatRoom.findOne({ _id }); return !!(room && room.prid); }; const getUserStatus = (id) => { const roomData = Session.get(`roomData${ id }`); return roomTypes.getUserStatus(roomData.t, id) || 'offline'; }; Template.headerRoom.helpers({ back() { return Template.instance().data.back; }, avatarBackground() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } return roomTypes.getSecondaryRoomName(roomData.t, roomData) || roomTypes.getRoomName(roomData.t, roomData); }, buttons() { return TabBar.getButtons(); }, isDiscussion() { return isDiscussion(Template.instance().data); }, isTranslated() { const sub = ChatSubscription.findOne({ rid: this._id }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } }); return settings.get('AutoTranslate_Enabled') && ((sub != null ? sub.autoTranslate : undefined) === true) && (sub.autoTranslateLanguage != null); }, state() { const sub = ChatSubscription.findOne({ rid: this._id }, { fields: { f: 1 } }); if (((sub != null ? sub.f : undefined) != null) && sub.f && favoritesEnabled()) { return ' favorite-room'; } return 'empty'; }, favoriteLabel() { const sub = ChatSubscription.findOne({ rid: this._id }, { fields: { f: 1 } }); if (((sub != null ? sub.f : undefined) != null) && sub.f && favoritesEnabled()) { return 'Unfavorite'; } return 'Favorite'; }, isDirect() { return Rooms.findOne(this._id).t === 'd'; }, roomName() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } return roomTypes.getRoomName(roomData.t, roomData); }, secondaryName() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } return roomTypes.getSecondaryRoomName(roomData.t, roomData); }, roomTopic() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData || !roomData.topic) { return ''; } let roomTopic = Markdown.parse(roomData.topic.replace(/\n/mg, ' ')); // &#39; to apostrophe (') for emojis such as :') roomTopic = roomTopic.replace(/&#39;/g, '\''); roomTopic = Object.keys(emoji.packages).reduce((topic, emojiPackage) => emoji.packages[emojiPackage].render(topic), roomTopic); // apostrophe (') back to &#39; return roomTopic.replace(/\'/g, '&#39;'); }, roomIcon() { const roomData = Session.get(`roomData${ this._id }`); if (!(roomData != null ? roomData.t : undefined)) { return ''; } return roomTypes.getIcon(roomData); }, tokenAccessChannel() { return Template.instance().hasTokenpass.get(); }, encryptionState() { const room = ChatRoom.findOne(this._id); return settings.get('E2E_Enable') && room && room.encrypted && 'encrypted'; }, userStatus() { return getUserStatus(this._id); }, userStatusText() { const roomData = Session.get(`roomData${ this._id }`); const statusText = roomTypes.getUserStatusText(roomData.t, this._id); if (s.trim(statusText)) { return statusText; } return t(getUserStatus(this._id)); }, showToggleFavorite() { return !isDiscussion(Template.instance().data) && isSubscribed(this._id) && favoritesEnabled(); }, fixedHeight() { return Template.instance().data.fixedHeight; }, fullpage() { return Template.instance().data.fullpage; }, isChannel() { return Template.instance().currentChannel != null; }, isSection() { return Template.instance().data.sectionName != null; }, }); Template.headerRoom.events({ 'click .iframe-toolbar .js-iframe-action'(e) { fireGlobalEvent('click-toolbar-button', { id: this.id }); e.currentTarget.querySelector('button').blur(); return false; }, 'click .rc-header__toggle-favorite'(event) { event.stopPropagation(); event.preventDefault(); return Meteor.call( 'toggleFavorite', this._id, !$(event.currentTarget).hasClass('favorite-room'), (err) => err && handleError(err) ); }, 'click .js-open-parent-channel'(event, t) { event.preventDefault(); const { prid } = t.currentChannel; FlowRouter.goToRoomById(prid); }, 'click .js-toggle-encryption'(event) { event.stopPropagation(); event.preventDefault(); const room = ChatRoom.findOne(this._id); if (hasAllPermission('edit-room', this._id)) { call('saveRoomSettings', this._id, 'encrypted', !(room && room.encrypted)).then(() => { toastr.success( t('Encrypted_setting_changed_successfully') ); }); } }, }); Template.headerRoom.onCreated(function() { this.currentChannel = (this.data && this.data._id && Rooms.findOne(this.data._id)) || undefined; this.hasTokenpass = new ReactiveVar(false); if (settings.get('API_Tokenpass_URL') !== '') { Meteor.call('getChannelTokenpass', this.data._id, (error, result) => { if (!error) { this.hasTokenpass.set(!!(result && result.tokens && result.tokens.length > 0)); } }); } });
mit
kaicataldo/babel
packages/babel-plugin-transform-classes/test/fixtures/get-set/set-semantics-getter-defined-on-parent/output.js
4114
"use strict"; function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } let Base = /*#__PURE__*/function () { function Base() { _classCallCheck(this, Base); } _createClass(Base, [{ key: "test", get: function () { return 1; } }]); return Base; }(); ; let Obj = /*#__PURE__*/function (_Base) { _inherits(Obj, _Base); function Obj() { _classCallCheck(this, Obj); return _possibleConstructorReturn(this, _getPrototypeOf(Obj).apply(this, arguments)); } _createClass(Obj, [{ key: "set", value: function set() { return _set(_getPrototypeOf(Obj.prototype), "test", 3, this, true); } }]); return Obj; }(Base); Object.defineProperty(Obj.prototype, 'test', { value: 2, writable: true, configurable: true }); const obj = new Obj(); expect(() => { // this requires helpers to be in file (not external), so they // are in "strict" mode code. obj.set(); }).toThrow(); expect(Base.prototype.test).toBe(1); expect(Obj.prototype.test).toBe(2); expect(obj.test).toBe(2);
mit
jongmin141215/ruby-kickstart
session2/3-challenge/7_array.rb
844
# Given a sentence, return an array containing every other word. # Punctuation is not part of the word unless it is a contraction. # In order to not have to write an actual language parser, there won't be any punctuation too complex. # There will be no "'" that is not part of a contraction. # Assume each of these charactsrs are not to be considered: ! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / < > ? \ | # # Examples # alternate_words("Lorem ipsum dolor sit amet.") # => ["Lorem", "dolor", "amet"] # alternate_words("Can't we all get along?") # => ["Can't", "all", "along"] # alternate_words("Elementary, my dear Watson!") # => ["Elementary", "dear"] def alternate_words(string) new_array = [] no_punctuation = string.scan(/[’'\w]+/) no_punctuation.each.with_index do |w, i| new_array << w if i.even? end new_array end
mit
wichtounet/eddic
src/Parameter.cpp
902
//======================================================================= // Copyright Baptiste Wicht 2011-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "Parameter.hpp" using namespace eddic; Parameter::Parameter(const std::string& name, std::shared_ptr<const Type> type) : _name(name), _type(type){ //Nothing to do } Parameter::Parameter(Parameter&& rhs) : _name(std::move(rhs._name)), _type(std::move(rhs._type)) { //Nothing to do } Parameter& Parameter::operator=(Parameter&& rhs){ _name = std::move(rhs._name); _type = std::move(rhs._type); return *this; } const std::string& Parameter::name() const { return _name; } const std::shared_ptr<const Type>& Parameter::type() const { return _type; }
mit
javifm86/codefights
arcade/intro/26 - evenDigitsOnly.js
119
function evenDigitsOnly(n) { return String(n).split('').filter((e) => ~~e % 2 === 0).length === String(n).length; }
mit
mlaursen/react-md
packages/material-icons/src/DeveloperBoardSVGIcon.tsx
602
// This is a generated file from running the "createIcons" script. This file should not be updated manually. import { forwardRef } from "react"; import { SVGIcon, SVGIconProps } from "@react-md/icon"; export const DeveloperBoardSVGIcon = forwardRef<SVGSVGElement, SVGIconProps>( function DeveloperBoardSVGIcon(props, ref) { return ( <SVGIcon {...props} ref={ref}> <path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z" /> </SVGIcon> ); } );
mit
trepo/trepo-js
packages/ptree/src/birth/getPlace.js
260
const {Direction} = require('@trepo/vgraph'); const Label = require('../label.js'); const util = require('../util.js'); module.exports = async ({input}) => util.getAdjacentNode({ node: input.node, label: Label.BIRTH_PLACE, direction: Direction.OUT, });
mit
StanislavPisotskyi/k12-new-
src/AppBundle/Form/VideoCommentForm.php
1090
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class VideoCommentForm extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('body', TextareaType::class, [ 'label' => 'Коментар', 'attr' => ['rows' => '5'] ]) ->add('save', SubmitType::class, ['label' => 'Вперед']); } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => 'AppBundle\Entity\VideoComment' ]); } public function getName() { return 'appbundle_videocomment'; } }
mit
inkton/nester.deploy
Nester.Deploy/Nester.Deploy/Helpers/Validators/ValidationFluent/ValidationCollected.cs
4328
/* Copyright (c) 2017 Inkton. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using Xamarin.Forms; namespace Inkton.Nester.Helpers.Validators { public class ValidationCollected { private readonly List<ValidationObject> _validationObjects; public ValidationCollected() { _validationObjects = new List<ValidationObject>(); } /// <summary> /// Apply the first invalid validation /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TCtrl"></typeparam> /// <param name="validatorBehavior"></param> /// <returns></returns> public T ApplyResult<T, TCtrl>(T validatorBehavior) where TCtrl : BindableObject where T : ValidatorBehavior<TCtrl> { var validationObject = _validationObjects.FirstOrDefault(x => !x.IsValid); if (validationObject != null) { validatorBehavior.NoValided(validationObject.Message); } else { validatorBehavior.Valided(); } //NOTE: Do set default valid value if needed return validatorBehavior; } /// <summary> /// Collect all invalid messages and apply at one /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TCtrl"></typeparam> /// <param name="validatorBehavior"></param> /// <param name="separate"></param> /// <returns></returns> public T ApplyAllResults<T, TCtrl>(T validatorBehavior, string separate = ", ") where TCtrl : BindableObject where T : ValidatorBehavior<TCtrl> { if (_validationObjects != null && _validationObjects.Any()) { var message = string.Join(separate, _validationObjects.Select(x => x.Message)); validatorBehavior.NoValided(message); } else { validatorBehavior.Valided(); } //NOTE: Do set default valid value if needed return validatorBehavior; } public void Add( bool hasValidation, List<Func<bool>> validateFuncs, string message) { _validationObjects.Add(new ValidationObject { HasValidation = hasValidation, ValidateFuncs = validateFuncs, Message = message }); } private class ValidationObject { public bool IsValid => DoValidate(); public bool HasValidation { get; set; } public List<Func<bool>> ValidateFuncs { get; set; } public string Message { get; set; } private bool DoValidate() { if (!HasValidation) { return true; } var isValid = true; foreach (var func in ValidateFuncs) { isValid = isValid && func(); } return isValid; } } } }
mit
harikt/web.expressive
resources/views/template/template.blade.php
625
<!DOCTYPE html> <?php /** @var \Dms\Core\Auth\IAdmin $user */ ?> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="csrf-token" content="" /> <title>{{ ($pageTitle ?? false) ? $pageTitle . ' :: ' : '' }}{{ $title }}</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> @include('dms::partials.assets.styles') </head> @yield('body-content') @include('dms::partials.assets.scripts') @include('dms::partials.js-config') </html>
mit
cuckata23/wurfl-data
data/ms_office_subua14.php
198
<?php return array ( 'id' => 'ms_office_subua14', 'fallback' => 'ms_office_subua12', 'capabilities' => array ( 'model_name' => 'Office 2010', 'release_date' => '2010_june', ), );
mit
gds-operations/vcloud-core
lib/vcloud/core/config_loader.rb
1793
require 'mustache' require 'json' module Vcloud module Core class ConfigLoader # Loads the configuration from +config_file+, optionally rendering # +config_file+ as a Mustache template using vars in +vars_file+ and # optionally validating config against +schema+ supplied. # # @param config_file [String] Location of the YAML config file # @param schema [String, nil] Location of the validation schema # if nil, no validation takes place. # @param vars_file [String, nil] Location of the vars_file (YAML), # if nil, config_file is not rendered # by Mustache # @return [Hash] def load_config(config_file, schema = nil, vars_file = nil) if vars_file rendered_config = Mustache.render( File.read(config_file), YAML::load_file(vars_file) ) input_config = YAML::load(rendered_config) else input_config = YAML::load_file(config_file) end # There is no way in YAML or Ruby to symbolize keys in a hash json_string = JSON.generate(input_config) config = JSON.parse(json_string, :symbolize_names => true) if schema validation = Core::ConfigValidator.validate(:base, config, schema) validation.warnings.each do |warning| Vcloud::Core.logger.warn(warning) end unless validation.valid? validation.errors.each do |error| Vcloud::Core.logger.fatal(error) end raise("Supplied configuration does not match supplied schema") end end config end end end end
mit
Firebird1029/BestChinese
package backups/1.0.0 auto login/background.js
961
/* // Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Called when the user clicks on the browser action. chrome.browserAction.onClicked.addListener(function(tab) { // No tabs or host permissions needed! console.log('Turning ' + tab.url + ' red!'); chrome.tabs.executeScript({ code: 'document.body.style.backgroundColor="red"' }); }); */ // alert("Started!"); console.log("Starting BC Signin."); console.log("Class ID: " + document.getElementById("txtClassID").value); document.getElementById("txtClassID").value = "Punahou8Blue"; document.getElementById("txtUsername").value = "15s15"; document.getElementById("txtPassword").value = "123123"; console.log("Finished BC Signin."); console.log("Class ID: " + document.getElementById("txtClassID").value); document.getElementById("LoginButton").click(); // alert("Finished!");
mit
VictorQRS/mega-project
inverted index/Lib/Exceptions/PathIsNotDirectoryException.cs
205
using System; namespace Lib.Exceptions { public class PathIsNotDirectoryException : Exception { public PathIsNotDirectoryException() : base("The path given is not a directory.") { } } }
mit
kinsney/sport
participator/views.py
14620
from django.shortcuts import render,render_to_response,get_object_or_404,redirect from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, Http404, HttpResponseNotFound from django.contrib.auth import authenticate, login as do_login, logout as do_logout from django.core.urlresolvers import reverse, reverse_lazy from django.template import RequestContext from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db.models import Q,Sum,Count from django.template.loader import render_to_string from message.models import IPRecord, VerificationCode,Message from order.models import Comments from participator.models import Participator,Province,VerifyCategory,VerifyAttachment from order.models import Order,Transaction from bike.models import Bike,Photo from participator.forms import verifyForm import constance import datetime import logging from django.utils import timezone logger = logging.getLogger("django") # Create your views here. month = datetime.date.today().month year = datetime.date.today().year def get_month_profit(user): '''每月收益''' orders = Order.objects.filter(bike__owner=user,beginTime__month=month,beginTime__year=year,status='completed') profit= orders.aggregate(Sum('rentMoney')) return profit["rentMoney__sum"] or 0 def get_ratio(user): '''接单率''' orders_success = Order.objects.filter(bike__owner=user,status__in=["completed","confirmed"]) orders_all = Order.objects.filter(bike__owner=user) if len(orders_all)>0: ratio = round(len(orders_success)/len(orders_all)*100) else: ratio =0 return ratio def get_average_time(user): '''平均接单时间''' orders = Order.objects.filter(bike__owner=user,status__in=["completed","confirmed"]) times = orders.aggregate(Sum('receiveTime')) if len(orders) != 0: time = times["receiveTime__sum"]/len(orders) time = time-datetime.timedelta(microseconds=time.microseconds) return time else : return "暂无" # time = datetime.timedelta(0) def login_required(view): def wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view(request, *args, **kwargs) elif request.is_ajax(): return HttpResponseForbidden() else: return render(request, 'login.html') return wrapped_view def login(request): try: assert request.is_ajax() identity = request.POST['identity'] password = request.POST['password'] assert len(identity) > 0 except (KeyError,AssertionError): return HttpResponseBadRequest() user = authenticate(username=identity,password=password) if user is None: return HttpResponseForbidden() do_login(request,user) if not request.POST.get('memorize'): request.session.set_expiry(0) return HttpResponse(status=205) def logout(request): do_logout(request) return redirect(reverse('home')) def register_code(request): try: assert request.is_ajax() phone = request.POST['phone'] ip = request.META.get('HTTP_X_REAL_IP', request.META['REMOTE_ADDR']) try: User.objects.get(username=phone) except User.DoesNotExist: pass else: return HttpResponse(status=409) ip_record = IPRecord(ip = ip) try: ip_record.clean() except ValidationError: return HttpResponse(status=421) code = VerificationCode(target=phone) code.save() ip_record.message = code.message ip_record.save() except (KeyError, AssertionError, ValidationError): return HttpResponseBadRequest() return HttpResponse(status=204) def register(request): try: assert request.is_ajax() phone = request.POST['phone'] code = request.POST['code'] password = request.POST['password'] confirm = request.POST['confirm'] nickname = request.POST['nickname'] assert 'agree' in request.POST assert password == confirm except (KeyError, AssertionError): return HttpResponseBadRequest() if not VerificationCode.objects.verify(phone, code): return HttpResponseForbidden() try: user = User.objects.create_user( username=phone, email="", password=password) except: return HttpResponse(status=409) user = authenticate(username=phone, password=password) user.participator = Participator.objects.create(user=user,nickname=nickname) do_login(request, user) return HttpResponse(status=205) #个人中心 @login_required def selfCenter(request): participator = Participator.objects.of_user(request.user) provinces = Province.objects.all() verifyCategories = VerifyCategory.objects.all() for verifyCategory in verifyCategories: try : verifyCategory.attachment = VerifyAttachment.objects.get(Q(owner=participator)&Q(title=verifyCategory)) verifyCategory.save() except: pass return render(request,'selfCenter.html',locals()) #订单处理 @login_required def orderManage(request): participator = Participator.objects.of_user(request.user) profit = get_month_profit(participator) ratio = get_ratio(participator) successOrders = len(Order.objects.filter(bike__owner=participator,status='completed')) time = get_average_time(participator) return render(request,'orderManage.html',locals()) @login_required def orderDisplay(request,tab): participator = Participator.objects.of_user(request.user) orders = Order.objects.filter( Q(renter = participator) |Q(bike__owner = participator) ) transactions = Transaction.objects.filter( Q(renter = participator) |Q(bike__owner = participator) ) if tab == 'recent': orders = orders.filter(Q(status='confirming')|Q(status='confirmed')) transactions = transactions.filter(status="confirming") elif tab == 'owner': orders = orders.filter(bike__owner = participator) transactions = transactions.filter(bike__owner = participator) elif tab == 'renter': orders = orders.filter(renter = participator) transactions = transactions.filter(renter = participator) for order in orders : order.bike.photo = Photo.objects.filter(bike=order.bike)[0] order.comments = Comments.objects.filter(order = order) for transaction in transactions: transaction.bike.photo = Photo.objects.filter(bike=transaction.bike)[0] return render_to_response('orderTable.html',{'orders':orders,'participator':participator,'transactions':transactions},context_instance = RequestContext(request)) @login_required def myBike(request): participator = Participator.objects.of_user(request.user) bikes = Bike.objects.filter(owner = participator).exclude(status= 'deleted') for bike in bikes: bike.photos = Photo.objects.filter(bike=bike) if request.POST: pass return render(request,'myBike.html',locals()) @login_required def modify(request): participator = Participator.objects.of_user(request.user) try : if request.is_ajax(): nickname = request.POST['nickname'] participator.nickname = nickname participator.save() return HttpResponse(nickname) if request.FILES: avatar = request.FILES['avatar'] participator.avatar = avatar participator.save() return redirect(reverse('selfCenter')) except : return HttpResponseBadRequest() @login_required def beginTime(request,bikeNumber): try: bike = Bike.objects.get(number = bikeNumber) beginTime = request.POST['beginTime'] endTime = request.POST['endTime'] beginTime = datetime.datetime.strptime(beginTime,'%Y-%m-%d %H:%M') bike.beginTime = beginTime endTime = datetime.datetime.strptime(endTime,'%Y-%m-%d %H:%M') bike.endTime = endTime bike.save() return HttpResponse(status=200) except: return HttpResponseBadRequest() @login_required def eraseTime(request,bikeNumber): try: assert request.is_ajax() bike = Bike.objects.get(number = bikeNumber) bike.beginTime = None bike.endTime = None bike.save() return HttpResponse(status=200) except: return HttpResponseBadRequest() @login_required def verifyInfo(request): participator = Participator.objects.of_user(request.user) provinces = Province.objects.all() verifyCategories = VerifyCategory.objects.all() VerifyAttachments = VerifyAttachment.objects.filter(owner = participator) if participator.status == 'verified': return HttpResponseForbidden() try: form = verifyForm(request.POST,instance=participator) form.save() request.user.save() attachmentType = VerifyCategory.objects.all() for i in range(1,len(request.FILES)+1): content = request.FILES['#'+str(i)] title = attachmentType[i-1] if participator.verifyattachment_set.all().filter(title = title).exists(): attachment = participator.verifyattachment_set.all().get(title=title) attachment.attachment = content attachment.save() else : attachment = VerifyAttachment.objects.create(owner = participator,title=title,attachment = content) participator.status = 'verifing' participator.save() except: return HttpResponseBadRequest(form.errors.as_json()) return redirect(reverse('selfCenter')) @login_required def orderConfirm(request,orderNumber): try: assert request.is_ajax() participator = Participator.objects.of_user(request.user) order = Order.objects.get(number = orderNumber) assert order.bike.owner == participator if order.status == 'confirming': order.set_status('confirmed') content = "{"+'"{0}":"{1}"'.format('tell',order.bike.owner.user.username)+"}" #车主确认订单 Message(target=order.renter.user.username, content=content, template_code='SMS_25390240' ).save() return redirect(reverse('orderManage')) if order.status == 'confirmed': order.set_status('completed') content = "{"+"}" #车主完成订单 Message(target=order.renter.user.username, content=content, template_code='SMS_25325300' ).save() return HttpResponse(status=200) except (Order.DoesNotExist,AssertionError) : return HttpResponseBadRequest() # *******************************取消订单**************************** @login_required def cancel(request,orderNumber): try: participator = Participator.objects.of_user(request.user) order = Order.objects.get(number = orderNumber) if "reason" in request.POST: reason = request.POST["reason"] else: reason = "" if "others" in request.POST: others = request.POST["others"] else: ohters = "" if order.bike.owner == participator : order.set_status('rejected') order.rejectReason = reason + '' + others content = "{"+'"{0}":"{1}"'.format('reason',order.rejectReason)+"}" #车主拒绝订单 Message(target=order.renter.user.username, content=content, template_code='SMS_25520320' ).save() elif order.renter == participator : order.set_status('canceled') order.canceledReason = reason + ':' + others content = "{"+'"{0}":"{1}"'.format('oid',order.number)+',"{0}":"{1}"'.format('reason',order.canceledReason)+"}" #租客取消订单 Message(target=order.bike.owner.user.username, content=content, template_code='SMS_25405301' ).save() order.save() return HttpResponse(status=200) except (Order.DoesNotExist,AssertionError) : return HttpResponseBadRequest() @login_required def orderComment(request,orderNumber): try: content = request.POST['content'] if "rating" in request.POST: rating = request.POST['rating'] else : rating = 0 participator = Participator.objects.of_user(request.user) order = Order.objects.get(number = orderNumber) if participator == order.bike.owner and rating: order.ScoreOnRenter = int(rating) elif participator == order.renter and rating: order.ScoreOnOwner = int(rating) order.save() comment = Comments.objects.create(owner=participator,content=content,order =order) return HttpResponse(status=200) except: return HttpResponseBadRequest() #删除单车 @login_required def bikeDelete(request,bikeNumber): try: bike = Bike.objects.get(number=bikeNumber) bike.status = "deleted" bike.save() except (KeyError, AssertionError): HttpResponseBadRequest() return HttpResponse(status=200) #拒绝交易 @login_required def cancelTransaction(request,trannumber): try: participator = Participator.objects.of_user(request.user) transaction = get_object_or_404(Transaction,number=trannumber) if transaction.renter == participator: transaction.set_status('canceled') elif transaction.bike.owner == participator: transaction.set_status('rejected') except: return HttpResponseBadRequest() return HttpResponse(200) @login_required def confirmTransaction(request,trannumber): try: participator = Participator.objects.of_user(request.user) transaction = get_object_or_404(Transaction,number=trannumber) assert transaction.bike.owner == participator transaction.set_status("completed") content = "{"+"}" #二手车成交通知 Message(target=transaction.bike.owner, content=content, template_code='SMS_24880413' ).save() except: return HttpResponseBadRequest() return HttpResponse(200)
mit