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)
node_samples = est.tree_.n_node_samples[(est.tree_.children_left != (-1))]
assert_greater(np.min(node_samples), 9, 'Failed with {0}'.format(name))
est = TreeEstimator(min_samples_split=0.2, max_leaf_nodes=max_leaf_nodes, random_state=0)
est.fit(X, y)
node_samples = est.tree_.n_node_samples[(est.tree_.children_left != (-1))]
assert_greater(np.min(node_samples), 9, 'Failed with {0}'.format(name))
| [
"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",
")",
"node_samples",
"=",
"est",
".",
"tree_",
".",
"n_node_samples",
"[",
"(",
"est",
".",
"tree_",
".",
"children_left",
"!=",
"(",
"-",
"1",
")",
")",
"]",
"assert_greater",
"(",
"np",
".",
"min",
"(",
"node_samples",
")",
",",
"9",
",",
"'Failed with {0}'",
".",
"format",
"(",
"name",
")",
")",
"est",
"=",
"TreeEstimator",
"(",
"min_samples_split",
"=",
"0.2",
",",
"max_leaf_nodes",
"=",
"max_leaf_nodes",
",",
"random_state",
"=",
"0",
")",
"est",
".",
"fit",
"(",
"X",
",",
"y",
")",
"node_samples",
"=",
"est",
".",
"tree_",
".",
"n_node_samples",
"[",
"(",
"est",
".",
"tree_",
".",
"children_left",
"!=",
"(",
"-",
"1",
")",
")",
"]",
"assert_greater",
"(",
"np",
".",
"min",
"(",
"node_samples",
")",
",",
"9",
",",
"'Failed with {0}'",
".",
"format",
"(",
"name",
")",
")"
] | 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 with an additional '%%'.") % input_url)])
| [
"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 with an additional '%%'.\"",
")",
"%",
"input_url",
")",
"]",
")"
] | 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",
"try",
":",
"mod",
"=",
"tracer",
".",
"__module__",
"except",
"AttributeError",
":",
"try",
":",
"mod",
"=",
"tracer",
".",
"__class__",
".",
"__module__",
"except",
"AttributeError",
":",
"return",
"False",
"return",
"mod",
".",
"startswith",
"(",
"'coverage'",
")"
] | 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",
"in",
"cache",
".",
"itersiblings",
"(",
"parent",
")",
":",
"if",
"(",
"sibling",
"in",
"right",
")",
":",
"(",
"yield",
"sibling",
")",
"break"
] | 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 = source.data;\n\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\n var geometry = cb_data['geometry'];\n\n /// calculate Rect attributes\n var width = geometry['x1'] - geometry['x0'];\n var height = geometry['y1'] - geometry['y0'];\n var x = geometry['x0'] + width/2;\n var y = geometry['y0'] + height/2;\n\n /// update data source with new Rect attributes\n data['x'].push(x);\n data['y'].push(y);\n data['width'].push(width);\n data['height'].push(height);\n\n // trigger update of data source\n source.trigger('change');\n ")
box_select = BoxSelectTool(callback=callback)
plot.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)
plot.add_tools(box_select)
return plot
| [
"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 = source.data;\\n\\n /// get BoxSelectTool dimensions from cb_data parameter of Callback\\n var geometry = cb_data['geometry'];\\n\\n /// calculate Rect attributes\\n var width = geometry['x1'] - geometry['x0'];\\n var height = geometry['y1'] - geometry['y0'];\\n var x = geometry['x0'] + width/2;\\n var y = geometry['y0'] + height/2;\\n\\n /// update data source with new Rect attributes\\n data['x'].push(x);\\n data['y'].push(y);\\n data['width'].push(width);\\n data['height'].push(height);\\n\\n // trigger update of data source\\n source.trigger('change');\\n \"",
")",
"box_select",
"=",
"BoxSelectTool",
"(",
"callback",
"=",
"callback",
")",
"plot",
".",
"add_glyph",
"(",
"source",
",",
"rect",
",",
"selection_glyph",
"=",
"rect",
",",
"nonselection_glyph",
"=",
"rect",
")",
"plot",
".",
"add_tools",
"(",
"box_select",
")",
"return",
"plot"
] | 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' % (vdi_uuid, exc)))
| [
"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'",
"%",
"(",
"vdi_uuid",
",",
"exc",
")",
")",
")"
] | 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_index = len(pk)
return _yield_csv_messages(foreign_cls, columns, first_string_index, csvreader, force_column=force_column)
| [
"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_index",
"=",
"len",
"(",
"pk",
")",
"return",
"_yield_csv_messages",
"(",
"foreign_cls",
",",
"columns",
",",
"first_string_index",
",",
"csvreader",
",",
"force_column",
"=",
"force_column",
")"
] | 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",
".",
"unit",
")",
")"
] | 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 = cls1.from_entity(entity)
models.append(model)
if multiple:
return models
assert (len(models) == 1)
return models[0]
return datastore.GetAsync(keys, extra_hook=extra_hook, **kwargs)
| [
"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",
"=",
"cls1",
".",
"from_entity",
"(",
"entity",
")",
"models",
".",
"append",
"(",
"model",
")",
"if",
"multiple",
":",
"return",
"models",
"assert",
"(",
"len",
"(",
"models",
")",
"==",
"1",
")",
"return",
"models",
"[",
"0",
"]",
"return",
"datastore",
".",
"GetAsync",
"(",
"keys",
",",
"extra_hook",
"=",
"extra_hook",
",",
"**",
"kwargs",
")"
] | 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",
":",
"return",
"f",
"(",
"self",
",",
"tmp",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"tmp",
")",
"return",
"wrapper"
] | 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_size = int((float(img.size[1]) * float(width_percent)))
img = img.resize((basewidth, height_size), PIL.Image.ANTIALIAS)
img.save(image_file)
file = UploadedFile(file_path=image_file, filename=filename)
if remove_after_upload:
os.remove(image_file)
return upload(file, upload_path)
| [
"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_size",
"=",
"int",
"(",
"(",
"float",
"(",
"img",
".",
"size",
"[",
"1",
"]",
")",
"*",
"float",
"(",
"width_percent",
")",
")",
")",
"img",
"=",
"img",
".",
"resize",
"(",
"(",
"basewidth",
",",
"height_size",
")",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
"img",
".",
"save",
"(",
"image_file",
")",
"file",
"=",
"UploadedFile",
"(",
"file_path",
"=",
"image_file",
",",
"filename",
"=",
"filename",
")",
"if",
"remove_after_upload",
":",
"os",
".",
"remove",
"(",
"image_file",
")",
"return",
"upload",
"(",
"file",
",",
"upload_path",
")"
] | 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)))
totalToothAngle += toothAngleRadian
return gearProfile
| [
"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",
")",
")",
")",
"totalToothAngle",
"+=",
"toothAngleRadian",
"return",
"gearProfile"
] | 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 AttributeError()
except AttributeError:
try:
found = sym.celery
if isinstance(found, ModuleType):
raise AttributeError()
except AttributeError:
if getattr(sym, u'__path__', None):
try:
return find_app(u'{0}.celery'.format(app), symbol_by_name=symbol_by_name, imp=imp)
except ImportError:
pass
for suspect in values(vars(sym)):
if isinstance(suspect, Celery):
return suspect
raise
else:
return found
else:
return found
return sym
| [
"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",
"AttributeError",
"(",
")",
"except",
"AttributeError",
":",
"try",
":",
"found",
"=",
"sym",
".",
"celery",
"if",
"isinstance",
"(",
"found",
",",
"ModuleType",
")",
":",
"raise",
"AttributeError",
"(",
")",
"except",
"AttributeError",
":",
"if",
"getattr",
"(",
"sym",
",",
"u'__path__'",
",",
"None",
")",
":",
"try",
":",
"return",
"find_app",
"(",
"u'{0}.celery'",
".",
"format",
"(",
"app",
")",
",",
"symbol_by_name",
"=",
"symbol_by_name",
",",
"imp",
"=",
"imp",
")",
"except",
"ImportError",
":",
"pass",
"for",
"suspect",
"in",
"values",
"(",
"vars",
"(",
"sym",
")",
")",
":",
"if",
"isinstance",
"(",
"suspect",
",",
"Celery",
")",
":",
"return",
"suspect",
"raise",
"else",
":",
"return",
"found",
"else",
":",
"return",
"found",
"return",
"sym"
] | 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):
return x
else:
return subsample_f(x.astype(int), seqs_per_sample)
subsampled_otu_table = otu_table.transform(func, axis='sample')
return subsampled_otu_table
| [
"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",
")",
":",
"return",
"x",
"else",
":",
"return",
"subsample_f",
"(",
"x",
".",
"astype",
"(",
"int",
")",
",",
"seqs_per_sample",
")",
"subsampled_otu_table",
"=",
"otu_table",
".",
"transform",
"(",
"func",
",",
"axis",
"=",
"'sample'",
")",
"return",
"subsampled_otu_table"
] | 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'",
")",
"return",
"context",
".",
"is_admin"
] | 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 line in mach_info.readlines():
match = pattern.match(line)
if match:
desc = _strip_quotes(match.group(1).strip()).replace('\\"', '"')
except IOError:
return False
return desc
| [
"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",
"line",
"in",
"mach_info",
".",
"readlines",
"(",
")",
":",
"match",
"=",
"pattern",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"desc",
"=",
"_strip_quotes",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
".",
"replace",
"(",
"'\\\\\"'",
",",
"'\"'",
")",
"except",
"IOError",
":",
"return",
"False",
"return",
"desc"
] | 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",
".",
"error",
"(",
"\"Error saving data '%s' to Dweet.io\"",
",",
"msg",
")"
] | 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, _, filenames) in os.walk(in_path):
for filename in filenames:
if (not filename.startswith('.')):
for (name, resizer) in resizers.items():
in_filename = path.join(dirpath, filename)
out_path = get_out_path(pelican, in_path, in_filename, name)
resizer.resize_file_to(in_filename, out_path, pelican.settings.get('THUMBNAIL_KEEP_NAME'))
| [
"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",
",",
"_",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"in_path",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"if",
"(",
"not",
"filename",
".",
"startswith",
"(",
"'.'",
")",
")",
":",
"for",
"(",
"name",
",",
"resizer",
")",
"in",
"resizers",
".",
"items",
"(",
")",
":",
"in_filename",
"=",
"path",
".",
"join",
"(",
"dirpath",
",",
"filename",
")",
"out_path",
"=",
"get_out_path",
"(",
"pelican",
",",
"in_path",
",",
"in_filename",
",",
"name",
")",
"resizer",
".",
"resize_file_to",
"(",
"in_filename",
",",
"out_path",
",",
"pelican",
".",
"settings",
".",
"get",
"(",
"'THUMBNAIL_KEEP_NAME'",
")",
")"
] | 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 = []
for filepath in sorted_file_list:
(buffer_num, close_window) = _OpenFileInSplitIfNeeded(filepath)
ReplaceChunksInBuffer(chunks_by_file[filepath], vim.buffers[buffer_num], locations)
if close_window:
vim.command(u'lclose')
vim.command(u'hide')
if locations:
SetQuickFixList(locations)
PostVimMessage(u'Applied {0} changes'.format(len(chunks)), warning=False)
| [
"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",
"=",
"[",
"]",
"for",
"filepath",
"in",
"sorted_file_list",
":",
"(",
"buffer_num",
",",
"close_window",
")",
"=",
"_OpenFileInSplitIfNeeded",
"(",
"filepath",
")",
"ReplaceChunksInBuffer",
"(",
"chunks_by_file",
"[",
"filepath",
"]",
",",
"vim",
".",
"buffers",
"[",
"buffer_num",
"]",
",",
"locations",
")",
"if",
"close_window",
":",
"vim",
".",
"command",
"(",
"u'lclose'",
")",
"vim",
".",
"command",
"(",
"u'hide'",
")",
"if",
"locations",
":",
"SetQuickFixList",
"(",
"locations",
")",
"PostVimMessage",
"(",
"u'Applied {0} changes'",
".",
"format",
"(",
"len",
"(",
"chunks",
")",
")",
",",
"warning",
"=",
"False",
")"
] | 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 targets for subscriptions')
events = constants.NODE_SUBSCRIPTIONS_AVAILABLE
notification_type = 'email_transactional'
target_id = node._id
if user.is_registered:
for event in events:
event_id = to_subscription_key(target_id, event)
global_event_id = to_subscription_key(user._id, ('global_' + event))
global_subscription = NotificationSubscription.load(global_event_id)
subscription = NotificationSubscription.load(event_id)
if (not (node and node.parent_node and (not subscription) and (node.creator == user))):
if (not subscription):
subscription = NotificationSubscription(_id=event_id, owner=node, event_name=event)
subscription.save()
if global_subscription:
global_notification_type = get_global_notification_type(global_subscription, user)
subscription.add_user_to_subscription(user, global_notification_type)
else:
subscription.add_user_to_subscription(user, notification_type)
subscription.save()
| [
"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 targets for subscriptions'",
")",
"events",
"=",
"constants",
".",
"NODE_SUBSCRIPTIONS_AVAILABLE",
"notification_type",
"=",
"'email_transactional'",
"target_id",
"=",
"node",
".",
"_id",
"if",
"user",
".",
"is_registered",
":",
"for",
"event",
"in",
"events",
":",
"event_id",
"=",
"to_subscription_key",
"(",
"target_id",
",",
"event",
")",
"global_event_id",
"=",
"to_subscription_key",
"(",
"user",
".",
"_id",
",",
"(",
"'global_'",
"+",
"event",
")",
")",
"global_subscription",
"=",
"NotificationSubscription",
".",
"load",
"(",
"global_event_id",
")",
"subscription",
"=",
"NotificationSubscription",
".",
"load",
"(",
"event_id",
")",
"if",
"(",
"not",
"(",
"node",
"and",
"node",
".",
"parent_node",
"and",
"(",
"not",
"subscription",
")",
"and",
"(",
"node",
".",
"creator",
"==",
"user",
")",
")",
")",
":",
"if",
"(",
"not",
"subscription",
")",
":",
"subscription",
"=",
"NotificationSubscription",
"(",
"_id",
"=",
"event_id",
",",
"owner",
"=",
"node",
",",
"event_name",
"=",
"event",
")",
"subscription",
".",
"save",
"(",
")",
"if",
"global_subscription",
":",
"global_notification_type",
"=",
"get_global_notification_type",
"(",
"global_subscription",
",",
"user",
")",
"subscription",
".",
"add_user_to_subscription",
"(",
"user",
",",
"global_notification_type",
")",
"else",
":",
"subscription",
".",
"add_user_to_subscription",
"(",
"user",
",",
"notification_type",
")",
"subscription",
".",
"save",
"(",
")"
] | 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=inputs, outputs=outputs, mode=mode, updates=updates, givens=givens, no_default_updates=no_default_updates, accept_inplace=accept_inplace, name=name, rebuild_strict=rebuild_strict, allow_input_downcast=allow_input_downcast, profile=profile, on_unused_input=on_unused_input)
with open(filename, 'wb') as f:
import theano.misc.pkl_utils
pickler = theano.misc.pkl_utils.StripPickler(f, protocol=(-1), extra_tag_to_remove=extra_tag_to_remove)
pickler.dump(d)
| [
"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",
"=",
"inputs",
",",
"outputs",
"=",
"outputs",
",",
"mode",
"=",
"mode",
",",
"updates",
"=",
"updates",
",",
"givens",
"=",
"givens",
",",
"no_default_updates",
"=",
"no_default_updates",
",",
"accept_inplace",
"=",
"accept_inplace",
",",
"name",
"=",
"name",
",",
"rebuild_strict",
"=",
"rebuild_strict",
",",
"allow_input_downcast",
"=",
"allow_input_downcast",
",",
"profile",
"=",
"profile",
",",
"on_unused_input",
"=",
"on_unused_input",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"import",
"theano",
".",
"misc",
".",
"pkl_utils",
"pickler",
"=",
"theano",
".",
"misc",
".",
"pkl_utils",
".",
"StripPickler",
"(",
"f",
",",
"protocol",
"=",
"(",
"-",
"1",
")",
",",
"extra_tag_to_remove",
"=",
"extra_tag_to_remove",
")",
"pickler",
".",
"dump",
"(",
"d",
")"
] | 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_bounds, reqs)
if conda_format:
reqs = map(_conda_format, reqs)
return list(reqs)
| [
"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_bounds",
",",
"reqs",
")",
"if",
"conda_format",
":",
"reqs",
"=",
"map",
"(",
"_conda_format",
",",
"reqs",
")",
"return",
"list",
"(",
"reqs",
")"
] | 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",
"(",
"param_text_utf8",
")",
"return",
"(",
"param_text_ascii",
"or",
"Charset",
"(",
"'utf8'",
")",
".",
"header_encode",
"(",
"param_text_utf8",
")",
")"
] | 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",
"(",
"[",
"(",
"(",
"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",
"(",
")"
] | 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('topo_view', data=dataset.get_topological_view())
f.create_dataset('y', data=dataset.get_targets())
trainer = yaml_parse.load((topo_view_yaml % {'filename': filename}))
trainer.main_loop()
os.remove(filename)
| [
"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",
"(",
"'topo_view'",
",",
"data",
"=",
"dataset",
".",
"get_topological_view",
"(",
")",
")",
"f",
".",
"create_dataset",
"(",
"'y'",
",",
"data",
"=",
"dataset",
".",
"get_targets",
"(",
")",
")",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"(",
"topo_view_yaml",
"%",
"{",
"'filename'",
":",
"filename",
"}",
")",
")",
"trainer",
".",
"main_loop",
"(",
")",
"os",
".",
"remove",
"(",
"filename",
")"
] | 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_STYLE_FACTORY()
style_factory = _STYLE_NAME_TO_FACTORY.get(style_config.lower())
if (style_factory is not None):
return style_factory()
if style_config.startswith('{'):
config = _CreateConfigParserFromConfigString(style_config)
else:
config = _CreateConfigParserFromConfigFile(style_config)
return _CreateStyleFromConfigParser(config)
| [
"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_STYLE_FACTORY",
"(",
")",
"style_factory",
"=",
"_STYLE_NAME_TO_FACTORY",
".",
"get",
"(",
"style_config",
".",
"lower",
"(",
")",
")",
"if",
"(",
"style_factory",
"is",
"not",
"None",
")",
":",
"return",
"style_factory",
"(",
")",
"if",
"style_config",
".",
"startswith",
"(",
"'{'",
")",
":",
"config",
"=",
"_CreateConfigParserFromConfigString",
"(",
"style_config",
")",
"else",
":",
"config",
"=",
"_CreateConfigParserFromConfigFile",
"(",
"style_config",
")",
"return",
"_CreateStyleFromConfigParser",
"(",
"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, variables=True)
subs_dict1 = {}
subs_dict2 = {}
for (i, x) in enumerate(frame):
subs_dict1[frame[i]] = x.dot(position1)
subs_dict2[frame[i]] = x.dot(position2)
return (scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1))
| [
"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",
",",
"variables",
"=",
"True",
")",
"subs_dict1",
"=",
"{",
"}",
"subs_dict2",
"=",
"{",
"}",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"frame",
")",
":",
"subs_dict1",
"[",
"frame",
"[",
"i",
"]",
"]",
"=",
"x",
".",
"dot",
"(",
"position1",
")",
"subs_dict2",
"[",
"frame",
"[",
"i",
"]",
"]",
"=",
"x",
".",
"dot",
"(",
"position2",
")",
"return",
"(",
"scalar_fn",
".",
"subs",
"(",
"subs_dict2",
")",
"-",
"scalar_fn",
".",
"subs",
"(",
"subs_dict1",
")",
")"
] | 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",
".",
"strip",
"(",
")",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"u'\\n'",
")"
] | 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__
if (geom['type'] == 'Point'):
geom['coordinates'] = _p2p(geom['coordinates'], projection)
elif (geom['type'] in ('MultiPoint', 'LineString')):
geom['coordinates'] = [_p2p(c, projection) for c in geom['coordinates']]
elif (geom['type'] in ('MultiLineString', 'Polygon')):
geom['coordinates'] = [[_p2p(c, projection) for c in cs] for cs in geom['coordinates']]
elif (geom['type'] == 'MultiPolygon'):
geom['coordinates'] = [[[_p2p(c, projection) for c in cs] for cs in ccs] for ccs in geom['coordinates']]
return geom
| [
"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__",
"if",
"(",
"geom",
"[",
"'type'",
"]",
"==",
"'Point'",
")",
":",
"geom",
"[",
"'coordinates'",
"]",
"=",
"_p2p",
"(",
"geom",
"[",
"'coordinates'",
"]",
",",
"projection",
")",
"elif",
"(",
"geom",
"[",
"'type'",
"]",
"in",
"(",
"'MultiPoint'",
",",
"'LineString'",
")",
")",
":",
"geom",
"[",
"'coordinates'",
"]",
"=",
"[",
"_p2p",
"(",
"c",
",",
"projection",
")",
"for",
"c",
"in",
"geom",
"[",
"'coordinates'",
"]",
"]",
"elif",
"(",
"geom",
"[",
"'type'",
"]",
"in",
"(",
"'MultiLineString'",
",",
"'Polygon'",
")",
")",
":",
"geom",
"[",
"'coordinates'",
"]",
"=",
"[",
"[",
"_p2p",
"(",
"c",
",",
"projection",
")",
"for",
"c",
"in",
"cs",
"]",
"for",
"cs",
"in",
"geom",
"[",
"'coordinates'",
"]",
"]",
"elif",
"(",
"geom",
"[",
"'type'",
"]",
"==",
"'MultiPolygon'",
")",
":",
"geom",
"[",
"'coordinates'",
"]",
"=",
"[",
"[",
"[",
"_p2p",
"(",
"c",
",",
"projection",
")",
"for",
"c",
"in",
"cs",
"]",
"for",
"cs",
"in",
"ccs",
"]",
"for",
"ccs",
"in",
"geom",
"[",
"'coordinates'",
"]",
"]",
"return",
"geom"
] | 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, 'if')
if_leaf.set_prefix(' ')
inner_args.append(Node(syms.comp_if, [if_leaf, test]))
inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)])
return Node(syms.atom, [Leaf(token.LBRACE, '['), inner, Leaf(token.RBRACE, ']')])
| [
"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",
",",
"'if'",
")",
"if_leaf",
".",
"set_prefix",
"(",
"' '",
")",
"inner_args",
".",
"append",
"(",
"Node",
"(",
"syms",
".",
"comp_if",
",",
"[",
"if_leaf",
",",
"test",
"]",
")",
")",
"inner",
"=",
"Node",
"(",
"syms",
".",
"listmaker",
",",
"[",
"xp",
",",
"Node",
"(",
"syms",
".",
"comp_for",
",",
"inner_args",
")",
"]",
")",
"return",
"Node",
"(",
"syms",
".",
"atom",
",",
"[",
"Leaf",
"(",
"token",
".",
"LBRACE",
",",
"'['",
")",
",",
"inner",
",",
"Leaf",
"(",
"token",
".",
"RBRACE",
",",
"']'",
")",
"]",
")"
] | 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",
"]",
"=",
"obj",
"except",
"AttributeError",
":",
"pass",
"return",
"memo"
] | 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_path",
")",
"import",
"dev_appserver",
"dev_appserver",
".",
"fix_sys_path",
"(",
")",
"import",
"google",
".",
"appengine",
".",
"tools",
".",
"os_compat"
] | 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://pypi.pinaxproject.com' in result.stdout), result.stdout
assert (('Skipping link %s' % data.find_links) in result.stdout)
| [
"@",
"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://pypi.pinaxproject.com'",
"in",
"result",
".",
"stdout",
")",
",",
"result",
".",
"stdout",
"assert",
"(",
"(",
"'Skipping link %s'",
"%",
"data",
".",
"find_links",
")",
"in",
"result",
".",
"stdout",
")"
] | 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)]['G'][0], lut[(lut['id'] == ii)]['B'][0], lut[(lut['id'] == ii)]['A'][0]] for ii in np.unique(mgz_data)]
order = np.argsort(label_names)
label_names = [label_names[k] for k in order]
label_colors = [label_colors[k] for k in order]
if return_colors:
return (label_names, label_colors)
else:
return label_names
| [
"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",
")",
"]",
"[",
"'G'",
"]",
"[",
"0",
"]",
",",
"lut",
"[",
"(",
"lut",
"[",
"'id'",
"]",
"==",
"ii",
")",
"]",
"[",
"'B'",
"]",
"[",
"0",
"]",
",",
"lut",
"[",
"(",
"lut",
"[",
"'id'",
"]",
"==",
"ii",
")",
"]",
"[",
"'A'",
"]",
"[",
"0",
"]",
"]",
"for",
"ii",
"in",
"np",
".",
"unique",
"(",
"mgz_data",
")",
"]",
"order",
"=",
"np",
".",
"argsort",
"(",
"label_names",
")",
"label_names",
"=",
"[",
"label_names",
"[",
"k",
"]",
"for",
"k",
"in",
"order",
"]",
"label_colors",
"=",
"[",
"label_colors",
"[",
"k",
"]",
"for",
"k",
"in",
"order",
"]",
"if",
"return_colors",
":",
"return",
"(",
"label_names",
",",
"label_colors",
")",
"else",
":",
"return",
"label_names"
] | 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 ColumnIdentifierError(('Column %s has index %i which already has a pattern.' % (k, idx)))
p2[idx] = patterns[k]
else:
p2[k] = patterns[k]
return p2
except AttributeError:
return dict(((i, pattern_as_function(x)) for (i, x) in enumerate(patterns)))
| [
"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",
"ColumnIdentifierError",
"(",
"(",
"'Column %s has index %i which already has a pattern.'",
"%",
"(",
"k",
",",
"idx",
")",
")",
")",
"p2",
"[",
"idx",
"]",
"=",
"patterns",
"[",
"k",
"]",
"else",
":",
"p2",
"[",
"k",
"]",
"=",
"patterns",
"[",
"k",
"]",
"return",
"p2",
"except",
"AttributeError",
":",
"return",
"dict",
"(",
"(",
"(",
"i",
",",
"pattern_as_function",
"(",
"x",
")",
")",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"patterns",
")",
")",
")"
] | 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, value, typename(value))))
if ((not value) and (not empty_ok)):
raise exception(('%s must not be empty.' % name))
if (len(value.encode('utf-8')) > max_len):
raise exception(('%s must be under %d bytes.' % (name, max_len)))
| [
"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",
",",
"value",
",",
"typename",
"(",
"value",
")",
")",
")",
")",
"if",
"(",
"(",
"not",
"value",
")",
"and",
"(",
"not",
"empty_ok",
")",
")",
":",
"raise",
"exception",
"(",
"(",
"'%s must not be empty.'",
"%",
"name",
")",
")",
"if",
"(",
"len",
"(",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
">",
"max_len",
")",
":",
"raise",
"exception",
"(",
"(",
"'%s must be under %d bytes.'",
"%",
"(",
"name",
",",
"max_len",
")",
")",
")"
] | 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",
")",
")",
"return",
"f",
"(",
")"
] | 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",
")",
":",
"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"
] | 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 IP address/port')
elif (len(ip) == 2):
(addr, port) = ip
if ((not validipaddr(addr)) and validipport(port)):
raise ValueError, (':'.join(ip) + ' is not a valid IP address/port')
port = int(port)
else:
raise ValueError, (':'.join(ip) + ' is not a valid IP address/port')
return (addr, port)
| [
"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 IP address/port'",
")",
"elif",
"(",
"len",
"(",
"ip",
")",
"==",
"2",
")",
":",
"(",
"addr",
",",
"port",
")",
"=",
"ip",
"if",
"(",
"(",
"not",
"validipaddr",
"(",
"addr",
")",
")",
"and",
"validipport",
"(",
"port",
")",
")",
":",
"raise",
"ValueError",
",",
"(",
"':'",
".",
"join",
"(",
"ip",
")",
"+",
"' is not a valid IP address/port'",
")",
"port",
"=",
"int",
"(",
"port",
")",
"else",
":",
"raise",
"ValueError",
",",
"(",
"':'",
".",
"join",
"(",
"ip",
")",
"+",
"' is not a valid IP address/port'",
")",
"return",
"(",
"addr",
",",
"port",
")"
] | 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.\nUpgrade to GDB >= 7.11 for better core-dumps.' % binary()))
gdb_args = ['-batch', '-q', '--nx', '-ex', '"set pagination off"', '-ex', '"set height 0"', '-ex', '"set width 0"', '-ex', '"set use-coredump-filter on"', '-ex', ('"generate-core-file %s"' % temp.name), '-ex', 'detach']
with context.local(terminal=['sh', '-c']):
with context.quiet:
pid = attach(process, gdb_args=gdb_args)
os.waitpid(pid, 0)
return elf.corefile.Core(temp.name)
| [
"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.\\nUpgrade to GDB >= 7.11 for better core-dumps.'",
"%",
"binary",
"(",
")",
")",
")",
"gdb_args",
"=",
"[",
"'-batch'",
",",
"'-q'",
",",
"'--nx'",
",",
"'-ex'",
",",
"'\"set pagination off\"'",
",",
"'-ex'",
",",
"'\"set height 0\"'",
",",
"'-ex'",
",",
"'\"set width 0\"'",
",",
"'-ex'",
",",
"'\"set use-coredump-filter on\"'",
",",
"'-ex'",
",",
"(",
"'\"generate-core-file %s\"'",
"%",
"temp",
".",
"name",
")",
",",
"'-ex'",
",",
"'detach'",
"]",
"with",
"context",
".",
"local",
"(",
"terminal",
"=",
"[",
"'sh'",
",",
"'-c'",
"]",
")",
":",
"with",
"context",
".",
"quiet",
":",
"pid",
"=",
"attach",
"(",
"process",
",",
"gdb_args",
"=",
"gdb_args",
")",
"os",
".",
"waitpid",
"(",
"pid",
",",
"0",
")",
"return",
"elf",
".",
"corefile",
".",
"Core",
"(",
"temp",
".",
"name",
")"
] | 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_source",
",",
"size",
",",
"encoding",
",",
"filetype",
",",
"avoid_if_small",
")"
] | 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, func.func_code.co_filename, func.func_code.co_name, func.func_code.co_firstlineno, func.func_code.co_lnotab, func.func_code.co_freevars, func.func_code.co_cellvars)
return pickle.dumps((code_info, func_info, func.func_doc), pickle.HIGHEST_PROTOCOL)
| [
"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",
",",
"func",
".",
"func_code",
".",
"co_filename",
",",
"func",
".",
"func_code",
".",
"co_name",
",",
"func",
".",
"func_code",
".",
"co_firstlineno",
",",
"func",
".",
"func_code",
".",
"co_lnotab",
",",
"func",
".",
"func_code",
".",
"co_freevars",
",",
"func",
".",
"func_code",
".",
"co_cellvars",
")",
"return",
"pickle",
".",
"dumps",
"(",
"(",
"code_info",
",",
"func_info",
",",
"func",
".",
"func_doc",
")",
",",
"pickle",
".",
"HIGHEST_PROTOCOL",
")"
] | 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",
".",
"close",
"(",
")",
"return",
"port"
] | 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
return True
s3.prep = prep
if (('delete' in request.args) or ((request.env.request_method == 'POST') and (auth.permission.format == 's3json'))):
return s3_rest_controller()
else:
return s3_rest_controller('hrm', 'human_resource')
| [
"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",
"return",
"True",
"s3",
".",
"prep",
"=",
"prep",
"if",
"(",
"(",
"'delete'",
"in",
"request",
".",
"args",
")",
"or",
"(",
"(",
"request",
".",
"env",
".",
"request_method",
"==",
"'POST'",
")",
"and",
"(",
"auth",
".",
"permission",
".",
"format",
"==",
"'s3json'",
")",
")",
")",
":",
"return",
"s3_rest_controller",
"(",
")",
"else",
":",
"return",
"s3_rest_controller",
"(",
"'hrm'",
",",
"'human_resource'",
")"
] | 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",
"(",
"(",
"'Could not launch '",
"+",
"editor",
"(",
")",
")",
")"
] | 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('Invalid type for seed: {} ({})'.format(type(a), a))
return a
| [
"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",
"(",
"'Invalid type for seed: {} ({})'",
".",
"format",
"(",
"type",
"(",
"a",
")",
",",
"a",
")",
")",
"return",
"a"
] | 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):
kwargs = {}
if args.image:
kwargs['image'] = _find_image(cs, args.image)
if args.password:
kwargs['password'] = args.password
utils.print_dict(_find_server(cs, args.server).rescue(**kwargs)[1])
| [
"@",
"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",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"args",
".",
"image",
":",
"kwargs",
"[",
"'image'",
"]",
"=",
"_find_image",
"(",
"cs",
",",
"args",
".",
"image",
")",
"if",
"args",
".",
"password",
":",
"kwargs",
"[",
"'password'",
"]",
"=",
"args",
".",
"password",
"utils",
".",
"print_dict",
"(",
"_find_server",
"(",
"cs",
",",
"args",
".",
"server",
")",
".",
"rescue",
"(",
"**",
"kwargs",
")",
"[",
"1",
"]",
")"
] | 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, message)
try:
note = pynotify.Notification(title, message, icon)
note.show()
except:
logging.info(error)
return error
return None
else:
return error
| [
"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",
",",
"message",
")",
"try",
":",
"note",
"=",
"pynotify",
".",
"Notification",
"(",
"title",
",",
"message",
",",
"icon",
")",
"note",
".",
"show",
"(",
")",
"except",
":",
"logging",
".",
"info",
"(",
"error",
")",
"return",
"error",
"return",
"None",
"else",
":",
"return",
"error"
] | 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:
os.chdir(train_example_path)
train_yaml_path = os.path.join(train_example_path, 'cifar_grbm_smd.yaml')
train_object = load_train_file(train_yaml_path)
train_object.algorithm.termination_criterion.prop_decrease = 0.5
train_object.algorithm.termination_criterion.N = 1
train_object.main_loop()
finally:
os.chdir(cwd)
| [
"@",
"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",
":",
"os",
".",
"chdir",
"(",
"train_example_path",
")",
"train_yaml_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"train_example_path",
",",
"'cifar_grbm_smd.yaml'",
")",
"train_object",
"=",
"load_train_file",
"(",
"train_yaml_path",
")",
"train_object",
".",
"algorithm",
".",
"termination_criterion",
".",
"prop_decrease",
"=",
"0.5",
"train_object",
".",
"algorithm",
".",
"termination_criterion",
".",
"N",
"=",
"1",
"train_object",
".",
"main_loop",
"(",
")",
"finally",
":",
"os",
".",
"chdir",
"(",
"cwd",
")"
] | 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_pool):
vns[v_network.find('NAME').text] = _xml_to_dict(v_network)
return vns
| [
"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_pool",
")",
":",
"vns",
"[",
"v_network",
".",
"find",
"(",
"'NAME'",
")",
".",
"text",
"]",
"=",
"_xml_to_dict",
"(",
"v_network",
")",
"return",
"vns"
] | 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 output_dir {}'.format(dir_to_create, output_dir))
output_dir_exists = os.path.exists(dir_to_create)
if overwrite_if_exists:
if output_dir_exists:
logger.debug(u'Output directory {} already exists,overwriting it'.format(dir_to_create))
elif output_dir_exists:
msg = u'Error: "{}" directory already exists'.format(dir_to_create)
raise OutputDirExistsException(msg)
make_sure_path_exists(dir_to_create)
return dir_to_create
| [
"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 output_dir {}'",
".",
"format",
"(",
"dir_to_create",
",",
"output_dir",
")",
")",
"output_dir_exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"dir_to_create",
")",
"if",
"overwrite_if_exists",
":",
"if",
"output_dir_exists",
":",
"logger",
".",
"debug",
"(",
"u'Output directory {} already exists,overwriting it'",
".",
"format",
"(",
"dir_to_create",
")",
")",
"elif",
"output_dir_exists",
":",
"msg",
"=",
"u'Error: \"{}\" directory already exists'",
".",
"format",
"(",
"dir_to_create",
")",
"raise",
"OutputDirExistsException",
"(",
"msg",
")",
"make_sure_path_exists",
"(",
"dir_to_create",
")",
"return",
"dir_to_create"
] | 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('Failed to get cluster references %s'), excep)
| [
"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",
"(",
"'Failed to get cluster references %s'",
")",
",",
"excep",
")"
] | 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.data.colnames == indexp.data.data.colnames)
| [
"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",
".",
"data",
".",
"colnames",
"==",
"indexp",
".",
"data",
".",
"data",
".",
"colnames",
")"
] | 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 ValueError("'match' is not a boolean")
except:
match = (arg_val_dict[key] is compat_args[key])
if (not match):
raise ValueError("the '{arg}' parameter is not supported in the pandas implementation of {fname}()".format(fname=fname, arg=key))
| [
"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",
"ValueError",
"(",
"\"'match' is not a boolean\"",
")",
"except",
":",
"match",
"=",
"(",
"arg_val_dict",
"[",
"key",
"]",
"is",
"compat_args",
"[",
"key",
"]",
")",
"if",
"(",
"not",
"match",
")",
":",
"raise",
"ValueError",
"(",
"\"the '{arg}' parameter is not supported in the pandas implementation of {fname}()\"",
".",
"format",
"(",
"fname",
"=",
"fname",
",",
"arg",
"=",
"key",
")",
")"
] | 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",
".",
"append",
"(",
"f",
")",
"return",
"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",
")",
"diff_code_assert",
"(",
"code_basic_features",
",",
"prs",
".",
"module",
".",
"get_code",
"(",
")",
")"
] | 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.InvalidInput('op', item.op, ('unimplemented operator for %s' % item.field))
return True
return False
| [
"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",
".",
"InvalidInput",
"(",
"'op'",
",",
"item",
".",
"op",
",",
"(",
"'unimplemented operator for %s'",
"%",
"item",
".",
"field",
")",
")",
"return",
"True",
"return",
"False"
] | 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'",
",",
"'{'",
")",
".",
"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",
":",
"key",
"=",
"key_type",
".",
"Read",
"(",
"key_file",
".",
"read",
"(",
")",
")",
"return",
"key"
] | 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",
"(",
"[",
"attr",
".",
"ref",
"for",
"attr",
"in",
"attributes",
"]",
",",
"dependencies",
")",
"return",
"depsorted"
] | 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_freq=h_freq)
n_events = len(ecg_events)
ecg_events = np.c_[((ecg_events + raw.first_samp), np.zeros(n_events), (event_id * np.ones(n_events)))]
return ecg_events
| [
"@",
"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_freq",
"=",
"h_freq",
")",
"n_events",
"=",
"len",
"(",
"ecg_events",
")",
"ecg_events",
"=",
"np",
".",
"c_",
"[",
"(",
"(",
"ecg_events",
"+",
"raw",
".",
"first_samp",
")",
",",
"np",
".",
"zeros",
"(",
"n_events",
")",
",",
"(",
"event_id",
"*",
"np",
".",
"ones",
"(",
"n_events",
")",
")",
")",
"]",
"return",
"ecg_events"
] | 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",
".",
"getRadiusArealizedMultiplier",
"(",
"sides",
")",
")"
] | 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_tuple))
if isinstance(int_or_tuple, tf.TensorShape):
if (len(int_or_tuple) == 2):
return (int_or_tuple[0], int_or_tuple[1])
raise ValueError('Must be an int, a list with 2 elements or a TensorShape of length 2')
| [
"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_tuple",
")",
")",
"if",
"isinstance",
"(",
"int_or_tuple",
",",
"tf",
".",
"TensorShape",
")",
":",
"if",
"(",
"len",
"(",
"int_or_tuple",
")",
"==",
"2",
")",
":",
"return",
"(",
"int_or_tuple",
"[",
"0",
"]",
",",
"int_or_tuple",
"[",
"1",
"]",
")",
"raise",
"ValueError",
"(",
"'Must be an int, a list with 2 elements or a TensorShape of length 2'",
")"
] | 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', u'200': u'400', u'300': u'400', u'400': u'700', u'500': u'700'}.get(pwt, u'900')
elif (wt == u'lighter'):
style[u'font-weight'] = {u'600': u'400', u'700': u'400', u'800': u'700', u'900': u'700'}.get(pwt, u'100')
return style
| [
"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'",
",",
"u'200'",
":",
"u'400'",
",",
"u'300'",
":",
"u'400'",
",",
"u'400'",
":",
"u'700'",
",",
"u'500'",
":",
"u'700'",
"}",
".",
"get",
"(",
"pwt",
",",
"u'900'",
")",
"elif",
"(",
"wt",
"==",
"u'lighter'",
")",
":",
"style",
"[",
"u'font-weight'",
"]",
"=",
"{",
"u'600'",
":",
"u'400'",
",",
"u'700'",
":",
"u'400'",
",",
"u'800'",
":",
"u'700'",
",",
"u'900'",
":",
"u'700'",
"}",
".",
"get",
"(",
"pwt",
",",
"u'100'",
")",
"return",
"style"
] | 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 = [(var, ((var * rng.binomial(var.shape, p=(1 - drop_prob), dtype=theano.config.floatX)) / divisor)) for var in variables]
for (variable, replacement) in replacements:
add_role(replacement, DROPOUT)
replacement.tag.replacement_of = variable
return computation_graph.replace(replacements)
| [
"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",
"=",
"[",
"(",
"var",
",",
"(",
"(",
"var",
"*",
"rng",
".",
"binomial",
"(",
"var",
".",
"shape",
",",
"p",
"=",
"(",
"1",
"-",
"drop_prob",
")",
",",
"dtype",
"=",
"theano",
".",
"config",
".",
"floatX",
")",
")",
"/",
"divisor",
")",
")",
"for",
"var",
"in",
"variables",
"]",
"for",
"(",
"variable",
",",
"replacement",
")",
"in",
"replacements",
":",
"add_role",
"(",
"replacement",
",",
"DROPOUT",
")",
"replacement",
".",
"tag",
".",
"replacement_of",
"=",
"variable",
"return",
"computation_graph",
".",
"replace",
"(",
"replacements",
")"
] | 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.cartesian_product(Gnew, Gold)
H = nx.relabel_nodes(G, flatten)
H.name = ('grid_graph(%s)' % dlabel)
return H
| [
"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",
".",
"cartesian_product",
"(",
"Gnew",
",",
"Gold",
")",
"H",
"=",
"nx",
".",
"relabel_nodes",
"(",
"G",
",",
"flatten",
")",
"H",
".",
"name",
"=",
"(",
"'grid_graph(%s)'",
"%",
"dlabel",
")",
"return",
"H"
] | 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 path.parent().exists()):
path.parent().makedirs()
source_key = os.path.join(intent.source_prefix, key)
(yield Effect(DownloadS3Key(source_bucket=intent.source_bucket, source_key=source_key, target_path=path)))
| [
"@",
"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",
"path",
".",
"parent",
"(",
")",
".",
"exists",
"(",
")",
")",
":",
"path",
".",
"parent",
"(",
")",
".",
"makedirs",
"(",
")",
"source_key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"intent",
".",
"source_prefix",
",",
"key",
")",
"(",
"yield",
"Effect",
"(",
"DownloadS3Key",
"(",
"source_bucket",
"=",
"intent",
".",
"source_bucket",
",",
"source_key",
"=",
"source_key",
",",
"target_path",
"=",
"path",
")",
")",
")"
] | 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-gi', 'ncbi-geneid', 'uniprot']) or ((target_db in ['drug', 'compound', 'glycan']) and (source_db in ['pubchem', 'glycan'])) or ((target_db in ['pubchem', 'glycan']) and (source_db in ['drug', 'compound', 'glycan']))):
if option:
resp = _q('conv', target_db, source_db, option)
else:
resp = _q('conv', target_db, source_db)
return resp
else:
raise Exception('Bad argument target_db or source_db for kegg conv request.')
| [
"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-gi'",
",",
"'ncbi-geneid'",
",",
"'uniprot'",
"]",
")",
"or",
"(",
"(",
"target_db",
"in",
"[",
"'drug'",
",",
"'compound'",
",",
"'glycan'",
"]",
")",
"and",
"(",
"source_db",
"in",
"[",
"'pubchem'",
",",
"'glycan'",
"]",
")",
")",
"or",
"(",
"(",
"target_db",
"in",
"[",
"'pubchem'",
",",
"'glycan'",
"]",
")",
"and",
"(",
"source_db",
"in",
"[",
"'drug'",
",",
"'compound'",
",",
"'glycan'",
"]",
")",
")",
")",
":",
"if",
"option",
":",
"resp",
"=",
"_q",
"(",
"'conv'",
",",
"target_db",
",",
"source_db",
",",
"option",
")",
"else",
":",
"resp",
"=",
"_q",
"(",
"'conv'",
",",
"target_db",
",",
"source_db",
")",
"return",
"resp",
"else",
":",
"raise",
"Exception",
"(",
"'Bad argument target_db or source_db for kegg conv request.'",
")"
] | 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",
".",
"published",
".",
"datetimes",
"(",
"'publication_date'",
",",
"'month'",
",",
"order",
"=",
"'DESC'",
")",
"}"
] | 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_upload = resource.FileUpload.create(purpose='video', content_type='application/vnd.openai.video+x-compressed', api_key=api_key)
file_upload.put(archive_file, encode=None)
return file_upload
| [
"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_upload",
"=",
"resource",
".",
"FileUpload",
".",
"create",
"(",
"purpose",
"=",
"'video'",
",",
"content_type",
"=",
"'application/vnd.openai.video+x-compressed'",
",",
"api_key",
"=",
"api_key",
")",
"file_upload",
".",
"put",
"(",
"archive_file",
",",
"encode",
"=",
"None",
")",
"return",
"file_upload"
] | 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)) for x in lst]
cmd_list = list_string_sub('%F', filename, cmd_list)
cmd_list = list_string_sub('%d', ddir, cmd_list)
cmd_list = list_string_sub('%f', basename, cmd_list)
cmd_list = list_string_sub('%u', url, cmd_list)
cmd_list = list_string_sub('%i', song.ytid, cmd_list)
util.dbg('Downloading using: %s', ' '.join(cmd_list))
subprocess.call(cmd_list)
| [
"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",
")",
":",
"return",
"[",
"(",
"x",
"if",
"(",
"orig",
"not",
"in",
"x",
")",
"else",
"x",
".",
"replace",
"(",
"orig",
",",
"repl",
")",
")",
"for",
"x",
"in",
"lst",
"]",
"cmd_list",
"=",
"list_string_sub",
"(",
"'%F'",
",",
"filename",
",",
"cmd_list",
")",
"cmd_list",
"=",
"list_string_sub",
"(",
"'%d'",
",",
"ddir",
",",
"cmd_list",
")",
"cmd_list",
"=",
"list_string_sub",
"(",
"'%f'",
",",
"basename",
",",
"cmd_list",
")",
"cmd_list",
"=",
"list_string_sub",
"(",
"'%u'",
",",
"url",
",",
"cmd_list",
")",
"cmd_list",
"=",
"list_string_sub",
"(",
"'%i'",
",",
"song",
".",
"ytid",
",",
"cmd_list",
")",
"util",
".",
"dbg",
"(",
"'Downloading using: %s'",
",",
"' '",
".",
"join",
"(",
"cmd_list",
")",
")",
"subprocess",
".",
"call",
"(",
"cmd_list",
")"
] | 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.strip()
if (line and (not line.startswith(u'#'))):
(k, v) = split_env(line)
env[k] = v
return env
| [
"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",
".",
"strip",
"(",
")",
"if",
"(",
"line",
"and",
"(",
"not",
"line",
".",
"startswith",
"(",
"u'#'",
")",
")",
")",
":",
"(",
"k",
",",
"v",
")",
"=",
"split_env",
"(",
"line",
")",
"env",
"[",
"k",
"]",
"=",
"v",
"return",
"env"
] | 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.UnauthorizedAccess:
print ('No token available for access to %s' % object_id)
| [
"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",
".",
"UnauthorizedAccess",
":",
"print",
"(",
"'No token available for access to %s'",
"%",
"object_id",
")"
] | 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.makedirs(prov_dir)
missing_node_cache(prov_dir, nodes, provider, opts)
for node in nodes:
diff_node_cache(prov_dir, node, nodes[node], opts)
path = os.path.join(prov_dir, '{0}.p'.format(node))
with salt.utils.fopen(path, 'w') as fh_:
msgpack.dump(nodes[node], fh_)
| [
"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",
".",
"makedirs",
"(",
"prov_dir",
")",
"missing_node_cache",
"(",
"prov_dir",
",",
"nodes",
",",
"provider",
",",
"opts",
")",
"for",
"node",
"in",
"nodes",
":",
"diff_node_cache",
"(",
"prov_dir",
",",
"node",
",",
"nodes",
"[",
"node",
"]",
",",
"opts",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prov_dir",
",",
"'{0}.p'",
".",
"format",
"(",
"node",
")",
")",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"path",
",",
"'w'",
")",
"as",
"fh_",
":",
"msgpack",
".",
"dump",
"(",
"nodes",
"[",
"node",
"]",
",",
"fh_",
")"
] | 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/vz/template/cache'",
")",
":",
"run_as_root",
"(",
"(",
"'wget --progress=dot:mega \"%s\"'",
"%",
"url",
")",
")"
] | 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 != v):
while (dfn[u] < dfn[v]):
u = idom[u]
while (dfn[u] > dfn[v]):
v = idom[v]
return u
changed = True
while changed:
changed = False
for u in order:
new_idom = reduce(intersect, (v for v in G.pred[u] if (v in idom)))
if ((u not in idom) or (idom[u] != new_idom)):
idom[u] = new_idom
changed = True
return idom
| [
"@",
"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",
"!=",
"v",
")",
":",
"while",
"(",
"dfn",
"[",
"u",
"]",
"<",
"dfn",
"[",
"v",
"]",
")",
":",
"u",
"=",
"idom",
"[",
"u",
"]",
"while",
"(",
"dfn",
"[",
"u",
"]",
">",
"dfn",
"[",
"v",
"]",
")",
":",
"v",
"=",
"idom",
"[",
"v",
"]",
"return",
"u",
"changed",
"=",
"True",
"while",
"changed",
":",
"changed",
"=",
"False",
"for",
"u",
"in",
"order",
":",
"new_idom",
"=",
"reduce",
"(",
"intersect",
",",
"(",
"v",
"for",
"v",
"in",
"G",
".",
"pred",
"[",
"u",
"]",
"if",
"(",
"v",
"in",
"idom",
")",
")",
")",
"if",
"(",
"(",
"u",
"not",
"in",
"idom",
")",
"or",
"(",
"idom",
"[",
"u",
"]",
"!=",
"new_idom",
")",
")",
":",
"idom",
"[",
"u",
"]",
"=",
"new_idom",
"changed",
"=",
"True",
"return",
"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",
"=",
"True",
")",
"]",
"if",
"(",
"not",
"doc_ids",
")",
":",
"break",
"index",
".",
"delete",
"(",
"doc_ids",
")"
] | 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) = kmeans(features, k)
(code, distance) = vq(features, centroids)
return (code, V)
| [
"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",
")",
"=",
"kmeans",
"(",
"features",
",",
"k",
")",
"(",
"code",
",",
"distance",
")",
"=",
"vq",
"(",
"features",
",",
"centroids",
")",
"return",
"(",
"code",
",",
"V",
")"
] | 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 = '<html><body><h1>%s</h1></body></html>'
p.error_message_ticket = (('<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body><!-- this is junk text else IE does not display the page: ' + ('x' * 512)) + ' //--></html>')
p.routers = None
p.logging = 'off'
return p
| [
"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",
"=",
"'<html><body><h1>%s</h1></body></html>'",
"p",
".",
"error_message_ticket",
"=",
"(",
"(",
"'<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body><!-- this is junk text else IE does not display the page: '",
"+",
"(",
"'x'",
"*",
"512",
")",
")",
"+",
"' //--></html>'",
")",
"p",
".",
"routers",
"=",
"None",
"p",
".",
"logging",
"=",
"'off'",
"return",
"p"
] | 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",
")",
"in",
"G1",
".",
"degree",
"(",
")",
")",
")",
"d2",
"=",
"sorted",
"(",
"(",
"d",
"for",
"(",
"n",
",",
"d",
")",
"in",
"G2",
".",
"degree",
"(",
")",
")",
")",
"if",
"(",
"d1",
"!=",
"d2",
")",
":",
"return",
"False",
"return",
"True"
] | 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",
"None",
")",
":",
"return",
"None",
"else",
":",
"return",
"user_model",
".",
"email"
] | 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",
")",
"return",
"normalize_delete_at_timestamp",
"(",
"(",
"(",
"(",
"int",
"(",
"x_delete_at",
")",
"/",
"expirer_divisor",
")",
"*",
"expirer_divisor",
")",
"-",
"shard_int",
")",
")"
] | returns a expiring object container name for given x-delete-at and a/c/o . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.