file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
test_auto_MaskTool.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..utils import MaskTool def test_MaskTool_inputs(): input_map = dict(args=dict(argstr='%s', ), count=dict(argstr='-count', position=2, ), datum=dict(argstr='-datum %s', ), dilate_inputs=dict...
def test_MaskTool_outputs(): output_map = dict(out_file=dict(), ) outputs = MaskTool.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
yield assert_equal, getattr(inputs.traits()[key], metakey), value
conditional_block
test_auto_MaskTool.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..utils import MaskTool def test_MaskTool_inputs(): input_map = dict(args=dict(argstr='%s', ), count=dict(argstr='-count', position=2, ), datum=dict(argstr='-datum %s', ), dilate_inputs=dict...
(): output_map = dict(out_file=dict(), ) outputs = MaskTool.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
test_MaskTool_outputs
identifier_name
test_auto_MaskTool.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..utils import MaskTool def test_MaskTool_inputs(): input_map = dict(args=dict(argstr='%s', ), count=dict(argstr='-count', position=2, ), datum=dict(argstr='-datum %s', ), dilate_inputs=dict...
output_map = dict(out_file=dict(), ) outputs = MaskTool.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
identifier_body
huffman.py
různě dlouhé řádky textu, # text obsahuje pouze písmena abecedy (malá a velká), a číslice. # # Předpokládejte rozumně dlouhé řádky (např. max. 1000 znaků na řádku). # # Program načte vstupní soubor, spočítá četnost jednotlivých znaků a vypočte # algoritmem Huffmanova kódování jejich komprimovaný obraz. # # Do výstupní...
Parametry: ---------- tree: dictionary Slovník reprezentující strom, který se má projít prefix: string Řetězec obsahující kód cesty k tomuto node code: dictionary Slovník obsahujcí páry písmen/číslic (klíč) a jejich kódu. Vrací...
osloupností kódů
identifier_name
huffman.py
různě dlouhé řádky textu, # text obsahuje pouze písmena abecedy (malá a velká), a číslice. # # Předpokládejte rozumně dlouhé řádky (např. max. 1000 znaků na řádku). # # Program načte vstupní soubor, spočítá četnost jednotlivých znaků a vypočte # algoritmem Huffmanova kódování jejich komprimovaný obraz. # # Do výstupní...
Vystaví strom pro další zpracování huffmanovým kódováním. Parametry: ---------- probability: list Pole slovníků ve formátu: { "name": Znak číslice či písmena "count": Počet výskytů v souboru } Pole musí být seřazeno o...
= next( (n for n in characters if n["name"] == char), None ) # Pokud jde o první výskyt tohoto znaku if char_data == None: # Vytvoří jeho reprezentaci a vloží jí na seznam char_data = {"name": char, "count": 0 ...
conditional_block
huffman.py
ůzně dlouhé řádky textu, # text obsahuje pouze písmena abecedy (malá a velká), a číslice. # # Předpokládejte rozumně dlouhé řádky (např. max. 1000 znaků na řádku). # # Program načte vstupní soubor, spočítá četnost jednotlivých znaků a vypočte # algoritmem Huffmanova kódování jejich komprimovaný obraz. # # Do výstupního...
# Nechci upravovat originální parametr # Jen pro sichr, možná je to tu navíc :( tree = copy.deepcopy( probability ) # Dokud nezbývá jen jeden parametr while len( tree ) > 1: # Vezme dva vrcholy s nejmenší hodností (nejmenší count) # Pole je seřazeno od nejmenších po největší, proto...
slice či písmena "count": Počet výskytů v souboru } Pole musí být seřazeno od nejmenšího po nejvyšší výskyt. Vrací: ------ dictionary Slovník ve formátu: { "name": Znak/číslo (pokud jde o počítaný znak) nebo prázdný ...
identifier_body
huffman.py
různě dlouhé řádky textu, # text obsahuje pouze písmena abecedy (malá a velká), a číslice. # # Předpokládejte rozumně dlouhé řádky (např. max. 1000 znaků na řádku). # # Program načte vstupní soubor, spočítá četnost jednotlivých znaků a vypočte # algoritmem Huffmanova kódování jejich komprimovaný obraz. # # Do výstupní...
# Jen pro sichr, možná je to tu navíc :( tree = copy.deepcopy( probability ) # Dokud nezbývá jen jeden parametr while len( tree ) > 1: # Vezme dva vrcholy s nejmenší hodností (nejmenší count) # Pole je seřazeno od nejmenších po největší, proto stačí pop right = tree.pop(0) # Vp...
""" # Nechci upravovat originální parametr
random_line_split
verifytree.py
: continue raise IOError(paths) def testopia_create_run(plan): '''Create a run of the given test plan. Returns the run ID.''' run_id = 49 # STUB actually create the run print "Testopia: created run %i of plan %i" % (run_id,plan) return run_id def testopia_report(run,case,result): p...
if checkfileurl(pkg): print " verifying %s checksum" % pkg else: print " verifying %s checksum FAILED" % pkg packages_ok = False
conditional_block
verifytree.py
.misc import getCacheDir, checksum import urlparse from yum import Errors from optparse import OptionParser import ConfigParser # Subclass ConfigParser so that the options don't get lowercased. This is # important given that they are path names. class LocalConfigParser(ConfigParser.ConfigParser): """A subclass of...
if type(case) == str: case = case_numbers[case] # STUB actually do the reporting def checkfileurl(pkg): pkg_path = pkg.remote_url pkg_path = pkg_path.replace('file://', '') (csum_type, csum) = pkg.returnIdSum() try: filesum = checksum(csum_type, pkg_path) except Errors....
def testopia_report(run,case,result): print " testopia: reporting %s for case %s in run %i" % (result, str(case),run)
random_line_split
verifytree.py
yum.misc import getCacheDir, checksum import urlparse from yum import Errors from optparse import OptionParser import ConfigParser # Subclass ConfigParser so that the options don't get lowercased. This is # important given that they are path names. class LocalConfigParser(ConfigParser.ConfigParser): """A subclas...
fnpath = os.path.normpath(fnpath) csuminfo = cp.get('checksums', opt).split(':') if len(csuminfo) < 2: print " checksum information doesn't make any sense for %s." % opt result = BAD_IMAGES continue if not os.path.exists(fnpath): print " ...
result = 0 cp = LocalConfigParser() try: cp.read(treeinfo) except ConfigParser.MissingSectionHeaderError: # Generally this means we failed to access the file print " could not find sections in treeinfo file %s" % treeinfo return BAD_IMAGES except ConfigParser.Error: ...
identifier_body
verifytree.py
.misc import getCacheDir, checksum import urlparse from yum import Errors from optparse import OptionParser import ConfigParser # Subclass ConfigParser so that the options don't get lowercased. This is # important given that they are path names. class LocalConfigParser(ConfigParser.ConfigParser): """A subclass of...
(self, optionstr): return optionstr #### # take a file path to a repo as an option, verify all the metadata vs repomd.xml # optionally go through packages and verify them vs the checksum in the primary # Error values BAD_REPOMD = 1 BAD_METADATA = 2 BAD_COMPS = 4 BAD_PACKAGES = 8 BAD_IMAGES = 16 # Testopia ca...
optionxform
identifier_name
zdict_gen.py
#!/usr/bin/python3.3 from __future__ import print_function import argparse import json ''' Zlib's implementation uses 262 bytes of overhead for pre-defined dictionary thus, the max zdict size is 32KB - 262B = 23506B ''' MAX_WINDOW_SIZE = 32506 # 32KB-262B, size of MAX_WBITS - zdict overhead MAX_LOOKAHEAD_BUFFER_SI...
# 2. add substring scores to superstring value and flag for # removal (set score to 0) for i, key_i in enumerate(sorted_keys): # highest scoring superstring should consume substring sorted_keys_by_score = sorted(sorted_keys[i+1:], key=lambda k: freq_d...
""" Creates a LZ77 dictionary (initial lookback window) from a dictionary of word: frequency Args: freq_dict (dict(str)): A dictionary mapping word to frequency size_b (int): output size of frequency dictionary in B Returns: str: A LZ77 dictionary of size_b scored on len...
identifier_body
zdict_gen.py
#!/usr/bin/python3.3 from __future__ import print_function import argparse import json ''' Zlib's implementation uses 262 bytes of overhead for pre-defined dictionary thus, the max zdict size is 32KB - 262B = 23506B ''' MAX_WINDOW_SIZE = 32506 # 32KB-262B, size of MAX_WBITS - zdict overhead MAX_LOOKAHEAD_BUFFER_SI...
# 3. Remove substring items (has score 0) freq_dict = {k: v for k, v in freq_dict.items() if v > 0} """ Create LZ77 dictionary string """ # 1. Join keys (word) on score in ascending) order # According to zlib documentation, most common substrings should be placed # at the end of the pre-defin...
sorted_keys_by_score = sorted(sorted_keys[i+1:], key=lambda k: freq_dict[k], reverse=True) for j, key_j in enumerate(sorted_keys_by_score): if key_i in key_j: freq_dict[key_j] += freq_dict[key_i] ...
conditional_block
zdict_gen.py
#!/usr/bin/python3.3 from __future__ import print_function import argparse import json ''' Zlib's implementation uses 262 bytes of overhead for pre-defined dictionary thus, the max zdict size is 32KB - 262B = 23506B ''' MAX_WINDOW_SIZE = 32506 # 32KB-262B, size of MAX_WBITS - zdict overhead MAX_LOOKAHEAD_BUFFER_SI...
(freq_dict, size_b): """ Creates a LZ77 dictionary (initial lookback window) from a dictionary of word: frequency Args: freq_dict (dict(str)): A dictionary mapping word to frequency size_b (int): output size of frequency dictionary in B Returns: str: A LZ77 dictionar...
genDictFromFreq
identifier_name
zdict_gen.py
#!/usr/bin/python3.3 from __future__ import print_function import argparse import json ''' Zlib's implementation uses 262 bytes of overhead for pre-defined dictionary thus, the max zdict size is 32KB - 262B = 23506B ''' MAX_WINDOW_SIZE = 32506 # 32KB-262B, size of MAX_WBITS - zdict overhead
''' TODO Implement a more optimal shortest common superstring solution. This would allow more relevant substrings to fit within the pre-defined dictionary window. In order to generalize it for compression against larger data objects the solution would have to account for more commonly occuring substrings to be placed ...
MAX_LOOKAHEAD_BUFFER_SIZE = 258 # Maximum Match Length in zlib BATCHING_FACTOR = 3 # Number of times of cores to use as batching size DEFAULT_ZDICT_SIZE = 32506 # Length of predefined dictionary to generate
random_line_split
index.d.ts
// Type definitions for use-global-hook 0.1 // Project: https://github.com/andregardi/use-global-hook#readme // Definitions by: James Hong <https://github.com/ojameso> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.6 import Immer from 'immer'; // Use an interface so that d...
export interface Options<S, A> { Immer?: IProduce | undefined; initializer?: InitializerFunction<S, A> | undefined; } type UseGlobal<S, A> = (() => [S, A]) & (<NS>(stateFunc: (state: S) => NS) => [NS, A]) & (<NS, NA>(stateFunc: (state: S) => NS, actionsFunc: (state: A) => NA) => [NS, NA]) & (<NA>(...
export type InitializerFunction<S, A> = (store: Store<S, A>) => void;
random_line_split
plugin_manager.py
import os import sys from copy import copy from watchdog.events import RegexMatchingEventHandler if sys.platform == "darwin": from watchdog.observers.polling import PollingObserver as Observer else: from watchdog.observers import Observer from microproxy.log import ProxyLogger logger = ProxyLogger.get_logger(...
sys.path.pop() logger.info("Load Plugin : {0}".format(self.plugin_name)) def _reload_plugin(self): logger.info("Reload Plugin : {0}".format(self.plugin_name)) self._load_plugin() def __getattr__(self, attr): if attr not in self.PLUGIN_METHODS: raise Attribu...
except Exception as e: logger.exception(e)
random_line_split
plugin_manager.py
import os import sys from copy import copy from watchdog.events import RegexMatchingEventHandler if sys.platform == "darwin": from watchdog.observers.polling import PollingObserver as Observer else: from watchdog.observers import Observer from microproxy.log import ProxyLogger logger = ProxyLogger.get_logger(...
try: with open(self.plugin_path) as fp: self.namespace = {"__file__": self.plugin_path} code = compile(fp.read(), self.plugin_path, "exec") exec (code, self.namespace, self.namespace) except Exception as e: logger.exception(e) ...
PLUGIN_METHODS = ["on_request", "on_response"] def __init__(self, plugin_path): self.plugin_path = os.path.abspath(plugin_path) self.plugin_name = os.path.basename(self.plugin_path) self.plugin_dir = os.path.dirname(self.plugin_path) self.namespace = None self._load_plugin()...
identifier_body
plugin_manager.py
import os import sys from copy import copy from watchdog.events import RegexMatchingEventHandler if sys.platform == "darwin": from watchdog.observers.polling import PollingObserver as Observer else: from watchdog.observers import Observer from microproxy.log import ProxyLogger logger = ProxyLogger.get_logger(...
current_context = copy(plugin_context) for plugin in self.plugins: try: new_context = plugin.on_response(current_context) current_context = copy(new_context) except AttributeError: logger.debug( "Plugin {0} doe...
return plugin_context
conditional_block
plugin_manager.py
import os import sys from copy import copy from watchdog.events import RegexMatchingEventHandler if sys.platform == "darwin": from watchdog.observers.polling import PollingObserver as Observer else: from watchdog.observers import Observer from microproxy.log import ProxyLogger logger = ProxyLogger.get_logger(...
(self): logger.info("Reload Plugin : {0}".format(self.plugin_name)) self._load_plugin() def __getattr__(self, attr): if attr not in self.PLUGIN_METHODS: raise AttributeError try: return self.namespace[attr] except KeyError: raise Attribute...
_reload_plugin
identifier_name
titles.rs
#![crate_name = "foo"] // @matches 'foo/index.html' '//h1' 'Crate foo' // @matches 'foo/foo_mod/index.html' '//h1' 'Module foo::foo_mod' pub mod foo_mod { pub struct __Thing {} } extern "C" { // @matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn' pub fn foo_ffn(); } // @matches 'foo/fn.foo_fn....
// @matches 'foo/primitive.bool.html' '//h1' 'Primitive Type bool' #[doc(primitive = "bool")] mod bool {} // @matches 'foo/static.FOO_STATIC.html' '//h1' 'Static foo::FOO_STATIC' pub static FOO_STATIC: FooStruct = FooStruct; extern "C" { // @matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static foo::FOO_FSTATIC' ...
random_line_split
titles.rs
#![crate_name = "foo"] // @matches 'foo/index.html' '//h1' 'Crate foo' // @matches 'foo/foo_mod/index.html' '//h1' 'Module foo::foo_mod' pub mod foo_mod { pub struct
{} } extern "C" { // @matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn' pub fn foo_ffn(); } // @matches 'foo/fn.foo_fn.html' '//h1' 'Function foo::foo_fn' pub fn foo_fn() {} // @matches 'foo/trait.FooTrait.html' '//h1' 'Trait foo::FooTrait' pub trait FooTrait {} // @matches 'foo/struct.FooStruct...
__Thing
identifier_name
findBarcode.py
, l=[], offset=0): l = [ (i[1], i[2]) for i in l ] print l for y in range( 0, self.height-1): output = [] for x in range( 5+offset, self.stride-1): if x > 115+offset: continue i = self.im[y][x] if (x,y) in l: output.append("B") elif i < 20: ...
( self, l, rev ): l.sort( key= lambda x: x[0], reverse=rev ) restart = False sizeOfArray = len(l)-1 for i in range (1, sizeOfArray): for j in range(i, sizeOfArray): if abs( l[i-1][1] - l[j][1] ) < 5: restart = True l[j] = False if restart==True: return se...
removeNeighbors
identifier_name
findBarcode.py
s was not found in filter.py" % f) return convolve( self.im, filt, reshape ) def findBarcode( self ): results = self.applyFilter("scaledFilter", reshape=False) list = [ (x[1], int(x[0] % self.stride), int(x[0] / self.stride)) for x in enumerate(results) if x[1] > 1000 ] list.sort(reverse=True)...
filterCutoff = 18000
random_line_split
findBarcode.py
# Ignore leading white space start=True level = barcode[pos+1] code.append(pos) continue if abs(level - c) > 1250 and abs(level-barcode[pos+1]) > 1250: if (trend<0 and (level-c)>0) or (trend>0 and (level-c)<0): # Trend is in the same direction we are going,...
log.info("No barcode found for %s.", prefix)
conditional_block
findBarcode.py
, l=[], offset=0): l = [ (i[1], i[2]) for i in l ] print l for y in range( 0, self.height-1): output = [] for x in range( 5+offset, self.stride-1): if x > 115+offset: continue i = self.im[y][x] if (x,y) in l: output.append("B") elif i < 20: ...
if trend > 0: trend=-1 else: trend=1 level = c if trend > 0: level = max(c, level) else: level = min(c, level) if len(code) >= 7
""" Return a single code from a code 128 barcode. """ code=[] start = False trend = 1 for pos, c in enumerate(barcode): if (pos+1) >= len(barcode): continue if not start: if c > int(10*250): # Ignore leading white space start=True level = barcode[...
identifier_body
mysql_query_model.ts
import { find, map } from 'lodash'; import { TemplateSrv } from '@grafana/runtime'; import { ScopedVars } from '@grafana/data'; export default class MySQLQueryModel { target: any; templateSrv: any; scopedVars: any; /** @ngInject */ constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars)...
() { let query = ''; const conditions = map(this.target.where, (tag, index) => { switch (tag.type) { case 'macro': return tag.name + '(' + this.target.timeColumn + ')'; break; case 'expression': return tag.params.join(' '); break; } }); ...
buildWhereClause
identifier_name
mysql_query_model.ts
import { find, map } from 'lodash'; import { TemplateSrv } from '@grafana/runtime'; import { ScopedVars } from '@grafana/data'; export default class MySQLQueryModel { target: any; templateSrv: any; scopedVars: any; /** @ngInject */ constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars)...
else { query = this.target.timeColumn; if (alias) { query += ' AS "time"'; } } return query; } buildMetricColumn() { if (this.hasMetricColumn()) { return this.target.metricColumn + ' AS metric'; } return ''; } buildValueColumns() { let query = ''; ...
{ let args; if (timeGroup.params.length > 1 && timeGroup.params[1] !== 'none') { args = timeGroup.params.join(','); } else { args = timeGroup.params[0]; } if (this.hasUnixEpochTimecolumn()) { macro = '$__unixEpochGroup'; } if (alias) { macro += '...
conditional_block
mysql_query_model.ts
import { find, map } from 'lodash'; import { TemplateSrv } from '@grafana/runtime'; import { ScopedVars } from '@grafana/data'; export default class MySQLQueryModel { target: any; templateSrv: any; scopedVars: any; /** @ngInject */ constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars)...
case 'macro': return tag.name + '(' + this.target.timeColumn + ')'; break; case 'expression': return tag.params.join(' '); break; } }); if (conditions.length > 0) { query = '\nWHERE\n ' + conditions.join(' AND\n '); } return query; ...
buildWhereClause() { let query = ''; const conditions = map(this.target.where, (tag, index) => { switch (tag.type) {
random_line_split
config.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {existsSync} from 'fs'; import {dirname, join} from 'path'; import {debug, error} from './console'; import {e...
(config: Partial<NgDevConfig>) { const errors: string[] = []; // Validate the github configuration. if (config.github === undefined) { errors.push(`Github repository not configured. Set the "github" option.`); } else { if (config.github.name === undefined) { errors.push(`"github.name" is not defin...
validateCommonConfig
identifier_name
config.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {existsSync} from 'fs'; import {dirname, join} from 'path'; import {debug, error} from './console'; import {e...
for (const err of errors) { error(` - ${err}`); } process.exit(1); } /** Gets the path of the directory for the repository base. */ export function getRepoBaseDir() { const baseRepoDir = exec(`git rev-parse --show-toplevel`); if (baseRepoDir.code) { throw Error( `Unable to find the path to t...
random_line_split
config.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {existsSync} from 'fs'; import {dirname, join} from 'path'; import {debug, error} from './console'; import {e...
{ // If the global config is not defined, load it from the file system. if (userConfig === null) { // The full path to the configuration file. const configPath = join(getRepoBaseDir(), USER_CONFIG_FILE_PATH); // Set the global config object. userConfig = readConfigFile(configPath, true); } // Re...
identifier_body
config.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {existsSync} from 'fs'; import {dirname, join} from 'path'; import {debug, error} from './console'; import {e...
try { return require(configPath); } catch (e) { if (returnEmptyObjectOnError) { debug(`Could not read configuration file at ${configPath}, returning empty object instead.`); debug(e); return {}; } error(`Could not read configuration file at ${configPath}.`); error(e); pro...
{ // Ensure the module target is set to `commonjs`. This is necessary because the // dev-infra tool runs in NodeJS which does not support ES modules by default. // Additionally, set the `dir` option to the directory that contains the configuration // file. This allows for custom compiler options (such a...
conditional_block
v1.rs
// 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 ...
{ #[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] pub fill: char, #[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] pub align: Alignment, #[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] pub flags: u32, #[cfg_attr(stage0, stable(feature = "rust1"...
FormatSpec
identifier_name
v1.rs
// 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 ...
/// Indication that contents should be right-aligned. #[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] Right, /// Indication that contents should be center-aligned. #[cfg_attr(stage0, stable(feature = "rust1", since = "1.0.0"))] Center, /// No alignment was requested. #[cf...
Left,
random_line_split
htmlformelement.rs
/* 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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFormElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFormEl...
{ pub htmlelement: HTMLElement } impl HTMLFormElementDerived for EventTarget { fn is_htmlformelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId)) } } impl HTMLFormElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> ...
HTMLFormElement
identifier_name
htmlformelement.rs
/* 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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFormElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFormEl...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFormElement> { let element = HTMLFormElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLFormElementBinding::Wrap) } } impl Reflectable for HTMLF...
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document) } }
random_line_split
htmlformelement.rs
/* 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 http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFormElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFormEl...
} impl HTMLFormElement { pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLFormElement { HTMLFormElement { htmlelement: HTMLElement::new_inherited(HTMLFormElementTypeId, localName, document) } } #[allow(unrooted_must_root)] pub fn new(localName: ...
{ self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFormElementTypeId)) }
identifier_body
load_info.rs
= get!(elf_header, e_phoff, u64)?; let program_headers_count = get!(elf_header, e_phnum)?; // We skip the initial part, directly to the program headers. file.seek(SeekFrom::Start(program_headers_offset))?; let mut load_info = LoadInfo::new(elf_header); // We will read all the...
test_load_info_from_invalid_path
identifier_name
load_info.rs
pub needs_executable_stack: bool, } lazy_static! { static ref PAGE_SIZE: Word = match sysconf(SysconfVar::PAGE_SIZE) { Ok(Some(value)) => value as Word, _ => 0x1000, }; static ref PAGE_MASK: Word = !(*PAGE_SIZE - 1); } //TODO: move these in arch.rs and do cfg for each env #[cfg(target_...
pub mappings: Vec<Mapping>, pub interp: Option<Box<LoadInfo>>,
random_line_split
load_info.rs
elf_header: elf_header, mappings: Vec::new(), interp: None, needs_executable_stack: false, } } /// Extracts information about an executable: /// - the ELF header info /// - the program header segments, which contain: /// - mappings /// - inte...
{ if flags & compare_flag > 0 { success_flag } else { default_flag } }
identifier_body
RichHistoryQueriesTab.test.tsx
import React from 'react'; import { mount } from 'enzyme'; import { ExploreId } from '../../../types/explore'; import { SortOrder } from 'app/core/utils/richHistory'; import { RichHistoryQueriesTab, Props } from './RichHistoryQueriesTab'; import { RangeSlider } from '@grafana/ui'; jest.mock('../state/selectors', () =>...
const wrapper = setup(); expect(wrapper.find({ 'aria-label': 'Sort queries' })).toHaveLength(1); }); }); describe('select datasource', () => { it('should render select datasource if activeDatasourceOnly is false', () => { const wrapper = setup(); expect(wrapper.find({ 'aria-label': ...
describe('sort options', () => { it('should render sorter', () => {
random_line_split
emitter.rs
//! An emitter is an instance of geometry that both receives and emits light //! //! # Scene Usage Example //! An emitter is an object in the scene that emits light, it can be a point light //! or an area light. The emitter takes an extra 'emitter' parameter to specify //! whether the instance is an area or point emitt...
(&self) -> bool { match &self.emitter { &EmitterType::Point => true, _ => false, } } fn pdf(&self, p: &Point, w_i: &Vector) -> f32 { match &self.emitter { &EmitterType::Point => 0.0, &EmitterType::Area(ref g, _ ) => { let p...
delta_light
identifier_name
emitter.rs
//! An emitter is an instance of geometry that both receives and emits light //! //! # Scene Usage Example //! An emitter is an object in the scene that emits light, it can be a point light //! or an area light. The emitter takes an extra 'emitter' parameter to specify //! whether the instance is an area or point emitt...
let w = (self.transform.inv_mul_vector(w_i)).normalized(); g.pdf(&p_l, &w) } } } }
let p_l = self.transform.inv_mul_point(p);
random_line_split
emitter.rs
//! An emitter is an instance of geometry that both receives and emits light //! //! # Scene Usage Example //! An emitter is an object in the scene that emits light, it can be a point light //! or an area light. The emitter takes an extra 'emitter' parameter to specify //! whether the instance is an area or point emitt...
} impl Light for Emitter { fn sample_incident(&self, p: &Point, samples: &(f32, f32)) -> (Colorf, Vector, f32, OcclusionTester) { match &self.emitter { &EmitterType::Point => { let pos = self.transform * Point::broadcast(0.0); let w_i = (pos - *p).no...
{ match &self.emitter { &EmitterType::Point => BBox::singular(self.transform * Point::broadcast(0.0)), &EmitterType::Area(ref g, _) => { self.transform * g.bounds() }, } }
identifier_body
downloadview.py
# # downloadview.py # # Copyright 2010 Brett Mravec <brett.mravec@gmail.com> # # 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 #...
def update_download (self, download): print 'DownloadView.update_download (download): stub' def remove_download (self, download): print 'DownloadView.remove_download (download): stub' def get_selected (self): print 'DownloadView.get_selected (): stub' return []
print 'DownloadView.add_download (download): stub'
identifier_body
downloadview.py
# # downloadview.py # # Copyright 2010 Brett Mravec <brett.mravec@gmail.com> # # 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 #...
(self, download): print 'DownloadView.remove_download (download): stub' def get_selected (self): print 'DownloadView.get_selected (): stub' return []
remove_download
identifier_name
downloadview.py
# # downloadview.py # # Copyright 2010 Brett Mravec <brett.mravec@gmail.com> # # 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 #...
print 'DownloadView.remove_download (download): stub' def get_selected (self): print 'DownloadView.get_selected (): stub' return []
print 'DownloadView.update_download (download): stub' def remove_download (self, download):
random_line_split
receive_as_stream.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
fn _poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<(), Error>>> { if let Some(recv_future) = self.recv_future.as_mut() { match recv_future.poll_unpin(cx) { Poll::Ready(Err(Error::IOError)) => { self.recv_future = None; ...
{ self.recv_future = Some(self.local_endpoint.receive(self.handler.clone())); }
identifier_body
receive_as_stream.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
}
type Item = Result<(), Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.get_mut()._poll_next_unpin(cx) }
random_line_split
receive_as_stream.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(local_endpoint: &'a LE, handler: F) -> ReceiveAsStream<'a, LE, F> { let mut ret = ReceiveAsStream { local_endpoint, recv_future: None, handler, }; ret.update_recv_future(); return ret; } fn update_recv_future(&mut self) { self.recv_fu...
new
identifier_name
frukkola.ts
import * as request from 'request-promise'; const FRUKKOLA_URL = 'http://fruccola.hu/'; const FRUKKOLA_MENU_URL = 'http://fruccola.hu/admin/api/daily_menu'; const ARANY_ID = 1; interface IMenu { id: number; place_id: number; soup_hu: string; soup_en: string; dish_hu: string; dish_en: string; due_date: s...
const text_hu = `${aranyMenu.soup_hu} (${response.pricing.soup}), \n` + `${aranyMenu.dish_hu} (${response.pricing.dish}) \n` + `${response.pricing.combo}.- Ft`; return { title: 'Frukkola :green_apple:', title_link: FRUKKOLA_URL, text: text_hu, }; } catch (error) { console.lo...
const response: IFrukkolaResponse = await request(options); const aranyMenu = response[ARANY_ID];
random_line_split
frukkola.ts
import * as request from 'request-promise'; const FRUKKOLA_URL = 'http://fruccola.hu/'; const FRUKKOLA_MENU_URL = 'http://fruccola.hu/admin/api/daily_menu'; const ARANY_ID = 1; interface IMenu { id: number; place_id: number; soup_hu: string; soup_en: string; dish_hu: string; dish_en: string; due_date: s...
() { try { const options: request.OptionsWithUrl = { url: FRUKKOLA_MENU_URL, json: true, }; const response: IFrukkolaResponse = await request(options); const aranyMenu = response[ARANY_ID]; const text_hu = `${aranyMenu.soup_hu} (${response.pricing.soup}), \n` + `${aranyMenu.dish_h...
getFrukkola
identifier_name
frukkola.ts
import * as request from 'request-promise'; const FRUKKOLA_URL = 'http://fruccola.hu/'; const FRUKKOLA_MENU_URL = 'http://fruccola.hu/admin/api/daily_menu'; const ARANY_ID = 1; interface IMenu { id: number; place_id: number; soup_hu: string; soup_en: string; dish_hu: string; dish_en: string; due_date: s...
return { title: 'Frukkola :ripepperonis:', title_link: FRUKKOLA_URL, text: `${error}`, }; } }
{ try { const options: request.OptionsWithUrl = { url: FRUKKOLA_MENU_URL, json: true, }; const response: IFrukkolaResponse = await request(options); const aranyMenu = response[ARANY_ID]; const text_hu = `${aranyMenu.soup_hu} (${response.pricing.soup}), \n` + `${aranyMenu.dish_hu} ...
identifier_body
VerifyType.py
# $Id: VerifyType.py,v 1.4 2005/11/02 22:26:08 tavis_rudd Exp $ """Functions to verify an argument's type Meta-Data ================================================================================ Author: Mike Orr <iron@mso.oz.net> License: This software is released for unlimited distribution under the terms ...
return "arg '%s' must be %s%s" % (argname, ltd, errmsgExtra) ################################################## ## TYPE VERIFICATION FUNCTIONS def VerifyType(arg, argname, legalTypes, ltd, errmsgExtra=''): """Verify the type of an argument. arg, any, the argument. argname, string, name of the a...
errmsgExtra = '\n' + errmsgExtra
conditional_block
VerifyType.py
# $Id: VerifyType.py,v 1.4 2005/11/02 22:26:08 tavis_rudd Exp $ """Functions to verify an argument's type Meta-Data ================================================================================ Author: Mike Orr <iron@mso.oz.net> License: This software is released for unlimited distribution under the terms ...
################################################## ## TYPE VERIFICATION FUNCTIONS def VerifyType(arg, argname, legalTypes, ltd, errmsgExtra=''): """Verify the type of an argument. arg, any, the argument. argname, string, name of the argument. legalTypes, list of type objects, the allowed types....
"""Construct an error message. argname, string, the argument name. ltd, string, description of the legal types. errmsgExtra, string, text to append to error mssage. Returns: string, the error message. """ if errmsgExtra: errmsgExtra = '\n' + errmsgExtra return "arg '%s' must be %s%s...
identifier_body
VerifyType.py
# $Id: VerifyType.py,v 1.4 2005/11/02 22:26:08 tavis_rudd Exp $ """Functions to verify an argument's type Meta-Data ================================================================================ Author: Mike Orr <iron@mso.oz.net> License: This software is released for unlimited distribution under the terms ...
""" if type(arg) not in legalTypes: m = _errmsg(argname, ltd, errmsgExtra) raise TypeError(m) return True def VerifyTypeClass(arg, argname, legalTypes, ltd, klass, errmsgExtra=''): """Same, but if it's a class, verify it's a subclass of the right class. arg, any, the argument. ...
legalTypes, list of type objects, the allowed types. ltd, string, description of legal types (for error message). errmsgExtra, string, text to append to error message. Returns: None. Exceptions: TypeError if 'arg' is the wrong type.
random_line_split
VerifyType.py
# $Id: VerifyType.py,v 1.4 2005/11/02 22:26:08 tavis_rudd Exp $ """Functions to verify an argument's type Meta-Data ================================================================================ Author: Mike Orr <iron@mso.oz.net> License: This software is released for unlimited distribution under the terms ...
(arg, argname, legalTypes, ltd, klass, errmsgExtra=''): """Same, but if it's a class, verify it's a subclass of the right class. arg, any, the argument. argname, string, name of the argument. legalTypes, list of type objects, the allowed types. ltd, string, description of legal types (for error mes...
VerifyTypeClass
identifier_name
eo_view.rs
// std imports use std::mem; // external imports use num::traits::Num; // local imports use algebra::structure::MagmaBase; use super::eo_traits::{ERO, ECO}; use matrix::view::MatrixView; use matrix::traits::{Shape, MatrixBuffer, Strided}; /// Implementation of Elementary row operations. impl<'a, T:MagmaBase + Nu...
(&mut self, i : usize, j : isize, scale : T )-> &mut MatrixView<'a, T> { debug_assert! (i < self.num_cols()); let m = self.matrix(); // Compute j-th column in m (by doing offset) let j = j + (self.start_col() as isize); debug_assert! (j >= 0...
eco_scale_add
identifier_name
eo_view.rs
// std imports use std::mem; // external imports use num::traits::Num; // local imports use algebra::structure::MagmaBase; use super::eo_traits::{ERO, ECO}; use matrix::view::MatrixView; use matrix::traits::{Shape, MatrixBuffer, Strided}; /// Implementation of Elementary row operations. impl<'a, T:MagmaBase + Nu...
} // Update offsets offset_a += 1; offset_b += 1; } self } } /****************************************************** * * Unit tests * *******************************************************/ #[cfg(test)] mod test{ //use super::*; } /*...
{ debug_assert! (i < self.num_cols()); let m = self.matrix(); // Compute j-th column in m (by doing offset) let j = j + (self.start_col() as isize); debug_assert! (j >= 0); let j = j as usize; debug_assert!(j < m.num_cols()); let ptr = m.as_ptr(); ...
identifier_body
eo_view.rs
// std imports use std::mem; // external imports use num::traits::Num;
// local imports use algebra::structure::MagmaBase; use super::eo_traits::{ERO, ECO}; use matrix::view::MatrixView; use matrix::traits::{Shape, MatrixBuffer, Strided}; /// Implementation of Elementary row operations. impl<'a, T:MagmaBase + Num> ERO<T> for MatrixView<'a, T> { /// Row scaling by a factor and addi...
random_line_split
data-types.js
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); const inherits = require('../../utils/inherits'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @...
() { if (!(this instanceof UUID)) { return new UUID(); } BaseTypes.UUID.apply(this, arguments); } inherits(UUID, BaseTypes.UUID); UUID.prototype.toSql = function toSql() { return 'CHAR(36) BINARY'; }; function GEOMETRY(type, srid) { if (!(this instanceof GEOMETRY)) { return ...
UUID
identifier_name
data-types.js
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); const inherits = require('../../utils/inherits'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @...
else { value = new Date(`${value} ${options.timezone}`); } return value; }; function DATEONLY() { if (!(this instanceof DATEONLY)) { return new DATEONLY(); } BaseTypes.DATEONLY.apply(this, arguments); } inherits(DATEONLY, BaseTypes.DATEONLY); DATEONLY.parse = function pars...
{ value = moment.tz(value, options.timezone).toDate(); }
conditional_block
data-types.js
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); const inherits = require('../../utils/inherits'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @...
inherits(JSONTYPE, BaseTypes.JSON); JSONTYPE.prototype._stringify = function _stringify(value, options) { return options.operation === 'where' && typeof value === 'string' ? value : JSON.stringify(value); }; const exports = { ENUM, DATE, DATEONLY, UUID, GEOMETRY, DECIMAL, ...
random_line_split
data-types.js
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); const inherits = require('../../utils/inherits'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @...
inherits(JSONTYPE, BaseTypes.JSON); JSONTYPE.prototype._stringify = function _stringify(value, options) { return options.operation === 'where' && typeof value === 'string' ? value : JSON.stringify(value); }; const exports = { ENUM, DATE, DATEONLY, UUID, GEOMETRY, DECIMAL, ...
{ if (!(this instanceof JSONTYPE)) { return new JSONTYPE(); } BaseTypes.JSON.apply(this, arguments); }
identifier_body
resources.ts
path. * @returns The resulting URI. */ joinPath(resource: URI, ...pathFragment: string[]): URI /** * Normalizes the path part of a URI: Resolves `.` and `..` elements with directory names. * * @param resource The URI to normalize the path. * @returns The URI with the normalized path. */ normalizePath(...
/** * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you * understand what you are doing.
random_line_split
resources.ts
Authority(resource: URI): string; /** * Returns the basename of the path component of an uri. * @param resource */ basename(resource: URI): string; /** * Returns the extension of the path component of an uri. * @param resource */ extname(resource: URI): string; /** * Return a URI representing the d...
dirname(resource: URI): URI { if (resource.path.length === 0) { return resource; } let dirname; if (resource.scheme === Schemas.file) { dirname = URI.file(paths.dirname(originalFSPath(resource))).path; } else { dirname = paths.posix.dirname(resource.path); if (resource.authority && dirname.leng...
{ return paths.posix.extname(resource.path); }
identifier_body
resources.ts
Authority(resource: URI): string; /** * Returns the basename of the path component of an uri. * @param resource */ basename(resource: URI): string; /** * Returns the extension of the path component of an uri. * @param resource */ extname(resource: URI): string; /** * Return a URI representing the d...
(uri: URI): boolean { return this._ignorePathCasing(uri); } isEqualOrParent(base: URI, parentCandidate: URI, ignoreFragment: boolean = false): boolean { if (base.scheme === parentCandidate.scheme) { if (base.scheme === Schemas.file) { return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(par...
ignorePathCasing
identifier_name
resources.ts
Authority(resource: URI): string; /** * Returns the basename of the path component of an uri. * @param resource */ basename(resource: URI): string; /** * Returns the extension of the path component of an uri. * @param resource */ extname(resource: URI): string; /** * Return a URI representing the d...
else { dirname = paths.posix.dirname(resource.path); if (resource.authority && dirname.length && dirname.charCodeAt(0) !== CharCode.Slash) { console.error(`dirname("${resource.toString})) resulted in a relative path`); dirname = '/'; // If a URI contains an authority component, then the path component mu...
{ dirname = URI.file(paths.dirname(originalFSPath(resource))).path; }
conditional_block
borrowck-lend-flow.rs
// 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 ...
fn produce<T>() -> T { panic!(); } fn inc(v: &mut Box<isize>) { *v = box (**v + 1); } fn pre_freeze() { // In this instance, the freeze starts before the mut borrow. let mut v: Box<_> = box 3; let _w = &v; borrow_mut(&mut *v); //~ ERROR cannot borrow _w.use_ref(); } fn post_freeze() { /...
{ panic!() }
identifier_body
borrowck-lend-flow.rs
// 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 ...
() { // In this instance, the const alias starts after the borrow. let mut v: Box<_> = box 3; borrow_mut(&mut *v); let _w = &v; } fn main() {} trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
post_freeze
identifier_name
borrowck-lend-flow.rs
// 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 ...
// either genuine or would require more advanced changes. The latter // cases are noted. #![feature(box_syntax)] fn borrow(_v: &isize) {} fn borrow_mut(_v: &mut isize) {} fn cond() -> bool { panic!() } fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() } fn produce<T>() -> T { panic!(); } fn inc(v: &mut Box...
random_line_split
web_modform_space_computing.py
ular_forms.elliptic_modular_forms.backend import WebModFormSpace class WebModFormSpace_computing_class(WebModFormSpace_class): r""" Space of cuspforms to be presented on the web. G = NS. EXAMPLES:: sage: WS=WebModFormSpace(2,39) """ def __init__(self, N=1, k=2, chi=1, cuspidal=1, p...
self): r""" Fetch dictionary data from the database. """ db = connect_to_modularforms_db('WebModformspace.files') s = {'name':self._name,'version':emf_version} wmf_logger.debug("Looking in DB for rec={0}".format(s)) f = db.find_one(s) wmf_logger.debug("Fou...
et_from_db(
identifier_name
web_modform_space_computing.py
ular_forms.elliptic_modular_forms.backend import WebModFormSpace class WebModFormSpace_computing_class(WebModFormSpace_class): r""" Space of cuspforms to be presented on the web. G = NS. EXAMPLES:: sage: WS=WebModFormSpace(2,39) """ def __init__(self, N=1, k=2, chi=1, cuspidal=1, p...
modular_symbols = connect_to_modularforms_db('Modular_symbols.files') key = {'k': int(self._k), 'N': int(self._N), 'cchi': int(self._chi)} modular_symbols_from_db = modular_symbols.find_one(key) wmf_logger.debug("found ms={0}".format(modular_symbols_from_db)) if modular_symbols...
eturn
conditional_block
web_modform_space_computing.py
.modular_forms.elliptic_modular_forms.backend import WebModFormSpace class WebModFormSpace_computing_class(WebModFormSpace_class): r""" Space of cuspforms to be presented on the web. G = NS. EXAMPLES:: sage: WS=WebModFormSpace(2,39) """ def __init__(self, N=1, k=2, chi=1, cuspidal=...
self._is_new = False self.set_sturm_bound() self.set_oldspace_decomposition() self.insert_into_db() def newform_factors(self): r""" Return newform factors of self. """ if self._newform_factors is None: self._newform_facto...
if self.dimension() == self.dimension_newspace(): self._is_new = True else:
random_line_split
web_modform_space_computing.py
from lmfdb.modular_forms.elliptic_modular_forms.backend import WebModFormSpace class WebModFormSpace_computing_class(WebModFormSpace_class): r""" Space of cuspforms to be presented on the web. G = NS. EXAMPLES:: sage: WS=WebModFormSpace(2,39) """ def __init__(self, N=1, k=2, chi=1...
""" Constructor for WebNewForms with added 'nicer' error message. """ if data is None: data = {} if cuspidal <> 1: raise IndexError,"We are very sorry. There are only cuspidal spaces currently in the database!" #try: F = WebModFormSpace_class(N=N, k=k, chi=chi, cuspidal=cuspidal, prec=p...
identifier_body
grasp_approach.py
import argparse parser = argparse.ArgumentParser() parser.add_argument("--interactive", action="store_true") args = parser.parse_args() import trajoptpy import openravepy as rave import numpy as np import json import trajoptpy.math_utils as mu import trajoptpy.kin_utils as ku def move_arm_to_grasp(xyz_targ, quat_tar...
trajoptpy.SetInteractive(args.interactive); prob = trajoptpy.ConstructProblem(s, env) result = trajoptpy.OptimizeProblem(prob)
ENV_FILE = "data/wamtest1.env.xml" MANIP_NAME = "arm" LINK_NAME = "wam7" ################## ### Env setup #### env = rave.Environment() env.StopSimulation() env.Load(ENV_FILE) robot = env.GetRobots()[0] manip = robot.GetManipulator(MANIP_NAME) ################## ...
conditional_block
grasp_approach.py
import argparse parser = argparse.ArgumentParser() parser.add_argument("--interactive", action="store_true") args = parser.parse_args() import trajoptpy import openravepy as rave import numpy as np import json import trajoptpy.math_utils as mu import trajoptpy.kin_utils as ku def move_arm_to_grasp(xyz_targ, quat_tar...
"type" : "collision", "params" : {"coeffs" : [10],"dist_pen" : [0.025]} }, { "type" : "joint_vel", "params": {"coeffs" : [1]} } ], "constraints" : [ { "type" : "pose", "name" : "final_pose", ...
"start_fixed" : True }, "costs" : [ {
random_line_split
grasp_approach.py
import argparse parser = argparse.ArgumentParser() parser.add_argument("--interactive", action="store_true") args = parser.parse_args() import trajoptpy import openravepy as rave import numpy as np import json import trajoptpy.math_utils as mu import trajoptpy.kin_utils as ku def
(xyz_targ, quat_targ, link_name, manip_name): request = { "basic_info" : { "n_steps" : 10, "manip" : manip_name, "start_fixed" : True }, "costs" : [ { "type" : "collision", "params" : {"coeffs" : [10],"dist_pen" : [0.02...
move_arm_to_grasp
identifier_name
grasp_approach.py
import argparse parser = argparse.ArgumentParser() parser.add_argument("--interactive", action="store_true") args = parser.parse_args() import trajoptpy import openravepy as rave import numpy as np import json import trajoptpy.math_utils as mu import trajoptpy.kin_utils as ku def move_arm_to_grasp(xyz_targ, quat_tar...
"pos_coeffs" : [1,1,1], "rot_coeffs" : [1,1,1], "xyz" : list(xyz_targ), "wxyz" : list(quat_targ), "link" : link_name, }, }, { "type" : "cart_vel", "name" : "cart_vel", ...
request = { "basic_info" : { "n_steps" : 10, "manip" : manip_name, "start_fixed" : True }, "costs" : [ { "type" : "collision", "params" : {"coeffs" : [10],"dist_pen" : [0.025]} }, { "type" : "joint_ve...
identifier_body
form_array_name.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { OnDestroy, OnInit } from '@angular/core'; import { FormArray } from '../../model'; import { ControlContainer...
extends ControlContainer implements OnInit, OnDestroy { name: string; constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]); ngOnInit(): void; ngOnDestroy(): void; control: FormArray; formDirective: FormGroupDirective; path: string[]; validator: ValidatorFn; ...
FormArrayName
identifier_name
form_array_name.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { OnDestroy, OnInit } from '@angular/core'; import { FormArray } from '../../model'; import { ControlContainer...
* ` * }) * export class App { * cityArray = new FormArray([ * new FormControl('SF'), * new FormControl('NY') * ]); * myForm = new FormGroup({ * cities: this.cityArray * }); * } * ``` * * @experimental */ export declare class FormArrayName extends ControlContainer implements OnInit, ...
* </form> * {{ myForm.value | json }} // {cities: ['SF', 'NY']} * </div>
random_line_split
modal.js
/* ========================================================================
* Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, o...
* Bootstrap: modal.js v3.1.0 * http://getbootstrap.com/javascript/#modals * ========================================================================
random_line_split
modal.js
/* ======================================================================== * Bootstrap: modal.js v3.1.0 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstra...
} // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof opt...
{ callback() }
conditional_block
extended_status.py
# Copyright 2011 OpenStack Foundation # # 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 a...
class ExtendedStatusTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('server', selector='server') make_server(root) return xmlutil.SlaveTemplate(root, 1, nsmap={ Extended_status.alias: Extended_status.namespace}) class ExtendedStatusesTe...
elem.set('{%s}task_state' % Extended_status.namespace, '%s:task_state' % Extended_status.alias) elem.set('{%s}power_state' % Extended_status.namespace, '%s:power_state' % Extended_status.alias) elem.set('{%s}vm_state' % Extended_status.namespace, '%s:vm_state' % Extended_s...
identifier_body
extended_status.py
# Copyright 2011 OpenStack Foundation # # 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 a...
@wsgi.extends def detail(self, req, resp_obj): context = req.environ['nova.context'] if authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=ExtendedStatusesTemplate()) servers = list(resp_obj.obj['servers']) ...
resp_obj.attach(xml=ExtendedStatusTemplate()) server = resp_obj.obj['server'] db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'show' method. self._extend_server(server, db_i...
conditional_block
extended_status.py
# Copyright 2011 OpenStack Foundation # # 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 a...
elem.set('{%s}vm_state' % Extended_status.namespace, '%s:vm_state' % Extended_status.alias) class ExtendedStatusTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('server', selector='server') make_server(root) return xmlutil.SlaveTemplat...
'%s:power_state' % Extended_status.alias)
random_line_split
extended_status.py
# Copyright 2011 OpenStack Foundation # # 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 a...
(self): root = xmlutil.TemplateElement('servers') elem = xmlutil.SubTemplateElement(root, 'server', selector='servers') make_server(elem) return xmlutil.SlaveTemplate(root, 1, nsmap={ Extended_status.alias: Extended_status.namespace})
construct
identifier_name
utils.rs
//! Various utilities /* use std::old_io::net::ip; /// Convert socket address to bytes in network order. pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> { match addr.ip { ip::Ipv4Addr(a, b, c, d) => vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8], // TOD...
(id: usize) -> num::BigUint { FromPrimitive::from_usize(id).unwrap() } }
usize_to_id
identifier_name
utils.rs
//! Various utilities /* use std::old_io::net::ip; /// Convert socket address to bytes in network order. pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> { match addr.ip { ip::Ipv4Addr(a, b, c, d) => vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8], // TOD...
pub fn new_node_with_port(id: usize, port: u16) -> Node { Node { id: FromPrimitive::from_usize(id).unwrap(), address: SocketAddr::V4( SocketAddrV4::new( Ipv4Addr::new(127, 0, 0, 1), port ) ) } } pub fn usize_to_id(id: us...
{ new_node_with_port(id, 8008) }
identifier_body
utils.rs
//! Various utilities /* use std::old_io::net::ip; /// Convert socket address to bytes in network order. pub fn netaddr_to_netbytes(addr: &ip::SocketAddr) -> Vec<u8> { match addr.ip { ip::Ipv4Addr(a, b, c, d) => vec![a, b, c, d, (addr.port >> 8) as u8, (addr.port & 0xFF) as u8], // TOD...
use num::traits::FromPrimitive; use num; use super::super::Node; pub static ADDR: &'static str = "127.0.0.1:8008"; pub fn new_node(id: usize) -> Node { new_node_with_port(id, 8008) } pub fn new_node_with_port(id: usize, port: u16) -> Node { Node { id: FromPr...
#[cfg(test)] pub mod test { use std::net::SocketAddr; use std::net::SocketAddrV4; use std::net::Ipv4Addr;
random_line_split
adadelta_test.py
# Copyright 2015 The TensorFlow 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 applica...
# ADADELTA gradient optimizer rho = 0.95 epsilon = 1e-8 adadelta_opt = adadelta.AdadeltaOptimizer(lr, rho, epsilon) adadelta_update = adadelta_opt.apply_gradients( zip([grads, grads], [var0, var1])) opt_vars = adadelta_opt.variabl...
num_updates = 4 # number of ADADELTA steps to perform for dtype in [dtypes.half, dtypes.float32]: for grad in [0.2, 0.1, 0.01]: for lr in [1.0, 0.5, 0.1]: with self.test_session(): var0_init = [1.0, 2.0] var1_init = [3.0, 4.0] if use_resource: ...
identifier_body
adadelta_test.py
# Copyright 2015 The TensorFlow 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 applica...
dtype=dtype.as_numpy_dtype()), slot_update[slot_idx].eval(), rtol=1e-5) # Check that the parameters have been updated self.assertAllCloseAccordingToType( np.array( [var0_init[0] - tot_upd...
adadelta_update.run() # Perform initial update without previous accum values accum = accum * rho + (grad**2) * (1 - rho) update[step] = (np.sqrt(accum_update + epsilon) * (1. / np.sqrt(accum + epsilon)) * grad) accum_update = (accum_...
conditional_block
adadelta_test.py
# Copyright 2015 The TensorFlow 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 applica...
loss = pred * pred sgd_op = adadelta.AdadeltaOptimizer( 1.0, 1.0, 1.0).minimize(loss) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval()) # Run 1 step of sgd ...
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype) x = constant_op.constant([[4.0], [5.0]], dtype=dtype) pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
random_line_split
adadelta_test.py
# Copyright 2015 The TensorFlow 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 applica...
(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.test_session(): var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype) x = constant_op.constant([[4.0], [5.0]], dtype=dtype) pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]...
testMinimizeSparseResourceVariable
identifier_name
EDMLoop_neg_slope.py
(text): sys.stdout.write(text) return sys.stdin.readline().strip() def measureParametersAndMakeBC(cluster, eState, bState, rfState, scramblerV, probePolAngle, pumpPolAngle): fileSystem = Environs.FileSystem print("Measuring parameters ...") bh.StopPattern() hc.UpdateRFPowerMonitor() hc.UpdateRFFrequenc...
prompt
identifier_name
EDMLoop_neg_slope.py
from System.Xml.Serialization import * from System import * from Analysis.EDM import * from DAQ.Environment import * from EDMConfig import * def saveBlockConfig(path, config): fs = FileStream(path, FileMode.Create) s = XmlSerializer(BlockConfig) s.Serialize(fs,config) fs.Close() def loadBlockConfig(...
from System.IO import * from System.Drawing import * from System.Runtime.Remoting import * from System.Threading import * from System.Windows.Forms import *
random_line_split
EDMLoop_neg_slope.py
bc.Settings["rfState"] = rfState bc.Settings["phaseScramblerV"] = scramblerV bc.Settings["probePolarizerAngle"] = probePolAngle bc.Settings["pumpPolarizerAngle"] = pumpPolAngle bc.Settings["ePlus"] = hc.CPlusMonitorVoltage * hc.CPlusMonitorScale bc.Settings["eMinus"] = hc.CMinusMonitorVoltage * hc.CMinusMoni...
fileSystem = Environs.FileSystem print("Measuring parameters ...") bh.StopPattern() hc.UpdateRFPowerMonitor() hc.UpdateRFFrequencyMonitor() bh.StartPattern() hc.UpdateBCurrentMonitor() hc.UpdateVMonitor() hc.UpdateI2AOMFreqMonitor() print("V plus: " + str(hc.CPlusMonitorVoltage * hc.CPlusMonitorScale)...
identifier_body
EDMLoop_neg_slope.py
PhysicalCentre = (hc.BiasCurrent)/1000 bc.GetModulationByName("B").PhysicalStep = abs(hc.FlipStepCurrent)/1000 bc.GetModulationByName("DB").PhysicalStep = abs(hc.CalStepCurrent)/1000 bc.GetModulationByName("RF1A").Centre = hc.RF1AttCentre bc.GetModulationByName("RF1A").Step = hc.RF1AttStep bc.GetModulationByN...
else: feedbackSign = -1 deltaBias = - (1.0/8.0) * feedbackSign * (hc.CalStepCurrent * (bValue / dbValue)) / kSteppingBiasCurrentPerVolt deltaBias = windowValue(deltaBias, -kBMaxChange, kBMaxChange) print "Attempting to change stepping B bias by " + str(deltaBias) + " V." newBiasVoltage = windowValue( hc....
feedbackSign = 1
conditional_block
htmlbrelement.rs
use dom::bindings::codegen::Bindings::HTMLBRElementBinding; use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived; use dom::bindings::js::Root; use dom::document::Document; use dom::element::ElementTypeId; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::{HTMLElement, HTMLElementT...
/* 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 http://mozilla.org/MPL/2.0/. */
random_line_split