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
UserController.ts
import express = require("express"); import mongodb = require("mongodb"); import bodyParser = require("body-parser"); import jwt = require('jsonwebtoken'); import config = require('../config'); import { Persistance } from "../db/Persistance"; import { Vendeur } from "../_model/Vendeur"; import { Inscription } from "../...
{ utilisateurConnecte: UtilisateurConnecte; session: Session; async inscrireVendeur(inscription:Inscription) : Promise<void> { var utilisateur = new Utilisateur(); utilisateur.email = inscription.email; utilisateur.password = inscription.password; utilisateur...
UserController
identifier_name
query_list.ts
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; import {getSymbolIterator} from 'angular2/src/facade/lang'; import {Observable, EventEmitter} from 'angular2/src/facade/async'; /** * An unmodifiable list of items that Angular keeps up to date when the state * of the application changes. * *...
/** * converts QueryList into an array */ toArray(): T[] { return ListWrapper.clone(this._results); } [getSymbolIterator()](): any { return this._results[getSymbolIterator()](); } toString(): string { return this._results.toString(); } /** * @internal */ reset(res: T[]): void { this._results ...
reduce<U>(fn: (acc: U, item: T) => U, init: U): U { return this._results.reduce(fn, init); }
random_line_split
query_list.ts
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; import {getSymbolIterator} from 'angular2/src/facade/lang'; import {Observable, EventEmitter} from 'angular2/src/facade/async'; /** * An unmodifiable list of items that Angular keeps up to date when the state * of the application changes. * *...
/** * returns a filtered array. */ filter(fn: (item: T) => boolean): T[] { return this._results.filter(fn); } /** * returns a reduced value. */ reduce<U>(fn: (acc: U, item: T) => U, init: U): U { return this._results.reduce(fn, init); } /** * converts QueryList into an array */ toArray...
{ return this._results.map(fn); }
identifier_body
query_list.ts
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; import {getSymbolIterator} from 'angular2/src/facade/lang'; import {Observable, EventEmitter} from 'angular2/src/facade/async'; /** * An unmodifiable list of items that Angular keeps up to date when the state * of the application changes. * *...
(): T { return ListWrapper.last(this._results); } /** * returns a new array with the passed in function applied to each element. */ map<U>(fn: (item: T) => U): U[] { return this._results.map(fn); } /** * returns a filtered array. */ filter(fn: (item: T) => boolean): T[] { return this._results.filt...
last
identifier_name
GetIndexErrorsOperation.ts
import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { IndexErrors } from "../../Indexes/Errors"; import { RavenCommand } from "../../../Http/RavenCommand"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { ServerNode } from "../../../Http...
(indexNames: string[], conventions: DocumentConventions) { super(); this._indexNames = indexNames; this._conventions = conventions; } public createRequest(node: ServerNode): HttpRequestParameters { let uri = node.url + "/databases/" + node.database + "/indexes/errors"; ...
constructor
identifier_name
GetIndexErrorsOperation.ts
import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { IndexErrors } from "../../Indexes/Errors"; import { RavenCommand } from "../../../Http/RavenCommand"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { ServerNode } from "../../../Http...
}
{ return true; }
identifier_body
GetIndexErrorsOperation.ts
import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { IndexErrors } from "../../Indexes/Errors"; import { RavenCommand } from "../../../Http/RavenCommand"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { ServerNode } from "../../../Http...
const typeInfo = { nestedTypes: { "results[].errors[].timestamp": "date" } }; let body: string = null; await this._defaultPipeline(_ => body = _).process(bodyStream) .then(results => { this.result = this._r...
{ this._throwInvalidResponse(); }
conditional_block
GetIndexErrorsOperation.ts
import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { IndexErrors } from "../../Indexes/Errors"; import { RavenCommand } from "../../../Http/RavenCommand"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { ServerNode } from "../../../Http...
public constructor(); public constructor(indexNames: string[]); public constructor(indexNames: string[] = null) { this._indexNames = indexNames; } public getCommand(conventions: DocumentConventions): RavenCommand<IndexErrors[]> { return new GetIndexErrorsCommand(this._index...
export class GetIndexErrorsOperation implements IMaintenanceOperation<IndexErrors[]> { private readonly _indexNames: string[];
random_line_split
builder.js
var Backbone = require('backbone'); var Modules = require('collections/modules'); var ModuleFactory = require('utils/module-factory'); var Builder = Backbone.Model.extend({ defaults: { selectDefault: modularPageBuilderData.l10n.selectDefault, addNewButton: modularPageBuilderData.l10n.add...
else if ( selection.at( i ) && selection.at( i ).get( 'name' ) === required[ i ] ) { selection.at( i ).set( 'sortable', false ); } } } }); module.exports = Builder;
{ var module = ModuleFactory.create( required[ i ], [], { sortable: false } ); selection.add( module, { at: i, silent: true } ); }
conditional_block
builder.js
var Backbone = require('backbone'); var Modules = require('collections/modules'); var ModuleFactory = require('utils/module-factory'); var Builder = Backbone.Model.extend({ defaults: { selectDefault: modularPageBuilderData.l10n.selectDefault, addNewButton: modularPageBuilderData.l10n.add...
saveData: function() { var data = []; this.get('selection').each( function( module ) { // Skip empty/broken modules. if ( ! module.get('name' ) ) { return; } data.push( module.toMicroJSON() ); } ); this.trigger( 'save', data ); }, /** * List all available modules for this builder. ...
} },
random_line_split
AssetSettingsDialogContainer.tsx
import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import type { InjectedProps } from '../../types/injectedPropsType'; import AssetSettingsDialog from '../../components/assets/AssetSettingsDialog'; import type { AssetToken } from '../../api/assets/types'; type Props = InjectedProp...
extends Component<Props> { static defaultProps = { actions: null, stores: null, }; handleSubmit = (asset: AssetToken, decimals: number) => { const { assets, dialogs } = this.props.actions; assets.onAssetSettingsSubmit.trigger({ asset, decimals }); dialogs.closeActiveDialog.trigger(); }; ...
AssetSettingsDialogContainer
identifier_name
AssetSettingsDialogContainer.tsx
import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import type { InjectedProps } from '../../types/injectedPropsType'; import AssetSettingsDialog from '../../components/assets/AssetSettingsDialog'; import type { AssetToken } from '../../api/assets/types'; type Props = InjectedProp...
assets.onAssetSettingsSubmit.trigger({ asset, decimals }); dialogs.closeActiveDialog.trigger(); }; handleCancel = () => { const { assets, dialogs } = this.props.actions; assets.unsetEditedAsset.trigger(); dialogs.closeActiveDialog.trigger(); }; render() { const { stores } = this.props;...
stores: null, }; handleSubmit = (asset: AssetToken, decimals: number) => { const { assets, dialogs } = this.props.actions;
random_line_split
value_oid_as.rs
#![allow(dead_code)] #![allow(unused_imports)] extern crate libc; extern crate sysctl; // Import the trait use sysctl::Sysctl; // Converted from definition in from /usr/include/sys/time.h #[derive(Debug)] #[repr(C)] struct ClockInfo { hz: libc::c_int, /* clock frequency */ tick: libc::c_int, /* micro-secon...
() { println!("This operation is not supported on Linux."); }
main
identifier_name
value_oid_as.rs
#![allow(dead_code)] #![allow(unused_imports)] extern crate libc; extern crate sysctl; // Import the trait use sysctl::Sysctl; // Converted from definition in from /usr/include/sys/time.h #[derive(Debug)] #[repr(C)] struct ClockInfo { hz: libc::c_int, /* clock frequency */ tick: libc::c_int, /* micro-secon...
#[cfg(any(target_os = "linux", target_os = "android"))] fn main() { println!("This operation is not supported on Linux."); }
random_line_split
value_oid_as.rs
#![allow(dead_code)] #![allow(unused_imports)] extern crate libc; extern crate sysctl; // Import the trait use sysctl::Sysctl; // Converted from definition in from /usr/include/sys/time.h #[derive(Debug)] #[repr(C)] struct ClockInfo { hz: libc::c_int, /* clock frequency */ tick: libc::c_int, /* micro-secon...
#[cfg(any(target_os = "linux", target_os = "android"))] fn main() { println!("This operation is not supported on Linux."); }
{ let oid: Vec<i32> = vec![libc::CTL_KERN, libc::KERN_CLOCKRATE]; let val: Box<ClockInfo> = sysctl::Ctl { oid }.value_as().expect("could not get value"); println!("{:?}", val); }
identifier_body
export_spec.py
import os
from pychron.core.ui import set_toolkit set_toolkit('qt4') #e=ExportSpec(p='/Users/ross/Sandbox/aaaa_isotopes.h5') #for iso,det in # #from pychron.core.ui.dialogs import myConfirmationDialog # #from traits.api import HasTraits, Button #from traitsui.api import View # # #class A(HasTraits): # a = Button # # d...
import sys d = os.path.dirname(os.getcwd()) sys.path.append(d)
random_line_split
collect.py
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import logging import requests
"""Return filters from FEWS, cleaned and ready for storing as json.""" from_fews = _download(url) result = [] for filter_dict in from_fews: result.append(_process_filter_dict(filter_dict)) return result def collect_parameters(url): from_fews = _download(url) # TODO return from_...
logger = logging.getLogger(__name__) def collect_filters(url):
random_line_split
collect.py
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import logging import requests logger = logging.getLogger(__name__) def collect_filters(url): """Return filters from FEWS, cleaned and ready for storing...
(url): from_fews = _download(url) # TODO return from_fews def collect_locations(url): from_fews = _download(url) # TODO return from_fews def _download(url): r = requests.get(url) r.raise_for_status() # Only raises an error when not succesful. return r.json() def _process_filte...
collect_parameters
identifier_name
collect.py
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import logging import requests logger = logging.getLogger(__name__) def collect_filters(url): """Return filters from FEWS, cleaned and ready for storing...
children = [_process_filter_dict(child_filter_dict) for child_filter_dict in content.get('childFilters', [])] result = {'id': content['id'], 'name': name, 'description': description, 'children': children} return result
description = ''
conditional_block
collect.py
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import logging import requests logger = logging.getLogger(__name__) def collect_filters(url):
def collect_parameters(url): from_fews = _download(url) # TODO return from_fews def collect_locations(url): from_fews = _download(url) # TODO return from_fews def _download(url): r = requests.get(url) r.raise_for_status() # Only raises an error when not succesful. return r.js...
"""Return filters from FEWS, cleaned and ready for storing as json.""" from_fews = _download(url) result = [] for filter_dict in from_fews: result.append(_process_filter_dict(filter_dict)) return result
identifier_body
scenarios.js
describe('my app', function() { it('should redirect `index.html` to `index.html#!/countries/countries', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toBe('/home'); }); describe('home', function() { beforeEach(function() { browser.get('index.html'); }); ...
expect(countryList.count()).toBe(1); query.clear(); query.sendKeys('Indien'); expect(countryList.count()).toBe(0); }); it('should render country specific links', function() { var query = element(by.model('$ctrl.query')); query.sendKeys('Brunei'); element.all(by.css('.t...
random_line_split
supertypes.rs
use super::{general::StatusedTypeId, imports::Imports}; use crate::{ analysis::{namespaces, rust_type::used_rust_type}, env::Env, library::TypeId, }; pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> { let mut parents = Vec::new(); let gobject_id = env.library...
(env: &Env, type_id: TypeId) -> Vec<TypeId> { let mut parents = Vec::new(); let gobject_id = match env.library.find_type(0, "GObject.Object") { Some(gobject_id) => gobject_id, None => TypeId::tid_none(), }; for &super_tid in env.class_hierarchy.supertypes(type_id) { // skip GObj...
dependencies
identifier_name
supertypes.rs
use super::{general::StatusedTypeId, imports::Imports}; use crate::{ analysis::{namespaces, rust_type::used_rust_type}, env::Env, library::TypeId, }; pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> { let mut parents = Vec::new(); let gobject_id = env.library...
} } parents } pub fn dependencies(env: &Env, type_id: TypeId) -> Vec<TypeId> { let mut parents = Vec::new(); let gobject_id = match env.library.find_type(0, "GObject.Object") { Some(gobject_id) => gobject_id, None => TypeId::tid_none(), }; for &super_tid in env.class_...
{ if super_tid.ns_id == namespaces::MAIN { imports.add(&s); } else { let ns = &env.namespaces[super_tid.ns_id]; imports.add(&ns.crate_name); } }
conditional_block
supertypes.rs
use super::{general::StatusedTypeId, imports::Imports}; use crate::{ analysis::{namespaces, rust_type::used_rust_type}, env::Env, library::TypeId, }; pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> { let mut parents = Vec::new(); let gobject_id = env.library...
parents }
{ let mut parents = Vec::new(); let gobject_id = match env.library.find_type(0, "GObject.Object") { Some(gobject_id) => gobject_id, None => TypeId::tid_none(), }; for &super_tid in env.class_hierarchy.supertypes(type_id) { // skip GObject, it's inherited implicitly if su...
identifier_body
supertypes.rs
use super::{general::StatusedTypeId, imports::Imports}; use crate::{ analysis::{namespaces, rust_type::used_rust_type}, env::Env, library::TypeId, }; pub fn analyze(env: &Env, type_id: TypeId, imports: &mut Imports) -> Vec<StatusedTypeId> { let mut parents = Vec::new(); let gobject_id = env.library...
status, }); if !status.ignored() { if let Ok(s) = used_rust_type(env, super_tid, true) { if super_tid.ns_id == namespaces::MAIN { imports.add(&s); } else { let ns = &env.namespaces[super_tid.ns_id]; ...
parents.push(StatusedTypeId { type_id: super_tid, name: env.library.type_(super_tid).get_name(),
random_line_split
control.ts
import {Stage} from './'; import {Raycaster, Vector2, Vector3} from 'three'; export class Control { constructor(stage: Stage) { this.active = false; this.last = new Vector2(); this.radius = stage.camera.position.length(); this.stage = stage; let canvas = stage.renderer.domElement; canvas.add...
// console.log(origin, direction, intersection); return intersection; } calculateRay(point: Vector2) { let raycaster = new Raycaster(); // TODO Extract point transform function. point = point.clone().divide( new Vector2( this.stage.renderer.domElement.offsetWidth, this.sta...
// And now the intersection itself. let intersection = Number.isNaN(t) ? undefined : // This modifies our vectors, but we made them and don't need them later. origin.add(direction.multiplyScalar(t));
random_line_split
control.ts
import {Stage} from './'; import {Raycaster, Vector2, Vector3} from 'three'; export class Control { constructor(stage: Stage) { this.active = false; this.last = new Vector2(); this.radius = stage.camera.position.length(); this.stage = stage; let canvas = stage.renderer.domElement; canvas.add...
radius: number; stage: Stage; surface() { // TODO Work off elevation at current point. // TODO Why does below 1.1 go inside the sphere? return 1.1; } update() { let position = this.stage.camera.position; // Make sure we don't change altitude over time. position.normalize().multipl...
{ this.active = false; }
identifier_body
control.ts
import {Stage} from './'; import {Raycaster, Vector2, Vector3} from 'three'; export class Control { constructor(stage: Stage) { this.active = false; this.last = new Vector2(); this.radius = stage.camera.position.length(); this.stage = stage; let canvas = stage.renderer.domElement; canvas.add...
() { return this.radius - this.surface(); } calculateIntersection(point: Vector2) { let {origin, direction} = this.calculateRay(point); let {x, y, z} = origin; let {x: u, y: v, z: w} = direction; // Swap a and b out with real values if we vary later. let a = 1, b = 1; // Calculate dista...
altitude
identifier_name
converter.py
#!/usr/bin/env python # coding=utf-8 import sys import argparse parser = argparse.ArgumentParser( description='convert a non-standord hostname like xx-xx-[1-3] to a ' 'expansion state', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Sample: $ ./converter.py xxx-xxx-\[1-3\] xxx-xxx-1 x...
for arg in args.hostname_pattern: basestr=arg.split('-') prefix='-'.join(basestr[:-2]) range_li=basestr[-2:] start_num=int(range_li[0][1:]) end_num=int(range_li[1][:-1]) for i in range(start_num,end_num+1): print prefix + '-' + str(i)
conditional_block
converter.py
#!/usr/bin/env python # coding=utf-8 import sys
parser = argparse.ArgumentParser( description='convert a non-standord hostname like xx-xx-[1-3] to a ' 'expansion state', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Sample: $ ./converter.py xxx-xxx-\[1-3\] xxx-xxx-1 xxx-xxx-2 xxx-xxx-3 Tips: You can pass many args behind the comm...
import argparse
random_line_split
reactor_server.py
from kivy.support import install_twisted_reactor install_twisted_reactor() from twisted.internet import reactor from twisted.internet import protocol class EchoProtocol(protocol.Protocol): def dataReceived(self, data): response = self.factory.app.handle_message(data) if response: sel...
self.label.text += "responded: %s\n" % msg return msg if __name__ == '__main__': TwistedServerApp().run()
msg = "kivy rocks"
conditional_block
reactor_server.py
from kivy.support import install_twisted_reactor install_twisted_reactor() from twisted.internet import reactor from twisted.internet import protocol class EchoProtocol(protocol.Protocol):
class EchoFactory(protocol.Factory): protocol = EchoProtocol def __init__(self, app): self.app = app from kivy.app import App from kivy.uix.label import Label class TwistedServerApp(App): def build(self): self.label = Label(text="server started\n") reactor.listenTCP(8000, Ech...
def dataReceived(self, data): response = self.factory.app.handle_message(data) if response: self.transport.write(response)
identifier_body
reactor_server.py
from kivy.support import install_twisted_reactor install_twisted_reactor() from twisted.internet import reactor from twisted.internet import protocol class EchoProtocol(protocol.Protocol): def dataReceived(self, data): response = self.factory.app.handle_message(data) if response: sel...
if __name__ == '__main__': TwistedServerApp().run()
msg = "pong" if msg == "plop": msg = "kivy rocks" self.label.text += "responded: %s\n" % msg return msg
random_line_split
reactor_server.py
from kivy.support import install_twisted_reactor install_twisted_reactor() from twisted.internet import reactor from twisted.internet import protocol class EchoProtocol(protocol.Protocol): def
(self, data): response = self.factory.app.handle_message(data) if response: self.transport.write(response) class EchoFactory(protocol.Factory): protocol = EchoProtocol def __init__(self, app): self.app = app from kivy.app import App from kivy.uix.label import Label cla...
dataReceived
identifier_name
testbindingpairiterable.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/. */ // check-tidy: no specs after this line use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings...
} impl TestBindingPairIterable { fn new(global: GlobalRef) -> Root<TestBindingPairIterable> { reflect_dom_object(box TestBindingPairIterable { reflector: Reflector::new(), map: DOMRefCell::new(vec![]), }, global, TestBindingPairIterableBinding::TestBindingPairIterableWrap) ...
{ self.map.borrow().iter().nth(index as usize).map(|a| &a.0).unwrap().clone() }
identifier_body
testbindingpairiterable.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/. */ // check-tidy: no specs after this line use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings...
self.map.borrow().iter().nth(index as usize).map(|a| &a.1).unwrap().clone() } fn get_key_at_index(&self, index: u32) -> DOMString { self.map.borrow().iter().nth(index as usize).map(|a| &a.0).unwrap().clone() } } impl TestBindingPairIterable { fn new(global: GlobalRef) -> Root<TestBindin...
self.map.borrow().len() as u32 } fn get_value_at_index(&self, index: u32) -> u32 {
random_line_split
testbindingpairiterable.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/. */ // check-tidy: no specs after this line use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings...
(global: GlobalRef) -> Root<TestBindingPairIterable> { reflect_dom_object(box TestBindingPairIterable { reflector: Reflector::new(), map: DOMRefCell::new(vec![]), }, global, TestBindingPairIterableBinding::TestBindingPairIterableWrap) } pub fn Constructor(global: GlobalR...
new
identifier_name
main.rs
// // George 'papanikge' Papanikolaou 2014-2018 // tail + head = tead // // This was originally written in an ancient form of rust. // Rewritten for rust 1.22. // extern crate getopts; use getopts::Options; // use extra::getopts::{optopt, optflag, getopts}; // renamed to BufReader. but probaby do not want it // use st...
usage(&program_name); return; // No files provided. stdin() is a reader so we can do: // let mut buffer = BufferedReader::new(std::io::stdin()); // call tead here } else { println!("temp - lines: {}", lines); files[0].clone(); // call tead here } }
let lines = given.opt_str("n").or(Some(String::from(DEFAULT_LINE_NUMBER))).unwrap(); let files = given.free; if files.is_empty() {
random_line_split
main.rs
// // George 'papanikge' Papanikolaou 2014-2018 // tail + head = tead // // This was originally written in an ancient form of rust. // Rewritten for rust 1.22. // extern crate getopts; use getopts::Options; // use extra::getopts::{optopt, optflag, getopts}; // renamed to BufReader. but probaby do not want it // use st...
() { let args: Vec<String> = env::args().collect(); let program_name = args[0].clone(); let mut available = Options::new(); available.optopt("n", "lines-number", "number of lines to print [default: 5]", ""); available.optflag("v", "version", "print tead's version"); available.optflag("h", "help...
main
identifier_name
main.rs
// // George 'papanikge' Papanikolaou 2014-2018 // tail + head = tead // // This was originally written in an ancient form of rust. // Rewritten for rust 1.22. // extern crate getopts; use getopts::Options; // use extra::getopts::{optopt, optflag, getopts}; // renamed to BufReader. but probaby do not want it // use st...
let lines = given.opt_str("n").or(Some(String::from(DEFAULT_LINE_NUMBER))).unwrap(); let files = given.free; if files.is_empty() { usage(&program_name); return; // No files provided. stdin() is a reader so we can do: // let mut buffer = BufferedReader::new(std::io::stdin()...
{ println!("tead -- Version {}", VERSION); return; }
conditional_block
main.rs
// // George 'papanikge' Papanikolaou 2014-2018 // tail + head = tead // // This was originally written in an ancient form of rust. // Rewritten for rust 1.22. // extern crate getopts; use getopts::Options; // use extra::getopts::{optopt, optflag, getopts}; // renamed to BufReader. but probaby do not want it // use st...
fn main() { let args: Vec<String> = env::args().collect(); let program_name = args[0].clone(); let mut available = Options::new(); available.optopt("n", "lines-number", "number of lines to print [default: 5]", ""); available.optflag("v", "version", "print tead's version"); available.optflag("...
{ println!("Usage: {} [options]", program_name); println!("\t-n <number of lines to print>"); println!("\t-h --help"); println!("\t-v --version"); }
identifier_body
compat.py
six from django.views.generic import View try: from django.urls import ( NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ) except ImportError: from django.core.urlresolvers import ( # Will be removed in Django 2.0 ...
elif transaction.is_managed(): # Otherwise handle it explicitly if in managed mode. if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() else: # transaction not managed pass def template_render(template, context=None,...
if connection.in_atomic_block: transaction.set_rollback(True)
conditional_block
compat.py
import django from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import connection, models, transaction from django.template import Context, RequestContext, Template from django.utils import six from django.views.generic import View tr...
import inspect
random_line_split
compat.py
six from django.views.generic import View try: from django.urls import ( NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ) except ImportError: from django.core.urlresolvers import ( # Will be removed in Django 2.0 ...
def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key...
if 'default' in kwargs: if django.VERSION < (1, 9): return getattr(field, 'rel', kwargs['default']) return getattr(field, 'remote_field', kwargs['default']) if django.VERSION < (1, 9): return field.rel return field.remote_field
identifier_body
compat.py
six from django.views.generic import View try: from django.urls import ( NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ) except ImportError: from django.core.urlresolvers import ( # Will be removed in Django 2.0 ...
(field, obj): if django.VERSION < (1, 9): return field._get_val_from_obj(obj) return field.value_from_object(obj) # contrib.postgres only supported from 1.8 onwards. try: from django.contrib.postgres import fields as postgres_fields except ImportError: postgres_fields = None # JSONField is o...
value_from_object
identifier_name
server_renderer.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 {DOCUMENT} from '@angular/common'; import {DomElementSchemaRegistry} from '@angular/compiler'; import {Inject...
selectRootElement(selectorOrNode: string|any, debugInfo?: any): any { let el: any; if (typeof selectorOrNode === 'string') { el = getDOM().querySelector(this.document, selectorOrNode); if (!el) { throw new Error(`The selector "${selectorOrNode}" did not match any elements`); } } ...
getDOM().removeChild(parent, oldChild); } }
conditional_block
server_renderer.ts
/** * @license * Copyright Google Inc. All Rights Reserved.
import {DOCUMENT} from '@angular/common'; import {DomElementSchemaRegistry} from '@angular/compiler'; import {Inject, Injectable, NgZone, Renderer2, RendererFactory2, RendererStyleFlags2, RendererType2, ViewEncapsulation} from '@angular/core'; import {EventManager, ɵNAMESPACE_URIS as NAMESPACE_URIS, ɵSharedStylesHost a...
* * 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 */
random_line_split
server_renderer.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 {DOCUMENT} from '@angular/common'; import {DomElementSchemaRegistry} from '@angular/compiler'; import {Inject...
ny, name: string): void { getDOM().removeClass(el, name); } setStyle(el: any, style: string, value: any, flags: RendererStyleFlags2): void { getDOM().setStyle(el, style, value); } removeStyle(el: any, style: string, flags: RendererStyleFlags2): void { getDOM().removeStyle(el, style); } // The value...
Class(el: a
identifier_name
server_renderer.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 {DOCUMENT} from '@angular/common'; import {DomElementSchemaRegistry} from '@angular/compiler'; import {Inject...
tValue(node: any, value: string): void { getDOM().setText(node, value); } listen( target: 'document'|'window'|'body'|any, eventName: string, callback: (event: any) => boolean): () => void { checkNoSyntheticProp(eventName, 'listener'); if (typeof target === 'string') { return <() => void>thi...
checkNoSyntheticProp(name, 'property'); getDOM().setProperty(el, name, value); // Mirror property values for known HTML element properties in the attributes. // Skip `innerhtml` which is conservatively marked as an attribute for security // purposes but is not actually an attribute. const tagName = ...
identifier_body
reflected-attributes.ts
, reflected attribute name] * or * property name (if reflected attribute name is identical). * Item 1: * Array of tag names which reflect the property * * List of attributes and which elements they apply is sourced from * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes * * Commented eleme...
{ // Property has a different attribute name. addPropertyForElement(elementName, attr[0], attr[1]); }
conditional_block
reflected-attributes.ts
Array of [property name, reflected attribute name] * or * property name (if reflected attribute name is identical). * Item 1: * Array of tag names which reflect the property * * List of attributes and which elements they apply is sourced from * https://developer.mozilla.org/en-US/docs/Web/HTML/Attribut...
['charset', [/*'meta',*/ 'script']], ['checked', [/*'command',*/ 'input']], ['cite', ['blockquote', 'del', 'ins', 'q']], [['class', 'className'], ['*']], ['code', [/*'applet'*/]], ['codebase', [/*'applet'*/]], ['color', [/*'basefont',*/ 'font', 'hr']], ['cols', ['textarea']], [['colspan', 'colSpan'], ...
random_line_split
lxqt-config-cursor_pt_BR.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="pt_BR"> <context> <name>SelectWnd</name> <message> <location filename="../../../selectwnd.ui" line="14"/> <source>LXQt Mouse Theme Configuration</source> <translation>Configuração Do Tema Do Mouse</translati...
<context> <name>XCursorThemeModel</name> <message> <location filename="../../../thememodel.cpp" line="61"/> <source>Name</source> <translation>Nome</translation> </message> <message> <location filename="../../../thememodel.cpp" line="62"/> <source>Description</sou...
random_line_split
main.rs
#![feature(plugin, start)] #![no_std] #![plugin(macro_zinc)] extern crate zinc; #[zinc_main] fn
() { use zinc::drivers::chario::CharIO; use zinc::hal; use zinc::hal::pin::Gpio; use zinc::hal::stm32f1::{init, pin, usart}; // configure PLL and set it as System Clock source let pll_conf = init::PllConf { source: init::PllClockSource::PllSourceHSE(8_000_000), mult: init::PllMult:...
main
identifier_name
main.rs
#![feature(plugin, start)] #![no_std] #![plugin(macro_zinc)] extern crate zinc; #[zinc_main] fn main() { use zinc::drivers::chario::CharIO; use zinc::hal; use zinc::hal::pin::Gpio; use zinc::hal::stm32f1::{init, pin, usart}; // configure PLL and set it as System Clock source let pll_conf = init::PllConf...
usb_prescaler: init::PllUsbDiv::PllUsbDiv1p5, }; let sys_clock = init::ClockConfig { source: init::SystemClockSource::SystemClockPLL(pll_conf), ahb_prescaler: init::ClockAhbPrescaler::AhbDivNone, apb1_prescaler: init::ClockApbPrescaler::ApbDiv2, apb2_prescaler: init::ClockApbPre...
hse_prediv: init::PllHsePrediv::PllHsePrediv1,
random_line_split
main.rs
#![feature(plugin, start)] #![no_std] #![plugin(macro_zinc)] extern crate zinc; #[zinc_main] fn main()
}; sys_clock.setup(); let _pin_tx = pin::Pin::new(pin::Port::PortA, 2, pin::PinConf::OutPushPullAlt2MHz); let led1 = pin::Pin::new(pin::Port::PortC, 13, pin::PinConf::OutPushPull50MHz); led1.set_low(); let uart = usart::Usart::new(usart::UsartPeripheral::Usart2, 38400, usart::WordLen::WordLen8bits, ...
{ use zinc::drivers::chario::CharIO; use zinc::hal; use zinc::hal::pin::Gpio; use zinc::hal::stm32f1::{init, pin, usart}; // configure PLL and set it as System Clock source let pll_conf = init::PllConf { source: init::PllClockSource::PllSourceHSE(8_000_000), mult: init::PllMult::Pl...
identifier_body
gogapi.py
GOG_CLIENT_ID = "46899977096215655" GOG_CLIENT_SECRET = "9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9" CLIENT_VERSION = "1.1.24.16" # Just for their statistics DATA_VERSION="33" VERSION="11" GAME="0.9.10" SECRET="YRvdbcMfxsPSiv1dsk7h" HASH="739BAE63391829F78129E18DFF6E6307711DACB3" LOGIN_INSTRUCTIO...
(self, *args, **kwargs): return self.request("GET", *args, **kwargs) def post(self, *args, **kwargs): return self.request("POST", *args, **kwargs) def request_json(self, *args, **kwargs): resp = self.request(*args, **kwargs) if PARSE_JSON: return json.loads(resp.tex...
get
identifier_name
gogapi.py
GOG_CLIENT_ID = "46899977096215655" GOG_CLIENT_SECRET = "9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9" CLIENT_VERSION = "1.1.24.16" # Just for their statistics DATA_VERSION="33" VERSION="11" GAME="0.9.10" SECRET="YRvdbcMfxsPSiv1dsk7h" HASH="739BAE63391829F78129E18DFF6E6307711DACB3" LOGIN_INSTRUCTIO...
else: self.created = datetime.now(tz=timezone.utc) def get_data(self): token_data = { "access_token": self.access_token, "refresh_token": self.refresh_token, "expires_in": int(self.expires_in.total_seconds()), "scope": self.scope, ...
self.created = datetime.fromtimestamp( token_data["created"], tz=timezone.utc)
conditional_block
gogapi.py
GOG_CLIENT_ID = "46899977096215655" GOG_CLIENT_SECRET = "9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9" CLIENT_VERSION = "1.1.24.16" # Just for their statistics DATA_VERSION="33" VERSION="11" GAME="0.9.10" SECRET="YRvdbcMfxsPSiv1dsk7h" HASH="739BAE63391829F78129E18DFF6E6307711DACB3" LOGIN_INSTRUCTIO...
def gwent_definitions(self): return self.get_json(galaxy_url("gwent.definitions")) def gwent_definition(self, card_id): return self.get_json(galaxy_url("gwent.definition", card_id)) # Requires 'extended' scope that we don't have. def gwent_data_versions(self): return self.get_j...
def gwent_template(self, card_id): return self.get_json(galaxy_url("gwent.template", card_id))
random_line_split
gogapi.py
GOG_CLIENT_ID = "46899977096215655" GOG_CLIENT_SECRET = "9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9" CLIENT_VERSION = "1.1.24.16" # Just for their statistics DATA_VERSION="33" VERSION="11" GAME="0.9.10" SECRET="YRvdbcMfxsPSiv1dsk7h" HASH="739BAE63391829F78129E18DFF6E6307711DACB3" LOGIN_INSTRUCTIO...
def gwent_card(self, user_id=None): if user_id is None: user_id = self.token.user_id return self.get_json(galaxy_url("gwent.card", user_id, "357886761177080483")) def gwent_profile(self, user_id=None): if user_id is None: user_id = self.token.user_id re...
return self.get_json(galaxy_url("gwent.version", version))
identifier_body
test_InT01.py
""" Integration test: permit call """ import os import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') import logging import nose from nose.tools import * import inte_testutils from telewall.core.model import TelephoneNumber from telewall.core.util import sleep_until
LOG = logging.getLogger(__name__) def test_Anruf_erlauben(): u = inte_testutils.TestUtil() u.unblock_callerid(TelephoneNumber('0790000001')) call = u.make_call_to_incoming(callerid='0790000001') LOG.info('call: %s', call) sleep_until(lambda: 'Ringing' in call.get_call_states() or 'Up' in call.get...
logging.basicConfig(filename='/tmp/telewall-inte.log', level=logging.DEBUG) logging.getLogger('telewall').setLevel(logging.DEBUG)
random_line_split
test_InT01.py
""" Integration test: permit call """ import os import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') import logging import nose from nose.tools import * import inte_testutils from telewall.core.model import TelephoneNumber from telewall.core.util import sleep_until...
nose.runmodule()
conditional_block
test_InT01.py
""" Integration test: permit call """ import os import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') import logging import nose from nose.tools import * import inte_testutils from telewall.core.model import TelephoneNumber from telewall.core.util import sleep_until...
(): u = inte_testutils.TestUtil() u.unblock_callerid(TelephoneNumber('0790000001')) call = u.make_call_to_incoming(callerid='0790000001') LOG.info('call: %s', call) sleep_until(lambda: 'Ringing' in call.get_call_states() or 'Up' in call.get_call_states(), 5) call.hangup() states = call.get...
test_Anruf_erlauben
identifier_name
test_InT01.py
""" Integration test: permit call """ import os import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') import logging import nose from nose.tools import * import inte_testutils from telewall.core.model import TelephoneNumber from telewall.core.util import sleep_until...
if __name__ == '__main__': nose.runmodule()
u = inte_testutils.TestUtil() u.unblock_callerid(TelephoneNumber('0790000001')) call = u.make_call_to_incoming(callerid='0790000001') LOG.info('call: %s', call) sleep_until(lambda: 'Ringing' in call.get_call_states() or 'Up' in call.get_call_states(), 5) call.hangup() states = call.get_call_st...
identifier_body
rt_multi_threaded.rs
//! Benchmark implementation details of the threaded scheduler. These benches are //! intended to be used as a form of regression testing and not as a general //! purpose benchmark demonstrating real-world performance. use tokio::runtime::{self, Runtime}; use tokio::sync::oneshot; use bencher::{benchmark_group, bench...
(b: &mut Bencher) { const NUM_PINGS: usize = 1_000; let rt = rt(); let (done_tx, done_rx) = mpsc::sync_channel(1000); let rem = Arc::new(AtomicUsize::new(0)); b.iter(|| { let done_tx = done_tx.clone(); let rem = rem.clone(); rem.store(NUM_PINGS, Relaxed); rt.block...
ping_pong
identifier_name
rt_multi_threaded.rs
//! Benchmark implementation details of the threaded scheduler. These benches are //! intended to be used as a form of regression testing and not as a general //! purpose benchmark demonstrating real-world performance. use tokio::runtime::{self, Runtime}; use tokio::sync::oneshot; use bencher::{benchmark_group, bench...
benchmark_group!(scheduler, spawn_many, ping_pong, yield_many, chained_spawn,); benchmark_main!(scheduler);
{ runtime::Builder::new_multi_thread() .worker_threads(4) .enable_all() .build() .unwrap() }
identifier_body
rt_multi_threaded.rs
//! Benchmark implementation details of the threaded scheduler. These benches are //! intended to be used as a form of regression testing and not as a general //! purpose benchmark demonstrating real-world performance. use tokio::runtime::{self, Runtime}; use tokio::sync::oneshot; use bencher::{benchmark_group, bench...
else { tokio::spawn(async move { iter(done_tx, n - 1); }); } } let (done_tx, done_rx) = mpsc::sync_channel(1000); b.iter(move || { let done_tx = done_tx.clone(); rt.block_on(async { tokio::spawn(async move { iter...
{ done_tx.send(()).unwrap(); }
conditional_block
rt_multi_threaded.rs
//! Benchmark implementation details of the threaded scheduler. These benches are //! intended to be used as a form of regression testing and not as a general //! purpose benchmark demonstrating real-world performance. use tokio::runtime::{self, Runtime}; use tokio::sync::oneshot; use bencher::{benchmark_group, bench...
tx.send(()).unwrap(); }); } for _ in 0..TASKS { let _ = rx.recv().unwrap(); } }); } fn ping_pong(b: &mut Bencher) { const NUM_PINGS: usize = 1_000; let rt = rt(); let (done_tx, done_rx) = mpsc::sync_channel(1000); let rem = Arc::ne...
rt.spawn(async move { for _ in 0..NUM_YIELD { tokio::task::yield_now().await; }
random_line_split
websockets.service.ts
import { Injectable, Inject, EventEmitter } from '@angular/core'; import { Http } from '@angular/http'; import { APIClientService } from '../common/api-client.service'; import { AuthService } from "../auth/auth.service"; import { EventsManagerService } from "../common/events-manager.service"; import { Oauth2Service } ...
this._onConnectError.next(error); if (this.reconnectionAttempts < MAX_RETRIES) { this.reconnectionAttempts++; setTimeout(() => { this.connect(); }, 1000); } } }); } }
onFailure: (error: any) => { this._isConnected = false;
random_line_split
websockets.service.ts
import { Injectable, Inject, EventEmitter } from '@angular/core'; import { Http } from '@angular/http'; import { APIClientService } from '../common/api-client.service'; import { AuthService } from "../auth/auth.service"; import { EventsManagerService } from "../common/events-manager.service"; import { Oauth2Service } ...
send(topic: string, message: any) { if (!this.client || !this.isConnected) { throw new Error('WebSockets: not connected connected'); } let messageObject: any = new Paho.MQTT.Message(JSON.stringify(message)); messageObject.destinationName = topic; this.client.send(messageObject); } pr...
{ this._clientDisconnect = !retryable; if (this.client && this.isConnected) { this.client.disconnect(); } }
identifier_body
websockets.service.ts
import { Injectable, Inject, EventEmitter } from '@angular/core'; import { Http } from '@angular/http'; import { APIClientService } from '../common/api-client.service'; import { AuthService } from "../auth/auth.service"; import { EventsManagerService } from "../common/events-manager.service"; import { Oauth2Service } ...
(): Observable<any> { return this._onPairingsMessage.asObservable(); } get onEventsMessage(): Observable<any> { return this._onEventsMessage.asObservable(); } get onReady(): Observable<any> { return this._onReady.asObservable(); } constructor( http: HttpInterceptor, authService: AuthServi...
onPairingsMessage
identifier_name
websockets.service.ts
import { Injectable, Inject, EventEmitter } from '@angular/core'; import { Http } from '@angular/http'; import { APIClientService } from '../common/api-client.service'; import { AuthService } from "../auth/auth.service"; import { EventsManagerService } from "../common/events-manager.service"; import { Oauth2Service } ...
}, onFailure: (error: any) => { this._isConnected = false; this._onConnectError.next(error); if (this.reconnectionAttempts < MAX_RETRIES) { this.reconnectionAttempts++; setTimeout(() => { this.connect(); }, 1000); } } });...
{ let topic = topics[i]; this.client.subscribe(topic, { onSuccess: () => { this._onSubscribe.next(topic); if (i >= topics.length - 1) { this._onReady.next({}); } } }); }
conditional_block
mustache.d.ts
// Type definitions for Mustache 0.8.2 // Project: https://github.com/janl/mustache.js // Definitions by: Mark Ashley Bell <https://github.com/markashleybell/> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface MustacheScanner { string: string; tail: string; pos: number; eos(): ...
Scanner: MustacheScanner; Context: MustacheContext; Writer: MustacheWriter; escape: any; clearCache(): MustacheWriter; parse(template: string, tags?: any): any; render(template: string, view: any, partials?: any): string; to_html(template: string, view: any, partials?: any, send?: any):...
name: string; version: string; tags: string;
random_line_split
Scroll.js
/** * @private */ Ext.define('Ext.util.sizemonitor.Scroll', { extend: 'Ext.util.sizemonitor.Abstract', getElementConfig: function() { return { reference: 'detectorsContainer', classList: [Ext.baseCSSPrefix + 'size-monitors', 'scroll'], children: [ ...
bindListeners: function(bind) { var method = bind ? 'addEventListener' : 'removeEventListener'; this.expandMonitor[method]('scroll', this.onScroll, true); this.shrinkMonitor[method]('scroll', this.onScroll, true); }, forceRefresh: function() { Ext.TaskQueue.requestRead('re...
},
random_line_split
Scroll.js
/** * @private */ Ext.define('Ext.util.sizemonitor.Scroll', { extend: 'Ext.util.sizemonitor.Abstract', getElementConfig: function() { return { reference: 'detectorsContainer', classList: [Ext.baseCSSPrefix + 'size-monitors', 'scroll'], children: [ ...
if (shrinkMonitor && !shrinkMonitor.isDestroyed) { shrinkMonitor.scrollLeft = end; shrinkMonitor.scrollTop = end; } } });
{ expandMonitor.scrollLeft = end; expandMonitor.scrollTop = end; }
conditional_block
deriving-zero.rs
// Copyright 2012-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-MI...
} } } #[deriving(Zero)] struct Vector3<T> { x: T, y: T, z: T, } impl<T: Add<T, T>> Add<Vector3<T>, Vector3<T>> for Vector3<T> { fn add(&self, other: &Vector3<T>) -> Vector3<T> { Vector3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, ...
{ Vector2(*x0 + *x1, *y0 + *y1) }
conditional_block
deriving-zero.rs
// Copyright 2012-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-MI...
<T> { x: Vector2<T>, y: Vector2<T>, z: Vector2<T>, } impl<T: Add<T, T>> Add<Matrix3x2<T>, Matrix3x2<T>> for Matrix3x2<T> { fn add(&self, other: &Matrix3x2<T>) -> Matrix3x2<T> { Matrix3x2 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, ...
Matrix3x2
identifier_name
deriving-zero.rs
// Copyright 2012-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-MI...
let _: Matrix3x2<u8> = Zero::zero(); }
random_line_split
deriving-zero.rs
// Copyright 2012-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-MI...
} #[deriving(Zero)] struct Vector3<T> { x: T, y: T, z: T, } impl<T: Add<T, T>> Add<Vector3<T>, Vector3<T>> for Vector3<T> { fn add(&self, other: &Vector3<T>) -> Vector3<T> { Vector3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } } ...
{ match (self, other) { (&Vector2(ref x0, ref y0), &Vector2(ref x1, ref y1)) => { Vector2(*x0 + *x1, *y0 + *y1) } } }
identifier_body
netutil.py
as e: if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return raise callback(connection, address) io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ) def is_valid_ip(ip): """Returns true if the given string is a well-formed IP addr...
if key == 'commonName': if _dnsname_to_pat(value).match(hostname): return dnsnames.append(value)
conditional_block
netutil.py
backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. """ sockets = [] if address == "": address = None if not socket.has_ipv6 and fa...
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None): """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple...
@classmethod def configurable_default(cls): return BlockingResolver
random_line_split
netutil.py
backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. """ sockets = [] if address == "": address = None if not socket.has_ipv6 and fa...
io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ) def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, ...
while True: try: connection, address = sock.accept() except socket.error as e: if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN): return raise callback(connection, address)
identifier_body
netutil.py
(file) except OSError as err: if err.errno != errno.ENOENT: raise else: if stat.S_ISSOCK(st.st_mode): os.remove(file) else: raise ValueError("File %s exists and is not a socket", file) sock.bind(file) os....
ssl_match_hostname
identifier_name
test_brocade_l3_plugin.py
# Copyright (c) 2014 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. ...
random_line_split
test_brocade_l3_plugin.py
# Copyright (c) 2014 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 agreed to ...
(test_l3.TestL3NatBasePlugin): def setUp(self): def mocked_brocade_init(self): LOG.debug("brocadeSVIPlugin::mocked_brocade_init()") self._switch = {'address': cfg.CONF.ml2_brocade.address, 'username': cfg.CONF.ml2_brocade.username, ...
BrocadeSVIPlugin_TestCases
identifier_name
test_brocade_l3_plugin.py
# Copyright (c) 2014 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 agreed to ...
class TestBrocadeSVINatBase(test_l3.L3NatExtensionTestCase, BrocadeSVIPlugin_TestCases): pass
def setUp(self): def mocked_brocade_init(self): LOG.debug("brocadeSVIPlugin::mocked_brocade_init()") self._switch = {'address': cfg.CONF.ml2_brocade.address, 'username': cfg.CONF.ml2_brocade.username, 'password': cfg.CONF.ml2_broc...
identifier_body
change_healthcare_desktop_icons.py
import frappe from frappe import _ change_icons_map = [ { "module_name": "Patient", "color": "#6BE273", "icon": "fa fa-user", "doctype": "Patient", "type": "link", "link": "List/Patient", "label": _("Patient") }, { "module_name": "Patient Encounter", "color": "#2ecc71", "icon": "fa fa-stethoscop...
(): doctypes = ["patient", "patient_encounter", "healthcare_practitioner", "patient_appointment", "lab_test"] for doctype in doctypes: frappe.reload_doc("healthcare", "doctype", doctype) for spec in change_icons_map: frappe.db.sql(""" delete from `tabDesktop Icon` where _doctype = '{0}' """.format(spec...
change_healthcare_desktop_icons
identifier_name
change_healthcare_desktop_icons.py
import frappe from frappe import _ change_icons_map = [ { "module_name": "Patient", "color": "#6BE273", "icon": "fa fa-user", "doctype": "Patient", "type": "link", "link": "List/Patient", "label": _("Patient") }, { "module_name": "Patient Encounter", "color": "#2ecc71", "icon": "fa fa-stethoscop...
desktop_icon.link = spec['link'] desktop_icon.save(ignore_permissions=True) frappe.db.sql(""" delete from `tabDesktop Icon` where module_name = 'Healthcare' and type = 'module' """) desktop_icon = frappe.new_doc("Desktop Icon") desktop_icon.hidden = 1 desktop_icon.standard = 1 desktop_icon.icon = "fa fa...
doctypes = ["patient", "patient_encounter", "healthcare_practitioner", "patient_appointment", "lab_test"] for doctype in doctypes: frappe.reload_doc("healthcare", "doctype", doctype) for spec in change_icons_map: frappe.db.sql(""" delete from `tabDesktop Icon` where _doctype = '{0}' """.format(spec['doc...
identifier_body
change_healthcare_desktop_icons.py
import frappe from frappe import _ change_icons_map = [ { "module_name": "Patient", "color": "#6BE273", "icon": "fa fa-user", "doctype": "Patient", "type": "link", "link": "List/Patient", "label": _("Patient") }, { "module_name": "Patient Encounter", "color": "#2ecc71", "icon": "fa fa-stethoscop...
frappe.db.sql(""" delete from `tabDesktop Icon` where module_name = 'Healthcare' and type = 'module' """) desktop_icon = frappe.new_doc("Desktop Icon") desktop_icon.hidden = 1 desktop_icon.standard = 1 desktop_icon.icon = "fa fa-heartbeat" desktop_icon.color = "#FF888B" desktop_icon.module_name = "Health...
frappe.db.sql(""" delete from `tabDesktop Icon` where _doctype = '{0}' """.format(spec['doctype'])) desktop_icon = frappe.new_doc("Desktop Icon") desktop_icon.hidden = 1 desktop_icon.standard = 1 desktop_icon.icon = spec['icon'] desktop_icon.color = spec['color'] desktop_icon.module_name = spec['mo...
conditional_block
change_healthcare_desktop_icons.py
import frappe from frappe import _ change_icons_map = [ { "module_name": "Patient", "color": "#6BE273", "icon": "fa fa-user", "doctype": "Patient", "type": "link", "link": "List/Patient", "label": _("Patient") }, { "module_name": "Patient Encounter", "color": "#2ecc71", "icon": "fa fa-stethoscop...
desktop_icon.standard = 1 desktop_icon.icon = "fa fa-heartbeat" desktop_icon.color = "#FF888B" desktop_icon.module_name = "Healthcare" desktop_icon.label = _("Healthcare") desktop_icon.app = "erpnext" desktop_icon.type = 'module' desktop_icon.save(ignore_permissions=True)
random_line_split
Footer.tsx
import { FC } from "react"; import { formatShortDate } from "../utils/dates"; import { MaisOuMenos } from "./Logos"; interface FooterProps { startedOn: string | Date; total: number; } export const Footer: FC<FooterProps> = ({ startedOn, total }) => ( <footer className="footer">
<div className="footer__text"> <p> A simple breakdown of {total} workouts since{" "} {formatShortDate(startedOn)} using data from{" "} <a href="https://stronglifts.com/5x5/" target="_blank"> Stronglifts 5x5 </a> . </p> </div> <a href="http://mai...
random_line_split
commonBubble.js
import Bubble from './bubble'; import * as types from'../../../common/constants'; class
extends Bubble { constructor({ context, levelConfig }) { super(); this.context = context; this.radius = Math.floor(Math.random() * 10) + 5; this.maxY = types.CANVAS_HEIGHT - levelConfig.WATER_BORDER_BOTTOM - this.radius; this.minY = levelConfig.WATER_BORDER_TOP + this.radius; this.x = types.O...
CommonBubble
identifier_name
commonBubble.js
import Bubble from './bubble'; import * as types from'../../../common/constants'; class CommonBubble extends Bubble { constructor({ context, levelConfig })
} export default (data) => { const random = Math.floor(Math.random() * 100) + 1; return (random < 5) ? new CommonBubble(data) : null ; };
{ super(); this.context = context; this.radius = Math.floor(Math.random() * 10) + 5; this.maxY = types.CANVAS_HEIGHT - levelConfig.WATER_BORDER_BOTTOM - this.radius; this.minY = levelConfig.WATER_BORDER_TOP + this.radius; this.x = types.OBJECT_INIT_X; this.y = Math.floor(Math.random() * (thi...
identifier_body
commonBubble.js
import Bubble from './bubble'; import * as types from'../../../common/constants'; class CommonBubble extends Bubble { constructor({ context, levelConfig }) { super(); this.context = context; this.radius = Math.floor(Math.random() * 10) + 5; this.maxY = types.CANVAS_HEIGHT - levelConfig.WATER_BORDER_B...
this.xDirection = 'left'; this.yDirection = null; this.borderColor = 'black'; this.background = 'white'; this.canChangeDirection = true; } } export default (data) => { const random = Math.floor(Math.random() * 100) + 1; return (random < 5) ? new CommonBubble(data) : null ; };
this.y = Math.floor(Math.random() * (this.maxY - this.minY + 1) + this.minY); this.xSpeed = Math.floor(Math.random() * 3) + 1; this.ySpeed = Math.floor(Math.random() * 2) + 1;
random_line_split
translation.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
######################################################################### from modeltranslation.translator import translator, TranslationOptions from geonode.layers.models import Layer class LayerTranslationOptions(TranslationOptions): fields = ( 'title', 'abstract', 'purpose', 'c...
#
random_line_split
translation.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
translator.register(Layer, LayerTranslationOptions)
fields = ( 'title', 'abstract', 'purpose', 'constraints_other', 'supplemental_information', 'data_quality_statement', )
identifier_body
translation.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
(TranslationOptions): fields = ( 'title', 'abstract', 'purpose', 'constraints_other', 'supplemental_information', 'data_quality_statement', ) translator.register(Layer, LayerTranslationOptions)
LayerTranslationOptions
identifier_name
persistent_liveness_storage.rs
LivenessStorageData; /// Persist the highest timeout certificate for improved liveness - proof for other replicas /// to jump to this round fn save_highest_timeout_cert(&self, highest_timeout_cert: TimeoutCertificate) -> Result<()>; /// Retrieve a epoch change proof for SafetyRules so it can instanti...
fn prune_tree(&self, block_ids: Vec<HashValue>) -> Result<()> { if !block_ids.is_empty() { // quorum certs that certified the block_ids will get removed self.db.delete_blocks_and_quorum_certificates(block_ids)?; } Ok(()) } fn save_vote(&self, vote: &Vote) -...
{ let mut trace_batch = vec![]; for block in blocks.iter() { trace_code_block!("consensusdb::save_tree", {"block", block.id()}, trace_batch); } Ok(self .db .save_blocks_and_quorum_certificates(blocks, quorum_certs)?) }
identifier_body
persistent_liveness_storage.rs
LivenessStorageData; /// Persist the highest timeout certificate for improved liveness - proof for other replicas /// to jump to this round fn save_highest_timeout_cert(&self, highest_timeout_cert: TimeoutCertificate) -> Result<()>; /// Retrieve a epoch change proof for SafetyRules so it can instanti...
} pub fn root_block(&self) -> &Block { &self.root.0 } pub fn last_vote(&self) -> Option<Vote> { self.last_vote.clone() } pub fn take(self) -> (RootInfo, RootMetadata, Vec<Block>, Vec<QuorumCert>) { ( self.root, self.root_metadata, se...
}, })
random_line_split
persistent_liveness_storage.rs
LivenessStorageData; /// Persist the highest timeout certificate for improved liveness - proof for other replicas /// to jump to this round fn save_highest_timeout_cert(&self, highest_timeout_cert: TimeoutCertificate) -> Result<()>; /// Retrieve a epoch change proof for SafetyRules so it can instanti...
Ok(()) } fn save_vote(&self, vote: &Vote) -> Result<()> {
{ // quorum certs that certified the block_ids will get removed self.db.delete_blocks_and_quorum_certificates(block_ids)?; }
conditional_block
persistent_liveness_storage.rs
LivenessStorageData; /// Persist the highest timeout certificate for improved liveness - proof for other replicas /// to jump to this round fn save_highest_timeout_cert(&self, highest_timeout_cert: TimeoutCertificate) -> Result<()>; /// Retrieve a epoch change proof for SafetyRules so it can instanti...
(&self) -> Round { self.storage_ledger.round() } /// Finds the root (last committed block) and returns the root block, the QC to the root block /// and the ledger info for the root block, return an error if it can not be found. /// /// We guarantee that the block corresponding to the storag...
commit_round
identifier_name