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 |
|---|---|---|---|---|
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, prope... | ,
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
}
| {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
}
... | identifier_body |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, prope... |
return true;
},
defaultMessage(args: ValidationArguments) {
return args.constraints[1];
},
},
});
};
}
| {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
return false;
} | conditional_block |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, prope... | (value: AnyObject, args: ValidationArguments) {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} characters`;
... | validate | identifier_name |
MainTextMaxLength.ts | import { AnyObject } from '@jovotech/framework';
import { registerDecorator, ValidationArguments, ValidationOptions } from '@jovotech/output';
import { TextContent } from '../../models';
export function MainTextMaxLength(length: number, options?: ValidationOptions): PropertyDecorator {
return function (object, prope... | validate(value: AnyObject, args: ValidationArguments) {
if (!(value instanceof TextContent)) {
return true;
}
if (value.primaryText?.text?.length > args.constraints[0]) {
args.constraints[1] = `primaryText of $property can not exceed ${args.constraints[0]} ... | target: object.constructor,
propertyName: propertyKey.toString(),
constraints: [length],
options,
validator: { | random_line_split |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... |
# define a simple setup class
ss = oc.SimpleSetup(cspace)
validityChecker = ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation()))
ss.setStateValidityChecker(validityChecker)
ode = oc.ODE(kinematicCarODE)
odeSolver = oc.ODEBasicSolver(ss.getSpaceInformation(), ode)
propa... | cbounds.setLow(-.3)
cbounds.setHigh(.3)
cspace.setBounds(cbounds) | random_line_split |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... | ():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace(space, 2)... | plan | identifier_name |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... |
def plan():
# construct the state space we are planning in
space = ob.SE2StateSpace()
# set the bounds for the R^2 part of SE(2)
bounds = ob.RealVectorBounds(2)
bounds.setLow(-1)
bounds.setHigh(1)
space.setBounds(bounds)
# create a control space
cspace = oc.RealVectorControlSpace... | return spaceInformation.satisfiesBounds(state) | identifier_body |
RigidBodyPlanningWithODESolverAndControls.py | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... | plan() | conditional_block | |
path.rs | glob-like pattern matching (using `glob` crate) to a
/// gitignore-like pattern matching (using `ignore` crate). The migration
/// stages are:
///
/// 1) Only warn users about the future change iff their matching rules are
/// affected. (CURRENT STAGE)
///
/// 2) Switch to the new strat... | else {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL NOT be included in a future Cargo version.\n\
... | {
self.config
.shell()
.warn(format!(
"Pattern matching for Cargo's include/exclude fields is changing and \
file `{}` WILL be excluded in a future Cargo version.\n\
... | conditional_block |
path.rs | fn discover_git_and_list_files(&self,
pkg: &Package,
root: &Path,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> Option<CargoResult<Vec<PathBuf>>> {
// If this pack... | supports_checksums | identifier_name | |
path.rs | to this Cargo.toml, we still
// check to see if we are indeed part of the index. If not, then
// this is likely an unrelated git repo, so keep going.
if let Ok(repo) = git2::Repository::open(cur) {
let index = match repo.index() {
... | {
trace!("getting packages; id={}", id);
let pkg = self.packages.iter().find(|pkg| pkg.package_id() == id);
pkg.cloned().ok_or_else(|| {
internal(format!("failed to find {} in path source", id))
})
} | identifier_body | |
path.rs | _git(&self, pkg: &Package, repo: git2::Repository,
filter: &mut FnMut(&Path) -> CargoResult<bool>)
-> CargoResult<Vec<PathBuf>> {
warn!("list_files_git {}", pkg.package_id());
let index = repo.index()?;
let root = repo.workdir().ok_or_else(|| {
... | random_line_split | ||
replViewer.ts | implements IRenderer {
private static VARIABLE_TEMPLATE_ID = 'variable';
private static EXPRESSION_TEMPLATE_ID = 'inputOutputPair';
private static VALUE_OUTPUT_TEMPLATE_ID = 'outputValue';
private static NAME_VALUE_OUTPUT_TEMPLATE_ID = 'outputNameValue';
private static FILE_LOCATION_PATTERNS: RegExp[] = [
// ... | ReplExpressionsRenderer | identifier_name | |
replViewer.ts | Width / this.width);
}, lines.length);
return ReplExpressionsRenderer.LINE_HEIGHT_PX * numLines;
}
public setWidth(fullWidth: number, characterWidth: number): void {
this.width = fullWidth;
this.characterWidth = characterWidth;
}
public getTemplateId(tree: ITree, element: any): string {
if (element ins... | {
let span = document.createElement('span');
span.textContent = textBeforeLink;
linkContainer.appendChild(span);
} | conditional_block | |
replViewer.ts | }
public renderElement(tree: ITree, element: any, templateId: string, templateData: any): void {
if (templateId === ReplExpressionsRenderer.VARIABLE_TEMPLATE_ID) {
renderVariable(tree, element, templateData, false);
} else if (templateId === ReplExpressionsRenderer.EXPRESSION_TEMPLATE_ID) {
this.renderExpr... | return nls.localize('replKeyValueOutputAriaLabel', "Output variable {0} has value {1}, read eval print loop, debug", (<OutputNameValueElement>element).name, (<OutputNameValueElement>element).value);
}
return null; | random_line_split | |
replViewer.ts |
}
interface IExpressionTemplateData {
input: HTMLElement;
output: HTMLElement;
value: HTMLElement;
annotation: HTMLElement;
}
interface IValueOutputTemplateData {
container: HTMLElement;
counter: HTMLElement;
value: HTMLElement;
}
interface IKeyValueOutputTemplateData {
container: HTMLElement;
expression: ... | {
return TPromise.as(null);
} | identifier_body | |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, N... | (NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14])
name = 'snmpProxyMIB'
class snmpProxyObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1])
name = 'snmpProxyObjects'
class snmpProxyConformance(NodeObject):
OID = pycopia.SMI.Base... | snmpProxyMIB | identifier_name |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
| from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from SNMPv2_TC import RowStatus, StorageType
from SNMP_TARGET_MIB import SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup
from SNMP_FRAMEWORK_MIB import SnmpEngineID, SnmpAdminString
class SNMP_PROXY_MIB(ModuleObject):
path = '/usr/share/mibs/ietf/SNM... | from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import MODULE_IDENTITY, OBJECT_TYPE, snmpModules | random_line_split |
SNMP_PROXY_MIB.py | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, N... |
# nodes
class snmpProxyMIB(NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14])
name = 'snmpProxyMIB'
class snmpProxyObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1])
name = 'snmpProxyObjects'
class snmpProxyConformance(NodeObje... | path = '/usr/share/mibs/ietf/SNMP-PROXY-MIB'
name = 'SNMP-PROXY-MIB'
language = 2
description = 'This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module i... | identifier_body |
matrix_inverse_op_test.py | 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_)
inv2 = linalg_ops... | testConcurrentExecutesWithoutError | identifier_name |
matrix_inverse_op_test.py | 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def _verifyInverseComplex(self, x):
for np_type in [np.complex64, np.complex128]:
self._verifyInverse(x, np_type)
def _makeBatch(self, matrix1, matrix2):
matrix_batch = np.concatenate(
[np.expand_dims(matrix1, 0),
np.expand_dims(matrix2, 0)])
matrix_batch = np.tile(matrix_batch... | for np_type in [np.float32, np.float64]:
self._verifyInverse(x, np_type) | identifier_body |
matrix_inverse_op_test.py | 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
@test_util.deprecated_graph_mode_only
def testConcurrentExecutesWithoutError(self):
with self.session(use_gpu=True) as sess:
all_ops = []
for adjoint_ in True, False:
matrix1 = random_ops.random_normal([5, 5], seed=42)
matrix2 = random_ops.random_normal([5, 5], seed=42)
inv... | for batch_dims in [(), (1,), (3,), (2, 2)]:
for size in 8, 31, 32:
shape = batch_dims + (size, size)
matrix = np.random.uniform(
low=-1.0, high=1.0,
size=np.prod(shape)).reshape(shape).astype(dtype)
self._verifyInverseReal(matrix) | conditional_block |
matrix_inverse_op_test.py | 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | self._verifyInverseComplex(matrix1)
self._verifyInverseComplex(matrix2)
# Complex batch
self._verifyInverseComplex(self._makeBatch(matrix1, matrix2))
@test_util.deprecated_graph_mode_only
def testNonSquareMatrix(self):
# When the inverse of a non-square matrix is attempted we should return
... | matrix2 = matrix2.astype(np.complex64)
matrix2 += 1j * matrix2 | random_line_split |
app_routing_selectors.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
const compareParams = routeParams as CompareRouteParams;
const userDefinedAliasMap = getCompareExperimentIdAliasSpec(compareParams);
return Object.fromEntries(userDefinedAliasMap.entries());
}
);
export const getExperimentIdToExperimentAliasMap = createSelector(
getRouteKind,
getRouteParams,
(rou... | {
return {};
} | conditional_block |
app_routing_selectors.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | }
const compareParams = routeParams as CompareRouteParams;
const userDefinedAliasMap = getCompareExperimentIdAliasSpec(compareParams);
return Object.fromEntries(userDefinedAliasMap.entries());
}
);
export const getExperimentIdToExperimentAliasMap = createSelector(
getRouteKind,
getRouteParams,
... | random_line_split | |
ajax.ts | import { Log } from './log';
//import Url = require('./url');
import { Url } from './url';
import { HashString } from './lib';
/**
* Делаем HTTP (Ajax) запрос.
*
* @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(... | // никаких call, apply надо сохранить контекст вызова иногда это важно
original(jqXHR, textStatus, errorThrown);
Log('Ajax.error()', textStatus, errorThrown);
};
}
return $.ajax(opts);
}; | } else {
let original = opts.error;
opts.error = function (jqXHR, textStatus, errorThrown) { | random_line_split |
ajax.ts | import { Log } from './log';
//import Url = require('./url');
import { Url } from './url';
import { HashString } from './lib';
/**
* Делаем HTTP (Ajax) запрос.
*
* @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(... | us, errorThrown) {
// никаких call, apply надо сохранить контекст вызова иногда это важно
original(jqXHR, textStatus, errorThrown);
Log('Ajax.error()', textStatus, errorThrown);
};
}
return $.ajax(opts);
};
| conditional_block | |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__... | red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.select(table.id,
where=red_sql & table.id.in_(domain)))
writable_ids.extend(x[0] for x in cursor.fetchall())
else:
writable_ids = ids
writable_ids = set(writa... | random_line_split | |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__... |
@classmethod
def delete(cls, events):
if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events)
| if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__) | conditional_block |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__... | (cls, domain, offset=0, limit=None, order=None, count=False,
query=False):
if Transaction().user:
domain = domain[:]
domain = [domain,
['OR',
[
('classification', '=', 'private'),
['OR',
... | search | identifier_name |
calendar_.py | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__... | if len(set(events)) != cls.search([('id', 'in', map(int, events))],
count=True):
cls.raise_user_error('access_error', cls.__doc__)
super(Event, cls).delete(events) | identifier_body | |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)... |
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
... | _LOGGER.error(
"Error saving data %s to %s (http status code = %d)",
payload, fullurl, req.status_code) | conditional_block |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)... |
def update_emoncms(time):
"""Send whitelisted entities states regularly to Emoncms."""
payload_dict = {}
for entity_id in whitelist:
state = hass.states.get(entity_id)
if state is None or state.state in (
STATE_UNKNOWN, '', STATE_UNAVAILABLE):
... | """Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey": apikey, "data": payload}
parameters = {"node": node}
req = requests.post(
fullurl, params=parameters, data=data, allow_redirects=True,
... | identifier_body |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)... | _LOGGER = logging.getLogger(__name__)
DOMAIN = 'emoncms_history'
CONF_INPUTNODE = 'inputnode'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_INPUTNODE): cv.positive_int,
vol.Required(CONF... | random_line_split | |
__init__.py | """Support for sending data to Emoncms."""
import logging
from datetime import timedelta
import requests
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_API_KEY, CONF_WHITELIST, CONF_URL, STATE_UNKNOWN, STATE_UNAVAILABLE,
CONF_SCAN_INTERVAL)... | (hass, config):
"""Set up the Emoncms history component."""
conf = config[DOMAIN]
whitelist = conf.get(CONF_WHITELIST)
def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms."""
try:
fullurl = '{}/input/post.json'.format(url)
data = {"apikey":... | setup | identifier_name |
typings.d.ts | interface AutoNumericOptions {
aSep?: string
dGroup?: number
aDec?: string
altDec?: string
aSign?: string
pSign?: "p" | "s"
vMin?: number
vMax?: number
mDec?: number
mRound?: "S" | "A" | "s" | "a" | "B" | "U" | "D" | "C" | "F" | "CHF"
aPad?: boolean
nBracket?: string
wEmpty?: "empty" | "zero" ... | autoNumeric(method: "set", value: string): JQuery
autoNumeric(method: "get"): string
autoNumeric(method: "getString"): string
autoNumeric(method: "getArray"): Serialized[]
autoNumeric(method: "getSettings"): AutoNumericOptions
} | autoNumeric(method: "init", options?: AutoNumericOptions): JQuery
autoNumeric(method: "destroy"): JQuery
autoNumeric(method: "update", options: AutoNumericOptions): JQuery | random_line_split |
operations.py | (level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op... |
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.v[15] = context.v[y] & 0x1
context.v[x] = context.v[y] >> 1
context.pc += 2
def sub_vx_v... | context.pc += 2 | conditional_block |
operations.py | =logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op):
... | (context, x):
for i in range(x+1):
context.v[i] = context.memory.get_byte(context.index_reg + i)
context.pc += 2
def set_bcd_vx(context, x):
val = int(context.v[x])
context.memory.write_byte(context.index_reg, val / 100)
context.memory.write_byte(context.index_reg + 1, val % 100 / 10)
... | fill_v0_vx | identifier_name |
operations.py | (level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op... | context.v[15] = 1 if val < 0 else 0
context.v[x] = val % 256
context.pc += 2
def set_vx_or_vy(context, x, y):
logging.info('Setting V[X] = V[X] | V[Y]')
context.v[x] = context.v[x] | context.v[y]
context.pc += 2
def set_vx_xor_vy(context, x, y):
logging.info('Setting V[X] = V[X] ^ ... | context.pc += 2
def sub_vx_vy(context, x, y):
logging.info('Setting V[X] = V[X] - V[Y]')
val = context.v[x] - context.v[y] | random_line_split |
operations.py | (level=logging.INFO)
class Executor(object):
def __init__(self, op_map):
processed = {}
for pattern, f in op_map.iteritems():
s = self._build_pattern_groups(pattern.lower())
processed[re.compile(s)] = f
self.operations = processed
def execute(self, context, op... |
def jump_noteq(context, x, y):
if context.v[x] != context.v[y]:
context.pc += 2
context.pc += 2
def shift_vy_left(context, x, y):
context.v[15] = context.v[15] >> 7 # First value
context.v[x] = (context.v[y] << 1) % 255
context.pc += 2
def shift_right(context, x, y):
context.... | import random
context.v[x] = random.randint(0, 0xFF) & nn
context.pc += 2 | identifier_body |
torrentEngine.ts | return;
// Send handshake, metadata handshake, and bitfield.
wire.sendHandshake();
wire.sendBitfield(self.bitfieldDL);
});
wire.on("request", () => {
if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) ... | cleanupAll | identifier_name | |
torrentEngine.ts | , timeTillNextScrape) => {
self.trackerData[tracker + ":seeders"] = seeders;
self.trackerData[tracker + ":completed"] = completed;
self.trackerData[tracker + ":leechers"] = leechers;
self.trackerData[tracker + ":nextReq"] = timeTillNextScrape;
});
});
}
newConnectio... | // Set the peers piece number and index of piece | random_line_split | |
torrentEngine.ts | if (!wire.reqBusy) {
wire.reqBusy = true;
// Iterate through requests...
while (wire.inRequests.length) {
let request = wire.inRequests.shift();
self.tph.prepareUpload(request.index, request.begin, request.length, (piece: Buffer) => {
process.nextTick(() =>... | {
const self = this;
for (let host in self.peers) {
self.peers[host].socket.destroy();
delete self.peers[host];
}
} | identifier_body | |
torrentEngine.ts | interval, leechers, seeders, peers) => {
peers = peers.map((peer) => { return peer + ":" + ( (self.trackers[tracker].TYPE === "udp") ? "tcp" : "ws" ); });
self.connectQueue = self.connectQueue.concat(peers);
self.connectQueue = _.uniq(self.connectQueue);
if (!self.finished)
sel... | {
self._debug("failed hash");
// Remove piece and try again
self.bitfield.set(self.peers[host + port].piece, false);
} | conditional_block | |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods... | (func):
def _inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except NotImplementedError:
return None
update_wrapper(_inner, func)
return _inner
class IgnoreNotimplementedError(type):
def __new__(cls, name, bases, attrs):
for k,v in attrs.items()... | ignore_not_implemented | identifier_name |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods... |
def test_get_key_columns(self):
cursor = connection.cursor()
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
def test_get_primary_key_column(self):
cursor = c... | self.assertEqual(relations, {3: (0, Reporter._meta.db_table)}) | conditional_block |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods... |
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description... | tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter])) | identifier_body |
tests.py | from __future__ import absolute_import,unicode_literals
from functools import update_wrapper
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils import six
from .models import Reporter, Article
#
# The introspection module is optional, so methods... | cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
cursor.execute('DROP TABLE django_ixn_real_test_table;')
self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
... |
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature('has_real_datatype')
def test_postgresql_real_type(self):
cursor = connection.cursor() | random_line_split |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import... | except Exception as e:
log.error("PID:%d bloom filter error:%s ip:%s" % (os.getpid(),e,ele["ip_port"]))
#url, ip, is_http, store_cookies, use_default_cookies, check_anonymity,
ele["name"] = "global"
ele["db"] = 0
ele["ur... | bloom.add(ele["ip_port"]) | random_line_split |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import... | ():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times = 0
while True:
try:
num = db_zcount()
log.debug("PID:%d db current ips %d------" % (os.getpid(),num))
... | db_zcount | identifier_name |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import... |
except Exception as e:
log.error("PID:%d proxy url error:%s %s " % (os.getpid(),traceback.format_exc(), str(pattern)))
def db_zcount():
r = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP, decode_responses=True)
return r.zcard("proxy:counts")
def get_proxy(q):
#bloom.clear_all()
times... | index = pattern["url"][i].find("%d")
log.debug("PID:%d url:%s" % (os.getpid(), str(pattern)))
if index == -1:
get_and_check(pattern["url"][i],pattern,q)
time.sleep(10)
continue
for j in range(1,num+1):
url = pattern["url... | conditional_block |
proxy.py | # -*- coding: utf-8 -*-
from queue import Queue
from lxml import etree
import requests
import random
from settings import *
import time
import socket
from pybloom_live import BloomFilter
from settings import log
import os
from settings import REFRESH_BF
from settings import MIN_NUM
import redis
import threading
import... |
def get_and_check(url,pattern,q):
try:
page = get_pages(url)
if page == None:
return
lists = parse_page(url, page, pattern)
for ele in lists:
is_existed = ele["ip_port"] in bloom
#log.debug("PID:%d proxy worker ip %s is_existed %d" % (os.getpid(... | page = etree.HTML(page.lower())
#page = etree.HTML(page.lower().decode('utf-8'))
ips = page.xpath(pattern["ip"])
ports = page.xpath(pattern["port"])
ty = page.xpath(pattern["type"])
if ips == None or ports == None or ty == None:
raise ValueError("current page "+str(ips)+str(ports)+str(ty))... | identifier_body |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
# Additional utilities for the main interface.
def albums_in_dir(path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files... | MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d'
| random_line_split |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
# Title.
item.title = track_info.title
if config['per_disc_numbering']:
item.track = track_info.medium_index or track_info.index
item.tracktotal = track_info.medium_total or len(album_info.tracks)
else:
item.track = track_info.index
item... | if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
# If we don't even have a year, apply nothin... | conditional_block |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | for prefix in '', 'original_':
if config['original_date'] and not prefix:
# Ignore specific release date.
continue
for suffix in 'year', 'month', 'day':
key = prefix + suffix
value = getattr(album_info, key) or 0
... | """Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in mapping.iteritems():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist
else:
item.artist = al... | identifier_body |
__init__.py | # This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... | (path):
"""Recursively searches the given directory and returns an iterable
of (paths, items) where paths is a list of directories and items is
a list of Items that is probably an album. Specifically, any folder
containing any media files is an album.
"""
collapse_pat = collapse_paths = collapse... | albums_in_dir | identifier_name |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenge... | def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of the user-defined config file.
"""
import json
from flask import current_app
config_file = current_app.config[... | else:
print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message
| random_line_split |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenge... | print "Sending a message that HAS been previously sent."
message = random.choice(questions)
return message
def __load_config_file(self):
"""
Stores the contents of the client-defined config file to a json object.
Returns:
json: A json object of ... | """
Select a client-defined open-ended question that has not been previously
selected at random. If all have been sent then select one at random.
Args:
number (str): The mobile number of the patient.
Returns:
str: An open-ended question to ask the patient.
... | identifier_body |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenge... | (self, number):
"""
Adds the patient to the service database.
Args:
number (str): The mobile number of the patient.
"""
db.session.add(models.User(mobile=number))
db.session.commit()
def __save_message(self, number, message, status):
"""
... | __create_new_patient | identifier_name |
manager.py | from sris import db, models
from messenger import Messenger
from service import SMSService
from datetime import datetime
class Manager:
"""
The middle-man of interaction between messenger and the SMS service.
"""
def __init__(self):
self.config = self.__load_config_file()
self.messenge... |
else:
print 'Message received was response to a RS. Sending OEQ.'
response = self.__select_question(number)
if response:
self.__save_message(number, patient_message, 'received')
self.__save_message(number, response, 'sent')
... | print 'Sending the conversation closer as limit met.'
response = self.config['endQuestion'] | conditional_block |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` an... | pairoff(4,2, -1,2)
except AssertionError as e:
print(e)
try: # non-integer
pairoff(1.25,0.6)
except AssertionError as e:
print(e) | random_line_split | |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` an... |
def check_post(*args):
'Post-condition checker.'
# return value from decorated function is always the last positional
# parameter
rval = args[-1]
# simple check of the number of items in the return
assert 2 * len(rval) == len(args) - 1
# check units
units_out = [i%10 for i in rval]
... | 'Pre-condition checker.'
# must have an even number of args
assert ( len(args) & 1 ) == 0, 'Expected an even number of arguments'
# all numbers must be non-negative ints
assert all(i>=0 and isinstance(i,int) for i in args), \
'Numbers must be positive integers'
# all second numbers must be <... | identifier_body |
DbC_methods_with_both_pre_and_post.py | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` an... | (*args):
'Pre-condition checker.'
# must have an even number of args
assert ( len(args) & 1 ) == 0, 'Expected an even number of arguments'
# all numbers must be non-negative ints
assert all(i>=0 and isinstance(i,int) for i in args), \
'Numbers must be positive integers'
# all second numb... | check_pre | identifier_name |
taskcluster-spark-dogfood.py | #!/usr/bin/env python
import os.path
config = {
"default_vcs": "tc-vcs",
"default_actions": [
'checkout-sources',
'build',
'build-symbols',
'make-updates',
'prep-upload',
'submit-to-balrog'
],
"balrog_credentials_file": "balrog_credentials",
"nightly_b... | "B2G_UPDATE_CHANNEL": "dogfood",
"BOWER_FLAGS": "--allow-root",
"B2G_PATH": "%(work_dir)s",
"GAIA_DISTRIBUTION_DIR": "%(work_dir)s/gaia/distros/spark",
"WGET_OPTS": "-c -q"
},
"is_automation": True,
"repo_remote_mappings": {
'https://android.googlesource.com/'... | "DOGFOOD": "1", | random_line_split |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. Thi... |
option_parser.add_option('--debug', action='store_const', const='Debug',
dest='build_type', default=default_build_type,
help='If set, run test suites under out/Debug. '
'Default is env var BUILDTYPE or Debug')
option_parser.add_option... | default_build_type = os.environ['BUILDTYPE'] | conditional_block |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. Thi... | default=default_timeout)
option_parser.add_option('-c', dest='cleanup_test_files',
help='Cleanup test files on the device after run',
action='store_true')
option_parser.add_option('--num_retries', dest='num_retries', type='int',
... | option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int', | random_line_split |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. Thi... | 'traceview']
option_parser.add_option('--profiler', dest='profilers', action='append',
choices=profilers,
help='Profiling tool to run during test. '
'Pass multiple times to run multiple profilers. '
... | """Decorates OptionParser with options applicable to all tests."""
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int',
default=default_timeout)
option_parser.add_option('-c', dest='cleanup_... | identifier_body |
test_options_parser.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses options for the instrumentation tests."""
import os
# TODO(gkanwar): Some downstream scripts current rely on these functions
# existing. Thi... | (option_parser, default_timeout=60):
"""Decorates OptionParser with options applicable to all tests."""
option_parser.add_option('-t', dest='timeout',
help='Timeout to wait for each test',
type='int',
default=default_timeout)
option... | AddTestRunnerOptions | identifier_name |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForE... | } catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet (x) {
if (!setSize) {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
}... | }
try {
mapSize.call(x);
try {
setSize.call(x); | random_line_split |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForE... | (obj, key) {
return hasOwn.call(obj, key);
}
function toStr (obj) {
return objectToString.call(obj);
}
function nameOf (f) {
if (f.name) return f.name;
var m = String(f).match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
... | has | identifier_name |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForE... |
function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
function isError (obj) { return toStr(obj) === '[object Error]' }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]' }
function isString (obj) { return toStr(obj) === '[object String]' }
function isNumber (obj) { return toStr(obj) === '... | { return toStr(obj) === '[object Date]' } | identifier_body |
index.js | var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForE... |
return String(obj);
}
if (!opts) opts = {};
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') depth = 0;
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return '[Object]';
}
if (typeof seen === 'undefine... | {
return Infinity / obj > 0 ? '0' : '-0';
} | conditional_block |
typeid-intrinsic2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> TypeId { TypeId::of::<B>() }
pub unsafe fn id_C() -> TypeId { TypeId::of::<C>() }
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H()... | id_B | identifier_name |
typeid-intrinsic2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use std::any::TypeId;
pub struct A;
pub struct B(Option<A>);
pub struct C(Option<int>);
pub struct D(Option<&'static str>);
pub struct E(Result<&'static str, int>);
pub type F = Option<int>;
pub type G = uint;
pub type H = &'static str;
pub unsafe fn id_A() -> TypeId { TypeId::of::<A>() }
pub unsafe fn id_B() -> Ty... | // option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
typeid-intrinsic2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub unsafe fn id_D() -> TypeId { TypeId::of::<D>() }
pub unsafe fn id_E() -> TypeId { TypeId::of::<E>() }
pub unsafe fn id_F() -> TypeId { TypeId::of::<F>() }
pub unsafe fn id_G() -> TypeId { TypeId::of::<G>() }
pub unsafe fn id_H() -> TypeId { TypeId::of::<H>() }
pub unsafe fn foo<T: 'static>() -> TypeId { TypeId::o... | { TypeId::of::<C>() } | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(se... | {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
} | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... | () {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));... | line_through | identifier_name |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
... | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.co... | }
}
| random_line_split |
copy.js | /* 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/. */
module.exports = function (grunt) {
grunt.config('copy', {
build: {
files: [{
cwd: '<%= yeoman... | files: [
{
cwd: '<%= yeoman.strings_src %>',
dest: '<%= yeoman.strings_dist %>',
expand: true,
src: ['**/*.po']
},
{
cwd: '<%= yeoman.strings_src %>/sv_SE',
dest: '<%= yeoman.strings_dist %>/sv',
// Copy strings from sv_... | random_line_split | |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | identifier_body | |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() {
let mut nyan = cat(0u, 2, ~"nyan");
... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
classes-cross-crate.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
}
| main | identifier_name |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy ... | extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
}
public async action(message: Message):... | Mute | identifier_name |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy ... |
const [result, ask, confirmation]: [PromptResult, Message, Message] = <[PromptResult, Message, Message]> await prompt(message,
'Are you sure you want to initiate a member sync? (__y__es | __n__o)',
/^(?:yes|y)$/i, /^(?:no|n)$/i, { embed });
// If message sent from a non-mod channel then delete the ... | {
// Delete calling message immediately
message.delete();
} | conditional_block |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy ... |
public async action(message: Message): Promise<any> {
let msgAuthor: GuildMember = message.member;
if (msgAuthor) {
// If calling user is the server owner or D0cR3d
if (msgAuthor.user.id === message.guild.ownerID || msgAuthor.user.id === '82942340309716992') {
let embed: RichEmbed = new RichEmbed();
... | {
super({
name: 'membersSync',
aliases: ['ms'],
desc: 'Sync list of users in the server',
usage: '<prefix>membersSync',
group: 'admin',
guildOnly: true
});
} | identifier_body |
membersSync.ts | // Note: ModManager and and a few related aspects have come from https://github.com/zajrik/modbot | import { SweeperClient } from '../../util/lib/SweeperClient';
import { prompt, PromptResult } from '../../util/lib/Util';
const idRegex: RegExp = /^(?:<@!?)?(\d+)>?$/;
export default class Mute extends Command<SweeperClient> {
@logger private readonly logger: Logger;
public constructor() {
super({
name: 'mem... |
import { Command, GuildStorage, Logger, logger } from 'yamdbf';
import { Collection, GuildMember, Message, RichEmbed, TextChannel, User } from 'discord.js';
import Constants from '../../util/Constants';
import * as fuzzy from 'fuzzy'; | random_line_split |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.... |
# GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
Arg... | with tf.Session() as sess:
cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
| random_line_split |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.... | (z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
x = tf.placeholder(tf.float32, name='x')
sigmoid = tf.nn.sigmoid(x)
with tf.Session() as sess:
result = sess.run(sigmoid, feed_dict={x: z})
... | sigmoid | identifier_name |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.... | cost = sess.run(cost, feed_dict={z: logits, y: labels})
return cost
# GRADED FUNCTION: one_hot_ma
trix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if... | """
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "z" and "y" in this class are respectively called "logits" an... | identifier_body |
Dxq_1.py | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week_three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.... | , 0.9])
cost = cost(logits, np.array([0, 0, 1, 1]))
print("cost = " + str(cost))
tf.one_hot(labels,C,axis=0) | conditional_block | |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
//... | (stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
... | read_and_decode | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result; | // Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_... | random_line_split | |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
//... | }
Ok(results)
}
}
| {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
... | identifier_body |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This pro... | problem, strategy):
node = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there ... | s( | identifier_name |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This pro... | # checks if the chosen node its a goal state before expand it
if problem.goalState(node) is True:
iteration = next(iterCounter)
return execute(node), iteration, len(frontier), generatedNodes
iteration = next(iterCounter)
# Debugging process
#gsDebug(iterat... | ode = {'state': problem.initialState, 'parent': [], 'actions': [], 'g': 0, 'f': 0}
frontier = [node]
exploredSet = []
iterCounter = itertools.count(start = 0)
nodesCounter = itertools.count(start = 1)
iteration = 0
generatedNodes = 1
while True:
# when there are no more nodes to expl... | identifier_body |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This pro... | # chooses the node with the lowest cost
# first we sort by max and then we take the last element of the list
# this allow us to choose the vertice with the last lowest cost that was
# appended to list (in case of ties)
sortedFrontier = sorted(frontier, key = itemgetter('f'), reve... | teration = next(iterCounter)
return None, iteration, len(frontier), generatedNodes
| conditional_block |
search.py | """
Copyright (C) 2017 João Barroca <joao.barroca@tecnico.ulisboa.pt>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This pro... | generatedNodes = next(nodesCounter)
# checks if the child node has already been explored or if it is already in the frontier
if not inExploredList(problem, child, exploredSet) and not inFrontier(problem, child, frontier):
frontier.append(child) | # adds the node being explored to the explored set
exploredSet.append(node)
# expand the node and get the child nodes
childNodes = childNodesGetter(problem, node, strategy)
for child in childNodes: | random_line_split |
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(... | context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click() | identifier_body | |
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(... | (context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))... | step_impl | identifier_name |
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(... |
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_l... | assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name]) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.