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
mtmap.rs
#[deriving(Clone)] #[deriving(ToStr)] type LinkedList = Option<~Node>; #[deriving(Clone)] struct Node { val: int, tail: LinkedList } trait Length { fn length(&self) -> int; } #[allow(dead_code)] fn length(p: LinkedList) -> int { match p { None => { 0 } Some(node) => { 1 + length(node.tail) }...
} } } fn expensive_inc(n: int) -> int { let mut a = 1; println!("starting inc: {:d}", n); for _ in range(0, 10000) { for _ in range(0, 1000000) { a = a + 1; } } println!("finished inc: {:d} ({:d})", n, a); n + 1 } fn main() { let mut l10 : LinkedLi...
{ let (port, chan) : (Port<int>, Chan<int>) = Chan::new(); let val = current.val; // Can't use current inside task! spawn(proc() { chan.send(f(val)); }); current.tail.mapr(f); // Make sure to do this first, so we're not waiting for recv! curren...
conditional_block
mtmap.rs
#[deriving(Clone)] #[deriving(ToStr)] type LinkedList = Option<~Node>; #[deriving(Clone)] struct Node { val: int, tail: LinkedList }
trait Length { fn length(&self) -> int; } #[allow(dead_code)] fn length(p: LinkedList) -> int { match p { None => { 0 } Some(node) => { 1 + length(node.tail) } } } impl Length for LinkedList { fn length(&self) -> int { match self { &Some(ref node) => { 1 + node.tail.length() } ...
random_line_split
objType.spec.ts
import objType from '../src/objType'; describe('objType', () => { it('should determine the correct type', () => { expect(objType({})).toBe('Object'); expect(objType([])).toBe('Array'); expect(objType(new Map())).toBe('Map'); expect(objType(new WeakMap())).toBe('WeakMap'); expect(objType(new Set()...
expect(objType('')).toBe('String'); expect(objType(true)).toBe('Boolean'); expect(objType(null)).toBe('Null'); expect(objType(undefined)).toBe('Undefined'); expect(objType(10)).toBe('Number'); expect(objType(Symbol.iterator)).toBe('Symbol'); }); });
objType(() => { // noop }) ).toBe('Function');
random_line_split
prework--numpy-ultraquick-tutorial.py
""" ## NumPy UltraQuick Tutorial [source](https://colab.research.google.com/github/google/eng-edu/blob/main/ml/cc/exercises/numpy_ultraquick_tutorial.ipynb?utm_source=mlcc) > create/manipulate vectors and matrices """ ## import module as import numpy as np ## populate array with specific numbers ### 'np.array' to...
* modify each value assigned to 'label' by adding different random float between -2/+2 without 'broadcasting' instead create noise array having same dimension """ noise = (np.random.random([15]) * 4) print(noise) label = label + noise print(label)
""" Task.2 Add some noise to the dataset to mae dataset realistic; insert random noise to each element of 'label' array
random_line_split
urls.py
from django.conf.urls.defaults import *
import frontend.views as frontend_views import codewiki.views import codewiki.viewsuml from django.contrib.syndication.views import feed as feed_view from django.views.generic import date_based, list_detail from django.views.generic.simple import direct_to_template from django.contrib import admin import dja...
random_line_split
vector_utils.py
import numpy as np from scipy.sparse import csr_matrix, coo_matrix def save_sparse_csr(filename,array): np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape ) def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix(( loader['...
def confusion_matrix(y_pred, y_true, labels=None): # Send only filtered y values. y_pred, y_true = np.array(y_pred).flatten().squeeze(), np.array(y_true).flatten().squeeze() if labels is None: labels = list(set(y_true).union(set(y_pred))) n_labels = len(labels) print "[%s] labels = %s" % (...
return Y.argmax(axis=len(Y.shape) - 1)
identifier_body
vector_utils.py
import numpy as np from scipy.sparse import csr_matrix, coo_matrix def
(filename,array): np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape ) def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix(( loader['data'], loader['indices'], loader['indptr']), shape = loader['...
save_sparse_csr
identifier_name
vector_utils.py
import numpy as np
def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix(( loader['data'], loader['indices'], loader['indptr']), shape = loader['shape']) def save_arr_assparse(filename, array): return save_sparse_csr(filename, csr_matrix(array)) def load_sparse_asarr(filename...
from scipy.sparse import csr_matrix, coo_matrix def save_sparse_csr(filename,array): np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape )
random_line_split
vector_utils.py
import numpy as np from scipy.sparse import csr_matrix, coo_matrix def save_sparse_csr(filename,array): np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape ) def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix(( loader['...
return X_vec def onehot_to_idxarr(Y): return Y.argmax(axis=len(Y.shape) - 1) def confusion_matrix(y_pred, y_true, labels=None): # Send only filtered y values. y_pred, y_true = np.array(y_pred).flatten().squeeze(), np.array(y_true).flatten().squeeze() if labels is None: labels = list(set(y...
for j in xrange(X_vec.shape[1]): for k in xrange(X_vec.shape[2]): try: X_vec[i,j,k,X[i,j,k]] = 1 except: print X_vec.shape, X.shape, (i, j, k), X[i,j,k] raise Exception
conditional_block
libvirt.py
= libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST _NET_UPDATE_FLAGS = ( libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG | libvirt.VIR_NETWORK_UPDATE_AFFECT_LIVE ) _IMAGE_OS_TABLE = { 'centos-6': 'centos6.5', # TODO: fix versions 'centos-7.1': 'centos7.0', # TODO: fix versions 'centos-7.2': 'centos7.0', # TOD...
_del_network_host
identifier_name
libvirt.py
= '{0}-{1}-{2}'.format(vmid, template, kwargs['arch']) image = '{0}.qcow2'.format(name) conn = self._libvirt_open() pool = conn.storagePoolLookupByName(kwargs['pool']) net = conn.networkLookupByName(kwargs['network']) repository = _get_pool_path(pool) path = os.path.jo...
for x in xmldesc.iterfind('./ip/dhcp/host'): yield {'name': x.get('name'), 'mac': x.get('mac'),
random_line_split
libvirt.py
' BASE_FORMAT = 'qcow2' BASE_SIZE = '20G' INSTANCE_DEFAULTS = { 'cpus': 2, 'memory': 1024, 'arch': 'x86_64', 'network': DEFAULT_NET, 'pool': DEFAULT_POOL, 'password': None, } _NET_ADD_LAST = libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST _NET_MODIFY = libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY _N...
def _create_base(template, arch, repository): name = '_{0}-{1}.{2}'.format(template, arch, BASE_FORMAT) path = os.path.join(repository, name) if not os.path.exists(path): execute(('virt-builder', template, '-o', path, '--size', BASE_SIZE, '--for...
try: return _IMAGE_OS_TABLE[image] except KeyError: return image.replace('-', '')
identifier_body
libvirt.py
' BASE_FORMAT = 'qcow2' BASE_SIZE = '20G' INSTANCE_DEFAULTS = { 'cpus': 2, 'memory': 1024, 'arch': 'x86_64', 'network': DEFAULT_NET, 'pool': DEFAULT_POOL, 'password': None, } _NET_ADD_LAST = libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_LAST _NET_MODIFY = libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY _N...
addresses = set() for name, macs in netmacs.iteritems(): net = conn.networkLookupByName(name) for lease in _get_network_dhcp_leases(net): if lease['mac'] in macs: addresses.add(lease['ip']) return list(addresses) def instance_...
netmacs = {k: v for k, v in netmacs.iteritems()}
conditional_block
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
(kind: Option<HidKind>) -> Result<Vec<UsbDeviceInfo>> { let udev = Context::new().expect("Failed to create udev context"); let mut iter = Enumerator::new(&udev)?; iter.match_subsystem("usb")?; let devtype = if kind.is_some() { "usb_interface" } else { "usb_device" }; iter.match_property("DEVTYPE", d...
list_devices
identifier_name
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
} } } else { // device not connected match dev.binding { UsbBinding::ById(id) => { let info = UsbDeviceInfo::from_id(id); println!("[{}]\t{} (Not Connected)", i, info); ...
{ let infos = list_devices(None).expect("Can't read connected USB devices"); loop { println!("You have currently selected the following usb devices: "); let mut last = 0; for (i, dev) in usb_devices.iter().cloned().enumerate() { if let Some(pos) = infos.iter().position(|info...
identifier_body
usb.rs
use std::io::Write; use libudev::{Result, Context, Enumerator}; use common::config::{self, MachineConfig, UsbId, UsbPort, UsbBinding, UsbDevice}; use common::usb_device::{UsbDevice as UsbDeviceInfo, Binding}; use ask; use wizard; #[derive(Clone, Copy, PartialEq, Eq)] pub enum HidKind { Mouse, Keyboard, } pu...
println!(); true } /// Lets the user remove (some) of given devices /// /// This modifies the passed list. fn remove(usb_devices: &mut Vec<UsbDevice>) { let infos = list_devices(None).expect("Can't read connected USB devices"); loop { println!("You have currently selected the following usb dev...
}).expect("Cannot write udev rules");
random_line_split
plugin.js
/** * Tom Select v1.3.0 * Licensed under the Apache License, Version 2.0 (the "License"); */ import TomSelect from '../../tom-select.js'; import getSettings from '../../getSettings.js'; import { addEvent } from '../../utils.js'; /** * Plugin: "change_listener" (Tom Select) * Copyright (c) contributors * * License...
* 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. * */ TomSelect.define('change_listener', function (options) { var self = this; var ch...
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under
random_line_split
plugin.js
/** * Tom Select v1.3.0 * Licensed under the Apache License, Version 2.0 (the "License"); */ import TomSelect from '../../tom-select.js'; import getSettings from '../../getSettings.js'; import { addEvent } from '../../utils.js'; /** * Plugin: "change_listener" (Tom Select) * Copyright (c) contributors * * License...
changed = true; var settings = getSettings(self.input, {}); self.setupOptions(settings.options, settings.optgroups); self.setValue(settings.items); }); }); //# sourceMappingURL=plugin.js.map
{ changed = false; return; }
conditional_block
cached_db.py
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions...
(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete(self.session_key) self.create()
flush
identifier_name
cached_db.py
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions...
return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.cache_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(session...
def exists(self, session_key): if (KEY_PREFIX + session_key) in cache: return True
random_line_split
cached_db.py
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions...
def exists(self, session_key): if (KEY_PREFIX + session_key) in cache: return True return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.cache_key, self._session, settings....
try: data = cache.get(self.cache_key, None) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. data = None if data is None: data = super(SessionStore, se...
identifier_body
cached_db.py
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions...
return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.cache_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(sessio...
return True
conditional_block
virtual_machine_scale_set_managed_disk_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
class VirtualMachineScaleSetManagedDiskParameters(Model): """Describes the parameters of a ScaleSet managed disk. :param storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS or Premium_LRS. Possible values include: 'Standard_LRS', 'Premium_L...
from msrest.serialization import Model
random_line_split
virtual_machine_scale_set_managed_disk_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(self, storage_account_type=None): super(VirtualMachineScaleSetManagedDiskParameters, self).__init__() self.storage_account_type = storage_account_type
__init__
identifier_name
virtual_machine_scale_set_managed_disk_parameters.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
"""Describes the parameters of a ScaleSet managed disk. :param storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS or Premium_LRS. Possible values include: 'Standard_LRS', 'Premium_LRS' :type storage_account_type: str or ~azure.mgmt.co...
identifier_body
test_generators.py
#-*-coding:utf-8-*- """ @package bsemantic.tests.test_generators @brief tests for bsemantic.generators @author Sebastian Thiel @copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) """ from __future__ import unicode_literals from butility.future import str __all__ = [] # W0614 unused ...
assert root.apply_format(data).format_result is None, "It should not throw if it cannot resolve the key" data = self.base_data() assert root.apply_format(DictObject(data)).format_result == self.fs_root fmt_data = root.format_data() assert len(fmt_data) == 1 and isinstance(fmt_dat...
__slots__ = () def test_formatting(self): """Test basic node formatting""" tree = ElementNodeTree.new('root', self.path_rule_data, element_node_type=StringFormatNode) root = tree.root_node() assert isinstance(root, StringFormatNode) assert isinstance(root.format_string(), s...
identifier_body
test_generators.py
#-*-coding:utf-8-*- """ @package bsemantic.tests.test_generators @brief tests for bsemantic.generators @author Sebastian Thiel @copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) """ from __future__ import unicode_literals from butility.future import str __all__ = [] # W0614 unused ...
# end for each nlist assert len(names) == len(snode_lists), "expected unique path names" # end class TestGenerators
nlist_string = nlist.to_string() names.add(nlist_string) # should have the same result, as the data is exactly the same assert nlist.apply_format(data).to_string() == nlist_string # also we assume that we don't get short lists, as we return the longest ones only ...
conditional_block
test_generators.py
#-*-coding:utf-8-*- """ @package bsemantic.tests.test_generators @brief tests for bsemantic.generators @author Sebastian Thiel @copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) """ from __future__ import unicode_literals from butility.future import str __all__ = [] # W0614 unused ...
assert root.format_result is None, "default result should be None" assert not root.format_data() assert root.apply_format(dict()).format_result is None, "Should have no result if substitution failed" assert not root.format_data() data = dict(project='something') assert r...
random_line_split
test_generators.py
#-*-coding:utf-8-*- """ @package bsemantic.tests.test_generators @brief tests for bsemantic.generators @author Sebastian Thiel @copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) """ from __future__ import unicode_literals from butility.future import str __all__ = [] # W0614 unused ...
(Test): __slots__ = () def test_formatting(self): """Test basic node formatting""" tree = ElementNodeTree.new('root', self.path_rule_data, element_node_type=StringFormatNode) root = tree.root_node() assert isinstance(root, StringFormatNode) assert isinstance(root.format...
TestGenerators
identifier_name
pipes.ts
import { Pipe, PipeTransform } from '@angular/core'; function isUndefined(value: any) { return typeof value === 'undefined'; } function extractDeepPropertyByMapKey(obj: any, map: string): any { const keys = map.split('.'); const key = keys.shift(); return keys.reduce((prop: any, key: string) => { return ...
private static simpleSort(a: any, b: any) { return isString(a) && isString(b) ? a.toLowerCase().localeCompare(b.toLowerCase()) : a - b; } private static orderCompare(prop: string, asc: boolean, a: any, b: any) { const first = extractDeepPropertyByMapKey(a, prop); const second = extractD...
{ if (!Array.isArray(input)) { return input; } const out = [...input]; const [prop, asc, sign] = SortCardsPipe.extractFromConfig(config); return out.sort(SortCardsPipe.orderCompare.bind(this, prop, asc)); }
identifier_body
pipes.ts
import { Pipe, PipeTransform } from '@angular/core'; function isUndefined(value: any) { return typeof value === 'undefined'; } function extractDeepPropertyByMapKey(obj: any, map: string): any { const keys = map.split('.'); const key = keys.shift(); return keys.reduce((prop: any, key: string) => { return ...
return asc ? first - second : second - first; } private static extractFromConfig(config: any) { const sign = config.substr(0, 1); const prop = config.replace(/^[-+]/, ''); const asc = sign !== '-'; return [prop, asc, sign]; } }
{ const pos = first.toLowerCase().localeCompare(second.toLowerCase()); return asc ? pos : -pos; }
conditional_block
pipes.ts
import { Pipe, PipeTransform } from '@angular/core'; function isUndefined(value: any) { return typeof value === 'undefined'; } function extractDeepPropertyByMapKey(obj: any, map: string): any { const keys = map.split('.'); const key = keys.shift(); return keys.reduce((prop: any, key: string) => { return ...
(input: any, config: any): any[] { if (!Array.isArray(input)) { return input; } const out = [...input]; const [prop, asc, sign] = SortCardsPipe.extractFromConfig(config); return out.sort(SortCardsPipe.orderCompare.bind(this, prop, asc)); } private static simpleSort(a: any, b: any) { ...
transform
identifier_name
pipes.ts
import { Pipe, PipeTransform } from '@angular/core'; function isUndefined(value: any) { return typeof value === 'undefined'; } function extractDeepPropertyByMapKey(obj: any, map: string): any { const keys = map.split('.'); const key = keys.shift(); return keys.reduce((prop: any, key: string) => { return ...
return asc ? first - second : second - first; } private static extractFromConfig(config: any) { const sign = config.substr(0, 1); const prop = config.replace(/^[-+]/, ''); const asc = sign !== '-'; return [prop, asc, sign]; } }
return asc ? pos : -pos; }
random_line_split
token.rs
//! Traits and enums dealing with Tokenization of printf Format String #[allow(unused_must_use)] use std::iter::Peekable; use std::str::Chars; use std::slice::Iter; use itertools::PutBackN; // A token object is an object that can print the expected output // of a contiguous segment of the format string, and
} // A tokenizer object is an object that takes an iterator // at a position in a format string, and sees whether // it can return a token of a type it knows how to produce // if so, return the token, move the iterator past the // format string text the token represents, and if an // argument is used move the argument...
// requires at most 1 argusegment pub trait Token { fn print(&self, args: &mut Peekable<Iter<String>>);
random_line_split
group.ts
/// <reference path="../../../app/scripts/controllers/group.ts" /> /// <reference path="../../../typings/angularjs/angular-mocks.d.ts" /> /// <reference path="../../mock/services/get-groups-for-user.ts" />
'use strict'; module labsFrontendApp { describe('Controller: GroupCtrl', () => { // load the controller's module var groupCtrl:GroupCtrl; var rootScope:ng.IRootScopeService; var groupsService: UserGroups; var scope:GroupScope = { currentGroup: undefined, ...
/// <reference path="../../mock/services/jwt-token-decoder.ts" />
random_line_split
output.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { DOMWidgetModel, DOMWidgetView } from 'jupyter-js-widgets'; import { IDisposable } from '@phosphor/disposable'; import { Panel, Widget } from '@phosphor/widgets'; import { WidgetManager } from '....
import * as _ from 'underscore'; import * as $ from 'jquery'; export class OutputModel extends DOMWidgetModel { defaults() { return _.extend(super.defaults(), { _model_name: 'OutputModel', _view_name: 'OutputView', msg_id: '' }); } initialize(attributes: any, options: any) { supe...
import { KernelMessage } from '@jupyterlab/services';
random_line_split
output.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { DOMWidgetModel, DOMWidgetView } from 'jupyter-js-widgets'; import { IDisposable } from '@phosphor/disposable'; import { Panel, Widget } from '@phosphor/widgets'; import { WidgetManager } from '....
() { this._outputView.dispose(); return super.remove(); } model: OutputModel; _outputView: OutputAreaWidget; pWidget: Panel }
remove
identifier_name
output.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { DOMWidgetModel, DOMWidgetView } from 'jupyter-js-widgets'; import { IDisposable } from '@phosphor/disposable'; import { Panel, Widget } from '@phosphor/widgets'; import { WidgetManager } from '....
model: OutputModel; _outputView: OutputAreaWidget; pWidget: Panel }
{ this._outputView.dispose(); return super.remove(); }
identifier_body
secret.js
const Data = {}; Data.properties = {} const SIXTEEN_COLORS = [ '#F0F0F0', 'silver', 'gray', 'black', 'red', 'maroon', 'yellow', 'olive', 'lime', 'green', 'aqua', 'teal', 'blue', 'navy', 'fuschia', 'purple' ] const SIXTEEN_GRAYS = [ '#000', '#111', '#222', '#333', '#444', '#555', '#666', '#777', '#888', '#999...
this.revealBottom = this.elementBottom(this.reveal) this.appendInitialPaddingRows() } Secret.shouldUpdate = function(timestamp) { return (((timestamp - this.lastUpdateAt) / 1000) > this.UPDATE_AT_LEAST_EVERY) && (! this.updating) } Secret.elementBottom = function(element) { return element.offset().top ...
Secret.lastUpdateAt = 0 Secret.init = function() { this.reveal = $('#reveal')
random_line_split
secret.js
const Data = {}; Data.properties = {} const SIXTEEN_COLORS = [ '#F0F0F0', 'silver', 'gray', 'black', 'red', 'maroon', 'yellow', 'olive', 'lime', 'green', 'aqua', 'teal', 'blue', 'navy', 'fuschia', 'purple' ] const SIXTEEN_GRAYS = [ '#000', '#111', '#222', '#333', '#444', '#555', '#666', '#777', '#888', '#999...
)
conditional_block
translation.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS language="cs_CZ" version="2.0"> <context> <name>design/admin/popupmenu</name> <message> <source>Upload multiple files</source> <translation>Nahrát více souborů naráz</translation> </message> </context> <context> <name>extension/ezm...
<translation>Vybrat soubory ke hromadnému nahrátí</translation> </message> <message> <source>All files received.</source> <translation>Všechny soubory byly přijaty.</translation> </message> <message> <source>Thumbnail created.</source> <translation>Náhled souboru ...
<source>The files are uploaded to</source> <translation>Soubory budou nahrány do uzlu</translation> </message> <message> <source>Select files</source>
random_line_split
sign-up.component.ts
import { Component, OnInit } from '@angular/core'; import { SignUpModel } from 'app/models/sign-up-model'; import { SignUpValidationModel } from 'app/models/sign-up-validation-model'; import { DialogService } from 'app/services/dialog.service'; import { AccountService } from 'app/services/account.service'; import { Rou...
(): string { const letters = '0123456789ABCDEF'.split(''); let color = '#'; for ( let i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } }
getRandomColor
identifier_name
sign-up.component.ts
import { Component, OnInit } from '@angular/core'; import { SignUpModel } from 'app/models/sign-up-model'; import { SignUpValidationModel } from 'app/models/sign-up-validation-model'; import { DialogService } from 'app/services/dialog.service'; import { AccountService } from 'app/services/account.service'; import { Rou...
else { this.validationModel.validPassword = true; this.validationModel.passwordValidationMessage = ''; } if (!this.model.confirmPassword) { this.validationModel.validConfirmPassword = false; this.validationModel.confirmPasswordValidationMessage = 'Confirm Password is required.'; ...
{ this.validationModel.validPassword = false; this.validationModel.passwordValidationMessage = 'Password is required.'; hasError = true; }
conditional_block
sign-up.component.ts
import { Component, OnInit } from '@angular/core'; import { SignUpModel } from 'app/models/sign-up-model'; import { SignUpValidationModel } from 'app/models/sign-up-validation-model'; import { DialogService } from 'app/services/dialog.service'; import { AccountService } from 'app/services/account.service'; import { Rou...
if (!this.model.confirmPassword) { this.validationModel.validConfirmPassword = false; this.validationModel.confirmPasswordValidationMessage = 'Confirm Password is required.'; hasError = true; } else { this.validationModel.validConfirmPassword = true; this.validationModel.confirmPa...
{ let hasError = false; if (!this.model.userName) { this.validationModel.validUserName = false; this.validationModel.userNameValidationMessage = 'User Name is required.'; hasError = true; } else { this.validationModel.validUserName = true; this.validationModel.userNameValidati...
identifier_body
sign-up.component.ts
import { Component, OnInit } from '@angular/core'; import { SignUpModel } from 'app/models/sign-up-model'; import { SignUpValidationModel } from 'app/models/sign-up-validation-model'; import { DialogService } from 'app/services/dialog.service'; import { AccountService } from 'app/services/account.service'; import { Rou...
if (this.validationModel.validConfirmPassword) { if (this.model.confirmPassword !== this.model.password) { this.validationModel.validConfirmPassword = false; this.validationModel.confirmPasswordValidationMessage = 'Confirm Password is not the same as Password.'; hasError = true; ...
} else { this.validationModel.validConfirmPassword = true; this.validationModel.confirmPasswordValidationMessage = ''; }
random_line_split
htmltablecellelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethod...
impl HTMLTableCellElementMethods for HTMLTableCellElement { // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_getter!(ColSpan, "colspan", DEFAULT_COLSPAN); // https://html.spec.whatwg.org/multipage/#dom-tdth-colspan make_uint_setter!(SetColSpan, "colspan", DEFAULT_COLSPAN); // ...
} }
random_line_split
htmltablecellelement.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 cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableCellElementBinding::HTMLTableCellElementMethod...
(tag_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLTableCellElement { HTMLTableCellElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), } } } impl HTMLTableCell...
new_inherited
identifier_name
dienststellung-ff-popup.service.ts
import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { DienststellungFf } from './dienststellung-ff.model'; import { DienststellungFfService } from './dienststellung-ff.service'; @Injectable() export ...
}
{ const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'}); modalRef.componentInstance.dienststellung = dienststellung; modalRef.result.then((result) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true }); this.ngbModal...
identifier_body
dienststellung-ff-popup.service.ts
import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { DienststellungFf } from './dienststellung-ff.model'; import { DienststellungFfService } from './dienststellung-ff.service'; @Injectable() export ...
{ private ngbModalRef: NgbModalRef; constructor( private modalService: NgbModal, private router: Router, private dienststellungService: DienststellungFfService ) { this.ngbModalRef = null; } open(component: Component, id?: number | any): Promise<NgbModalRef> { ...
DienststellungFfPopupService
identifier_name
dienststellung-ff-popup.service.ts
import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { DienststellungFf } from './dienststellung-ff.model'; import { DienststellungFfService } from './dienststellung-ff.service'; @Injectable() export ...
else { // setTimeout used as a workaround for getting ExpressionChangedAfterItHasBeenCheckedError setTimeout(() => { this.ngbModalRef = this.dienststellungModalRef(component, new DienststellungFf()); resolve(this.ngbModalRef); }, 0...
{ this.dienststellungService.find(id).subscribe((dienststellung) => { this.ngbModalRef = this.dienststellungModalRef(component, dienststellung); resolve(this.ngbModalRef); }); }
conditional_block
dienststellung-ff-popup.service.ts
import { Injectable, Component } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { DienststellungFf } from './dienststellung-ff.model'; import { DienststellungFfService } from './dienststellung-ff.service'; @Injectable() export ...
modalRef.componentInstance.dienststellung = dienststellung; modalRef.result.then((result) => { this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true }); this.ngbModalRef = null; }, (reason) => { this.router.navigate([{ outlets: { popup: null }...
random_line_split
settings.py
# Django settings for tests2 project. import django import sys sys.path.append("../..") sys.path.append("../../../../..") from siteconf import * DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'djan...
# Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finde...
random_line_split
settings.py
# Django settings for tests2 project. import django import sys sys.path.append("../..") sys.path.append("../../../../..") from siteconf import * DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'djan...
# A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { ...
AUTH_USER_MODEL = 'testprofiles.TestUser'
conditional_block
mempool_persist.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bitcoind will dump mempool on shutdown and then reload it on sta...
MempoolPersistTest().main()
conditional_block
mempool_persist.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bitcoind will dump mempool on shutdown and then reload it on sta...
class MempoolPersistTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 3 self.extra_args = [[], ["-persistmempool=0"], []] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.log.debug("Send 5 transactions from node2...
random_line_split
mempool_persist.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bitcoind will dump mempool on shutdown and then reload it on sta...
(self): self.log.debug("Send 5 transactions from node2 (to its own address)") tx_creation_time_lower = int(time.time()) for i in range(5): last_txid = self.nodes[2].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("10")) node2_balance = self.nodes[2].getbalance() ...
run_test
identifier_name
mempool_persist.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bitcoind will dump mempool on shutdown and then reload it on sta...
def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.log.debug("Send 5 transactions from node2 (to its own address)") tx_creation_time_lower = int(time.time()) for i in range(5): last_txid = self.nodes[2].sendtoaddress(self.nodes...
self.num_nodes = 3 self.extra_args = [[], ["-persistmempool=0"], []]
identifier_body
flights.service.ts
import { Injectable, EventEmitter } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Flight } from '../model/Flight'; @Injectable() export class FlightsService { private f: Flight[] = []; private selectedIndex: number = -1; private searchStarted: EventEmitter<any> = new Eve...
} public get flights(): any[] { return this.f; } public get selectedFlight(): any { return (this.selectedIndex >= 0) ? this.f[this.selectedIndex] : -1; } public get searchStartedEvent(): EventEmitter<any> { return this.searchStarted; } p...
this.selectedIndex = -1; this.flightSelection.emit(undefined); }
conditional_block
flights.service.ts
import { Injectable, EventEmitter } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Flight } from '../model/Flight'; @Injectable() export class FlightsService { private f: Flight[] = []; private selectedIndex: number = -1; private searchStarted: EventEmitter<any> = new Eve...
public unselectFlight() { if (this.selectedIndex >= 0) { this.selectedIndex = -1; this.flightSelection.emit(undefined); } } public get flights(): any[] { return this.f; } public get selectedFlight(): any { return (this.selectedIndex >= 0) ...
for (let i = 0; i < this.f.length; i++) { if (this.f[i].id === flightId) { this.selectedIndex = i; this.flightSelection.emit(this.f[i]); return; } } this.selectedIndex = -1; }
identifier_body
flights.service.ts
import { Injectable, EventEmitter } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Flight } from '../model/Flight'; @Injectable() export class FlightsService { private f: Flight[] = []; private selectedIndex: number = -1; private searchStarted: EventEmitter<any> = new Eve...
epartureCity: string, arrivalCity: string, departureDate: string): void { this.searchStarted.emit(); const queryString = `?departureCity=${departureCity}&arrivalCity=${arrivalCity}&departureDate=${departureDate}`; this.http.get("http://localhost:53046/api/flights/search" + queryString).subscribe...
archFlights(d
identifier_name
flights.service.ts
import { Injectable, EventEmitter } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Flight } from '../model/Flight'; @Injectable() export class FlightsService { private f: Flight[] = []; private selectedIndex: number = -1; private searchStarted: EventEmitter<any> = new Eve...
if (this.f[i].id === flightId) { this.selectedIndex = i; this.flightSelection.emit(this.f[i]); return; } } this.selectedIndex = -1; } public unselectFlight() { if (this.selectedIndex >= 0) { this.selecte...
random_line_split
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct RpcCall { id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub stru...
match result { Ok(data) => RpcResponse{id: req.id, result: Json::String(data), error: Json::Null}, Err(e) => RpcResponse{id: req.id, result: Json::Null, error: Json::String(e)}, } } pub fn register_function<F: Fn(&T, Vec<String>) -> Result<String, String> + Sync + Send + 'static>(&mut self, s: &str, f...
None => Err(format!("Unknown method: {}", req.method)) };
random_line_split
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct
{ id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub struct RpcApi<T> { api_impl: RwLock<Box<T>>, method_mappings: RwLock<HashMap<String, RwLock<Box<Fn(&T, Vec<String>) -> Result<String,String> + Sync + Send>>>>, } impl...
RpcCall
identifier_name
rpc.rs
extern crate rustc_serialize; use std::collections::HashMap; use rustc_serialize::json::Json; use std::sync::{RwLock}; #[derive(RustcDecodable)] pub struct RpcCall { id: u32, method: String, params: Vec<String> } #[derive(RustcEncodable)] pub struct RpcResponse { id: u32, result: Json, error: Json } pub stru...
, None => Err(format!("Unknown method: {}", req.method)) }; match result { Ok(data) => RpcResponse{id: req.id, result: Json::String(data), error: Json::Null}, Err(e) => RpcResponse{id: req.id, result: Json::Null, error: Json::String(e)}, } } pub fn register_function<F: Fn(&T, Vec<String>) -> Res...
{ let api = self.api_impl.read().unwrap(); let mapping = mapping_lock.read().unwrap(); mapping(&(*api), req.params) }
conditional_block
transformconst.py
"""treetools: Tools for transforming treebank trees. transformations: constants and utilities Author: Wolfgang Maier <maierw@hhu.de> """ from . import trees # Head rules for PTB (WSJ) from Collins (1999, p. 240) HEAD_RULES_PTB = { 'adjp' : [('left-to-right', 'nns qp nn $ advp jj vbn vbg adjp jjr np jjs dt fw rbr...
return 0
if hrule[0] == 'left-to-right': for i, child_label in enumerate(children_label): parsed_label = trees.parse_label(child_label.lower()) if parsed_label.label.lower() == label: return i elif hrule[0] == 'right-to-left': ...
conditional_block
transformconst.py
"""treetools: Tools for transforming treebank trees. transformations: constants and utilities Author: Wolfgang Maier <maierw@hhu.de> """ from . import trees # Head rules for PTB (WSJ) from Collins (1999, p. 240) HEAD_RULES_PTB = { 'adjp' : [('left-to-right', 'nns qp nn $ advp jj vbn vbg adjp jjr np jjs dt fw rbr...
(parent_label, children_label, rules, default=0): """Given parent and children labels and head rules, return position of lexical head. """ if not parent_label.lower() in rules: return default for hrule in rules[parent_label.lower()]: if len(hrule[1]) == 0: ...
get_headpos_by_rule
identifier_name
transformconst.py
"""treetools: Tools for transforming treebank trees. transformations: constants and utilities Author: Wolfgang Maier <maierw@hhu.de> """ from . import trees # Head rules for PTB (WSJ) from Collins (1999, p. 240) HEAD_RULES_PTB = { 'adjp' : [('left-to-right', 'nns qp nn $ advp jj vbn vbg adjp jjr np jjs dt fw rbr...
for i, child_label in \ zip(reversed(range(len(children_label))), reversed(children_label)): parsed_label = trees.parse_label(child_label.lower()) if parsed_label.label.lower() == label: return i ...
"""Given parent and children labels and head rules, return position of lexical head. """ if not parent_label.lower() in rules: return default for hrule in rules[parent_label.lower()]: if len(hrule[1]) == 0: if hrule[0] == 'left-to-right': return len(children_l...
identifier_body
transformconst.py
"""treetools: Tools for transforming treebank trees. transformations: constants and utilities Author: Wolfgang Maier <maierw@hhu.de> """ from . import trees # Head rules for PTB (WSJ) from Collins (1999, p. 240) HEAD_RULES_PTB = { 'adjp' : [('left-to-right', 'nns qp nn $ advp jj vbn vbg adjp jjr np jjs dt fw rbr...
'co' : [('left-to-right', '')], 'avp' : [('right-to-left', 'adv avp adjd proav pp')], 'aa' : [('right-to-left', 'adjd adja')], 'cnp' : [('right-to-left', 'nn ne mpn np cnp pn car')], 'cap' : [('right-to-left', 'adjd adja cap aa adv')], 'cpp' : [('right-to-left', 'appr proav pp cpp')], 'cs' :...
random_line_split
tests.py
import unittest import doctest from pprint import pprint from interlude import interact import lxml.etree as etree optionflags = doctest.NORMALIZE_WHITESPACE | \ doctest.ELLIPSIS | \ doctest.REPORT_ONLY_FIRST_FAILURE #| \ # doctest.REPORT_NDIFF TESTFILES = [ 'api.rst', ...
unittest.main(defaultTest='test_suite') # pragma NO COVERAGE
conditional_block
tests.py
import unittest import doctest from pprint import pprint from interlude import interact import lxml.etree as etree optionflags = doctest.NORMALIZE_WHITESPACE | \ doctest.ELLIPSIS | \ doctest.REPORT_ONLY_FIRST_FAILURE #| \ # doctest.REPORT_NDIFF TESTFILES = [ 'api.rst', ...
(): return unittest.TestSuite([ doctest.DocFileSuite( filename, optionflags=optionflags, globs={'interact': interact, 'pprint': pprint, 'pxml': pxml}, ) for filename in TESTFILES ]) if __name__ == '__main__': # pragma N...
test_suite
identifier_name
tests.py
import unittest import doctest from pprint import pprint from interlude import interact import lxml.etree as etree optionflags = doctest.NORMALIZE_WHITESPACE | \ doctest.ELLIPSIS | \ doctest.REPORT_ONLY_FIRST_FAILURE #| \ # doctest.REPORT_NDIFF TESTFILES = [ 'api.rst', ...
def test_suite(): return unittest.TestSuite([ doctest.DocFileSuite( filename, optionflags=optionflags, globs={'interact': interact, 'pprint': pprint, 'pxml': pxml}, ) for filename in TESTFILES ]) if __name__ == '__mai...
print fxml(xml)
identifier_body
tests.py
import unittest import doctest from pprint import pprint from interlude import interact import lxml.etree as etree optionflags = doctest.NORMALIZE_WHITESPACE | \ doctest.ELLIPSIS | \ doctest.REPORT_ONLY_FIRST_FAILURE #| \ # doctest.REPORT_NDIFF TESTFILES = [ 'api.rst',
'script.rst', ] def fxml(xml): et = etree.fromstring(xml) return etree.tostring(et, pretty_print=True) def pxml(xml): print fxml(xml) def test_suite(): return unittest.TestSuite([ doctest.DocFileSuite( filename, optionflags=optionflags, globs={'inter...
random_line_split
expression-011.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ gTestfile = 'expression-011.js';
/** File Name: expression-011.js Corresponds To: ecma/Expressions/11.2.2-6-n.js ECMA Section: 11.2.2. The new operator Description: Author: christine@netscape.com Date: 12 november 1997 */ var SECTION = "expression-011"; var VERSION = "JS1_4"; var TITLE ...
random_line_split
command_runner.py
import subprocess import os class CommandRunner: HOST_LIST_TO_RUN_LOCAL = ["localhost", "127.0.0.1"] def __init__(self, local_hostname, logger): logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals())) self.local_hostname = loca...
if process.stdout is not None: output += [out.decode() if isinstance(out, bytes) else out for out in process.stdout.readlines()] if process.returncode != 0: self.logger.warn("Process returned code '" + str(process.returncode) + "'") is_successful ...
output += [err.decode() if isinstance(err, bytes) else err for err in stderr_output] self.logger.debug("Run Command stderr output: " + str(stderr_output))
conditional_block
command_runner.py
import subprocess import os class CommandRunner: HOST_LIST_TO_RUN_LOCAL = ["localhost", "127.0.0.1"] def __init__(self, local_hostname, logger): logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals())) self.local_hostname = loca...
(self, command_split): self.logger.debug("Running command_split: " + str(command_split)) is_successful = True output = [] try: process = subprocess.Popen(command_split, stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.wait() if process.stderr is...
_run_split_command
identifier_name
command_runner.py
import subprocess import os class CommandRunner:
self.local_hostname = local_hostname self.logger = logger # returns: is_successful, output def run_command(self, host, base_command): self.logger.debug("Running Command: " + str(base_command)) if host == self.local_hostname or host in self.HOST_LIST_TO_RUN_LOCAL: ret...
HOST_LIST_TO_RUN_LOCAL = ["localhost", "127.0.0.1"] def __init__(self, local_hostname, logger): logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals()))
random_line_split
command_runner.py
import subprocess import os class CommandRunner: HOST_LIST_TO_RUN_LOCAL = ["localhost", "127.0.0.1"] def __init__(self, local_hostname, logger): logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals())) self.local_hostname = loca...
def _run_split_command(self, command_split): self.logger.debug("Running command_split: " + str(command_split)) is_successful = True output = [] try: process = subprocess.Popen(command_split, stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.wait() ...
self.logger.debug("Running command as SSH command") if base_command.startswith("sudo"): command_split = ["ssh", "-tt", host, base_command] else: command_split = ["ssh", host, base_command] return self._run_split_command( command_split=command_split )
identifier_body
method-mangling.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo { pub _address: u8, } #[test] fn
() { assert_eq!( ::std::mem::size_of::<Foo>(), 1usize, concat!("Size of: ", stringify!(Foo)) ); assert_eq!( ::std::mem::align_of::<Foo>(), 1usize, concat!("Alignment of ", stringify!(Foo)) ); } extern "C" { #[link_name = "\u{1}_ZN3Foo4typeEv"] pub ...
bindgen_test_layout_Foo
identifier_name
method-mangling.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Foo { pub _address: u8, } #[test] fn bindgen_test_layout_Foo() { assert_eq!( ::std::mem::size_of::<Foo>(), 1usize, concat!("S...
} impl Foo { #[inline] pub unsafe fn type_(&mut self) -> ::std::os::raw::c_int { Foo_type(self) } }
#[link_name = "\u{1}_ZN3Foo4typeEv"] pub fn Foo_type(this: *mut Foo) -> ::std::os::raw::c_int;
random_line_split
vaunix.py
part of the CsPyController package for AQuA experiment control by Martin Lichtman Handles sending commands to Instek PST power supplies over RS232. created = 2015.07.09 modified >= 2015.07.09 """ __author__ = 'Martin Lichtman' import logging logger = logging.getLogger(__name__) from atom.api import Bool...
""" instek_pst.py
random_line_split
vaunix.py
'Martin Lichtman' import logging logger = logging.getLogger(__name__) from atom.api import Bool, Str, Member, Int from instrument_property import Prop, IntProp, ListProp, FloatProp from cs_instruments import Instrument from cs_errors import PauseError from ctypes import * class Vaunix(Prop): isI...
(self): if (not self.isInitialized): #test if DLL is already loaded. If not, load it. self.initialize() num=self.va.fnLMS_GetNumDevices() #ask DLL for the number of connected devices logger.debug("Number of vaunix devices detected: {}".format(num)) while (num>len(se...
detect_generators
identifier_name
vaunix.py
'Martin Lichtman' import logging logger = logging.getLogger(__name__) from atom.api import Bool, Str, Member, Int from instrument_property import Prop, IntProp, ListProp, FloatProp from cs_instruments import Instrument from cs_errors import PauseError from ctypes import * class Vaunix(Prop): isI...
self.va.fnLMS_SetTestMode(self.testMode) #Test mode... this needs to be set False for actual run. Do not remove this command (default setting is True). self.isInitialized = True num = self.detect_generators() return num def preExperiment(self, hdf5): ...
logger.warning("Warning: Vaunix in test mode. Set testMode=False in vaunix.py to turn off test mode.")
conditional_block
vaunix.py
'Martin Lichtman' import logging logger = logging.getLogger(__name__) from atom.api import Bool, Str, Member, Int from instrument_property import Prop, IntProp, ListProp, FloatProp from cs_instruments import Instrument from cs_errors import PauseError from ctypes import * class Vaunix(Prop): isI...
def postIteration(self, iterationresults, hdf5): return def postExperiment(self, hdf5): return def finalize(self,hdf5): return #detect_generators: Calls DLL function to check for number of generators and their IDs. def detect_generators(self): if (not ...
return
identifier_body
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
self.putc(i as char); } } /// Outputs an integer. fn puti(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive...
{ break; }
conditional_block
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
/// Outputs an integer. fn puti(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive(Copy)] pub struct TestCharIOData { ...
random_line_split
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
fn get_and_reset_putc_calls(&self) -> usize { let current = self.data.borrow().putc_calls; self.data.borrow_mut().putc_calls = 0; current } } #[test] fn putc_should_store_a_char() { let io = TestCharIO::new(); io.putc('a'); assert!(io.get_last_char() == 'a'); io.putc('...
{ self.data.borrow().last_char }
identifier_body
chario.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
(&self, i: u32) { self.putint(i, 10); } /// Outputs an integer as a hex string. fn puth(&self, i: u32) { self.putint(i, 16); } } #[cfg(test)] pub mod test { use core::cell::RefCell; use drivers::chario::CharIO; #[derive(Copy)] pub struct TestCharIOData { last_char: char, putc_calls: ...
puti
identifier_name
RegExps.js
var RegExps = { /* RegExp from https://gist.github.com/dperini/729294 * Modified to: * 1. Allow scheme-less URLs (e.g. kg.gg) - which will be handled * as http:// URLs by default. * 2. Support some other popular schemes (tftp, mailto, ws, data.). * 3. Accept URLs pointing to localhost and 1...
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + // domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + // TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + // TLD may end with dot "\\.?" + ")" + ...
"|" +
random_line_split
index.node.d.ts
/** * @license * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applica...
database?(): types.FirebaseDatabase; } }
random_line_split
utils.py
"\noutput=" + self.output assert not "panic" in self.output, "Exited with an error due to a panic" self.assert_output_contains(text) def assert_no_error(self, text=None): """ Assert the calicoctl command did not exit with an error code. Args: text: (optional) ...
truncate_for_log
identifier_name
utils.py
stdin, calicoctl_bin) if no_config : calicoctl_env_cmd = calicoctl_bin full_cmd = calicoctl_env_cmd + " " + command + option_file try: output = log_and_run(full_cmd, stderr=(None if only_stdout else STDOUT)) return CalicoctlOutput(full_cmd, output) except CalledProcessError as ...
'kind': kind,
random_line_split
utils.py
%s" % \ pformat(DeepDiff(cleaned, data), indent=2) def assert_empty_list(self, kind, format="yaml", text=None): """ Assert the calicoctl command output an empty list of the specified kind. Args: kind: The resource kind. format: The expected ou...
writeyaml("/tmp/input-data", data) else: writejson("/tmp/input-data", data) stdin = '' option_file = '' if data and load_as_stdin: stdin = 'cat /tmp/input-data | ' option_file = ' -f -' elif data and not load_as_stdin: option_file = ' -f /tmp/inp...
""" Convenience function for abstracting away calling the calicoctl command. :param command: The calicoctl command line parms as a single string. :param data: Input data either as a string or a JSON serializable Python object. :param load_as_stdin: Load the input data through stdin rather th...
identifier_body
utils.py
in self.output, "Exited with an error due to a panic" self.assert_output_contains(text) def assert_no_error(self, text=None): """ Assert the calicoctl command did not exit with an error code. Args: text: (optional) Expected text in the command output. """ ...
return text
conditional_block
parser.py
# -*- coding: utf-8 -*- from .record import ( Metadata, Record, ) __all__ = ['Parser'] class Parser: def __init__(self, store): self.store = store def parse_record(self, metadata, line): factors = line.split('|') if len(factors) < 7: return registry, cc...
metadata = None for line in fp: line = line[:-1] if line.startswith('#') or line.endswith('summary'): continue if metadata is None: version, registry, serial, records,\ startdate, enddate, utcoffset = line.split('|...
random_line_split
parser.py
# -*- coding: utf-8 -*- from .record import ( Metadata, Record, ) __all__ = ['Parser'] class Parser: def __init__(self, store): self.store = store def parse_record(self, metadata, line): factors = line.split('|') if len(factors) < 7: return registry, cc...
(self, fp): metadata = None for line in fp: line = line[:-1] if line.startswith('#') or line.endswith('summary'): continue if metadata is None: version, registry, serial, records,\ startdate, enddate, utcoffset = l...
do
identifier_name
parser.py
# -*- coding: utf-8 -*- from .record import ( Metadata, Record, ) __all__ = ['Parser'] class Parser: def __init__(self, store): self.store = store def parse_record(self, metadata, line): factors = line.split('|') if len(factors) < 7: return registry, cc...
self.store.persist(record)
continue
conditional_block
parser.py
# -*- coding: utf-8 -*- from .record import ( Metadata, Record, ) __all__ = ['Parser'] class Parser:
continue if metadata is None: version, registry, serial, records,\ startdate, enddate, utcoffset = line.split('|')[:7] metadata = Metadata(registry, version, serial) continue record = self.parse_record(metadata...
def __init__(self, store): self.store = store def parse_record(self, metadata, line): factors = line.split('|') if len(factors) < 7: return registry, cc, type_, start, value, dete, status = factors[:7] if type_ not in ('ipv4', 'ipv6'): return ...
identifier_body
manager.js
define([ "dojo/_base/array", "dojo/_base/config", // defaultDuration "../registry", ".." // for setting exports to dijit namespace ], function(array, config, registry, dijit){ // module: // dijit/_base/manager // summary: // Shim to methods on registry, plus a few other declarations. // New code should acc...
// node: DOMNode return registry.getEnclosingWidget(node); }; =====*/ array.forEach(["byId", "getUniqueId", "findWidgets", "_destroyAll", "byNode", "getEnclosingWidget"], function(name){ dijit[name] = registry[name]; }); /*===== dojo.mixin(dijit, { // defaultDuration: Integer // The default fx.animati...
// the node is not contained within the DOM tree of any widget
random_line_split
tradeskill-to-equip.ts
import { isUndefined } from 'lodash'; import { Command } from '../../../../base/Command'; import { Player } from '../../../../../shared/models/player'; export class TradeskillToEquip extends Command { public name = '~TtE'; public format = 'TradeskillSlot TradeskillSrcSlot AlchUUID';
(player: Player, { room, args }) { const [tsSlot, tsSrcSlot, alchUUID] = args.split(' '); if(!tsSlot || isUndefined(tsSrcSlot) || !alchUUID) return false; const container = room.state.findNPC(alchUUID); if(!container) return player.sendClientMessage('That person is not here.'); const item = playe...
execute
identifier_name
tradeskill-to-equip.ts
export class TradeskillToEquip extends Command { public name = '~TtE'; public format = 'TradeskillSlot TradeskillSrcSlot AlchUUID'; execute(player: Player, { room, args }) { const [tsSlot, tsSrcSlot, alchUUID] = args.split(' '); if(!tsSlot || isUndefined(tsSrcSlot) || !alchUUID) return false; cons...
import { isUndefined } from 'lodash'; import { Command } from '../../../../base/Command'; import { Player } from '../../../../../shared/models/player';
random_line_split