id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
37,033
def test_min_samples_split(): X = np.asfortranarray(iris.data.astype(tree._tree.DTYPE)) y = iris.target for (max_leaf_nodes, name) in product((None, 1000), ALL_TREES.keys()): TreeEstimator = ALL_TREES[name] est = TreeEstimator(min_samples_split=10, max_leaf_nodes=max_leaf_nodes, random_state=0) est.fit(X, y) ...
[ "def", "test_min_samples_split", "(", ")", ":", "X", "=", "np", ".", "asfortranarray", "(", "iris", ".", "data", ".", "astype", "(", "tree", ".", "_tree", ".", "DTYPE", ")", ")", "y", "=", "iris", ".", "target", "for", "(", "max_leaf_nodes", ",", "na...
test min_samples_split parameter .
train
false
37,034
def validate_bug_tracker_base_hosting_url(input_url): try: (input_url % ()) except TypeError: raise ValidationError([(_(u"The URL '%s' is not valid because it contains a format character. For bug trackers other than 'Custom Bug Tracker', use the base URL of the server. If you need a '%%' character, prepend it wit...
[ "def", "validate_bug_tracker_base_hosting_url", "(", "input_url", ")", ":", "try", ":", "(", "input_url", "%", "(", ")", ")", "except", "TypeError", ":", "raise", "ValidationError", "(", "[", "(", "_", "(", "u\"The URL '%s' is not valid because it contains a format ch...
check that hosting service bug urls dont contain %s .
train
false
37,035
def is_coverage_running(): if ('coverage' not in sys.modules): return False tracer = sys.gettrace() if (tracer is None): return False try: mod = tracer.__module__ except AttributeError: try: mod = tracer.__class__.__module__ except AttributeError: return False return mod.startswith('coverage')
[ "def", "is_coverage_running", "(", ")", ":", "if", "(", "'coverage'", "not", "in", "sys", ".", "modules", ")", ":", "return", "False", "tracer", "=", "sys", ".", "gettrace", "(", ")", "if", "(", "tracer", "is", "None", ")", ":", "return", "False", "t...
return whether coverage is currently running .
train
false
37,036
def select_direct_adjacent(cache, left, right): right = (always_in if (right is None) else frozenset(right)) for parent in left: for sibling in cache.itersiblings(parent): if (sibling in right): (yield sibling) break
[ "def", "select_direct_adjacent", "(", "cache", ",", "left", ",", "right", ")", ":", "right", "=", "(", "always_in", "if", "(", "right", "is", "None", ")", "else", "frozenset", "(", "right", ")", ")", "for", "parent", "in", "left", ":", "for", "sibling"...
right is a sibling immediately after left .
train
false
37,038
def add_visual_box_select(plot): source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[])) rect = Rect(x='x', y='y', width='width', height='height', fill_alpha=0.3, fill_color='#009933') callback = CustomJS(args=dict(source=source), code="\n // get data source from Callback args\n var data ...
[ "def", "add_visual_box_select", "(", "plot", ")", ":", "source", "=", "ColumnDataSource", "(", "data", "=", "dict", "(", "x", "=", "[", "]", ",", "y", "=", "[", "]", ",", "width", "=", "[", "]", ",", "height", "=", "[", "]", ")", ")", "rect", "...
add a box select tool to your plot which draws a rect on box select .
train
false
37,040
def clean_orphaned_vdis(xenapi, vdi_uuids): for vdi_uuid in vdi_uuids: if CONF.verbose: print ('CLEANING VDI (%s)' % vdi_uuid) vdi_ref = call_xenapi(xenapi, 'VDI.get_by_uuid', vdi_uuid) try: call_xenapi(xenapi, 'VDI.destroy', vdi_ref) except XenAPI.Failure as exc: sys.stderr.write(('Skipping %s: %s' %...
[ "def", "clean_orphaned_vdis", "(", "xenapi", ",", "vdi_uuids", ")", ":", "for", "vdi_uuid", "in", "vdi_uuids", ":", "if", "CONF", ".", "verbose", ":", "print", "(", "'CLEANING VDI (%s)'", "%", "vdi_uuid", ")", "vdi_ref", "=", "call_xenapi", "(", "xenapi", ",...
clean orphaned vdis .
train
false
37,041
def yield_source_csv_messages(cls, foreign_cls, csvreader, force_column=None): columns = list(cls.__table__.c) column_names = next(csvreader) assert ([cls.__table__.c[name] for name in column_names] == columns), ','.join((c.name for c in columns)) pk = columns[:len(cls.__table__.primary_key.columns)] first_string_...
[ "def", "yield_source_csv_messages", "(", "cls", ",", "foreign_cls", ",", "csvreader", ",", "force_column", "=", "None", ")", ":", "columns", "=", "list", "(", "cls", ".", "__table__", ".", "c", ")", "column_names", "=", "next", "(", "csvreader", ")", "asse...
yield all messages from one source csv file .
train
false
37,042
def vvd(val, valok, dval, func, test, status): assert quantity_allclose(val, (valok * val.unit), atol=(dval * val.unit))
[ "def", "vvd", "(", "val", ",", "valok", ",", "dval", ",", "func", ",", "test", ",", "status", ")", ":", "assert", "quantity_allclose", "(", "val", ",", "(", "valok", "*", "val", ".", "unit", ")", ",", "atol", "=", "(", "dval", "*", "val", ".", ...
mimic routine of erfa/src/t_erfa_c .
train
false
37,043
def get_async(keys, **kwargs): (keys, multiple) = datastore.NormalizeAndTypeCheckKeys(keys) def extra_hook(entities): if ((not multiple) and (not entities)): return None models = [] for entity in entities: if (entity is None): model = None else: cls1 = class_for_kind(entity.kind()) model = ...
[ "def", "get_async", "(", "keys", ",", "**", "kwargs", ")", ":", "(", "keys", ",", "multiple", ")", "=", "datastore", ".", "NormalizeAndTypeCheckKeys", "(", "keys", ")", "def", "extra_hook", "(", "entities", ")", ":", "if", "(", "(", "not", "multiple", ...
asynchronously fetch the specified model instance(s) from the datastore .
train
false
37,044
def with_tmpdir(f): @wraps(f) def wrapper(self, *args, **kwargs): tmp = tempfile.mkdtemp(prefix='f2b-temp') try: return f(self, tmp, *args, **kwargs) finally: shutil.rmtree(tmp) return wrapper
[ "def", "with_tmpdir", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "tmp", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'f2b-temp'", ")", "try", ":", "ret...
helper decorator to create a temporary directory directory gets removed after function returns .
train
false
37,045
def save_resized_image(image_file, width_, height_, basewidth, aspect, height_size, upload_path, ext='jpg', remove_after_upload=False): filename = '{filename}.{ext}'.format(filename=time.time(), ext=ext) img = Image.open(image_file) if (aspect == 'on'): width_percent = (basewidth / float(img.size[0])) height_siz...
[ "def", "save_resized_image", "(", "image_file", ",", "width_", ",", "height_", ",", "basewidth", ",", "aspect", ",", "height_size", ",", "upload_path", ",", "ext", "=", "'jpg'", ",", "remove_after_upload", "=", "False", ")", ":", "filename", "=", "'{filename}....
save the resized version of the background image .
train
false
37,047
def getGearProfileCylinder(teeth, toothProfile): gearProfile = [] toothAngleRadian = ((2.0 * math.pi) / float(teeth)) totalToothAngle = 0.0 for toothIndex in xrange(abs(teeth)): for toothPoint in toothProfile: gearProfile.append((toothPoint * euclidean.getWiddershinsUnitPolar(totalToothAngle))) totalToothAng...
[ "def", "getGearProfileCylinder", "(", "teeth", ",", "toothProfile", ")", ":", "gearProfile", "=", "[", "]", "toothAngleRadian", "=", "(", "(", "2.0", "*", "math", ".", "pi", ")", "/", "float", "(", "teeth", ")", ")", "totalToothAngle", "=", "0.0", "for",...
get gear profile for a cylinder gear .
train
false
37,048
def find_app(app, symbol_by_name=symbol_by_name, imp=import_from_cwd): from .base import Celery try: sym = symbol_by_name(app, imp=imp) except AttributeError: sym = imp(app) if (isinstance(sym, ModuleType) and (u':' not in app)): try: found = sym.app if isinstance(found, ModuleType): raise Attribute...
[ "def", "find_app", "(", "app", ",", "symbol_by_name", "=", "symbol_by_name", ",", "imp", "=", "import_from_cwd", ")", ":", "from", ".", "base", "import", "Celery", "try", ":", "sym", "=", "symbol_by_name", "(", "app", ",", "imp", "=", "imp", ")", "except...
find app by name .
train
false
37,049
def get_rare_data(otu_table, seqs_per_sample, include_small_samples=False, subsample_f=subsample): with errstate(empty='raise'): if (not include_small_samples): otu_table = filter_samples_from_otu_table(otu_table, otu_table.ids(), seqs_per_sample, inf) def func(x, s_id, s_md): if (x.sum() < seqs_per_sample):...
[ "def", "get_rare_data", "(", "otu_table", ",", "seqs_per_sample", ",", "include_small_samples", "=", "False", ",", "subsample_f", "=", "subsample", ")", ":", "with", "errstate", "(", "empty", "=", "'raise'", ")", ":", "if", "(", "not", "include_small_samples", ...
filter otu table to keep only desired sample sizes .
train
false
37,050
def get_texts_box(texts, fs): max_len = max(map(len, texts)) return (fs, text_len(max_len, fs))
[ "def", "get_texts_box", "(", "texts", ",", "fs", ")", ":", "max_len", "=", "max", "(", "map", "(", "len", ",", "texts", ")", ")", "return", "(", "fs", ",", "text_len", "(", "max_len", ",", "fs", ")", ")" ]
approximation of multiple texts bounds .
train
true
37,052
def is_admin_context(context): if (not context): LOG.warning(_LW('Use of empty request context is deprecated'), DeprecationWarning) raise Exception('die') return context.is_admin
[ "def", "is_admin_context", "(", "context", ")", ":", "if", "(", "not", "context", ")", ":", "LOG", ".", "warning", "(", "_LW", "(", "'Use of empty request context is deprecated'", ")", ",", "DeprecationWarning", ")", "raise", "Exception", "(", "'die'", ")", "r...
indicates if the request context is an administrator .
train
false
37,053
def get_computer_desc(): desc = None hostname_cmd = salt.utils.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']('{0} status --pretty'.format(hostname_cmd)) else: pattern = re.compile('^\\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.fopen('/etc/machine-info', 'r') as mach_info: for lin...
[ "def", "get_computer_desc", "(", ")", ":", "desc", "=", "None", "hostname_cmd", "=", "salt", ".", "utils", ".", "which", "(", "'hostnamectl'", ")", "if", "hostname_cmd", ":", "desc", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'{0} status --pretty'", ".", ...
get the windows computer description :return: returns the computer description if found .
train
false
37,055
@Throttle(MIN_TIME_BETWEEN_UPDATES) def send_data(name, msg): import dweepy try: dweepy.dweet_for(name, msg) except dweepy.DweepyError: _LOGGER.error("Error saving data '%s' to Dweet.io", msg)
[ "@", "Throttle", "(", "MIN_TIME_BETWEEN_UPDATES", ")", "def", "send_data", "(", "name", ",", "msg", ")", ":", "import", "dweepy", "try", ":", "dweepy", ".", "dweet_for", "(", "name", ",", "msg", ")", "except", "dweepy", ".", "DweepyError", ":", "_LOGGER", ...
send the collected data to dweet .
train
false
37,057
def resize_thumbnails(pelican): global enabled if (not enabled): return in_path = _image_path(pelican) sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES) resizers = dict(((k, _resizer(k, v, in_path)) for (k, v) in sizes.items())) logger.debug('Thumbnailer Started') for (dirpath, _, filena...
[ "def", "resize_thumbnails", "(", "pelican", ")", ":", "global", "enabled", "if", "(", "not", "enabled", ")", ":", "return", "in_path", "=", "_image_path", "(", "pelican", ")", "sizes", "=", "pelican", ".", "settings", ".", "get", "(", "'THUMBNAIL_SIZES'", ...
resize a directory tree full of images into thumbnails .
train
true
37,058
def ReplaceChunks(chunks): chunks_by_file = _SortChunksByFile(chunks) sorted_file_list = sorted(iterkeys(chunks_by_file)) num_files_to_open = _GetNumNonVisibleFiles(sorted_file_list) if (num_files_to_open > 0): if (not Confirm(FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format(num_files_to_open))): return locations ...
[ "def", "ReplaceChunks", "(", "chunks", ")", ":", "chunks_by_file", "=", "_SortChunksByFile", "(", "chunks", ")", "sorted_file_list", "=", "sorted", "(", "iterkeys", "(", "chunks_by_file", ")", ")", "num_files_to_open", "=", "_GetNumNonVisibleFiles", "(", "sorted_fil...
apply the source file deltas supplied in |chunks| to arbitrary files .
train
false
37,059
def subscribe_user_to_notifications(node, user): NotificationSubscription = apps.get_model('osf.NotificationSubscription') if node.is_collection: raise InvalidSubscriptionError('Collections are invalid targets for subscriptions') if node.is_deleted: raise InvalidSubscriptionError('Deleted Nodes are invalid targe...
[ "def", "subscribe_user_to_notifications", "(", "node", ",", "user", ")", ":", "NotificationSubscription", "=", "apps", ".", "get_model", "(", "'osf.NotificationSubscription'", ")", "if", "node", ".", "is_collection", ":", "raise", "InvalidSubscriptionError", "(", "'Co...
update the notification settings for the creator or contributors .
train
false
37,061
def function_dump(filename, inputs, outputs=None, mode=None, updates=None, givens=None, no_default_updates=False, accept_inplace=False, name=None, rebuild_strict=True, allow_input_downcast=None, profile=None, on_unused_input=None, extra_tag_to_remove=None): assert isinstance(filename, string_types) d = dict(inputs=in...
[ "def", "function_dump", "(", "filename", ",", "inputs", ",", "outputs", "=", "None", ",", "mode", "=", "None", ",", "updates", "=", "None", ",", "givens", "=", "None", ",", "no_default_updates", "=", "False", ",", "accept_inplace", "=", "False", ",", "na...
this is helpful to make a reproducible case for problems during theano compilation .
train
false
37,065
def _gp_int(tok): try: return int(tok) except ValueError: return str(tok)
[ "def", "_gp_int", "(", "tok", ")", ":", "try", ":", "return", "int", "(", "tok", ")", "except", "ValueError", ":", "return", "str", "(", "tok", ")" ]
gets a int from a token .
train
false
37,068
def read_requirements(path, strict_bounds, conda_format=False, filter_names=None): real_path = join(dirname(abspath(__file__)), path) with open(real_path) as f: reqs = _filter_requirements(f.readlines(), filter_names=filter_names, filter_sys_version=(not conda_format)) if (not strict_bounds): reqs = map(_with_...
[ "def", "read_requirements", "(", "path", ",", "strict_bounds", ",", "conda_format", "=", "False", ",", "filter_names", "=", "None", ")", ":", "real_path", "=", "join", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ",", "path", ")", "with", "...
read a requirements .
train
true
37,071
def lines(path, comments=None): stream = open(path, 'U') result = stream_lines(stream, comments) stream.close() return result
[ "def", "lines", "(", "path", ",", "comments", "=", "None", ")", ":", "stream", "=", "open", "(", "path", ",", "'U'", ")", "result", "=", "stream_lines", "(", "stream", ",", "comments", ")", "stream", ".", "close", "(", ")", "return", "result" ]
return a list of non empty lines in the file located at path .
train
false
37,072
def encode_header_param(param_text): if (not param_text): return '' param_text_utf8 = ustr(param_text).encode('utf-8') param_text_ascii = try_coerce_ascii(param_text_utf8) return (param_text_ascii or Charset('utf8').header_encode(param_text_utf8))
[ "def", "encode_header_param", "(", "param_text", ")", ":", "if", "(", "not", "param_text", ")", ":", "return", "''", "param_text_utf8", "=", "ustr", "(", "param_text", ")", ".", "encode", "(", "'utf-8'", ")", "param_text_ascii", "=", "try_coerce_ascii", "(", ...
returns an appropriate rfc2047 encoded representation of the given header parameter value .
train
false
37,074
def hash_args(*args, **kwargs): arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([((str(key) + '=') + str(value)) for (key, value) in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg_string]) hasher = md5() hasher.update(b(combined)) return hasher.hexdigest()
[ "def", "hash_args", "(", "*", "args", ",", "**", "kwargs", ")", ":", "arg_string", "=", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "]", ")", "kwarg_string", "=", "'_'", ".", "join", "(", "[", "(", "(", "st...
define a unique string for any set of representable args .
train
true
37,076
def test_hdf5_topo_view(): skip_if_no_h5py() import h5py (handle, filename) = tempfile.mkstemp() dataset = random_one_hot_topological_dense_design_matrix(np.random.RandomState(1), num_examples=10, shape=(2, 2), channels=3, axes=('b', 0, 1, 'c'), num_classes=3) with h5py.File(filename, 'w') as f: f.create_dataset...
[ "def", "test_hdf5_topo_view", "(", ")", ":", "skip_if_no_h5py", "(", ")", "import", "h5py", "(", "handle", ",", "filename", ")", "=", "tempfile", ".", "mkstemp", "(", ")", "dataset", "=", "random_one_hot_topological_dense_design_matrix", "(", "np", ".", "random"...
train using an hdf5 dataset with topo_view instead of x .
train
false
37,077
def CreateStyleFromConfig(style_config): def GlobalStyles(): for (style, _) in _DEFAULT_STYLE_TO_FACTORY: (yield style) def_style = False if (style_config is None): for style in GlobalStyles(): if (_style == style): def_style = True break if (not def_style): return _style return _GLOBAL_STYL...
[ "def", "CreateStyleFromConfig", "(", "style_config", ")", ":", "def", "GlobalStyles", "(", ")", ":", "for", "(", "style", ",", "_", ")", "in", "_DEFAULT_STYLE_TO_FACTORY", ":", "(", "yield", "style", ")", "def_style", "=", "False", "if", "(", "style_config",...
create a style dict from the given config .
train
false
37,078
def scalar_potential_difference(field, frame, point1, point2, origin): _check_frame(frame) if isinstance(field, Vector): scalar_fn = scalar_potential(field, frame) else: scalar_fn = field position1 = express(point1.pos_from(origin), frame, variables=True) position2 = express(point2.pos_from(origin), frame, var...
[ "def", "scalar_potential_difference", "(", "field", ",", "frame", ",", "point1", ",", "point2", ",", "origin", ")", ":", "_check_frame", "(", "frame", ")", "if", "isinstance", "(", "field", ",", "Vector", ")", ":", "scalar_fn", "=", "scalar_potential", "(", ...
returns the scalar potential difference between two points in a certain coordinate system .
train
false
37,079
def deprecation_warning(message=None): sys.stderr.write(u'WARNING: This function is deprecated.') if message: sys.stderr.write((u' ' + message.strip())) sys.stderr.write(u'\n')
[ "def", "deprecation_warning", "(", "message", "=", "None", ")", ":", "sys", ".", "stderr", ".", "write", "(", "u'WARNING: This function is deprecated.'", ")", "if", "message", ":", "sys", ".", "stderr", ".", "write", "(", "(", "u' '", "+", "message", ".", ...
print a deprecation warning to stderr .
train
false
37,080
def shape2geometry(shape, projection, clip): if clip: try: shape = shape.intersection(clip) except TopologicalError: raise _InvisibleBike('Clipping shape resulted in a topological error') if shape.is_empty: raise _InvisibleBike('Clipping shape resulted in a null geometry') geom = shape.__geo_interface_...
[ "def", "shape2geometry", "(", "shape", ",", "projection", ",", "clip", ")", ":", "if", "clip", ":", "try", ":", "shape", "=", "shape", ".", "intersection", "(", "clip", ")", "except", "TopologicalError", ":", "raise", "_InvisibleBike", "(", "'Clipping shape ...
convert a shapely geometry object to a geojson-suitable geometry dict .
train
false
37,081
def create_local_xmlrpc_uri(port): return ('http://%s:%s/' % (get_host_name(), port))
[ "def", "create_local_xmlrpc_uri", "(", "port", ")", ":", "return", "(", "'http://%s:%s/'", "%", "(", "get_host_name", "(", ")", ",", "port", ")", ")" ]
determine the xmlrpc uri for local servers .
train
false
37,084
def ListComp(xp, fp, it, test=None): xp.set_prefix('') fp.set_prefix(' ') it.set_prefix(' ') for_leaf = Leaf(token.NAME, 'for') for_leaf.set_prefix(' ') in_leaf = Leaf(token.NAME, 'in') in_leaf.set_prefix(' ') inner_args = [for_leaf, fp, in_leaf, it] if test: test.set_prefix(' ') if_leaf = Leaf(token.NAME,...
[ "def", "ListComp", "(", "xp", ",", "fp", ",", "it", ",", "test", "=", "None", ")", ":", "xp", ".", "set_prefix", "(", "''", ")", "fp", ".", "set_prefix", "(", "' '", ")", "it", ".", "set_prefix", "(", "' '", ")", "for_leaf", "=", "Leaf", "(", "...
a list comprehension of the form [xp for fp in it if test] .
train
false
37,085
def use_obj_for_literal_in_memo(expr, obj, lit, memo): for node in pyll.dfs(expr): try: if (node.obj == lit): memo[node] = obj except AttributeError: pass return memo
[ "def", "use_obj_for_literal_in_memo", "(", "expr", ",", "obj", ",", "lit", ",", "memo", ")", ":", "for", "node", "in", "pyll", ".", "dfs", "(", "expr", ")", ":", "try", ":", "if", "(", "node", ".", "obj", "==", "lit", ")", ":", "memo", "[", "node...
set memo[node] = obj for all nodes in expr such that node .
train
false
37,090
def set_up_gae_environment(sdk_path): if ('google' in sys.modules): reload_module(sys.modules['google']) sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path() import google.appengine.tools.os_compat
[ "def", "set_up_gae_environment", "(", "sdk_path", ")", ":", "if", "(", "'google'", "in", "sys", ".", "modules", ")", ":", "reload_module", "(", "sys", ".", "modules", "[", "'google'", "]", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "sdk_pat...
set up appengine sdk third-party imports .
train
false
37,091
@pytest.mark.network def test_command_line_appends_correctly(script, data): script.environ['PIP_FIND_LINKS'] = ('http://pypi.pinaxproject.com %s' % data.find_links) result = script.pip('install', '-vvv', 'INITools', '--trusted-host', 'pypi.pinaxproject.com', expect_error=True) assert ('Analyzing links from page http...
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_command_line_appends_correctly", "(", "script", ",", "data", ")", ":", "script", ".", "environ", "[", "'PIP_FIND_LINKS'", "]", "=", "(", "'http://pypi.pinaxproject.com %s'", "%", "data", ".", "find_links", ...
test multiple appending options set by environmental variables .
train
false
37,093
def decode_result(found): return {True: 'Countermodel found', False: 'No countermodel found', None: 'None'}[found]
[ "def", "decode_result", "(", "found", ")", ":", "return", "{", "True", ":", "'Countermodel found'", ",", "False", ":", "'No countermodel found'", ",", "None", ":", "'None'", "}", "[", "found", "]" ]
decode the result of model_found() .
train
false
37,094
def reset_devices(): temper_devices = get_temper_devices() for (sensor, device) in zip(TEMPER_SENSORS, temper_devices): sensor.set_temper_device(device)
[ "def", "reset_devices", "(", ")", ":", "temper_devices", "=", "get_temper_devices", "(", ")", "for", "(", "sensor", ",", "device", ")", "in", "zip", "(", "TEMPER_SENSORS", ",", "temper_devices", ")", ":", "sensor", ".", "set_temper_device", "(", "device", ")...
re-scan for underlying temper sensors and assign them to our devices .
train
false
37,095
def get_volume_labels_from_aseg(mgz_fname, return_colors=False): import nibabel as nib mgz_data = nib.load(mgz_fname).get_data() lut = _get_lut() label_names = [lut[(lut['id'] == ii)]['name'][0].decode('utf-8') for ii in np.unique(mgz_data)] label_colors = [[lut[(lut['id'] == ii)]['R'][0], lut[(lut['id'] == ii)]['...
[ "def", "get_volume_labels_from_aseg", "(", "mgz_fname", ",", "return_colors", "=", "False", ")", ":", "import", "nibabel", "as", "nib", "mgz_data", "=", "nib", ".", "load", "(", "mgz_fname", ")", ".", "get_data", "(", ")", "lut", "=", "_get_lut", "(", ")",...
return a list of names and colors of segmented volumes .
train
false
37,097
def standardize_patterns(column_names, patterns): try: patterns = dict(((k, pattern_as_function(v)) for (k, v) in patterns.items() if v)) if (not column_names): return patterns p2 = {} for k in patterns: if (k in column_names): idx = column_names.index(k) if (idx in patterns): raise ColumnId...
[ "def", "standardize_patterns", "(", "column_names", ",", "patterns", ")", ":", "try", ":", "patterns", "=", "dict", "(", "(", "(", "k", ",", "pattern_as_function", "(", "v", ")", ")", "for", "(", "k", ",", "v", ")", "in", "patterns", ".", "items", "(...
given patterns in any of the permitted input forms .
train
false
37,098
def ValidateString(value, name='unused', exception=datastore_errors.BadValueError, max_len=_MAX_STRING_LENGTH, empty_ok=False): if ((value is None) and empty_ok): return if ((not isinstance(value, basestring)) or isinstance(value, Blob)): raise exception(('%s should be a string; received %s (a %s):' % (name, valu...
[ "def", "ValidateString", "(", "value", ",", "name", "=", "'unused'", ",", "exception", "=", "datastore_errors", ".", "BadValueError", ",", "max_len", "=", "_MAX_STRING_LENGTH", ",", "empty_ok", "=", "False", ")", ":", "if", "(", "(", "value", "is", "None", ...
raises an exception if value is not a valid string or a subclass thereof .
train
false
37,100
def libvlc_get_changeset(): f = (_Cfunctions.get('libvlc_get_changeset', None) or _Cfunction('libvlc_get_changeset', (), None, ctypes.c_char_p)) return f()
[ "def", "libvlc_get_changeset", "(", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_get_changeset'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_get_changeset'", ",", "(", ")", ",", "None", ",", "ctypes", ".", "c_char_p", ")", ")"...
retrieve libvlc changeset .
train
false
37,101
def response_truncated(f): @functools.wraps(f) def wrapper(self, *args, **kwargs): if (kwargs.get('hints') is None): return f(self, *args, **kwargs) list_limit = self.driver._get_list_limit() if list_limit: kwargs['hints'].set_limit(list_limit) return f(self, *args, **kwargs) return wrapper
[ "def", "response_truncated", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "kwargs", ".", "get", "(", "'hints'", ")", "is", "None", ")...
truncate the list returned by the wrapped function .
train
false
37,102
def validip(ip, defaultaddr='0.0.0.0', defaultport=8080): addr = defaultaddr port = defaultport ip = ip.split(':', 1) if (len(ip) == 1): if (not ip[0]): pass elif validipaddr(ip[0]): addr = ip[0] elif validipport(ip[0]): port = int(ip[0]) else: raise ValueError, (':'.join(ip) + ' is not a valid ...
[ "def", "validip", "(", "ip", ",", "defaultaddr", "=", "'0.0.0.0'", ",", "defaultport", "=", "8080", ")", ":", "addr", "=", "defaultaddr", "port", "=", "defaultport", "ip", "=", "ip", ".", "split", "(", "':'", ",", "1", ")", "if", "(", "len", "(", "...
returns from string ip_addr_port .
train
true
37,103
def corefile(process): if context.noptrace: log.warn_once('Skipping corefile since context.noptrace==True') return temp = tempfile.NamedTemporaryFile(prefix='pwn-corefile-') if (version() < (7, 11)): log.warn_once(('The installed GDB (%s) does not emit core-dumps which contain all of the data in the process.\n...
[ "def", "corefile", "(", "process", ")", ":", "if", "context", ".", "noptrace", ":", "log", ".", "warn_once", "(", "'Skipping corefile since context.noptrace==True'", ")", "return", "temp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'pwn-coref...
drops a core file for the process .
train
false
37,105
def image_resize_image_big(base64_source, size=(1024, 1024), encoding='base64', filetype=None, avoid_if_small=True): return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
[ "def", "image_resize_image_big", "(", "base64_source", ",", "size", "=", "(", "1024", ",", "1024", ")", ",", "encoding", "=", "'base64'", ",", "filetype", "=", "None", ",", "avoid_if_small", "=", "True", ")", ":", "return", "image_resize_image", "(", "base64...
wrapper on image_resize_image .
train
false
37,106
def _dump_function(func): func_info = (func.func_name, func.func_defaults, func.func_closure) code_info = (func.func_code.co_argcount, func.func_code.co_nlocals, func.func_code.co_stacksize, func.func_code.co_flags, func.func_code.co_code, func.func_code.co_consts, func.func_code.co_names, func.func_code.co_varnames,...
[ "def", "_dump_function", "(", "func", ")", ":", "func_info", "=", "(", "func", ".", "func_name", ",", "func", ".", "func_defaults", ",", "func", ".", "func_closure", ")", "code_info", "=", "(", "func", ".", "func_code", ".", "co_argcount", ",", "func", "...
serializes a function .
train
false
37,108
def is_empty(filename): try: return (os.stat(filename).st_size == 0) except OSError: return False
[ "def", "is_empty", "(", "filename", ")", ":", "try", ":", "return", "(", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "==", "0", ")", "except", "OSError", ":", "return", "False" ]
is a file empty? .
train
false
37,110
def get_nginx_port(appid): filename = (('/etc/appscale/port-' + appid) + '.txt') file_handle = open(filename) port = file_handle.read() file_handle.close() return port
[ "def", "get_nginx_port", "(", "appid", ")", ":", "filename", "=", "(", "(", "'/etc/appscale/port-'", "+", "appid", ")", "+", "'.txt'", ")", "file_handle", "=", "open", "(", "filename", ")", "port", "=", "file_handle", ".", "read", "(", ")", "file_handle", ...
an appscale-specific method that callers can use to find out what port task queue api calls should be routed through .
train
false
37,112
def application(): settings.hrm.staff_experience = True settings.hrm.use_skills = True settings.search.filter_manager = True def prep(r): method = r.method if ((not method) and (r.representation != 's3json')): r.method = method = 'select' if (method == 'select'): r.custom_action = s3db.deploy_apply re...
[ "def", "application", "(", ")", ":", "settings", ".", "hrm", ".", "staff_experience", "=", "True", "settings", ".", "hrm", ".", "use_skills", "=", "True", "settings", ".", "search", ".", "filter_manager", "=", "True", "def", "prep", "(", "r", ")", ":", ...
the main wsgi application .
train
false
37,113
def wininst_name(pyver): ext = '.exe' return ('scipy-%s.win32-py%s%s' % (FULLVERSION, pyver, ext))
[ "def", "wininst_name", "(", "pyver", ")", ":", "ext", "=", "'.exe'", "return", "(", "'scipy-%s.win32-py%s%s'", "%", "(", "FULLVERSION", ",", "pyver", ",", "ext", ")", ")" ]
return the name of the installer built by wininst command .
train
false
37,114
def open_with_editor(filepath): editor_cmd = editor().split() try: subprocess.call((editor_cmd + [filepath])) except OSError: die(('Could not launch ' + editor()))
[ "def", "open_with_editor", "(", "filepath", ")", ":", "editor_cmd", "=", "editor", "(", ")", ".", "split", "(", ")", "try", ":", "subprocess", ".", "call", "(", "(", "editor_cmd", "+", "[", "filepath", "]", ")", ")", "except", "OSError", ":", "die", ...
open filepath using the editor specified by the environment variables .
train
false
37,115
def _seed(a=None, max_bytes=8): if (a is None): a = _bigint_from_bytes(os.urandom(max_bytes)) elif isinstance(a, str): a = a.encode('utf8') a += hashlib.sha512(a).digest() a = _bigint_from_bytes(a[:max_bytes]) elif isinstance(a, integer_types): a = (a % (2 ** (8 * max_bytes))) else: raise error.Error('I...
[ "def", "_seed", "(", "a", "=", "None", ",", "max_bytes", "=", "8", ")", ":", "if", "(", "a", "is", "None", ")", ":", "a", "=", "_bigint_from_bytes", "(", "os", ".", "urandom", "(", "max_bytes", ")", ")", "elif", "isinstance", "(", "a", ",", "str"...
create a strong random seed .
train
false
37,116
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('--password', metavar='<password>', dest='password', help=_('The admin password to be set in the rescue environment.')) @utils.arg('--image', metavar='<image>', dest='image', help=_('The image to rescue with.')) def do_rescue(cs, args)...
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'--password'", ",", "metavar", "=", "'<password>'", ",", "dest", "=", "'passwor...
reboots a server into rescue mode .
train
false
37,117
def send_notify_osd(title, message): global _NTFOSD if (not _HAVE_NTFOSD): return T('Not available') error = 'NotifyOSD not working' icon = os.path.join(sabnzbd.DIR_PROG, 'sabnzbd.ico') _NTFOSD = (_NTFOSD or pynotify.init('icon-summary-body')) if _NTFOSD: logging.info('Send to NotifyOSD: %s / %s', title, mess...
[ "def", "send_notify_osd", "(", "title", ",", "message", ")", ":", "global", "_NTFOSD", "if", "(", "not", "_HAVE_NTFOSD", ")", ":", "return", "T", "(", "'Not available'", ")", "error", "=", "'NotifyOSD not working'", "icon", "=", "os", ".", "path", ".", "jo...
send a message to notifyosd .
train
false
37,118
@no_debug_mode def test_train_example(): assert (config.mode != 'DEBUG_MODE') path = pylearn2.__path__[0] train_example_path = os.path.join(path, 'scripts', 'tutorials', 'grbm_smd') if (not os.path.isfile(os.path.join(train_example_path, 'cifar10_preprocessed_train.pkl'))): raise SkipTest cwd = os.getcwd() try:...
[ "@", "no_debug_mode", "def", "test_train_example", "(", ")", ":", "assert", "(", "config", ".", "mode", "!=", "'DEBUG_MODE'", ")", "path", "=", "pylearn2", ".", "__path__", "[", "0", "]", "train_example_path", "=", "os", ".", "path", ".", "join", "(", "p...
tests that the grbm_smd example script runs correctly .
train
false
37,119
def list_vns(call=None): if (call == 'action'): raise SaltCloudSystemExit('The list_vns function must be called with -f or --function.') (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) vn_pool = server.one.vnpool.info(auth, (-2), (-1), (-1))[1] vns = {} for v_network in _get_xml(vn_p...
[ "def", "list_vns", "(", "call", "=", "None", ")", ":", "if", "(", "call", "==", "'action'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The list_vns function must be called with -f or --function.'", ")", "(", "server", ",", "user", ",", "password", ")", "="...
lists all virtual networks available to the user and the users groups .
train
true
37,121
def render_and_create_dir(dirname, context, output_dir, environment, overwrite_if_exists=False): name_tmpl = environment.from_string(dirname) rendered_dirname = name_tmpl.render(**context) dir_to_create = os.path.normpath(os.path.join(output_dir, rendered_dirname)) logger.debug(u'Rendered dir {} must exist in outpu...
[ "def", "render_and_create_dir", "(", "dirname", ",", "context", ",", "output_dir", ",", "environment", ",", "overwrite_if_exists", "=", "False", ")", ":", "name_tmpl", "=", "environment", ".", "from_string", "(", "dirname", ")", "rendered_dirname", "=", "name_tmpl...
render name of a directory .
train
true
37,124
def typecast_string(s): if ((not s) and (not isinstance(s, str))): return s return smart_unicode(s)
[ "def", "typecast_string", "(", "s", ")", ":", "if", "(", "(", "not", "s", ")", "and", "(", "not", "isinstance", "(", "s", ",", "str", ")", ")", ")", ":", "return", "s", "return", "smart_unicode", "(", "s", ")" ]
cast all returned strings to unicode strings .
train
false
37,125
def get_all_cluster_mors(session): try: results = session._call_method(vim_util, 'get_objects', 'ClusterComputeResource', ['name']) session._call_method(vutil, 'cancel_retrieval', results) if (results.objects is None): return [] else: return results.objects except Exception as excep: LOG.warning(_LW('...
[ "def", "get_all_cluster_mors", "(", "session", ")", ":", "try", ":", "results", "=", "session", ".", "_call_method", "(", "vim_util", ",", "'get_objects'", ",", "'ClusterComputeResource'", ",", "[", "'name'", "]", ")", "session", ".", "_call_method", "(", "vut...
get all the clusters in the vcenter .
train
false
37,127
def test_pickle_indexed_table(protocol): t = simple_table() t.add_index('a') t.add_index(['a', 'b']) ts = pickle.dumps(t) tp = pickle.loads(ts) assert (len(t.indices) == len(tp.indices)) for (index, indexp) in zip(t.indices, tp.indices): assert np.all((index.data.data == indexp.data.data)) assert (index.data...
[ "def", "test_pickle_indexed_table", "(", "protocol", ")", ":", "t", "=", "simple_table", "(", ")", "t", ".", "add_index", "(", "'a'", ")", "t", ".", "add_index", "(", "[", "'a'", ",", "'b'", "]", ")", "ts", "=", "pickle", ".", "dumps", "(", "t", ")...
ensure that any indices that have been added will survive pickling .
train
false
37,128
def make_caller_id(name): return make_global_ns(ns_join(get_ros_namespace(), name))
[ "def", "make_caller_id", "(", "name", ")", ":", "return", "make_global_ns", "(", "ns_join", "(", "get_ros_namespace", "(", ")", ",", "name", ")", ")" ]
resolve a local name to the caller id based on ros environment settings .
train
false
37,130
def _check_for_default_values(fname, arg_val_dict, compat_args): for key in arg_val_dict: try: v1 = arg_val_dict[key] v2 = compat_args[key] if (((v1 is not None) and (v2 is None)) or ((v1 is None) and (v2 is not None))): match = False else: match = (v1 == v2) if (not is_bool(match)): raise...
[ "def", "_check_for_default_values", "(", "fname", ",", "arg_val_dict", ",", "compat_args", ")", ":", "for", "key", "in", "arg_val_dict", ":", "try", ":", "v1", "=", "arg_val_dict", "[", "key", "]", "v2", "=", "compat_args", "[", "key", "]", "if", "(", "(...
check that the keys in arg_val_dict are mapped to their default values as specified in compat_args .
train
true
37,131
def GetAllFieldInDocument(document, field_name): fields = [] for f in document.field_list(): if (f.name() == field_name): fields.append(f) return fields
[ "def", "GetAllFieldInDocument", "(", "document", ",", "field_name", ")", ":", "fields", "=", "[", "]", "for", "f", "in", "document", ".", "field_list", "(", ")", ":", "if", "(", "f", ".", "name", "(", ")", "==", "field_name", ")", ":", "fields", ".",...
find and return all fields with the provided name in the document .
train
false
37,132
@pytest.mark.skipif('True', reason='Refactor a few parser things first.') def test_basic_parsing(): prs = ParserWithRecovery(load_grammar(), code_basic_features) diff_code_assert(code_basic_features, prs.module.get_code())
[ "@", "pytest", ".", "mark", ".", "skipif", "(", "'True'", ",", "reason", "=", "'Refactor a few parser things first.'", ")", "def", "test_basic_parsing", "(", ")", ":", "prs", "=", "ParserWithRecovery", "(", "load_grammar", "(", ")", ",", "code_basic_features", "...
validate the parsing features .
train
false
37,133
def _validate_timestamp_fields(query, field_name, operator_list, allow_timestamps): for item in query: if (item.field == field_name): if (not allow_timestamps): raise wsme.exc.UnknownArgument(field_name, ('not valid for ' + 'this resource')) if (item.op not in operator_list): raise wsme.exc.InvalidInpu...
[ "def", "_validate_timestamp_fields", "(", "query", ",", "field_name", ",", "operator_list", ",", "allow_timestamps", ")", ":", "for", "item", "in", "query", ":", "if", "(", "item", ".", "field", "==", "field_name", ")", ":", "if", "(", "not", "allow_timestam...
validates the timestamp related constraints in a query if there are any .
train
false
37,134
def _swap_curly(string): return string.replace('{{ ', '{{').replace('{{', '\x00').replace('{', '{{').replace('\x00', '{').replace(' }}', '}}').replace('}}', '\x00').replace('}', '}}').replace('\x00', '}')
[ "def", "_swap_curly", "(", "string", ")", ":", "return", "string", ".", "replace", "(", "'{{ '", ",", "'{{'", ")", ".", "replace", "(", "'{{'", ",", "'\\x00'", ")", ".", "replace", "(", "'{'", ",", "'{{'", ")", ".", "replace", "(", "'\\x00'", ",", ...
swap single and double curly brackets .
train
true
37,135
def read_crypto_key(key_path, key_type=None): from keyczar.keys import AesKey key_type = (key_type or AesKey) with open(key_path) as key_file: key = key_type.Read(key_file.read()) return key
[ "def", "read_crypto_key", "(", "key_path", ",", "key_type", "=", "None", ")", ":", "from", "keyczar", ".", "keys", "import", "AesKey", "key_type", "=", "(", "key_type", "or", "AesKey", ")", "with", "open", "(", "key_path", ")", "as", "key_file", ":", "ke...
return the crypto key given a path to key file and the key type .
train
false
37,136
@with_device @no_emulator def unlock_bootloader(): AdbClient().reboot_bootloader() fastboot(['oem', 'unlock']) fastboot(['continue'])
[ "@", "with_device", "@", "no_emulator", "def", "unlock_bootloader", "(", ")", ":", "AdbClient", "(", ")", ".", "reboot_bootloader", "(", ")", "fastboot", "(", "[", "'oem'", ",", "'unlock'", "]", ")", "fastboot", "(", "[", "'continue'", "]", ")" ]
unlocks the bootloader of the device .
train
false
37,137
def collect_dependencies(attributes, all_attributes): dependencies = {attr.ref: attr.dependencies for attr in all_attributes} depsorted = depsort_attributes([attr.ref for attr in attributes], dependencies) return depsorted
[ "def", "collect_dependencies", "(", "attributes", ",", "all_attributes", ")", ":", "dependencies", "=", "{", "attr", ".", "ref", ":", "attr", ".", "dependencies", "for", "attr", "in", "all_attributes", "}", "depsorted", "=", "depsort_attributes", "(", "[", "at...
collect all original and dependant cube attributes for attributes .
train
false
37,140
@verbose def ica_find_ecg_events(raw, ecg_source, event_id=999, tstart=0.0, l_freq=5, h_freq=35, qrs_threshold='auto', verbose=None): logger.info('Using ICA source to identify heart beats') ecg_events = qrs_detector(raw.info['sfreq'], ecg_source.ravel(), tstart=tstart, thresh_value=qrs_threshold, l_freq=l_freq, h_fre...
[ "@", "verbose", "def", "ica_find_ecg_events", "(", "raw", ",", "ecg_source", ",", "event_id", "=", "999", ",", "tstart", "=", "0.0", ",", "l_freq", "=", "5", ",", "h_freq", "=", "35", ",", "qrs_threshold", "=", "'auto'", ",", "verbose", "=", "None", ")...
find ecg peaks from one selected ica source .
train
false
37,141
def getRadiusArealizedBasedOnAreaRadius(elementNode, radius, sides): if elementNode.getCascadeBoolean(False, 'radiusAreal'): return radius return (radius * euclidean.getRadiusArealizedMultiplier(sides))
[ "def", "getRadiusArealizedBasedOnAreaRadius", "(", "elementNode", ",", "radius", ",", "sides", ")", ":", "if", "elementNode", ".", "getCascadeBoolean", "(", "False", ",", "'radiusAreal'", ")", ":", "return", "radius", "return", "(", "radius", "*", "euclidean", "...
get the areal radius from the radius .
train
false
37,143
def _two_element_tuple(int_or_tuple): if isinstance(int_or_tuple, (list, tuple)): if (len(int_or_tuple) != 2): raise ValueError(('Must be a list with 2 elements: %s' % int_or_tuple)) return (int(int_or_tuple[0]), int(int_or_tuple[1])) if isinstance(int_or_tuple, int): return (int(int_or_tuple), int(int_or_tu...
[ "def", "_two_element_tuple", "(", "int_or_tuple", ")", ":", "if", "isinstance", "(", "int_or_tuple", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "(", "len", "(", "int_or_tuple", ")", "!=", "2", ")", ":", "raise", "ValueError", "(", "(", "'Must...
converts int_or_tuple to height .
train
true
37,145
def elem_style(style_rules, cls, inherited_style): classes = cls.split() style = inherited_style.copy() for cls in classes: style.update(style_rules.get(cls, {})) wt = style.get(u'font-weight', None) pwt = inherited_style.get(u'font-weight', u'400') if (wt == u'bolder'): style[u'font-weight'] = {u'100': u'400...
[ "def", "elem_style", "(", "style_rules", ",", "cls", ",", "inherited_style", ")", ":", "classes", "=", "cls", ".", "split", "(", ")", "style", "=", "inherited_style", ".", "copy", "(", ")", "for", "cls", "in", "classes", ":", "style", ".", "update", "(...
find the effective style for the given element .
train
false
37,146
def apply_dropout(computation_graph, variables, drop_prob, rng=None, seed=None, custom_divisor=None): if ((not rng) and (not seed)): seed = config.default_seed if (not rng): rng = MRG_RandomStreams(seed) if (custom_divisor is None): divisor = (1 - drop_prob) else: divisor = custom_divisor replacements = [(...
[ "def", "apply_dropout", "(", "computation_graph", ",", "variables", ",", "drop_prob", ",", "rng", "=", "None", ",", "seed", "=", "None", ",", "custom_divisor", "=", "None", ")", ":", "if", "(", "(", "not", "rng", ")", "and", "(", "not", "seed", ")", ...
apply dropout to specified variables in a graph .
train
false
37,147
def grid_graph(dim, periodic=False): dlabel = ('%s' % str(dim)) if (not dim): G = empty_graph(0) G.name = ('grid_graph(%s)' % dlabel) return G if periodic: func = cycle_graph else: func = path_graph G = func(dim[0]) for current_dim in dim[1:]: Gold = G.copy() Gnew = func(current_dim) G = nx.cartes...
[ "def", "grid_graph", "(", "dim", ",", "periodic", "=", "False", ")", ":", "dlabel", "=", "(", "'%s'", "%", "str", "(", "dim", ")", ")", "if", "(", "not", "dim", ")", ":", "G", "=", "empty_graph", "(", "0", ")", "G", ".", "name", "=", "(", "'g...
return the n-dimensional grid graph .
train
false
37,148
@sync_performer @do def perform_download_s3_key_recursively(dispatcher, intent): keys = (yield Effect(ListS3Keys(prefix=(intent.source_prefix + '/'), bucket=intent.source_bucket))) for key in keys: if (not key.endswith(intent.filter_extensions)): continue path = intent.target_path.preauthChild(key) if (not p...
[ "@", "sync_performer", "@", "do", "def", "perform_download_s3_key_recursively", "(", "dispatcher", ",", "intent", ")", ":", "keys", "=", "(", "yield", "Effect", "(", "ListS3Keys", "(", "prefix", "=", "(", "intent", ".", "source_prefix", "+", "'/'", ")", ",",...
see :class:downloads3keyrecursively .
train
false
37,150
def kegg_conv(target_db, source_db, option=None): if (option and (option not in ['turtle', 'n-triple'])): raise Exception('Invalid option arg for kegg conv request.') if isinstance(source_db, list): source_db = '+'.join(source_db) if ((target_db in ['ncbi-gi', 'ncbi-geneid', 'uniprot']) or (source_db in ['ncbi-g...
[ "def", "kegg_conv", "(", "target_db", ",", "source_db", ",", "option", "=", "None", ")", ":", "if", "(", "option", "and", "(", "option", "not", "in", "[", "'turtle'", ",", "'n-triple'", "]", ")", ")", ":", "raise", "Exception", "(", "'Invalid option arg ...
kegg conv - convert kegg identifiers to/from outside identifiers target_db - target database source_db_or_dbentries - source database or database entries option - can be "turtle" or "n-triple" .
train
false
37,153
@register.inclusion_tag('zinnia/tags/dummy.html') def get_archives_entries(template='zinnia/tags/entries_archives.html'): return {'template': template, 'archives': Entry.published.datetimes('publication_date', 'month', order='DESC')}
[ "@", "register", ".", "inclusion_tag", "(", "'zinnia/tags/dummy.html'", ")", "def", "get_archives_entries", "(", "template", "=", "'zinnia/tags/entries_archives.html'", ")", ":", "return", "{", "'template'", ":", "template", ",", "'archives'", ":", "Entry", ".", "pu...
return archives entries .
train
false
37,154
def upload_training_video(videos, api_key=None, env_id=None): with tempfile.TemporaryFile() as archive_file: write_archive(videos, archive_file, env_id=env_id) archive_file.seek(0) logger.info('[%s] Uploading videos of %d training episodes (%d bytes)', env_id, len(videos), util.file_size(archive_file)) file_up...
[ "def", "upload_training_video", "(", "videos", ",", "api_key", "=", "None", ",", "env_id", "=", "None", ")", ":", "with", "tempfile", ".", "TemporaryFile", "(", ")", "as", "archive_file", ":", "write_archive", "(", "videos", ",", "archive_file", ",", "env_id...
videos: should be list of tuples .
train
false
37,155
def external_download(song, filename, url): cmd = config.DOWNLOAD_COMMAND.get (ddir, basename) = (config.DDIR.get, os.path.basename(filename)) cmd_list = shlex.split(cmd) def list_string_sub(orig, repl, lst): ' Replace substrings for items in a list. ' return [(x if (orig not in x) else x.replace(orig, repl)) f...
[ "def", "external_download", "(", "song", ",", "filename", ",", "url", ")", ":", "cmd", "=", "config", ".", "DOWNLOAD_COMMAND", ".", "get", "(", "ddir", ",", "basename", ")", "=", "(", "config", ".", "DDIR", ".", "get", ",", "os", ".", "path", ".", ...
perform download using external application .
train
false
37,156
def env_vars_from_file(filename): if (not os.path.exists(filename)): raise ConfigurationError((u"Couldn't find env file: %s" % filename)) elif (not os.path.isfile(filename)): raise ConfigurationError((u'%s is not a file.' % filename)) env = {} for line in codecs.open(filename, u'r', u'utf-8'): line = line.str...
[ "def", "env_vars_from_file", "(", "filename", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ")", ":", "raise", "ConfigurationError", "(", "(", "u\"Couldn't find env file: %s\"", "%", "filename", ")", ")", "elif", "(", ...
read in a line delimited file of environment variables .
train
false
37,157
def test_word(word): return ((len(word) <= 2) or (word in SAME_BLACKLIST))
[ "def", "test_word", "(", "word", ")", ":", "return", "(", "(", "len", "(", "word", ")", "<=", "2", ")", "or", "(", "word", "in", "SAME_BLACKLIST", ")", ")" ]
test whether word should be ignored .
train
false
37,158
def ApprovalFind(object_id, token=None): user = getpass.getuser() object_id = rdfvalue.RDFURN(object_id) try: approved_token = security.Approval.GetApprovalForObject(object_id, token=token, username=user) print ('Found token %s' % str(approved_token)) return approved_token except access_control.UnauthorizedAc...
[ "def", "ApprovalFind", "(", "object_id", ",", "token", "=", "None", ")", ":", "user", "=", "getpass", ".", "getuser", "(", ")", "object_id", "=", "rdfvalue", ".", "RDFURN", "(", "object_id", ")", "try", ":", "approved_token", "=", "security", ".", "Appro...
find approvals issued for a specific client .
train
true
37,159
def extract_msg_options(options, keep=MSG_OPTIONS): return dict(((name, options.get(name)) for name in keep))
[ "def", "extract_msg_options", "(", "options", ",", "keep", "=", "MSG_OPTIONS", ")", ":", "return", "dict", "(", "(", "(", "name", ",", "options", ".", "get", "(", "name", ")", ")", "for", "name", "in", "keep", ")", ")" ]
extracts known options to basic_publish from a dict .
train
false
37,161
def cache_node_list(nodes, provider, opts): if (('update_cachedir' not in opts) or (not opts['update_cachedir'])): return base = os.path.join(init_cachedir(), 'active') driver = next(six.iterkeys(opts['providers'][provider])) prov_dir = os.path.join(base, driver, provider) if (not os.path.exists(prov_dir)): os...
[ "def", "cache_node_list", "(", "nodes", ",", "provider", ",", "opts", ")", ":", "if", "(", "(", "'update_cachedir'", "not", "in", "opts", ")", "or", "(", "not", "opts", "[", "'update_cachedir'", "]", ")", ")", ":", "return", "base", "=", "os", ".", "...
if configured to do so .
train
true
37,164
def CheckSection(sec): try: CFG[sec] return True except: CFG[sec] = {} return False
[ "def", "CheckSection", "(", "sec", ")", ":", "try", ":", "CFG", "[", "sec", "]", "return", "True", "except", ":", "CFG", "[", "sec", "]", "=", "{", "}", "return", "False" ]
check if ini section exists .
train
false
37,165
def download_template(name=None, url=None): if (url is None): url = ('http://download.openvz.org/template/precreated/%s.tar.gz' % name) with cd('/var/lib/vz/template/cache'): run_as_root(('wget --progress=dot:mega "%s"' % url))
[ "def", "download_template", "(", "name", "=", "None", ",", "url", "=", "None", ")", ":", "if", "(", "url", "is", "None", ")", ":", "url", "=", "(", "'http://download.openvz.org/template/precreated/%s.tar.gz'", "%", "name", ")", "with", "cd", "(", "'/var/lib/...
download an openvz template .
train
false
37,166
def on_plugin_start(config): pass
[ "def", "on_plugin_start", "(", "config", ")", ":", "pass" ]
called once after plugin is loaded .
train
false
37,168
@not_implemented_for('undirected') def immediate_dominators(G, start): if (start not in G): raise nx.NetworkXError('start is not in G') idom = {start: start} order = list(nx.dfs_postorder_nodes(G, start)) dfn = {u: i for (i, u) in enumerate(order)} order.pop() order.reverse() def intersect(u, v): while (u !=...
[ "@", "not_implemented_for", "(", "'undirected'", ")", "def", "immediate_dominators", "(", "G", ",", "start", ")", ":", "if", "(", "start", "not", "in", "G", ")", ":", "raise", "nx", ".", "NetworkXError", "(", "'start is not in G'", ")", "idom", "=", "{", ...
returns the immediate dominators of all nodes of a directed graph .
train
false
37,170
def clear_index(index_name): index = gae_search.Index(index_name) while True: doc_ids = [document.doc_id for document in index.get_range(ids_only=True)] if (not doc_ids): break index.delete(doc_ids)
[ "def", "clear_index", "(", "index_name", ")", ":", "index", "=", "gae_search", ".", "Index", "(", "index_name", ")", "while", "True", ":", "doc_ids", "=", "[", "document", ".", "doc_id", "for", "document", "in", "index", ".", "get_range", "(", "ids_only", ...
clears an index completely .
train
false
37,172
def as_list(arg): if _is_list(arg): return arg return [arg]
[ "def", "as_list", "(", "arg", ")", ":", "if", "_is_list", "(", "arg", ")", ":", "return", "arg", "return", "[", "arg", "]" ]
coerces arg into a list .
train
false
37,173
def cluster(S, k, ndim): if (sum(abs((S - S.T))) > 1e-10): print 'not symmetric' rowsum = sum(abs(S), axis=0) D = diag((1 / sqrt((rowsum + 1e-06)))) L = dot(D, dot(S, D)) (U, sigma, V) = linalg.svd(L, full_matrices=False) features = array(V[:ndim]).T features = whiten(features) (centroids, distortion) = kmean...
[ "def", "cluster", "(", "S", ",", "k", ",", "ndim", ")", ":", "if", "(", "sum", "(", "abs", "(", "(", "S", "-", "S", ".", "T", ")", ")", ")", ">", "1e-10", ")", ":", "print", "'not symmetric'", "rowsum", "=", "sum", "(", "abs", "(", "S", ")"...
spectral clustering from a similarity matrix .
train
false
37,174
def _params_default(app=None): p = Storage() p.name = (app or 'BASE') p.default_application = (app or 'init') p.default_controller = 'default' p.default_function = 'index' p.routes_app = [] p.routes_in = [] p.routes_out = [] p.routes_onerror = [] p.routes_apps_raw = [] p.error_handler = None p.error_message...
[ "def", "_params_default", "(", "app", "=", "None", ")", ":", "p", "=", "Storage", "(", ")", "p", ".", "name", "=", "(", "app", "or", "'BASE'", ")", "p", ".", "default_application", "=", "(", "app", "or", "'init'", ")", "p", ".", "default_controller",...
returns a new copy of default parameters .
train
false
37,175
def after_this_request(f): _request_ctx_stack.top._after_request_functions.append(f) return f
[ "def", "after_this_request", "(", "f", ")", ":", "_request_ctx_stack", ".", "top", ".", "_after_request_functions", ".", "append", "(", "f", ")", "return", "f" ]
executes a function after this request .
train
false
37,176
def lambda_min(X): X = Expression.cast_to_const(X) return (- lambda_max((- X)))
[ "def", "lambda_min", "(", "X", ")", ":", "X", "=", "Expression", ".", "cast_to_const", "(", "X", ")", "return", "(", "-", "lambda_max", "(", "(", "-", "X", ")", ")", ")" ]
miximum eigenvalue; :math:lambda_{min}(a) .
train
false
37,178
def faster_could_be_isomorphic(G1, G2): if (G1.order() != G2.order()): return False d1 = sorted((d for (n, d) in G1.degree())) d2 = sorted((d for (n, d) in G2.degree())) if (d1 != d2): return False return True
[ "def", "faster_could_be_isomorphic", "(", "G1", ",", "G2", ")", ":", "if", "(", "G1", ".", "order", "(", ")", "!=", "G2", ".", "order", "(", ")", ")", ":", "return", "False", "d1", "=", "sorted", "(", "(", "d", "for", "(", "n", ",", "d", ")", ...
returns false if graphs are definitely not isomorphic .
train
false
37,179
def get_email_from_username(username): user_model = user_models.UserSettingsModel.get_by_normalized_username(UserSettings.normalize_username(username)) if (user_model is None): return None else: return user_model.email
[ "def", "get_email_from_username", "(", "username", ")", ":", "user_model", "=", "user_models", ".", "UserSettingsModel", ".", "get_by_normalized_username", "(", "UserSettings", ".", "normalize_username", "(", "username", ")", ")", "if", "(", "user_model", "is", "Non...
gets the email for a given username .
train
false
37,180
def get_expirer_container(x_delete_at, expirer_divisor, acc, cont, obj): shard_int = (int(hash_path(acc, cont, obj), 16) % 100) return normalize_delete_at_timestamp((((int(x_delete_at) / expirer_divisor) * expirer_divisor) - shard_int))
[ "def", "get_expirer_container", "(", "x_delete_at", ",", "expirer_divisor", ",", "acc", ",", "cont", ",", "obj", ")", ":", "shard_int", "=", "(", "int", "(", "hash_path", "(", "acc", ",", "cont", ",", "obj", ")", ",", "16", ")", "%", "100", ")", "ret...
returns a expiring object container name for given x-delete-at and a/c/o .
train
false