prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>test-regexp-instance-properties.js<|end_file_name|><|fim▁begin|>/* * RegExp instance properties. * * RegExp instance 'source' property must behave as specified in E5 Section * 15.10.4.1 paragraphcs 5 and 6. Note: there is no one required form of source. * Tests are for the source form that we want. */ /* * FIXME: when does '\' in source need to be escaped? */ /* * FIXME: add property attribute checks */ function getflags(r) { var res = '' if (r.global) { res += 'g'; } if (r.ignoreCase) { res += 'i'; } if (r.multiline) { res += 'm'; } return res; } /* * Empty string */ /*=== (?:) ===*/ try { t = new RegExp(''); print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec(''); print(t[0]); } catch (e) { print(e.name); } /* * Forward slash */ /*=== \/ / ===*/ try { t = new RegExp('/'); /* matches one forward slash (only) */ print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec('/'); print(t[0]); } catch (e) { print(e.name); } /* * Backslash */ /*=== \d 9 ===*/ try { t = new RegExp('\\d'); /* matches a digit */ print(t.source); t = eval('/' + t.source + '/' + getflags(t)); t = t.exec('9'); print(t[0]); } catch (e) { print(e.name); } /* * Flags */ /*=== foo false true false foo false true false Foo foo true false false foo true false false foo false false true foo false false true ===*/ try { t = new RegExp('foo', 'i'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline); t = t.exec('Foo'); print(t[0]); } catch (e) { print(e.name); } try { t = new RegExp('foo', 'g'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline); } catch (e) { print(e.name); } try {<|fim▁hole|>} catch (e) { print(e.name); } /* * lastIndex */ /*=== 0 ===*/ try { t = new RegExp('foo', 'i'); print(t.lastIndex); } catch (e) { print(e.name); }<|fim▁end|>
t = new RegExp('foo', 'm'); print(t.source, t.global, t.ignoreCase, t.multiline); t = eval('/' + t.source + '/' + getflags(t)); print(t.source, t.global, t.ignoreCase, t.multiline);
<|file_name|>FilesystemCache.cpp<|end_file_name|><|fim▁begin|>/* Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <[email protected]> This file is part of Kompas. Kompas is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, as published by the Free Software Foundation. Kompas 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 version 3 for more details. */ #include "FilesystemCache.h" #include "Utility/Directory.h" #include "Utility/Endianness.h" using namespace std; using namespace Kompas::Utility; using namespace Kompas::Core; namespace Kompas { namespace Plugins { PLUGIN_REGISTER(Kompas::Plugins::FilesystemCache, "cz.mosra.Kompas.Core.AbstractCache/0.2") bool FilesystemCache::initializeCache(const std::string& url) { if(!_url.empty()) finalizeCache(); _url = url; string _file = Directory::join(_url, "index.kps"); if(Directory::fileExists(_file)) { ifstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot open cache index" << _file; return false; } char* buffer = new char[4]; /* Check file signature */ file.get(buffer, 4); if(string(buffer) != "CCH") { Error() << "Unknown Kompas cache signature" << buffer << "in" << _file; return false; } /* Check file version */ file.read(buffer, 1); if(buffer[0] != 1) { Error() << "Unsupported Kompas cache version" << buffer[0] << "in" << _file; return false; } /* Block size */<|fim▁hole|> file.read(buffer, 4); _maxBlockCount = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Count of all entries */ file.read(buffer, 4); unsigned int count = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); _entries.reserve(count); /* Populate the hash table with entries */ for(unsigned int i = 0; i != count; ++i) { if(!file.good()) { Error() << "Incomplete cache index" << _file; return false; } Entry* entry = new Entry(); /* SHA-1, file size, key size and usage */ file.read(reinterpret_cast<char*>(&entry->sha1), 20); file.read(buffer, 4); entry->size = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); file.read(buffer, 4); file.read(reinterpret_cast<char*>(&entry->usage), 1); /* Key */ unsigned int keySize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); char* key = new char[keySize]; file.read(key, keySize); entry->key = string(key, keySize); delete[] key; /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } /* Add entry to entries table */ set(entry); } file.close(); } Debug() << "Initialized cache with block size" << _blockSize << "B," << _maxBlockCount << "blocks, containing" << _entries.size() << "entries of size" << _usedBlockCount << "blocks."; return true; } void FilesystemCache::finalizeCache() { if(_url.empty()) return; string _file = Directory::join(_url, "index.kps"); Directory::mkpath(Directory::path(_file)); ofstream file(_file.c_str(), ios::binary); if(!file.good()) { Error() << "Cannot write cache index" << _file; /* Avoid memory leak */ for(unordered_map<string, Entry*>::const_iterator it = _entries.begin(); it != _entries.end(); ++it) delete it->second; return; } unsigned int buffer; /* Write file signature, version, block size, block count and entry count */ file.write("CCH", 3); file.write("\1", 1); buffer = Endianness::littleEndian(static_cast<unsigned int>(_blockSize)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_maxBlockCount)); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian(static_cast<unsigned int>(_entries.size())); file.write(reinterpret_cast<const char*>(&buffer), 4); /* Foreach all entries and write them to index */ if(_position != 0) { Entry* entry = _position; do { file.write(reinterpret_cast<const char*>(&entry->sha1), Sha1::DigestSize); buffer = Endianness::littleEndian<unsigned int>(entry->size); file.write(reinterpret_cast<const char*>(&buffer), 4); buffer = Endianness::littleEndian<unsigned int>(entry->key.size()); file.write(reinterpret_cast<const char*>(&buffer), 4); file.write(reinterpret_cast<const char*>(&entry->usage), 1); file.write(entry->key.c_str(), entry->key.size()); entry = entry->next; delete entry->previous; } while(entry != _position); } file.close(); _position = 0; _usedBlockCount = 0; _entries.clear(); _files.clear(); _url.clear(); } void FilesystemCache::setBlockSize(size_t size) { _blockSize = size; if(_entries.size() == 0) return; /* Rebuild files map */ _files.clear(); _usedBlockCount = 0; Entry* entry = _position; do { /* Find hash of the file, if it already exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); if(it != _files.end()) ++it->second; /* If it doesn't exist, add the hash and increase used size */ else { _files.insert(pair<Sha1::Digest, unsigned int>(entry->sha1, 1u)); _usedBlockCount += blockCount(entry->size); } entry = entry->next; } while(entry != _position); } void FilesystemCache::purge() { Debug() << "Cleaning cache."; for(unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.begin(); it != _files.end(); ++it) Directory::rm(fileUrl(it->first)); _entries.clear(); _files.clear(); _position = 0; _usedBlockCount = 0; optimize(); } void FilesystemCache::optimize() { size_t orphanEntryCount = 0; size_t orphanFileCount = 0; size_t orphanDirectoryCount = 0; /* Remove entries without files */ if(_position != 0) { Entry* entry = _position; do { Entry* next = entry->next; /* If the file doesn't exist, remove entry */ if(!Directory::fileExists(fileUrl(entry->sha1))) { ++orphanEntryCount; remove(_entries.find(entry->key)); } entry = next; } while(_position == 0 || entry != _position); } /* Delete files which are not in the file table */ Directory d(_url, Directory::SkipDotAndDotDot); for(Directory::const_iterator it = d.begin(); it != d.end(); ++it) { if(*it == "index.kps") continue; /* Subdirectory, open it and look */ if(it->size() == 2) { string subdir = Directory::join(_url, *it); bool used = false; Directory sd(subdir, Directory::SkipDotAndDotDot); /* Remove unused files */ for(Directory::const_iterator sit = sd.begin(); sit != sd.end(); ++sit) { if(sit->size() == 38) { Sha1::Digest sha1 = Sha1::Digest::fromHexString(*it + *sit); if(sha1 != Sha1::Digest() && _files.find(sha1) == _files.end()) { if(Directory::rm(Directory::join(subdir, *sit))) ++orphanFileCount; continue; } } used = true; } if(!used) { if(Directory::rm(subdir)) ++orphanDirectoryCount; } } } Debug() << "Optimization removed" << orphanEntryCount << "orphan entries," << orphanFileCount << "orphan files and" << orphanDirectoryCount << "orphan directories."; } string FilesystemCache::get(const std::string& key) { ++_getCount; /* Find the key in entry table */ unordered_map<string, Entry*>::iterator eit = _entries.find(key); if(eit == _entries.end()) { Debug() << "Cache miss."; return string(); } Entry* entry = eit->second; /* Hash found, open the file */ string _file = fileUrl(entry->sha1); ifstream file(_file, ios::binary); if(!file.is_open()) { Error() << "Cannot open cached file" << _file; return string(); } /* Increase usage count and return file contents */ ++entry->usage; char* buffer = new char[entry->size]; file.read(buffer, entry->size); string s(buffer, entry->size); delete[] buffer; ++_hitCount; Debug() << "Retrieved entry" << entry->sha1.hexString() << "from cache. Hit rate:" << ((double) _hitCount)/_getCount; return s; } bool FilesystemCache::set(const std::string& key, const std::string& data) { if(_url.empty()) return false; /* Hash of the data */ Sha1::Digest sha1 = Sha1::digest(data); /* Add the entry */ Entry* entry = new Entry(); entry->key = key; entry->sha1 = sha1; entry->size = data.size(); entry->usage = 0; /* Find the hash in file table, if it exists, increase usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(sha1); if(it != _files.end()) { ++it->second; Debug() << "Entry" << sha1.hexString() << "already exists in cache."; /* If it doesn't exists, prepare free space and insert it */ } else { if(!reserveSpace(data.size())) return false; _usedBlockCount += blockCount(data.size()); _files.insert(pair<Sha1::Digest, unsigned int>(sha1, 1u)); if(!Directory::mkpath(filePath(sha1))) return false; string _file = fileUrl(sha1); ofstream file(_file, ios::binary); if(!file.good()) { Error() << "Cannot write cache file" << _file; return false; } file.write(data.c_str(), data.size()); file.close(); Debug() << "Added entry" << sha1.hexString() << "to cache."; } set(entry); return true; } void FilesystemCache::set(Entry* entry) { /* Find the key in entry table and remove it if it already exists */ unordered_map<string, Entry*>::iterator eit = _entries.find(entry->key); if(eit != _entries.end()) remove(eit); /* First item in the cache, initialize circular linked list */ if(_position == 0) { entry->next = entry; entry->previous = entry; _position = entry; } else { entry->next = _position; entry->previous = _position->previous; _position->previous->next = entry; _position->previous = entry; } _entries.insert(pair<string, Entry*>(entry->key, entry)); } void FilesystemCache::remove(const unordered_map<string, Entry*>::iterator& eit) { Entry* entry = eit->second; /* Disconnect the entry from circular linked list and remove it from the table */ if(entry->next == entry) _position = 0; else { entry->next->previous = entry->previous; entry->previous->next = entry->next; if(_position == entry) _position = _position->next; } _entries.erase(eit); /* Find the hash in file table, decrease usage count */ unordered_map<Sha1::Digest, unsigned int>::iterator it = _files.find(entry->sha1); /* If the file is not used anymore, remove it and decrease used size */ if(it != _files.end() && --it->second == 0) { Directory::rm(fileUrl(entry->sha1)); Directory::rm(filePath(entry->sha1)); _files.erase(it); _usedBlockCount -= blockCount(entry->size); } Debug() << "Removed entry" << entry->sha1.hexString() << "from cache, freed" << blockCount(entry->size) << "blocks."; delete entry; } bool FilesystemCache::reserveSpace(int required) { /* If we need more space than is available, don't do anything */ if(blockCount(required) > _maxBlockCount) { Error() << "Cannot reserve" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return false; } /* Go through the cycle and exponentially decrease usage count */ while(_usedBlockCount+blockCount(required) > _maxBlockCount) { _position->usage >>= 1; /* If the usage decreased to zero, remove the entry */ if(_position->usage == 0) remove(_entries.find(_position->key)); /* Otherwise advance to next entry */ else _position = _position->next; } Debug() << "Reserved" << blockCount(required) << "blocks in cache of" << _maxBlockCount << "blocks."; return true; } string FilesystemCache::filePath(const Sha1::Digest& sha1) const { return Directory::join(_url, sha1.hexString().substr(0, 2)); } string FilesystemCache::fileUrl(const Sha1::Digest& sha1) const { return Directory::join(filePath(sha1), sha1.hexString().substr(2)); } }}<|fim▁end|>
file.read(buffer, 4); _blockSize = Endianness::littleEndian(*reinterpret_cast<unsigned int*>(buffer)); /* Block count */
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ 'use strict'; // THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE // This is to ensure that we catch env issues before we error while requiring other dependencies. const engines = require('./package.json').engines; require('./tools/check-environment')({ requiredNodeVersion: engines.node, requiredNpmVersion: engines.npm, requiredYarnVersion: engines.yarn }); const gulp = require('gulp'); // See `tools/gulp-tasks/README.md` for information about task loading. function loadTask(fileName, taskName) { const taskModule = require('./tools/gulp-tasks/' + fileName); const task = taskName ? taskModule[taskName] : taskModule; return task(gulp); } gulp.task('format:enforce', loadTask('format', 'enforce')); gulp.task('format', loadTask('format', 'format')); gulp.task('build.sh', loadTask('build', 'all')); gulp.task('build.sh:no-bundle', loadTask('build', 'no-bundle')); gulp.task('public-api:enforce', loadTask('public-api', 'enforce')); gulp.task('public-api:update', ['build.sh'], loadTask('public-api', 'update')); gulp.task('lint', ['format:enforce', 'validate-commit-messages', 'tslint']); gulp.task('tslint', ['tools:build'], loadTask('lint')); gulp.task('validate-commit-messages', loadTask('validate-commit-message')); gulp.task('tools:build', loadTask('tools-build')); gulp.task('check-cycle', loadTask('check-cycle')); gulp.task('serve', loadTask('serve', 'default')); gulp.task('serve-examples', loadTask('serve', 'examples')); gulp.task('changelog', loadTask('changelog')); gulp.task('check-env', () => {/* this is a noop because the env test ran already above */});<|fim▁end|>
* @license * Copyright Google Inc. All Rights Reserved.
<|file_name|>psqworker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from importlib import import_module import logging import os import sys import click from colorlog import ColoredFormatter logger = logging.getLogger(__name__) def setup_logging(): # pragma: no cover root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(asctime)s %(green)s%(name)s" "%(reset)s %(message)s", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'blue', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', } ) handler.setFormatter(formatter) root_logger.addHandler(handler) def import_queue(location): module, attr = location.rsplit('.', 1) module = import_module(module) queue = getattr(module, attr)<|fim▁hole|> @click.command() @click.option( '--path', '-p', help='Import path. By default, this is the current working directory.') @click.option( '--pid', help='Write the process ID to the specified file.') @click.argument( 'queue', nargs=1, required=True) def main(path, pid, queue): """ Standalone PSQ worker. The queue argument must be the full importable path to a psq.Queue instance. Example usage: psqworker config.q psqworker --path /opt/app queues.fast """ setup_logging() if pid: with open(os.path.expanduser(pid), "w") as f: f.write(str(os.getpid())) if not path: path = os.getcwd() sys.path.insert(0, path) queue = import_queue(queue) import psq worker = psq.Worker(queue=queue) worker.listen() if __name__ == '__main__': main()<|fim▁end|>
if hasattr(queue, '__call__'): queue = queue() return queue
<|file_name|>WidgetUtil.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2007 Divmod.<|fim▁hole|>/** * Utilities for testing L{Nevow.Athena.Widget} subclasses. */ /** * Make a node suitable for passing as the first argument to a * L{Nevow.Athena.Widget} constructor. * * @param athenaID: the athena ID of the widget this node belongs to. * defaults to '1'. * @type athenaID: C{Number} * * @return: a node. */ Nevow.Test.WidgetUtil.makeWidgetNode = function makeWidgetNode(athenaID/*=1*/) { if(athenaID === undefined) { athenaID = 1; } var node = document.createElement('div'); node.id = Nevow.Athena.Widget.translateAthenaID(athenaID); return node; } /** * Tell athena that there is a widget with the ID C{athenaID}. * * @param widget: a widget (the one to associate with C{athenaID}). * @type widget: L{Nevow.Athena.Widget} * * @param athenaID: the athena ID of this widget. defaults to '1'. * @type athenaID: C{Number} * * @rtype: C{undefined} */ Nevow.Test.WidgetUtil.registerWidget = function registerWidget(widget, athenaID/*=1*/) { if(athenaID == undefined) { athenaID = 1; } Nevow.Athena.Widget._athenaWidgets[athenaID] = widget; } /** * Replace required global state for operating Athena widgets and events. * * @return: a thunk which will restore the global state to what it was at the * time this function was called. * @rtype: C{Function} */ Nevow.Test.WidgetUtil.mockTheRDM = function mockTheRDM() { var originalRDM = Nevow.Athena.page; Nevow.Athena.page = Nevow.Athena.PageWidget("fake-page-id", function (page) { var c = { pause: function () { }, unpause: function () { }}; return c; }); return function() { Nevow.Athena.page = originalRDM; }; }<|fim▁end|>
// See LICENSE for details.
<|file_name|>test_group_lasso.py<|end_file_name|><|fim▁begin|>from __future__ import division, print_function import numpy as np import nose.tools as nt import regreg.api as rr from ..group_lasso import (group_lasso, selected_targets, full_targets, debiased_targets) from ...tests.instance import gaussian_instance from ...tests.flags import SET_SEED from ...tests.decorators import set_sampling_params_iftrue, set_seed_iftrue from ...algorithms.sqrt_lasso import choose_lambda, solve_sqrt_lasso from ..randomization import randomization from ...tests.decorators import rpy_test_safe @set_seed_iftrue(SET_SEED) def test_group_lasso(n=400, p=100, signal_fac=3, s=5, sigma=3, target='full', rho=0.4, randomizer_scale=.75, ndraw=100000): """ Test group lasso """ inst, const = gaussian_instance, group_lasso.gaussian signal = np.sqrt(signal_fac * np.log(p)) X, Y, beta = inst(n=n, p=p, signal=signal, s=s, equicorrelated=False, rho=rho, sigma=sigma, random_signs=True)[:3] orthogonal = True if orthogonal: X = np.linalg.svd(X, full_matrices=False)[0] Y = X.dot(beta) + sigma * np.random.standard_normal(n) n, p = X.shape sigma_ = np.std(Y) groups = np.floor(np.arange(p)/2).astype(np.int) weights = dict([(i, sigma_ * 2 * np.sqrt(2)) for i in np.unique(groups)]) conv = const(X, Y, groups, weights, randomizer_scale=randomizer_scale * sigma_) signs = conv.fit() nonzero = conv.selection_variable['directions'].keys() if target == 'full': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = full_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'selected': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = selected_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'debiased': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = debiased_targets(conv.loglike, conv._W, nonzero, conv.penalty) _, pval, intervals = conv.summary(observed_target, group_assignments, cov_target, cov_target_score, alternatives, ndraw=ndraw, compute_intervals=False) which = np.zeros(p, np.bool) for group in conv.selection_variable['directions'].keys(): which_group = conv.penalty.groups == group which += which_group return pval[beta[which] == 0], pval[beta[which] != 0] @set_seed_iftrue(SET_SEED) def test_lasso(n=400, p=200, signal_fac=1.5, s=5, sigma=3, target='full', rho=0.4, ndraw=10000): """ Test group lasso with groups of size 1, ie lasso """ inst, const = gaussian_instance, group_lasso.gaussian signal = np.sqrt(signal_fac * np.log(p)) X, Y, beta = inst(n=n, p=p, signal=signal, s=s, equicorrelated=False, rho=rho, sigma=sigma, random_signs=True)[:3] n, p = X.shape sigma_ = np.std(Y) groups = np.arange(p) weights = dict([(i, sigma_ * 2 * np.sqrt(2)) for i in np.unique(groups)]) conv = const(X, Y, groups, weights) signs = conv.fit() nonzero = conv.selection_variable['directions'].keys() if target == 'full': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = full_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'selected': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = selected_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'debiased': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = debiased_targets(conv.loglike, conv._W, nonzero, conv.penalty) <|fim▁hole|> alternatives, ndraw=ndraw, compute_intervals=False) which = np.zeros(p, np.bool) for group in conv.selection_variable['directions'].keys(): which_group = conv.penalty.groups == group which += which_group return pval[beta[which] == 0], pval[beta[which] != 0] @set_seed_iftrue(SET_SEED) def test_mixed(n=400, p=200, signal_fac=1.5, s=5, sigma=3, target='full', rho=0.4, ndraw=10000): """ Test group lasso with a mix of groups of size 1, and larger """ inst, const = gaussian_instance, group_lasso.gaussian signal = np.sqrt(signal_fac * np.log(p)) X, Y, beta = inst(n=n, p=p, signal=signal, s=s, equicorrelated=False, rho=rho, sigma=sigma, random_signs=True)[:3] n, p = X.shape sigma_ = np.std(Y) groups = np.arange(p) groups[-5:] = -1 groups[-8:-5] = -2 Y += X[:,-8:].dot(np.ones(8)) * 5 # so we select the last two groups weights = dict([(i, sigma_ * 2 * np.sqrt(2)) for i in np.unique(groups)]) conv = const(X, Y, groups, weights) signs = conv.fit() nonzero = conv.selection_variable['directions'].keys() if target == 'full': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = full_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'selected': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = selected_targets(conv.loglike, conv._W, nonzero, conv.penalty) elif target == 'debiased': (observed_target, group_assignments, cov_target, cov_target_score, alternatives) = debiased_targets(conv.loglike, conv._W, nonzero, conv.penalty) _, pval, intervals = conv.summary(observed_target, group_assignments, cov_target, cov_target_score, alternatives, ndraw=ndraw, compute_intervals=False) which = np.zeros(p, np.bool) for group in conv.selection_variable['directions'].keys(): which_group = conv.penalty.groups == group which += which_group return pval[beta[which] == 0], pval[beta[which] != 0] @set_seed_iftrue(SET_SEED) def test_all_targets(n=100, p=20, signal_fac=1.5, s=5, sigma=3, rho=0.4): for target in ['full', 'selected', 'debiased']: test_group_lasso(n=n, p=p, signal_fac=signal_fac, s=s, sigma=sigma, rho=rho, target=target) def main(nsim=500, n=200, p=50, target='full', sigma=3): import matplotlib.pyplot as plt P0, PA = [], [] from statsmodels.distributions import ECDF for i in range(nsim): try: p0, pA = test_group_lasso(n=n, p=p, target=target, sigma=sigma) except: pass print(len(p0), len(pA)) P0.extend(p0) PA.extend(pA) P0_clean = np.array(P0) P0_clean = P0_clean[P0_clean > 1.e-5] # print(np.mean(P0_clean), np.std(P0_clean), np.mean(np.array(PA) < 0.05), np.sum(np.array(PA) < 0.05) / (i+1), np.mean(np.array(P0) < 0.05), np.mean(P0_clean < 0.05), np.mean(np.array(P0) < 1e-5), 'null pvalue + power + failure') if i % 3 == 0 and i > 0: U = np.linspace(0, 1, 101) plt.clf() if len(P0_clean) > 0: plt.plot(U, ECDF(P0_clean)(U)) if len(PA) > 0: plt.plot(U, ECDF(PA)(U), 'r') plt.plot([0, 1], [0, 1], 'k--') plt.savefig("plot.pdf") plt.show()<|fim▁end|>
_, pval, intervals = conv.summary(observed_target, group_assignments, cov_target, cov_target_score,
<|file_name|>test_zopetestbrowser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2013 splinter authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import os import unittest import sys from splinter import Browser from .base import BaseBrowserTests from .fake_webapp import EXAMPLE_APP from .is_element_present_nojs import IsElementPresentNoJSTest @unittest.skipIf( sys.version_info[0] > 2, "zope.testbrowser is not currently compatible with Python 3", ) class ZopeTestBrowserDriverTest( BaseBrowserTests, IsElementPresentNoJSTest, unittest.TestCase ): @classmethod def setUpClass(cls): cls.browser = Browser("zope.testbrowser", wait_time=0.1) def setUp(self): self.browser.visit(EXAMPLE_APP) @classmethod def tearDownClass(self): self.browser.quit() def test_should_support_with_statement(self): with Browser("zope.testbrowser"): pass def test_attach_file(self): "should provide a way to change file field value" file_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), "mockfile.txt" ) self.browser.attach_file("file", file_path) self.browser.find_by_name("upload").click() html = self.browser.html self.assertIn("text/plain", html) self.assertIn(open(file_path).read().encode("utf-8"), html) def test_forward_to_none_page(self): "should not fail when trying to forward to none" browser = Browser("zope.testbrowser") browser.visit(EXAMPLE_APP) browser.forward() self.assertEqual(EXAMPLE_APP, browser.url) browser.quit() def test_cant_switch_to_frame(self): "zope.testbrowser should not be able to switch to frames" with self.assertRaises(NotImplementedError) as cm: self.browser.get_iframe("frame_123") self.fail() e = cm.exception self.assertEqual("zope.testbrowser doesn't support frames.", e.args[0]) def test_simple_type(self): """ zope.testbrowser won't support type method because it doesn't interact with JavaScript """ with self.assertRaises(NotImplementedError): self.browser.type("query", "with type method") def test_simple_type_on_element(self): """ zope.testbrowser won't support type method because it doesn't interact with JavaScript """ with self.assertRaises(NotImplementedError): self.browser.find_by_name("query").type("with type method") def test_can_clear_password_field_content(self): "zope.testbrowser should not be able to clear" with self.assertRaises(NotImplementedError): self.browser.find_by_name("password").first.clear() def test_can_clear_tel_field_content(self): "zope.testbrowser should not be able to clear" with self.assertRaises(NotImplementedError): self.browser.find_by_name("telephone").first.clear() def test_can_clear_text_field_content(self): "zope.testbrowser should not be able to clear" with self.assertRaises(NotImplementedError): self.browser.find_by_name("query").first.clear() def test_slowly_typing(self): """ zope.testbrowser won't support type method because it doesn't interact with JavaScript<|fim▁hole|> self.browser.type("query", "with type method", slowly=True) def test_slowly_typing_on_element(self): """ zope.testbrowser won't support type method on element because it doesn't interac with JavaScript """ with self.assertRaises(NotImplementedError): query = self.browser.find_by_name("query") query.type("with type method", slowly=True) def test_cant_mouseover(self): "zope.testbrowser should not be able to put the mouse over the element" with self.assertRaises(NotImplementedError): self.browser.find_by_css("#visible").mouse_over() def test_cant_mouseout(self): "zope.testbrowser should not be able to mouse out of an element" with self.assertRaises(NotImplementedError): self.browser.find_by_css("#visible").mouse_out() def test_links_with_nested_tags_xpath(self): links = self.browser.find_by_xpath('//a/span[text()="first bar"]/..') self.assertEqual( len(links), 1, 'Found not exactly one link with a span with text "BAR ONE". %s' % (map(lambda item: item.outer_html, links)), ) def test_finding_all_links_by_non_ascii_text(self): "should find links by non ascii text" non_ascii_encodings = { "pangram_pl": u"Jeżu klątw, spłódź Finom część gry hańb!", "pangram_ja": u"天 地 星 空", "pangram_ru": u"В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!", "pangram_eo": u"Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo kun spicoj.", } for key, text in non_ascii_encodings.iteritems(): link = self.browser.find_link_by_text(text) self.assertEqual(key, link["id"])<|fim▁end|>
""" with self.assertRaises(NotImplementedError):
<|file_name|>clean_mac_info_plist.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the Litecoin-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "Gwangcoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"gwangcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"):<|fim▁hole|>fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"<|fim▁end|>
version = lineArr[1].replace("\n", "");
<|file_name|>cache_restore.rs<|end_file_name|><|fim▁begin|>use anyhow::Result; mod common; use common::cache::*; use common::common_args::*; use common::fixture::*; use common::input_arg::*; use common::output_option::*; use common::process::*; use common::program::*; use common::target::*; use common::test_dir::*; //------------------------------------------ const USAGE: &str = concat!( "cache_restore ", include_str!("../VERSION"), "Convert XML format metadata to binary. USAGE: cache_restore [OPTIONS] --input <FILE> --output <FILE> OPTIONS: -h, --help Print help information -i, --input <FILE> Specify the input xml -o, --output <FILE> Specify the output device to check -q, --quiet Suppress output messages, return only exit code. -V, --version Print version information" ); //------------------------------------------ struct CacheRestore; impl<'a> Program<'a> for CacheRestore { fn name() -> &'a str { "thin_restore" } fn cmd<I>(args: I) -> Command where I: IntoIterator, I::Item: Into<std::ffi::OsString>, { cache_restore_cmd(args) } fn usage() -> &'a str { USAGE } fn arg_type() -> ArgType { ArgType::IoOptions } fn bad_option_hint(option: &str) -> String { msg::bad_option_hint(option) }<|fim▁hole|> impl<'a> InputProgram<'a> for CacheRestore { fn mk_valid_input(td: &mut TestDir) -> Result<std::path::PathBuf> { mk_valid_xml(td) } fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } fn missing_input_arg() -> &'a str { msg::MISSING_INPUT_ARG } fn corrupted_input() -> &'a str { "" // we don't intent to verify error messages of XML parsing } } impl<'a> OutputProgram<'a> for CacheRestore { fn missing_output_arg() -> &'a str { msg::MISSING_OUTPUT_ARG } } impl<'a> MetadataWriter<'a> for CacheRestore { fn file_not_found() -> &'a str { msg::FILE_NOT_FOUND } } //----------------------------------------- test_accepts_help!(CacheRestore); test_accepts_version!(CacheRestore); test_missing_input_option!(CacheRestore); test_input_file_not_found!(CacheRestore); test_corrupted_input_data!(CacheRestore); test_missing_output_option!(CacheRestore); test_tiny_output_file!(CacheRestore); test_unwritable_output_file!(CacheRestore); //----------------------------------------- // TODO: share with thin_restore, era_restore fn quiet_flag(flag: &str) -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; let output = run_ok_raw(cache_restore_cmd(args!["-i", &xml, "-o", &md, flag]))?; assert_eq!(output.stdout.len(), 0); assert_eq!(output.stderr.len(), 0); Ok(()) } #[test] fn accepts_q() -> Result<()> { quiet_flag("-q") } #[test] fn accepts_quiet() -> Result<()> { quiet_flag("--quiet") } //----------------------------------------- #[test] fn successfully_restores() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok(cache_restore_cmd(args!["-i", &xml, "-o", &md]))?; Ok(()) } // FIXME: finish /* #[test] fn override_metadata_version() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args![ "-i", &xml, "-o", &md, "--debug-override-metadata-version", "10298" ], ))?; Ok(()) } */ // FIXME: finish /* #[test] fn accepts_omit_clean_shutdown() -> Result<()> { let mut td = TestDir::new()?; let xml = mk_valid_xml(&mut td)?; let md = mk_zeroed_md(&mut td)?; run_ok( cache_restore_cmd( args!["-i", &xml, "-o", &md, "--omit-clean-shutdown"], ))?; Ok(()) } */ //-----------------------------------------<|fim▁end|>
}
<|file_name|>batchDeleteExistingOverlayActionsCommand.ts<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ import { BaseCommand, RestHttpMethodEnum } from '@salesforce/salesforcedx-apex-replay-debugger/node_modules/@salesforce/salesforcedx-utils-vscode/out/src/requestService';<|fim▁hole|> export interface BatchRequests { batchRequests: BatchRequest[]; } export interface BatchRequest { method: RestHttpMethodEnum; url: string; } export interface BatchDeleteResponse { hasErrors: boolean; results: BatchDeleteResult[]; } export interface BatchDeleteResult { statusCode: number; result: SingleResult[] | null; } export interface SingleResult { errorCode: string; message: string; } export class BatchDeleteExistingOverlayActionCommand extends BaseCommand { private readonly requests: BatchRequests; public constructor(requests: BatchRequests) { super(undefined); this.requests = requests; } public getCommandUrl(): string { return COMPOSITE_BATCH_URL; } public getRequest(): string | undefined { return JSON.stringify(this.requests); } }<|fim▁end|>
import { COMPOSITE_BATCH_URL } from '@salesforce/salesforcedx-apex-replay-debugger/out/src/constants';
<|file_name|>StatisticCalc.java<|end_file_name|><|fim▁begin|>/* {{ jtdavids-reflex }} Copyright (C) 2015 Jake Davidson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.example.jake.jtdavids_reflex; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by Jake on 28/09/2015. */ public class StatisticCalc { List<Double> reaction_times = new ArrayList<Double>(); public StatisticCalc() { } public void add(double time){ reaction_times.add(time); } public void clear(){ reaction_times.clear(); } public String getAllTimeMin(){ //gets the minimum time of all recorded reaction times //if no reaction times are recored, return 'N/A' if (reaction_times.size() != 0) { double min = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { if (reaction_times.get(i) < min) { min = reaction_times.get(i); } } return String.valueOf(min); } else{ return "N/A"; } } public String getSpecifiedTimeMin(int length){ //Gets the minimum reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() != 0) { if(reaction_times.size() < length){ length = reaction_times.size(); } double min = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) { if (reaction_times.get(i) < min) { min = reaction_times.get(i); } } return String.valueOf(min); } else{ return "N/A"; } } public String getAllTimeMax(){ //gets the maximum reaction time of all reactions if (reaction_times.size() !=0 ) { double max = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { if (reaction_times.get(i) > max) { max = reaction_times.get(i); } } return String.valueOf(max); } else{ return "N/A"; } } public String getSpecifiedTimeMax(int length){ //Gets the maximum reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() !=0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } double max = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) { if (reaction_times.get(i) > max) { max = reaction_times.get(i); } } return String.valueOf(max); } else{ return "N/A"; } } public String getAllTimeAvg(){ //gets the average reaction time of all reactions if (reaction_times.size() !=0 ) { double avg = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= 0; i--) { avg = avg + reaction_times.get(i); } return String.valueOf((avg / reaction_times.size())); } else{ return "N/A "; } } public String getSpecifiedTimeAvg(int length){ //Gets the average reaction time of the last X reactions //a negative value should not be passed into this method //Since reactions are stored in a list, must iterate backwards through the list //to retrieve reaction times in chronological order if (reaction_times.size() !=0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } double avg = reaction_times.get(reaction_times.size()-1); for (int i = reaction_times.size()-2; i >= reaction_times.size()-length; i--) { avg = avg + reaction_times.get(i); } return String.valueOf((avg / length)); }else{ return "N/A "; } } public String getAllTimeMed(){ //gets the median reaction time of all reactions if (reaction_times.size() !=0 ) { List<Double> sorted_times = new ArrayList<Double>(reaction_times); Collections.sort(sorted_times); return String.valueOf((sorted_times.get(sorted_times.size() / 2))); } else{ return "N/A"; } } public String getSpecifiedTimeMed(int length){ //Gets the median reaction time of the last X reactions //a negative value should not be passed into this method if (reaction_times.size() != 0 ) { if(reaction_times.size() < length){ length = reaction_times.size(); } List<Double> sorted_times = new ArrayList<Double>(reaction_times.subList(0, length)); Collections.sort(sorted_times); return String.valueOf((sorted_times.get(sorted_times.size() / 2))); }else{ return "N/A"; } } public String getStatsMessage(SharedPreferences twoplayers_score, SharedPreferences threeplayers_score, SharedPreferences fourplayers_score){<|fim▁hole|> "All Time: " + getAllTimeMin() + "\nLast 10 times: " + getSpecifiedTimeMin(10) + "\nLast 100 times: " + getSpecifiedTimeMin(100) + "\n" + " MAX TIME:\n" + "All Time: " + getAllTimeMax() + "\nLast 10 times: " + getSpecifiedTimeMax(10) + "\nLast 100 times: " + getSpecifiedTimeMax(100) + "\n" + " AVERAGE TIME:\n" + "All Time: " + getAllTimeAvg() + "\nLast 10 times: " + getSpecifiedTimeAvg(10) + "\nLast 100 times: " + getSpecifiedTimeAvg(100) + "\n" + " MEDIAN TIME:\n" + "All Time: " + getAllTimeMed() + "\nLast 10 times: " + getSpecifiedTimeMed(10) + "\nLast 100 times: " + getSpecifiedTimeMed(100) + "\n" + "______PARTY PLAY______\n" + " 2 PLAYERS:\n" + "Player 1: " + String.valueOf(twoplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(twoplayers_score.getInt("player2", 0)) + "\n" + " 3 PLAYERS:\n" + "Player 1: " + String.valueOf(threeplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(threeplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(threeplayers_score.getInt("player3", 0)) + "\n" + " 4 PLAYERS:\n" + "Player 1: " + String.valueOf(fourplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(fourplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(fourplayers_score.getInt("player3", 0)) + "\nPlayer 4: " + String.valueOf(fourplayers_score.getInt("player4", 0)) + "\n"); } }<|fim▁end|>
return ("______SINGLEPLAYER______\n" + " MIN TIME:\n" +
<|file_name|>KurentoHttpPlayer.java<|end_file_name|><|fim▁begin|>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library 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. * */ package org.kurento.tutorial.player; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.kurento.client.EndOfStreamEvent; import org.kurento.client.EventListener; import org.kurento.client.FaceOverlayFilter; import org.kurento.client.HttpGetEndpoint; import org.kurento.client.MediaPipeline; import org.kurento.client.PlayerEndpoint; import org.kurento.client.KurentoClient; /** * HTTP Player with Kurento; the media pipeline is composed by a PlayerEndpoint * connected to a filter (FaceOverlay) and an HttpGetEnpoint; the default * desktop web browser is launched to play the video. * * @author Micael Gallego ([email protected]) * @author Boni Garcia ([email protected]) * @since 5.0.0 */ public class KurentoHttpPlayer { public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException { // Connecting to Kurento Server KurentoClient kurento = KurentoClient .create("ws://localhost:8888/kurento"); // Creating media pipeline MediaPipeline pipeline = kurento.createMediaPipeline(); // Creating media elements PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, "http://files.kurento.org/video/fiwarecut.mp4").build(); FaceOverlayFilter filter = new FaceOverlayFilter.Builder(pipeline) .build(); filter.setOverlayedImage( "http://files.kurento.org/imgs/mario-wings.png", -0.2F, -1.1F, 1.6F, 1.6F); HttpGetEndpoint http = new HttpGetEndpoint.Builder(pipeline).build(); // Connecting media elements player.connect(filter); filter.connect(http); // Reacting to events player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { System.out.println("The playing has finished"); System.exit(0); } }); // Playing media and opening the default desktop browser player.play(); String videoUrl = http.getUrl(); Desktop.getDesktop().browse(new URI(videoUrl)); // Setting a delay to wait the EndOfStream event, previously subscribed Thread.sleep(60000);<|fim▁hole|><|fim▁end|>
} }
<|file_name|>iCellRenderer.js<|end_file_name|><|fim▁begin|>/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components<|fim▁hole|> * @link http://www.ag-grid.com/ * @license MIT */<|fim▁end|>
* @version v4.1.1
<|file_name|>state_change_repeating.py<|end_file_name|><|fim▁begin|>from bson import ObjectId from . import repeating_schedule from state_change import StateChange class StateChangeRepeating(StateChange): def __init__(self, seconds_into_week, AC_target, heater_target, fan, id=None): self.id = id self.seconds_into_week = seconds_into_week self.AC_target = AC_target self.heater_target = heater_target self.fan = fan assert type(seconds_into_week) is int or long assert type(AC_target) is int or float assert type(heater_target) is int or float assert type(fan) is int or float @classmethod def from_dictionary(cls, json): seconds_into_week = json["week_time"] AC_target = json["state"]["AC_target"] heater_target = json["state"]["heater_target"] fan = json["state"]["fan"]<|fim▁hole|> try: id = ObjectId(json["_id"]["$oid"]) except KeyError: id = None except TypeError: try: id = ObjectId(json["_id"]) except: id = None return cls(seconds_into_week, AC_target, heater_target, fan, id=id) @classmethod def get_current(cls, now): week_time = now.weekday() * 24 * 60 ** 2 + (now.hour * 60 + now.minute) * 60 result = repeating_schedule.aggregate( [ {"$project": { "time_delta": {"$mod": [{"$add": [{"$subtract": [week_time, "$week_time"]}, 24 * 7 * 60 ** 2]}, 24 * 7 * 60 ** 2]}, "state": 1, "week_time": 1} }, {"$sort": {"time_delta": 1}} ]).next() return cls.from_dictionary(result) def save(self): delayed_state_change = { "week_time": self.seconds_into_week, "state": {"AC_target": self.AC_target, "heater_target": self.heater_target, "fan": self.fan} } if self.id is not None: delayed_state_change["_id"] = self.id return repeating_schedule.save(delayed_state_change) def to_dictionary(self): return {"week_time": self.seconds_into_week, "_id": str(self.id), "state": {"AC_target": self.AC_target, "heater_target": self.heater_target, "fan": self.fan}} @classmethod def get_all_dic(cls): all_items = cls.get_all() result = [] for item in all_items: result.append(item.to_dictionary()) return result<|fim▁end|>
<|file_name|>index.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
export * from './table-enquete.component';
<|file_name|>keyup.js<|end_file_name|><|fim▁begin|>function(){ var db = $$(this).app.db, term = $(this).val(), nonce = Math.random(); $$($(this)).nonce = nonce; db.view("icd9lookup/by_code", { startkey : term, endkey : term+"\u9999", //I don't know why only \u9999 works, not \uFFFF limit : 100, success : function(names){ if($$($(this)).nonce = nonce){ $("#results").html( "<tr><th>ICD-9 Code</th><th>Long Description</th><th>Short Description</th></tr>"+ names.rows.map(function(r){ return '<tr><td>'+r.value.icd9code+'</td><td>'+r.value.long_description+'</td><td>'+r.value.short_description+'</td></tr>'; }).join("")); }}});<|fim▁hole|>}<|fim▁end|>
<|file_name|>CollectiveInfoResource.java<|end_file_name|><|fim▁begin|><|fim▁hole|> import at.ac.tuwien.dsg.pm.PeerManager; import at.ac.tuwien.dsg.pm.model.Collective; import at.ac.tuwien.dsg.smartcom.model.CollectiveInfo; import at.ac.tuwien.dsg.smartcom.model.Identifier; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; /** * @author Philipp Zeppezauer ([email protected]) * @version 1.0 */ @Path("collectiveInfo") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class CollectiveInfoResource { @Inject private PeerManager manager; @GET @Path("/{id}") public CollectiveInfo getCollectiveInfo(@PathParam("id") String id) { Collective collective = manager.getCollective(id); if (collective == null) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } CollectiveInfo info = new CollectiveInfo(); info.setId(Identifier.collective(id)); info.setDeliveryPolicy(collective.getDeliveryPolicy()); List<Identifier> peers = new ArrayList<>(collective.getPeers().size()); for (String s : collective.getPeers()) { peers.add(Identifier.peer(s)); } info.setPeers(peers); return info; } }<|fim▁end|>
package at.ac.tuwien.dsg.pm.resources;
<|file_name|>rsa.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii try: from gdata.tlslite.utils import keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory try: from gdata.tlslite.utils import cryptomath except ImportError: from tlslite.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod): def get_name(self): return "RSA-SHA1" def _fetch_public_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # (2) fetch via http using a url provided by the requester # (3) some sort of specific discovery code based on request # # either way should return a string representation of the certificate raise NotImplementedError def _fetch_private_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # # either way should return a string representation of the certificate raise NotImplementedError def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()),<|fim▁hole|> raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the private key cert based on the request cert = self._fetch_private_cert(oauth_request) # Pull the private key from the certificate privatekey = keyfactory.parsePrivateKey(cert) # Convert base_string to bytes #base_string_bytes = cryptomath.createByteArraySequence(base_string) # Sign using the key signed = privatekey.hashAndSign(base_string) return binascii.b2a_base64(signed)[:-1] def check_signature(self, oauth_request, consumer, token, signature): decoded_sig = base64.b64decode(signature); key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the public key cert based on the request cert = self._fetch_public_cert(oauth_request) # Pull the public key from the certificate publickey = keyfactory.parsePEMKey(cert, public=True) # Check the signature ok = publickey.hashAndVerify(decoded_sig, base_string) return ok class TestOAuthSignatureMethod_RSA_SHA1(OAuthSignatureMethod_RSA_SHA1): def _fetch_public_cert(self, oauth_request): cert = """ -----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE----- """ return cert def _fetch_private_cert(self, oauth_request): cert = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY----- """ return cert<|fim▁end|>
oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = ''
<|file_name|>PrayerGroup.java<|end_file_name|><|fim▁begin|>package org.maxgamer.rs.model.skill.prayer; import java.util.LinkedList; /** * @author netherfoam, alva */ public enum PrayerGroup { //Standard prayer book /** All prayers that boost defense */ DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY), /** All prayers that boost strength */ STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost attack */ ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost range */ RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR), /** All prayers that boost magic */ MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY), /** * most prayers that put a symbol above player head (Prot * (melee/magic/range), retribution, smite, redemption) */ STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE), /** Protect from melee/range/magic prayers */ PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC), //Curses prayer book /** Sap prayers (warrior, range, spirit) */<|fim▁hole|> SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT), /** * leech prayers (attack, range, magic, defence, strength, energy, special * attack) */ LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.LEECH_SPECIAL_ATTACK), /** * similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles, * melee) */ CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE), /** All deflections (magic, missiles, melee) */ DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE); private PrayerType[] types; private PrayerGroup(PrayerType... types) { this.types = types; } public PrayerType[] getTypes() { return types; } /** * Returns true if this prayer group contains the given prayer. * @param type the prayer * @return true if it is contained, else false. */ public boolean contains(PrayerType type) { for (PrayerType p : this.types) { if (type == p) { return true; } } return false; } /** * Returns an array of groups that the given prayer is in. * @param type the prayer * @return an array of groups that the given prayer is in. */ public static LinkedList<PrayerGroup> getGroups(PrayerType type) { LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>(); for (PrayerGroup g : values()) { if (g.contains(type)) { groups.add(g); } } return groups; } }<|fim▁end|>
<|file_name|>help.hpp<|end_file_name|><|fim▁begin|>#ifndef METASHELL_PRAGMA_HELP_HPP #define METASHELL_PRAGMA_HELP_HPP // Metashell - Interactive C++ template metaprogramming shell // Copyright (C) 2014, Abel Sinkovics ([email protected]) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <metashell/iface/pragma_handler.hpp> namespace metashell { namespace pragma { class help : public iface::pragma_handler { public: std::string arguments() const override; std::string description() const override; void run(const data::command::iterator& name_begin_, const data::command::iterator& name_end_, const data::command::iterator& args_begin_, const data::command::iterator& args_end_, iface::main_shell& shell_, iface::displayer& displayer_) const override; data::code_completion code_complete(data::command::const_iterator, data::command::const_iterator,<|fim▁hole|>} #endif<|fim▁end|>
iface::main_shell&) const override; }; }
<|file_name|>reader.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A wrapper around any Read to treat it as an RNG.<|fim▁hole|>use io::prelude::*; use rand::Rng; /// An RNG that reads random bytes straight from a `Read`. This will /// work best with an infinite reader, but this is not required. /// /// # Panics /// /// It will panic if it there is insufficient data to fulfill a request. pub struct ReaderRng<R> { reader: R } impl<R: Read> ReaderRng<R> { /// Create a new `ReaderRng` from a `Read`. pub fn new(r: R) -> ReaderRng<R> { ReaderRng { reader: r } } } impl<R: Read> Rng for ReaderRng<R> { fn next_u32(&mut self) -> u32 { // This is designed for speed: reading a LE integer on a LE // platform just involves blitting the bytes into the memory // of the u32, similarly for BE on BE; avoiding byteswapping. let mut bytes = [0; 4]; self.fill_bytes(&mut bytes); unsafe { *(bytes.as_ptr() as *const u32) } } fn next_u64(&mut self) -> u64 { // see above for explanation. let mut bytes = [0; 8]; self.fill_bytes(&mut bytes); unsafe { *(bytes.as_ptr() as *const u64) } } fn fill_bytes(&mut self, mut v: &mut [u8]) { while !v.is_empty() { let t = v; match self.reader.read(t) { Ok(0) => panic!("ReaderRng.fill_bytes: EOF reached"), Ok(n) => v = t.split_at_mut(n).1, Err(e) => panic!("ReaderRng.fill_bytes: {}", e), } } } } #[cfg(test)] mod tests { use prelude::v1::*; use super::ReaderRng; use rand::Rng; #[test] fn test_reader_rng_u64() { // transmute from the target to avoid endianness concerns. let v = &[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3][..]; let mut rng = ReaderRng::new(v); assert_eq!(rng.next_u64(), 1u64.to_be()); assert_eq!(rng.next_u64(), 2u64.to_be()); assert_eq!(rng.next_u64(), 3u64.to_be()); } #[test] fn test_reader_rng_u32() { let v = &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3][..]; let mut rng = ReaderRng::new(v); assert_eq!(rng.next_u32(), 1u32.to_be()); assert_eq!(rng.next_u32(), 2u32.to_be()); assert_eq!(rng.next_u32(), 3u32.to_be()); } #[test] fn test_reader_rng_fill_bytes() { let v = [1, 2, 3, 4, 5, 6, 7, 8]; let mut w = [0; 8]; let mut rng = ReaderRng::new(&v[..]); rng.fill_bytes(&mut w); assert!(v == w); } #[test] #[should_panic] fn test_reader_rng_insufficient_bytes() { let mut rng = ReaderRng::new(&[][..]); let mut v = [0; 3]; rng.fill_bytes(&mut v); } }<|fim▁end|>
#![allow(dead_code)] #[cfg(stage0)] use prelude::v1::*;
<|file_name|>index.tsx<|end_file_name|><|fim▁begin|>import { NPS } from './NPS'<|fim▁hole|><|fim▁end|>
export default NPS
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os<|fim▁hole|> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "radiocontrol.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)<|fim▁end|>
import sys if __name__ == "__main__":
<|file_name|>validate-config.js<|end_file_name|><|fim▁begin|>'use strict'; var async = require('async'); var _ = require('lodash'); var yamlReader = require('./yaml-reader/yaml-reader'); var fliprValidation = require('flipr-validation'); module.exports = validateConfig; function validateConfig(options, cb) { var validateOptions = { rules: options.rules, }; async.auto({<|fim▁hole|> validate: ['config', function(callback, results){ validateOptions.config = results.config; callback(null, fliprValidation(validateOptions)); }] }, function(err, results){ if(err) return void cb(err); return void cb(null, results.validate); }); }<|fim▁end|>
config: _.partial(yamlReader, options),
<|file_name|>dir_4627380db2f0c36581ca02ea208a64c6.js<|end_file_name|><|fim▁begin|>var dir_4627380db2f0c36581ca02ea208a64c6 = [<|fim▁hole|><|fim▁end|>
[ "support", "dir_2e2aa096c82c7fb5ccae4b9643632450.html", "dir_2e2aa096c82c7fb5ccae4b9643632450" ] ];
<|file_name|>manage.py<|end_file_name|><|fim▁begin|><|fim▁hole|> if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ProxyServe.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)<|fim▁end|>
#!/usr/bin/env python import os import sys
<|file_name|>QPropertyModel.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore, QtGui from components.propertyeditor.Property import Property from components.RestrictFileDialog import RestrictFileDialog from PyQt4.QtCore import * from PyQt4.QtGui import * import sys, os class QPropertyModel(QtCore.QAbstractItemModel): def __init__(self, parent): super(QPropertyModel, self).__init__(parent) self.rootItem = Property("Root", "Root", 0, None); def index (self, row, column, parent): parentItem = self.rootItem; if (parent.isValid()): parentItem = parent.internalPointer() if (row >= parentItem.childCount() or row < 0): return QtCore.QModelIndex(); return self.createIndex(row, column, parentItem.child(row)) def getIndexForNode(self, node): return self.createIndex(node.row(), 1, node) def getPropItem(self, name, parent=None): if(parent == None): parent = self.rootItem for item in parent.childItems: if(item.name == name): return item return None def headerData (self, section, orientation, role) : if (orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole) :<|fim▁hole|> return "Property" elif (section == 1) : return "Value" return None # QtCore.QVariant(); def flags (self, index ): if (not index.isValid()): return QtCore.Qt.ItemIsEnabled; item = index.internalPointer(); if (index.column() == 0): return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable # only allow change of value attribute if (item.isRoot()): return QtCore.Qt.ItemIsEnabled; elif (item.readOnly): return QtCore.Qt.ItemIsDragEnabled else: return QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable; def parent(self, index): if not index.isValid(): return QtCore.QModelIndex() childItem = index.internalPointer() parentItem = childItem.parentItem if parentItem == None or parentItem == self.rootItem: return QtCore.QModelIndex() return self.createIndex(parentItem.childCount(), 0, parentItem) def rowCount ( self, parent ): parentItem = self.rootItem; if (parent.isValid()): parentItem = parent.internalPointer() return len(parentItem.childItems) def columnCount (self, parent): return 2 def data (self, index, role): if (not index.isValid()): return None item = index.internalPointer() if(item.editor_type == Property.IMAGE_EDITOR): if (index.column() == 0) and ( role == QtCore.Qt.ToolTipRole or role == QtCore.Qt.DecorationRole or role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole): return item.label.replace('_', ' '); if (index.column() == 1): if(role == QtCore.Qt.DecorationRole): if(item.value['icon'] != None and not item.value['icon'].isNull()): return item.value['icon'].scaled(18, 18) else: return None if(role == QtCore.Qt.DisplayRole): return item.value['url'] if(role == QtCore.Qt.EditRole): return item.value else: if(role == QtCore.Qt.ToolTipRole or role == QtCore.Qt.DecorationRole or role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole): if (index.column() == 0): return item.label.replace('_', ' '); if (index.column() == 1): return item.value if(role == QtCore.Qt.BackgroundRole): if (item.isRoot()): return QtGui.QApplication.palette("QTreeView").brush(QtGui.QPalette.Normal, QtGui.QPalette.Button).color(); return None def getItem(self, index): if index.isValid(): item = index.internalPointer() if item: return item return self.rootItem def insertRows(self, position, rows, parent=QtCore.QModelIndex()): parentItem = self.getItem(parent) self.beginInsertRows(parent, position, position + rows - 1) for row in range(rows): success = parentItem.insertChild(position+row) != None self.endInsertRows() return success def removeRows(self, position, rows, parent=QtCore.QModelIndex()): parentItem = self.getItem(parent) self.beginRemoveRows(parent, position, position + rows - 1) success = parentItem.removeChildren(position, rows) self.endRemoveRows() return success # edit methods def setData(self, index, value, role = QtCore.Qt.EditRole): if (index.isValid() and role == Qt.EditRole): item = index.internalPointer() item.setValue(value) self.dataChanged.emit(index, index) return True; return False def import_module_from_file(self, full_path_to_module): """ Import a module given the full path/filename of the .py file Python 3.4 """ module = None # Get module name and path from full path module_dir, module_file = os.path.split(full_path_to_module) module_name, module_ext = os.path.splitext(module_file) if(sys.version_info >= (3,4)): import importlib # Get module "spec" from filename spec = importlib.util.spec_from_file_location(module_name,full_path_to_module) module = spec.loader.load_module() else: import imp module = imp.load_source(module_name,full_path_to_module) return module def getModuleFuncList(self, module_name): import inspect func_list = [] if(module_name != ''): try: module_name = os.getcwd() + '\\' + module_name module = self.import_module_from_file(module_name) all_functions = inspect.getmembers(module, inspect.isfunction) for function in all_functions: func_list.append(function[0]) except: pass return func_list def getModuleName(self, editor): module_name = QFileDialog.getOpenFileName(None, 'Open File', '.', "All file(*.*);;Python (*.py)") module_name = os.path.relpath(module_name, os.getcwd()) if (module_name == ''): return prop_root = self.getPropItem('properties') module_name_prop= self.getPropItem('module_name', prop_root) module_name_prop.setValue(module_name) module_name_index = self.getIndexForNode(module_name_prop) self.dataChanged.emit(module_name_index, module_name_index) function_name_prop= self.getPropItem('function_name', prop_root) function_name_prop.editor_type = Property.COMBO_BOX_EDITOR function_name_prop.editor_data = self.getModuleFuncList(module_name) function_name_index = self.getIndexForNode(function_name_prop) self.dataChanged.emit(function_name_index, function_name_index)<|fim▁end|>
if (section == 0) :
<|file_name|>foundation.equalizer.min.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
version https://git-lfs.github.com/spec/v1 oid sha256:a2aca9cd81f31f3e9e83559fdcfa84d3ee900090ee4baeb2bae129e9d06473eb size 1264
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>use bindgen::RustTarget; use pkg_config::Error; use std::env; use std::io::Write; use std::path::PathBuf; fn main() { let package_name = "cfitsio"; match pkg_config::probe_library(package_name) { Ok(_) => { let bindings = bindgen::builder() .header("wrapper.h") .block_extern_crate(true) .opaque_type("fitsfile") .opaque_type("FITSfile") .rust_target(RustTarget::Stable_1_0) .generate() .expect("Unable to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings"); } Err(Error::Failure { output, .. }) => { // Handle the case where the user has not installed cfitsio, and thusly it is not on // the PKG_CONFIG_PATH let stderr = String::from_utf8(output.stderr).unwrap(); if stderr.contains::<&str>( format!( "{} was not found in the pkg-config search path", package_name ) .as_ref(), ) { let err_msg = format!( " Cannot find {} on the pkg-config search path. Consider installing the library for your system (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add the directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.: PKG_CONFIG_PATH=<blah> cargo build ", package_name );<|fim▁hole|> std::io::stderr().write_all(err_msg.as_bytes()).unwrap(); std::process::exit(output.status.code().unwrap()); } } Err(e) => panic!("Unhandled error: {:?}", e), }; }<|fim▁end|>
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Store, StoreModule } from '@ngrx/store'; import { AppComponent } from './app.component'; import { Child } from './child.component'; import { Child2 } from './child2.component';<|fim▁hole|> imports: [ BrowserModule, StoreModule.provideStore({appState}) ], declarations: [ AppComponent, Child, Child2 ], bootstrap: [ AppComponent ] }) export class AppModule { }<|fim▁end|>
import { appState } from './reducer.appstate'; @NgModule({
<|file_name|>test_sensor.py<|end_file_name|><|fim▁begin|>"""Test zha sensor.""" from unittest import mock import pytest import zigpy.zcl.clusters.general as general import zigpy.zcl.clusters.homeautomation as homeautomation import zigpy.zcl.clusters.measurement as measurement import zigpy.zcl.clusters.smartenergy as smartenergy from homeassistant.components.sensor import DOMAIN import homeassistant.config as config_util from homeassistant.const import ( ATTR_UNIT_OF_MEASUREMENT, CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_IMPERIAL, CONF_UNIT_SYSTEM_METRIC, POWER_WATT, STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, UNIT_PERCENTAGE, ) from homeassistant.helpers import restore_state from homeassistant.util import dt as dt_util from .common import ( async_enable_traffic, async_test_rejoin, find_entity_id, send_attribute_report, send_attributes_report, ) async def async_test_humidity(hass, cluster, entity_id): """Test humidity sensor.""" await send_attributes_report(hass, cluster, {1: 1, 0: 1000, 2: 100}) assert_state(hass, entity_id, "10.0", UNIT_PERCENTAGE) async def async_test_temperature(hass, cluster, entity_id): """Test temperature sensor.""" await send_attributes_report(hass, cluster, {1: 1, 0: 2900, 2: 100}) assert_state(hass, entity_id, "29.0", TEMP_CELSIUS) async def async_test_pressure(hass, cluster, entity_id): """Test pressure sensor.""" await send_attributes_report(hass, cluster, {1: 1, 0: 1000, 2: 10000}) assert_state(hass, entity_id, "1000", "hPa") await send_attributes_report(hass, cluster, {0: 1000, 20: -1, 16: 10000}) assert_state(hass, entity_id, "1000", "hPa") async def async_test_illuminance(hass, cluster, entity_id): """Test illuminance sensor.""" await send_attributes_report(hass, cluster, {1: 1, 0: 10, 2: 20}) assert_state(hass, entity_id, "1.0", "lx")<|fim▁hole|>async def async_test_metering(hass, cluster, entity_id): """Test metering sensor.""" await send_attributes_report(hass, cluster, {1025: 1, 1024: 12345, 1026: 100}) assert_state(hass, entity_id, "12345.0", "unknown") async def async_test_electrical_measurement(hass, cluster, entity_id): """Test electrical measurement sensor.""" with mock.patch( ( "homeassistant.components.zha.core.channels.homeautomation" ".ElectricalMeasurementChannel.divisor" ), new_callable=mock.PropertyMock, ) as divisor_mock: divisor_mock.return_value = 1 await send_attributes_report(hass, cluster, {0: 1, 1291: 100, 10: 1000}) assert_state(hass, entity_id, "100", POWER_WATT) await send_attributes_report(hass, cluster, {0: 1, 1291: 99, 10: 1000}) assert_state(hass, entity_id, "99", POWER_WATT) divisor_mock.return_value = 10 await send_attributes_report(hass, cluster, {0: 1, 1291: 1000, 10: 5000}) assert_state(hass, entity_id, "100", POWER_WATT) await send_attributes_report(hass, cluster, {0: 1, 1291: 99, 10: 5000}) assert_state(hass, entity_id, "9.9", POWER_WATT) @pytest.mark.parametrize( "cluster_id, test_func, report_count", ( (measurement.RelativeHumidity.cluster_id, async_test_humidity, 1), (measurement.TemperatureMeasurement.cluster_id, async_test_temperature, 1), (measurement.PressureMeasurement.cluster_id, async_test_pressure, 1), (measurement.IlluminanceMeasurement.cluster_id, async_test_illuminance, 1), (smartenergy.Metering.cluster_id, async_test_metering, 1), ( homeautomation.ElectricalMeasurement.cluster_id, async_test_electrical_measurement, 1, ), ), ) async def test_sensor( hass, zigpy_device_mock, zha_device_joined_restored, cluster_id, test_func, report_count, ): """Test zha sensor platform.""" zigpy_device = zigpy_device_mock( { 1: { "in_clusters": [cluster_id, general.Basic.cluster_id], "out_cluster": [], "device_type": 0x0000, } } ) cluster = zigpy_device.endpoints[1].in_clusters[cluster_id] zha_device = await zha_device_joined_restored(zigpy_device) entity_id = await find_entity_id(DOMAIN, zha_device, hass) await async_enable_traffic(hass, [zha_device], enabled=False) await hass.async_block_till_done() # ensure the sensor entity was created assert hass.states.get(entity_id).state == STATE_UNAVAILABLE # allow traffic to flow through the gateway and devices await async_enable_traffic(hass, [zha_device]) # test that the sensor now have a state of unknown assert hass.states.get(entity_id).state == STATE_UNKNOWN # test sensor associated logic await test_func(hass, cluster, entity_id) # test rejoin await async_test_rejoin(hass, zigpy_device, [cluster], (report_count,)) def assert_state(hass, entity_id, state, unit_of_measurement): """Check that the state is what is expected. This is used to ensure that the logic in each sensor class handled the attribute report it received correctly. """ hass_state = hass.states.get(entity_id) assert hass_state.state == state assert hass_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == unit_of_measurement @pytest.fixture def hass_ms(hass): """Hass instance with measurement system.""" async def _hass_ms(meas_sys): await config_util.async_process_ha_core_config( hass, {CONF_UNIT_SYSTEM: meas_sys} ) await hass.async_block_till_done() return hass return _hass_ms @pytest.fixture def core_rs(hass_storage): """Core.restore_state fixture.""" def _storage(entity_id, uom, state): now = dt_util.utcnow().isoformat() hass_storage[restore_state.STORAGE_KEY] = { "version": restore_state.STORAGE_VERSION, "key": restore_state.STORAGE_KEY, "data": [ { "state": { "entity_id": entity_id, "state": str(state), "attributes": {ATTR_UNIT_OF_MEASUREMENT: uom}, "last_changed": now, "last_updated": now, "context": { "id": "3c2243ff5f30447eb12e7348cfd5b8ff", "user_id": None, }, }, "last_seen": now, } ], } return return _storage @pytest.mark.parametrize( "uom, raw_temp, expected, restore", [ (TEMP_CELSIUS, 2900, 29, False), (TEMP_CELSIUS, 2900, 29, True), (TEMP_FAHRENHEIT, 2900, 84, False), (TEMP_FAHRENHEIT, 2900, 84, True), ], ) async def test_temp_uom( uom, raw_temp, expected, restore, hass_ms, core_rs, zigpy_device_mock, zha_device_restored, ): """Test zha temperature sensor unit of measurement.""" entity_id = "sensor.fake1026_fakemodel1026_004f3202_temperature" if restore: core_rs(entity_id, uom, state=(expected - 2)) hass = await hass_ms( CONF_UNIT_SYSTEM_METRIC if uom == TEMP_CELSIUS else CONF_UNIT_SYSTEM_IMPERIAL ) zigpy_device = zigpy_device_mock( { 1: { "in_clusters": [ measurement.TemperatureMeasurement.cluster_id, general.Basic.cluster_id, ], "out_cluster": [], "device_type": 0x0000, } } ) cluster = zigpy_device.endpoints[1].temperature zha_device = await zha_device_restored(zigpy_device) entity_id = await find_entity_id(DOMAIN, zha_device, hass) if not restore: await async_enable_traffic(hass, [zha_device], enabled=False) assert hass.states.get(entity_id).state == STATE_UNAVAILABLE # allow traffic to flow through the gateway and devices await async_enable_traffic(hass, [zha_device]) # test that the sensors now have a state of unknown if not restore: assert hass.states.get(entity_id).state == STATE_UNKNOWN await send_attribute_report(hass, cluster, 0, raw_temp) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert round(float(state.state)) == expected assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == uom async def test_electrical_measurement_init( hass, zigpy_device_mock, zha_device_joined, ): """Test proper initialization of the electrical measurement cluster.""" cluster_id = homeautomation.ElectricalMeasurement.cluster_id zigpy_device = zigpy_device_mock( { 1: { "in_clusters": [cluster_id, general.Basic.cluster_id], "out_cluster": [], "device_type": 0x0000, } } ) cluster = zigpy_device.endpoints[1].in_clusters[cluster_id] zha_device = await zha_device_joined(zigpy_device) entity_id = await find_entity_id(DOMAIN, zha_device, hass) # allow traffic to flow through the gateway and devices await async_enable_traffic(hass, [zha_device]) # test that the sensor now have a state of unknown assert hass.states.get(entity_id).state == STATE_UNKNOWN await send_attributes_report(hass, cluster, {0: 1, 1291: 100, 10: 1000}) assert int(hass.states.get(entity_id).state) == 100 channel = zha_device.channels.pools[0].all_channels["1:0x0b04"] assert channel.divisor == 1 assert channel.multiplier == 1 # update power divisor await send_attributes_report(hass, cluster, {0: 1, 1291: 20, 0x0403: 5, 10: 1000}) assert channel.divisor == 5 assert channel.multiplier == 1 assert hass.states.get(entity_id).state == "4.0" await send_attributes_report(hass, cluster, {0: 1, 1291: 30, 0x0605: 10, 10: 1000}) assert channel.divisor == 10 assert channel.multiplier == 1 assert hass.states.get(entity_id).state == "3.0" # update power multiplier await send_attributes_report(hass, cluster, {0: 1, 1291: 20, 0x0402: 6, 10: 1000}) assert channel.divisor == 10 assert channel.multiplier == 6 assert hass.states.get(entity_id).state == "12.0" await send_attributes_report(hass, cluster, {0: 1, 1291: 30, 0x0604: 20, 10: 1000}) assert channel.divisor == 10 assert channel.multiplier == 20 assert hass.states.get(entity_id).state == "60.0"<|fim▁end|>
<|file_name|>factory.py<|end_file_name|><|fim▁begin|>#-*- coding: ISO-8859-1 -*- # pysqlite2/test/factory.py: tests for the various factories in pysqlite # # Copyright (C) 2005-2007 Gerhard Häring <[email protected]> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import unittest import sqlite3 as sqlite class MyConnection(sqlite.Connection): def __init__(self, *args, **kwargs): sqlite.Connection.__init__(self, *args, **kwargs) def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class MyCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = dict_factory class ConnectionFactoryTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:", factory=MyConnection) def tearDown(self): self.con.close() def CheckIsInstance(self): self.assertTrue(isinstance(self.con, MyConnection), "connection is not instance of MyConnection") class CursorFactoryTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:")<|fim▁hole|> def CheckIsInstance(self): cur = self.con.cursor(factory=MyCursor) self.assertTrue(isinstance(cur, MyCursor), "cursor is not instance of MyCursor") class RowFactoryTestsBackwardsCompat(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") def CheckIsProducedByFactory(self): cur = self.con.cursor(factory=MyCursor) cur.execute("select 4+5 as foo") row = cur.fetchone() self.assertTrue(isinstance(row, dict), "row is not instance of dict") cur.close() def tearDown(self): self.con.close() class RowFactoryTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") def CheckCustomFactory(self): self.con.row_factory = lambda cur, row: list(row) row = self.con.execute("select 1, 2").fetchone() self.assertTrue(isinstance(row, list), "row is not instance of list") def CheckSqliteRowIndex(self): self.con.row_factory = sqlite.Row row = self.con.execute("select 1 as a, 2 as b").fetchone() self.assertTrue(isinstance(row, sqlite.Row), "row is not instance of sqlite.Row") col1, col2 = row["a"], row["b"] self.assertTrue(col1 == 1, "by name: wrong result for column 'a'") self.assertTrue(col2 == 2, "by name: wrong result for column 'a'") col1, col2 = row["A"], row["B"] self.assertTrue(col1 == 1, "by name: wrong result for column 'A'") self.assertTrue(col2 == 2, "by name: wrong result for column 'B'") col1, col2 = row[0], row[1] self.assertTrue(col1 == 1, "by index: wrong result for column 0") self.assertTrue(col2 == 2, "by index: wrong result for column 1") def CheckSqliteRowIter(self): """Checks if the row object is iterable""" self.con.row_factory = sqlite.Row row = self.con.execute("select 1 as a, 2 as b").fetchone() for col in row: pass def CheckSqliteRowAsTuple(self): """Checks if the row object can be converted to a tuple""" self.con.row_factory = sqlite.Row row = self.con.execute("select 1 as a, 2 as b").fetchone() t = tuple(row) def CheckSqliteRowAsDict(self): """Checks if the row object can be correctly converted to a dictionary""" self.con.row_factory = sqlite.Row row = self.con.execute("select 1 as a, 2 as b").fetchone() d = dict(row) self.assertEqual(d["a"], row["a"]) self.assertEqual(d["b"], row["b"]) def CheckSqliteRowHashCmp(self): """Checks if the row object compares and hashes correctly""" self.con.row_factory = sqlite.Row row_1 = self.con.execute("select 1 as a, 2 as b").fetchone() row_2 = self.con.execute("select 1 as a, 2 as b").fetchone() row_3 = self.con.execute("select 1 as a, 3 as b").fetchone() self.assertTrue(row_1 == row_1) self.assertTrue(row_1 == row_2) self.assertTrue(row_2 != row_3) self.assertFalse(row_1 != row_1) self.assertFalse(row_1 != row_2) self.assertFalse(row_2 == row_3) self.assertEqual(row_1, row_2) self.assertEqual(hash(row_1), hash(row_2)) self.assertNotEqual(row_1, row_3) self.assertNotEqual(hash(row_1), hash(row_3)) def tearDown(self): self.con.close() class TextFactoryTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") def CheckUnicode(self): austria = "Österreich" row = self.con.execute("select ?", (austria,)).fetchone() self.assertTrue(type(row[0]) == str, "type of row[0] must be unicode") def CheckString(self): self.con.text_factory = bytes austria = "Österreich" row = self.con.execute("select ?", (austria,)).fetchone() self.assertTrue(type(row[0]) == bytes, "type of row[0] must be bytes") self.assertTrue(row[0] == austria.encode("utf-8"), "column must equal original data in UTF-8") def CheckCustom(self): self.con.text_factory = lambda x: str(x, "utf-8", "ignore") austria = "Österreich" row = self.con.execute("select ?", (austria,)).fetchone() self.assertTrue(type(row[0]) == str, "type of row[0] must be unicode") self.assertTrue(row[0].endswith("reich"), "column must contain original data") def CheckOptimizedUnicode(self): self.con.text_factory = sqlite.OptimizedUnicode austria = "Österreich" germany = "Deutchland" a_row = self.con.execute("select ?", (austria,)).fetchone() d_row = self.con.execute("select ?", (germany,)).fetchone() self.assertTrue(type(a_row[0]) == str, "type of non-ASCII row must be str") self.assertTrue(type(d_row[0]) == str, "type of ASCII-only row must be str") def tearDown(self): self.con.close() class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.execute("create table test (value text)") self.con.execute("insert into test (value) values (?)", ("a\x00b",)) def CheckString(self): # text_factory defaults to str row = self.con.execute("select value from test").fetchone() self.assertIs(type(row[0]), str) self.assertEqual(row[0], "a\x00b") def CheckBytes(self): self.con.text_factory = bytes row = self.con.execute("select value from test").fetchone() self.assertIs(type(row[0]), bytes) self.assertEqual(row[0], b"a\x00b") def CheckBytearray(self): self.con.text_factory = bytearray row = self.con.execute("select value from test").fetchone() self.assertIs(type(row[0]), bytearray) self.assertEqual(row[0], b"a\x00b") def CheckCustom(self): # A custom factory should receive a bytes argument self.con.text_factory = lambda x: x row = self.con.execute("select value from test").fetchone() self.assertIs(type(row[0]), bytes) self.assertEqual(row[0], b"a\x00b") def tearDown(self): self.con.close() def suite(): connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check") cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check") row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check") row_suite = unittest.makeSuite(RowFactoryTests, "Check") text_suite = unittest.makeSuite(TextFactoryTests, "Check") text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check") return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite)) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()<|fim▁end|>
def tearDown(self): self.con.close()
<|file_name|>63880000.jsonp.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
jsonp({"cep":"63880000","cidade":"Domingos da Costa","uf":"CE","estado":"Cear\u00e1"});
<|file_name|>test_smbfs.py<|end_file_name|><|fim▁begin|># Copyright 2014 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import os import mock from cinder import exception from cinder.image import image_utils from cinder import test from cinder.volume.drivers import smbfs class SmbFsTestCase(test.TestCase): _FAKE_SHARE = '//1.2.3.4/share1' _FAKE_MNT_BASE = '/mnt' _FAKE_VOLUME_NAME = 'volume-4f711859-4928-4cb7-801a-a50c37ceaccc' _FAKE_TOTAL_SIZE = '2048' _FAKE_TOTAL_AVAILABLE = '1024' _FAKE_TOTAL_ALLOCATED = 1024 _FAKE_VOLUME = {'id': '4f711859-4928-4cb7-801a-a50c37ceaccc', 'size': 1, 'provider_location': _FAKE_SHARE, 'name': _FAKE_VOLUME_NAME, 'status': 'available'} _FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, 'fake_hash') _FAKE_VOLUME_PATH = os.path.join(_FAKE_MNT_POINT, _FAKE_VOLUME_NAME) _FAKE_SNAPSHOT_ID = '5g811859-4928-4cb7-801a-a50c37ceacba' _FAKE_SNAPSHOT = {'id': _FAKE_SNAPSHOT_ID, 'volume': _FAKE_VOLUME, 'status': 'available', 'volume_size': 1} _FAKE_SNAPSHOT_PATH = ( _FAKE_VOLUME_PATH + '-snapshot' + _FAKE_SNAPSHOT_ID) _FAKE_SHARE_OPTS = '-o username=Administrator,password=12345' _FAKE_OPTIONS_DICT = {'username': 'Administrator', 'password': '12345'} _FAKE_LISTDIR = [_FAKE_VOLUME_NAME, _FAKE_VOLUME_NAME + '.vhd', _FAKE_VOLUME_NAME + '.vhdx', 'fake_folder'] _FAKE_SMBFS_CONFIG = mock.MagicMock() _FAKE_SMBFS_CONFIG.smbfs_oversub_ratio = 2 _FAKE_SMBFS_CONFIG.smbfs_used_ratio = 0.5 _FAKE_SMBFS_CONFIG.smbfs_shares_config = '/fake/config/path' _FAKE_SMBFS_CONFIG.smbfs_default_volume_format = 'raw' _FAKE_SMBFS_CONFIG.smbfs_sparsed_volumes = False def setUp(self): super(SmbFsTestCase, self).setUp() self._smbfs_driver = smbfs.SmbfsDriver(configuration=mock.Mock()) self._smbfs_driver._remotefsclient = mock.Mock() self._smbfs_driver._local_volume_dir = mock.Mock( return_value=self._FAKE_MNT_POINT) self._smbfs_driver._execute = mock.Mock() self._smbfs_driver.base = self._FAKE_MNT_BASE def test_delete_volume(self): drv = self._smbfs_driver fake_vol_info = self._FAKE_VOLUME_PATH + '.info' drv._ensure_share_mounted = mock.MagicMock() fake_ensure_mounted = drv._ensure_share_mounted drv._local_volume_dir = mock.Mock( return_value=self._FAKE_MNT_POINT) drv.get_active_image_from_info = mock.Mock( return_value=self._FAKE_VOLUME_NAME) drv._delete = mock.Mock() drv._local_path_volume_info = mock.Mock( return_value=fake_vol_info) with mock.patch('os.path.exists', lambda x: True): drv.delete_volume(self._FAKE_VOLUME) fake_ensure_mounted.assert_called_once_with(self._FAKE_SHARE) drv._delete.assert_any_call( self._FAKE_VOLUME_PATH) drv._delete.assert_any_call(fake_vol_info) @mock.patch('os.path.exists') @mock.patch.object(image_utils, 'check_qemu_img_version') def _test_setup(self, mock_check_qemu_img_version, mock_exists, config, share_config_exists=True): mock_exists.return_value = share_config_exists fake_ensure_mounted = mock.MagicMock() self._smbfs_driver._ensure_shares_mounted = fake_ensure_mounted self._smbfs_driver.configuration = config if not (config.smbfs_shares_config and share_config_exists and config.smbfs_oversub_ratio > 0 and 0 <= config.smbfs_used_ratio <= 1): self.assertRaises(exception.SmbfsException, self._smbfs_driver.do_setup, None) else: self._smbfs_driver.do_setup(mock.sentinel.context) mock_check_qemu_img_version.assert_called_once_with() self.assertEqual(self._smbfs_driver.shares, {}) fake_ensure_mounted.assert_called_once_with() def test_setup_missing_shares_config_option(self): fake_config = copy.copy(self._FAKE_SMBFS_CONFIG) fake_config.smbfs_shares_config = None self._test_setup(config=fake_config, share_config_exists=False) def test_setup_missing_shares_config_file(self): self._test_setup(config=self._FAKE_SMBFS_CONFIG, share_config_exists=False) def test_setup_invlid_oversub_ratio(self): fake_config = copy.copy(self._FAKE_SMBFS_CONFIG) fake_config.smbfs_oversub_ratio = -1 self._test_setup(config=fake_config) def test_setup_invalid_used_ratio(self): fake_config = copy.copy(self._FAKE_SMBFS_CONFIG) fake_config.smbfs_used_ratio = -1 self._test_setup(config=fake_config) def _test_create_volume(self, volume_exists=False, volume_format=None): fake_method = mock.MagicMock() self._smbfs_driver.configuration = copy.copy(self._FAKE_SMBFS_CONFIG) self._smbfs_driver._set_rw_permissions_for_all = mock.MagicMock() fake_set_permissions = self._smbfs_driver._set_rw_permissions_for_all self._smbfs_driver.get_volume_format = mock.MagicMock() windows_image_format = False fake_vol_path = self._FAKE_VOLUME_PATH self._smbfs_driver.get_volume_format.return_value = volume_format if volume_format: if volume_format in ('vhd', 'vhdx'): windows_image_format = volume_format if volume_format == 'vhd': windows_image_format = 'vpc' method = '_create_windows_image' fake_vol_path += '.' + volume_format else: method = '_create_%s_file' % volume_format if volume_format == 'sparsed': self._smbfs_driver.configuration.smbfs_sparsed_volumes = ( True) else: method = '_create_regular_file' setattr(self._smbfs_driver, method, fake_method) with mock.patch('os.path.exists', new=lambda x: volume_exists): if volume_exists: self.assertRaises(exception.InvalidVolume, self._smbfs_driver._do_create_volume, self._FAKE_VOLUME) return self._smbfs_driver._do_create_volume(self._FAKE_VOLUME) if windows_image_format: fake_method.assert_called_once_with( fake_vol_path, self._FAKE_VOLUME['size'], windows_image_format) else: fake_method.assert_called_once_with( fake_vol_path, self._FAKE_VOLUME['size']) fake_set_permissions.assert_called_once_with(fake_vol_path) def test_create_existing_volume(self): self._test_create_volume(volume_exists=True) def test_create_vhdx(self): self._test_create_volume(volume_format='vhdx') def test_create_qcow2(self): self._test_create_volume(volume_format='qcow2') def test_create_sparsed(self): self._test_create_volume(volume_format='sparsed') def test_create_regular(self): self._test_create_volume() def _test_find_share(self, existing_mounted_shares=True, eligible_shares=True): if existing_mounted_shares: mounted_shares = ('fake_share1', 'fake_share2', 'fake_share3') else: mounted_shares = None self._smbfs_driver._mounted_shares = mounted_shares self._smbfs_driver._is_share_eligible = mock.Mock( return_value=eligible_shares) fake_capacity_info = ((2, 1, 5), (2, 1, 4), (2, 1, 1)) self._smbfs_driver._get_capacity_info = mock.Mock( side_effect=fake_capacity_info) if not mounted_shares: self.assertRaises(exception.SmbfsNoSharesMounted, self._smbfs_driver._find_share, self._FAKE_VOLUME['size']) elif not eligible_shares: self.assertRaises(exception.SmbfsNoSuitableShareFound, self._smbfs_driver._find_share, self._FAKE_VOLUME['size']) else: ret_value = self._smbfs_driver._find_share( self._FAKE_VOLUME['size']) # The eligible share with the minimum allocated space # will be selected self.assertEqual(ret_value, 'fake_share3') def test_find_share(self): self._test_find_share() def test_find_share_missing_mounted_shares(self): self._test_find_share(existing_mounted_shares=False) def test_find_share_missing_eligible_shares(self): self._test_find_share(eligible_shares=False) def _test_is_share_eligible(self, capacity_info, volume_size): self._smbfs_driver._get_capacity_info = mock.Mock( return_value=[float(x << 30) for x in capacity_info]) self._smbfs_driver.configuration = self._FAKE_SMBFS_CONFIG return self._smbfs_driver._is_share_eligible(self._FAKE_SHARE, volume_size) def test_share_volume_above_used_ratio(self): fake_capacity_info = (4, 1, 1) fake_volume_size = 2 ret_value = self._test_is_share_eligible(fake_capacity_info, fake_volume_size) self.assertFalse(ret_value) def test_eligible_share(self): fake_capacity_info = (4, 4, 0) fake_volume_size = 1 ret_value = self._test_is_share_eligible(fake_capacity_info, fake_volume_size) self.assertTrue(ret_value) def test_share_volume_above_oversub_ratio(self): fake_capacity_info = (4, 4, 7) fake_volume_size = 2 ret_value = self._test_is_share_eligible(fake_capacity_info, fake_volume_size) self.assertFalse(ret_value) def test_share_reserved_above_oversub_ratio(self): fake_capacity_info = (4, 4, 10) fake_volume_size = 1 ret_value = self._test_is_share_eligible(fake_capacity_info, fake_volume_size) self.assertFalse(ret_value) def test_parse_options(self): (opt_list, opt_dict) = self._smbfs_driver.parse_options( self._FAKE_SHARE_OPTS) expected_ret = ([], self._FAKE_OPTIONS_DICT) self.assertEqual(expected_ret, (opt_list, opt_dict)) def test_parse_credentials(self): fake_smb_options = r'-o user=MyDomain\Administrator,noperm' expected_flags = '-o username=Administrator,noperm' flags = self._smbfs_driver.parse_credentials(fake_smb_options) self.assertEqual(expected_flags, flags) @mock.patch.object(smbfs.SmbfsDriver, '_get_local_volume_path_template') @mock.patch.object(smbfs.SmbfsDriver, '_lookup_local_volume_path') @mock.patch.object(smbfs.SmbfsDriver, 'get_volume_format') def _test_get_volume_path(self, mock_get_volume_format, mock_lookup_volume, mock_get_path_template, volume_exists=True, volume_format='raw'): drv = self._smbfs_driver mock_get_path_template.return_value = self._FAKE_VOLUME_PATH expected_vol_path = self._FAKE_VOLUME_PATH if volume_format in (drv._DISK_FORMAT_VHD, drv._DISK_FORMAT_VHDX): expected_vol_path += '.' + volume_format mock_lookup_volume.return_value = ( expected_vol_path if volume_exists else None) mock_get_volume_format.return_value = volume_format ret_val = drv.local_path(self._FAKE_VOLUME) if volume_exists: self.assertFalse(mock_get_volume_format.called) else: mock_get_volume_format.assert_called_once_with(self._FAKE_VOLUME) self.assertEqual(expected_vol_path, ret_val) def test_get_existing_volume_path(self): self._test_get_volume_path() def test_get_new_raw_volume_path(self): self._test_get_volume_path(volume_exists=False) def test_get_new_vhd_volume_path(self): self._test_get_volume_path(volume_exists=False, volume_format='vhd') @mock.patch.object(smbfs.SmbfsDriver, '_local_volume_dir') def test_get_local_volume_path_template(self, mock_get_local_dir): mock_get_local_dir.return_value = self._FAKE_MNT_POINT ret_val = self._smbfs_driver._get_local_volume_path_template( self._FAKE_VOLUME) self.assertEqual(self._FAKE_VOLUME_PATH, ret_val) @mock.patch('os.path.exists') def test_lookup_local_volume_path(self, mock_exists): expected_path = self._FAKE_VOLUME_PATH + '.vhdx' mock_exists.side_effect = lambda x: x == expected_path ret_val = self._smbfs_driver._lookup_local_volume_path( self._FAKE_VOLUME_PATH) possible_paths = [self._FAKE_VOLUME_PATH + ext for ext in ('', '.vhd', '.vhdx')] mock_exists.assert_has_calls( [mock.call(path) for path in possible_paths]) self.assertEqual(expected_path, ret_val) @mock.patch.object(smbfs.SmbfsDriver, '_get_local_volume_path_template') @mock.patch.object(smbfs.SmbfsDriver, '_lookup_local_volume_path') @mock.patch.object(smbfs.SmbfsDriver, '_qemu_img_info') @mock.patch.object(smbfs.SmbfsDriver, '_get_volume_format_spec') def _mock_get_volume_format(self, mock_get_format_spec, mock_qemu_img_info, mock_lookup_volume, mock_get_path_template, qemu_format=False, volume_format='raw', volume_exists=True): mock_get_path_template.return_value = self._FAKE_VOLUME_PATH mock_lookup_volume.return_value = ( self._FAKE_VOLUME_PATH if volume_exists else None) mock_qemu_img_info.return_value.file_format = volume_format mock_get_format_spec.return_value = volume_format ret_val = self._smbfs_driver.get_volume_format(self._FAKE_VOLUME, qemu_format) if volume_exists: mock_qemu_img_info.assert_called_once_with(self._FAKE_VOLUME_PATH, self._FAKE_VOLUME_NAME) self.assertFalse(mock_get_format_spec.called) else: mock_get_format_spec.assert_called_once_with(self._FAKE_VOLUME) self.assertFalse(mock_qemu_img_info.called) return ret_val def test_get_existing_raw_volume_format(self): fmt = self._mock_get_volume_format() self.assertEqual(fmt, 'raw') def test_get_new_vhd_volume_format(self): expected_fmt = 'vhd' fmt = self._mock_get_volume_format(volume_format=expected_fmt, volume_exists=False) self.assertEqual(expected_fmt, fmt) def test_get_new_vhd_legacy_volume_format(self): img_fmt = 'vhd' expected_fmt = 'vpc' ret_val = self._mock_get_volume_format(volume_format=img_fmt, volume_exists=False, qemu_format=True) self.assertEqual(expected_fmt, ret_val) def test_initialize_connection(self): self._smbfs_driver.get_active_image_from_info = mock.Mock( return_value=self._FAKE_VOLUME_NAME) self._smbfs_driver._get_mount_point_base = mock.Mock( return_value=self._FAKE_MNT_BASE) self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS} self._smbfs_driver._qemu_img_info = mock.Mock( return_value=mock.Mock(file_format='raw')) fake_data = {'export': self._FAKE_SHARE, 'format': 'raw', 'name': self._FAKE_VOLUME_NAME, 'options': self._FAKE_SHARE_OPTS} expected = { 'driver_volume_type': 'smbfs', 'data': fake_data, 'mount_point_base': self._FAKE_MNT_BASE} ret_val = self._smbfs_driver.initialize_connection( self._FAKE_VOLUME, None) self.assertEqual(expected, ret_val) def _test_extend_volume(self, extend_failed=False, image_format='raw'): drv = self._smbfs_driver drv.local_path = mock.Mock( return_value=self._FAKE_VOLUME_PATH) drv._check_extend_volume_support = mock.Mock( return_value=True) drv._is_file_size_equal = mock.Mock( return_value=not extend_failed) drv._qemu_img_info = mock.Mock( return_value=mock.Mock(file_format=image_format)) drv._delete = mock.Mock() with mock.patch.object(image_utils, 'resize_image') as fake_resize, \ mock.patch.object(image_utils, 'convert_image') as \ fake_convert: if extend_failed: self.assertRaises(exception.ExtendVolumeError, drv._extend_volume, self._FAKE_VOLUME, mock.sentinel.new_size) else: drv._extend_volume( self._FAKE_VOLUME, mock.sentinel.new_size) if image_format in (drv._DISK_FORMAT_VHDX, drv._DISK_FORMAT_VHD_LEGACY): fake_tmp_path = self._FAKE_VOLUME_PATH + '.tmp' fake_convert.assert_any_call(self._FAKE_VOLUME_PATH, fake_tmp_path, 'raw') fake_resize.assert_called_once_with( fake_tmp_path, mock.sentinel.new_size) fake_convert.assert_any_call(fake_tmp_path, self._FAKE_VOLUME_PATH, image_format) else: fake_resize.assert_called_once_with( self._FAKE_VOLUME_PATH, mock.sentinel.new_size) def test_extend_volume(self): self._test_extend_volume() def test_extend_volume_failed(self): self._test_extend_volume(extend_failed=True) def test_extend_vhd_volume(self): self._test_extend_volume(image_format='vpc') def _test_check_extend_support(self, has_snapshots=False, is_eligible=True): self._smbfs_driver.local_path = mock.Mock( return_value=self._FAKE_VOLUME_PATH) if has_snapshots: active_file_path = self._FAKE_SNAPSHOT_PATH else: active_file_path = self._FAKE_VOLUME_PATH self._smbfs_driver.get_active_image_from_info = mock.Mock( return_value=active_file_path) self._smbfs_driver._is_share_eligible = mock.Mock( return_value=is_eligible) if has_snapshots: self.assertRaises(exception.InvalidVolume, self._smbfs_driver._check_extend_volume_support, self._FAKE_VOLUME, 2) elif not is_eligible: self.assertRaises(exception.ExtendVolumeError, self._smbfs_driver._check_extend_volume_support, self._FAKE_VOLUME, 2) else: self._smbfs_driver._check_extend_volume_support( self._FAKE_VOLUME, 2) self._smbfs_driver._is_share_eligible.assert_called_once_with( self._FAKE_SHARE, 1) def test_check_extend_support(self): self._test_check_extend_support() def test_check_extend_volume_with_snapshots(self): self._test_check_extend_support(has_snapshots=True) def test_check_extend_volume_uneligible_share(self): self._test_check_extend_support(is_eligible=False) def test_create_volume_from_in_use_snapshot(self): fake_snapshot = {'status': 'in-use'} self.assertRaises( exception.InvalidSnapshot, self._smbfs_driver.create_volume_from_snapshot, self._FAKE_VOLUME, fake_snapshot) def test_copy_volume_from_snapshot(self): drv = self._smbfs_driver fake_volume_info = {self._FAKE_SNAPSHOT_ID: 'fake_snapshot_file_name'} fake_img_info = mock.MagicMock() fake_img_info.backing_file = self._FAKE_VOLUME_NAME drv.get_volume_format = mock.Mock( return_value='raw') drv._local_path_volume_info = mock.Mock( return_value=self._FAKE_VOLUME_PATH + '.info') drv._local_volume_dir = mock.Mock( return_value=self._FAKE_MNT_POINT) drv._read_info_file = mock.Mock( return_value=fake_volume_info) drv._qemu_img_info = mock.Mock( return_value=fake_img_info) drv.local_path = mock.Mock( return_value=self._FAKE_VOLUME_PATH[:-1]) drv._extend_volume = mock.Mock() drv._set_rw_permissions_for_all = mock.Mock() with mock.patch.object(image_utils, 'convert_image') as ( fake_convert_image): drv._copy_volume_from_snapshot( self._FAKE_SNAPSHOT, self._FAKE_VOLUME, self._FAKE_VOLUME['size']) drv._extend_volume.assert_called_once_with( self._FAKE_VOLUME, self._FAKE_VOLUME['size']) fake_convert_image.assert_called_once_with( self._FAKE_VOLUME_PATH, self._FAKE_VOLUME_PATH[:-1], 'raw') def test_ensure_mounted(self): self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS} self._smbfs_driver._ensure_share_mounted(self._FAKE_SHARE) self._smbfs_driver._remotefsclient.mount.assert_called_once_with( self._FAKE_SHARE, self._FAKE_SHARE_OPTS.split()) def _test_copy_image_to_volume(self, wrong_size_after_fetch=False): drv = self._smbfs_driver vol_size_bytes = self._FAKE_VOLUME['size'] << 30 fake_img_info = mock.MagicMock() if wrong_size_after_fetch: fake_img_info.virtual_size = 2 * vol_size_bytes else: fake_img_info.virtual_size = vol_size_bytes drv.get_volume_format = mock.Mock( return_value=drv._DISK_FORMAT_VHDX) drv.local_path = mock.Mock( return_value=self._FAKE_VOLUME_PATH) drv._do_extend_volume = mock.Mock() drv.configuration = mock.MagicMock() drv.configuration.volume_dd_blocksize = ( mock.sentinel.block_size) with mock.patch.object(image_utils, 'fetch_to_volume_format') as \ fake_fetch, mock.patch.object(image_utils, 'qemu_img_info') as \ fake_qemu_img_info: fake_qemu_img_info.return_value = fake_img_info if wrong_size_after_fetch: self.assertRaises( exception.ImageUnacceptable, drv.copy_image_to_volume, mock.sentinel.context, self._FAKE_VOLUME, mock.sentinel.image_service, mock.sentinel.image_id) else: drv.copy_image_to_volume( mock.sentinel.context, self._FAKE_VOLUME, mock.sentinel.image_service, mock.sentinel.image_id) fake_fetch.assert_called_once_with( mock.sentinel.context, mock.sentinel.image_service, mock.sentinel.image_id, self._FAKE_VOLUME_PATH, drv._DISK_FORMAT_VHDX, mock.sentinel.block_size) drv._do_extend_volume.assert_called_once_with( self._FAKE_VOLUME_PATH, self._FAKE_VOLUME['size'], self._FAKE_VOLUME['name']) def test_copy_image_to_volume(self): self._test_copy_image_to_volume()<|fim▁hole|> def test_get_capacity_info(self): fake_block_size = 4096.0 fake_total_blocks = 1024 fake_avail_blocks = 512 fake_total_allocated = fake_total_blocks * fake_block_size fake_df = ('%s %s %s' % (fake_block_size, fake_total_blocks, fake_avail_blocks), None) fake_du = (str(fake_total_allocated), None) self._smbfs_driver._get_mount_point_for_share = mock.Mock( return_value=self._FAKE_MNT_POINT) self._smbfs_driver._execute = mock.Mock( side_effect=(fake_df, fake_du)) ret_val = self._smbfs_driver._get_capacity_info(self._FAKE_SHARE) expected = (fake_block_size * fake_total_blocks, fake_block_size * fake_avail_blocks, fake_total_allocated) self.assertEqual(expected, ret_val)<|fim▁end|>
def test_copy_image_to_volume_wrong_size_after_fetch(self): self._test_copy_image_to_volume(wrong_size_after_fetch=True)
<|file_name|>transform-requests.ts<|end_file_name|><|fim▁begin|>import { cloneRecordIdentity, equalRecordIdentities, recordDiffs, Record, RecordIdentity, RecordOperation, Transform, AddRecordOperation, RemoveRecordOperation, ReplaceAttributeOperation, ReplaceRecordOperation, AddToRelatedRecordsOperation, RemoveFromRelatedRecordsOperation, ReplaceRelatedRecordOperation, ReplaceRelatedRecordsOperation, buildTransform } from '@orbit/data'; import { clone, deepSet } from '@orbit/utils'; import JSONAPISource from '../jsonapi-source'; import { JSONAPIDocument } from '../jsonapi-document'; import { DeserializedDocument } from '../jsonapi-serializer'; import { RequestOptions, buildFetchSettings } from './request-settings'; export const TransformRequestProcessors = { addRecord(source: JSONAPISource, request) { const { serializer } = source; const record = request.record; const requestDoc: JSONAPIDocument = serializer.serializeDocument(record); const settings = buildFetchSettings(request, { method: 'POST', json: requestDoc }); return source.fetch(source.resourceURL(record.type), settings) .then((raw: JSONAPIDocument) => { let responseDoc: DeserializedDocument = serializer.deserializeDocument(raw); let updatedRecord: Record = <Record>responseDoc.data; let updateOps = recordDiffs(record, updatedRecord); if (updateOps.length > 0) { return [buildTransform(updateOps)]; } }); }, removeRecord(source: JSONAPISource, request) { const { type, id } = request.record; const settings = buildFetchSettings(request, { method: 'DELETE' }); return source.fetch(source.resourceURL(type, id), settings) .then(() => []); }, replaceRecord(source: JSONAPISource, request) { const record = request.record; const { type, id } = record; const requestDoc: JSONAPIDocument = source.serializer.serializeDocument(record); const settings = buildFetchSettings(request, { method: 'PATCH', json: requestDoc }); return source.fetch(source.resourceURL(type, id), settings) .then(() => []); }, addToRelatedRecords(source: JSONAPISource, request) { const { type, id } = request.record; const { relationship } = request; const json = { data: request.relatedRecords.map(r => source.serializer.resourceIdentity(r)) }; const settings = buildFetchSettings(request, { method: 'POST', json }); return source.fetch(source.resourceRelationshipURL(type, id, relationship), settings) .then(() => []);<|fim▁hole|> }, removeFromRelatedRecords(source: JSONAPISource, request) { const { type, id } = request.record; const { relationship } = request; const json = { data: request.relatedRecords.map(r => source.serializer.resourceIdentity(r)) }; const settings = buildFetchSettings(request, { method: 'DELETE', json }); return source.fetch(source.resourceRelationshipURL(type, id, relationship), settings) .then(() => []); }, replaceRelatedRecord(source: JSONAPISource, request) { const { type, id } = request.record; const { relationship, relatedRecord } = request; const json = { data: relatedRecord ? source.serializer.resourceIdentity(relatedRecord) : null }; const settings = buildFetchSettings(request, { method: 'PATCH', json }); return source.fetch(source.resourceRelationshipURL(type, id, relationship), settings) .then(() => []); }, replaceRelatedRecords(source: JSONAPISource, request) { const { type, id } = request.record; const { relationship, relatedRecords } = request; const json = { data: relatedRecords.map(r => source.serializer.resourceIdentity(r)) }; const settings = buildFetchSettings(request, { method: 'PATCH', json }); return source.fetch(source.resourceRelationshipURL(type, id, relationship), settings) .then(() => []); } }; export function getTransformRequests(source: JSONAPISource, transform: Transform) { const operations: RecordOperation[] = <RecordOperation[]>transform.operations; const requests = []; let prevRequest; const options = (transform.options && transform.options.sources && transform.options.sources[source.name]) || {}; transform.operations.forEach((operation: RecordOperation) => { let request; let newRequestNeeded = true; if (prevRequest && equalRecordIdentities(prevRequest.record, operation.record)) { if (operation.op === 'removeRecord') { newRequestNeeded = false; if (prevRequest.op !== 'removeRecord') { prevRequest = null; requests.pop(); } } else if (prevRequest.op === 'addRecord' || prevRequest.op === 'replaceRecord') { if (operation.op === 'replaceAttribute') { newRequestNeeded = false; replaceRecordAttribute(prevRequest.record, operation.attribute, operation.value); } else if (operation.op === 'replaceRelatedRecord') { newRequestNeeded = false; replaceRecordHasOne(prevRequest.record, operation.relationship, operation.relatedRecord); } else if (operation.op === 'replaceRelatedRecords') { newRequestNeeded = false; replaceRecordHasMany(prevRequest.record, operation.relationship, operation.relatedRecords); } } else if (prevRequest.op === 'addToRelatedRecords' && operation.op === 'addToRelatedRecords' && prevRequest.relationship === operation.relationship) { newRequestNeeded = false; prevRequest.relatedRecords.push(cloneRecordIdentity(operation.relatedRecord)); } } if (newRequestNeeded) { request = OperationToRequestMap[operation.op](operation); } if (request) { if (options.include) { request.include = options.include.join(','); } if (options.timeout) { request.timeout = options.timeout; } requests.push(request); prevRequest = request; } }); return requests; } const OperationToRequestMap = { addRecord(operation: AddRecordOperation) { return { op: 'addRecord', record: clone(operation.record) }; }, removeRecord(operation: RemoveRecordOperation) { return { op: 'removeRecord', record: cloneRecordIdentity(operation.record) }; }, replaceAttribute(operation: ReplaceAttributeOperation) { const record = cloneRecordIdentity(operation.record); replaceRecordAttribute(record, operation.attribute, operation.value); return { op: 'replaceRecord', record }; }, replaceRecord(operation: ReplaceRecordOperation) { return { op: 'replaceRecord', record: clone(operation.record) }; }, addToRelatedRecords(operation: AddToRelatedRecordsOperation) { return { op: 'addToRelatedRecords', record: cloneRecordIdentity(operation.record), relationship: operation.relationship, relatedRecords: [cloneRecordIdentity(operation.relatedRecord)] }; }, removeFromRelatedRecords(operation: RemoveFromRelatedRecordsOperation) { return { op: 'removeFromRelatedRecords', record: cloneRecordIdentity(operation.record), relationship: operation.relationship, relatedRecords: [cloneRecordIdentity(operation.relatedRecord)] }; }, replaceRelatedRecord(operation: ReplaceRelatedRecordOperation) { const record: Record = { type: operation.record.type, id: operation.record.id }; deepSet(record, ['relationships', operation.relationship, 'data'], operation.relatedRecord); return { op: 'replaceRecord', record }; }, replaceRelatedRecords(operation: ReplaceRelatedRecordsOperation) { const record = cloneRecordIdentity(operation.record); deepSet(record, ['relationships', operation.relationship, 'data'], operation.relatedRecords); return { op: 'replaceRecord', record }; } }; function replaceRecordAttribute(record: RecordIdentity, attribute: string, value: any) { deepSet(record, ['attributes', attribute], value); } function replaceRecordHasOne(record: RecordIdentity, relationship: string, relatedRecord: RecordIdentity) { deepSet(record, ['relationships', relationship, 'data'], relatedRecord ? cloneRecordIdentity(relatedRecord) : null); } function replaceRecordHasMany(record: RecordIdentity, relationship: string, relatedRecords: RecordIdentity[]) { deepSet(record, ['relationships', relationship, 'data'], relatedRecords.map(r => cloneRecordIdentity(r))); }<|fim▁end|>
<|file_name|>marimo.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time host = "10.211.55.6" port = 8888 host = "ch41l3ng3s.codegate.kr" port = 3333 r = remote(host,port) def sell(idx): r.recvuntil(">>") r.sendline("S") r.recvuntil(">>") r.sendline(str(idx)) r.recvuntil("?") r.sendline("S") def buy(size,name,pr): r.recvuntil(">>") r.sendline("B") r.recvuntil(">>") r.sendline(str(size)) r.recvuntil(">>") r.sendline("P") r.recvuntil(">>") r.sendline(name) r.recvuntil(">>") r.sendline(pr) def view(idx,profile=None): r.recvuntil(">>") r.sendline("V") r.recvuntil(">>") r.sendline(str(idx)) data = r.recvuntil(">>") if profile : r.sendline("M") r.recvuntil(">>") r.sendline(profile) return data else : r.sendline("B") return data <|fim▁hole|> r.sendline("show me the marimo") r.recvuntil(">>") r.sendline("Aa") r.recvuntil(">>") r.sendline("orange") time.sleep(1) sell(0) buy(1,"danogg","fuck") buy(1,"orange","fuck") time.sleep(3) data = view(0) ctime = int(data.split("current time :")[1].split("\n")[0].strip()) view(0,"a"*0x30 + p32(ctime) + p32(1) + p64(puts_got) + p64(puts_got)) r.recvuntil(">>") r.sendline("B") data = view(1) libc = u64(data.split("name :")[1].split("\n")[0].strip().ljust(8,"\x00")) - 0x6f690 print hex(libc) magic = libc + 0x45216 view(1,p64(magic)) r.interactive()<|fim▁end|>
puts_got = 0x603018 r.recvuntil(">>")
<|file_name|>doc.go<|end_file_name|><|fim▁begin|>// ts project doc.go /* ts document */<|fim▁hole|>package main<|fim▁end|>
<|file_name|>config.rs<|end_file_name|><|fim▁begin|>//! Defines configuration file format. use anyhow::{anyhow, Result}; use glob::Pattern; use lazy_static::lazy_static; use serde::Deserialize; use std::{ fs, io::Read, ops::{Deref, DerefMut}, path::{Path, PathBuf}, }; lazy_static! { static ref CONFIG_PATH: PathBuf = dirs::config_dir() .map(|config_path| config_path.join("rhq/config.toml")) .expect("failed to determine the configuration path"); } /// configuration load from config files #[derive(Deserialize)] struct RawConfigData { root: Option<String>, default_host: Option<String>, includes: Option<Vec<String>>, excludes: Option<Vec<String>>, } #[derive(Debug)] pub struct ConfigData { pub root_dir: PathBuf, pub host: String, pub include_dirs: Vec<PathBuf>, pub exclude_patterns: Vec<Pattern>, } impl ConfigData { fn from_raw(raw: RawConfigData) -> Result<Self> { let root_dir = raw.root.as_deref().unwrap_or("~/rhq"); let root_dir = crate::util::make_path_buf(root_dir)?; let include_dirs = raw .includes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|root| crate::util::make_path_buf(&root).ok()) .collect(); let exclude_patterns = raw .excludes .as_deref() .unwrap_or(&[]) .iter() .filter_map(|ex| { ::shellexpand::full(&ex) .ok() .map(|ex| ex.replace(r"\", "/")) .and_then(|ex| ::glob::Pattern::new(&ex).ok()) }) .collect(); let host = raw.default_host.unwrap_or_else(|| "github.com".to_owned()); Ok(Self { root_dir, host, include_dirs, exclude_patterns, }) } } #[derive(Debug)] pub struct Config { path: PathBuf, data: ConfigData, } impl Config { pub fn new(config_path: Option<&Path>) -> Result<Self> { let config_path: &Path = config_path.unwrap_or_else(|| &*CONFIG_PATH); if !config_path.is_file() { return Err(anyhow!( "Failed to load configuration file (config_path = {})", config_path.display() )); } let mut content = String::new(); fs::File::open(config_path)?.read_to_string(&mut content)?; let data = ::toml::from_str(&content)?; Ok(Config { path: config_path.into(), data: ConfigData::from_raw(data)?, }) } pub fn cache_dir(&self) -> PathBuf {<|fim▁hole|>impl Deref for Config { type Target = ConfigData; #[inline] fn deref(&self) -> &Self::Target { &self.data } } impl DerefMut for Config { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data } }<|fim▁end|>
self.root_dir.join(".cache.json") } }
<|file_name|>linkrefs.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit, Input} from '@angular/core'; import {Messages} from "../../messages"; import {AbstractRegisteredService} from "../../../domain/registered-service"; import {Data} from "../data"; @Component({ selector: 'app-linkrefs', templateUrl: './linkrefs.component.html' })<|fim▁hole|> constructor(public messages: Messages, public data: Data) { } ngOnInit() { } }<|fim▁end|>
export class LinkrefsComponent implements OnInit {
<|file_name|>SGDerivative.java<|end_file_name|><|fim▁begin|>/* <|fim▁hole|> * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.savitzkygolay; public final class SGDerivative { /** * This method returns the second smoothed derivative values of an array. * * @param double[] values * @param boolean is first derivative * @param int level of filter (1 - 12) * @return double[] derivative of values */ public static double[] calculateDerivative(double[] values, boolean firstDerivative, int levelOfFilter) { double[] derivative = new double[values.length]; int M = 0; for (int k = 0; k < derivative.length; k++) { // Determine boundaries if (k <= levelOfFilter) M = k; if (k + M > derivative.length - 1) M = derivative.length - (k + 1); // Perform derivative using Savitzky Golay coefficients for (int i = -M; i <= M; i++) { derivative[k] += values[k + i] * getSGCoefficient(M, i, firstDerivative); } // if ((Math.abs(derivative[k])) > maxValueDerivative) // maxValueDerivative = Math.abs(derivative[k]); } return derivative; } /** * This method return the Savitzky-Golay 2nd smoothed derivative coefficient * from an array * * @param M * @param signedC * @return */ private static Double getSGCoefficient(int M, int signedC, boolean firstDerivate) { int C = Math.abs(signedC), sign = 1; if (firstDerivate) { if (signedC < 0) sign = -1; return sign * SGCoefficients.SGCoefficientsFirstDerivativeQuartic[M][C]; } else { return SGCoefficients.SGCoefficientsSecondDerivative[M][C]; } } }<|fim▁end|>
* Copyright 2006-2015 The MZmine 2 Development Team
<|file_name|>issue-6117.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; enum Either<T, U> { Left(T), Right(U) } pub fn main() { match Left(@17) {<|fim▁hole|><|fim▁end|>
Right(()) => {} _ => {} } }
<|file_name|>69b85d86968f_init2.py<|end_file_name|><|fim▁begin|>"""init2 Revision ID: 69b85d86968f Revises: 9f83e778144c Create Date: 2017-09-25 17:36:03.015859 <|fim▁hole|>import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '69b85d86968f' down_revision = '9f83e778144c' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('about_me', sa.Text(), nullable=True)) op.add_column('users', sa.Column('colleage', sa.String(length=64), nullable=True)) op.add_column('users', sa.Column('last_seen', sa.DateTime(), nullable=True)) op.add_column('users', sa.Column('major', sa.String(length=64), nullable=True)) op.add_column('users', sa.Column('member_since', sa.DateTime(), nullable=True)) op.add_column('users', sa.Column('nick', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'nick') op.drop_column('users', 'member_since') op.drop_column('users', 'major') op.drop_column('users', 'last_seen') op.drop_column('users', 'colleage') op.drop_column('users', 'about_me') # ### end Alembic commands ###<|fim▁end|>
""" from alembic import op
<|file_name|>addTrip.js<|end_file_name|><|fim▁begin|>const pObj=pico.export('pico/obj'), fb=require('api/fbJSON'), rdTrip=require('redis/trip') return { setup(context,cb){ cb() }, addPickup(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(a){ case 'TripFirstPickup': switch(text.toLowerCase()){ case 'done': return next(null,`fb/ask${a}`) default: action.push('-',text) this.set(name,'TripPickup') break } break case 'TripPickup':<|fim▁hole|> break default: action.push('-',text) this.set(name,'TripPickup') break } break default: return next(null,`fb/ask${a}`) } next() }, addDropoff(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(a){ case 'TripFirstDropoff': switch(text.toLowerCase()){ case 'done': return next(null,`fb/ask${a}`) default: action.push('-',text) this.set(name,'TripDropoff') break } break case 'TripDropoff': switch(text.toLowerCase()){ case 'done': action.push('+:dropoff',null) this.set(name,'TripSeat') break default: action.push('-',text) this.set(name,'TripDropoff') break } break default: return next(null,`fb/ask${a}`) } next() }, done(user,cmd,msg,next){ console.log('addTrp.done',user,cmd) rdTrip.set(user,cmd,(err)=>{ if (err) Object.assign(msg, fb.message(user,fb.text(`An error has encountered when adding your trip: ${err}.\ntype help for more action`))) else Object.assign(msg, fb.message(user,fb.text(`New trip on ${fb.toDateTime(user,cmd.date)} has been added.\ntype help for more action`))) next() }) } }<|fim▁end|>
switch(text.toLowerCase()){ case 'done': action.push('+:pickup',null) this.set(name,'TripFirstDropoff')
<|file_name|>mailer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ This script sends confirmation messages to recently registered users. It should be run periodically so that users receive a registration confirmation link soon after they have registered. [email protected] """ import smtplib from email.message import Message from . db import Connection from . config import options def create_message(email, key): msg = Message() msg['From'] = '{0} <{1}>'.format(options.reg_confirmation_from, options.reg_confirmation_from_addr) msg['To'] = email msg['Subject'] = options.reg_confirmation_subject body = open(options.reg_confirmation_template).read() msg.set_payload(body.format(registration_key=key)) return msg<|fim▁hole|> server = smtplib.SMTP(options.smtp_server) server.sendmail(options.reg_confirmation_from_addr, email, msg) server.quit() def send_pending_confirmations(): db_conn = Connection(options.db_params, driver=options.db_driver) db_conn.connect() results = {'failed': []} pending = db_conn.get_pending_users_unmailed() for email, key in pending: msg = create_message(email, key) try: mail_confirmation(email, msg.as_string()) except Exception, e: results['failed'].append((email, e.args)) else: db_conn.set_pending_user_as_mailed(email) return results if __name__ == '__main__': results = send_pending_confirmations() if results: print "Sending failed for:" print "\n".join(i[0] for i in results["failed"])<|fim▁end|>
def mail_confirmation(email, msg):
<|file_name|>Socket.ts<|end_file_name|><|fim▁begin|>import { Event } from "../events/Event" import { EventDispatcher } from "../events/EventDispatcher" import { Browser } from "../utils/Browser" import { Byte } from "../utils/Byte" /** * 连接建立成功后调度。 * @eventType Event.OPEN * */ /*[Event(name = "open", type = "laya.events.Event")]*/ /** * 接收到数据后调度。 * @eventType Event.MESSAGE * */ /*[Event(name = "message", type = "laya.events.Event")]*/ /** * 连接被关闭后调度。 * @eventType Event.CLOSE * */ /*[Event(name = "close", type = "laya.events.Event")]*/ /** * 出现异常后调度。 * @eventType Event.ERROR * */ /*[Event(name = "error", type = "laya.events.Event")]*/ /** * <p> <code>Socket</code> 封装了 HTML5 WebSocket ,允许服务器端与客户端进行全双工(full-duplex)的实时通信,并且允许跨域通信。在建立连接后,服务器和 Browser/Client Agent 都能主动的向对方发送或接收文本和二进制数据。</p> * <p>要使用 <code>Socket</code> 类的方法,请先使用构造函数 <code>new Socket</code> 创建一个 <code>Socket</code> 对象。 <code>Socket</code> 以异步方式传输和接收数据。</p> */ export class Socket extends EventDispatcher { /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p> */ static LITTLE_ENDIAN: string = "littleEndian"; /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> */ static BIG_ENDIAN: string = "bigEndian"; /**@internal */ _endian: string; /**@private */ protected _socket: any; /**@private */ private _connected: boolean; /**@private */ private _addInputPosition: number; /**@private */ private _input: any; /**@private */ private _output: any; /** * 不再缓存服务端发来的数据,如果传输的数据为字符串格式,建议设置为true,减少二进制转换消耗。 */ disableInput: boolean = false; /** * 用来发送和接收数据的 <code>Byte</code> 类。 */ private _byteClass: new () => any; /** * <p>子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。必须在调用 connect 或者 connectByUrl 之前进行赋值,否则无效。</p> * <p>指定后,只有当服务器选择了其中的某个子协议,连接才能建立成功,否则建立失败,派发 Event.ERROR 事件。</p> * @see https://html.spec.whatwg.org/multipage/comms.html#dom-websocket */ protocols: any = []; /** * 缓存的服务端发来的数据。 */ get input(): any { return this._input; } /** * 表示需要发送至服务端的缓冲区中的数据。 */ get output(): any { return this._output; } /** * 表示此 Socket 对象目前是否已连接。 */ get connected(): boolean { return this._connected; } /** * <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p> * <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p> * <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。</p> */ get endian(): string { return this._endian; } set endian(value: string) { this._endian = value; if (this._input != null) this._input.endian = value; if (this._output != null) this._output.endian = value; } /** * <p>创建新的 Socket 对象。默认字节序为 Socket.BIG_ENDIAN 。若未指定参数,将创建一个最初处于断开状态的套接字。若指定了有效参数,则尝试连接到指定的主机和端口。</p> * @param host 服务器地址。 * @param port 服务器端口。 * @param byteClass 用于接收和发送数据的 Byte 类。如果为 null ,则使用 Byte 类,也可传入 Byte 类的子类。 * @param protocols 子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组 * @see laya.utils.Byte */ constructor(host: string|null = null, port: number = 0, byteClass: new () => any = null, protocols: any[]|null = null) { super(); this._byteClass = byteClass ? byteClass : Byte; this.protocols = protocols; this.endian = Socket.BIG_ENDIAN; if (host && port > 0 && port < 65535) this.connect(host, port); } /** * <p>连接到指定的主机和端口。</p> * <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p> * @param host 服务器地址。 * @param port 服务器端口。 */ connect(host: string, port: number): void { var url: string = "ws://" + host + ":" + port; this.connectByUrl(url); } /** * <p>连接到指定的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。</p> * <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p> * @param url 要连接的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。 */ connectByUrl(url: string): void { if (this._socket != null) this.close(); this._socket && this.cleanSocket(); if (!this.protocols || this.protocols.length == 0) { this._socket = new Browser.window.WebSocket(url); } else { this._socket = new Browser.window.WebSocket(url, this.protocols); } this._socket.binaryType = "arraybuffer"; this._output = new this._byteClass(); this._output.endian = this.endian; this._input = new this._byteClass(); this._input.endian = this.endian; this._addInputPosition = 0; this._socket.onopen = (e: any) => { this._onOpen(e); }; this._socket.onmessage = (msg: any): void => { this._onMessage(msg); }; this._socket.onclose = (e: any): void => { this._onClose(e); }; this._socket.onerror = (e: any): void => { this._onError(e); }; } /** * 清理Socket:关闭Socket链接,关闭事件监听,重置Socket */ cleanSocket(): void { this.close(); this._connected = false; this._socket.onopen = null; this._socket.onmessage = null; this._socket.onclose = null; this._socket.onerror = null; this._socket = null; } /** * 关闭连接。 */ close(): void { if (this._socket != null) { try { this._socket.close(); } catch (e) { } } } /** * @private * 连接建立成功 。 */ protected _onOpen(e: any): void { this._connected = true; this.event(Event.OPEN, e); } /** * @private * 接收到数据处理方法。 * @param msg 数据。 */ protected _onMessage(msg: any): void { if (!msg || !msg.data) return; var data: any = msg.data; if (this.disableInput && data) { this.event(Event.MESSAGE, data); return; } if (this._input.length > 0 && this._input.bytesAvailable < 1) { this._input.clear(); this._addInputPosition = 0; } var pre: number = this._input.pos; !this._addInputPosition && (this._addInputPosition = 0); this._input.pos = this._addInputPosition; if (data) { if (typeof (data) == 'string') { this._input.writeUTFBytes(data); } else { this._input.writeArrayBuffer(data); } this._addInputPosition = this._input.pos; this._input.pos = pre; } this.event(Event.MESSAGE, data); } /** * @private * 连接被关闭处理方法。 */ protected _onClose(e: any): void { this._connected = false; this.event(Event.CLOSE, e) } /** * @private * 出现异常处理方法。 */ protected _onError(e: any): void { this.event(Event.ERROR, e)<|fim▁hole|> * 发送数据到服务器。 * @param data 需要发送的数据,可以是String或者ArrayBuffer。 */ send(data: any): void { this._socket.send(data); } /** * 发送缓冲区中的数据到服务器。 */ flush(): void { if (this._output && this._output.length > 0) { var evt: any; try { this._socket && this._socket.send(this._output.__getBuffer().slice(0, this._output.length)); } catch (e) { evt = e; } this._output.endian = this.endian; this._output.clear(); if (evt) this.event(Event.ERROR, evt); } } }<|fim▁end|>
} /**
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|>"""Configuration for pytest.""" import json def pytest_generate_tests(metafunc): """Configure pytest to call each of the tests once for each test case."""<|fim▁hole|> tests = json.load(open("tests/test_data.json"))["tests"] metafunc.parametrize("test_case", tests)<|fim▁end|>
if "test_case" in metafunc.fixturenames:
<|file_name|>explicit_instantiation.cc<|end_file_name|><|fim▁begin|>// { dg-do compile { target c++11 } } // Copyright (C) 2013-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // NB: This file is for testing type_traits with NO OTHER INCLUDES. #include <type_traits> namespace std { typedef short test_type; template struct add_pointer<test_type>;<|fim▁hole|>}<|fim▁end|>
<|file_name|>preview.js<|end_file_name|><|fim▁begin|>/*global gdn, jQuery*/ jQuery(($) => { const $preview = $('<div class="Preview"></div>') .insertBefore('#ConversationForm .bodybox-wrap, #Form_ConversationMessage .bodybox-wrap') .hide(); const $textbox = $('#ConversationForm textarea[name="Body"], #Form_ConversationMessage textarea[name="Body"]'); $('<a class="Button PreviewButton">' + gdn.getMeta('conversationsPreview.preview') + '</a>') .insertBefore('#ConversationForm input[type="submit"], #Form_ConversationMessage input[type="submit"]') .click(({target}) => { const $this = $(target); if ($this.hasClass('WriteButton')) { $preview.hide(); $textbox.show(); $this<|fim▁hole|> .addClass('PreviewButton') .removeClass('WriteButton') .text(gdn.getMeta('conversationsPreview.preview')); return; } gdn.disable($this); $this.toggleClass('PreviewButton').toggleClass('WriteButton'); $.post( gdn.url('messages/preview'), { Body: $this.closest('form').find('textarea[name="Body"]').val(), Format: $this.closest('form').find('input[name="Format"]').val(), TransientKey: gdn.definition('TransientKey') }, (data) => { $preview.html(data).show(); $textbox.hide(); $this .addClass('WriteButton') .removeClass('PreviewButton') .text(gdn.getMeta('conversationsPreview.edit')); $(document).trigger('PreviewLoaded'); }, 'html' ).always(() => { gdn.enable($this); }); }); $(document).on('MessageAdded', () => { $('.WriteButton').click(); }); });<|fim▁end|>
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|>""" Form Widget classes specific to the Django admin site. """ from __future__ import unicode_literals import copy from django import forms from django.contrib.admin.templatetags.admin_static import static from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.forms.utils import flatatt from django.utils.html import escape, format_html, format_html_join, smart_urlquote from django.utils.text import Truncator from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_text from django.utils import six class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ @property def media(self): js = ["core.js", "SelectBox.js", "SelectFilter2.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} attrs['class'] = 'selectfilter' if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] output.append('<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append('SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), static('admin/'))) return mark_safe(''.join(output)) class AdminDateWidget(forms.DateInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vDateField', 'size': '10'} if attrs is not None: final_attrs.update(attrs) super(AdminDateWidget, self).__init__(attrs=final_attrs, format=format) class AdminTimeWidget(forms.TimeInput): @property def media(self): js = ["calendar.js", "admin/DateTimeShortcuts.js"] return forms.Media(js=[static("admin/js/%s" % path) for path in js]) def __init__(self, attrs=None, format=None): final_attrs = {'class': 'vTimeField', 'size': '8'} if attrs is not None: final_attrs.update(attrs) super(AdminTimeWidget, self).__init__(attrs=final_attrs, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): return format_html('<p class="datetime">{0} {1}<br />{2} {3}</p>', _('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1]) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return format_html('<ul{0}>\n{1}\n</ul>', flatatt(self.attrs), format_html_join('\n', '<li>{0}</li>', ((force_text(w),) for w in self))) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.ClearableFileInput): template_with_initial = ('<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) template_with_clear = ('<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def url_params_from_lookup_dict(lookups): """ Converts the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): items = [] for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ','.join(str(x) for x in v) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] else: v = six.text_type(v) items.append((k, v)) params.update(dict(items)) return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ def __init__(self, rel, admin_site, attrs=None, using=None): self.rel = rel self.admin_site = admin_site self.db = using super(ForeignKeyRawIdWidget, self).__init__(attrs) def render(self, name, value, attrs=None): rel_to = self.rel.to if attrs is None: attrs = {} extra = [] if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse('admin:%s_%s_changelist' % (rel_to._meta.app_label, rel_to._meta.model_name), current_app=self.admin_site.name) params = self.url_parameters() if params: url = '?' + '&amp;'.join('%s=%s' % (k, v) for k, v in params.items()) else: url = '' if "class" not in attrs: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append('<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (related_url, url, name)) extra.append('<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] + extra if value: output.append(self.label_for_value(value)) return mark_safe(''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return '&nbsp;<strong>%s</strong>' % escape(Truncator(obj).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return '' class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """<|fim▁hole|> def render(self, name, value, attrs=None): if attrs is None: attrs = {} if self.rel.to in self.admin_site._registry: # The related object is registered with the same AdminSite attrs['class'] = 'vManyToManyRawIdAdminField' if value: value = ','.join(force_text(v) for v in value) else: value = '' return super(ManyToManyRawIdWidget, self).render(name, value, attrs) def url_parameters(self): return self.base_url_parameters() def label_for_value(self, value): return '' def value_from_datadict(self, data, files, name): value = data.get(name) if value: return value.split(',') class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ def __init__(self, widget, rel, admin_site, can_add_related=None): self.is_hidden = widget.is_hidden self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if can_add_related is None: can_add_related = rel.to in admin_site._registry self.can_add_related = can_add_related # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def media(self): return self.widget.media def render(self, name, value, *args, **kwargs): from django.contrib.admin.views.main import TO_FIELD_VAR rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.model_name) self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if self.can_add_related: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) url_params = '?%s=%s' % (TO_FIELD_VAR, self.rel.get_related_field().name) # TODO: "add_id_" is hard-coded here. This should instead use the # correct API to determine the ID dynamically. output.append('<a href="%s%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % (related_url, url_params, name)) output.append('<img src="%s" width="10" height="10" alt="%s"/></a>' % (static('admin/img/icon_addlink.gif'), _('Add Another'))) return mark_safe(''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs) class AdminEmailInputWidget(forms.EmailInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminEmailInputWidget, self).__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.URLInput): def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) def render(self, name, value, attrs=None): html = super(AdminURLFieldWidget, self).render(name, value, attrs) if value: value = force_text(self._format_value(value)) final_attrs = {'href': smart_urlquote(value)} html = format_html( '<p class="url">{0} <a{1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(final_attrs), value, _('Change:'), html ) return html class AdminIntegerFieldWidget(forms.TextInput): class_name = 'vIntegerField' def __init__(self, attrs=None): final_attrs = {'class': self.class_name} if attrs is not None: final_attrs.update(attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) class AdminBigIntegerFieldWidget(AdminIntegerFieldWidget): class_name = 'vBigIntegerField' class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vCommaSeparatedIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs)<|fim▁end|>
<|file_name|>database.js<|end_file_name|><|fim▁begin|>'use strict'; const MongoClient = require('mongodb').MongoClient; module.exports = class Events { constructor() { this.database = null; this.collections = {}; } getDatabase(callback) { if (this.database) { callback(this.database); } else { MongoClient.connect('mongodb://writer:[email protected]:17584/events', (err, db) => { if (!err) { console.log('connected to database!'); this.database = db; callback(this.database); } else { console.log(err); } }); } } getCollection(collection, callback) { if (this.collections[collection]) { callback(this.collections[collection]);<|fim▁hole|> }); } } addEvent(event, callback) { this.getCollection('events', collection => { collection.insertOne(event, callback); }); } getTags(callback) { this.getCollection('events', collection => { //collection.find().toArray(callback); collection.aggregate([ { "$group": { "_id": "$tags", "count": { $sum: 1 } } } ], callback); }); } }<|fim▁end|>
} else { this.getDatabase(database => { this.collections[collection] = database.collection(collection); callback(this.collections[collection]);
<|file_name|>test_cvs.cpp<|end_file_name|><|fim▁begin|>/*************************************************************************** * Copyright 2007 Robert Gruber <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "test_cvs.h" #include <QtTest/QtTest> #include <QUrl> #include <KIO/DeleteJob> #include <cvsjob.h> #include <cvsproxy.h> #include <tests/autotestshell.h> #include <tests/testcore.h> #define CVSTEST_BASEDIR "/tmp/kdevcvs_testdir/" #define CVS_REPO CVSTEST_BASEDIR "repo/" #define CVS_IMPORT CVSTEST_BASEDIR "import/" #define CVS_TESTFILE_NAME "testfile" #define CVS_CHECKOUT CVSTEST_BASEDIR "working/" // we need to add this since it is declared in cvsplugin.cpp which we don't compile here Q_LOGGING_CATEGORY(PLUGIN_CVS, "kdevplatform.plugins.cvs") void TestCvs::initTestCase() { KDevelop::AutoTestShell::init(); KDevelop::TestCore::initialize(KDevelop::Core::NoUi); m_proxy = new CvsProxy; // If the basedir for this cvs test exists from a // previous run; remove it... cleanup(); } void TestCvs::cleanupTestCase() { KDevelop::TestCore::shutdown(); delete m_proxy; } void TestCvs::init() { // Now create the basic directory structure QDir tmpdir("/tmp"); tmpdir.mkdir(CVSTEST_BASEDIR); tmpdir.mkdir(CVS_REPO); tmpdir.mkdir(CVS_IMPORT); } void TestCvs::cleanup() { if ( QFileInfo::exists(CVSTEST_BASEDIR) ) KIO::del(QUrl::fromLocalFile(QString(CVSTEST_BASEDIR)))->exec(); } void TestCvs::repoInit() { // make job that creates the local repository CvsJob* j = new CvsJob(0); QVERIFY( j ); j->setDirectory(CVSTEST_BASEDIR); *j << "cvs" << "-d" << CVS_REPO << "init"; // try to start the job QVERIFY( j->exec() ); //check if the CVSROOT directory in the new local repository exists now QVERIFY( QFileInfo::exists(QString(CVS_REPO "/CVSROOT")) ); } void TestCvs::importTestData() { // create a file so we don't import an empty dir QFile f(CVS_IMPORT "" CVS_TESTFILE_NAME); if(f.open(QIODevice::WriteOnly)) { QTextStream input( &f ); input << "HELLO WORLD"; } f.flush(); CvsJob* j = m_proxy->import(QUrl::fromLocalFile(CVS_IMPORT), CVS_REPO, "test", "vendor", "release", "test import message"); QVERIFY( j ); <|fim▁hole|> //check if the directory has been added to the repository QString testdir(CVS_REPO "/test"); QVERIFY( QFileInfo::exists(testdir) ); //check if the file has been added to the repository QString testfile(CVS_REPO "/test/" CVS_TESTFILE_NAME ",v"); QVERIFY( QFileInfo::exists(testfile) ); } void TestCvs::checkoutTestData() { CvsJob* j = m_proxy->checkout(QUrl::fromLocalFile(CVS_CHECKOUT), CVS_REPO, "test"); QVERIFY( j ); // try to start the job QVERIFY( j->exec() ); //check if the directory is there QString testdir(CVS_CHECKOUT); QVERIFY( QFileInfo::exists(testdir) ); //check if the file is there QString testfile(CVS_CHECKOUT "" CVS_TESTFILE_NAME); QVERIFY( QFileInfo::exists(testfile) ); } void TestCvs::testInitAndImport() { repoInit(); importTestData(); checkoutTestData(); } void TestCvs::testLogFolder() { repoInit(); importTestData(); checkoutTestData(); QString testdir(CVS_CHECKOUT); KDevelop::VcsRevision rev = KDevelop::VcsRevision::createSpecialRevision(KDevelop::VcsRevision::Head); CvsJob* job = m_proxy->log(QUrl::fromLocalFile(testdir), rev); QVERIFY(job); } QTEST_MAIN(TestCvs)<|fim▁end|>
// try to start the job QVERIFY( j->exec() );
<|file_name|>index.tsx<|end_file_name|><|fim▁begin|>/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {MithrilComponent} from "jsx/mithril-component"; import m from "mithril"; import {EnvironmentVariable, EnvironmentVariables} from "models/environment_variables/types"; import s from "underscore.string"; import {ButtonIcon, Secondary} from "views/components/buttons"; import {FlashMessage, MessageType} from "views/components/flash_message"; import {EnvironmentVariableWidget} from "./environment_variable_widget"; import styles from "./index.scss"; export interface GroupedEnvironmentVariablesAttrs { title: string; environmentVariables: EnvironmentVariables; onAdd: () => void; onRemove: (environmentVariable: EnvironmentVariable) => void; } export class GroupedEnvironmentVariables extends MithrilComponent<GroupedEnvironmentVariablesAttrs> { renderEnvironmentVariableWidget(vnode: m.Vnode<GroupedEnvironmentVariablesAttrs>, environmentVariable: EnvironmentVariable) { return <EnvironmentVariableWidget environmentVariable={environmentVariable} onRemove={vnode.attrs.onRemove}/>; } view(vnode: m.Vnode<GroupedEnvironmentVariablesAttrs>): m.Children { let noEnvironmentVariablesConfiguredMessage: m.Children; if (vnode.attrs.environmentVariables.length === 0) { noEnvironmentVariablesConfiguredMessage = `No ${vnode.attrs.title} are configured.`; } return <div class={styles.groupContainer}> <h4 data-test-id={`${s.slugify(vnode.attrs.title)}-title`}>{vnode.attrs.title}</h4> <FlashMessage dataTestId={`${s.slugify(vnode.attrs.title)}-msg`} type={MessageType.info} message={noEnvironmentVariablesConfiguredMessage}/> {vnode.attrs.environmentVariables.map((envVar) => this.renderEnvironmentVariableWidget(vnode, envVar))} <Secondary small={true} icon={ButtonIcon.ADD} data-test-id={`add-${s.slugify(vnode.attrs.title)}-btn`} onclick={vnode.attrs.onAdd.bind(this)}> Add </Secondary> </div>; }<|fim▁hole|>} interface EnvironmentVariablesWidgetAttrs { environmentVariables: EnvironmentVariables; } export class EnvironmentVariablesWidget extends MithrilComponent<EnvironmentVariablesWidgetAttrs, {}> { static onAdd(isSecure: boolean, vnode: m.Vnode<EnvironmentVariablesWidgetAttrs, {}>) { vnode.attrs.environmentVariables.push(new EnvironmentVariable("", undefined, isSecure, "")); } static onRemove(envVar: EnvironmentVariable, vnode: m.Vnode<EnvironmentVariablesWidgetAttrs, {}>) { vnode.attrs.environmentVariables.remove(envVar); } view(vnode: m.Vnode<EnvironmentVariablesWidgetAttrs, {}>): m.Children { return <div> <GroupedEnvironmentVariables environmentVariables={vnode.attrs.environmentVariables.plainTextVariables()} title="Plain Text Variables" onAdd={EnvironmentVariablesWidget.onAdd.bind(this, false, vnode)} onRemove={(envVar: EnvironmentVariable) => EnvironmentVariablesWidget.onRemove(envVar, vnode)}/> <GroupedEnvironmentVariables environmentVariables={vnode.attrs.environmentVariables.secureVariables()} title="Secure Variables" onAdd={EnvironmentVariablesWidget.onAdd.bind(this, true, vnode)} onRemove={(envVar: EnvironmentVariable) => EnvironmentVariablesWidget.onRemove(envVar, vnode)}/> </div>; } }<|fim▁end|>
<|file_name|>handler.ts<|end_file_name|><|fim▁begin|>// (C) Copyright 2015 Moodle Pty Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { AddonModQuizAccessRuleHandler } from '../../../providers/access-rules-delegate'; /** * Handler to support IP address access rule. */ @Injectable() export class AddonModQuizAccessIpAddressHandler implements AddonModQuizAccessRuleHandler {<|fim▁hole|> // Nothing to do. } /** * Whether or not the handler is enabled on a site level. * * @return True or promise resolved with true if enabled. */ isEnabled(): boolean | Promise<boolean> { return true; } /** * Whether the rule requires a preflight check when prefetch/start/continue an attempt. * * @param quiz The quiz the rule belongs to. * @param attempt The attempt started/continued. If not supplied, user is starting a new attempt. * @param prefetch Whether the user is prefetching the quiz. * @param siteId Site ID. If not defined, current site. * @return Whether the rule requires a preflight check. */ isPreflightCheckRequired(quiz: any, attempt?: any, prefetch?: boolean, siteId?: string): boolean | Promise<boolean> { return false; } }<|fim▁end|>
name = 'AddonModQuizAccessIpAddress'; ruleName = 'quizaccess_ipaddress'; constructor() {
<|file_name|>string.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2015 Daniel Grunwald // // 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. use std; use std::str; use std::ascii::AsciiExt; use std::borrow::Cow; use libc::c_char; use ffi; use python::{Python, PythonObject, ToPythonPointer}; use super::{exc, PyObject}; use err::{self, PyResult, PyErr}; use conversion::{ExtractPyObject, ToPyObject}; /// Represents a Python byte string. /// Corresponds to `str` in Python 2, and `bytes` in Python 3. pub struct PyBytes<'p>(PyObject<'p>); /// Represents a Python unicode string. /// Corresponds to `unicode` in Python 2, and `str` in Python 3. pub struct PyUnicode<'p>(PyObject<'p>); pyobject_newtype!(PyBytes, PyBytes_Check, PyBytes_Type); pyobject_newtype!(PyUnicode, PyUnicode_Check, PyUnicode_Type); #[cfg(feature="python27-sys")] pub use PyBytes as PyString; #[cfg(feature="python3-sys")] pub use PyUnicode as PyString; impl <'p> PyBytes<'p> { /// Creates a new Python byte string object. /// The byte string is initialized by copying the data from the `&[u8]`. /// /// Panics if out of memory. pub fn new(py: Python<'p>, s: &[u8]) -> PyBytes<'p> { let ptr = s.as_ptr() as *const c_char; let len = s.len() as ffi::Py_ssize_t; unsafe { err::cast_from_owned_ptr_or_panic(py, ffi::PyBytes_FromStringAndSize(ptr, len)) } } /// Gets the Python string data as byte slice. pub fn as_slice(&self) -> &[u8] { unsafe { let buffer = ffi::PyBytes_AsString(self.as_ptr()) as *const u8; let length = ffi::PyBytes_Size(self.as_ptr()) as usize; std::slice::from_raw_parts(buffer, length) } } } impl <'p> PyUnicode<'p> { /// Creates a new unicode string object from the Rust string. pub fn new(py: Python<'p>, s: &str) -> PyUnicode<'p> { let ptr = s.as_ptr() as *const c_char; let len = s.len() as ffi::Py_ssize_t; unsafe { err::cast_from_owned_ptr_or_panic(py, ffi::PyUnicode_FromStringAndSize(ptr, len)) } } /* Note: 'as_slice removed temporarily, we need to reconsider // whether we really should expose the platform-dependent Py_UNICODE to user code. #[cfg(feature="python27-sys")] pub fn as_slice(&self) -> &[ffi::Py_UNICODE] { unsafe { let buffer = ffi::PyUnicode_AS_UNICODE(self.as_ptr()) as *const _; let length = ffi::PyUnicode_GET_SIZE(self.as_ptr()) as usize; std::slice::from_raw_parts(buffer, length) } }*/ /// Convert the `PyUnicode` into a rust string. /// /// Returns a `UnicodeDecodeError` if the input contains invalid code points. pub fn to_string(&self) -> PyResult<'p, Cow<str>> { // TODO: use PyUnicode_AsUTF8AndSize if available let py = self.python(); let bytes: PyBytes = unsafe { try!(err::result_cast_from_owned_ptr(py, ffi::PyUnicode_AsUTF8String(self.as_ptr()))) }; match str::from_utf8(bytes.as_slice()) { Ok(s) => Ok(Cow::Owned(s.to_owned())), Err(e) => Err(PyErr::from_instance(try!(exc::UnicodeDecodeError::new_utf8(py, bytes.as_slice(), e)))) } } /// Convert the `PyUnicode` into a rust string. /// /// Any invalid code points are replaced with U+FFFD REPLACEMENT CHARACTER. pub fn to_string_lossy(&self) -> Cow<str> { // TODO: use PyUnicode_AsUTF8AndSize if available // TODO: test how this function handles lone surrogates or otherwise invalid code points let py = self.python(); let bytes: PyBytes = unsafe { err::result_cast_from_owned_ptr(py, ffi::PyUnicode_AsUTF8String(self.as_ptr())) .ok().expect("Error in PyUnicode_AsUTF8String") }; Cow::Owned(String::from_utf8_lossy(bytes.as_slice()).into_owned()) } } // On PyString (i.e. PyBytes in 2.7, PyUnicode otherwise), put static methods // for extraction as Cow<str>: impl <'p> PyString<'p> { /// Extract a rust string from the Python object. /// /// In Python 2.7, accepts both byte strings and unicode strings. /// Byte strings will be decoded using UTF-8. /// /// In Python 3.x, accepts unicode strings only. /// /// Returns `TypeError` if the input is not one of the accepted types. /// Returns `UnicodeDecodeError` if the input is not valid unicode. #[cfg(feature="python27-sys")] pub fn extract<'a>(o: &'a PyObject<'p>) -> PyResult<'p, Cow<'a, str>> { let py = o.python(); if let Ok(s) = o.cast_as::<PyBytes>() { s.to_string() } else if let Ok(u) = o.cast_as::<PyUnicode>() {<|fim▁hole|> u.to_string() } else { Err(PyErr::new_lazy_init(py.get_type::<exc::TypeError>(), None)) } } /// Extract a rust string from the Python object. /// /// In Python 2.7, accepts both byte strings and unicode strings. /// Byte strings will be decoded using UTF-8. /// /// In Python 3.x, accepts unicode strings only. /// /// Returns `TypeError` if the input is not one of the accepted types. /// Any invalid code points are replaced with U+FFFD REPLACEMENT CHARACTER. #[cfg(feature="python27-sys")] pub fn extract_lossy<'a>(o: &'a PyObject<'p>) -> PyResult<'p, Cow<'a, str>> { let py = o.python(); if let Ok(s) = o.cast_as::<PyBytes>() { Ok(s.to_string_lossy()) } else if let Ok(u) = o.cast_as::<PyUnicode>() { Ok(u.to_string_lossy()) } else { Err(PyErr::new_lazy_init(py.get_type::<exc::TypeError>(), None)) } } /// Extract a rust string from the Python object. /// /// In Python 2.7, accepts both byte strings and unicode strings. /// Byte strings will be decoded using UTF-8. /// /// In Python 3.x, accepts unicode strings only. /// /// Returns `TypeError` if the input is not one of the accepted types. /// Returns `UnicodeDecodeError` if the input is not valid unicode. #[cfg(feature="python3-sys")] pub fn extract<'a>(o: &'a PyObject<'p>) -> PyResult<'p, Cow<'a, str>> { let py = o.python(); if let Ok(u) = o.cast_as::<PyUnicode>() { u.to_string() } else { Err(PyErr::new_lazy_init(py.get_type::<exc::TypeError>(), None)) } } /// Extract a rust string from the Python object. /// /// In Python 2.7, accepts both byte strings and unicode strings. /// Byte strings will be decoded using UTF-8. /// /// In Python 3.x, accepts unicode strings only. /// /// Returns `TypeError` if the input is not one of the accepted types. /// Any invalid code points are replaced with U+FFFD REPLACEMENT CHARACTER. #[cfg(feature="python3-sys")] pub fn extract_lossy<'a>(o: &'a PyObject<'p>) -> PyResult<'p, Cow<'a, str>> { let py = o.python(); if let Ok(u) = o.cast_as::<PyUnicode>() { Ok(u.to_string_lossy()) } else { Err(PyErr::new_lazy_init(py.get_type::<exc::TypeError>(), None)) } } // In Python 2.7, PyBytes serves as PyString, so it should offer the // same to_string and to_string_lossy functions as PyUnicode: /// Convert the `PyString` into a rust string. /// /// In Python 2.7, `PyString` is a byte string and will be decoded using UTF-8. /// In Python 3.x, `PyString` is a unicode string. /// /// Returns a `UnicodeDecodeError` if the input is not valid unicode. #[cfg(feature="python27-sys")] pub fn to_string(&self) -> PyResult<'p, Cow<str>> { let py = self.python(); match str::from_utf8(self.as_slice()) { Ok(s) => Ok(Cow::Borrowed(s)), Err(e) => Err(PyErr::from_instance(try!(exc::UnicodeDecodeError::new_utf8(py, self.as_slice(), e)))) } } /// Convert the `PyString` into a rust string. /// /// In Python 2.7, `PyString` is a byte string and will be decoded using UTF-8. /// In Python 3.x, `PyString` is a unicode string. /// /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER. #[cfg(feature="python27-sys")] pub fn to_string_lossy(&self) -> Cow<str> { String::from_utf8_lossy(self.as_slice()) } } // When converting strings to/from Python, we need to copy the string data. // This means we can implement ToPyObject for str, but FromPyObject only for (Cow)String. /// Converts rust `str` to Python object: /// ASCII-only strings are converted to Python `str` objects; /// other strings are converted to Python `unicode` objects. /// /// Note that `str::ObjectType` differs based on Python version: /// In Python 2.7, it is `PyObject` (`object` is the common base class of `str` and `unicode`). /// In Python 3.x, it is `PyUnicode`. impl <'p> ToPyObject<'p> for str { #[cfg(feature="python27-sys")] type ObjectType = PyObject<'p>; #[cfg(feature="python3-sys")] type ObjectType = PyUnicode<'p>; #[cfg(feature="python27-sys")] fn to_py_object(&self, py : Python<'p>) -> PyObject<'p> { if self.is_ascii() { PyBytes::new(py, self.as_bytes()).into_object() } else { PyUnicode::new(py, self).into_object() } } #[cfg(feature="python3-sys")] #[inline] fn to_py_object(&self, py : Python<'p>) -> PyUnicode<'p> { PyUnicode::new(py, self) } } /// Converts rust `String` to Python object: /// ASCII-only strings are converted to Python `str` objects; /// other strings are converted to Python `unicode` objects. /// /// Note that `str::ObjectType` differs based on Python version: /// In Python 2.7, it is `PyObject` (`object` is the common base class of `str` and `unicode`). /// In Python 3.x, it is `PyUnicode`. impl <'p> ToPyObject<'p> for String { type ObjectType = <str as ToPyObject<'p>>::ObjectType; #[inline] fn to_py_object(&self, py: Python<'p>) -> Self::ObjectType { <str as ToPyObject>::to_py_object(self, py) } } /// Allows extracting strings from Python objects. /// Accepts Python `str` and `unicode` objects. /// In Python 2.7, `str` is expected to be UTF-8 encoded. extract!(obj to String => { PyString::extract(obj).map(|s| s.into_owned()) }); /// Allows extracting strings from Python objects. /// Accepts Python `str` and `unicode` objects. /// In Python 2.7, `str` is expected to be UTF-8 encoded. extract!(obj to Cow<'source, str> => { PyString::extract(obj) }); impl <'python, 'source, 'prepared> ExtractPyObject<'python, 'source, 'prepared> for &'prepared str { type Prepared = Cow<'source, str>; #[inline] fn prepare_extract(obj: &'source PyObject<'python>) -> PyResult<'python, Self::Prepared> { PyString::extract(obj) } #[inline] fn extract(cow: &'prepared Cow<'source, str>) -> PyResult<'python, Self> { Ok(cow) } } #[cfg(test)] mod test { use python::{Python, PythonObject}; use conversion::{ToPyObject, ExtractPyObject}; #[test] fn test_non_bmp() { let gil = Python::acquire_gil(); let py = gil.python(); let s = "\u{1F30F}"; let py_string = s.to_py_object(py).into_object(); assert_eq!(s, py_string.extract::<String>().unwrap()); } #[test] fn test_extract_str() { let gil = Python::acquire_gil(); let py = gil.python(); let s = "Hello Python"; let py_string = s.to_py_object(py).into_object(); let prepared = <&str>::prepare_extract(&py_string).unwrap(); assert_eq!(s, <&str>::extract(&prepared).unwrap()); } }<|fim▁end|>
<|file_name|>TaylorTest.py<|end_file_name|><|fim▁begin|># This software is Copyright (C) 2004-2008 Bristol University # and is released under the GNU General Public License version 2. import unittest from Powers import Powers from Polynomial import Polynomial<|fim▁hole|> class Sine(unittest.TestCase): def test_terms(self): s = Taylor.Sine(1, 0) self.assert_(not s[0]) self.assert_(not s[2]) self.assert_(not s[4]) self.assert_(s[1] == Polynomial(1, terms={Powers((1,)): +1.0})) self.assert_(s[3] == Polynomial(1, terms={Powers((3,)): -1.0/6.0}), s[3]) self.assert_(s[5] == Polynomial(1, terms={Powers((5,)): +1.0/120.0}), s[5]) def test_terms_embed(self): s = Taylor.Sine(2, 1) self.assert_(not s[0]) self.assert_(not s[2]) self.assert_(not s[4]) self.assert_(s[1] == Polynomial(2, terms={Powers((0, 1)): +1.0})) self.assert_(s[3] == Polynomial(2, terms={Powers((0, 3)): -1.0/6.0}), s[3]) self.assert_(s[5] == Polynomial(2, terms={Powers((0, 5)): +1.0/120.0}), s[5]) def test_terms_cached(self): s = Taylor.Cached(Taylor.Sine(2, 1)) self.assert_(not s[0]) self.assert_(not s[2]) self.assert_(not s[4]) self.assert_(s[1] == Polynomial(2, terms={Powers((0, 1)): +1.0})) self.assert_(s[3] == Polynomial(2, terms={Powers((0, 3)): -1.0/6.0}), s[3]) self.assert_(s[5] == Polynomial(2, terms={Powers((0, 5)): +1.0/120.0}), s[5]) class Cosine(unittest.TestCase): def test_terms(self): s = Taylor.Cosine(1, 0) self.assert_(not s[1]) self.assert_(not s[3]) self.assert_(not s[5]) self.assert_(s[0] == Polynomial(1, terms={Powers((0,)): +1.0})) self.assert_(s[2] == Polynomial(1, terms={Powers((2,)): -1.0/2.0}), s[2]) self.assert_(s[4] == Polynomial(1, terms={Powers((4,)): +1.0/24.0}), s[4]) def test_terms_embed(self): s = Taylor.Cosine(2, 1) self.assert_(not s[1]) self.assert_(not s[3]) self.assert_(not s[5]) self.assert_(s[0] == Polynomial(2, terms={Powers((0, 0)): +1.0})) self.assert_(s[2] == Polynomial(2, terms={Powers((0, 2)): -1.0/2.0}), s[2]) self.assert_(s[4] == Polynomial(2, terms={Powers((0, 4)): +1.0/24.0}), s[4]) class Sum(unittest.TestCase): def test_sine_plus_cosine(self): s = Taylor.Cached(Taylor.Sine(2, 0)) c = Taylor.Cached(Taylor.Cosine(2, 1)) r = s+c self.assert_(r[0] == Polynomial(2, terms={Powers((0, 0)): +1.0}), r[0]) self.assert_(r[1] == Polynomial(2, terms={Powers((1, 0)): +1.0}), r[1]) self.assert_(r[2] == Polynomial(2, terms={Powers((0, 2)): -1.0/2.0}), r[2]) self.assert_(r[3] == Polynomial(2, terms={Powers((3, 0)): -1.0/6.0}), r[3]) self.assert_(r[4] == Polynomial(2, terms={Powers((0, 4)): +1.0/24.0}), r[4]) self.assert_(r[5] == Polynomial(2, terms={Powers((5, 0)): +1.0/120.0}), r[5]) class Product(unittest.TestCase): def test_sine_times_cosine(self): s = Taylor.Cached(Taylor.Sine(2, 0)) c = Taylor.Cached(Taylor.Cosine(2, 1)) r = s*c self.assert_(not r[0]) self.assert_(r[1] == Polynomial(2, terms={Powers((1, 0)): +1.0}), r[1]) def test_sine_times_sine(self): s = Taylor.Cached(Taylor.Sine(2, 0)) r = s*s self.assert_(not r[0]) self.assert_(not r[1]) self.assert_(r[2] == Polynomial(2, terms={Powers((2, 0)): +1.0})) self.assert_(not r[3]) self.assert_(r[4] == Polynomial(2, terms={Powers((4, 0)): 2.0*(-1.0/6.0)}), r[4]) self.assert_(not r[5]) self.assert_(r[6] == Polynomial(2, terms={Powers((6, 0)): +2.0*1.0/120.0+1.0/36.0}), r[6]) class Bernoulli(unittest.TestCase): def test_values(self): b = Taylor.bernoulli self.assertEquals(b(0), +1.0) self.assertEquals(b(1), -1.0/2.0) self.assertEquals(b(2), +1.0/6.0) self.assertEquals(b(3), +0.0) self.assertEquals(b(4), -1.0/30.0) self.assertEquals(b(5), +0.0) self.assertEquals(b(6), +1.0/42.0) self.assertEquals(b(7), +0.0) self.assertEquals(b(8), -1.0/30.0) self.assertEquals(b(9), +0.0) class Tanh(unittest.TestCase): def test_terms(self): t = Taylor.Tanh(1, 0) self.assert_(not t[0]) self.assert_(t[1] == Polynomial(1, terms={Powers((1,)): 1.0}), t[1]) def suite(): suites = [] suites.append(unittest.makeSuite(Bernoulli)) suites.append(unittest.makeSuite(Tanh)) suites.append(unittest.makeSuite(Product)) suites.append(unittest.makeSuite(Sum)) suites.append(unittest.makeSuite(Sine)) suites.append(unittest.makeSuite(Cosine)) return unittest.TestSuite(suites) if __name__ == '__main__': unittest.main(defaultTest='suite')<|fim▁end|>
import Taylor
<|file_name|>SimpleConfigObject.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package com.typesafe.config.impl; import java.io.ObjectStreamException; import java.io.Serializable; import java.math.BigInteger; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigOrigin; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValue; final class SimpleConfigObject extends AbstractConfigObject implements Serializable { private static final long serialVersionUID = 2L; // this map should never be modified - assume immutable final private Map<String, AbstractConfigValue> value; final private boolean resolved; final private boolean ignoresFallbacks; SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value, ResolveStatus status, boolean ignoresFallbacks) { super(origin); if (value == null) throw new ConfigException.BugOrBroken( "creating config object with null map"); this.value = value; this.resolved = status == ResolveStatus.RESOLVED; this.ignoresFallbacks = ignoresFallbacks; // Kind of an expensive debug check. Comment out? if (status != ResolveStatus.fromValues(value.values())) throw new ConfigException.BugOrBroken("Wrong resolved status on " + this); } SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value) { this(origin, value, ResolveStatus.fromValues(value.values()), false /* ignoresFallbacks */); } @Override public SimpleConfigObject withOnlyKey(String key) { return withOnlyPath(Path.newKey(key)); } @Override public SimpleConfigObject withoutKey(String key) { return withoutPath(Path.newKey(key)); } // gets the object with only the path if the path // exists, otherwise null if it doesn't. this ensures // that if we have { a : { b : 42 } } and do // withOnlyPath("a.b.c") that we don't keep an empty // "a" object. @Override protected SimpleConfigObject withOnlyPathOrNull(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (next != null) { if (v != null && (v instanceof AbstractConfigObject)) { v = ((AbstractConfigObject) v).withOnlyPathOrNull(next); } else { // if the path has more elements but we don't have an object, // then the rest of the path does not exist. v = null; } } if (v == null) { return null; } else { return new SimpleConfigObject(origin(), Collections.singletonMap(key, v), v.resolveStatus(), ignoresFallbacks); } } @Override SimpleConfigObject withOnlyPath(Path path) { SimpleConfigObject o = withOnlyPathOrNull(path); if (o == null) { return new SimpleConfigObject(origin(), Collections.<String, AbstractConfigValue> emptyMap(), ResolveStatus.RESOLVED, ignoresFallbacks); } else { return o; } } @Override SimpleConfigObject withoutPath(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (v != null && next != null && v instanceof AbstractConfigObject) { v = ((AbstractConfigObject) v).withoutPath(next); Map<String, AbstractConfigValue> updated = new HashMap<String, AbstractConfigValue>( value); updated.put(key, v); return new SimpleConfigObject(origin(), updated, ResolveStatus.fromValues(updated .values()), ignoresFallbacks); } else if (next != null || v == null) { // can't descend, nothing to remove return this; } else { Map<String, AbstractConfigValue> smaller = new HashMap<String, AbstractConfigValue>( value.size() - 1); for (Map.Entry<String, AbstractConfigValue> old : value.entrySet()) { if (!old.getKey().equals(key)) smaller.put(old.getKey(), old.getValue()); } return new SimpleConfigObject(origin(), smaller, ResolveStatus.fromValues(smaller .values()), ignoresFallbacks); } } @Override public SimpleConfigObject withValue(String key, ConfigValue v) { if (v == null) throw new ConfigException.BugOrBroken( "Trying to store null ConfigValue in a ConfigObject"); Map<String, AbstractConfigValue> newMap; if (value.isEmpty()) { newMap = Collections.singletonMap(key, (AbstractConfigValue) v); } else { newMap = new HashMap<String, AbstractConfigValue>(value); newMap.put(key, (AbstractConfigValue) v); } return new SimpleConfigObject(origin(), newMap, ResolveStatus.fromValues(newMap.values()), ignoresFallbacks); } @Override SimpleConfigObject withValue(Path path, ConfigValue v) { String key = path.first(); Path next = path.remainder(); if (next == null) { return withValue(key, v); } else { AbstractConfigValue child = value.get(key); if (child != null && child instanceof AbstractConfigObject) { // if we have an object, add to it return withValue(key, ((AbstractConfigObject) child).withValue(next, v)); } else { // as soon as we have a non-object, replace it entirely SimpleConfig subtree = ((AbstractConfigValue) v).atPath( SimpleConfigOrigin.newSimple("withValue(" + next.render() + ")"), next); return withValue(key, subtree.root()); } } } @Override protected AbstractConfigValue attemptPeekWithPartialResolve(String key) { return value.get(key); } private SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin, boolean newIgnoresFallbacks) { return new SimpleConfigObject(newOrigin, value, newStatus, newIgnoresFallbacks); } @Override protected SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin) { return newCopy(newStatus, newOrigin, ignoresFallbacks); } @Override protected SimpleConfigObject withFallbacksIgnored() { if (ignoresFallbacks) return this; else return newCopy(resolveStatus(), origin(), true /* ignoresFallbacks */); } @Override ResolveStatus resolveStatus() { return ResolveStatus.fromBoolean(resolved); } @Override public SimpleConfigObject replaceChild(AbstractConfigValue child, AbstractConfigValue replacement) { HashMap<String, AbstractConfigValue> newChildren = new HashMap<String, AbstractConfigValue>(value); for (Map.Entry<String, AbstractConfigValue> old : newChildren.entrySet()) { if (old.getValue() == child) { if (replacement != null) old.setValue(replacement); else newChildren.remove(old.getKey()); return new SimpleConfigObject(origin(), newChildren, ResolveStatus.fromValues(newChildren.values()), ignoresFallbacks); } } throw new ConfigException.BugOrBroken("SimpleConfigObject.replaceChild did not find " + child + " in " + this); } @Override public boolean hasDescendant(AbstractConfigValue descendant) { for (AbstractConfigValue child : value.values()) { if (child == descendant) return true; } // now do the expensive search for (AbstractConfigValue child : value.values()) { if (child instanceof Container && ((Container) child).hasDescendant(descendant)) return true; } return false; } @Override protected boolean ignoresFallbacks() { return ignoresFallbacks; } @Override public Map<String, Object> unwrapped() { Map<String, Object> m = new HashMap<String, Object>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { m.put(e.getKey(), e.getValue().unwrapped()); } return m; } @Override protected SimpleConfigObject mergedWithObject(AbstractConfigObject abstractFallback) { requireNotIgnoringFallbacks(); if (!(abstractFallback instanceof SimpleConfigObject)) { throw new ConfigException.BugOrBroken( "should not be reached (merging non-SimpleConfigObject)"); } SimpleConfigObject fallback = (SimpleConfigObject) abstractFallback; boolean changed = false; boolean allResolved = true; Map<String, AbstractConfigValue> merged = new HashMap<String, AbstractConfigValue>(); Set<String> allKeys = new HashSet<String>(); allKeys.addAll(this.keySet()); allKeys.addAll(fallback.keySet()); for (String key : allKeys) { AbstractConfigValue first = this.value.get(key); AbstractConfigValue second = fallback.value.get(key); AbstractConfigValue kept; if (first == null) kept = second; else if (second == null) kept = first; else kept = first.withFallback(second); merged.put(key, kept); if (first != kept) changed = true; if (kept.resolveStatus() == ResolveStatus.UNRESOLVED) allResolved = false; } ResolveStatus newResolveStatus = ResolveStatus.fromBoolean(allResolved); boolean newIgnoresFallbacks = fallback.ignoresFallbacks(); if (changed) return new SimpleConfigObject(mergeOrigins(this, fallback), merged, newResolveStatus, newIgnoresFallbacks); else if (newResolveStatus != resolveStatus() || newIgnoresFallbacks != ignoresFallbacks()) return newCopy(newResolveStatus, origin(), newIgnoresFallbacks); else return this; } private SimpleConfigObject modify(NoExceptionsModifier modifier) { try { return modifyMayThrow(modifier); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } private SimpleConfigObject modifyMayThrow(Modifier modifier) throws Exception { Map<String, AbstractConfigValue> changes = null; for (String k : keySet()) { AbstractConfigValue v = value.get(k); // "modified" may be null, which means remove the child; // to do that we put null in the "changes" map. AbstractConfigValue modified = modifier.modifyChildMayThrow(k, v); if (modified != v) { if (changes == null) changes = new HashMap<String, AbstractConfigValue>(); changes.put(k, modified); } } if (changes == null) { return this; } else { Map<String, AbstractConfigValue> modified = new HashMap<String, AbstractConfigValue>(); boolean sawUnresolved = false; for (String k : keySet()) { if (changes.containsKey(k)) { AbstractConfigValue newValue = changes.get(k); if (newValue != null) { modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } else { // remove this child; don't put it in the new map. } } else { AbstractConfigValue newValue = value.get(k); modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } } return new SimpleConfigObject(origin(), modified, sawUnresolved ? ResolveStatus.UNRESOLVED : ResolveStatus.RESOLVED, ignoresFallbacks()); } } private static final class ResolveModifier implements Modifier { final Path originalRestrict; ResolveContext context; final ResolveSource source; ResolveModifier(ResolveContext context, ResolveSource source) { this.context = context; this.source = source; originalRestrict = context.restrictToChild(); } @Override public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) throws NotPossibleToResolve { if (context.isRestrictedToChild()) { if (key.equals(context.restrictToChild().first())) { Path remainder = context.restrictToChild().remainder(); if (remainder != null) { ResolveResult<? extends AbstractConfigValue> result = context.restrict(remainder).resolve(v, source); context = result.context.unrestricted().restrict(originalRestrict); return result.value; } else { // we don't want to resolve the leaf child. return v; } } else { // not in the restrictToChild path return v; } } else { // no restrictToChild, resolve everything ResolveResult<? extends AbstractConfigValue> result = context.unrestricted().resolve(v, source); context = result.context.unrestricted().restrict(originalRestrict); return result.value; } } } @Override ResolveResult<? extends AbstractConfigObject> resolveSubstitutions(ResolveContext context, ResolveSource source) throws NotPossibleToResolve { if (resolveStatus() == ResolveStatus.RESOLVED) return ResolveResult.make(context, this); final ResolveSource sourceWithParent = source.pushParent(this); try { ResolveModifier modifier = new ResolveModifier(context, sourceWithParent); AbstractConfigValue value = modifyMayThrow(modifier); return ResolveResult.make(modifier.context, value).asObjectResult(); } catch (NotPossibleToResolve e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } @Override SimpleConfigObject relativized(final Path prefix) { return modify(new NoExceptionsModifier() { @Override public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) { return v.relativized(prefix); } }); } // this is only Serializable to chill out a findbugs warning static final private class RenderComparator implements java.util.Comparator<String>, Serializable { private static final long serialVersionUID = 1L; private static boolean isAllDigits(String s) { int length = s.length(); // empty string doesn't count as a number // string longer than "max number of digits in a long" cannot be parsed as a long if (length == 0) return false; for (int i = 0; i < length; ++i) { char c = s.charAt(i); if (!Character.isDigit(c)) return false; } return true; } // This is supposed to sort numbers before strings, // and sort the numbers numerically. The point is // to make objects which are really list-like // (numeric indices) appear in order. @Override public int compare(String a, String b) { boolean aDigits = isAllDigits(a); boolean bDigits = isAllDigits(b); if (aDigits && bDigits) { return new BigInteger(a).compareTo(new BigInteger(b)); } else if (aDigits) { return -1; } else if (bDigits) { return 1; } else { return a.compareTo(b); } } } @Override protected void render(StringBuilder sb, int indent, boolean atRoot, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = options.getJson() || !atRoot; int innerIndent; if (outerBraces) { innerIndent = indent + 1; sb.append("{"); if (options.getFormatted()) sb.append('\n'); } else { innerIndent = indent; } int separatorCount = 0; String[] keys = keySet().toArray(new String[size()]); Arrays.sort(keys, new RenderComparator()); for (String k : keys) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { String[] lines = v.origin().description().split("\n"); for (String l : lines) { indent(sb, indent + 1, options); sb.append('#'); if (!l.isEmpty()) sb.append(' '); sb.append(l); sb.append("\n"); } } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, innerIndent, options); sb.append("#"); if (!comment.startsWith(" ")) sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, innerIndent, options); v.render(sb, innerIndent, false /* atRoot */, k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; }<|fim▁hole|> } } // chop last commas/newlines sb.setLength(sb.length() - separatorCount); if (outerBraces) { if (options.getFormatted()) { sb.append('\n'); // put a newline back if (outerBraces) indent(sb, indent, options); } sb.append("}"); } } if (atRoot && options.getFormatted()) sb.append('\n'); } @Override public AbstractConfigValue get(Object key) { return value.get(key); } private static boolean mapEquals(Map<String, ConfigValue> a, Map<String, ConfigValue> b) { if (a == b) return true; Set<String> aKeys = a.keySet(); Set<String> bKeys = b.keySet(); if (!aKeys.equals(bKeys)) return false; for (String key : aKeys) { if (!a.get(key).equals(b.get(key))) return false; } return true; } private static int mapHash(Map<String, ConfigValue> m) { // the keys have to be sorted, otherwise we could be equal // to another map but have a different hashcode. List<String> keys = new ArrayList<String>(); keys.addAll(m.keySet()); Collections.sort(keys); int valuesHash = 0; for (String k : keys) { valuesHash += m.get(k).hashCode(); } return 41 * (41 + keys.hashCode()) + valuesHash; } @Override protected boolean canEqual(Object other) { return other instanceof ConfigObject; } @Override public boolean equals(Object other) { // note that "origin" is deliberately NOT part of equality. // neither are other "extras" like ignoresFallbacks or resolve status. if (other instanceof ConfigObject) { // optimization to avoid unwrapped() for two ConfigObject, // which is what AbstractConfigValue does. return canEqual(other) && mapEquals(this, ((ConfigObject) other)); } else { return false; } } @Override public int hashCode() { // note that "origin" is deliberately NOT part of equality // neither are other "extras" like ignoresFallbacks or resolve status. return mapHash(this); } @Override public boolean containsKey(Object key) { return value.containsKey(key); } @Override public Set<String> keySet() { return value.keySet(); } @Override public boolean containsValue(Object v) { return value.containsValue(v); } @Override public Set<Map.Entry<String, ConfigValue>> entrySet() { // total bloat just to work around lack of type variance HashSet<java.util.Map.Entry<String, ConfigValue>> entries = new HashSet<Map.Entry<String, ConfigValue>>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { entries.add(new AbstractMap.SimpleImmutableEntry<String, ConfigValue>( e.getKey(), e .getValue())); } return entries; } @Override public boolean isEmpty() { return value.isEmpty(); } @Override public int size() { return value.size(); } @Override public Collection<ConfigValue> values() { return new HashSet<ConfigValue>(value.values()); } final private static String EMPTY_NAME = "empty config"; final private static SimpleConfigObject emptyInstance = empty(SimpleConfigOrigin .newSimple(EMPTY_NAME)); final static SimpleConfigObject empty() { return emptyInstance; } final static SimpleConfigObject empty(ConfigOrigin origin) { if (origin == null) return empty(); else return new SimpleConfigObject(origin, Collections.<String, AbstractConfigValue> emptyMap()); } final static SimpleConfigObject emptyMissing(ConfigOrigin baseOrigin) { return new SimpleConfigObject(SimpleConfigOrigin.newSimple( baseOrigin.description() + " (not found)"), Collections.<String, AbstractConfigValue> emptyMap()); } // serialization all goes through SerializedConfigValue private Object writeReplace() throws ObjectStreamException { return new SerializedConfigValue(this); } }<|fim▁end|>
sb.append('\n'); } else { sb.append(","); separatorCount = 1;
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.conf import settings from django.db import models from django.template.context import Context from django.template.loader import get_template_from_string from django.utils import timezone import swapper class BaseLogEntry(models.Model): """ A base class that implements the interface necessary to log an event. The render method returns a representation of this event. """ event = models.ForeignKey(swapper.get_model_name('loggit', 'LogEvent'), related_name='(classname)%s') created_ts = models.DateTimeField(default=timezone.now) def render(self, **kwargs): """ A method to render this entry. This can be overridden to provide custom behavior. For example, if you want the entry to return a different rendering based on who was viewing it, or when it is being viewed. This default rendering just returns the event's rendering. """ return self.event.render(self, **kwargs) class Meta: abstract = True class ActorMixin(models.Model): actor = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="(classname)%s") class Meta: abstract = True class LogEntry(BaseLogEntry, ActorMixin): class Meta(BaseLogEntry.Meta): swappable = swapper.swappable_setting('loggit', 'LogEntry') class BaseLogEvent(models.Model): """ The base class that defines some event happening. """ name = models.CharField(max_length=255) class Meta: abstract = True def __unicode__(self): return self.name def get_context(self, **kwargs): return Context(kwargs) def render(self, entry, **kwargs): """ Render method for a log event. This base method just returns the name. """<|fim▁hole|>class TemplateLogEvent(BaseLogEvent): """ A subclass of BaseLogEvent that renders a template using django's templating engine. The current entry is added to the context that is passed to the template. """ template = models.TextField() class Meta: abstract = True def render(self, entry, **kwargs): kwargs['entry'] = entry context = self.get_context(**kwargs) return get_template_from_string(self.template).render(context) class LogEvent(TemplateLogEvent): class Meta(TemplateLogEvent.Meta): swappable = swapper.swappable_setting('loggit', 'LogEvent') # Optional models using django-genericm2m that allow attaching of objects to # a log event try: from collections import defaultdict from genericm2m.models import RelatedObjectsDescriptor from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class RelatedObject(models.Model): log_entry = models.ForeignKey(swapper.get_model_name('loggit', 'LogEntry'), related_name='log_entries') # ACTUAL RELATED OBJECT: content_type = models.ForeignKey(ContentType, related_name="related_%(class)s") object_id = models.IntegerField(db_index=True) object = GenericForeignKey(fk_field="object_id") label = models.CharField(max_length=255) class M2MLogEntryMixin(models.Model): related = RelatedObjectsDescriptor(RelatedObject, 'log_entry', 'object') class Meta: abstract = True class M2MLogEventMixin(object): def get_context(self, **kwargs): entry = kwargs.pop('entry') models_context = defaultdict(list) for relation in entry.related.order_by('label'): models_context[relation.label].append(relation.object) return super(M2MLogEventMixin, self).get_context(**models_context) except ImportError: pass<|fim▁end|>
return unicode(self.name)
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url from .views import ObservationListView, AddObservationView, UploadObservationsView <|fim▁hole|> url( r"^(?P<observer_id>\d+)/$", ObservationListView.as_view(), name="observation_list_by_observer", ), url(r"^add/$", AddObservationView.as_view(), name="add_observation"), url( r"^add/(?P<star_id>\d+)/$", AddObservationView.as_view(), name="add_observation_for_star", ), url(r"^upload/$", UploadObservationsView.as_view(), name="upload_observations"), ]<|fim▁end|>
app_name = "observations" urlpatterns = [ url(r"^$", ObservationListView.as_view(), name="observation_list"),
<|file_name|>user_entities_request.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from ..request import Request from ..query import Entity from ..query import Entry import json class UserEntity(Entity): """UserEntity object used for upload user entities. Detail information about user entities you can see at our site https://docs.api.ai/docs/userentities""" @property def session_id(self): """session_id parameter used for determinate of every unique users.""" return self._session_id @session_id.setter def session_id(self, session_id): self._session_id = session_id @property def extend(self): return self._extend @extend.setter def extend(self, extend): """extend parameter used definition user entities logic. If True then uploaded user entities will be mixed with user entities specified in server side else currently uploaded entities witll uverride server entities.""" self._extend = extend def __init__(self, name, entries, session_id=None, extend=False): super(UserEntity, self).__init__(name, entries) self._session_id = session_id self._extend = extend """Private method used for object serialization.""" def _to_dict(self): parent_data = super(UserEntity, self)._to_dict() if self._session_id is not None: parent_data['sessionId'] = self._session_id parent_data['extend'] = self._extend return parent_data class UserEntityEntry(Entry): """UserEntityEntry object used for upload user entities. Detail information about user entities you can see at our site https://docs.api.ai/docs/userentities""" pass class UserEntitiesRequest(Request): """UserEntitiesRequest is request for upload user entities. Detail see http://docs.api.ai/""" @property def user_entities(self): "user_entities parameter for specification of same user entities." return self._user_entities @user_entities.setter def user_entities(self, user_entities): self._user_entities = user_entities def __init__(self, client_access_token, base_url, user_entities=[]): super(UserEntitiesRequest, self).__init__(client_access_token, base_url, '/v1/userEntities', {}) self._user_entities = user_entities def _prepare_headers(self): return { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': len(self._prepage_end_request_data()) } def _prepage_begin_request_data(self):<|fim▁hole|> def _prepage_end_request_data(self): return json.dumps(map(lambda x: x._to_dict(), self._user_entities))<|fim▁end|>
return None
<|file_name|>textModelResolverService.test.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ITextModel } from 'vs/editor/common/model'; import { URI } from 'vs/base/common/uri'; import { TextResourceEditorInput } from 'vs/workbench/common/editor/textResourceEditorInput'; import { TextResourceEditorModel } from 'vs/workbench/common/editor/textResourceEditorModel'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { workbenchInstantiationService, TestServiceAccessor, TestTextFileEditorModelManager } from 'vs/workbench/test/browser/workbenchTestServices'; import { toResource } from 'vs/base/test/common/utils'; import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel'; import { snapshotToString } from 'vs/workbench/services/textfile/common/textfiles'; import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager'; import { Event } from 'vs/base/common/event'; import { timeout } from 'vs/base/common/async'; import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput'; import { createTextBufferFactory } from 'vs/editor/common/model/textModel'; suite('Workbench - TextModelResolverService', () => { let instantiationService: IInstantiationService;<|fim▁hole|> let accessor: TestServiceAccessor; let model: TextFileEditorModel; setup(() => { instantiationService = workbenchInstantiationService(); accessor = instantiationService.createInstance(TestServiceAccessor); }); teardown(() => { model?.dispose(); (<TextFileEditorModelManager>accessor.textFileService.files).dispose(); }); test('resolve resource', async () => { const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', { provideTextContent: async function (resource: URI): Promise<ITextModel | null> { if (resource.scheme === 'test') { let modelContent = 'Hello Test'; let languageSelection = accessor.modeService.create('json'); return accessor.modelService.createModel(modelContent, languageSelection, resource); } return null; } }); let resource = URI.from({ scheme: 'test', authority: null!, path: 'thePath' }); let input = instantiationService.createInstance(TextResourceEditorInput, resource, 'The Name', 'The Description', undefined, undefined); const model = await input.resolve(); assert.ok(model); assert.strictEqual(snapshotToString(((model as TextResourceEditorModel).createSnapshot()!)), 'Hello Test'); let disposed = false; let disposedPromise = new Promise<void>(resolve => { Event.once(model.onWillDispose)(() => { disposed = true; resolve(); }); }); input.dispose(); await disposedPromise; assert.strictEqual(disposed, true); disposable.dispose(); }); test('resolve file', async function () { const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined); (<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel); await textModel.resolve(); const ref = await accessor.textModelResolverService.createModelReference(textModel.resource); const model = ref.object; const editorModel = model.textEditorModel; assert.ok(editorModel); assert.strictEqual(editorModel.getValue(), 'Hello Html'); let disposed = false; Event.once(model.onWillDispose)(() => { disposed = true; }); ref.dispose(); await timeout(0); // due to the reference resolving the model first which is async assert.strictEqual(disposed, true); }); test('resolved dirty file eventually disposes', async function () { const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined); (<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel); await textModel.resolve(); textModel.updateTextEditorModel(createTextBufferFactory('make dirty')); const ref = await accessor.textModelResolverService.createModelReference(textModel.resource); let disposed = false; Event.once(textModel.onWillDispose)(() => { disposed = true; }); ref.dispose(); await timeout(0); assert.strictEqual(disposed, false); // not disposed because model still dirty textModel.revert(); await timeout(0); assert.strictEqual(disposed, true); // now disposed because model got reverted }); test('resolved dirty file does not dispose when new reference created', async function () { const textModel = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8', undefined); (<TestTextFileEditorModelManager>accessor.textFileService.files).add(textModel.resource, textModel); await textModel.resolve(); textModel.updateTextEditorModel(createTextBufferFactory('make dirty')); const ref1 = await accessor.textModelResolverService.createModelReference(textModel.resource); let disposed = false; Event.once(textModel.onWillDispose)(() => { disposed = true; }); ref1.dispose(); await timeout(0); assert.strictEqual(disposed, false); // not disposed because model still dirty const ref2 = await accessor.textModelResolverService.createModelReference(textModel.resource); textModel.revert(); await timeout(0); assert.strictEqual(disposed, false); // not disposed because we got another ref meanwhile ref2.dispose(); await timeout(0); assert.strictEqual(disposed, true); // now disposed because last ref got disposed }); test('resolve untitled', async () => { const service = accessor.untitledTextEditorService; const untitledModel = service.create(); const input = instantiationService.createInstance(UntitledTextEditorInput, untitledModel); await input.resolve(); const ref = await accessor.textModelResolverService.createModelReference(input.resource); const model = ref.object; assert.strictEqual(untitledModel, model); const editorModel = model.textEditorModel; assert.ok(editorModel); ref.dispose(); input.dispose(); model.dispose(); }); test('even loading documents should be refcounted', async () => { let resolveModel!: Function; let waitForIt = new Promise(resolve => resolveModel = resolve); const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', { provideTextContent: async (resource: URI): Promise<ITextModel> => { await waitForIt; let modelContent = 'Hello Test'; let languageSelection = accessor.modeService.create('json'); return accessor.modelService.createModel(modelContent, languageSelection, resource); } }); const uri = URI.from({ scheme: 'test', authority: null!, path: 'thePath' }); const modelRefPromise1 = accessor.textModelResolverService.createModelReference(uri); const modelRefPromise2 = accessor.textModelResolverService.createModelReference(uri); resolveModel(); const modelRef1 = await modelRefPromise1; const model1 = modelRef1.object; const modelRef2 = await modelRefPromise2; const model2 = modelRef2.object; const textModel = model1.textEditorModel; assert.strictEqual(model1, model2, 'they are the same model'); assert(!textModel.isDisposed(), 'the text model should not be disposed'); modelRef1.dispose(); assert(!textModel.isDisposed(), 'the text model should still not be disposed'); let p1 = new Promise<void>(resolve => textModel.onWillDispose(resolve)); modelRef2.dispose(); await p1; assert(textModel.isDisposed(), 'the text model should finally be disposed'); disposable.dispose(); }); });<|fim▁end|>
<|file_name|>helper_functions.js<|end_file_name|><|fim▁begin|>/*----------------------------------------------------------------------*/ /* The name says it all */ /*----------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Subroutines */ /*-----------------------------------------------------------------------*/ function filterTasks(occ_code) { var results = []; for (var i = 0; i < taskData.length; i++) { if (taskData[i].fedscope_occ_code == occ_code) { newObject = {}; newObject = taskData[i]; newObject.hours = freq2hours(newObject.category);<|fim▁hole|> return results; } /*-----------------------------------------------------------------------*/ /* Convert frequency categories to hours */ /*-----------------------------------------------------------------------*/ function freq2hours(category) { var hours = 0; switch(category) { case "1": hours = .5; break; case "2": hours = 1; break; case "3": hours = 12; break; case "4": hours = 52; break; case "5": hours = 260; break; case "6": hours = 520; break; case "7": hours = 1043; break; default: console.log("Unknown frequency category: " + category); break; } return hours; } /*-----------------------------------------------------------------------*/ /* refresh the pie chart when you pass in a new occ code */ /*-----------------------------------------------------------------------*/ function refreshPie(newOccCode) { filteredTaskData = []; filteredTaskData = filterTasks(newOccCode); pieChartHandle.data(filteredTaskData) .draw(); $('#pie_heading').html("Hours per task for occupation " + newOccCode); }<|fim▁end|>
results.push(newObject); } }
<|file_name|>general_rates.py<|end_file_name|><|fim▁begin|># Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights # Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ============================================================================== """Contains functions for constructing binary or multiclass rate expressions. There are a number of rates (e.g. error_rate()) that can be defined for either binary classification or multiclass contexts. The former rates are implemented in binary_rates.py, and the latter in multiclass_rates.py. In this file, the given functions choose which rate to create based on the type of the context: for multiclass contexts, they'll call the corresponding implementation in multiclass_rates.py, otherwise, they'll call binary_rates.py. Many of the functions in this file take the optional "positive_class" parameter, which tells us which classes should be considered "positive" (for e.g. the positive prediction rate). This parameter *must* be provided for multiclass contexts, and must *not* be provided for non-multiclass contexts. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_constrained_optimization.python.rates import basic_expression from tensorflow_constrained_optimization.python.rates import binary_rates from tensorflow_constrained_optimization.python.rates import defaults from tensorflow_constrained_optimization.python.rates import deferred_tensor from tensorflow_constrained_optimization.python.rates import expression from tensorflow_constrained_optimization.python.rates import multiclass_rates from tensorflow_constrained_optimization.python.rates import subsettable_context from tensorflow_constrained_optimization.python.rates import term def _is_multiclass(context): """Returns True iff we're given a multiclass context.""" if not isinstance(context, subsettable_context.SubsettableContext): raise TypeError("context must be a SubsettableContext object") raw_context = context.raw_context return raw_context.num_classes is not None def _ratio_bound(numerator_expression, denominator_expression, lower_bound, upper_bound): """Creates an `Expression` for a bound on a ratio. The result of this function is an `Expression` representing: numerator / denominator_bound where denominator_bound is a newly-created slack variable projected to satisfy the following (in an update op): denominator_lower_bound <= denominator_bound <= 1 Additionally, the following constraint will be added if lower_bound is True: denominator_bound >= denominator_expression and/or the following if upper_bound is true: denominator_bound <= denominator_expression These constraints are placed in the "extra_constraints" field of the resulting `Expression`. If you're going to be lower-bounding or maximizing the result of this function, then need to set the lower_bound parameter to `True`. Likewise, if you're going to be upper-bounding or minimizing the result of this function, then the upper_bound parameter must be `True`. At least one of these parameters *must* be `True`, and it's permitted for both of them to be `True` (but we recommend against this, since it would result in equality constraints, which might cause problems during optimization and/or post-processing). Args: numerator_expression: `Expression`, the numerator of the ratio. denominator_expression: `Expression`, the denominator of the ratio. The value of this expression must be between zero and one. lower_bound: bool, `True` if you want the result of this function to lower-bound the ratio. upper_bound: bool, `True` if you want the result of this function to upper-bound the ratio. Returns: An `Expression` representing the ratio. Raises: TypeError: if either numerator_expression or denominator_expression is not an `Expression`. ValueError: if both lower_bound and upper_bound are `False`. """ if not (isinstance(numerator_expression, expression.Expression) and isinstance(denominator_expression, expression.Expression)): raise TypeError( "both numerator_expression and denominator_expression must be " "Expressions (perhaps you need to call wrap_rate() to create an " "Expression from a Tensor?)") # One could set both lower_bound and upper_bound to True, in which case the # result of this function could be treated as the ratio itself (instead of a # {lower,upper} bound of it). However, this would come with some drawbacks: it # would of course make optimization more difficult, but more importantly, it # would potentially cause post-processing for feasibility (e.g. using # "shrinking") to fail to find a feasible solution. if not (lower_bound or upper_bound): raise ValueError("at least one of lower_bound or upper_bound must be True") # We use an "update_ops_fn" instead of a "constraint" (which we would usually # prefer) to perform the projection because we want to grab the denominator # lower bound out of the structure_memoizer. def update_ops_fn(denominator_bound_variable, structure_memoizer, value_memoizer): """Projects denominator_bound onto the feasible region.""" del value_memoizer denominator_bound = tf.maximum( structure_memoizer[defaults.DENOMINATOR_LOWER_BOUND_KEY], tf.minimum(1.0, denominator_bound_variable)) return [denominator_bound_variable.assign(denominator_bound)] # Ideally the slack variable would have the same dtype as the predictions, but # we might not know their dtype (e.g. in eager mode), so instead we always use # float32 with auto_cast=True. denominator_bound = deferred_tensor.DeferredVariable( 1.0, trainable=True, name="tfco_denominator_bound", dtype=tf.float32, update_ops_fn=update_ops_fn, auto_cast=True) denominator_bound_basic_expression = basic_expression.BasicExpression( [term.TensorTerm(denominator_bound)]) denominator_bound_expression = expression.ExplicitExpression( penalty_expression=denominator_bound_basic_expression, constraint_expression=denominator_bound_basic_expression) extra_constraints = [] if lower_bound: extra_constraints.append( denominator_expression <= denominator_bound_expression) if upper_bound: extra_constraints.append( denominator_bound_expression <= denominator_expression) return expression.ConstrainedExpression( expression=numerator_expression._positive_scalar_div(denominator_bound), # pylint: disable=protected-access extra_constraints=extra_constraints) def _ratio(numerator_expression, denominator_expression): """Creates an `Expression` for a ratio. The result of this function is an `Expression` representing: numerator / denominator_bound where denominator_bound satisfies the following: denominator_lower_bound <= denominator_bound <= 1 The resulting `Expression` will include both the implicit denominator_bound slack variable, and implicit constraints. Args: numerator_expression: `Expression`, the numerator of the ratio. denominator_expression: `Expression`, the denominator of the ratio. Returns: An `Expression` representing the ratio. Raises: TypeError: if either numerator_expression or denominator_expression is not an `Expression`. """ return expression.BoundedExpression( lower_bound=_ratio_bound( numerator_expression=numerator_expression, denominator_expression=denominator_expression, lower_bound=True, upper_bound=False), upper_bound=_ratio_bound( numerator_expression=numerator_expression, denominator_expression=denominator_expression, lower_bound=False, upper_bound=True)) def positive_prediction_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a positive prediction rate. A positive prediction rate is the number of examples within the given context on which the model makes a positive prediction, divided by the number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of positive_prediction_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the positive prediction rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.positive_prediction_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "positive_prediction_rate unless it's also given a " "multiclass context") return binary_rates.positive_prediction_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def negative_prediction_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a negative prediction rate. A negative prediction rate is the number of examples within the given context on which the model makes a negative prediction, divided by the number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of negative_prediction_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the negative prediction rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.negative_prediction_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "negative_prediction_rate unless it's also given a " "multiclass context") return binary_rates.negative_prediction_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def error_rate(context, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for an error rate. An error rate is the number of examples within the given context on which the model makes an incorrect prediction, divided by the number of examples within the context. Please see the docstrings of error_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the error rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). ValueError: if the context doesn't contain labels. """ if _is_multiclass(context): return multiclass_rates.error_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) return binary_rates.error_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def accuracy_rate(context, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for an accuracy rate. An accuracy rate is the number of examples within the given context on which the model makes a correct prediction, divided by the number of examples within the context. Please see the docstrings of accuracy_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the accuracy rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). ValueError: if the context doesn't contain labels. """ if _is_multiclass(context): return multiclass_rates.accuracy_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) return binary_rates.accuracy_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def true_positive_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a true positive rate. A true positive rate is the number of positively-labeled examples within the given context on which the model makes a positive prediction, divided by the number of positively-labeled examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of true_positive_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the true positive rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.true_positive_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "true_positive_rate unless it's also given a multiclass " "context") return binary_rates.true_positive_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def false_negative_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a false negative rate. A false negative rate is the number of positively-labeled examples within the given context on which the model makes a negative prediction, divided by the number of positively-labeled examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of false_negative_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the false negative rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.false_negative_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "false_negative_rate unless it's also given a multiclass " "context") return binary_rates.false_negative_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def false_positive_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a false positive rate. A false positive rate is the number of negatively-labeled examples within the given context on which the model makes a positive prediction, divided by the number of negatively-labeled examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of false_positive_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the false positive rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.false_positive_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "false_positive_rate unless it's also given a multiclass " "context") return binary_rates.false_positive_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def true_negative_rate(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a true negative rate. A true negative rate is the number of negatively-labeled examples within the given context on which the model makes a negative prediction, divided by the number of negatively-labeled examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of true_negative_rate() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the true negative rate. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.true_negative_rate( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "true_negative_rate unless it's also given a multiclass " "context") return binary_rates.true_negative_rate( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def true_positive_proportion(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a true positive proportion. A true positive proportion is the number of positively-labeled examples within the given context on which the model makes a positive prediction, divided by the total number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of true_positive_proportion() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the true positive proportion. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.true_positive_proportion( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError( "positive_class cannot be provided to " "true_positive_proportion unless it's also given a multiclass " "context") return binary_rates.true_positive_proportion( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def false_negative_proportion(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a false negative proportion. A false negative proportion is the number of positively-labeled examples within the given context on which the model makes a negative prediction, divided by the total number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of false_negative_proportion() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the false negative proportion. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.false_negative_proportion( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError( "positive_class cannot be provided to " "false_negative_proportion unless it's also given a multiclass " "context") return binary_rates.false_negative_proportion( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def false_positive_proportion(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a false positive proportion. A false positive proportion is the number of negatively-labeled examples within the given context on which the model makes a positive prediction, divided by the total number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of false_positive_proportion() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the false positive proportion. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.false_positive_proportion( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss)<|fim▁hole|> "false_positive_proportion unless it's also given a multiclass " "context") return binary_rates.false_positive_proportion( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def true_negative_proportion(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a true negative proportion. A true negative proportion is the number of negatively-labeled examples within the given context on which the model makes a negative prediction, divided by the total number of examples within the context. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of true_negative_proportion() in binary_rates.py and multiclass_rates.py for further details. Args: context: `SubsettableContext`, the block of data to use when calculating the rate. If this is a multiclass context, we'll calculate the multiclass version of the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the true negative proportion. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.true_negative_proportion( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError( "positive_class cannot be provided to " "true_negative_proportion unless it's also given a multiclass " "context") return binary_rates.true_negative_proportion( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def precision_ratio(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates two `Expression`s representing precision as a ratio. A precision is the number of positively-labeled examples within the given context on which the model makes a positive prediction, divided by the number of examples within the context on which the model makes a positive prediction. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of precision_ratio() in binary_rates.py and multiclass_rates.py for further details. The reason for decomposing a precision as a separate numerator and denominator is to make it easy to set up constraints of the form (for example): > precision := numerator / denominator >= 0.9 for which you can multiply through by the denominator to yield the equivalent constraint: > numerator >= 0.9 * denominator This latter form is something that we can straightforwardly handle. Args: context: multiclass `SubsettableContext`, the block of data to use when calculating the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An (`Expression`, `Expression`) pair representing the numerator and denominator of a precision, respectively. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.precision_ratio( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "precision_ratio unless it's also given a multiclass " "context") return binary_rates.precision_ratio( context=context, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def precision(context, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression`s for precision. A precision is the number of positively-labeled examples within the given context on which the model makes a positive prediction, divided by the number of examples within the context on which the model makes a positive prediction. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Args: context: multiclass `SubsettableContext`, the block of data to use when calculating the rate. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the precision. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ numerator_expression, denominator_expression = precision_ratio( context=context, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) return _ratio( numerator_expression=numerator_expression, denominator_expression=denominator_expression) def f_score_ratio(context, beta=1.0, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates two `Expression`s representing F-score as a ratio. An F score [Wikipedia](https://en.wikipedia.org/wiki/F1_score), is a harmonic mean of recall and precision, where the parameter beta weights the importance of the precision component. If beta=1, the result is the usual harmonic mean (the F1 score) of these two quantities. If beta=0, the result is the precision, and as beta goes to infinity, the result converges to the recall. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Please see the docstrings of f_score_ratio() in binary_rates.py and multiclass_rates.py for further details. The reason for decomposing an F-score as a separate numerator and denominator is to make it easy to set up constraints of the form (for example): > f_score := numerator / denominator >= 0.9 for which you can multiply through by the denominator to yield the equivalent constraint: > numerator >= 0.9 * denominator This latter form is something that we can straightforwardly handle. Args: context: multiclass `SubsettableContext`, the block of data to use when calculating the rate. beta: non-negative float, the beta parameter to the F-score. If beta=0, then the result is precision, and if beta=1 (the default), then the result is the F1-score. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An (`Expression`, `Expression`) pair representing the numerator and denominator of an F-score, respectively. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ if _is_multiclass(context): return multiclass_rates.f_score_ratio( context=context, positive_class=positive_class, beta=beta, penalty_loss=penalty_loss, constraint_loss=constraint_loss) if positive_class is not None: raise ValueError("positive_class cannot be provided to " "f_score_ratio unless it's also given a multiclass " "context") return binary_rates.f_score_ratio( context=context, beta=beta, penalty_loss=penalty_loss, constraint_loss=constraint_loss) def f_score(context, beta=1.0, positive_class=None, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for F-score. An F score [Wikipedia](https://en.wikipedia.org/wiki/F1_score), is a harmonic mean of recall and precision, where the parameter beta weights the importance of the precision component. If beta=1, the result is the usual harmonic mean (the F1 score) of these two quantities. If beta=0, the result is the precision, and as beta goes to infinity, the result converges to the recall. For multiclass problems, the positive_class argument, which tells us which class (or classes) should be treated as positive, must also be provided. Args: context: multiclass `SubsettableContext`, the block of data to use when calculating the rate. beta: non-negative float, the beta parameter to the F-score. If beta=0, then the result is precision, and if beta=1 (the default), then the result is the F1-score. positive_class: None for a non-multiclass problem. Otherwise, an int, the index of the class to treat as "positive", *or* a collection of num_classes elements, where the ith element is the probability that the ith class should be treated as "positive". penalty_loss: `MulticlassLoss`, the (differentiable) loss function to use when calculating the "penalty" approximation to the rate. constraint_loss: `MulticlassLoss`, the (not necessarily differentiable) loss function to use when calculating the "constraint" approximation to the rate. Returns: An `Expression` representing the F-score. Raises: TypeError: if the context is not a SubsettableContext, either loss is not a BinaryClassificationLoss (if the context is non-multiclass) or a MulticlassLoss (if the context is multiclass). In the latter case, an error will also be raised if positive_class is a non-integer number. ValueError: if the context doesn't contain labels, or positive_class is provided for a non-multiclass context, or is *not* provided for a multiclass context. In the latter case, an error will also be raised if positive_class is an integer outside the range [0,num_classes), or is a collection not containing num_classes elements. """ numerator_expression, denominator_expression = f_score_ratio( context=context, beta=beta, positive_class=positive_class, penalty_loss=penalty_loss, constraint_loss=constraint_loss) return _ratio( numerator_expression=numerator_expression, denominator_expression=denominator_expression)<|fim▁end|>
if positive_class is not None: raise ValueError( "positive_class cannot be provided to "
<|file_name|>beforePeekFlatMapCount.java<|end_file_name|><|fim▁begin|>// "Replace with 'Stream.mapToLong().sum()'" "true" import java.util.Collection; import java.util.List;<|fim▁hole|> void foo(List<List<String>> s) { long count = s.stream().peek(System.out::println).flatMap(Collection::stream).c<caret>ount(); } }<|fim▁end|>
class Test {
<|file_name|>feed_parse_extractLittlebambooHomeBlog.py<|end_file_name|><|fim▁begin|><|fim▁hole|> Parser for 'littlebamboo.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('FW', 'Fortunate Wife', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False<|fim▁end|>
def extractLittlebambooHomeBlog(item): '''
<|file_name|>update_users_report_view_settings.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals from frappe.model import update_users_report_view_settings from erpnext.patches.v4_0.fields_to_be_renamed import rename_map def execute(): for dt, field_list in rename_map.items(): for field in field_list:<|fim▁hole|><|fim▁end|>
update_users_report_view_settings(dt, field[0], field[1])
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. 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<|fim▁hole|> 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. */ export * from './VisSingleValue'<|fim▁end|>
<|file_name|>position.js<|end_file_name|><|fim▁begin|>'use strict'; module.exports.definition = { set: function (v) { this._setProperty('position', v); }, get: function () { return this.getPropertyValue('position'); }, enumerable: true,<|fim▁hole|><|fim▁end|>
configurable: true };
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for object-hash v1.2.0 // Project: https://github.com/puleos/object-hash // Definitions by: Michael Zabka <https://github.com/misak113> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import HashStatic = ObjectHash.HashStatic; export = HashStatic; export as namespace objectHash; declare namespace ObjectHash { export interface IOptions { algorithm?: string; encoding?: string; excludeValues?: boolean; ignoreUnknown?: boolean; replacer?: (value: any) => any; respectFunctionProperties?: boolean; respectFunctionNames?: boolean; unorderedArrays?: boolean; unorderedSets?: boolean; excludeKeys?: (key: string) => boolean; } interface HashTableItem { value: any; count: number; } interface HashTableItemWithKey extends HashTableItem { hash: string; } export interface HashTable { add(...values: any[]): HashTable; remove(...values: any[]): HashTable; hasKey(key: string): boolean; getValue(key: string): any; getCount(key: string): number; table(): { [key: string]: HashTableItem }; toArray(): HashTableItemWithKey[]; reset(): HashTable; } export interface HashTableStatic { (options?: IOptions): HashTable; } export interface Hash { (object: any, options?: IOptions): string; sha1(object: any): string; keys(object: any): string;<|fim▁hole|> export var HashStatic: Hash; }<|fim▁end|>
MD5(object: any): string; keysMD5(object: any): string; HashTable: HashTableStatic; }
<|file_name|>prelude.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2017 Pietro Albini // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //! Prelude for Fisher. //! //! This module re-exports useful things used by all the Fisher code, to be<|fim▁hole|><|fim▁end|>
//! easily included. pub use super::errors::{Error, ErrorKind, Result, ResultExt}; pub use super::traits::*;
<|file_name|>Client.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import json class Client(): def __init__(self, clientHostName, clientPort, channel): self.clientHostName = clientHostName self.clientPort = clientPort self.clientType = self.getClientType() self.channel = channel # TO DO implement this method properly def getClientType(self): try: self.WebClient = "Web Client" self.MobileClient = "Mobile Client" return self.WebClient except ImportError as e: print json.dumps({"status" : "error", "Client.getClientType" : str(e)}) exit(0)<|fim▁end|>
#!/usr/bin/python
<|file_name|>0014_signuplog.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-10-03 02:38 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0013_auto_20161002_0504'),<|fim▁hole|> ] operations = [ migrations.CreateModel( name='SignUpLog', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('referer', models.CharField(max_length=255, null=True)), ('ip', models.CharField(max_length=255, null=True)), ('user', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]<|fim▁end|>
<|file_name|>test_urllib.py<|end_file_name|><|fim▁begin|>"""Regresssion tests for urllib""" import urllib import httplib import unittest import os import sys import mimetools import tempfile import StringIO from test import test_support from base64 import b64encode def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = "0%s" % hex_repr return "%" + hex_repr class FakeHTTPMixin(object): def fakehttp(self, fakedata): class FakeSocket(StringIO.StringIO): def sendall(self, data): FakeHTTPConnection.buf = data def makefile(self, *args, **kwds): return self def read(self, amt=None): if self.closed: return "" return StringIO.StringIO.read(self, amt) def readline(self, length=None): if self.closed: return "" return StringIO.StringIO.readline(self, length) class FakeHTTPConnection(httplib.HTTPConnection): # buffer to store data for verification in urlopen tests. buf = "" def connect(self): self.sock = FakeSocket(fakedata) assert httplib.HTTP._connection_class == httplib.HTTPConnection httplib.HTTP._connection_class = FakeHTTPConnection def unfakehttp(self): httplib.HTTP._connection_class = httplib.HTTPConnection class urlopen_FileTests(unittest.TestCase): """Test urlopen() opening a temporary file. Try to test as much functionality as possible so as to cut down on reliance on connecting to the Net for testing. """ def setUp(self): """Setup of a temp file to use for testing""" self.text = "test_urllib: %s\n" % self.__class__.__name__ FILE = file(test_support.TESTFN, 'wb') try: FILE.write(self.text) finally: FILE.close() self.pathname = test_support.TESTFN self.returned_obj = urllib.urlopen("file:%s" % self.pathname) def tearDown(self): """Shut down the open object""" self.returned_obj.close() os.remove(test_support.TESTFN) def test_interface(self): # Make sure object returned by urlopen() has the specified methods for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl", "getcode", "__iter__"): self.assertTrue(hasattr(self.returned_obj, attr), "object returned by urlopen() lacks %s attribute" % attr) def test_read(self): self.assertEqual(self.text, self.returned_obj.read()) def test_readline(self): self.assertEqual(self.text, self.returned_obj.readline()) self.assertEqual('', self.returned_obj.readline(), "calling readline() after exhausting the file did not" " return an empty string") def test_readlines(self): lines_list = self.returned_obj.readlines() self.assertEqual(len(lines_list), 1, "readlines() returned the wrong number of lines") self.assertEqual(lines_list[0], self.text, "readlines() returned improper text") def test_fileno(self): file_num = self.returned_obj.fileno() self.assertIsInstance(file_num, int, "fileno() did not return an int") self.assertEqual(os.read(file_num, len(self.text)), self.text, "Reading on the file descriptor returned by fileno() " "did not return the expected text") def test_close(self): # Test close() by calling it hear and then having it be called again # by the tearDown() method for the test self.returned_obj.close() def test_info(self): self.assertIsInstance(self.returned_obj.info(), mimetools.Message) def test_geturl(self): self.assertEqual(self.returned_obj.geturl(), self.pathname) def test_getcode(self): self.assertEqual(self.returned_obj.getcode(), None) def test_iter(self): # Test iterator # Don't need to count number of iterations since test would fail the # instant it returned anything beyond the first line from the # comparison for line in self.returned_obj.__iter__(): self.assertEqual(line, self.text) def test_relativelocalfile(self): self.assertRaises(ValueError,urllib.urlopen,'./' + self.pathname) class ProxyTests(unittest.TestCase): def setUp(self): # Records changes to env vars self.env = test_support.EnvironmentVarGuard() # Delete all proxy related env vars for k in os.environ.keys(): if 'proxy' in k.lower(): self.env.unset(k) def tearDown(self): # Restore all proxy related env vars self.env.__exit__() del self.env def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost') proxies = urllib.getproxies_environment() # getproxies_environment use lowered case truncated (no '_proxy') keys self.assertEqual('localhost', proxies['no']) # List of no_proxies with space. self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com')) class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urlopen() opening a fake http connection.""" def test_read(self): self.fakehttp('Hello!') try: fp = urllib.urlopen("http://python.org/") self.assertEqual(fp.readline(), 'Hello!') self.assertEqual(fp.readline(), '') self.assertEqual(fp.geturl(), 'http://python.org/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_url_fragment(self): # Issue #11703: geturl() omits fragments in the original URL. url = 'http://docs.python.org/library/urllib.html#OK' self.fakehttp('Hello!') try: fp = urllib.urlopen(url) self.assertEqual(fp.geturl(), url) finally: self.unfakehttp() def test_read_bogus(self): # urlopen() should raise IOError for many error codes. self.fakehttp('''HTTP/1.1 401 Authentication Required Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Type: text/html; charset=iso-8859-1 ''') try: self.assertRaises(IOError, urllib.urlopen, "http://python.org/") finally: self.unfakehttp() def test_invalid_redirect(self): # urlopen() should raise IOError for many error codes. self.fakehttp("""HTTP/1.1 302 Found Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Location: file:README Connection: close Content-Type: text/html; charset=iso-8859-1 """) try: self.assertRaises(IOError, urllib.urlopen, "http://python.org/") finally: self.unfakehttp() def test_empty_socket(self): # urlopen() raises IOError if the underlying socket does not send any # data. (#1680230) self.fakehttp('') try: self.assertRaises(IOError, urllib.urlopen, 'http://something') finally: self.unfakehttp() def test_missing_localfile(self): self.assertRaises(IOError, urllib.urlopen, 'file://localhost/a/missing/file.py') fd, tmp_file = tempfile.mkstemp() tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/') try: self.assertTrue(os.path.exists(tmp_file)) fp = urllib.urlopen(tmp_fileurl) finally: os.close(fd) fp.close() os.unlink(tmp_file) self.assertFalse(os.path.exists(tmp_file)) self.assertRaises(IOError, urllib.urlopen, tmp_fileurl) def test_ftp_nonexisting(self): self.assertRaises(IOError, urllib.urlopen, 'ftp://localhost/not/existing/file.py') def test_userpass_inurl(self): self.fakehttp('Hello!') try: fakehttp_wrapper = httplib.HTTP._connection_class fp = urllib.urlopen("http://user:[email protected]/") authorization = ("Authorization: Basic %s\r\n" % b64encode('user:pass'))<|fim▁hole|> self.assertEqual(fp.readline(), "") self.assertEqual(fp.geturl(), 'http://user:[email protected]/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_userpass_with_spaces_inurl(self): self.fakehttp('Hello!') try: url = "http://a b:c [email protected]/" fakehttp_wrapper = httplib.HTTP._connection_class authorization = ("Authorization: Basic %s\r\n" % b64encode('a b:c d')) fp = urllib.urlopen(url) # The authorization header must be in place self.assertIn(authorization, fakehttp_wrapper.buf) self.assertEqual(fp.readline(), "Hello!") self.assertEqual(fp.readline(), "") # the spaces are quoted in URL so no match self.assertNotEqual(fp.geturl(), url) self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() class urlretrieve_FileTests(unittest.TestCase): """Test urllib.urlretrieve() on local files""" def setUp(self): # Create a list of temporary files. Each item in the list is a file # name (absolute path or relative to the current working directory). # All files in this list will be deleted in the tearDown method. Note, # this only helps to makes sure temporary files get deleted, but it # does nothing about trying to close files that may still be open. It # is the responsibility of the developer to properly close files even # when exceptional conditions occur. self.tempFiles = [] # Create a temporary file. self.registerFileForCleanUp(test_support.TESTFN) self.text = 'testing urllib.urlretrieve' try: FILE = file(test_support.TESTFN, 'wb') FILE.write(self.text) FILE.close() finally: try: FILE.close() except: pass def tearDown(self): # Delete the temporary files. for each in self.tempFiles: try: os.remove(each) except: pass def constructLocalFileUrl(self, filePath): return "file://%s" % urllib.pathname2url(os.path.abspath(filePath)) def createNewTempFile(self, data=""): """Creates a new temporary file containing the specified data, registers the file for deletion during the test fixture tear down, and returns the absolute path of the file.""" newFd, newFilePath = tempfile.mkstemp() try: self.registerFileForCleanUp(newFilePath) newFile = os.fdopen(newFd, "wb") newFile.write(data) newFile.close() finally: try: newFile.close() except: pass return newFilePath def registerFileForCleanUp(self, fileName): self.tempFiles.append(fileName) def test_basic(self): # Make sure that a local file just gets its own location returned and # a headers value is returned. result = urllib.urlretrieve("file:%s" % test_support.TESTFN) self.assertEqual(result[0], test_support.TESTFN) self.assertIsInstance(result[1], mimetools.Message, "did not get a mimetools.Message instance as " "second returned value") def test_copy(self): # Test that setting the filename argument works. second_temp = "%s.2" % test_support.TESTFN self.registerFileForCleanUp(second_temp) result = urllib.urlretrieve(self.constructLocalFileUrl( test_support.TESTFN), second_temp) self.assertEqual(second_temp, result[0]) self.assertTrue(os.path.exists(second_temp), "copy of the file was not " "made") FILE = file(second_temp, 'rb') try: text = FILE.read() FILE.close() finally: try: FILE.close() except: pass self.assertEqual(self.text, text) def test_reporthook(self): # Make sure that the reporthook works. def hooktester(count, block_size, total_size, count_holder=[0]): self.assertIsInstance(count, int) self.assertIsInstance(block_size, int) self.assertIsInstance(total_size, int) self.assertEqual(count, count_holder[0]) count_holder[0] = count_holder[0] + 1 second_temp = "%s.2" % test_support.TESTFN self.registerFileForCleanUp(second_temp) urllib.urlretrieve(self.constructLocalFileUrl(test_support.TESTFN), second_temp, hooktester) def test_reporthook_0_bytes(self): # Test on zero length file. Should call reporthook only 1 time. report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile() urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 1) self.assertEqual(report[0][2], 0) def test_reporthook_5_bytes(self): # Test on 5 byte file. Should call reporthook only 2 times (once when # the "network connection" is established and once when the block is # read). Since the block size is 8192 bytes, only one block read is # required to read the entire file. report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile("x" * 5) urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 2) self.assertEqual(report[0][1], 8192) self.assertEqual(report[0][2], 5) def test_reporthook_8193_bytes(self): # Test on 8193 byte file. Should call reporthook only 3 times (once # when the "network connection" is established, once for the next 8192 # bytes, and once for the last byte). report = [] def hooktester(count, block_size, total_size, _report=report): _report.append((count, block_size, total_size)) srcFileName = self.createNewTempFile("x" * 8193) urllib.urlretrieve(self.constructLocalFileUrl(srcFileName), test_support.TESTFN, hooktester) self.assertEqual(len(report), 3) self.assertEqual(report[0][1], 8192) self.assertEqual(report[0][2], 8193) class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urllib.urlretrieve() using fake http connections""" def test_short_content_raises_ContentTooShortError(self): self.fakehttp('''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') def _reporthook(par1, par2, par3): pass try: self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com', reporthook=_reporthook) finally: self.unfakehttp() def test_short_content_raises_ContentTooShortError_without_reporthook(self): self.fakehttp('''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') try: self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com/') finally: self.unfakehttp() class QuotingTests(unittest.TestCase): """Tests for urllib.quote() and urllib.quote_plus() According to RFC 2396 ("Uniform Resource Identifiers), to escape a character you write it as '%' + <2 character US-ASCII hex value>. The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly. Case does not matter on the hex letters. The various character sets specified are: Reserved characters : ";/?:@&=+$," Have special meaning in URIs and must be escaped if not being used for their special meaning Data characters : letters, digits, and "-_.!~*'()" Unreserved and do not need to be escaped; can be, though, if desired Control characters : 0x00 - 0x1F, 0x7F Have no use in URIs so must be escaped space : 0x20 Must be escaped Delimiters : '<>#%"' Must be escaped Unwise : "{}|\^[]`" Must be escaped """ def test_never_quote(self): # Make sure quote() does not quote letters, digits, and "_,.-" do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "_.-"]) result = urllib.quote(do_not_quote) self.assertEqual(do_not_quote, result, "using quote(): %s != %s" % (do_not_quote, result)) result = urllib.quote_plus(do_not_quote) self.assertEqual(do_not_quote, result, "using quote_plus(): %s != %s" % (do_not_quote, result)) def test_default_safe(self): # Test '/' is default value for 'safe' parameter self.assertEqual(urllib.quote.func_defaults[0], '/') def test_safe(self): # Test setting 'safe' parameter does what it should do quote_by_default = "<>" result = urllib.quote(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote(): %s != %s" % (quote_by_default, result)) result = urllib.quote_plus(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote_plus(): %s != %s" % (quote_by_default, result)) def test_default_quoting(self): # Make sure all characters that should be quoted are by default sans # space (separate test for that). should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F should_quote.append('<>#%"{}|\^[]`') should_quote.append(chr(127)) # For 0x7F should_quote = ''.join(should_quote) for char in should_quote: result = urllib.quote(char) self.assertEqual(hexescape(char), result, "using quote(): %s should be escaped to %s, not %s" % (char, hexescape(char), result)) result = urllib.quote_plus(char) self.assertEqual(hexescape(char), result, "using quote_plus(): " "%s should be escapes to %s, not %s" % (char, hexescape(char), result)) del should_quote partial_quote = "ab[]cd" expected = "ab%5B%5Dcd" result = urllib.quote(partial_quote) self.assertEqual(expected, result, "using quote(): %s != %s" % (expected, result)) result = urllib.quote_plus(partial_quote) self.assertEqual(expected, result, "using quote_plus(): %s != %s" % (expected, result)) self.assertRaises(TypeError, urllib.quote, None) def test_quoting_space(self): # Make sure quote() and quote_plus() handle spaces as specified in # their unique way result = urllib.quote(' ') self.assertEqual(result, hexescape(' '), "using quote(): %s != %s" % (result, hexescape(' '))) result = urllib.quote_plus(' ') self.assertEqual(result, '+', "using quote_plus(): %s != +" % result) given = "a b cd e f" expect = given.replace(' ', hexescape(' ')) result = urllib.quote(given) self.assertEqual(expect, result, "using quote(): %s != %s" % (expect, result)) expect = given.replace(' ', '+') result = urllib.quote_plus(given) self.assertEqual(expect, result, "using quote_plus(): %s != %s" % (expect, result)) def test_quoting_plus(self): self.assertEqual(urllib.quote_plus('alpha+beta gamma'), 'alpha%2Bbeta+gamma') self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'), 'alpha+beta+gamma') class UnquotingTests(unittest.TestCase): """Tests for unquote() and unquote_plus() See the doc string for quoting_Tests for details on quoting and such. """ def test_unquoting(self): # Make sure unquoting of all ASCII values works escape_list = [] for num in range(128): given = hexescape(chr(num)) expect = chr(num) result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %s != %s" % (expect, result)) result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) escape_list.append(given) escape_string = ''.join(escape_list) del escape_list result = urllib.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using quote(): not all characters escaped; %s" % result) result = urllib.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using unquote(): not all characters escaped: " "%s" % result) def test_unquoting_badpercent(self): # Test unquoting on bad percent-escapes given = '%xab' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%x' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%' expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) def test_unquoting_mixed_case(self): # Test unquoting on mixed-case hex digits in the percent-escapes given = '%Ab%eA' expect = '\xab\xea' result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) def test_unquoting_parts(self): # Make sure unquoting works when have non-quoted characters # interspersed given = 'ab%sd' % hexescape('c') expect = "abcd" result = urllib.unquote(given) self.assertEqual(expect, result, "using quote(): %s != %s" % (expect, result)) result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) def test_unquoting_plus(self): # Test difference between unquote() and unquote_plus() given = "are+there+spaces..." expect = given result = urllib.unquote(given) self.assertEqual(expect, result, "using unquote(): %s != %s" % (expect, result)) expect = given.replace('+', ' ') result = urllib.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %s != %s" % (expect, result)) def test_unquote_with_unicode(self): r = urllib.unquote(u'br%C3%BCckner_sapporo_20050930.doc') self.assertEqual(r, u'br\xc3\xbcckner_sapporo_20050930.doc') class urlencode_Tests(unittest.TestCase): """Tests for urlencode()""" def help_inputtype(self, given, test_type): """Helper method for testing different input types. 'given' must lead to only the pairs: * 1st, 1 * 2nd, 2 * 3rd, 3 Test cannot assume anything about order. Docs make no guarantee and have possible dictionary input. """ expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] result = urllib.urlencode(given) for expected in expect_somewhere: self.assertIn(expected, result, "testing %s: %s not found in %s" % (test_type, expected, result)) self.assertEqual(result.count('&'), 2, "testing %s: expected 2 '&'s; got %s" % (test_type, result.count('&'))) amp_location = result.index('&') on_amp_left = result[amp_location - 1] on_amp_right = result[amp_location + 1] self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(), "testing %s: '&' not located in proper place in %s" % (test_type, result)) self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps "testing %s: " "unexpected number of characters: %s != %s" % (test_type, len(result), (5 * 3) + 2)) def test_using_mapping(self): # Test passing in a mapping object as an argument. self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'}, "using dict as input type") def test_using_sequence(self): # Test passing in a sequence of two-item sequences as an argument. self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')], "using sequence of two-item tuples as input") def test_quoting(self): # Make sure keys and values are quoted using quote_plus() given = {"&":"="} expect = "%s=%s" % (hexescape('&'), hexescape('=')) result = urllib.urlencode(given) self.assertEqual(expect, result) given = {"key name":"A bunch of pluses"} expect = "key+name=A+bunch+of+pluses" result = urllib.urlencode(given) self.assertEqual(expect, result) def test_doseq(self): # Test that passing True for 'doseq' parameter works correctly given = {'sequence':['1', '2', '3']} expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3'])) result = urllib.urlencode(given) self.assertEqual(expect, result) result = urllib.urlencode(given, True) for value in given["sequence"]: expect = "sequence=%s" % value self.assertIn(expect, result) self.assertEqual(result.count('&'), 2, "Expected 2 '&'s, got %s" % result.count('&')) class Pathname_Tests(unittest.TestCase): """Test pathname2url() and url2pathname()""" def test_basic(self): # Make sure simple tests pass expected_path = os.path.join("parts", "of", "a", "path") expected_url = "parts/of/a/path" result = urllib.pathname2url(expected_path) self.assertEqual(expected_url, result, "pathname2url() failed; %s != %s" % (result, expected_url)) result = urllib.url2pathname(expected_url) self.assertEqual(expected_path, result, "url2pathame() failed; %s != %s" % (result, expected_path)) def test_quoting(self): # Test automatic quoting and unquoting works for pathnam2url() and # url2pathname() respectively given = os.path.join("needs", "quot=ing", "here") expect = "needs/%s/here" % urllib.quote("quot=ing") result = urllib.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) expect = given result = urllib.url2pathname(result) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) given = os.path.join("make sure", "using_quote") expect = "%s/using_quote" % urllib.quote("make sure") result = urllib.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) given = "make+sure/using_unquote" expect = os.path.join("make+sure", "using_unquote") result = urllib.url2pathname(given) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) @unittest.skipUnless(sys.platform == 'win32', 'test specific to the nturl2path library') def test_ntpath(self): given = ('/C:/', '///C:/', '/C|//') expect = 'C:\\' for url in given: result = urllib.url2pathname(url) self.assertEqual(expect, result, 'nturl2path.url2pathname() failed; %s != %s' % (expect, result)) given = '///C|/path' expect = 'C:\\path' result = urllib.url2pathname(given) self.assertEqual(expect, result, 'nturl2path.url2pathname() failed; %s != %s' % (expect, result)) class Utility_Tests(unittest.TestCase): """Testcase to test the various utility functions in the urllib.""" def test_splitpasswd(self): """Some of the password examples are not sensible, but it is added to confirming to RFC2617 and addressing issue4675. """ self.assertEqual(('user', 'ab'),urllib.splitpasswd('user:ab')) self.assertEqual(('user', 'a\nb'),urllib.splitpasswd('user:a\nb')) self.assertEqual(('user', 'a\tb'),urllib.splitpasswd('user:a\tb')) self.assertEqual(('user', 'a\rb'),urllib.splitpasswd('user:a\rb')) self.assertEqual(('user', 'a\fb'),urllib.splitpasswd('user:a\fb')) self.assertEqual(('user', 'a\vb'),urllib.splitpasswd('user:a\vb')) self.assertEqual(('user', 'a:b'),urllib.splitpasswd('user:a:b')) self.assertEqual(('user', 'a b'),urllib.splitpasswd('user:a b')) self.assertEqual(('user 2', 'ab'),urllib.splitpasswd('user 2:ab')) self.assertEqual(('user+1', 'a+b'),urllib.splitpasswd('user+1:a+b')) class URLopener_Tests(unittest.TestCase): """Testcase to test the open method of URLopener class.""" def test_quoted_open(self): class DummyURLopener(urllib.URLopener): def open_spam(self, url): return url self.assertEqual(DummyURLopener().open( 'spam://example/ /'),'//example/%20/') # test the safe characters are not quoted by urlopen self.assertEqual(DummyURLopener().open( "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc. # Everywhere else they work ok, but on those machines, sometimes # fail in one of the tests, sometimes in other. I have a linux, and # the tests go ok. # If anybody has one of the problematic enviroments, please help! # . Facundo # # def server(evt): # import socket, time # serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # serv.settimeout(3) # serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # serv.bind(("", 9093)) # serv.listen(5) # try: # conn, addr = serv.accept() # conn.send("1 Hola mundo\n") # cantdata = 0 # while cantdata < 13: # data = conn.recv(13-cantdata) # cantdata += len(data) # time.sleep(.3) # conn.send("2 No more lines\n") # conn.close() # except socket.timeout: # pass # finally: # serv.close() # evt.set() # # class FTPWrapperTests(unittest.TestCase): # # def setUp(self): # import ftplib, time, threading # ftplib.FTP.port = 9093 # self.evt = threading.Event() # threading.Thread(target=server, args=(self.evt,)).start() # time.sleep(.1) # # def tearDown(self): # self.evt.wait() # # def testBasic(self): # # connects # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # ftp.close() # # def testTimeoutNone(self): # # global default timeout is ignored # import socket # self.assertTrue(socket.getdefaulttimeout() is None) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # finally: # socket.setdefaulttimeout(None) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() # # def testTimeoutDefault(self): # # global default timeout is used # import socket # self.assertTrue(socket.getdefaulttimeout() is None) # socket.setdefaulttimeout(30) # try: # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) # finally: # socket.setdefaulttimeout(None) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() # # def testTimeoutValue(self): # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [], # timeout=30) # self.assertEqual(ftp.ftp.sock.gettimeout(), 30) # ftp.close() def test_main(): import warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', ".*urllib\.urlopen.*Python 3.0", DeprecationWarning) test_support.run_unittest( urlopen_FileTests, urlopen_HttpTests, urlretrieve_FileTests, urlretrieve_HttpTests, ProxyTests, QuotingTests, UnquotingTests, urlencode_Tests, Pathname_Tests, Utility_Tests, URLopener_Tests, #FTPWrapperTests, ) if __name__ == '__main__': test_main()<|fim▁end|>
# The authorization header must be in place self.assertIn(authorization, fakehttp_wrapper.buf) self.assertEqual(fp.readline(), "Hello!")
<|file_name|>CountBinaryWithoutConsecutiveOnes.java<|end_file_name|><|fim▁begin|>package dp; /** * Question: http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/ */ public class CountBinaryWithoutConsecutiveOnes { public int count(int N) { int[][] memo = new int[N + 1][2]; for (int i = 0; i < memo.length; i++) { for (int j = 0; j < memo[i].length; j++) { memo[i][j] = -1; } } return countBinary(N, false, memo); } private int countBinary(int N, boolean prevSet, int[][] memo) { if (N == 0) return 1; int i = (prevSet) ? 1 : 0; if (memo[N][i] == -1) { memo[N][i] = countBinary(N - 1, false, memo); if (!prevSet) { memo[N][i] += countBinary(N - 1, true, memo); } } return memo[N][i]; } public int countBottomUp(int N) { int a = 1, b = 1, c = 0; for (int i = 1; i <= N; i++) { c = a + b; a = b; b = c;<|fim▁hole|>}<|fim▁end|>
} return c; }
<|file_name|>sprydomutils.js<|end_file_name|><|fim▁begin|>// SpryDOMUtils.js - version 0.13 - Spry Pre-Release 1.7 // // Copyright (c) 2007. Adobe Systems Incorporated. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Adobe Systems Incorporated nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. (function() { // BeginSpryComponent if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Utils) Spry.Utils = {}; ////////////////////////////////////////////////////////////////////// // // Define Prototype's $() convenience function, but make sure it is // namespaced under Spry so that we avoid collisions with other // toolkits. // ////////////////////////////////////////////////////////////////////// Spry.$ = function(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) elements.push(Spry.$(arguments[i])); return elements; } if (typeof element == 'string') element = document.getElementById(element); return element; }; ////////////////////////////////////////////////////////////////////// // // DOM Utils // ////////////////////////////////////////////////////////////////////// Spry.Utils.getAttribute = function(ele, name) { ele = Spry.$(ele); if (!ele || !name) return null; // We need to wrap getAttribute with a try/catch because IE will throw // an exception if you call it with a namespace prefixed attribute name // that doesn't exist. try { var value = ele.getAttribute(name); } catch (e) { value == undefined; } // XXX: Workaround for Safari 2.x and earlier: // // If value is undefined, the attribute didn't exist. Check to see if this is // a namespace prefixed attribute name. If it is, remove the ':' from the name // and try again. This allows us to support spry attributes of the form // "spry:region" and "spryregion". if (value == undefined && name.search(/:/) != -1) { try { var value = ele.getAttribute(name.replace(/:/, "")); } catch (e) { value == undefined; } } return value; }; Spry.Utils.setAttribute = function(ele, name, value) { ele = Spry.$(ele); if (!ele || !name) return; // IE doesn't allow you to set the "class" attribute. You // have to set the className property instead. if (name == "class") ele.className = value; else { // I'm probably being a bit paranoid, but given the fact that // getAttribute() throws exceptions when dealing with namespace // prefixed attributes, I'm going to wrap this setAttribute() // call with try/catch just in case ... try { ele.setAttribute(name, value); } catch(e) {} // XXX: Workaround for Safari 2.x and earlier: // // If this is a namespace prefixed attribute, check to make // sure an attribute was created. This is necessary because some // older versions of Safari (2.x and earlier) drop the namespace // prefixes. If the attribute was munged, try removing the ':' // character from the attribute name and setting the attribute // using the resulting name. The idea here is that even if we // remove the ':' character, Spry.Utils.getAttribute() will still // find the attribute. if (name.search(/:/) != -1 && ele.getAttribute(name) == undefined) ele.setAttribute(name.replace(/:/, ""), value); } }; Spry.Utils.removeAttribute = function(ele, name) { ele = Spry.$(ele); if (!ele || !name) return; try { ele.removeAttribute(name); } catch(e) {} // XXX: Workaround for Safari 2.x and earlier: // // If this is a namespace prefixed attribute, make sure we // also remove any attributes with the same name, but without // the ':' character. if (name.search(/:/) != -1) ele.removeAttribute(name.replace(/:/, "")); // XXX: Workaround for IE // // IE doesn't allow you to remove the "class" attribute. // It requires you to remove "className" instead, so go // ahead and try to remove that too. if (name == "class") ele.removeAttribute("className"); }; Spry.Utils.addClassName = function(ele, className) { ele = Spry.$(ele); if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return; ele.className += (ele.className ? " " : "") + className; }; Spry.Utils.removeClassName = function(ele, className) { ele = Spry.$(ele); if (Spry.Utils.hasClassName(ele, className)) ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ""); }; Spry.Utils.toggleClassName = function(ele, className) { if (Spry.Utils.hasClassName(ele, className)) Spry.Utils.removeClassName(ele, className); else Spry.Utils.addClassName(ele, className); }; Spry.Utils.hasClassName = function(ele, className) { ele = Spry.$(ele); if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1) return false; return true; }; Spry.Utils.camelizeString = function(str) { var cStr = ""; var a = str.split("-"); for (var i = 0; i < a.length; i++) { var s = a[i]; if (s) cStr = cStr ? (cStr + s.charAt(0).toUpperCase() + s.substring(1)) : s; } return cStr; }; Spry.Utils.styleStringToObject = function(styleStr) { var o = {}; if (styleStr) { var pvA = styleStr.split(";"); for (var i = 0; i < pvA.length; i++) { var pv = pvA[i]; if (pv && pv.indexOf(":") != -1) { var nvA = pv.split(":"); var n = nvA[0].replace(/^\s*|\s*$/g, ""); var v = nvA[1].replace(/^\s*|\s*$/g, ""); if (n && v) o[Spry.Utils.camelizeString(n)] = v; } } } return o; }; Spry.Utils.addEventListener = function(element, eventType, handler, capture) { try { if (!Spry.Utils.eventListenerIsBoundToElement(element, eventType, handler, capture)) { element = Spry.$(element); handler = Spry.Utils.bindEventListenerToElement(element, eventType, handler, capture); if (element.addEventListener) element.addEventListener(eventType, handler, capture); else if (element.attachEvent) element.attachEvent("on" + eventType, handler); } } catch (e) {} }; Spry.Utils.removeEventListener = function(element, eventType, handler, capture) { try { element = Spry.$(element); handler = Spry.Utils.unbindEventListenerFromElement(element, eventType, handler, capture); if (element.removeEventListener) element.removeEventListener(eventType, handler, capture); else if (element.detachEvent) element.detachEvent("on" + eventType, handler); } catch (e) {} }; Spry.Utils.eventListenerHash = {}; Spry.Utils.nextEventListenerID = 1; Spry.Utils.getHashForElementAndHandler = function(element, eventType, handler, capture) { var hash = null; element = Spry.$(element); if (element) { if (typeof element.spryEventListenerID == "undefined") element.spryEventListenerID = "e" + (Spry.Utils.nextEventListenerID++); if (typeof handler.spryEventHandlerID == "undefined") handler.spryEventHandlerID = "h" + (Spry.Utils.nextEventListenerID++); hash = element.spryEventListenerID + "-" + handler.spryEventHandlerID + "-" + eventType + (capture?"-capture":""); } return hash; }; Spry.Utils.eventListenerIsBoundToElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); return Spry.Utils.eventListenerHash[hash] != undefined; }; Spry.Utils.bindEventListenerToElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); if (Spry.Utils.eventListenerHash[hash]) return Spry.Utils.eventListenerHash[hash]; return Spry.Utils.eventListenerHash[hash] = function(e) { e = e || window.event; if (!e.preventDefault) e.preventDefault = function() { this.returnValue = false; }; if (!e.stopPropagation) e.stopPropagation = function() { this.cancelBubble = true; }; var result = handler.call(element, e); if (result == false) { e.preventDefault(); e.stopPropagation(); } return result; }; }; Spry.Utils.unbindEventListenerFromElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); if (Spry.Utils.eventListenerHash[hash]) { handler = Spry.Utils.eventListenerHash[hash]; Spry.Utils.eventListenerHash[hash] = undefined; } return handler; }; Spry.Utils.cancelEvent = function(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; return false; }; Spry.Utils.addLoadListener = function(handler) { if (typeof window.addEventListener != 'undefined') window.addEventListener('load', handler, false); else if (typeof document.addEventListener != 'undefined') document.addEventListener('load', handler, false); else if (typeof window.attachEvent != 'undefined') window.attachEvent('onload', handler); }; Spry.Utils.isDescendant = function(parent, child) { if (parent && child) { child = child.parentNode; while (child) { if (parent == child) return true; child = child.parentNode; } } return false; }; Spry.Utils.getAncestor = function(ele, selector) { ele = Spry.$(ele); if (ele) { var s = Spry.$$.tokenizeSequence(selector ? selector : "*")[0]; var t = s ? s[0] : null; if (t) { var p = ele.parentNode; while (p) { if (t.match(p)) return p; p = p.parentNode; } } } return null; }; ////////////////////////////////////////////////////////////////////// // // CSS Selector Matching // ////////////////////////////////////////////////////////////////////// Spry.$$ = function(selectorSequence, rootNode) { var matches = []; Spry.$$.addExtensions(matches); // If the first argument to $$() is an object, it // is assumed that all args are either a DOM element // or an array of DOM elements, in which case we // simply append all DOM elements to our special // matches array and return immediately. if (typeof arguments[0] == "object") { for (var i = 0; i < arguments.length; i++) { if (arguments[i].constructor == Array) matches.push.apply(matches, arguments[i]); else matches.push(arguments[i]); } return matches; } if (!rootNode) rootNode = document; else rootNode = Spry.$(rootNode); var sequences = Spry.$$.tokenizeSequence(selectorSequence); ++Spry.$$.queryID; var nid = 0; var ns = sequences.length; for (var i = 0; i < ns; i++) { var m = Spry.$$.processTokens(sequences[i], rootNode); var nm = m.length; for (var j = 0; j < nm; j++) { var n = m[j]; if (!n.spry$$ID) { n.spry$$ID = ++nid; matches.push(n); } } } var nm = matches.length; for (i = 0; i < nm; i++) matches[i].spry$$ID = undefined; return matches; }; Spry.$$.cache = {}; Spry.$$.queryID = 0; Spry.$$.Token = function() { this.type = Spry.$$.Token.SELECTOR; this.name = "*"; this.id = ""; this.classes = []; this.attrs = []; this.pseudos = []; }; Spry.$$.Token.Attr = function(n, v) { this.name = n; this.value = v ? new RegExp(v) : undefined; }; Spry.$$.Token.PseudoClass = function(pstr) { this.name = pstr.replace(/\(.*/, ""); this.arg = pstr.replace(/^[^\(\)]*\(?\s*|\)\s*$/g, ""); this.func = Spry.$$.pseudoFuncs[this.name]; }; Spry.$$.Token.SELECTOR = 0; Spry.$$.Token.COMBINATOR = 1; Spry.$$.Token.prototype.match = function(ele, nameAlreadyMatches) { if (this.type == Spry.$$.Token.COMBINATOR) return false; if (!nameAlreadyMatches && this.name != '*' && this.name != ele.nodeName.toLowerCase()) return false; if (this.id && this.id != ele.id) return false; var classes = this.classes; var len = classes.length; for (var i = 0; i < len; i++) { if (!ele.className || !classes[i].value.test(ele.className)) return false; } var attrs = this.attrs; len = attrs.length; for (var i = 0; i < len; i++) { var a = attrs[i]; var an = ele.attributes.getNamedItem(a.name); if (!an || (!a.value && an.nodeValue == undefined) || (a.value && !a.value.test(an.nodeValue))) return false; } var ps = this.pseudos; var len = ps.length; for (var i = 0; i < len; i++) { var p = ps[i]; if (p && p.func && !p.func(p.arg, ele, this)) return false; } return true; }; Spry.$$.Token.prototype.getNodeNameIfTypeMatches = function(ele) { var nodeName = ele.nodeName.toLowerCase(); if (this.name != '*') { if (this.name != nodeName) return null; return this.name; } return nodeName; }; Spry.$$.escapeRegExpCharsRE = /\/|\.|\*|\+|\(|\)|\[|\]|\{|\}|\\|\|/g; Spry.$$.tokenizeSequence = function(s) { var cc = Spry.$$.cache[s]; if (cc) return cc; // Attribute Selector: /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])/g // Simple Selector: /((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)/g // Combinator: /(\s*[\s,>~\+]\s*)/g var tokenExpr = /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])|((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)|(\s*[\s,>~\+]\s*)/g; var tkn = new Spry.$$.Token; var sequence = []; sequence.push(tkn); var tokenSequences = []; tokenSequences.push(sequence); s = s.replace(/^\s*|\s*$/, ""); var expMatch = tokenExpr.exec(s); while (expMatch) { var tstr = expMatch[0]; var c = tstr.charAt(0); switch (c) { case '.': tkn.classes.push(new Spry.$$.Token.Attr("class", "\\b" + tstr.substr(1) + "\\b")); break; case '#': tkn.id = tstr.substr(1); break; case ':': tkn.pseudos.push(new Spry.$$.Token.PseudoClass(tstr)); break; case '[': var attrComps = tstr.match(/\[([^\"'~\^\$\*\|\]=]+)(([~\^\$\*\|]?=)\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\]/); var name = attrComps[1]; var matchType = attrComps[3]; var val = attrComps[4]; if (val) { val = val.replace(/^['"]|['"]$/g, ""); val = val.replace(Spry.$$.escapeRegExpCharsRE, '\\$&'); } var matchStr = undefined; switch(matchType) { case "=": matchStr = "^" + val + "$"; break; case "^=": matchStr = "^" + val; break; case "$=": matchStr = val + "$"; break; case "~=": case "|=": matchStr = "\\b" + val + "\\b"; break; case "*=": matchStr = val; break; } tkn.attrs.push(new Spry.$$.Token.Attr(name, matchStr)); break; default: var combiMatch = tstr.match(/^\s*([\s,~>\+])\s*$/); if (combiMatch) { if (combiMatch[1] == ',') { sequence = new Array; tokenSequences.push(sequence); tkn = new Spry.$$.Token; sequence.push(tkn); } else { tkn = new Spry.$$.Token; tkn.type = Spry.$$.Token.COMBINATOR; tkn.name = combiMatch[1]; sequence.push(tkn); tkn = new Spry.$$.Token(); sequence.push(tkn); } } else tkn.name = tstr.toLowerCase(); break; } expMatch = tokenExpr.exec(s); } Spry.$$.cache[s] = tokenSequences; return tokenSequences; }; Spry.$$.combinatorFuncs = { // Element Descendant " ": function(nodes, token) { var uid = ++Spry.$$.uniqueID; var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i]; if (uid != n.spry$$uid) { // n.spry$$uid = uid; var ea = nodes[i].getElementsByTagName(token.name); var ne = ea.length; for (var j = 0; j < ne; j++) { var e = ea[j]; // If the token matches, add it to our results. We have // to make sure e is an element because IE6 returns the DOCTYPE // tag as a comment when '*' is used in the call to getElementsByTagName(). if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true)) results.push(e); e.spry$$uid = uid; } } } return results; }, // Element Child ">": function(nodes, token) { var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].firstChild; while (n) { if (n.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(n)) results.push(n); n = n.nextSibling; } } return results; }, // Element Immediately Preceded By "+": function(nodes, token) { var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].nextSibling; while (n && n.nodeType != 1 /* Node.ELEMENT_NODE */) n = n.nextSibling; if (n && token.match(n)) results.push(n); } return results; }, // Element Preceded By "~": function(nodes, token) { var uid = ++Spry.$$.uniqueID; var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].nextSibling; while (n) { if (n.nodeType == 1 /* Node.ELEMENT_NODE */) { if (uid == n.spry$$uid) break; if (token.match(n)) { results.push(n); n.spry$$uid = uid; } } n = n.nextSibling; } } return results; } }; Spry.$$.uniqueID = 0; Spry.$$.pseudoFuncs = { ":first-child": function(arg, node, token) { var n = node.previousSibling; while (n) { if (n.nodeType == 1) return false; // Node.ELEMENT_NODE n = n.previousSibling; } return true; }, ":last-child": function(arg, node, token) { var n = node.nextSibling; while (n) { if (n.nodeType == 1) // Node.ELEMENT_NODE return false; n = n.nextSibling; } return true; }, ":empty": function(arg, node, token) { var n = node.firstChild; while (n) { switch(n.nodeType) { case 1: // Node.ELEMENT_NODE case 3: // Node.TEXT_NODE case 4: // Node.CDATA_NODE case 5: // Node.ENTITY_REFERENCE_NODE return false; } n = n.nextSibling; } return true; }, ":nth-child": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token); }, ":nth-last-child": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, true); }, ":nth-of-type": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, false, true); }, ":nth-last-of-type": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, true, true); }, ":first-of-type": function(arg, node, token) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; var n = node.previousSibling; while (n) { if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) return false; // Node.ELEMENT_NODE n = n.previousSibling; } return true; }, ":last-of-type": function(arg, node, token) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; var n = node.nextSibling; while (n) { if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) // Node.ELEMENT_NODE return false; n = n.nextSibling; } return true; }, ":only-child": function(arg, node, token) { var f = Spry.$$.pseudoFuncs; return f[":first-child"](arg, node, token) && f[":last-child"](arg, node, token); }, ":only-of-type": function(arg, node, token) { var f = Spry.$$.pseudoFuncs; return f[":first-of-type"](arg, node, token) && f[":last-of-type"](arg, node, token); }, ":not": function(arg, node, token) { var s = Spry.$$.tokenizeSequence(arg)[0]; var t = s ? s[0] : null; return !t || !t.match(node); }, ":enabled": function(arg, node, token) { return !node.disabled; }, ":disabled": function(arg, node, token) { return node.disabled; }, ":checked": function(arg, node, token) { return node.checked; }, ":root": function(arg, node, token) { return node.parentNode && node.ownerDocument && node.parentNode == node.ownerDocument; } }; Spry.$$.nthRegExp = /((-|[0-9]+)?n)?([+-]?[0-9]*)/; Spry.$$.nthCache = { "even": { a: 2, b: 0, mode: 1, invalid: false } , "odd": { a: 2, b: 1, mode: 1, invalid: false } , "2n": { a: 2, b: 0, mode: 1, invalid: false } , "2n+1": { a: 2, b: 1, mode: 1, invalid: false } }; Spry.$$.parseNthChildString = function(str) { var o = Spry.$$.nthCache[str]; if (!o) { var m = str.match(Spry.$$.nthRegExp); var n = m[1]; var a = m[2]; var b = m[3]; if (!a) { // An 'a' value was not specified. Was there an 'n' present? // If so, we treat it as an increment of 1, otherwise we're // in no-repeat mode. a = n ? 1 : 0; } else if (a == "-") { // The string is using the "-n" short-hand which is // short for -1. a = -1; } else { // An integer repeat value for 'a' was specified. Convert // it into number. a = parseInt(a, 10); } // If a 'b' value was specified, turn it into a number. // If no 'b' value was specified, default to zero. b = b ? parseInt(b, 10) : 0; // Figure out the mode: // // -1 - repeat backwards // 0 - no repeat // 1 - repeat forwards var mode = (a == 0) ? 0 : ((a > 0) ? 1 : -1); var invalid = false; // Fix up 'a' and 'b' for proper repeating. if (a > 0 && b < 0) { b = b % a; b = ((b=(b%a)) < 0) ? a + b : b; } else if (a < 0) { if (b < 0) invalid = true; else a = Math.abs(a); } o = new Object; o.a = a; o.b = b; o.mode = mode; o.invalid = invalid; Spry.$$.nthCache[str] = o; } return o; }; Spry.$$.nthChild = function(arg, node, token, fromLastSib, matchNodeName) { if (matchNodeName) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; } var o = Spry.$$.parseNthChildString(arg); if (o.invalid) return false; var qidProp = "spry$$ncQueryID"; var posProp = "spry$$ncPos"; var countProp = "spry$$ncCount"; if (matchNodeName) { qidProp += nodeName; posProp += nodeName; countProp += nodeName; } var parent = node.parentNode; if (parent[qidProp] != Spry.$$.queryID) { var pos = 0; parent[qidProp] = Spry.$$.queryID; var c = parent.firstChild; while (c) { if (c.nodeType == 1 && (!matchNodeName || nodeName == c.nodeName.toLowerCase())) c[posProp] = ++pos; c = c.nextSibling; } parent[countProp] = pos; } pos = node[posProp]; if (fromLastSib) pos = parent[countProp] - pos + 1; /* var sib = fromLastSib ? "nextSibling" : "previousSibling"; var pos = 1; var n = node[sib]; while (n) { if (n.nodeType == 1 && (!matchNodeName || nodeName == n.nodeName.toLowerCase())) { if (n == node) break; ++pos; } n = n[sib]; } */ if (o.mode == 0) // Exact match return pos == o.b; if (o.mode > 0) // Forward Repeat return (pos < o.b) ? false : (!((pos - o.b) % o.a)); return (pos > o.b) ? false : (!((o.b - pos) % o.a)); // Backward Repeat }; Spry.$$.processTokens = function(tokens, root) { var numTokens = tokens.length; var nodeSet = [ root ]; var combiFunc = null; for (var i = 0; i < numTokens && nodeSet.length > 0; i++) { var t = tokens[i]; if (t.type == Spry.$$.Token.SELECTOR) { if (combiFunc) { nodeSet = combiFunc(nodeSet, t); combiFunc = null; } else nodeSet = Spry.$$.getMatchingElements(nodeSet, t); } else // Spry.$$.Token.COMBINATOR combiFunc = Spry.$$.combinatorFuncs[t.name]; } return nodeSet; }; Spry.$$.getMatchingElements = function(nodes, token) { var results = []; if (token.id) { n = nodes[0]; if (n && n.ownerDocument) { var e = n.ownerDocument.getElementById(token.id); if (e) { // XXX: We need to make sure that the element // we found is actually underneath the root // we were given! if (token.match(e)) results.push(e); } return results; } } var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i]; // if (token.match(n)) results.push(n); var ea = n.getElementsByTagName(token.name); var ne = ea.length; for (var j = 0; j < ne; j++) { var e = ea[j]; // If the token matches, add it to our results. We have // to make sure e is an element because IE6 returns the DOCTYPE // tag as a comment when '*' is used in the call to getElementsByTagName(). if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true)) results.push(e); } } return results; }; /* Spry.$$.dumpSequences = function(sequences) { Spry.Debug.trace("<hr />Number of Sequences: " + sequences.length); for (var i = 0; i < sequences.length; i++) { var str = ""; var s = sequences[i]; Spry.Debug.trace("<hr />Sequence " + i + " -- Tokens: " + s.length); for (var j = 0; j < s.length; j++) { var t = s[j]; if (t.type == Spry.$$.Token.SELECTOR) { str += " SELECTOR:\n Name: " + t.name + "\n ID: " + t.id + "\n Attrs:\n"; for (var k = 0; k < t.classes.length; k++) str += " " + t.classes[k].name + ": " + t.classes[k].value + "\n"; for (var k = 0; k < t.attrs.length; k++) str += " " + t.attrs[k].name + ": " + t.attrs[k].value + "\n"; str += " Pseudos:\n"; for (var k = 0; k < t.pseudos.length; k++) str += " " + t.pseudos[k].name + (t.pseudos[k].arg ? "(" + t.pseudos[k].arg + ")" : "") + "\n"; } else { str += " COMBINATOR:\n Name: '" + t.name + "'\n"; } } Spry.Debug.trace("<pre>" + Spry.Utils.encodeEntities(str) + "</pre>"); } }; */ Spry.$$.addExtensions = function(a) { for (var f in Spry.$$.Results) a[f] = Spry.$$.Results[f]; }; Spry.$$.Results = {}; Spry.$$.Results.forEach = function(func) { var n = this.length; for (var i = 0; i < n; i++) func(this[i]); return this; }; Spry.$$.Results.setAttribute = function(name, value) { return this.forEach(function(n) { Spry.Utils.setAttribute(n, name, value); }); }; Spry.$$.Results.removeAttribute = function(name) { return this.forEach(function(n) { Spry.Utils.removeAttribute(n, name); }); }; Spry.$$.Results.addClassName = function(className) { return this.forEach(function(n) { Spry.Utils.addClassName(n, className); }); }; Spry.$$.Results.removeClassName = function(className) { return this.forEach(function(n) { Spry.Utils.removeClassName(n, className); }); }; Spry.$$.Results.toggleClassName = function(className) { return this.forEach(function(n) { Spry.Utils.toggleClassName(n, className); }); }; Spry.$$.Results.addEventListener = function(eventType, handler, capture, bindHandler) { return this.forEach(function(n) { Spry.Utils.addEventListener(n, eventType, handler, capture, bindHandler); }); }; Spry.$$.Results.removeEventListener = function(eventType, handler, capture) { return this.forEach(function(n) { Spry.Utils.removeEventListener(n, eventType, handler, capture); }); }; Spry.$$.Results.setStyle = function(style) { if (style) { style = Spry.Utils.styleStringToObject(style); this.forEach(function(n) { for (var p in style) try { n.style[p] = style[p]; } catch (e) {} }); } return this; }; Spry.$$.Results.setProperty = function(prop, value) { if (prop) { if (typeof prop == "string") { var p = {}; p[prop] = value; prop = p; } this.forEach(function(n) { for (var p in prop) try { n[p] = prop[p]; } catch (e) {} <|fim▁hole|> }); } return this; }; })(); // EndSpryComponent<|fim▁end|>
<|file_name|>start.js<|end_file_name|><|fim▁begin|>process.env.NODE_ENV = 'development'; // Load environment variables from .env file. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. // https://github.com/motdotla/dotenv require('dotenv').config({silent: true}); var chalk = require('chalk'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var historyApiFallback = require('connect-history-api-fallback'); var httpProxyMiddleware = require('http-proxy-middleware'); var detect = require('detect-port'); var clearConsole = require('react-dev-utils/clearConsole'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.dev'); var paths = require('../config/paths'); // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { process.exit(1); } // Tools like Cloud9 rely on this. var DEFAULT_PORT = process.env.PORT || 3000; var compiler; var handleCompile; function setupCompiler(host, port, protocol) { // "Compiler" is a low-level interface to Webpack. // It lets us listen to some events and provide our own custom messages. compiler = webpack(config, handleCompile); // "invalid" event fires when you have changed a file, and Webpack is // recompiling a bundle. WebpackDevServer takes care to pause serving the // bundle, so if you refresh, it'll wait instead of serving the old one. // "invalid" is short for "bundle invalidated", it doesn't imply any errors. compiler.plugin('invalid', function() { clearConsole(); console.log('Compiling...'); }); // "done" event fires when Webpack has finished recompiling the bundle. // Whether or not you have warnings or errors, you will get this event. compiler.plugin('done', function(stats) { clearConsole(); // We have switched off the default Webpack output in WebpackDevServer // options so we are going to "massage" the warnings and errors and present // them in a readable focused way. var messages = formatWebpackMessages(stats.toJson({}, true)); if (!messages.errors.length && !messages.warnings.length) { console.log(chalk.green('Compiled successfully!')); console.log(); console.log('The app is running at:'); console.log(); console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/')); console.log(); console.log('Note that the development build is not optimized.'); console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.'); console.log(); } // If errors exist, only show errors. if (messages.errors.length) { console.log(chalk.red('Failed to compile.')); console.log(); messages.errors.forEach(message => { console.log(message); console.log(); }); return; } // Show warnings if no errors were found. if (messages.warnings.length) { console.log(chalk.yellow('Compiled with warnings.')); console.log(); messages.warnings.forEach(message => { console.log(message); console.log(); }); // Teach some ESLint tricks. console.log('You may use special comments to disable some warnings.'); console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.'); console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.'); } }); } // We need to provide a custom onError function for httpProxyMiddleware.<|fim▁hole|> return function(err, req, res){ var host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' ); console.log( 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' + chalk.cyan(err.code) + ').' ); console.log(); // And immediately send the proper error response to the client. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end('Proxy error: Could not proxy request ' + req.url + ' from ' + host + ' to ' + proxy + ' (' + err.code + ').' ); } } function addMiddleware(devServer) { // `proxy` lets you to specify a fallback server during development. // Every unrecognized request will be forwarded to it. var proxy = require(paths.appPackageJson).proxy; devServer.use(historyApiFallback({ // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. disableDotRule: true, // For single page apps, we generally want to fallback to /index.html. // However we also want to respect `proxy` for API calls. // So if `proxy` is specified, we need to decide which fallback to use. // We use a heuristic: if request `accept`s text/html, we pick /index.html. // Modern browsers include text/html into `accept` header when navigating. // However API calls like `fetch()` won’t generally accept text/html. // If this heuristic doesn’t work well for you, don’t use `proxy`. htmlAcceptHeaders: proxy ? ['text/html'] : ['text/html', '*/*'] })); if (proxy) { if (typeof proxy !== 'string') { console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); process.exit(1); } // Otherwise, if proxy is specified, we will let it handle any request. // There are a few exceptions which we won't send to the proxy: // - /index.html (served as HTML5 history API fallback) // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) // - /sockjs-node/* (WebpackDevServer uses this for hot reloading) // Tip: use https://jex.im/regulex/ to visualize the regex var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/; devServer.use(mayProxy, // Pass the scope regex both to Express and to the middleware for proxying // of both HTTP and WebSockets to work without false positives. httpProxyMiddleware(pathname => mayProxy.test(pathname), { target: proxy, logLevel: 'silent', onError: onProxyError(proxy), secure: false, changeOrigin: true }) ); } // Finally, by now we have certainly resolved the URL. // It may be /index.html, so let the dev server try serving it again. devServer.use(devServer.middleware); } function runDevServer(host, port, protocol) { var devServer = new WebpackDevServer(compiler, { // Silence WebpackDevServer's own logs since they're generally not useful. // It will still show compile warnings and errors with this setting. clientLogLevel: 'none', // By default WebpackDevServer serves physical files from current directory // in addition to all the virtual build products that it serves from memory. // This is confusing because those files won’t automatically be available in // production build folder unless we copy them. However, copying the whole // project directory is dangerous because we may expose sensitive files. // Instead, we establish a convention that only files in `public` directory // get served. Our build script will copy `public` into the `build` folder. // In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. // Note that we only recommend to use `public` folder as an escape hatch // for files like `favicon.ico`, `manifest.json`, and libraries that are // for some reason broken when imported through Webpack. If you just want to // use an image, put it in `src` and `import` it from JavaScript instead. contentBase: paths.appPublic, // Enable hot reloading server. It will provide /sockjs-node/ endpoint // for the WebpackDevServer client so it can learn when the files were // updated. The WebpackDevServer client is included as an entry point // in the Webpack development configuration. Note that only changes // to CSS are currently hot reloaded. JS changes will refresh the browser. hot: true, // It is important to tell WebpackDevServer to use the same "root" path // as we specified in the config. In development, we always serve from /. publicPath: config.output.publicPath, // WebpackDevServer is noisy by default so we emit custom message instead // by listening to the compiler events with `compiler.plugin` calls above. quiet: true, // Reportedly, this avoids CPU overload on some systems. // https://github.com/facebookincubator/create-react-app/issues/293 watchOptions: { ignored: /node_modules/ }, // Enable HTTPS if the HTTPS environment variable is set to 'true' https: protocol === "https", host: host }); // Our custom middleware proxies requests to /index.html or a remote API. addMiddleware(devServer); // Launch WebpackDevServer. devServer.listen(port, (err, result) => { if (err) { return console.log(err); } clearConsole(); console.log(chalk.cyan('Starting the development server...')); console.log(); openBrowser(protocol + '://' + host + ':' + port + '/'); }); } function run(port) { var protocol = process.env.HTTPS === 'true' ? "https" : "http"; var host = process.env.HOST || 'localhost'; setupCompiler(host, port, protocol); runDevServer(host, port, protocol); } // We attempt to use the default port but if it is busy, we offer the user to // run on a different port. `detect()` Promise resolves to the next free port. detect(DEFAULT_PORT).then(port => { if (port == DEFAULT_PORT) { run(port); return; } clearConsole(); var question = chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.') + '\n\nWould you like to run the app on another port instead?'; prompt(question, true).then(shouldChangePort => { if (shouldChangePort) { run(port); } }); });<|fim▁end|>
// It allows us to log custom error messages on the console. function onProxyError(proxy) {
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Models provided by the `libsvm` library. <|fim▁hole|><|fim▁end|>
mod ffi; pub mod svc;
<|file_name|>doc.js<|end_file_name|><|fim▁begin|>(function () { var Demo = { init: function () { this.syntaxHighlight(); this.sticky(); }, syntaxHighlight: function () { hljs.initHighlighting(); },<|fim▁hole|> $sticky.sticky({ topSpacing: 10 }); } }; Demo.init(); })();<|fim▁end|>
sticky: function () { var $sticky = $('[data-sticky]');
<|file_name|>test_delete.py<|end_file_name|><|fim▁begin|>import os from jenkins_jobs import cmd from tests.base import mock from tests.cmd.test_cmd import CmdTestsBase @mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock) class DeleteTests(CmdTestsBase): @mock.patch('jenkins_jobs.cmd.Builder.delete_job') def test_delete_single_job(self, delete_job_mock): """ Test handling the deletion of a single Jenkins job. """ args = self.parser.parse_args(['delete', 'test_job']) cmd.execute(args, self.config) # passes if executed without error @mock.patch('jenkins_jobs.cmd.Builder.delete_job') def test_delete_multiple_jobs(self, delete_job_mock): """ Test handling the deletion of multiple Jenkins jobs. """ args = self.parser.parse_args(['delete', 'test_job1', 'test_job2']) cmd.execute(args, self.config) # passes if executed without error @mock.patch('jenkins_jobs.builder.Jenkins.delete_job') def test_delete_using_glob_params(self, delete_job_mock): """ Test handling the deletion of multiple Jenkins jobs using the glob<|fim▁hole|> '--path', os.path.join(self.fixtures_path, 'cmd-002.yaml'), '*bar*']) cmd.execute(args, self.config) calls = [mock.call('bar001'), mock.call('bar002')] delete_job_mock.assert_has_calls(calls, any_order=True) self.assertEqual(delete_job_mock.call_count, len(calls), "Jenkins.delete_job() was called '%s' times when " "expected '%s'" % (delete_job_mock.call_count, len(calls)))<|fim▁end|>
parameters feature. """ args = self.parser.parse_args(['delete',
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! This library provides wrappers for LLVM that are memory-safe and follow //! Rust idioms. //! //! The original LLVM reference is available [here](http://llvm.org/doxygen/) //! but take note that this isn't as thorough as this documentation. extern crate llvm_sys as ffi;<|fim▁hole|>mod macros; mod buffer; mod block; mod builder; mod compile; mod context; mod engine; mod module; mod object; mod target; mod ty; mod value; mod util; pub use cbox::{CBox, CSemiBox}; pub use builder::Builder; pub use block::BasicBlock; pub use compile::Compile; pub use context::{Context, GetContext}; pub use engine::{JitEngine, JitOptions, Interpreter, ExecutionEngine, GenericValue, GenericValueCast}; pub use module::{Module, Functions}; pub use object::{ObjectFile, Symbol, Symbols}; pub use target::{TargetData, Target}; pub use ty::{FunctionType, StructType, Type}; pub use value::{Arg, Attribute, Value, Function, Predicate}; pub use util::CastFrom;<|fim▁end|>
extern crate libc; extern crate cbox; #[macro_use]
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>from django.urls import reverse_lazy from modoboa.lib.tests import ModoTestCase class OpenAPITestCase(ModoTestCase): openapi_schema_url = reverse_lazy('schema-v1-legacy')<|fim▁hole|> self.client.logout() response = self.client.get(self.openapi_schema_url) self.assertEqual(response.status_code, 401) def test_get_schema(self): self.assertEqual(self.openapi_schema_url, "/docs/openapi.json") response = self.client.get(self.openapi_schema_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['info'], { 'title': "Modoboa API", 'version': "v1", })<|fim▁end|>
def test_unauthorized(self):
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors // // This library 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; version // 2.1 of the License. // // This library 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 library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA //<|fim▁hole|> EditError, EditErrorKind, ResultExt, Result; } errors { IOError { description("IO Error") display("IO Error") } NoEditor { description("No editor set") display("No editor set") } ProcessExitFailure { description("Process did not exit properly") display("Process did not exit properly") } InstantiateError { description("Instantation error") display("Instantation error") } } }<|fim▁end|>
error_chain! { types {
<|file_name|>dbconnect_shared.cc<|end_file_name|><|fim▁begin|>// $Id: dbconnect_shared.cc,v 1.9 2005/03/30 12:32:58 jacek Exp $ /* libcommonc++: ManuProC's main OO library * Copyright (C) 1998-2000 Adolf Petig GmbH & Co. KG, written by Jacek Jakubowski * Copyright (C) 2010 Christof Petig * * 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 2 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ManuProCConfig.h> #include <Misc/dbconnect.h> #include <cassert> //#include <cstring> //#include <unistd.h> #include <cstdlib> #include <Misc/Global_Settings.h> #if defined(WIN32) && !defined(__MINGW32__) # pragma warning( disable : 4290 ) // for VS2010 #endif ManuProC::Connection::Connection(const std::string &h, const std::string &d,<|fim▁hole|> std::string db_=DEFAULT_DB; std::string opt_port; char *h_opt(getenv("PGHOST")); char *d_opt(getenv("PGDATABASE")); char *p_opt(getenv("PGPORT")); char *t_opt(getenv("PGTYPE")); if(h_opt) host_=h_opt; if(d_opt) db_=d_opt; if(p_opt) opt_port=p_opt; if(t_opt && *t_opt) { if (t_opt[0]=='P' || t_opt[0]=='p') type= ManuProC::Connection::C_PostgreSQL; else if (t_opt[0]=='S' || t_opt[0]=='s') type= ManuProC::Connection::C_SQLite; else if (isdigit(t_opt[0])) type= ManuProC::Connection::CType_t(strtol(t_opt,0,0)); } if(host.empty()) host=host_; if(dbase.empty()) dbase=db_; if(!opt_port.empty()) port=atoi(opt_port.c_str()); } std::string ManuProC::Connection::get_current_dbname() { return Name(); } Handle<ManuProC::Connection_base> ManuProC::dbconnect_nt(const Connection &c) throw() { try { return dbconnect(c); } catch (SQLerror &e) { std::cerr << e << '\n'; } } void ManuProC::dbdisconnect_nt(const std::string &name) throw() { try { dbdisconnect(name); } catch (SQLerror &e) { std::cerr << e << '\n'; } } Handle<ManuProC::Connection_base> ManuProC::dbconnect(const Connection &c) throw(SQLerror) { Handle<Connection_base> res; switch(c.Type()) { case Connection::C_PostgreSQL: res= dbconnect_PQ(c); break; case Connection::C_ECPG: res= dbconnect_ECPG(c); break; case Connection::C_SQLite: res= dbconnect_SQLite3(c); break; default: throw SQLerror("dbconnect", 100, "Database type unknown"); } register_db(res); Global_Settings::database_connected(); return res; } //#include <iostream> //#include <fstream> const std::string ManuProC::Connection::Pass() const throw(AuthError) { // not nedeed at the time /* char buf[80]; buf[0]=0; ifstream passfile (".remote_access"); if (! passfile.is_open()) { throw AuthError(".remote_access not found"); } if(!passfile.eof()) passfile.getline(buf,sizeof buf); passfile.close(); */ return std::string(); } void ManuProC::dbdisconnect(const std::string &name) throw(SQLerror) { Global_Settings::database_connected(false); Handle<Connection_base> h=get_database(name); if(!h) return; unregister_db(h); h->disconnect(); } void ManuProC::Connection_base::make_default() const throw() { active_connection=const_cast<ManuProC::Connection_base*>(this); } Handle<ManuProC::Connection_base> ManuProC::dbdefault(std::string const& name) throw(SQLerror) { active_connection= get_database(name); return active_connection; } std::vector<Handle<ManuProC::Connection_base> > ManuProC::connections; Handle<ManuProC::Connection_base> ManuProC::active_connection; void ManuProC::register_db(Handle<Connection_base> const& c) { connections.push_back(c); if (!active_connection) active_connection=c; } void ManuProC::unregister_db(Handle<Connection_base> const& c) { if (&*active_connection==&*c) active_connection = Handle<Connection_base>(); for (std::vector<Handle<ManuProC::Connection_base> >::iterator i=connections.begin();i!=connections.end();++i) if (&*c == &**i) { connections.erase(i); return; } } Handle<ManuProC::Connection_base> ManuProC::get_database(std::string const& name) throw(SQLerror) { if (name.empty()) return active_connection; for (std::vector<Handle<ManuProC::Connection_base> >::const_iterator i=connections.begin();i!=connections.end();++i) if ((*i)->Name()==name) return *i; throw SQLerror("get_database",100,"Database not found"); } void ManuProC::Connection_base::setDTstyle(char const*) throw(SQLerror) { } // until implemented Handle<ManuProC::Connection_base> ManuProC::dbconnect_ECPG(ManuProC::Connection const&) throw(SQLerror) { throw SQLerror("dbconnect_ECPG", 100, "not implemented"); }<|fim▁end|>
const std::string &u,const std::string &n, const int p) : host(h), dbase(d), user(u), name(n), port(p), type(C_SQLite) { std::string host_=DEFAULT_DBHOST;
<|file_name|>config.py<|end_file_name|><|fim▁begin|>from collections import namedtuple Resolution = namedtuple('Resolution', ['x', 'y']) class Resolutions(object): resolutions = [ (1920, 1200), (1920, 1080), (1680, 1050), (1440, 900), (1360, 768), (1280, 800), (1024, 640) ] @classmethod def parse(self, x, y): <|fim▁hole|> class Color(object): gray = (0.15, 0.15, 0.13, 1.0) black = (0.0, 0.0, 0.0, 1.0) white = (1.0, 1.0, 1.0, 1.0) red = (1.0, 0.2, 0.0, 1.0) orange = (1.0, 0.4, 0.0, 1.0) yellow = (1.0, 0.9, 0.0, 1.0) light_green = (0.4, 1.0, 0.0, 1.0) green = (0.0, 1.0, 0.2, 1.0) cyan = (0.0, 1.0, 0.4, 1.0) light_blue = (0.0, 0.6, 1.0, 1.0) blue = (0.0, 0.2, 1.0, 1.0) purple = (0.4, 0.0, 1.0, 1.0) pink = (1.0, 0.0, 0.8, 1.0) @classmethod def __colors(self): return [key for key in self.__dict__.keys() if not key.startswith('_') and key != 'named'] @classmethod def named(self, name): if not hasattr(self, name): colors = ', '.join(self.__colors()) raise Exception('Unknown color %s. Available colors are: %s' % (name, colors)) return getattr(self, name) def try_parse(value): try: return int(value) except: return { 'true': True, 'false': False }.get(value.lower(), value) def read_config(): with open('config.cfg', 'r') as cfg_file: lines = cfg_file.readlines() lines = [ line.strip().replace(' ', '').split('=') for line in lines if line.strip() and '=' in line ] cfg = {key:try_parse(value) for key,value in lines} return cfg cfg = read_config() NUM_CELLS = cfg.get('CELLS', 100) RESOLUTION = Resolutions.parse(cfg.get('WINDOW_WIDTH', 1280), cfg.get('WINDOW_HEIGHT', 800)) limit = min(RESOLUTION) PIXEL_PER_CELL = limit / NUM_CELLS OFFSET_X = (RESOLUTION.x - (NUM_CELLS * PIXEL_PER_CELL)) / 2 OFFSET_Y = (RESOLUTION.y - (NUM_CELLS * PIXEL_PER_CELL)) / 2 SHOW_FULLSCREEN = cfg.get('FULLSCREEN', False) SHOW_GRID = cfg.get('SHOW_GRID', True) BACKGROUND_COLOR = Color.named(cfg.get('BACKGROUND_COLOR', 'black')) GRID_BACKDROP_COLOR = Color.named(cfg.get('GRID_BACKDROP_COLOR', 'gray')) GRID_LINE_COLOR = Color.named(cfg.get('GRID_LINE_COLOR', 'black')) CELL_COLOR = Color.named(cfg.get('CELL_COLOR', 'green')) CURSOR_COLOR = Color.named(cfg.get('CURSOR_COLOR', 'red'))<|fim▁end|>
if (x,y) not in self.resolutions: resolutions = ', '.join(['%sx%s' % (a, b) for a,b in self.resolutions]) raise Exception('Resolution %s x %s not supported. Available resolutions: %s' % (x,y, resolutions) ) return Resolution(x, y)
<|file_name|>_jet_Erroresql_0.java<|end_file_name|><|fim▁begin|>package org.eclipse.jet.compiled; import org.eclipse.jet.JET2Context; import org.eclipse.jet.JET2Template; import org.eclipse.jet.JET2Writer; import org.eclipse.jet.taglib.RuntimeTagElement; import org.eclipse.jet.taglib.TagInfo; public class _jet_Erroresql_0 implements JET2Template { private static final String _jetns_c = "org.eclipse.jet.controlTags"; //$NON-NLS-1$ public _jet_Erroresql_0() { super(); } private static final String NL = System.getProperty("line.separator"); //$NON-NLS-1$ private static final TagInfo _td_c_if_5_1 = new TagInfo("c:if", //$NON-NLS-1$ 5, 1, new String[] { "test", //$NON-NLS-1$ }, new String[] { "boolean($root/brokerSchema)", //$NON-NLS-1$ } ); private static final TagInfo _td_c_if_7_1 = new TagInfo("c:if", //$NON-NLS-1$ 7, 1, new String[] { "test", //$NON-NLS-1$ }, new String[] { "string-length($root/brokerSchema) > 0", //$NON-NLS-1$ } ); private static final TagInfo _td_c_get_9_15 = new TagInfo("c:get", //$NON-NLS-1$ 9, 15, new String[] { "select", //$NON-NLS-1$ }, new String[] { "$root/brokerSchema", //$NON-NLS-1$ } ); private static final TagInfo _td_c_get_12_18 = new TagInfo("c:get", //$NON-NLS-1$ 12, 18, new String[] { "select", //$NON-NLS-1$ }, new String[] { "$root/@patternName", //$NON-NLS-1$ } ); private static final TagInfo _td_c_get_12_63 = new TagInfo("c:get", //$NON-NLS-1$ 12, 63, new String[] { "select", //$NON-NLS-1$ }, new String[] { "$root/@patternVersion", //$NON-NLS-1$ } ); private static final TagInfo _td_c_get_13_23 = new TagInfo("c:get", //$NON-NLS-1$ 13, 23, new String[] { "select", //$NON-NLS-1$ }, new String[] { "$root/@patternName", //$NON-NLS-1$ } ); private static final TagInfo _td_c_get_14_26 = new TagInfo("c:get", //$NON-NLS-1$ 14, 26, new String[] { "select", //$NON-NLS-1$ }, new String[] { "$root/@patternVersion", //$NON-NLS-1$ } ); public void generate(final JET2Context context, final JET2Writer __out) { JET2Writer out = __out; com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin pattern = com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin.getInstance(); com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages messages = new com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages(); RuntimeTagElement _jettag_c_if_5_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_5_1); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_if_5_1.setRuntimeParent(null); _jettag_c_if_5_1.setTagInfo(_td_c_if_5_1); _jettag_c_if_5_1.doStart(context, out); while (_jettag_c_if_5_1.okToProcessBody()) { // Tag exists RuntimeTagElement _jettag_c_if_7_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_7_1); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_if_7_1.setRuntimeParent(_jettag_c_if_5_1); _jettag_c_if_7_1.setTagInfo(_td_c_if_7_1); _jettag_c_if_7_1.doStart(context, out); while (_jettag_c_if_7_1.okToProcessBody()) { // and has a value out.write("BROKER SCHEMA "); //$NON-NLS-1$ RuntimeTagElement _jettag_c_get_9_15 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_9_15); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_get_9_15.setRuntimeParent(_jettag_c_if_7_1); _jettag_c_get_9_15.setTagInfo(_td_c_get_9_15); _jettag_c_get_9_15.doStart(context, out); _jettag_c_get_9_15.doEnd(); out.write(NL); _jettag_c_if_7_1.handleBodyContent(out); } _jettag_c_if_7_1.doEnd(); _jettag_c_if_5_1.handleBodyContent(out); } _jettag_c_if_5_1.doEnd(); out.write("-- Generated by "); //$NON-NLS-1$ RuntimeTagElement _jettag_c_get_12_18 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_18); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_get_12_18.setRuntimeParent(null); _jettag_c_get_12_18.setTagInfo(_td_c_get_12_18); _jettag_c_get_12_18.doStart(context, out); _jettag_c_get_12_18.doEnd(); out.write(" Version "); //$NON-NLS-1$ RuntimeTagElement _jettag_c_get_12_63 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_63); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_get_12_63.setRuntimeParent(null); _jettag_c_get_12_63.setTagInfo(_td_c_get_12_63); _jettag_c_get_12_63.doStart(context, out); _jettag_c_get_12_63.doEnd(); out.write(NL); out.write("-- $MQSI patternName="); //$NON-NLS-1$ RuntimeTagElement _jettag_c_get_13_23 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_13_23); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_get_13_23.setRuntimeParent(null); _jettag_c_get_13_23.setTagInfo(_td_c_get_13_23); _jettag_c_get_13_23.doStart(context, out); _jettag_c_get_13_23.doEnd(); out.write(" MQSI$"); //$NON-NLS-1$ out.write(NL); out.write("-- $MQSI patternVersion="); //$NON-NLS-1$ RuntimeTagElement _jettag_c_get_14_26 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_14_26); //$NON-NLS-1$ //$NON-NLS-2$ _jettag_c_get_14_26.setRuntimeParent(null); _jettag_c_get_14_26.setTagInfo(_td_c_get_14_26); _jettag_c_get_14_26.doStart(context, out); _jettag_c_get_14_26.doEnd(); out.write(" MQSI$"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("DECLARE ErrorLoggingOn EXTERNAL BOOLEAN TRUE;"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("CREATE COMPUTE MODULE SF_Build_Error_Message"); //$NON-NLS-1$ out.write(NL); out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$ out.write(NL); out.write("\tBEGIN"); //$NON-NLS-1$ out.write(NL); out.write("\tSET OutputRoot.Properties = NULL;"); //$NON-NLS-1$ out.write(NL); out.write("\t-- No MQMD header so create domain "); //$NON-NLS-1$ out.write(NL); out.write("\tCREATE FIRSTCHILD OF OutputRoot DOMAIN ('MQMD') NAME 'MQMD';"); //$NON-NLS-1$ out.write(NL); out.write("\tDECLARE MQMDRef REFERENCE TO OutputRoot.MQMD;"); //$NON-NLS-1$ out.write(NL); out.write("\tSET MQMDRef.Version = MQMD_CURRENT_VERSION;"); //$NON-NLS-1$ out.write(NL); out.write("\tSET MQMDRef.ApplIdentityData = SQL.BrokerName;"); //$NON-NLS-1$ out.write(NL); out.write("\tSET MQMDRef.CodedCharSetId = InputRoot.Properties.CodedCharSetId;"); //$NON-NLS-1$ out.write(NL); out.write("\tSET MQMDRef.Encoding = InputRoot.Properties.Encoding;"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("\tCREATE NEXTSIBLING OF MQMDRef DOMAIN('XMLNSC') NAME 'XMLNSC';"); //$NON-NLS-1$ out.write(NL); out.write("\tDECLARE OutRef REFERENCE TO OutputRoot.XMLNSC;"); //$NON-NLS-1$ out.write(NL); out.write("\t-- Create error data\t"); //$NON-NLS-1$ out.write(NL); out.write("\tSET OutRef.Error.BrokerName = SQL.BrokerName;"); //$NON-NLS-1$ out.write(NL); out.write("\tMOVE OutRef TO OutputRoot.XMLNSC.Error;"); //$NON-NLS-1$ out.write(NL); out.write(" SET OutRef.MessageFlowLabel = SQL.MessageFlowLabel; "); //$NON-NLS-1$ out.write(NL); out.write(" SET OutRef.DTSTAMP = CURRENT_TIMESTAMP; "); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("\t"); //$NON-NLS-1$ out.write(NL); out.write("\t"); //$NON-NLS-1$ out.write(NL); out.write("\tCall AddExceptionData();"); //$NON-NLS-1$ out.write(NL); out.write("\tEND;"); //$NON-NLS-1$ out.write(NL); out.write(" "); //$NON-NLS-1$ out.write(NL); out.write("CREATE PROCEDURE AddExceptionData() BEGIN"); //$NON-NLS-1$ out.write(NL); out.write("\t"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE ERef REFERENCE TO OutputRoot.XMLNSC.Error; "); //$NON-NLS-1$ out.write(NL); out.write("\t -- Add some exception data for error and fault"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE Error INTEGER;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE Text CHARACTER;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE Label CHARACTER;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDeclare FaultText CHARACTER '"); //$NON-NLS-1$ out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.1") ); out.write("';"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE I INTEGER 1;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE K INTEGER;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tDECLARE start REFERENCE TO InputExceptionList.*[1];"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("\t\tWHILE start.Number IS NOT NULL DO "); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tSET Label = start.Label;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tSET Error = start.Number;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tIF Error = 3001 THEN"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET Text = start.Insert.Text;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tELSE"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET Text = start.Text;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tEND IF;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t-- Don't include the \"Caught exception and rethrowing message\""); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tIF Error <> 2230 THEN"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t-- Process inserts"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tDECLARE Inserts Character;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tDECLARE INS Integer;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSet Inserts = '';"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t-- Are there any inserts for this exception"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tIF EXISTS (start.Insert[]) THEN"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t-- If YES add them to inserts string"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t \tSET Inserts = Inserts || COALESCE(start.Insert[1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t \tSET K = 1;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t \tINSERTS: LOOP"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\tIF CARDINALITY(start.Insert[])> K "); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\tTHEN "); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\t\tSET Inserts = Inserts || COALESCE(start.Insert[K+1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\t-- No more inserts to process"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\tELSE LEAVE INSERTS;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\t\tEND IF;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\tSET K = K+1;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t\tEND LOOP INSERTS;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tEND IF;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET ERef.Exception[I].Label = Label;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET ERef.Exception[I].Error = Error;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET ERef.Exception[I].Text = Text;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSet ERef.Exception[I].Inserts = COALESCE(Inserts, '');"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\t"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$ out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.2") ); out.write(" ' || COALESCE(Label, ''); "); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$ out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.3") ); out.write(" ' || COALESCE(CAST(Error AS CHARACTER), '');"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$ out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.4") ); out.write(" ' || COALESCE(Text, '');"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$ out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.8") ); out.write(" ' || COALESCE(Inserts, '');"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t"); //$NON-NLS-1$ <|fim▁hole|> out.write("\t\t\t\tSET I = I+1; "); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tEND IF;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t-- Move start to the last child of the field to which it currently points"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\tMOVE start LASTCHILD;"); //$NON-NLS-1$ out.write(NL); out.write("\t\tEND WHILE;"); //$NON-NLS-1$ out.write(NL); out.write("\t\t\t\tSET Environment.PatternVariables.FaultText = FaultText;"); //$NON-NLS-1$ out.write(NL); out.write("\tEND; "); //$NON-NLS-1$ out.write(NL); out.write(" "); //$NON-NLS-1$ out.write(NL); out.write(" "); //$NON-NLS-1$ out.write(NL); out.write("END MODULE;"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("CREATE FILTER MODULE CheckifMessageSent"); //$NON-NLS-1$ out.write(NL); out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$ out.write(NL); out.write("\tBEGIN"); //$NON-NLS-1$ out.write(NL); out.write("\t\tRETURN Environment.PatternVariables.Complete = 'Complete';"); //$NON-NLS-1$ out.write(NL); out.write(NL); out.write("\tEND;"); //$NON-NLS-1$ out.write(NL); out.write("\tEND MODULE;"); //$NON-NLS-1$ out.write(NL); out.write("CREATE FILTER MODULE CheckErrorLogging"); //$NON-NLS-1$ out.write(NL); out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$ out.write(NL); out.write("\tBEGIN"); //$NON-NLS-1$ out.write(NL); out.write("\t\tRETURN ErrorLoggingOn;"); //$NON-NLS-1$ out.write(NL); out.write("\tEND;"); //$NON-NLS-1$ out.write(NL); out.write("\tEND MODULE;"); //$NON-NLS-1$ out.write(NL); out.write("\t"); //$NON-NLS-1$ out.write(NL); out.write("\t"); //$NON-NLS-1$ out.write(NL); out.write("CREATE DATABASE MODULE Throw"); //$NON-NLS-1$ out.write(NL); out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$ out.write(NL); out.write("\tBEGIN"); //$NON-NLS-1$ out.write(NL); out.write("\tTHROW USER EXCEPTION SEVERITY 3 MESSAGE 2372 VALUES(Environment.PatternVariables.FaultText);"); //$NON-NLS-1$ out.write(NL); out.write("END;"); //$NON-NLS-1$ out.write(NL); out.write("END MODULE;"); //$NON-NLS-1$ out.write(NL); out.write(NL); } }<|fim▁end|>
out.write(NL);
<|file_name|>connection_core.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2009, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.8.0r4 */ /** * The Connection Manager provides a simplified interface to the XMLHttpRequest * object. It handles cross-browser instantiantion of XMLHttpRequest, negotiates the * interactive states and server response, returning the results to a pre-defined * callback you create. * * @namespace YAHOO.util * @module connection * @requires yahoo * @requires event */ /** * The Connection Manager singleton provides methods for creating and managing * asynchronous transactions. * * @class Connect */ YAHOO.util.Connect = { /** * @description Array of MSFT ActiveX ids for XMLHttpRequest. * @property _msxml_progid * @private * @static * @type array */ _msxml_progid:[ 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP' ], /** * @description Object literal of HTTP header(s) * @property _http_header * @private * @static * @type object */ _http_headers:{}, /** * @description Determines if HTTP headers are set. * @property _has_http_headers * @private * @static * @type boolean */ _has_http_headers:false, /** * @description Determines if a default header of * Content-Type of 'application/x-www-form-urlencoded' * will be added to any client HTTP headers sent for POST * transactions. * @property _use_default_post_header * @private * @static * @type boolean */ _use_default_post_header:true, /** * @description The default header used for POST transactions. * @property _default_post_header * @private * @static * @type boolean */ _default_post_header:'application/x-www-form-urlencoded; charset=UTF-8', /** * @description The default header used for transactions involving the * use of HTML forms. * @property _default_form_header * @private * @static * @type boolean */ _default_form_header:'application/x-www-form-urlencoded', /** * @description Determines if a default header of * 'X-Requested-With: XMLHttpRequest' * will be added to each transaction. * @property _use_default_xhr_header * @private * @static * @type boolean */ _use_default_xhr_header:true, /** * @description The default header value for the label * "X-Requested-With". This is sent with each * transaction, by default, to identify the * request as being made by YUI Connection Manager. * @property _default_xhr_header * @private * @static * @type boolean */ _default_xhr_header:'XMLHttpRequest', /** * @description Determines if custom, default headers * are set for each transaction. * @property _has_default_header * @private * @static * @type boolean */ _has_default_headers:true, /** * @description Determines if custom, default headers * are set for each transaction. * @property _has_default_header * @private * @static * @type boolean */ _default_headers:{}, /** * @description Collection of polling references to the polling mechanism in handleReadyState. * @property _poll * @private * @static * @type object */ _poll:{}, /** * @description Queue of timeout values for each transaction callback with a defined timeout value. * @property _timeOut * @private * @static * @type object */ _timeOut:{}, /** * @description The polling frequency, in milliseconds, for HandleReadyState. * when attempting to determine a transaction's XHR readyState. * The default is 50 milliseconds. * @property _polling_interval * @private * @static * @type int */ _polling_interval:50, /** * @description A transaction counter that increments the transaction id for each transaction. * @property _transaction_id * @private * @static * @type int */ _transaction_id:0, /** * @description Custom event that fires at the start of a transaction * @property startEvent * @private * @static * @type CustomEvent */ startEvent: new YAHOO.util.CustomEvent('start'), /** * @description Custom event that fires when a transaction response has completed. * @property completeEvent * @private * @static * @type CustomEvent */ completeEvent: new YAHOO.util.CustomEvent('complete'), /** * @description Custom event that fires when handleTransactionResponse() determines a * response in the HTTP 2xx range. * @property successEvent * @private * @static * @type CustomEvent */ successEvent: new YAHOO.util.CustomEvent('success'), /** * @description Custom event that fires when handleTransactionResponse() determines a * response in the HTTP 4xx/5xx range. * @property failureEvent * @private * @static * @type CustomEvent */ failureEvent: new YAHOO.util.CustomEvent('failure'), /** * @description Custom event that fires when a transaction is successfully aborted. * @property abortEvent * @private * @static * @type CustomEvent */ abortEvent: new YAHOO.util.CustomEvent('abort'), /** * @description A reference table that maps callback custom events members to its specific * event name. * @property _customEvents * @private * @static * @type object */ _customEvents: { onStart:['startEvent', 'start'], onComplete:['completeEvent', 'complete'], onSuccess:['successEvent', 'success'], onFailure:['failureEvent', 'failure'], onUpload:['uploadEvent', 'upload'], onAbort:['abortEvent', 'abort'] }, /** * @description Member to add an ActiveX id to the existing xml_progid array. * In the event(unlikely) a new ActiveX id is introduced, it can be added * without internal code modifications. * @method setProgId * @public * @static * @param {string} id The ActiveX id to be added to initialize the XHR object. * @return void */ setProgId:function(id) { this._msxml_progid.unshift(id); }, /** * @description Member to override the default POST header. * @method setDefaultPostHeader * @public * @static * @param {boolean} b Set and use default header - true or false . * @return void */ setDefaultPostHeader:function(b) { if(typeof b == 'string'){ this._default_post_header = b; } else if(typeof b == 'boolean'){ this._use_default_post_header = b; } }, /** * @description Member to override the default transaction header.. * @method setDefaultXhrHeader * @public * @static * @param {boolean} b Set and use default header - true or false . * @return void */ setDefaultXhrHeader:function(b) { if(typeof b == 'string'){ this._default_xhr_header = b; } else{ this._use_default_xhr_header = b; } }, /** * @description Member to modify the default polling interval. * @method setPollingInterval * @public * @static * @param {int} i The polling interval in milliseconds. * @return void */ setPollingInterval:function(i) { if(typeof i == 'number' && isFinite(i)){ this._polling_interval = i; } }, /** * @description Instantiates a XMLHttpRequest object and returns an object with two properties: * the XMLHttpRequest instance and the transaction id. * @method createXhrObject * @private * @static * @param {int} transactionId Property containing the transaction id for this transaction. * @return object */ createXhrObject:function(transactionId) { var obj,http,i; try { // Instantiates XMLHttpRequest in non-IE browsers and assigns to http. http = new XMLHttpRequest(); // Object literal with http and tId properties obj = { conn:http, tId:transactionId, xhr: true }; } catch(e) { for(i=0; i<this._msxml_progid.length; ++i){ try { // Instantiates XMLHttpRequest for IE and assign to http http = new ActiveXObject(this._msxml_progid[i]); // Object literal with conn and tId properties obj = { conn:http, tId:transactionId, xhr: true }; break; } catch(e1){} } } finally { return obj; } }, /** * @description This method is called by asyncRequest to create a * valid connection object for the transaction. It also passes a * transaction id and increments the transaction id counter. * @method getConnectionObject * @private * @static * @return {object} */ getConnectionObject:function(t) { var o, tId = this._transaction_id; try { if(!t){ o = this.createXhrObject(tId); } else{ o = {tId:tId}; if(t==='xdr'){ o.conn = this._transport; o.xdr = true; } else if(t==='upload'){ o.upload = true; } } if(o){ this._transaction_id++; } } catch(e){} return o; }, /** * @description Method for initiating an asynchronous request via the XHR object. * @method asyncRequest * @public * @static * @param {string} method HTTP transaction method * @param {string} uri Fully qualified path of resource * @param {callback} callback User-defined callback function or object * @param {string} postData POST body * @return {object} Returns the connection object */ asyncRequest:function(method, uri, callback, postData) { var o,t,args = (callback && callback.argument)?callback.argument:null; if(this._isFileUpload){ t = 'upload'; } else if(callback.xdr){ t = 'xdr'; } o = this.getConnectionObject(t); if(!o){ return null; } else{ // Intialize any transaction-specific custom events, if provided. if(callback && callback.customevents){ this.initCustomEvents(o, callback); } if(this._isFormSubmit){ if(this._isFileUpload){ this.uploadFile(o, callback, uri, postData); return o; } // If the specified HTTP method is GET, setForm() will return an // encoded string that is concatenated to the uri to // create a querystring. if(method.toUpperCase() == 'GET'){ if(this._sFormData.length !== 0){ // If the URI already contains a querystring, append an ampersand // and then concatenate _sFormData to the URI. uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData; } } else if(method.toUpperCase() == 'POST'){ // If POST data exist in addition to the HTML form data, // it will be concatenated to the form data. postData = postData?this._sFormData + "&" + postData:this._sFormData; } } if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){ // If callback.cache is defined and set to false, a // timestamp value will be added to the querystring. uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString(); } // Each transaction will automatically include a custom header of // "X-Requested-With: XMLHttpRequest" to identify the request as // having originated from Connection Manager. if(this._use_default_xhr_header){ if(!this._default_headers['X-Requested-With']){ this.initHeader('X-Requested-With', this._default_xhr_header, true); } } //If the transaction method is POST and the POST header value is set to true //or a custom value, initalize the Content-Type header to this value. if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){ this.initHeader('Content-Type', this._default_post_header); } if(o.xdr){ this.xdr(o, method, uri, callback, postData); return o; } o.conn.open(method, uri, true); //Initialize all default and custom HTTP headers, if(this._has_default_headers || this._has_http_headers){ this.setHeader(o); } this.handleReadyState(o, callback); o.conn.send(postData || ''); // Reset the HTML form data and state properties as // soon as the data are submitted. if(this._isFormSubmit === true){ this.resetFormState(); } // Fire global custom event -- startEvent this.startEvent.fire(o, args); if(o.startEvent){ // Fire transaction custom event -- startEvent o.startEvent.fire(o, args); } return o; } }, /** * @description This method creates and subscribes custom events, * specific to each transaction * @method initCustomEvents * @private * @static * @param {object} o The connection object * @param {callback} callback The user-defined callback object * @return {void} */ initCustomEvents:function(o, callback) { var prop; // Enumerate through callback.customevents members and bind/subscribe // events that match in the _customEvents table. for(prop in callback.customevents){ if(this._customEvents[prop][0]){ // Create the custom event o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null); // Subscribe the custom event o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]); } } }, /** * @description This method serves as a timer that polls the XHR object's readyState * property during a transaction, instead of binding a callback to the * onreadystatechange event. Upon readyState 4, handleTransactionResponse * will process the response, and the timer will be cleared. * @method handleReadyState * @private * @static * @param {object} o The connection object * @param {callback} callback The user-defined callback object * @return {void} */ handleReadyState:function(o, callback) { var oConn = this, args = (callback && callback.argument)?callback.argument:null; if(callback && callback.timeout){ this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout); } this._poll[o.tId] = window.setInterval( function(){ if(o.conn && o.conn.readyState === 4){ // Clear the polling interval for the transaction // and remove the reference from _poll. window.clearInterval(oConn._poll[o.tId]); delete oConn._poll[o.tId]; if(callback && callback.timeout){ window.clearTimeout(oConn._timeOut[o.tId]); delete oConn._timeOut[o.tId]; } // Fire global custom event -- completeEvent oConn.completeEvent.fire(o, args); if(o.completeEvent){ // Fire transaction custom event -- completeEvent o.completeEvent.fire(o, args); } oConn.handleTransactionResponse(o, callback); } } ,this._polling_interval); }, /** * @description This method attempts to interpret the server response and * determine whether the transaction was successful, or if an error or * exception was encountered. * @method handleTransactionResponse * @private * @static * @param {object} o The connection object * @param {object} callback The user-defined callback object * @param {boolean} isAbort Determines if the transaction was terminated via abort(). * @return {void} */ handleTransactionResponse:function(o, callback, isAbort) { var httpStatus, responseObject, args = (callback && callback.argument)?callback.argument:null, xdrS = (o.r && o.r.statusText === 'xdr:success')?true:false, xdrF = (o.r && o.r.statusText === 'xdr:failure')?true:false, xdrA = isAbort; try { if((o.conn.status !== undefined && o.conn.status !== 0) || xdrS){ // XDR requests will not have HTTP status defined. The // statusText property will define the response status // set by the Flash transport. httpStatus = o.conn.status; } else if(xdrF && !xdrA){ // Set XDR transaction failure to a status of 0, which // resolves as an HTTP failure, instead of an exception. httpStatus = 0; } else{ httpStatus = 13030; } } catch(e){ // 13030 is a custom code to indicate the condition -- in Mozilla/FF -- // when the XHR object's status and statusText properties are // unavailable, and a query attempt throws an exception. httpStatus = 13030; } if((httpStatus >= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){ responseObject = o.xdr ? o.r : this.createResponseObject(o, args);<|fim▁hole|> else{ // If a scope property is defined, the callback will be fired from // the context of the object. callback.success.apply(callback.scope, [responseObject]); } } // Fire global custom event -- successEvent this.successEvent.fire(responseObject); if(o.successEvent){ // Fire transaction custom event -- successEvent o.successEvent.fire(responseObject); } } else{ switch(httpStatus){ // The following cases are wininet.dll error codes that may be encountered. case 12002: // Server timeout case 12029: // 12029 to 12031 correspond to dropped connections. case 12030: case 12031: case 12152: // Connection closed by server. case 13030: // See above comments for variable status. // XDR transactions will not resolve to this case, since the // response object is already built in the xdr response. responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false)); if(callback && callback.failure){ if(!callback.scope){ callback.failure(responseObject); } else{ callback.failure.apply(callback.scope, [responseObject]); } } break; default: responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args); if(callback && callback.failure){ if(!callback.scope){ callback.failure(responseObject); } else{ callback.failure.apply(callback.scope, [responseObject]); } } } // Fire global custom event -- failureEvent this.failureEvent.fire(responseObject); if(o.failureEvent){ // Fire transaction custom event -- failureEvent o.failureEvent.fire(responseObject); } } this.releaseObject(o); responseObject = null; }, /** * @description This method evaluates the server response, creates and returns the results via * its properties. Success and failure cases will differ in the response * object's property values. * @method createResponseObject * @private * @static * @param {object} o The connection object * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback * @return {object} */ createResponseObject:function(o, callbackArg) { var obj = {}, headerObj = {}, i, headerStr, header, delimitPos; try { headerStr = o.conn.getAllResponseHeaders(); header = headerStr.split('\n'); for(i=0; i<header.length; i++){ delimitPos = header[i].indexOf(':'); if(delimitPos != -1){ headerObj[header[i].substring(0,delimitPos)] = YAHOO.lang.trim(header[i].substring(delimitPos+2)); } } } catch(e){} obj.tId = o.tId; // Normalize IE's response to HTTP 204 when Win error 1223. obj.status = (o.conn.status == 1223)?204:o.conn.status; // Normalize IE's statusText to "No Content" instead of "Unknown". obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText; obj.getResponseHeader = headerObj; obj.getAllResponseHeaders = headerStr; obj.responseText = o.conn.responseText; obj.responseXML = o.conn.responseXML; if(callbackArg){ obj.argument = callbackArg; } return obj; }, /** * @description If a transaction cannot be completed due to dropped or closed connections, * there may be not be enough information to build a full response object. * The failure callback will be fired and this specific condition can be identified * by a status property value of 0. * * If an abort was successful, the status property will report a value of -1. * * @method createExceptionObject * @private * @static * @param {int} tId The Transaction Id * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort * @return {object} */ createExceptionObject:function(tId, callbackArg, isAbort) { var COMM_CODE = 0, COMM_ERROR = 'communication failure', ABORT_CODE = -1, ABORT_ERROR = 'transaction aborted', obj = {}; obj.tId = tId; if(isAbort){ obj.status = ABORT_CODE; obj.statusText = ABORT_ERROR; } else{ obj.status = COMM_CODE; obj.statusText = COMM_ERROR; } if(callbackArg){ obj.argument = callbackArg; } return obj; }, /** * @description Method that initializes the custom HTTP headers for the each transaction. * @method initHeader * @public * @static * @param {string} label The HTTP header label * @param {string} value The HTTP header value * @param {string} isDefault Determines if the specific header is a default header * automatically sent with each transaction. * @return {void} */ initHeader:function(label, value, isDefault) { var headerObj = (isDefault)?this._default_headers:this._http_headers; headerObj[label] = value; if(isDefault){ this._has_default_headers = true; } else{ this._has_http_headers = true; } }, /** * @description Accessor that sets the HTTP headers for each transaction. * @method setHeader * @private * @static * @param {object} o The connection object for the transaction. * @return {void} */ setHeader:function(o) { var prop; if(this._has_default_headers){ for(prop in this._default_headers){ if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){ o.conn.setRequestHeader(prop, this._default_headers[prop]); } } } if(this._has_http_headers){ for(prop in this._http_headers){ if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){ o.conn.setRequestHeader(prop, this._http_headers[prop]); } } this._http_headers = {}; this._has_http_headers = false; } }, /** * @description Resets the default HTTP headers object * @method resetDefaultHeaders * @public * @static * @return {void} */ resetDefaultHeaders:function(){ this._default_headers = {}; this._has_default_headers = false; }, /** * @description Method to terminate a transaction, if it has not reached readyState 4. * @method abort * @public * @static * @param {object} o The connection object returned by asyncRequest. * @param {object} callback User-defined callback object. * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout. * @return {boolean} */ abort:function(o, callback, isTimeout) { var abortStatus, args = (callback && callback.argument)?callback.argument:null; o = o || {}; if(o.conn){ if(o.xhr){ if(this.isCallInProgress(o)){ // Issue abort request o.conn.abort(); window.clearInterval(this._poll[o.tId]); delete this._poll[o.tId]; if(isTimeout){ window.clearTimeout(this._timeOut[o.tId]); delete this._timeOut[o.tId]; } abortStatus = true; } } else if(o.xdr){ o.conn.abort(o.tId); abortStatus = true; } } else if(o.upload){ var frameId = 'yuiIO' + o.tId; var io = document.getElementById(frameId); if(io){ // Remove all listeners on the iframe prior to // its destruction. YAHOO.util.Event.removeListener(io, "load"); // Destroy the iframe facilitating the transaction. document.body.removeChild(io); if(isTimeout){ window.clearTimeout(this._timeOut[o.tId]); delete this._timeOut[o.tId]; } abortStatus = true; } } else{ abortStatus = false; } if(abortStatus === true){ // Fire global custom event -- abortEvent this.abortEvent.fire(o, args); if(o.abortEvent){ // Fire transaction custom event -- abortEvent o.abortEvent.fire(o, args); } this.handleTransactionResponse(o, callback, true); } return abortStatus; }, /** * @description Determines if the transaction is still being processed. * @method isCallInProgress * @public * @static * @param {object} o The connection object returned by asyncRequest * @return {boolean} */ isCallInProgress:function(o) { o = o || {}; // if the XHR object assigned to the transaction has not been dereferenced, // then check its readyState status. Otherwise, return false. if(o.xhr && o.conn){ return o.conn.readyState !== 4 && o.conn.readyState !== 0; } else if(o.xdr && o.conn){ return o.conn.isCallInProgress(o.tId); } else if(o.upload === true){ return document.getElementById('yuiIO' + o.tId)?true:false; } else{ return false; } }, /** * @description Dereference the XHR instance and the connection object after the transaction is completed. * @method releaseObject * @private * @static * @param {object} o The connection object * @return {void} */ releaseObject:function(o) { if(o && o.conn){ //dereference the XHR instance. o.conn = null; //dereference the connection object. o = null; } } }; YAHOO.register("connection_core", YAHOO.util.Connect, {version: "2.8.0r4", build: "2449"});<|fim▁end|>
if(callback && callback.success){ if(!callback.scope){ callback.success(responseObject); }
<|file_name|>seeds_threshold.py<|end_file_name|><|fim▁begin|># This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License from load import load_dataset import numpy as np from threshold import learn_model, apply_model, accuracy features, labels = load_dataset('seeds') # Turn the labels into a binary array labels = (labels == 'Canadian') error = 0.0 for fold in range(10): training = np.ones(len(features), bool) <|fim▁hole|> # whatever is not training is for testing testing = ~training model = learn_model(features[training], labels[training]) test_error = accuracy(features[testing], labels[testing], model) error += test_error error /= 10.0 print('Ten fold cross-validated error was {0:.1%}.'.format(error))<|fim▁end|>
# numpy magic to make an array with 10% of 0s starting at fold training[fold::10] = 0
<|file_name|>coinaaa_ar.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Coinaaa Core</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Coinaaa Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+29"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Coinaaa Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <location line="+2"/> <source> (%1-bit)</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation>أنقر على الماوس مرتين لتعديل العنوان</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>انشأ عنوان جديد</translation> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation>قم بنسخ القوانين المختارة لحافظة النظام</translation> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+74"/> <source>&amp;Copy Address</source> <translation>انسخ العنوان</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation>&amp;أمسح</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your Coinaaa addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your Coinaaa addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>تعديل</translation> </message> <message> <location line="+194"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+168"/> <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 filename="../askpassphrasedialog.cpp" line="+40"/> <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>أدخل عبارة مرور جديدة إلى المحفظة. الرجاء استخدام عبارة مرور تتكون من10 حروف عشوائية على الاقل, أو أكثر من 7 كلمات </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>تشفير المحفظة</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>هذه العملية تحتاج عبارة المرور محفظتك لفتحها</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>إفتح المحفظة</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>هذه العملية تحتاج عبارة المرور محفظتك فك تشفيرها</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>فك تشفير المحفظة</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>تغيير عبارة المرور</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>أدخل عبارة المرور القديمة والجديدة إلى المحفظة.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>تأكيد التشفير المحفظة</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR CoinaaaS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>محفظة مشفرة</translation> </message> <message> <location line="-56"/> <source>Coinaaa will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coinaaas from being stolen by malware infecting your computer.</source> <translation>بتكوين سوف يغلق الآن لإنهاء عملية التشفير. تذكر أن التشفير لا يستطيع حماية محفظتك تمامًا من السرقة من خلال البرمجيات الخبيثة التي تصيب جهازك </translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>فشل تشفير المحفظة</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>شل تشفير المحفظة بسبب خطأ داخلي. لم يتم تشفير محفظتك.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>عبارتي المرور ليستا متطابقتان </translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>فشل فتح المحفظة</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>عبارة المرور التي تم إدخالها لفك شفرة المحفظة غير صحيحة. </translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>فشل فك التشفير المحفظة</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinaaaGUI</name> <message> <location filename="../coinaaagui.cpp" line="+295"/> <source>Sign &amp;message...</source> <translation>التوقيع و الرسائل</translation> </message> <message> <location line="+335"/> <source>Synchronizing with network...</source> <translation>مزامنة مع شبكة ...</translation> </message> <message> <location line="-407"/> <source>&amp;Overview</source> <translation>نظرة عامة</translation> </message> <message> <location line="-137"/> <source>Node</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Show general overview of wallet</source> <translation>إظهار نظرة عامة على المحفظة</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>المعاملات</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>تصفح التاريخ المعاملات</translation> </message> <message> <location line="+17"/> <source>E&amp;xit</source> <translation>خروج</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>الخروج من التطبيق</translation> </message> <message> <location line="+7"/> <source>Show information about Coinaaa</source> <translation> إظهار المزيد معلومات حول Coinaaa</translation> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation>عن</translation> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation>اظهر المعلومات</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>خيارات ...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <location line="+325"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-405"/> <source>Send coins to a Coinaaa address</source> <translation>ارسل عملات الى عنوان بيتكوين</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Coinaaa</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>احفظ نسخة احتياطية للمحفظة في مكان آخر</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>تغيير عبارة المرور المستخدمة لتشفير المحفظة</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="+430"/> <source>Coinaaa</source> <translation>بت كوين</translation> </message> <message> <location line="-643"/> <source>Wallet</source> <translation>محفظة</translation> </message> <message> <location line="+146"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Coinaaa addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Coinaaa addresses</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>&amp;File</source> <translation>ملف</translation> </message> <message> <location line="+14"/> <source>&amp;Settings</source> <translation>الاعدادات</translation> </message> <message> <location line="+9"/> <source>&amp;Help</source> <translation>مساعدة</translation> </message> <message> <location line="+15"/> <source>Tabs toolbar</source> <translation>شريط أدوات علامات التبويب</translation> </message> <message> <location line="-284"/> <location line="+376"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-401"/> <source>Coinaaa Core</source> <translation type="unfinished"/> </message> <message> <location line="+163"/> <source>Request payments (generates QR codes and coinaaa: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <location line="+2"/> <source>&amp;About Coinaaa Core</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open a coinaaa: URI or payment request</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the Coinaaa Core help message to get a list with possible Coinaaa command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+159"/> <location line="+5"/> <source>Coinaaa client</source> <translation>عميل بتكوين</translation> </message> <message numerus="yes"> <location line="+142"/> <source>%n active connection(s) to Coinaaa network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+23"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Error</source> <translation>خطأ</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="-85"/> <source>Up to date</source> <translation>محين</translation> </message> <message> <location line="+34"/> <source>Catching up...</source> <translation>اللحاق بالركب ...</translation> </message> <message> <location line="+130"/> <source>Sent transaction</source> <translation>المعاملات المرسلة</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>المعاملات واردة</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>المحفظة مشفرة و مفتوحة حاليا</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>المحفظة مشفرة و مقفلة حاليا</translation> </message> <message> <location filename="../coinaaa.cpp" line="+435"/> <source>A fatal error occurred. Coinaaa can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+119"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <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="+53"/> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <location line="+10"/> <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="+42"/> <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="+1"/> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <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="+323"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>higher</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>lower</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+141"/> <source>Dust</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>نعم</translation> </message> <message> <location line="+0"/> <source>no</source> <translation>لا</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+5"/> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+4"/> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <location line="-3"/> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <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 type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation>العنوان</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+28"/> <source>New receiving address</source> <translation>عنوان تلقي جديد</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>عنوان إرسال جديد</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>تعديل عنوان التلقي </translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>تعديل عنوان الارسال</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>هدا العنوان &quot;%1&quot; موجود مسبقا في دفتر العناوين</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Coinaaa address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation> يمكن فتح المحفظة.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>فشل توليد مفتاح جديد.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+65"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <location filename="../forms/helpmessagedialog.ui" line="+19"/> <source>Coinaaa Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+24"/> <source>Coinaaa Core</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>version</source> <translation>النسخة</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>المستخدم</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation>خيارات UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to Coinaaa Core.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where Coinaaa Core will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Coinaaa Core will download and store a copy of the Coinaaa block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+85"/> <source>Coinaaa</source> <translation>بت كوين</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Error</source> <translation>خطأ</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <location filename="../forms/openuridialog.ui" line="+14"/> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>URI:</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <location filename="../openuridialog.cpp" line="+47"/> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source><|fim▁hole|> <source>&amp;Main</source> <translation>الرئيسي</translation> </message> <message> <location line="+122"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="-131"/> <source>Automatically start Coinaaa after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Coinaaa on system login</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>MB</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>&amp;Spend unconfirmed change (experts only)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Connect to the Coinaaa network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <location line="+224"/> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="-323"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="-86"/> <source>W&amp;allet</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Automatically open the Coinaaa 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="+19"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <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>نافذه</translation> </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 Coinaaa.</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 Coinaaa 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="+136"/> <source>&amp;OK</source> <translation>تم</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>الغاء</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+70"/> <source>default</source> <translation>الافتراضي</translation> </message> <message> <location line="+58"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+78"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+29"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The supplied proxy address is invalid.</source> <translation>عنوان الوكيل توفيره غير صالح.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>نمودج</translation> </message> <message> <location line="+50"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Coinaaa network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-238"/> <source>Wallet</source> <translation>محفظة</translation> </message> <message> <location line="+51"/> <source>Available:</source> <translation>متوفر</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Pending:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Immature:</source> <translation>غير ناضجة</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>اخر المعملات </translation> </message> <message> <location filename="../overviewpage.cpp" line="+120"/> <location line="+1"/> <source>out of sync</source> <translation>خارج المزامنه</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+403"/> <location line="+13"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid Coinaaa address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="-221"/> <location line="+212"/> <location line="+13"/> <location line="+95"/> <location line="+18"/> <location line="+16"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="-353"/> <source>Cannot start coinaaa: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <location line="+73"/> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../coinaaa.cpp" line="+71"/> <location line="+11"/> <source>Coinaaa</source> <translation>بت كوين</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> <message> <location filename="../guiutil.cpp" line="+82"/> <source>Enter a Coinaaa address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>إدخال عنوانCoinaaa (مثال :1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+36"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>اسم العميل</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+359"/> <source>N/A</source> <translation>غير معروف</translation> </message> <message> <location line="-223"/> <source>Client version</source> <translation>نسخه العميل</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>المعلومات</translation> </message> <message> <location line="-10"/> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>General</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <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>Name</source> <translation>الاسم</translation> </message> <message> <location line="+23"/> <source>Number of connections</source> <translation>عدد الاتصالات</translation> </message> <message> <location line="+29"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>الفتح</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="+72"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-521"/> <source>Build date</source> <translation>وقت البناء</translation> </message> <message> <location line="+206"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Coinaaa 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="+76"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Coinaaa RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+107"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <location line="+23"/> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Coinaaa network.</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <location line="+21"/> <source>An optional label to associate with the new receiving address.</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <location line="+22"/> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+78"/> <source>Requested payments history</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <location line="+120"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Remove</source> <translation type="unfinished"/> </message> <message> <location filename="../receivecoinsdialog.cpp" line="+38"/> <source>Copy label</source> <translation> انسخ التسمية</translation> </message> <message> <location line="+1"/> <source>Copy message</source> <translation>انسخ الرسالة</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>نسخ الكمية</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+56"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation>عنوان</translation> </message> <message> <location line="+2"/> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <location line="+2"/> <source>Label</source> <translation>وصف</translation> </message> <message> <location line="+2"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <location filename="../recentrequeststablemodel.cpp" line="+24"/> <source>Date</source> <translation>التاريخ</translation> </message> <message> <location line="+0"/> <source>Label</source> <translation>وصف</translation> </message> <message> <location line="+0"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation>المبلغ</translation> </message> <message> <location line="+38"/> <source>(no label)</source> <translation>(لا وصف)</translation> </message> <message> <location line="+9"/> <source>(no message)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>(no amount)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+380"/> <location line="+80"/> <source>Send Coins</source> <translation>إرسال Coins</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="+89"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </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="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+164"/> <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="-23"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>مسح الكل</translation> </message> <message> <location line="+52"/> <source>Balance:</source> <translation>الرصيد:</translation> </message> <message> <location line="-78"/> <source>Confirm the send action</source> <translation>تأكيد الإرسال</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-229"/> <source>Confirm send coins</source> <translation>تأكيد الإرسال Coins</translation> </message> <message> <location line="-74"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <location line="-121"/> <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="+170"/> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>or</source> <translation type="unfinished"/> </message> <message> <location line="+203"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount to pay must be larger than 0.</source> <translation>المبلغ المدفوع يجب ان يكون اكبر من 0</translation> </message> <message> <location line="+3"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>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="+113"/> <source>Warning: Invalid Coinaaa address</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>(no label)</source> <translation>(لا وصف)</translation> </message> <message> <location line="-11"/> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <location line="-367"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+171"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+131"/> <location line="+521"/> <location line="+536"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="-1152"/> <source>Pay &amp;To:</source> <translation>ادفع الى </translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+30"/> <source>Enter a label for this address to add it to your address book</source> <translation>إدخال تسمية لهذا العنوان لإضافته إلى دفتر العناوين الخاص بك</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="+57"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <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"/> <location line="+524"/> <location line="+536"/> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <location line="-1008"/> <source>Message:</source> <translation>الرسائل</translation> </message> <message> <location line="+968"/> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="-991"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>A message that was attached to the coinaaa: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Coinaaa network.</source> <translation type="unfinished"/> </message> <message> <location line="+426"/> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <location line="+532"/> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <location line="-498"/> <location line="+536"/> <source>Memo:</source> <translation type="unfinished"/> </message> </context> <context> <name>ShutdownWindow</name> <message> <location filename="../utilitydialog.cpp" line="+48"/> <source>Coinaaa Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not shut down the computer until this window disappears.</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="+10"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+210"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-200"/> <location line="+210"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-200"/> <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="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Coinaaa address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+143"/> <source>Clear &amp;All</source> <translation>مسح الكل</translation> </message> <message> <location line="-84"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Verify the message to ensure it was signed with the specified Coinaaa address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+30"/> <source>Enter a Coinaaa address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>إدخال عنوانCoinaaa (مثال :1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-1"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <location line="+80"/> <source>The entered address is invalid.</source> <translation>العنوان المدخل غير صالح</translation> </message> <message> <location line="-80"/> <location line="+8"/> <location line="+72"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>الرجاء التأكد من العنوان والمحاولة مرة اخرى</translation> </message> <message> <location line="-80"/> <location line="+80"/> <source>The entered address does not refer to a key.</source> <translation>العنوان المدخل لا يشير الى مفتاح</translation> </message> <message> <location line="-72"/> <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>المفتاح الخاص للعنوان المدخل غير موجود.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>فشل توقيع الرسالة.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>الرسالة موقعة.</translation> </message> <message> <location line="+58"/> <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>فشلت عملية التأكد من الرسالة.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>تم تأكيد الرسالة.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+28"/> <source>Coinaaa Core</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>The Coinaaa Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+79"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+28"/> <source>Open until %1</source> <translation>مفتوح حتى 1٪</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>1% غير متواجد</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>غير مؤكدة/1%</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>تأكيد %1</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>الحالة.</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>التاريخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>المصدر</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>تم اصداره.</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>من</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>الى</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>عنوانه</translation> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+53"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-125"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>غير مقبولة</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+53"/> <source>Debit</source> <translation>دين</translation> </message> <message> <location line="-62"/> <source>Transaction fee</source> <translation>رسوم التحويل</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <location line="+9"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>Comment</source> <translation>تعليق</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>رقم المعاملة</translation> </message> <message> <location line="+18"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>معاملة</translation> </message> <message> <location line="+3"/> <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>صحيح</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>خاطئ</translation> </message> <message> <location line="-232"/> <source>, has not been successfully broadcast yet</source> <translation>لم يتم حتى الآن البث بنجاح</translation> </message> <message numerus="yes"> <location line="-37"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+72"/> <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="+234"/> <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="+78"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-21"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>مفتوح حتى 1٪</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>تأكيد الإرسال Coins</translation> </message> <message> <location line="+9"/> <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="-21"/> <source>Offline</source> <translation>غير متصل</translation> </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="+51"/> <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>Mined</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="+57"/> <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>v</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>Mined</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>اخرى</translation> </message> <message> <location line="+6"/> <source>Enter address or label to search</source> <translation>ادخل عنوان أووصف للبحث</translation> </message> <message> <location line="+6"/> <source>Min amount</source> <translation type="unfinished"/> </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="+142"/> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Exporting Successful</source> <translation>نجح الاستخراج</translation> </message> <message> <location line="+0"/> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <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="+107"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation>الى</translation> </message> </context> <context> <name>WalletFrame</name> <message> <location filename="../walletframe.cpp" line="+26"/> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+245"/> <source>Send Coins</source> <translation>إرسال Coins</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+43"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+181"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>coinaaa-core</name> <message> <location filename="../coinaaastrings.cpp" line="+223"/> <source>Usage:</source> <translation>المستخدم</translation> </message> <message> <location line="-55"/> <source>List commands</source> <translation>اعرض الأوامر</translation> </message> <message> <location line="-14"/> <source>Get help for a command</source> <translation>مساعدة في كتابة الاوامر</translation> </message> <message> <location line="+26"/> <source>Options:</source> <translation>خيارات: </translation> </message> <message> <location line="+22"/> <source>Specify configuration file (default: coinaaa.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: coinaaad.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>حدد موقع مجلد المعلومات او data directory</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>ضع حجم كاش قاعدة البيانات بالميجابايت (الافتراضي: 25)</translation> </message> <message> <location line="-26"/> <source>Listen for connections on &lt;port&gt; (default: 12444 or testnet: 112444)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-51"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-150"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 12443 or testnet: 112443)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+81"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Use the test network</source> <translation>استخدم التحقق من الشبكه</translation> </message> <message> <location line="-120"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>قبول الاتصالات من خارج</translation> </message> <message> <location line="-95"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=coinaaarpc 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;Coinaaa Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Coinaaa is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Coinaaa will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Coinaaa Core Daemon</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Coinaaa RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Clear list of wallet transactions (diagnostic tool; implies -rescan)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 12443 or testnet: 112443)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>فشل في الاستماع على أي منفذ. استخدام الاستماع = 0 إذا كنت تريد هذا.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to Coinaaa server</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start Coinaaa server</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Usage (deprecated, use coinaaa-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-106"/> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>SSL options: (see the Coinaaa Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</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="+2"/> <source>Zapping all transactions from wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>version</source> <translation>النسخة</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-60"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-71"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+81"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+163"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>This help message</source> <translation>رسالة المساعدة هذه</translation> </message> <message> <location line="+7"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-109"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Loading addresses...</source> <translation>تحميل العنوان</translation> </message> <message> <location line="-37"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطأ عند تنزيل wallet.dat: المحفظة تالفة</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Coinaaa</source> <translation>خطأ عند تنزيل wallet.dat: المحفظة تتطلب نسخة أحدث من بتكوين</translation> </message> <message> <location line="+99"/> <source>Wallet needed to be rewritten: restart Coinaaa to complete</source> <translation>المحفظة تحتاج لإعادة إنشاء: أعد تشغيل بتكوين للإتمام</translation> </message> <message> <location line="-101"/> <source>Error loading wallet.dat</source> <translation>خطأ عند تنزيل wallet.dat</translation> </message> <message> <location line="+31"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-63"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Unable to bind to %s on this computer. Coinaaa is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Loading wallet...</source> <translation>تحميل المحفظه</translation> </message> <message> <location line="-57"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Rescanning...</source> <translation>إعادة مسح</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>انتهاء التحميل</translation> </message> <message> <location line="+86"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Error</source> <translation>خطأ</translation> </message> <message> <location line="-36"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<translation>خيارات ...</translation> </message> <message> <location line="+13"/>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::io; pub struct JiaeHomework { index: usize, value: i32, } fn stdinln_i32() -> i32 { // 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다. let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin."); buffer.trim().parse::<i32>().unwrap() } fn stdinln_vec_i32() -> Vec<i32> { // 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vector로 리턴합니다. let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("Failed to read line"); let ret: Vec<i32> = buffer.split(" ") .map(|x| x.trim().parse().expect("Unexpected Integer Pattern")) .collect(); ret } /* 이번 문제는 Method 스타일로 풀어봅시다.! https://doc.rust-lang.org/rust-by-example/fn/methods.html 이번 문제는 Rust-Ownership 문제가 야기될 수 있습니다. 한번 읽어보세요. https://rinthel.github.io/rust-lang-book-ko/ch04-02-references-and-borrowing.html */ impl JiaeHomework { fn new() -> JiaeHomework { JiaeHomework{index:0, value:0} } fn solve(&mut self, source: &Vec<i32>, nr_items: usize) { // solve를 완성해주세요! let mut sum :i32 = 0; // get Sum of source vector. for i in 0..nr_items{ sum += source[i]; } let avg = sum/nr_items as i32; // Rust 2018에서는 (source[0]-avg).abs() 를 해도 되나.<|fim▁hole|> let mut near_gap = i32::abs(source[0]-avg); for i in 1..nr_items { let current_gap = i32::abs(source[i]-avg); if current_gap < near_gap { self.index = i; near_gap = current_gap; } } self.value = source[self.index]; // End of solve } fn print(&self) { println!("{} {}", self.index + 1, self.value); } } fn main(){ let nr_case = stdinln_i32() as usize; let inputs = stdinln_vec_i32(); // JiaeHomework.solve(...) 를 완성해주세요! let mut problem = JiaeHomework::new(); problem.solve(&inputs, nr_case); problem.print(); }<|fim▁end|>
// 현재 구름은 rustc 2017년대 버젼을 쓰고있다. 따라서 이와같이 해결한다. // i32::abs(...)
<|file_name|>server.go<|end_file_name|><|fim▁begin|><|fim▁hole|>import ( log "github.com/sirupsen/logrus" "github.com/catpie/musdk-go" "strconv" "strings" ) func handleLog(l string) error { log.Info("get log: ", l) arr := strings.Split(l, "\n") log.Infof("len: %d ", len(arr)) // var logs []musdk.UserTrafficLog for _, v := range arr { s := strings.Split(v, " ") log.Debugf("processing %s len: %d", v, len(s)) if len(s) < 8 { continue } var sArr []string for _, value := range s { //log.Debugf("key: %d value %s",key,value) if len(value) != 0 { sArr = append(sArr, value) } } log.Debugf("user %s traffic %s", sArr[7], sArr[4]) u, err := strconv.Atoi(sArr[7]) if err != nil { log.Error("error on get user id ", err) continue } d, err := strconv.Atoi(sArr[4]) if err != nil { log.Error("error on get traffic ", err) } l := musdk.UserTrafficLog{ UserId: int64(u), D: int64(d), } //logs = append(logs, l) Queue.Append(l) } //log.Info("start update traffic to api", logs) //err := client.UpdateTraffic(logs) //if err != nil { // log.Errorf("error on update traffic %s", err.Error()) //} return nil }<|fim▁end|>
package main
<|file_name|>issue-1701.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum pattern { tabby, tortoiseshell, calico } enum breed { beagle, rottweiler, pug } type name = String; enum ear_kind { lop, upright } enum animal { cat(pattern), dog(breed), rabbit(name, ear_kind), tiger } fn noise(a: animal) -> Option<String> { match a { animal::cat(..) => { Some("meow".to_string()) } animal::dog(..) => { Some("woof".to_string()) }<|fim▁hole|> pub fn main() { assert_eq!(noise(animal::cat(pattern::tabby)), Some("meow".to_string())); assert_eq!(noise(animal::dog(breed::pug)), Some("woof".to_string())); assert_eq!(noise(animal::rabbit("Hilbert".to_string(), ear_kind::upright)), None); assert_eq!(noise(animal::tiger), Some("roar".to_string())); }<|fim▁end|>
animal::rabbit(..) => { None } animal::tiger(..) => { Some("roar".to_string()) } } }
<|file_name|>xrwebglsubimage.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMethods; use crate::dom::bindings::root::Dom; use crate::dom::bindings::root::DomRoot; use crate::dom::webgltexture::WebGLTexture; use crate::dom::xrsubimage::XRSubImage; use dom_struct::dom_struct; #[dom_struct] pub struct XRWebGLSubImage { xr_sub_image: XRSubImage, color_texture: Dom<WebGLTexture>, depth_stencil_texture: Option<Dom<WebGLTexture>>, image_index: Option<u32>, } impl XRWebGLSubImageMethods for XRWebGLSubImage { /// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-colortexture fn ColorTexture(&self) -> DomRoot<WebGLTexture> { DomRoot::from_ref(&self.color_texture) } /// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-depthstenciltexture fn GetDepthStencilTexture(&self) -> Option<DomRoot<WebGLTexture>> { self.depth_stencil_texture.as_deref().map(DomRoot::from_ref) }<|fim▁hole|> /// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex fn GetImageIndex(&self) -> Option<u32> { self.image_index } }<|fim▁end|>
<|file_name|>ja.js<|end_file_name|><|fim▁begin|>tutao.provide('tutao.tutanota.ctrl.lang.ja'); tutao.tutanota.ctrl.lang.ja.writing_direction = "ltr"; tutao.tutanota.ctrl.lang.ja.id = "ja"; tutao.tutanota.ctrl.lang.ja.keys = { "account_label": "ユーザー", "activate_action": "有効にする", "address_label": "アドレス", "add_action": "追加する", "adminEmailSettings_action": "メール", "adminMessages_action": "表示されたメッセージ", "adminUserList_action": "ユーザー管理", "afterRegistration_msg": "アカウントが作成されました。ログインして楽しみましょう。", "archive_action": "アーカイブ", "backTologin_action": "ログインに戻る", "back_action": "前", "bcc_label": "Bcc", "birthday_alt": "生年月日", "cancel_action": "キャンセルする", "captchaDisplay_label": "キャプチャ", "changeNotificationMailLanguage_msg": "通知メールの言語:", "comment_label": "コメント", "community_label": "コミュニティ", "company_label": "会社", "company_placeholder": "会社", "confidentialMail_alt": "このメールはエンドツーエンドで暗号化され、送信されました。", "confidential_action": "親展", "contactImage_alt": "画像", "contacts_alt": "連絡先", "contacts_label": "連絡先", "createAccountInvalidCaptcha_msg": "申し訳ありませんが、回答が間違っています。もう一度やり直して下さい。", "createAccountRunning_msg": "アカウントを作成しています...", "custom_label": "カスタム", "db_label": "データベース", "defaultExternalDelivery_label": "デフォルトの送信設定", "defaultSenderMailAddress_label": "デフォルトの送信元", "deleteAccountWait_msg": "アカウントを削除しています...", "deleteContact_msg": "この連絡先を本当に削除しますか?", "deleteMail_msg": "新規メールを送信せずに削除しますか?", "deleteTrash_action": "すべて削除", "delete_action": "削除", "dev_label": "開発者", "discardContactChangesFor_msg": "{1}の連絡先の変更を破棄しますか?", "editFolder_action": "編集", "editUser_label": "ユーザーを編集する", "email_label": "Eメール", "enterPresharedPassword_msg": "送信者と共有しているパスワードを入力して下さい。", "errorNotification_label": "エラー通知", "export_action": "エクスポートする", "externalNotificationMailBody3_msg": "暗号化メールを表示する", "facebook_label": "Facebook", "fax_label": "ファックス", "finished_msg": "完了しました。", "folderNameCreate_label": "新しいフォルダーを作成する", "folderNameNeutral_msg": "フォルダ名を入力して下さい。", "folderTitle_label": "フォルダ", "goodPassphrase_action": "良いパスワードにするには?", "help_label": "ヘルプを見る:", "importCsvInvalid_msg": "", "importCsv_label": "CSVデータをインポートする", "import_action": "インポートする", "invalidLink_msg": "申し訳ありません、このリンクは無効です。", "invalidPassword_msg": "無効なパスワードです。もう一度確認して下さい。", "invalidRecipients_msg": "受信者欄の無効なメールアドレスを修正して下さい。", "invitationMailSubject_msg": "Tutanotaで私たちのプライバシーを取り戻そう!", "invite_alt": "招待", "invite_label": "招待", "languageAlbanian_label": "アルバニア語", "languageArabic_label": "アラビア語", "languageBulgarian_label": "ブルガリア語", "languageChineseSimplified_label": "中国語, 簡体字", "languageCroatian_label": "クロアチア語", "languageDutch_label": "オランダ語", "languageEnglish_label": "英語", "languageFinnish_label": "フィンランド語", "languageFrench_label": "フランス語", "languageGerman_label": "ドイツ語", "languageGreek_label": "ギリシャ語", "languageItalian_label": "イタリア語", "languageLithuanian_label": "リトアニア語", "languageMacedonian_label": "マケドニア語", "languagePolish_label": "ポーランド語", "languagePortugeseBrazil_label": "ポルトガル語, ブラジル", "languagePortugesePortugal_label": "ポルトガル語, ポルトガル", "languageRomanian_label": "ルーマニア語", "languageRussian_label": "ロシア語", "languageSerbian_label": "セルビア語", "languageSpanish_label": "スペイン語", "languageTurkish_label": "トルコ語", "lastName_placeholder": "姓", "linkedin_label": "LinkedIn", "loading_msg": "読み込み中", "loginNameInfoAdmin_msg": "任意: ユーザー名", "login_action": "ログイン", "login_msg": "ログインする。", "logout_alt": "ログアウト", "logout_label": "ログアウト", "logs_label": "ログ", "mailAddressAliases_label": "メールエイリアス", "mailAddressNA_msg": "このメールアドレスは利用できません。", "meDativ_label": "自分", "meNominative_label": "自分", "mobileNumberValidFormat_msg": "フォーマット OK.", "monthNames_label": [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], "move_action": "移動する", "newMails_msg": "Tutanotaの新着メールを受信しました。", "noConnection_msg": "あなたはオフラインです。Tutanotaに接続できませんでした。", "noContact_msg": "連絡先が1つも選択されていません。", "notificationMailSignatureSubject_msg": "{1}からの機密メール", "notificationMailSignature_label": "サイン", "ok_action": "OK", "oldBrowser_msg": "申し訳ありませんが、あなたは古いブラウザをご利用中です。以下のいずれかのブラウザの最新バージョンにアップグレードして下さい:", "other_label": "その他", "password1InvalidUnsecure_msg": "このパスワードは安全性に問題があります。", "passwords_label": "パスワード", "passwordTransmission_label": "パスワードの送信", "passwordWrongInvalid_msg": "パスワードが間違っています。",<|fim▁hole|> "privacyLink_label": "プライバシーポリシー", "registrationSubHeadline2_msg": "登録情報を入力して下さい。(ステップ2/2)", "removeAddress_alt": "このアドレスを削除する", "removePhoneNumber_alt": "", "removeRecipient_alt": "受信者を削除する", "rename_action": "名前の変更", "replyAll_action": "全員に返信", "saved_msg": "保存が完了しました!", "savePassword_label": "保存", "save_action": "保存", "selectAddress_label": "Eメールアドレスを選択して下さい", "sendMail_alt": "このアドレス宛にメールを送る", "send_action": "送信する", "sentMails_alt": "送信済みメール", "sent_action": "送信完了", "settings_label": "設定", "showAddress_alt": "この住所をGoogleマップで表示する", "showAttachment_label": "添付を表示する", "showInAddressBook_alt": "連絡先を編集する", "storageCapacityNoLimit_label": "制限なし", "subject_label": "件名", "terms_label": "確認", "title_placeholder": "件名", "tooBigAttachment_msg": "次のファイルは全体サイズが25MBを超えるため添付できません:", "unsecureMailSendFailureSubject_msg": "メールを送信できませんでした", "unsupportedBrowser_msg": "申し訳ありませんが、ご利用のブラウザは対応していません。以下のいずれかのブラウザをご利用下さい。", "welcomeMailSubject_msg": "安心して下さい: あなたのデータのプライバシーは保たれています。", "work_label": "仕事", "xing_label": "XING" };<|fim▁end|>
"password_label": "パスワード", "presharedPasswordAndStrength_msg": "パスワードの強さ", "preSharedPasswordNeeded_label": "各外部受信者用の承認パスワードを入力して下さい。",
<|file_name|>group_tags.py<|end_file_name|><|fim▁begin|>from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, group, kwargs, asvar): self.view_name = view_name self.group = group self.kwargs = kwargs self.asvar = asvar def render(self, context): url = "" group = self.group.resolve(context) kwargs = {} for k, v in self.kwargs.items(): kwargs[smart_str(k, "ascii")] = v.resolve(context) if group: bridge = group.content_bridge try: url = bridge.reverse(self.view_name, group, kwargs=kwargs) except NoReverseMatch: if self.asvar is None: raise else: try: url = reverse(self.view_name, kwargs=kwargs) except NoReverseMatch: if self.asvar is None: raise if self.asvar: context[self.asvar] = url return "" else: return url class ContentObjectsNode(template.Node): def __init__(self, group_var, model_name_var, context_var): self.group_var = template.Variable(group_var) self.model_name_var = template.Variable(model_name_var) self.context_var = context_var def render(self, context): group = self.group_var.resolve(context) model_name = self.model_name_var.resolve(context) if isinstance(model_name, QuerySet): model = model_name else: app_name, model_name = model_name.split(".") model = get_model(app_name, model_name) context[self.context_var] = group.content_objects(model) return "" @register.tag def groupurl(parser, token): bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes at least two arguments" " (path to a view and a group)" % tag_name) view_name = bits[1] group = parser.compile_filter(bits[2]) args = [] kwargs = {} asvar = None if len(bits) > 3: bits = iter(bits[3:]) for bit in bits: if bit == "as": asvar = bits.next() break else: for arg in bit.split(","): if "=" in arg: k, v = arg.split("=", 1) k = k.strip() kwargs[k] = parser.compile_filter(v) elif arg: raise template.TemplateSyntaxError("'%s' does not support non-kwargs arguments." % tag_name) return GroupURLNode(view_name, group, kwargs, asvar) @register.tag def content_objects(parser, token): """ {% content_objects group "tasks.Task" as tasks %}<|fim▁hole|> """ bits = token.split_contents() if len(bits) != 5: raise template.TemplateSyntaxError("'%s' requires five arguments." % bits[0]) return ContentObjectsNode(bits[1], bits[2], bits[4])<|fim▁end|>
<|file_name|>timer.py<|end_file_name|><|fim▁begin|>import pile import matplotlib.pyplot as plt import time import random x,y = [],[] for i in range(0,10): p = 10 ** i print(i) start = time.time() pile.pile(p) final = time.time()<|fim▁hole|> delta = final - start x.append(p) y.append(delta) plt.plot(x,y) plt.ylabel("The time taken to compute the pile splitting of a pile os size n") print(y) plt.show() plt.savefig("data.jpg") def cutter(tsize,dsize): p = [tsize] soma = 0 size = 1 for i in range(dsize): if size == 0: break update = [] for n in p: if n == 1: soma += 0 else: a = random.randint(1,n-1) b = n - a soma += a*b update.append(a) update.append(b) p = list(update) size = len(p) print(update,soma) return(p,soma) print(cutter(30,99))<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethereum virtual machine. extern crate bit_set; extern crate ethcore_util as util; extern crate ethcore_bigint as bigint; extern crate parking_lot; extern crate heapsize; extern crate vm; extern crate keccak_hash as hash; extern crate memory_cache; #[macro_use] extern crate lazy_static; extern crate log; #[cfg(feature = "jit")] extern crate evmjit; #[cfg(test)] extern crate rustc_hex; pub mod evm; pub mod interpreter; #[macro_use] pub mod factory; mod vmtype; mod instructions; #[cfg(feature = "jit" )] mod jit; #[cfg(test)] mod tests; #[cfg(all(feature="benches", test))] mod benches; pub use vm::{ Schedule, CleanDustMode, EnvInfo, CallType, ActionParams, Ext, ContractCreateResult, MessageCallResult, CreateContractAddress,<|fim▁hole|>}; pub use self::evm::{Finalize, FinalizationResult, CostType}; pub use self::instructions::{InstructionInfo, INSTRUCTIONS, push_bytes}; pub use self::vmtype::VMType; pub use self::factory::Factory;<|fim▁end|>
GasLeft, ReturnData
<|file_name|>network.py<|end_file_name|><|fim▁begin|># This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c) 2015 Peter Sprygada, <[email protected]> # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import traceback import json from ansible.module_utils._text import to_text, to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback from ansible.module_utils.connection import Connection, ConnectionError from ansible.module_utils.network.common.netconf import NetconfConnection from ansible.module_utils.network.common.parsing import Cli from ansible.module_utils.six import iteritems NET_TRANSPORT_ARGS = dict( host=dict(required=True), port=dict(type='int'), username=dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), password=dict(no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD'])), ssh_keyfile=dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'), authorize=dict(default=False, fallback=(env_fallback, ['ANSIBLE_NET_AUTHORIZE']), type='bool'), auth_pass=dict(no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_AUTH_PASS'])), provider=dict(type='dict', no_log=True), transport=dict(choices=list()), timeout=dict(default=10, type='int') ) NET_CONNECTION_ARGS = dict() NET_CONNECTIONS = dict() def _transitional_argument_spec(): argument_spec = {} for key, value in iteritems(NET_TRANSPORT_ARGS): value['required'] = False argument_spec[key] = value return argument_spec def to_list(val): if isinstance(val, (list, tuple)): return list(val) elif val is not None: return [val] else: return list() class ModuleStub(object): def __init__(self, argument_spec, fail_json): self.params = dict() for key, value in argument_spec.items(): self.params[key] = value.get('default') self.fail_json = fail_json class NetworkError(Exception): def __init__(self, msg, **kwargs): super(NetworkError, self).__init__(msg) self.kwargs = kwargs class Config(object): def __init__(self, connection): self.connection = connection def __call__(self, commands, **kwargs): lines = to_list(commands) return self.connection.configure(lines, **kwargs) def load_config(self, commands, **kwargs): commands = to_list(commands) return self.connection.load_config(commands, **kwargs) def get_config(self, **kwargs): return self.connection.get_config(**kwargs) def save_config(self): return self.connection.save_config() class NetworkModule(AnsibleModule): def __init__(self, *args, **kwargs): connect_on_load = kwargs.pop('connect_on_load', True) argument_spec = NET_TRANSPORT_ARGS.copy() argument_spec['transport']['choices'] = NET_CONNECTIONS.keys() argument_spec.update(NET_CONNECTION_ARGS.copy()) if kwargs.get('argument_spec'): argument_spec.update(kwargs['argument_spec']) kwargs['argument_spec'] = argument_spec super(NetworkModule, self).__init__(*args, **kwargs) self.connection = None self._cli = None self._config = None try: transport = self.params['transport'] or '__default__' cls = NET_CONNECTIONS[transport] self.connection = cls() except KeyError: self.fail_json(msg='Unknown transport or no default transport specified') except (TypeError, NetworkError) as exc: self.fail_json(msg=to_native(exc), exception=traceback.format_exc()) if connect_on_load: self.connect() @property def cli(self): if not self.connected: self.connect() if self._cli: return self._cli self._cli = Cli(self.connection) return self._cli @property def config(self): if not self.connected: self.connect() if self._config: return self._config self._config = Config(self.connection) return self._config @property def connected(self): return self.connection._connected def _load_params(self): super(NetworkModule, self)._load_params() provider = self.params.get('provider') or dict() for key, value in provider.items(): for args in [NET_TRANSPORT_ARGS, NET_CONNECTION_ARGS]: if key in args:<|fim▁hole|> if self.params.get(key) is None and value is not None: self.params[key] = value def connect(self): try: if not self.connected: self.connection.connect(self.params) if self.params['authorize']: self.connection.authorize(self.params) self.log('connected to %s:%s using %s' % (self.params['host'], self.params['port'], self.params['transport'])) except NetworkError as exc: self.fail_json(msg=to_native(exc), exception=traceback.format_exc()) def disconnect(self): try: if self.connected: self.connection.disconnect() self.log('disconnected from %s' % self.params['host']) except NetworkError as exc: self.fail_json(msg=to_native(exc), exception=traceback.format_exc()) def register_transport(transport, default=False): def register(cls): NET_CONNECTIONS[transport] = cls if default: NET_CONNECTIONS['__default__'] = cls return cls return register def add_argument(key, value): NET_CONNECTION_ARGS[key] = value def get_resource_connection(module): if hasattr(module, '_connection'): return module._connection capabilities = get_capabilities(module) network_api = capabilities.get('network_api') if network_api == 'cliconf': module._connection = Connection(module._socket_path) elif network_api == 'netconf': module._connection = NetconfConnection(module._socket_path) else: module.fail_json(msg='Invalid connection type {0!s}'.format(network_api)) return module._connection def get_capabilities(module): if hasattr(module, 'capabilities'): return module._capabilities try: capabilities = Connection(module._socket_path).get_capabilities() except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) module._capabilities = json.loads(capabilities) return module._capabilities<|fim▁end|>
<|file_name|>orderline.cpp<|end_file_name|><|fim▁begin|>#include <climits> #include <cstdlib> #include <cstring> #include "orderline.h" #include "../src/schema/conversion.h" using namespace std; void OrderlineStore::add(string elements[10]) { add_instance(atoi(elements[0].c_str()), atoi(elements[1].c_str()), atoi(elements[2].c_str()), atoi(elements[3].c_str()), atoi(elements[4].c_str()), atoi(elements[5].c_str()), db_stod(elements[6]), db_stol(elements[7]), db_stol(elements[8]), elements[9]); } void OrderlineStore::add_instance(int32_t ol_o_id, int32_t ol_d_id, int32_t ol_w_id, int32_t ol_number, int32_t ol_i_id, int32_t ol_supply_w_id, uint64_t ol_delivery_d, int64_t ol_quantity, int64_t ol_amount, std::string ol_dist_info) { this->ol_o_id.push_back(ol_o_id); this->ol_d_id.push_back(ol_d_id); this->ol_w_id.push_back(ol_w_id); this->ol_number.push_back(ol_number); this->ol_i_id.push_back(ol_i_id); this->ol_supply_w_id.push_back(ol_supply_w_id); this->ol_delivery_d.push_back(ol_delivery_d); this->ol_quantity.push_back(ol_quantity); this->ol_amount.push_back(ol_amount); this->ol_dist_info.push_back(ol_dist_info); pkIndex[std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid])] = tid; tid++; } void OrderlineStore::remove(uint64_t tid) { auto pkKey = std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid]); auto pkIt = pkIndex.find(pkKey); pkIndex.erase(pkIt); // We want to move the last item to the deleted item's position // We have one item less now, so decrease TID for next add_instance uint64_t tidToSwap = --this->tid; if (tid != tidToSwap) { // Move data from last item to deleted item's position this->ol_o_id[tid] = this->ol_o_id[tidToSwap]; this->ol_d_id[tid] = this->ol_d_id[tidToSwap]; this->ol_w_id[tid] = this->ol_w_id[tidToSwap]; this->ol_number[tid] = this->ol_number[tidToSwap]; this->ol_i_id[tid] = this->ol_i_id[tidToSwap]; this->ol_supply_w_id[tid] = this->ol_supply_w_id[tidToSwap]; this->ol_delivery_d[tid] = this->ol_delivery_d[tidToSwap]; this->ol_quantity[tid] = this->ol_quantity[tidToSwap]; this->ol_amount[tid] = this->ol_amount[tidToSwap]; this->ol_dist_info.set(tid, this->ol_dist_info[tidToSwap]); // Set swapped item's TID in index pkIndex[std::make_tuple(this->ol_w_id[tid], this->ol_d_id[tid], this->ol_o_id[tid], this->ol_number[tid])] = tid; } // Delete the data this->ol_o_id.pop_back(); this->ol_d_id.pop_back(); this->ol_w_id.pop_back(); this->ol_number.pop_back(); this->ol_i_id.pop_back(); this->ol_supply_w_id.pop_back(); this->ol_delivery_d.pop_back(); this->ol_quantity.pop_back(); this->ol_amount.pop_back(); this->ol_dist_info.pop_back(); } <|fim▁hole|>} std::pair<OrderlineStore::pkIndexType::iterator, OrderlineStore::pkIndexType::iterator> OrderlineStore::get(int32_t ol_w_id, int32_t ol_d_id, int32_t ol_o_id) { return std::make_pair( pkIndex.lower_bound(std::make_tuple(ol_w_id, ol_d_id, ol_o_id, 0)), pkIndex.upper_bound(std::make_tuple(ol_w_id, ol_d_id, ol_o_id, INT_MAX))); }<|fim▁end|>
uint64_t OrderlineStore::get(int32_t ol_w_id, int32_t ol_d_id, int32_t ol_o_id, int32_t ol_number) { return pkIndex[std::make_tuple(ol_w_id, ol_d_id, ol_o_id, ol_number)];
<|file_name|>gcc.py<|end_file_name|><|fim▁begin|>"""SCons.Tool.gcc Tool-specific initialization for gcc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2017 The SCons Foundation # # 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. # __revision__ = "src/engine/SCons/Tool/gcc.py 74b2c53bc42290e911b334a6b44f187da698a668 2017/11/14 13:16:53 bdbaddog" from . import cc import os import re import subprocess import SCons.Util compilers = ['gcc', 'cc'] def generate(env): """Add Builders and construction variables for gcc to an Environment.""" if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] cc.generate(env) if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version version = detect_version(env, env['CC']) if version: env['CCVERSION'] = version def exists(env): # is executable, and is a GNU compiler (or accepts '--version' at least) return detect_version(env, env.Detect(env.get('CC', compilers))) def detect_version(env, cc): """Return the version of the GNU compiler, or None if it is not a GNU compiler.""" cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # version = line line = SCons.Util.to_str(pipe.stdout.readline()) match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: version = match.group(0) # Non-GNU compiler's output (like AIX xlc's) may exceed the stdout buffer: # So continue with reading to let the child process actually terminate. while SCons.Util.to_str(pipe.stdout.readline()):<|fim▁hole|> pass ret = pipe.wait() if ret != 0: return None return version # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:<|fim▁end|>
<|file_name|>IjkMediaFormat.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2015 Bilibili * Copyright (C) 2015 Zhang Rui <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tv.danmaku.ijk.media.player.misc; import android.annotation.TargetApi; import android.os.Build; import android.text.TextUtils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import tv.danmaku.ijk.media.player.IjkMediaMeta; public class IjkMediaFormat implements IMediaFormat { // Common public static final String KEY_IJK_CODEC_LONG_NAME_UI = "ijk-codec-long-name-ui"; public static final String KEY_IJK_CODEC_NAME_UI = "ijk-codec-name-ui"; public static final String KEY_IJK_BIT_RATE_UI = "ijk-bit-rate-ui"; // Video public static final String KEY_IJK_CODEC_PROFILE_LEVEL_UI = "ijk-profile-level-ui"; public static final String KEY_IJK_CODEC_PIXEL_FORMAT_UI = "ijk-pixel-format-ui"; public static final String KEY_IJK_RESOLUTION_UI = "ijk-resolution-ui"; public static final String KEY_IJK_FRAME_RATE_UI = "ijk-frame-rate-ui"; // Audio public static final String KEY_IJK_SAMPLE_RATE_UI = "ijk-sample-rate-ui"; public static final String KEY_IJK_CHANNEL_UI = "ijk-channel-ui"; // Codec public static final String CODEC_NAME_H264 = "h264"; public final IjkMediaMeta.IjkStreamMeta mMediaFormat; public IjkMediaFormat(IjkMediaMeta.IjkStreamMeta streamMeta) { mMediaFormat = streamMeta; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public int getInteger(String name) { if (mMediaFormat == null) return 0; return mMediaFormat.getInt(name); } @Override public String getString(String name) { if (mMediaFormat == null) return null; if (sFormatterMap.containsKey(name)) { Formatter formatter = sFormatterMap.get(name); return formatter.format(this); } return mMediaFormat.getString(name); } //------------------------- // Formatter<|fim▁hole|> //------------------------- private static abstract class Formatter { public String format(IjkMediaFormat mediaFormat) { String value = doFormat(mediaFormat); if (TextUtils.isEmpty(value)) return getDefaultString(); return value; } protected abstract String doFormat(IjkMediaFormat mediaFormat); @SuppressWarnings("SameReturnValue") protected String getDefaultString() { return "N/A"; } } private static final Map<String, Formatter> sFormatterMap = new HashMap<String, Formatter>(); { sFormatterMap.put(KEY_IJK_CODEC_LONG_NAME_UI, new Formatter() { @Override public String doFormat(IjkMediaFormat mediaFormat) { return mMediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_LONG_NAME); } }); sFormatterMap.put(KEY_IJK_CODEC_NAME_UI, new Formatter() { @Override public String doFormat(IjkMediaFormat mediaFormat) { return mMediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_NAME); } }); sFormatterMap.put(KEY_IJK_BIT_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int bitRate = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_BITRATE); if (bitRate <= 0) { return null; } else if (bitRate < 1000) { return String.format(Locale.US, "%d bit/s", bitRate); } else { return String.format(Locale.US, "%d kb/s", bitRate / 1000); } } }); sFormatterMap.put(KEY_IJK_CODEC_PROFILE_LEVEL_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int profileIndex = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CODEC_PROFILE_ID); String profile; switch (profileIndex) { case IjkMediaMeta.FF_PROFILE_H264_BASELINE: profile = "Baseline"; break; case IjkMediaMeta.FF_PROFILE_H264_CONSTRAINED_BASELINE: profile = "Constrained Baseline"; break; case IjkMediaMeta.FF_PROFILE_H264_MAIN: profile = "Main"; break; case IjkMediaMeta.FF_PROFILE_H264_EXTENDED: profile = "Extended"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH: profile = "High"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_10: profile = "High 10"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_10_INTRA: profile = "High 10 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_422: profile = "High 4:2:2"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_422_INTRA: profile = "High 4:2:2 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444: profile = "High 4:4:4"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444_PREDICTIVE: profile = "High 4:4:4 Predictive"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444_INTRA: profile = "High 4:4:4 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_CAVLC_444: profile = "CAVLC 4:4:4"; break; default: return null; } StringBuilder sb = new StringBuilder(); sb.append(profile); String codecName = mediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_NAME); if (!TextUtils.isEmpty(codecName) && codecName.equalsIgnoreCase(CODEC_NAME_H264)) { int level = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CODEC_LEVEL); if (level < 10) return sb.toString(); sb.append(" Profile Level "); sb.append((level / 10) % 10); if ((level % 10) != 0) { sb.append("."); sb.append(level % 10); } } return sb.toString(); } }); sFormatterMap.put(KEY_IJK_CODEC_PIXEL_FORMAT_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { return mediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_PIXEL_FORMAT); } }); sFormatterMap.put(KEY_IJK_RESOLUTION_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int width = mediaFormat.getInteger(KEY_WIDTH); int height = mediaFormat.getInteger(KEY_HEIGHT); int sarNum = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAR_NUM); int sarDen = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAR_DEN); if (width <= 0 || height <= 0) { return null; } else if (sarNum <= 0 || sarDen <= 0) { return String.format(Locale.US, "%d x %d", width, height); } else { return String.format(Locale.US, "%d x %d [SAR %d:%d]", width, height, sarNum, sarDen); } } }); sFormatterMap.put(KEY_IJK_FRAME_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int fpsNum = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_FPS_NUM); int fpsDen = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_FPS_DEN); if (fpsNum <= 0 || fpsDen <= 0) { return null; } else { return String.valueOf(((float) (fpsNum)) / fpsDen); } } }); sFormatterMap.put(KEY_IJK_SAMPLE_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int sampleRate = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAMPLE_RATE); if (sampleRate <= 0) { return null; } else { return String.format(Locale.US, "%d Hz", sampleRate); } } }); sFormatterMap.put(KEY_IJK_CHANNEL_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int channelLayout = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CHANNEL_LAYOUT); if (channelLayout <= 0) { return null; } else { if (channelLayout == IjkMediaMeta.AV_CH_LAYOUT_MONO) { return "mono"; } else if (channelLayout == IjkMediaMeta.AV_CH_LAYOUT_STEREO) { return "stereo"; } else { return String.format(Locale.US, "%x", channelLayout); } } } }); } }<|fim▁end|>
<|file_name|>checkout_mode_tag.py<|end_file_name|><|fim▁begin|>from classytags.helpers import InclusionTag from django import template<|fim▁hole|>register = template.Library() class Banner(InclusionTag): """ Displays a checkout mode banner. """ template = 'sagepay/checkout_mode_banner.html' def render_tag(self, context, **kwargs): template = self.get_template(context, **kwargs) if settings.SAGEPAY_MODE == "Live": return '' data = self.get_context(context, **kwargs) return render_to_string(template, data) register.tag(Banner)<|fim▁end|>
from django.conf import settings from django.template.loader import render_to_string