file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
authenticator.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview An UI component to authenciate to Chrome. The component hosts * IdP web pages in a webview. A client who is interested in monitoring...
// TODO(guohui,xiyuan): no need to inherit EventTarget once we deprecate the // old event-based signin flow. Authenticator.prototype = Object.create(cr.EventTarget.prototype); /** * Loads the authenticator component with the given parameters. * @param {AuthMode} authMode Authorization mode. * @param...
{ this.webview_ = typeof webview == 'string' ? $(webview) : webview; assert(this.webview_); this.email_ = null; this.password_ = null; this.gaiaId_ = null, this.sessionIndex_ = null; this.chooseWhatToSync_ = false; this.skipForNow_ = false; this.authFlow_ = AuthFlow.DEFAULT; thi...
identifier_body
authenticator.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview An UI component to authenciate to Chrome. The component hosts * IdP web pages in a webview. A client who is interested in monitoring...
'newwindow', this.onNewWindow_.bind(this)); this.webview_.addEventListener( 'loadstop', this.onLoadStop_.bind(this)); this.webview_.request.onCompleted.addListener( this.onRequestCompleted_.bind(this), {urls: ['*://*/*', this.continueUrlWithoutParams_ + '*'], types: [...
this.authFlow_ = AuthFlow.DEFAULT; this.webview_.src = this.reloadUrl_; this.webview_.addEventListener(
random_line_split
fields.py
import json from wtforms.fields import TextAreaField from shapely.geometry import shape, mapping from .widgets import LeafletWidget from sqlalchemy import func import geoalchemy2 #from types import NoneType #from .. import db how do you get db.session in a Field? class JSONField(TextAreaField): def _value(self): ...
self.data = None if self.data is not None: web_shape = self.session.scalar(func.ST_AsText(func.ST_Transform(func.ST_GeomFromText(shape(self.data).wkt, self.web_srid), self.transform_srid))) self.data = 'SRID='+str(self.srid)+';'+str(web_shape)
super(GeoJSONField, self).process_formdata(valuelist) if str(self.data) is '':
random_line_split
fields.py
import json from wtforms.fields import TextAreaField from shapely.geometry import shape, mapping from .widgets import LeafletWidget from sqlalchemy import func import geoalchemy2 #from types import NoneType #from .. import db how do you get db.session in a Field? class JSONField(TextAreaField): def _value(self): ...
(self, valuelist): super(GeoJSONField, self).process_formdata(valuelist) if str(self.data) is '': self.data = None if self.data is not None: web_shape = self.session.scalar(func.ST_AsText(func.ST_Transform(func.ST_GeomFromText(shape(self.data).wkt, self.web_srid), self.tr...
process_formdata
identifier_name
fields.py
import json from wtforms.fields import TextAreaField from shapely.geometry import shape, mapping from .widgets import LeafletWidget from sqlalchemy import func import geoalchemy2 #from types import NoneType #from .. import db how do you get db.session in a Field? class JSONField(TextAreaField): def _value(self): ...
try: self.data = self.from_json(value) except ValueError: self.data = None raise ValueError(self.gettext('Invalid JSON')) def to_json(self, obj): return json.dumps(obj) def from_json(self, data): return json.loads(data) ...
self.data = None return
conditional_block
fields.py
import json from wtforms.fields import TextAreaField from shapely.geometry import shape, mapping from .widgets import LeafletWidget from sqlalchemy import func import geoalchemy2 #from types import NoneType #from .. import db how do you get db.session in a Field? class JSONField(TextAreaField): def _value(self): ...
widget = LeafletWidget() def __init__(self, label=None, validators=None, geometry_type="GEOMETRY", srid='-1', session=None, **kwargs): super(GeoJSONField, self).__init__(label, validators, **kwargs) self.web_srid = 4326 self.srid = srid if self.srid is -1: self.transfor...
identifier_body
base.py
"""Common settings and globals.""" from os.path import abspath, basename, dirname, join, normpath from sys import path try: from secret import * except: pass ########## PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(dirname(abspath(__file__))) # Absolut...
('layouts/classic_2columns.html', 'Classic 2 columns'), ) ######### END DJANGO CMS
random_line_split
testImport.py
# encoding: utf-8 import sys sys.path.append(sys.path.insert(0,"../src")) def urlopen(*args, **kwargs): # Only parse one arg: the url return Urls[args[0]] # Provide a simple hashtable to contain the content of the urls and # provide a mock object similar to what will be returned from the # real urlopen() fu...
(): pass @with_setup(clear_configs) def testImportContent(): "Cannot import content from a file" from xmlconfig import getConfig Urls.clear() Urls["file:file.txt"] = "Content embedded in a file" Urls["config.xml"] = \ u"""<?xml version="1.0" encoding="utf-8"?> <config> <constant...
clear_configs
identifier_name
testImport.py
# encoding: utf-8 import sys sys.path.append(sys.path.insert(0,"../src")) def urlopen(*args, **kwargs): # Only parse one arg: the url return Urls[args[0]] # Provide a simple hashtable to contain the content of the urls and # provide a mock object similar to what will be returned from the # real urlopen() fu...
# urlopen raises ValueError if unable to load content (not KeyError) raise ValueError("{0}: Cannot find file content".format(name)) Urls = MockUrlCache() def clear_configs(): pass @with_setup(clear_configs) def testImportContent(): "Cannot import content from a file" from xmlconfig impor...
try: name= scheme_re.sub('', name) return super(MockUrlCache, self).__getitem__(name) except: # Fall through pass
conditional_block
testImport.py
# encoding: utf-8 import sys sys.path.append(sys.path.insert(0,"../src")) def urlopen(*args, **kwargs): # Only parse one arg: the url return Urls[args[0]] # Provide a simple hashtable to contain the content of the urls and # provide a mock object similar to what will be returned from the # real urlopen() fu...
scheme_re = re.compile(r'file:(/+)?') class MockUrlCache(dict): def __setitem__(self, name, content): super(MockUrlCache, self).__setitem__(name, MockUrlContent(content)) def __getitem__(self, name): if name in self: return super(MockUrlCache, self).__getitem__(name) #...
def __init__(self, content): super(MockUrlContent, self).__init__(content) self.headers = { 'last-modified': time() } def close(self): pass
identifier_body
testImport.py
# encoding: utf-8 import sys sys.path.append(sys.path.insert(0,"../src")) def urlopen(*args, **kwargs): # Only parse one arg: the url return Urls[args[0]] # Provide a simple hashtable to contain the content of the urls and # provide a mock object similar to what will be returned from the # real urlopen() fu...
<section key="key4"> <string key="key5">value2</string> <string key="import">%(import:key22)</string> </section> </constants> </config> """ conf=getConfig() conf.load("config.xml") assert conf.get("import:foreign") == \ "Namespa...
<config> <constants namespace="import" src="file:config2.xml"/> <constants>
random_line_split
cast_sign_loss.rs
use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{method_chain_args, sext}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use super::CAST_SIGN_LOSS; pub(super) fn check(cx: &LateContext...
return false; } // Don't lint for positive constants. let const_val = constant(cx, cx.typeck_results(), cast_op); if_chain! { if let Some((Constant::Int(n), _)) = const_val; if let ty::Int(ity) = *cast_from.kind(); ...
fn should_lint(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool { match (cast_from.is_integral(), cast_to.is_integral()) { (true, true) => { if !cast_from.is_signed() || cast_to.is_signed() {
random_line_split
cast_sign_loss.rs
use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{method_chain_args, sext}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use super::CAST_SIGN_LOSS; pub(super) fn check(cx: &LateContext...
true }, (false, true) => !cast_to.is_signed(), (_, _) => false, } }
{ let mut method_name = path.ident.name.as_str(); let allowed_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"]; if_chain! { if method_name == "unwrap"; if let Some(arglist) = method_chain_args(cast_op, &["unwrap...
conditional_block
cast_sign_loss.rs
use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{method_chain_args, sext}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use super::CAST_SIGN_LOSS; pub(super) fn check(cx: &LateContext...
(cx: &LateContext<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool { match (cast_from.is_integral(), cast_to.is_integral()) { (true, true) => { if !cast_from.is_signed() || cast_to.is_signed() { return false; } // Don't lint for positi...
should_lint
identifier_name
cast_sign_loss.rs
use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint; use clippy_utils::{method_chain_args, sext}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; use super::CAST_SIGN_LOSS; pub(super) fn check(cx: &LateContext...
{ match (cast_from.is_integral(), cast_to.is_integral()) { (true, true) => { if !cast_from.is_signed() || cast_to.is_signed() { return false; } // Don't lint for positive constants. let const_val = constant(cx, cx.typeck_results(), cast_op); ...
identifier_body
structgruel_1_1rt__sched__param.js
var structgruel_1_1rt__sched__param =
];
[ [ "rt_sched_param", "structgruel_1_1rt__sched__param.html#a7592c8e69e3a07cc8ac0b0bf9339df70", null ], [ "rt_sched_param", "structgruel_1_1rt__sched__param.html#a5257e726503db28d31aa4f780ddead47", null ], [ "policy", "structgruel_1_1rt__sched__param.html#af42388ca3382b9f646228f9a391f1dbc", null ], [ "p...
random_line_split
utils.py
import functools import os import re import shutil import subprocess import sys import tempfile from io import StringIO from subprocess import TimeoutExpired from catkin_tools.commands.catkin import main as catkin_main TESTS_DIR = os.path.dirname(__file__) MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources') def c...
return f(*args, **kwds) decorated.__name__ = f.__name__ return decorated def run(args, **kwargs): """ Call to Popen, returns (errcode, stdout, stderr) """ print("run:", args) p = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
from inspect import getargspec # If it takes directory of kwargs and kwds does already have # directory, inject it if 'directory' not in kwds and 'directory' in getargspec(f)[0]: kwds['directory'] = directory
random_line_split
utils.py
import functools import os import re import shutil import subprocess import sys import tempfile from io import StringIO from subprocess import TimeoutExpired from catkin_tools.commands.catkin import main as catkin_main TESTS_DIR = os.path.dirname(__file__) MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources') def c...
(object): def __init__(self, prefix=''): self.prefix = prefix self.delete = False def __enter__(self): self.original_cwd = os.getcwd() self.temp_path = tempfile.mkdtemp(prefix=self.prefix) os.chdir(self.temp_path) return self.temp_path def __exit__(self, ex...
temporary_directory
identifier_name
utils.py
import functools import os import re import shutil import subprocess import sys import tempfile from io import StringIO from subprocess import TimeoutExpired from catkin_tools.commands.catkin import main as catkin_main TESTS_DIR = os.path.dirname(__file__) MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources') def c...
else: raise if exc_type is None: try: exc_name = self.expected.__name__ except AttributeError: exc_name = str(self.expected) raise AssertionError("{0} not raised".format(exc_name)) if not issubclass(exc_type...
return True
conditional_block
utils.py
import functools import os import re import shutil import subprocess import sys import tempfile from io import StringIO from subprocess import TimeoutExpired from catkin_tools.commands.catkin import main as catkin_main TESTS_DIR = os.path.dirname(__file__) MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources') def c...
def in_temporary_directory(f): @functools.wraps(f) def decorated(*args, **kwds): with temporary_directory() as directory: from inspect import getargspec # If it takes directory of kwargs and kwds does already have # directory, inject it if 'directory' n...
if self.delete and self.temp_path and os.path.exists(self.temp_path): print('Deleting temporary testind directory: %s' % self.temp_path) shutil.rmtree(self.temp_path) if self.original_cwd and os.path.exists(self.original_cwd): os.chdir(self.original_cwd)
identifier_body
symbol_query_spec.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 {StaticSymbol} from '@angular/compiler'; import {AngularCompilerOptions, CompilerHost} from '@angular/compile...
(): SymbolTable { return { size: 0, get(key: string) { return undefined; }, has(key: string) { return false; }, values(): Symbol[]{return [];} }; } describe('symbol query', () => { let program: ts.Program; let checker: ts.TypeChecker; let sourceFile: ts.SourceFile; let query: SymbolQuery; ...
emptyPipes
identifier_name
symbol_query_spec.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 {StaticSymbol} from '@angular/compiler'; import {AngularCompilerOptions, CompilerHost} from '@angular/compile...
export class AppComponent { name = 'Angular'; person: Person; people: Person[]; maybePerson?: Person; getName(): string { return this.name; } getPerson(): Person { return this.person; } getMaybePerson(): Person | undefined { this.maybePerson; } } `; } const QUICKSTA...
})
random_line_split
symbol_query_spec.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 {StaticSymbol} from '@angular/compiler'; import {AngularCompilerOptions, CompilerHost} from '@angular/compile...
, has(key: string) { return false; }, values(): Symbol[]{return [];} }; } describe('symbol query', () => { let program: ts.Program; let checker: ts.TypeChecker; let sourceFile: ts.SourceFile; let query: SymbolQuery; let context: DiagnosticContext; beforeEach(() => { const registry = ts.create...
{ return undefined; }
identifier_body
app.module.ts
/// <reference path="../globals.d.ts" /> import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { AppComponent, HeaderComponent, IndexComponent, CardListComponent, ...
CollectionService, SetService, UserService, AuthTokenService, StoreInitializerService, CardListStore, CollectionStore, CurrentUserStore, DispatcherService, ScrollPositionStore, SelectedCardStore, SetStore, ViewStore, UrlService ], bootstrap: [ AppComponent ] }...
random_line_split
app.module.ts
/// <reference path="../globals.d.ts" /> import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { AppComponent, HeaderComponent, IndexComponent, CardListComponent, ...
{ }
AppModule
identifier_name
sampler_no_sparsity.py
import numpy as np import pypolyagamma as pypolyagamma def calculate_D(S): N = S.shape[1] D = np.empty((N, N)) for i in range(N): for j in range(N): D[i, j] = np.dot(S[1:, i].T, S[:-1, j]) return D * 0.5 def calculate_C_w(S, w_i): w_mat = np.diag(w_i) return np.dot(S....
else: return samples_w_i[burnin:N_s:thin, :], samples_J_i[burnin:N_s:thin, :]
return samples_w_i[burnin:, :], samples_J_i[burnin:, :]
conditional_block
sampler_no_sparsity.py
import numpy as np import pypolyagamma as pypolyagamma def
(S): N = S.shape[1] D = np.empty((N, N)) for i in range(N): for j in range(N): D[i, j] = np.dot(S[1:, i].T, S[:-1, j]) return D * 0.5 def calculate_C_w(S, w_i): w_mat = np.diag(w_i) return np.dot(S.T, np.dot(w_mat, S)) def sample_w_i(S, J_i): """ :param S: ob...
calculate_D
identifier_name
sampler_no_sparsity.py
import numpy as np import pypolyagamma as pypolyagamma def calculate_D(S): N = S.shape[1] D = np.empty((N, N)) for i in range(N): for j in range(N): D[i, j] = np.dot(S[1:, i].T, S[:-1, j]) return D * 0.5 def calculate_C_w(S, w_i): w_mat = np.diag(w_i) return np.dot(S....
""" This function uses the Gibbs sampler to sample from w, gamma and J :param samp_num: Number of samples to be drawn :param burnin: Number of samples to burn in :param sigma_J: variance of the J slab :param S: Neurons' activity matrix. Including S0. (T + 1) x N :param C: observation correlation ma...
identifier_body
sampler_no_sparsity.py
import numpy as np import pypolyagamma as pypolyagamma def calculate_D(S): N = S.shape[1] D = np.empty((N, N)) for i in range(N): for j in range(N): D[i, j] = np.dot(S[1:, i].T, S[:-1, j]) return D * 0.5
def calculate_C_w(S, w_i): w_mat = np.diag(w_i) return np.dot(S.T, np.dot(w_mat, S)) def sample_w_i(S, J_i): """ :param S: observation matrix :param J_i: neuron i's couplings :return: samples for w_i from a polyagamma distribution """ ppg = pypolyagamma.PyPolyaGamma(np.random.randi...
random_line_split
get_started.py
# Copyright 2014-2018 The ODL contributors # # This file is part of ODL. # # 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/. """A simple example to get started with SPDH...
# set parameters for algorithm Ai_norm = [2, 2] gamma = 0.99 sigma = [gamma / a for a in Ai_norm] tau = gamma / (n * max(Ai_norm)) # callback for output during the iterations cb = (odl.solvers.CallbackPrintIteration(fmt='iter:{:4d}', step=n, end=', ') & odl.solvers.CallbackPrintTiming(fmt='time: {:5.2f} s', c...
return S[int(np.random.choice(n, 1, p=prob))]
identifier_body
get_started.py
# Copyright 2014-2018 The ODL contributors # # This file is part of ODL.
# 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/. """A simple example to get started with SPDHG [CERS2017]. The example at hand solves the ROF denoising problem. Refere...
#
random_line_split
get_started.py
# Copyright 2014-2018 The ODL contributors # # This file is part of ODL. # # 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/. """A simple example to get started with SPDH...
(k): # subset selection function return S[int(np.random.choice(n, 1, p=prob))] # set parameters for algorithm Ai_norm = [2, 2] gamma = 0.99 sigma = [gamma / a for a in Ai_norm] tau = gamma / (n * max(Ai_norm)) # callback for output during the iterations cb = (odl.solvers.CallbackPrintIteration(fmt='iter:{:4d}',...
fun_select
identifier_name
category_tags.py
from django import template from django.shortcuts import render_to_response, redirect, get_object_or_404 # from product.models import Slide register = template.Library() # @register.inclusion_tag('slides/slides.html') # def get_main_slides(): # slides = Slide.objects.filter(published_main=1).order_by('orde...
# .linked_readonly_fields: # return displayed # try: # fieldtype, attr, value = lookup_field(fieldname, obj, # admin_field.model_admin) # except ObjectDoesNotExist: # fieldtype = None # if isinstance(fieldtype, ForeignKey): # ...
# obj = admin_field.form.instance # if not hasattr(admin_field.model_admin, # 'linked_readonly_fields') or fieldname not in admin_field \ # .model_admin \
random_line_split
history.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::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::Histor...
} impl History { fn traverse_history(&self, direction: TraversalDirection) { let pipeline = self.window.pipeline_id(); let msg = ConstellationMsg::TraverseHistory(Some(pipeline), direction); let _ = self.window.constellation_chan().send(msg); } } impl HistoryMethods for History { ...
{ reflect_dom_object(box History::new_inherited(window), GlobalRef::Window(window), HistoryBinding::Wrap) }
identifier_body
history.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::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::Histor...
else { self.window.Location().Reload(); return; }; self.traverse_history(direction); } // https://html.spec.whatwg.org/multipage/#dom-history-back fn Back(&self) { self.traverse_history(TraversalDirection::Back(1)); } // https://html.spec.whatwg.or...
{ TraversalDirection::Back(-delta as usize) }
conditional_block
history.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::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::Histor...
} impl HistoryMethods for History { // https://html.spec.whatwg.org/multipage/#dom-history-length fn Length(&self) -> u32 { let pipeline = self.window.pipeline_id(); let (sender, recv) = ipc::channel().expect("Failed to create channel to send jsh length."); let msg = ConstellationMsg::J...
}
random_line_split
history.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::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::Histor...
{ reflector_: Reflector, window: JS<Window>, } impl History { pub fn new_inherited(window: &Window) -> History { History { reflector_: Reflector::new(), window: JS::from_ref(&window), } } pub fn new(window: &Window) -> Root<History> { reflect_dom_ob...
History
identifier_name
SnapshotListTable.test.tsx
import { locationService } from '@grafana/runtime'; import { getSnapshots } from './SnapshotListTable'; jest.mock('@grafana/runtime', () => ({ ...(jest.requireActual('@grafana/runtime') as unknown as object), getBackendSrv: () => ({ get: jest.fn().mockResolvedValue([ { name: 'Snap 1', key...
]), }), })); describe('getSnapshots', () => { (global as any).window = Object.create(window); Object.defineProperty(window, 'location', { value: { href: 'http://localhost:3000/grafana/dashboard/snapshots', }, writable: true, }); locationService.push('/dashboard/snapshots'); test('re...
external: false, externalUrl: '', },
random_line_split
merkletree.rs
use services::ledger::merkletree::tree::{ Tree, LeavesIterator, LeavesIntoIterator, TreeLeafData }; use services::ledger::merkletree::proof::{ Proof, Lemma }; use utils::crypto::hash::{Hash, HASH_OUTPUT_LEN}; use errors::crypto::CryptoError; /// A Merkle tree is a binary tree, with values of type `T` at the leafs, ///...
} debug_assert!(cur.len() == 1); let root = cur.remove(0); Ok(MerkleTree { root: root, height: height, count: count, nodes_count: nodes_count }) } /// Returns the root hash of Merkle tree pub fn root_hash(&self) -> &...
cur = next;
random_line_split
merkletree.rs
use services::ledger::merkletree::tree::{ Tree, LeavesIterator, LeavesIntoIterator, TreeLeafData }; use services::ledger::merkletree::proof::{ Proof, Lemma }; use utils::crypto::hash::{Hash, HASH_OUTPUT_LEN}; use errors::crypto::CryptoError; /// A Merkle tree is a binary tree, with values of type `T` at the leafs, ///...
(self) -> Self::IntoIter { self.root.iter() } }
into_iter
identifier_name
merkletree.rs
use services::ledger::merkletree::tree::{ Tree, LeavesIterator, LeavesIntoIterator, TreeLeafData }; use services::ledger::merkletree::proof::{ Proof, Lemma }; use utils::crypto::hash::{Hash, HASH_OUTPUT_LEN}; use errors::crypto::CryptoError; /// A Merkle tree is a binary tree, with values of type `T` at the leafs, ///...
let count = values.len(); let mut nodes_count = 0; let mut height = 0; let mut cur = Vec::with_capacity(count); for v in values { let leaf = Tree::new_leaf(v)?; cur.push(leaf); } while cur.len() > 1 { let mut next = Vec::...
{ return Ok(MerkleTree { root: Tree::empty(Hash::hash_empty()?), height: 0, count: 0, nodes_count: 0 }); }
conditional_block
merkletree.rs
use services::ledger::merkletree::tree::{ Tree, LeavesIterator, LeavesIntoIterator, TreeLeafData }; use services::ledger::merkletree::proof::{ Proof, Lemma }; use utils::crypto::hash::{Hash, HASH_OUTPUT_LEN}; use errors::crypto::CryptoError; /// A Merkle tree is a binary tree, with values of type `T` at the leafs, ///...
/// Returns whether the Merkle tree is empty or not pub fn is_empty(&self) -> bool { self.count() == 0 } /// Generate an inclusion proof for the given value. /// Returns `None` if the given value is not found in the tree. pub fn gen_proof(&self, value: TreeLeafData) -> Result<Option<P...
{ self.count }
identifier_body
panic_in_result_fn_debug_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)] // debug_assert should never trigger the `panic_in_result_fn` lint struct A; impl A { fn
(x: i32) -> Result<bool, String> { debug_assert!(x == 5, "wrong argument"); Ok(true) } fn result_with_debug_assert_eq(x: i32) -> Result<bool, String> { debug_assert_eq!(x, 5); Ok(true) } fn result_with_debug_assert_ne(x: i32) -> Result<bool, String> { debug_asse...
result_with_debug_assert_with_message
identifier_name
panic_in_result_fn_debug_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)] // debug_assert should never trigger the `panic_in_result_fn` lint struct A; impl A { fn result_with_debug_assert_with_message(x: i32) -> Result<bool, String> { debug_assert!(x == 5, "wrong argument"); Ok(true) } f...
{}
identifier_body
panic_in_result_fn_debug_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)]
// debug_assert should never trigger the `panic_in_result_fn` lint struct A; impl A { fn result_with_debug_assert_with_message(x: i32) -> Result<bool, String> { debug_assert!(x == 5, "wrong argument"); Ok(true) } fn result_with_debug_assert_eq(x: i32) -> Result<bool, String> { deb...
random_line_split
newpct.py
# coding=utf-8 # Author: CristianBB # Greetings to Mr. Pine-apple # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage 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 versi...
def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals """ Search query: http://www.newpct.com/index.php?l=doSearch&q=fringe&category_=All&idioma_=1&bus_de_=All q => Show name category_ = Category 'Shows' (767) idioma_ = Language Sp...
TorrentProvider.__init__(self, 'Newpct') self.onlyspasearch = None self.url = 'http://www.newpct.com' self.urls = {'search': urljoin(self.url, 'index.php')} self.cache = tvcache.TVCache(self, min_time=20)
identifier_body
newpct.py
# coding=utf-8 # Author: CristianBB # Greetings to Mr. Pine-apple # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage 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 versi...
else: logger.log('Could not download {0}'.format(url), logger.WARNING) helpers.remove_file_failed(filename) if urls: logger.log('Failed to download any results', logger.WARNING) return False @staticmethod def _processTitle(titl...
ger.log('Saved result to {0}'.format(filename), logger.INFO) return True
conditional_block
newpct.py
# coding=utf-8 # Author: CristianBB # Greetings to Mr. Pine-apple # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage 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 versi...
title = re.sub(r'\[Spanish[^\[]*]', 'SPANISH AUDIO', title, flags=re.I) title = re.sub(r'\[Castellano[^\[]*]', 'SPANISH AUDIO', title, flags=re.I) title = re.sub(r'\[Español[^\[]*]', 'SPANISH AUDIO', title, flags=re.I) title = re.sub(r'\[AC3 5\.1 Español[^\[]*]', 'SPANISH AUDIO', title, ...
title += ' 720p' # Language
random_line_split
newpct.py
# coding=utf-8 # Author: CristianBB # Greetings to Mr. Pine-apple # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage 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 versi...
lf, result): """ Save the result to disk. """ # check for auth if not self.login(): return False urls, filename = self._make_url(result) for url in urls: # Search results don't return torrent files directly, it returns show sheets so we ...
nload_result(se
identifier_name
gulpfile.js
/** * * Web Starter Kit * Copyright 2014 Google Inc. 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 * ...
'use strict'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var reload = browserSync.reload; // Clean Output Directory gulp.task('clean', del.bind(nul...
random_line_split
htmltabledatacellelement.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::HTMLTableDataCellElementBinding; use dom::document::AbstractDocument; use dom::element...
(localName: ~str, document: AbstractDocument) -> HTMLTableDataCellElement { HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, document) } } pub fn new(localName: ~str, document: AbstractDocument) -> Abstra...
new_inherited
identifier_name
htmltabledatacellelement.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::HTMLTableDataCellElementBinding; use dom::document::AbstractDocument; use dom::element...
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode { let element = HTMLTableDataCellElement::new_inherited(localName, document); Node::reflect_node(@mut element, document, HTMLTableDataCellElementBinding::Wrap) } }
{ HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, document) } }
identifier_body
htmltabledatacellelement.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::HTMLTableDataCellElementBinding; use dom::document::AbstractDocument; use dom::element...
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLTableDataCellElement { HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, document) } } pub fn new(localName: ~str, document: Abs...
} impl HTMLTableDataCellElement {
random_line_split
log_formatting.py
# -*- coding: utf-8 -*- import sys import string from datetime import datetime,timedelta import calendar import csv import re # ファイルオープン(fpは引数でログファイル,wfpは書き出すcsvファイルを指定) fp = open(sys.argv[1],'r') # logがローテートするタイミングが1日の間にある場合,/var/log/kern.logと/var/log/kern.log.1の両方を読み込む必要があるかもしれない wfp = open('/path/to/program/csv_dat...
#w[6] = "spt" # ファイルに1行出力 #writer.writerow(w) # ログファイルのEOFまで for line in fp.readlines(): # フォワーディングパケットで,内部ネットから出るログを指定 if line.find("FORWARD_F IN=eth1") >= 0: # kernel:の数値の[の後に空白が入ると,後のsplitでうまくきれないため,[を削除する line = line.replace('[','') line = line.replace(' DF ',' ') # 0文字以上...
#w[2] = "hour" #w[3] = "smacaddr" #w[4] = "dipaddr" #w[5] = "proto"
random_line_split
log_formatting.py
# -*- coding: utf-8 -*- import sys import string from datetime import datetime,timedelta import calendar import csv import re # ファイルオープン(fpは引数でログファイル,wfpは書き出すcsvファイルを指定) fp = open(sys.argv[1],'r') # logがローテートするタイミングが1日の間にある場合,/var/log/kern.logと/var/log/kern.log.1の両方を読み込む必要があるかもしれない wfp = open('/path/to/program/csv_dat...
d int(l[1], 10) == int(yesterday.strftime('%d'), 10): # print l # id w[0] = i # 昨日の曜日(Mon:0,Tue;1,Wed:2,Thu:3,FRI:4,SAT:5,SUN:6) w[1] = yesterday.weekday() # 時刻(時のみ) w[2] = int(l[2][:2], 10) # 送信元MACアドレス w[3] = l...
conditional_block
registry_test.ts
/** * @license * Copyright (C) 2021 The Android Open Source Project * * 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 require...
() { this.final.push('Bar'); } } interface DemoContext { foo: Foo; bar: Bar; } suite('Registry', () => { setup(() => {}); test('It finalizes correctly', () => { const final: string[] = []; const demoRegistry: Registry<DemoContext> = { foo: (_ctx: Partial<DemoContext>) => new Foo(final), ...
finalize
identifier_name
registry_test.ts
/** * @license * Copyright (C) 2021 The Android Open Source Project * * 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 require...
class Bar implements Finalizable { constructor(private readonly final: string[], _foo?: Foo) {} finalize() { this.final.push('Bar'); } } interface DemoContext { foo: Foo; bar: Bar; } suite('Registry', () => { setup(() => {}); test('It finalizes correctly', () => { const final: string[] = []; ...
} }
random_line_split
test.ts
import './polyfills.ts'; import 'zone.js/dist/long-stack-trace-zone'; import 'zone.js/dist/jasmine-patch'; import 'zone.js/dist/async-test'; import 'zone.js/dist/fake-async-test'; import 'zone.js/dist/sync-test'; // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. declare var __ka...
// And load the modules. .then(context => context.keys().map(context)) // Finally, start Karma to run the tests. .then(__karma__.start, __karma__.error);
// Then we find all the tests. .then(() => require.context('./', true, /\.spec\.ts/))
random_line_split
web_animations_player.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 { AnimationPlayer } from '@angular/animations'; import { DOMAnimation } from './dom_animation'; export declare...
implements AnimationPlayer { element: any; keyframes: { [key: string]: string | number; }[]; options: { [key: string]: string | number; }; private previousPlayers; private _onDoneFns; private _onStartFns; private _onDestroyFns; private _player; private _durat...
WebAnimationsPlayer
identifier_name
web_animations_player.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 { AnimationPlayer } from '@angular/animations'; import { DOMAnimation } from './dom_animation'; export declare...
[key: string]: string | number; }, previousPlayers?: WebAnimationsPlayer[]); private _onFinish(); init(): void; private _buildPlayer(); private _preparePlayerBeforeStart(); readonly domPlayer: DOMAnimation; onStart(fn: () => void): void; onDone(fn: () => void): void; onDestro...
}[], options: {
random_line_split
sockjs.js
class SockJS { constructor(url, whitelist, options, mockOptions) { this.nextLoginState = true; this.url = url; this.whitelist = whitelist; this.options = options; SockJS.mockInstances.push(this); SockJS.currentMockInstance = this; let fn = () => { if (typeof this.onopen === 'functio...
this.log(`[MOCK] SockJS.send(${event})`); if (message.replyAddress) { this.log(`[MOCK] Sending reply to ${message.replyAddress}`); var mockReply = message.body.mockReply || {data: 'reply'}; var reply = this._wrapToEvent(message.replyAddress, mockReply, undefined, mockReply.type); this.o...
{ return; }
conditional_block
sockjs.js
class SockJS { constructor(url, whitelist, options, mockOptions) { this.nextLoginState = true; this.url = url; this.whitelist = whitelist; this.options = options; SockJS.mockInstances.push(this); SockJS.currentMockInstance = this; let fn = () => { if (typeof this.onopen === 'functio...
}; } _buildLoginReplyAsSuccess(username, password) { this.sessionId = "SESSION" + (Math.round(1000000 * Math.random())); return { status : 'ok', sessionID : this.sessionId }; } _buildLoginReplyAsFail(username, password) { return { status : 'fail' }; } onmessage()...
replyAddress : replyAddress })
random_line_split
sockjs.js
class SockJS { constructor(url, whitelist, options, mockOptions) { this.nextLoginState = true; this.url = url; this.whitelist = whitelist; this.options = options; SockJS.mockInstances.push(this); SockJS.currentMockInstance = this; let fn = () => { if (typeof this.onopen === 'functio...
onmessage() { console.warn('No SockJS.onmessage() defined!'); } } SockJS.mockInstances = []; SockJS.currentMockInstance = null; module.exports = SockJS;
{ return { status : 'fail' }; }
identifier_body
sockjs.js
class SockJS { constructor(url, whitelist, options, mockOptions) { this.nextLoginState = true; this.url = url; this.whitelist = whitelist; this.options = options; SockJS.mockInstances.push(this); SockJS.currentMockInstance = this; let fn = () => { if (typeof this.onopen === 'functio...
() { console.warn('No SockJS.onmessage() defined!'); } } SockJS.mockInstances = []; SockJS.currentMockInstance = null; module.exports = SockJS;
onmessage
identifier_name
EffectMenu.ts
import * as $ from "jquery"; import { HTMLRenderer } from "./HTMLRenderer"; import { Effect } from "../Effects/Effect"; import { RubEns } from "../RubEns"; import { ParametersFieldPopup, ParametersFieldPopupParameters } from "./ParametersFieldPopup"; /** * UI element representing the effect menu. * * It displays a...
extends HTMLRenderer { protected rootNodeId = "effect_menu"; protected rootNodeType = "ul"; /** * Related app intance. */ private app: RubEns; /** * Set of effects, to display in the UI. */ private effects: Effect[]; /** * Event handler callback meant to be cal...
EffectMenu
identifier_name
EffectMenu.ts
import * as $ from "jquery"; import { HTMLRenderer } from "./HTMLRenderer"; import { Effect } from "../Effects/Effect"; import { RubEns } from "../RubEns"; import { ParametersFieldPopup, ParametersFieldPopupParameters } from "./ParametersFieldPopup"; /** * UI element representing the effect menu. * * It displays a...
// If there is no effect parameter, immetiately apply it let effectParameters = effect.parameters; if (Object.keys(effectParameters).length === 0) { effect.apply(); return; } // Otherwise, open a popup to allow the user to configure the effect parameter...
{ console.log("Error: effect " + effectClassName + " could not be loaded."); return; }
conditional_block
EffectMenu.ts
import * as $ from "jquery"; import { HTMLRenderer } from "./HTMLRenderer"; import { Effect } from "../Effects/Effect"; import { RubEns } from "../RubEns"; import { ParametersFieldPopup, ParametersFieldPopupParameters } from "./ParametersFieldPopup"; /** * UI element representing the effect menu. * * It displays a...
effectNode.append(effectButton); return effectNode; } /** * Method which must be called when a click occurs on an effect node. * @param {Event} event Related click event. * * @author Camille Gobert */ private onEffectClick (event: Event) { // Get the clicke...
effectButton.prop("disabled", true); let effectNode = $("<li>");
random_line_split
EffectMenu.ts
import * as $ from "jquery"; import { HTMLRenderer } from "./HTMLRenderer"; import { Effect } from "../Effects/Effect"; import { RubEns } from "../RubEns"; import { ParametersFieldPopup, ParametersFieldPopupParameters } from "./ParametersFieldPopup"; /** * UI element representing the effect menu. * * It displays a...
/** * Static method for creating an effect node, i.e. a node representing an effect in the UI, * able to respond to a click by applying the related effect, openning a popup to let the user * set the effect parameters if required. * * Note that this method assumes every effect has a differ...
{ this.effects = effects; this.updateRootNode(); }
identifier_body
es.js
/*! * This is a `i18n` language object. * * Spanish * * @author * Jalios (Twitter: @Jalios) * Sascha Greuel (Twitter: @SoftCreatR) * Rafael Miranda (GitHub: @rafa8626) * * @see core/i18n.js */
exports.es = { 'mejs.plural-form': 1, // core/mediaelement.js 'mejs.download-file': 'Descargar archivo', // renderers/flash.js 'mejs.install-flash': 'Esta usando un navegador que no tiene activado o instalado el reproductor de Flash. Por favor active el plugin del reproductor de Flash o descargue la ...
(function (exports) { if (exports.es === undefined) {
random_line_split
es.js
/*! * This is a `i18n` language object. * * Spanish * * @author * Jalios (Twitter: @Jalios) * Sascha Greuel (Twitter: @SoftCreatR) * Rafael Miranda (GitHub: @rafa8626) * * @see core/i18n.js */ (function (exports) { if (exports.es === undefined)
{ exports.es = { 'mejs.plural-form': 1, // core/mediaelement.js 'mejs.download-file': 'Descargar archivo', // renderers/flash.js 'mejs.install-flash': 'Esta usando un navegador que no tiene activado o instalado el reproductor de Flash. Por favor active el plugin del reproductor de Flash o descargue l...
conditional_block
transfer_state.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 {APP_ID, Injectable, NgModule} from '@angular/core'; import {DOCUMENT} from '../dom/dom_tokens'; export func...
get<T>(key: StateKey<T>, defaultValue: T): T { return this.store[key] !== undefined ? this.store[key] as T : defaultValue; } /** * Set the value corresponding to a key. */ set<T>(key: StateKey<T>, value: T): void { this.store[key] = value; } /** * Remove a key from the store. */ remove<T>(...
random_line_split
transfer_state.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 {APP_ID, Injectable, NgModule} from '@angular/core'; import {DOCUMENT} from '../dom/dom_tokens'; export func...
} return JSON.stringify(this.store); } } export function initTransferState(doc: Document, appId: string) { // Locate the script tag with the JSON data transferred from the server. // The id of the script tag is set to the Angular appId + 'state'. const script = doc.getElementById(appId + '-state'); ...
{ try { this.store[key] = this.onSerializeCallbacks[key](); } catch (e) { console.warn('Exception in onSerialize callback: ', e); } }
conditional_block
transfer_state.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 {APP_ID, Injectable, NgModule} from '@angular/core'; import {DOCUMENT} from '../dom/dom_tokens'; export func...
<T>(key: StateKey<T>): void { delete this.store[key]; } /** * Test whether a key exists in the store. */ hasKey<T>(key: StateKey<T>) { return this.store.hasOwnProperty(key); } /** * Register a callback to provide the value for a key when `toJson` is called. */ onSerialize<T>(key: StateKey<T>, call...
remove
identifier_name
transfer_state.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 {APP_ID, Injectable, NgModule} from '@angular/core'; import {DOCUMENT} from '../dom/dom_tokens'; export func...
/** * A key value store that is transferred from the application on the server side to the application * on the client side. * * `TransferState` will be available as an injectable token. To use it import * `ServerTransferStateModule` on the server and `BrowserTransferStateModule` on the client. * * The values ...
{ return key as StateKey<T>; }
identifier_body
utils.py
""" Helper functions for handling DB accesses. """ import subprocess import logging import gzip import io from nominatim.db.connection import get_pg_env from nominatim.errors import UsageError LOG = logging.getLogger() def _pipe_to_proc(proc, fdesc): chunk = fdesc.read(2048) while chunk and proc.poll() is No...
""" def __init__(self): self.buffer = io.StringIO() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if self.buffer is not None: self.buffer.close() def add(self, *data): """ Add another row of data to the copy bu...
""" Data collector for the copy_from command.
random_line_split
utils.py
""" Helper functions for handling DB accesses. """ import subprocess import logging import gzip import io from nominatim.db.connection import get_pg_env from nominatim.errors import UsageError LOG = logging.getLogger() def _pipe_to_proc(proc, fdesc): chunk = fdesc.read(2048) while chunk and proc.poll() is No...
(self, cur, table, columns=None): """ Copy all collected data into the given table. """ if self.buffer.tell() > 0: self.buffer.seek(0) cur.copy_from(self.buffer, table, columns=columns)
copy_out
identifier_name
utils.py
""" Helper functions for handling DB accesses. """ import subprocess import logging import gzip import io from nominatim.db.connection import get_pg_env from nominatim.errors import UsageError LOG = logging.getLogger() def _pipe_to_proc(proc, fdesc): chunk = fdesc.read(2048) while chunk and proc.poll() is No...
def add(self, *data): """ Add another row of data to the copy buffer. """ first = True for column in data: if first: first = False else: self.buffer.write('\t') if column is None: self.buffer.write...
if self.buffer is not None: self.buffer.close()
identifier_body
utils.py
""" Helper functions for handling DB accesses. """ import subprocess import logging import gzip import io from nominatim.db.connection import get_pg_env from nominatim.errors import UsageError LOG = logging.getLogger() def _pipe_to_proc(proc, fdesc): chunk = fdesc.read(2048) while chunk and proc.poll() is No...
else: with fname.open('rb') as fdesc: remain = _pipe_to_proc(proc, fdesc) if remain == 0 and post_code: proc.stdin.write((';' + post_code).encode('utf-8')) finally: proc.stdin.close() ret = proc.wait() if ret != 0 or remain > 0: ...
with gzip.open(str(fname), 'rb') as fdesc: remain = _pipe_to_proc(proc, fdesc)
conditional_block
_app.ts
///<reference path='../typings/tsd.d.ts' /> module <%= moduleName %> { 'use strict'; /* @ngdoc object * @name <%= moduleName %> * @description * */ angular
'ngAria',<% } %><% if (framework === 'material') { %> 'ngMaterial',<% } %> <% if (ngRoute) { %>'ngRoute'<% } else { %>'ui.router'<% } %><% if (framework === 'angularstrap') { %>, 'mgcrea.ngStrap'<% } %><% if (framework === 'uibootstrap') { %>, 'ui.bootstrap'<% } %><% if (framework === 'fo...
.module('<%= moduleName %>', [<% if (bower.indexOf('aria') > -1) { %>
random_line_split
PRESUBMIT.py
#!python # Copyright 2012 Google Inc. 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...
(input_api, output_api): return CheckChange(input_api, output_api, True)
CheckChangeOnCommit
identifier_name
PRESUBMIT.py
#!python # Copyright 2012 Google Inc. 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...
def CheckChangeOnUpload(input_api, output_api): return CheckChange(input_api, output_api, False) def CheckChangeOnCommit(input_api, output_api): return CheckChange(input_api, output_api, True)
white_list = [r'^.*\.py$'] black_list = [] disabled_warnings = [] results = input_api.canned_checks.RunPylint( input_api, output_api, white_list=white_list, black_list=black_list, disabled_warnings=disabled_warnings) return results
identifier_body
PRESUBMIT.py
#!python # Copyright 2012 Google Inc. 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...
def CheckChangeOnCommit(input_api, output_api): return CheckChange(input_api, output_api, True)
return results def CheckChangeOnUpload(input_api, output_api): return CheckChange(input_api, output_api, False)
random_line_split
check_reads.py
import os import sys import pysam import random from collections import Counter from .step import StepChunk from ..mlib import util from ..mlib.fq_idx import FastqIndex MIN_SEED_SIZE = 400 MIN_COV = 10. class CheckReadsStep(StepChunk): @staticmethod def get_steps(options): assert os.path.isfile(options.inpu...
self.__class__.__name__, self.__fqid(), ) def run(self): self.logger.broadcast('index fastq {}'.format(self.nfq_path)) with FastqIndex(self.nfq_path, self.logger) as idx: fq_num_se_bcoded = idx.num_se_bcoded # check for barcodes in fastq assert idx.num_bcodes > 0, \ ...
def __fqid(self): return os.path.basename(os.path.dirname(os.path.dirname(self.fq_path))) def __str__(self): return '{}_{}'.format(
random_line_split
check_reads.py
import os import sys import pysam import random from collections import Counter from .step import StepChunk from ..mlib import util from ..mlib.fq_idx import FastqIndex MIN_SEED_SIZE = 400 MIN_COV = 10. class CheckReadsStep(StepChunk): @staticmethod def get_steps(options): assert os.path.isfile(options.inpu...
(self): return os.path.join( self.options.results_dir, self.__class__.__name__, str(self), ) def __init__( self, options, fq_path, ): self.options = options self.fq_path = fq_path #self.nfq_path = fq_path[:-3] self.nfq_path = fq_path util.mkdir_p(self.outdi...
outdir
identifier_name
check_reads.py
import os import sys import pysam import random from collections import Counter from .step import StepChunk from ..mlib import util from ..mlib.fq_idx import FastqIndex MIN_SEED_SIZE = 400 MIN_COV = 10. class CheckReadsStep(StepChunk): @staticmethod def get_steps(options): assert os.path.isfile(options.inpu...
self.logger.broadcast('created {} bins from seeds'.format(len(bins))) util.write_pickle(self.options.bins_pickle_path, bins) passfile_path = os.path.join(self.outdir, 'pass') util.touch(passfile_path) self.logger.broadcast('done') def get_seeds(self, ctg_covs): ctg_size_map = util.get_fast...
binid = 'bin.{}'.format(i) bins.append((binid, seed_group))
conditional_block
check_reads.py
import os import sys import pysam import random from collections import Counter from .step import StepChunk from ..mlib import util from ..mlib.fq_idx import FastqIndex MIN_SEED_SIZE = 400 MIN_COV = 10. class CheckReadsStep(StepChunk): @staticmethod def get_steps(options): assert os.path.isfile(options.inpu...
def __fqid(self): return os.path.basename(os.path.dirname(os.path.dirname(self.fq_path))) def __str__(self): return '{}_{}'.format( self.__class__.__name__, self.__fqid(), ) def run(self): self.logger.broadcast('index fastq {}'.format(self.nfq_path)) with FastqIndex(self.nfq_pa...
self.options = options self.fq_path = fq_path #self.nfq_path = fq_path[:-3] self.nfq_path = fq_path util.mkdir_p(self.outdir)
identifier_body
__init__.py
# # Copyright 2008,2009 Free Software Foundation, Inc. # # This application 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 application is di...
#
# import any pure python here
random_line_split
show-in-viewport.js
'use strict'; var $ = require('./main') , getViewportRect = require('./get-viewport-rect') , getElementRect = require('./get-element-rect'); module.exports = $.showInViewport = function (el/*, options*/) { var vpRect = getViewportRect() , elRect = getElementRect(el) , options = Object(argume...
if (elTopLeft.x < vpTopLeft.x) { // left beyond diff = vpTopLeft.x - elTopLeft.x; elTopLeft.x += diff; elBottomRight.x += diff; diffPoint.x += diff; } if (elTopLeft.y < vpTopLeft.y) { // top beyond diff = vpTopLeft.y - elTopLeft.y; elTopLeft.y += diff; elBottomRight.y += diff; diffPoint.y += d...
{ // bottom beyond diff = elBottomRight.y - vpBottomRight.y; elTopLeft.y -= diff; elBottomRight.y -= diff; diffPoint.y -= diff; }
conditional_block
show-in-viewport.js
'use strict'; var $ = require('./main') , getViewportRect = require('./get-viewport-rect') , getElementRect = require('./get-element-rect'); module.exports = $.showInViewport = function (el/*, options*/) { var vpRect = getViewportRect() , elRect = getElementRect(el) , options = Object(argume...
} if (elTopLeft.y < vpTopLeft.y) { // top beyond diff = vpTopLeft.y - elTopLeft.y; elTopLeft.y += diff; elBottomRight.y += diff; diffPoint.y += diff; } if (diffPoint.x) el.style.left = (el.offsetLeft + diffPoint.x) + "px"; if (diffPoint.y) el.style.top = (el.offsetTop + diffPoint.y) + "px"; };
diffPoint.x += diff;
random_line_split
process_detail.py
#!/usr/bin/env python # $Id$ """ Print detailed information about a process. """ import os import datetime import socket import sys import psutil from psutil._compat import namedtuple def convert_bytes(n): if n == 0: return '0B' symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} ...
else: sys.exit('usage: %s [pid]' % __file__) if __name__ == '__main__': sys.exit(main())
sys.exit(run(int(argv[1])))
conditional_block
process_detail.py
#!/usr/bin/env python # $Id$ """ Print detailed information about a process. """ import os import datetime import socket import sys import psutil from psutil._compat import namedtuple def convert_bytes(n):
def print_(a, b): if sys.stdout.isatty(): fmt = '\x1b[1;32m%-17s\x1b[0m %s' %(a, b) else: fmt = '%-15s %s' %(a, b) print fmt def run(pid): p = psutil.Process(pid) if p.parent: parent = '(%s)' % p.parent.name else: parent = '' started = datetime.datetime.fro...
if n == 0: return '0B' symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i+1)*10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s)
identifier_body
process_detail.py
#!/usr/bin/env python # $Id$ """ Print detailed information about a process. """ import os import datetime import socket import sys import psutil from psutil._compat import namedtuple def convert_bytes(n): if n == 0: return '0B' symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} ...
if __name__ == '__main__': sys.exit(main())
else: sys.exit('usage: %s [pid]' % __file__)
random_line_split
process_detail.py
#!/usr/bin/env python # $Id$ """ Print detailed information about a process. """ import os import datetime import socket import sys import psutil from psutil._compat import namedtuple def convert_bytes(n): if n == 0: return '0B' symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} ...
(argv=None): if argv is None: argv = sys.argv if len(argv) == 1: sys.exit(run(os.getpid())) elif len(argv) == 2: sys.exit(run(int(argv[1]))) else: sys.exit('usage: %s [pid]' % __file__) if __name__ == '__main__': sys.exit(main())
main
identifier_name
helpers.js
var libTools = require("../lib/tools"); /* var fn = makeTimeoutFn(1500, null, "result2"); fn(1, "whatever2", 3, function (err, res) { console.log(err, res); // null, result2 }); */ exports.makeTimeoutFn = function makeTimeoutFn(ms) { var args = Array.prototype.slice.call(arguments, 1); return function () { v...
}; exports.asyncAddSub = function asyncAddSub(a, b, callback) { setTimeout(function () { if (libTools.isNumber(a) && libTools.isNumber(b)) { callback(null, a + b, a - b); } else { callback(new Error("Invalid")); } }, 100); }; exports.expectTimestamp = function expectTimestamp(expect, ts, target, precisi...
callback(new Error("Invalid")); } }, 100);
random_line_split
helpers.js
var libTools = require("../lib/tools"); /* var fn = makeTimeoutFn(1500, null, "result2"); fn(1, "whatever2", 3, function (err, res) { console.log(err, res); // null, result2 }); */ exports.makeTimeoutFn = function makeTimeoutFn(ms) { var args = Array.prototype.slice.call(arguments, 1); return function () { v...
}, 100); }; exports.expectTimestamp = function expectTimestamp(expect, ts, target, precision) { precision = precision || 35; ts = ts.getTime ? ts.getTime() : ts; target = target.getTime ? target.getTime() : target; expect(ts).toBeGreaterThan(target - precision); expect(ts).toBeLessThan(target + precision); };
{ callback(new Error("Invalid")); }
conditional_block
_9_1_geometry_shader_houses.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ptr; use std::mem; use std::os::raw::c_void; extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use cgmath::{Point3}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; // settin...
() { let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame ...
main_4_9_1
identifier_name
_9_1_geometry_shader_houses.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ptr; use std::mem; use std::os::raw::c_void; extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use cgmath::{Point3}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; // settin...
{ let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and...
identifier_body
_9_1_geometry_shader_houses.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ptr; use std::mem; use std::os::raw::c_void; extern crate glfw; use self::glfw::Context; extern crate gl; use self::gl::types::*; use cgmath::{Point3}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; // settin...
processInput(&mut window, deltaTime, &mut camera); // render // ------ unsafe { gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); shader.useProgram(); gl::BindVertexArray(VAO); gl::Dra...
// input // -----
random_line_split
DynamicPropertyOutput.ts
/** * Copyright 2014 Mozilla 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 agr...
() { super(); } // JS -> AS Bindings // AS -> JS Bindings writeDynamicProperty(name: string, value: any): void { name = axCoerceString(name); release || notImplemented("packageInternal flash.net.DynamicPropertyOutput::writeDynamicProperty"); return; } } }
constructor
identifier_name
DynamicPropertyOutput.ts
/** * Copyright 2014 Mozilla 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 agr...
export class DynamicPropertyOutput extends ASObject implements IDynamicPropertyOutput { // Called whenever the class is initialized. static classInitializer: any = null; // List of static symbols to link. static classSymbols: string [] = null; // []; // List of instance symbols to link....
random_line_split