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 |
|---|---|---|---|---|---|
39,443 | def _snapper_post(opts, jid, pre_num):
try:
if ((not opts['test']) and __opts__.get('snapper_states') and pre_num):
__salt__['snapper.create_snapshot'](config=__opts__.get('snapper_states_config', 'root'), snapshot_type='post', pre_number=pre_num, description='Salt State run for jid {0}'.format(jid), __pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: {0}'.format(jid))
| [
"def",
"_snapper_post",
"(",
"opts",
",",
"jid",
",",
"pre_num",
")",
":",
"try",
":",
"if",
"(",
"(",
"not",
"opts",
"[",
"'test'",
"]",
")",
"and",
"__opts__",
".",
"get",
"(",
"'snapper_states'",
")",
"and",
"pre_num",
")",
":",
"__salt__",
"[",
"'snapper.create_snapshot'",
"]",
"(",
"config",
"=",
"__opts__",
".",
"get",
"(",
"'snapper_states_config'",
",",
"'root'",
")",
",",
"snapshot_type",
"=",
"'post'",
",",
"pre_number",
"=",
"pre_num",
",",
"description",
"=",
"'Salt State run for jid {0}'",
".",
"format",
"(",
"jid",
")",
",",
"__pub_jid",
"=",
"jid",
")",
"except",
"Exception",
":",
"log",
".",
"error",
"(",
"'Failed to create snapper pre snapshot for jid: {0}'",
".",
"format",
"(",
"jid",
")",
")"
] | create the post states snapshot . | train | true |
39,444 | def setup_mock_calls(mocked_call, expected_calls_and_values):
return_values = [call[1] for call in expected_calls_and_values]
mocked_call.side_effect = return_values
| [
"def",
"setup_mock_calls",
"(",
"mocked_call",
",",
"expected_calls_and_values",
")",
":",
"return_values",
"=",
"[",
"call",
"[",
"1",
"]",
"for",
"call",
"in",
"expected_calls_and_values",
"]",
"mocked_call",
".",
"side_effect",
"=",
"return_values"
] | a convenient method to setup a sequence of mock calls . | train | false |
39,447 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | return a rabbitmq node to its virgin state cli example: . | train | false |
39,448 | def _make_rewritten_pyc(state, source_stat, pyc, co):
if sys.platform.startswith('win'):
_write_pyc(state, co, source_stat, pyc)
else:
proc_pyc = ((pyc + '.') + str(os.getpid()))
if _write_pyc(state, co, source_stat, proc_pyc):
os.rename(proc_pyc, pyc)
| [
"def",
"_make_rewritten_pyc",
"(",
"state",
",",
"source_stat",
",",
"pyc",
",",
"co",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"_write_pyc",
"(",
"state",
",",
"co",
",",
"source_stat",
",",
"pyc",
")",
"else",
":",
"proc_pyc",
"=",
"(",
"(",
"pyc",
"+",
"'.'",
")",
"+",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
")",
"if",
"_write_pyc",
"(",
"state",
",",
"co",
",",
"source_stat",
",",
"proc_pyc",
")",
":",
"os",
".",
"rename",
"(",
"proc_pyc",
",",
"pyc",
")"
] | try to dump rewritten code to *pyc* . | train | true |
39,451 | def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):
import scipy
from scipy import interpolate
if (LooseVersion(scipy.__version__) < '0.18.0'):
try:
method = interpolate.piecewise_polynomial_interpolate
return method(xi, yi.reshape((-1), 1), x, orders=order, der=der)
except AttributeError:
pass
method = interpolate.BPoly.from_derivatives
m = method(xi, yi.reshape((-1), 1), orders=order, extrapolate=extrapolate)
return m(x)
| [
"def",
"_from_derivatives",
"(",
"xi",
",",
"yi",
",",
"x",
",",
"order",
"=",
"None",
",",
"der",
"=",
"0",
",",
"extrapolate",
"=",
"False",
")",
":",
"import",
"scipy",
"from",
"scipy",
"import",
"interpolate",
"if",
"(",
"LooseVersion",
"(",
"scipy",
".",
"__version__",
")",
"<",
"'0.18.0'",
")",
":",
"try",
":",
"method",
"=",
"interpolate",
".",
"piecewise_polynomial_interpolate",
"return",
"method",
"(",
"xi",
",",
"yi",
".",
"reshape",
"(",
"(",
"-",
"1",
")",
",",
"1",
")",
",",
"x",
",",
"orders",
"=",
"order",
",",
"der",
"=",
"der",
")",
"except",
"AttributeError",
":",
"pass",
"method",
"=",
"interpolate",
".",
"BPoly",
".",
"from_derivatives",
"m",
"=",
"method",
"(",
"xi",
",",
"yi",
".",
"reshape",
"(",
"(",
"-",
"1",
")",
",",
"1",
")",
",",
"orders",
"=",
"order",
",",
"extrapolate",
"=",
"extrapolate",
")",
"return",
"m",
"(",
"x",
")"
] | convenience function for interpolate . | train | false |
39,452 | def query_item(name, query_string, order='Rank'):
(status, result) = _query(action=name, args={'query': query_string, 'order': order})
return result
| [
"def",
"query_item",
"(",
"name",
",",
"query_string",
",",
"order",
"=",
"'Rank'",
")",
":",
"(",
"status",
",",
"result",
")",
"=",
"_query",
"(",
"action",
"=",
"name",
",",
"args",
"=",
"{",
"'query'",
":",
"query_string",
",",
"'order'",
":",
"order",
"}",
")",
"return",
"result"
] | query a type of record for one or more items . | train | true |
39,453 | def FlattenFilter(node):
node_list = []
if (node.attributes and (node.getAttribute('Name') == '_excluded_files')):
return []
for current in node.childNodes:
if (current.nodeName == 'Filter'):
node_list.extend(FlattenFilter(current))
else:
node_list.append(current)
return node_list
| [
"def",
"FlattenFilter",
"(",
"node",
")",
":",
"node_list",
"=",
"[",
"]",
"if",
"(",
"node",
".",
"attributes",
"and",
"(",
"node",
".",
"getAttribute",
"(",
"'Name'",
")",
"==",
"'_excluded_files'",
")",
")",
":",
"return",
"[",
"]",
"for",
"current",
"in",
"node",
".",
"childNodes",
":",
"if",
"(",
"current",
".",
"nodeName",
"==",
"'Filter'",
")",
":",
"node_list",
".",
"extend",
"(",
"FlattenFilter",
"(",
"current",
")",
")",
"else",
":",
"node_list",
".",
"append",
"(",
"current",
")",
"return",
"node_list"
] | returns a list of all the node and sub nodes . | train | false |
39,454 | def test_longer():
jobs = bg.BackgroundJobManager()
j = jobs.new(sleeper, 0.1)
nt.assert_equal(len(jobs.running), 1)
nt.assert_equal(len(jobs.completed), 0)
j.join()
nt.assert_equal(len(jobs.running), 0)
nt.assert_equal(len(jobs.completed), 1)
| [
"def",
"test_longer",
"(",
")",
":",
"jobs",
"=",
"bg",
".",
"BackgroundJobManager",
"(",
")",
"j",
"=",
"jobs",
".",
"new",
"(",
"sleeper",
",",
"0.1",
")",
"nt",
".",
"assert_equal",
"(",
"len",
"(",
"jobs",
".",
"running",
")",
",",
"1",
")",
"nt",
".",
"assert_equal",
"(",
"len",
"(",
"jobs",
".",
"completed",
")",
",",
"0",
")",
"j",
".",
"join",
"(",
")",
"nt",
".",
"assert_equal",
"(",
"len",
"(",
"jobs",
".",
"running",
")",
",",
"0",
")",
"nt",
".",
"assert_equal",
"(",
"len",
"(",
"jobs",
".",
"completed",
")",
",",
"1",
")"
] | test control of longer-running jobs . | train | false |
39,456 | @intercept_errors(FakeOutputException, ignore_errors=[ValueError])
def intercepted_function(raise_error=None):
if (raise_error is not None):
raise raise_error
| [
"@",
"intercept_errors",
"(",
"FakeOutputException",
",",
"ignore_errors",
"=",
"[",
"ValueError",
"]",
")",
"def",
"intercepted_function",
"(",
"raise_error",
"=",
"None",
")",
":",
"if",
"(",
"raise_error",
"is",
"not",
"None",
")",
":",
"raise",
"raise_error"
] | function used to test the intercept error decorator . | train | false |
39,457 | @pytest.fixture
def afrikaans_tutorial(afrikaans, tutorial):
return _require_tp(afrikaans, tutorial)
| [
"@",
"pytest",
".",
"fixture",
"def",
"afrikaans_tutorial",
"(",
"afrikaans",
",",
"tutorial",
")",
":",
"return",
"_require_tp",
"(",
"afrikaans",
",",
"tutorial",
")"
] | require afrikaans tutorial . | train | false |
39,458 | def gae_mini_profiler_should_profile_production():
return False
| [
"def",
"gae_mini_profiler_should_profile_production",
"(",
")",
":",
"return",
"False"
] | uncomment the first two lines to enable gae mini profiler on production for admin accounts . | train | false |
39,459 | def max_pool_2d_same_size(input, patch_size):
output = Pool(True)(input, patch_size)
outs = MaxPoolGrad(True)(input, output, output, patch_size)
return outs
| [
"def",
"max_pool_2d_same_size",
"(",
"input",
",",
"patch_size",
")",
":",
"output",
"=",
"Pool",
"(",
"True",
")",
"(",
"input",
",",
"patch_size",
")",
"outs",
"=",
"MaxPoolGrad",
"(",
"True",
")",
"(",
"input",
",",
"output",
",",
"output",
",",
"patch_size",
")",
"return",
"outs"
] | takes as input a 4-d tensor . | train | false |
39,460 | def Subscript(index_node):
return Node(syms.trailer, [Leaf(token.LBRACE, u'['), index_node, Leaf(token.RBRACE, u']')])
| [
"def",
"Subscript",
"(",
"index_node",
")",
":",
"return",
"Node",
"(",
"syms",
".",
"trailer",
",",
"[",
"Leaf",
"(",
"token",
".",
"LBRACE",
",",
"u'['",
")",
",",
"index_node",
",",
"Leaf",
"(",
"token",
".",
"RBRACE",
",",
"u']'",
")",
"]",
")"
] | a numeric or string subscript . | train | false |
39,461 | def reset_terminal():
if (not mswin):
subprocess.call(['tset', '-c'])
| [
"def",
"reset_terminal",
"(",
")",
":",
"if",
"(",
"not",
"mswin",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'tset'",
",",
"'-c'",
"]",
")"
] | reset terminal control character and modes for non win oss . | train | false |
39,463 | def getGeometryOutputByNestedRing(derivation, nestedRing, portionDirections):
loopLists = getLoopListsByPath(derivation, None, nestedRing.vector3Loop, portionDirections)
outsideOutput = triangle_mesh.getPillarsOutput(loopLists)
if (len(nestedRing.innerNestedRings) < 1):
return outsideOutput
shapes = [outsideOutput]
for nestedRing.innerNestedRing in nestedRing.innerNestedRings:
loopLists = getLoopListsByPath(derivation, 1.000001, nestedRing.innerNestedRing.vector3Loop, portionDirections)
shapes.append(triangle_mesh.getPillarsOutput(loopLists))
return {'difference': {'shapes': shapes}}
| [
"def",
"getGeometryOutputByNestedRing",
"(",
"derivation",
",",
"nestedRing",
",",
"portionDirections",
")",
":",
"loopLists",
"=",
"getLoopListsByPath",
"(",
"derivation",
",",
"None",
",",
"nestedRing",
".",
"vector3Loop",
",",
"portionDirections",
")",
"outsideOutput",
"=",
"triangle_mesh",
".",
"getPillarsOutput",
"(",
"loopLists",
")",
"if",
"(",
"len",
"(",
"nestedRing",
".",
"innerNestedRings",
")",
"<",
"1",
")",
":",
"return",
"outsideOutput",
"shapes",
"=",
"[",
"outsideOutput",
"]",
"for",
"nestedRing",
".",
"innerNestedRing",
"in",
"nestedRing",
".",
"innerNestedRings",
":",
"loopLists",
"=",
"getLoopListsByPath",
"(",
"derivation",
",",
"1.000001",
",",
"nestedRing",
".",
"innerNestedRing",
".",
"vector3Loop",
",",
"portionDirections",
")",
"shapes",
".",
"append",
"(",
"triangle_mesh",
".",
"getPillarsOutput",
"(",
"loopLists",
")",
")",
"return",
"{",
"'difference'",
":",
"{",
"'shapes'",
":",
"shapes",
"}",
"}"
] | get geometry output by sorted . | train | false |
39,465 | def do_pre_ops(cnxt, stack, current_stack=None, action=None):
cinstances = get_plug_point_class_instances()
if (action is None):
action = stack.action
(failure, failure_exception_message, success_count) = _do_ops(cinstances, 'do_pre_op', cnxt, stack, current_stack, action, None)
if failure:
cinstances = cinstances[0:success_count]
_do_ops(cinstances, 'do_post_op', cnxt, stack, current_stack, action, True)
raise Exception(failure_exception_message)
| [
"def",
"do_pre_ops",
"(",
"cnxt",
",",
"stack",
",",
"current_stack",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"cinstances",
"=",
"get_plug_point_class_instances",
"(",
")",
"if",
"(",
"action",
"is",
"None",
")",
":",
"action",
"=",
"stack",
".",
"action",
"(",
"failure",
",",
"failure_exception_message",
",",
"success_count",
")",
"=",
"_do_ops",
"(",
"cinstances",
",",
"'do_pre_op'",
",",
"cnxt",
",",
"stack",
",",
"current_stack",
",",
"action",
",",
"None",
")",
"if",
"failure",
":",
"cinstances",
"=",
"cinstances",
"[",
"0",
":",
"success_count",
"]",
"_do_ops",
"(",
"cinstances",
",",
"'do_post_op'",
",",
"cnxt",
",",
"stack",
",",
"current_stack",
",",
"action",
",",
"True",
")",
"raise",
"Exception",
"(",
"failure_exception_message",
")"
] | call available pre-op methods sequentially . | train | false |
39,466 | def dmp_qq_collins_resultant(f, g, u, K0):
n = dmp_degree(f, u)
m = dmp_degree(g, u)
if ((n < 0) or (m < 0)):
return dmp_zero((u - 1))
K1 = K0.get_ring()
(cf, f) = dmp_clear_denoms(f, u, K0, K1)
(cg, g) = dmp_clear_denoms(g, u, K0, K1)
f = dmp_convert(f, u, K0, K1)
g = dmp_convert(g, u, K0, K1)
r = dmp_zz_collins_resultant(f, g, u, K1)
r = dmp_convert(r, (u - 1), K1, K0)
c = K0.convert(((cf ** m) * (cg ** n)), K1)
return dmp_quo_ground(r, c, (u - 1), K0)
| [
"def",
"dmp_qq_collins_resultant",
"(",
"f",
",",
"g",
",",
"u",
",",
"K0",
")",
":",
"n",
"=",
"dmp_degree",
"(",
"f",
",",
"u",
")",
"m",
"=",
"dmp_degree",
"(",
"g",
",",
"u",
")",
"if",
"(",
"(",
"n",
"<",
"0",
")",
"or",
"(",
"m",
"<",
"0",
")",
")",
":",
"return",
"dmp_zero",
"(",
"(",
"u",
"-",
"1",
")",
")",
"K1",
"=",
"K0",
".",
"get_ring",
"(",
")",
"(",
"cf",
",",
"f",
")",
"=",
"dmp_clear_denoms",
"(",
"f",
",",
"u",
",",
"K0",
",",
"K1",
")",
"(",
"cg",
",",
"g",
")",
"=",
"dmp_clear_denoms",
"(",
"g",
",",
"u",
",",
"K0",
",",
"K1",
")",
"f",
"=",
"dmp_convert",
"(",
"f",
",",
"u",
",",
"K0",
",",
"K1",
")",
"g",
"=",
"dmp_convert",
"(",
"g",
",",
"u",
",",
"K0",
",",
"K1",
")",
"r",
"=",
"dmp_zz_collins_resultant",
"(",
"f",
",",
"g",
",",
"u",
",",
"K1",
")",
"r",
"=",
"dmp_convert",
"(",
"r",
",",
"(",
"u",
"-",
"1",
")",
",",
"K1",
",",
"K0",
")",
"c",
"=",
"K0",
".",
"convert",
"(",
"(",
"(",
"cf",
"**",
"m",
")",
"*",
"(",
"cg",
"**",
"n",
")",
")",
",",
"K1",
")",
"return",
"dmp_quo_ground",
"(",
"r",
",",
"c",
",",
"(",
"u",
"-",
"1",
")",
",",
"K0",
")"
] | collinss modular resultant algorithm in q[x] . | train | false |
39,467 | def _is_valid_target(target, target_name, target_ports, is_pair):
if is_pair:
return ((target[:utils.PORT_ID_LENGTH] in target_ports) and (target_name == _PAIR_TARGET_NAME))
if ((target[:utils.PORT_ID_LENGTH] not in target_ports) or (not target_name.startswith(utils.TARGET_PREFIX)) or (target_name == _PAIR_TARGET_NAME)):
return False
return True
| [
"def",
"_is_valid_target",
"(",
"target",
",",
"target_name",
",",
"target_ports",
",",
"is_pair",
")",
":",
"if",
"is_pair",
":",
"return",
"(",
"(",
"target",
"[",
":",
"utils",
".",
"PORT_ID_LENGTH",
"]",
"in",
"target_ports",
")",
"and",
"(",
"target_name",
"==",
"_PAIR_TARGET_NAME",
")",
")",
"if",
"(",
"(",
"target",
"[",
":",
"utils",
".",
"PORT_ID_LENGTH",
"]",
"not",
"in",
"target_ports",
")",
"or",
"(",
"not",
"target_name",
".",
"startswith",
"(",
"utils",
".",
"TARGET_PREFIX",
")",
")",
"or",
"(",
"target_name",
"==",
"_PAIR_TARGET_NAME",
")",
")",
":",
"return",
"False",
"return",
"True"
] | return true if the specified target is valid . | train | false |
39,468 | def tupleize(func):
def wrapper(*args, **kargs):
return (func(*args, **kargs),)
return wrapper
| [
"def",
"tupleize",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
":",
"return",
"(",
"func",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
",",
")",
"return",
"wrapper"
] | a decorator that tuple-ize the result of a function . | train | false |
39,469 | def approximate_wkb(wkb_in):
(input, output) = (StringIO(wkb_in), StringIO())
approx_geometry(input, output)
wkb_out = output.getvalue()
assert (len(wkb_in) == input.tell()), 'The whole WKB was not processed'
assert (len(wkb_in) == len(wkb_out)), 'The output WKB is the wrong length'
return wkb_out
| [
"def",
"approximate_wkb",
"(",
"wkb_in",
")",
":",
"(",
"input",
",",
"output",
")",
"=",
"(",
"StringIO",
"(",
"wkb_in",
")",
",",
"StringIO",
"(",
")",
")",
"approx_geometry",
"(",
"input",
",",
"output",
")",
"wkb_out",
"=",
"output",
".",
"getvalue",
"(",
")",
"assert",
"(",
"len",
"(",
"wkb_in",
")",
"==",
"input",
".",
"tell",
"(",
")",
")",
",",
"'The whole WKB was not processed'",
"assert",
"(",
"len",
"(",
"wkb_in",
")",
"==",
"len",
"(",
"wkb_out",
")",
")",
",",
"'The output WKB is the wrong length'",
"return",
"wkb_out"
] | return an approximation of the input wkb with lower-precision geometry . | train | false |
39,470 | def relative_flat_glob(dirname, basename):
if os.path.exists(os.path.join(dirname, basename)):
return [basename]
return []
| [
"def",
"relative_flat_glob",
"(",
"dirname",
",",
"basename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"basename",
")",
")",
":",
"return",
"[",
"basename",
"]",
"return",
"[",
"]"
] | non-recursive glob for one directory . | train | false |
39,472 | def is_sevenfile(path):
return (SEVEN_COMMAND and (os.path.splitext(path)[1].lower() == '.7z'))
| [
"def",
"is_sevenfile",
"(",
"path",
")",
":",
"return",
"(",
"SEVEN_COMMAND",
"and",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'.7z'",
")",
")"
] | return true if path has proper extension and 7zip is installed . | train | false |
39,473 | def read_file_unix_endings(file_name, encoding='utf8', ignore=True):
if _ST3:
errors = ('ignore' if ignore else 'strict')
with open(file_name, 'rt', encoding=encoding, errors=errors) as f:
file_content = f.read()
else:
file_content = _read_file_content(file_name, encoding, ignore)
file_content = file_content.replace('\r\n', '\n')
return file_content
| [
"def",
"read_file_unix_endings",
"(",
"file_name",
",",
"encoding",
"=",
"'utf8'",
",",
"ignore",
"=",
"True",
")",
":",
"if",
"_ST3",
":",
"errors",
"=",
"(",
"'ignore'",
"if",
"ignore",
"else",
"'strict'",
")",
"with",
"open",
"(",
"file_name",
",",
"'rt'",
",",
"encoding",
"=",
"encoding",
",",
"errors",
"=",
"errors",
")",
"as",
"f",
":",
"file_content",
"=",
"f",
".",
"read",
"(",
")",
"else",
":",
"file_content",
"=",
"_read_file_content",
"(",
"file_name",
",",
"encoding",
",",
"ignore",
")",
"file_content",
"=",
"file_content",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"return",
"file_content"
] | reads a file with unix line endings and converts windows line endings into line endings . | train | false |
39,474 | def get_install_server_profiles():
install_server = None
install_server_info = get_install_server_info()
install_server_type = install_server_info.get('type', None)
install_server_url = install_server_info.get('xmlrpc_url', None)
if ((install_server_type == 'cobbler') and install_server_url):
install_server = xmlrpclib.ServerProxy(install_server_url)
if (install_server is None):
return None
return install_server.get_item_names('profile')
| [
"def",
"get_install_server_profiles",
"(",
")",
":",
"install_server",
"=",
"None",
"install_server_info",
"=",
"get_install_server_info",
"(",
")",
"install_server_type",
"=",
"install_server_info",
".",
"get",
"(",
"'type'",
",",
"None",
")",
"install_server_url",
"=",
"install_server_info",
".",
"get",
"(",
"'xmlrpc_url'",
",",
"None",
")",
"if",
"(",
"(",
"install_server_type",
"==",
"'cobbler'",
")",
"and",
"install_server_url",
")",
":",
"install_server",
"=",
"xmlrpclib",
".",
"ServerProxy",
"(",
"install_server_url",
")",
"if",
"(",
"install_server",
"is",
"None",
")",
":",
"return",
"None",
"return",
"install_server",
".",
"get_item_names",
"(",
"'profile'",
")"
] | get install server profiles . | train | false |
39,475 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | reset prefix of line . | train | false |
39,476 | def si32le(c, o=0):
return unpack('<i', c[o:(o + 4)])[0]
| [
"def",
"si32le",
"(",
"c",
",",
"o",
"=",
"0",
")",
":",
"return",
"unpack",
"(",
"'<i'",
",",
"c",
"[",
"o",
":",
"(",
"o",
"+",
"4",
")",
"]",
")",
"[",
"0",
"]"
] | converts a 4-bytes string to a signed integer . | train | false |
39,477 | def parseDiffTreeEntry(entry):
match = diffTreePattern().next().match(entry)
if match:
return {'src_mode': match.group(1), 'dst_mode': match.group(2), 'src_sha1': match.group(3), 'dst_sha1': match.group(4), 'status': match.group(5), 'status_score': match.group(6), 'src': match.group(7), 'dst': match.group(10)}
return None
| [
"def",
"parseDiffTreeEntry",
"(",
"entry",
")",
":",
"match",
"=",
"diffTreePattern",
"(",
")",
".",
"next",
"(",
")",
".",
"match",
"(",
"entry",
")",
"if",
"match",
":",
"return",
"{",
"'src_mode'",
":",
"match",
".",
"group",
"(",
"1",
")",
",",
"'dst_mode'",
":",
"match",
".",
"group",
"(",
"2",
")",
",",
"'src_sha1'",
":",
"match",
".",
"group",
"(",
"3",
")",
",",
"'dst_sha1'",
":",
"match",
".",
"group",
"(",
"4",
")",
",",
"'status'",
":",
"match",
".",
"group",
"(",
"5",
")",
",",
"'status_score'",
":",
"match",
".",
"group",
"(",
"6",
")",
",",
"'src'",
":",
"match",
".",
"group",
"(",
"7",
")",
",",
"'dst'",
":",
"match",
".",
"group",
"(",
"10",
")",
"}",
"return",
"None"
] | parses a single diff tree entry into its component elements . | train | false |
39,478 | def get_bind_addr(conf, default_port=None):
return (conf.bind_host, (conf.bind_port or default_port))
| [
"def",
"get_bind_addr",
"(",
"conf",
",",
"default_port",
"=",
"None",
")",
":",
"return",
"(",
"conf",
".",
"bind_host",
",",
"(",
"conf",
".",
"bind_port",
"or",
"default_port",
")",
")"
] | return the host and port to bind to . | train | false |
39,479 | def submit_flag(flag, exploit=env_exploit_name, target=env_target_host, server=env_server, port=env_port, proto=env_proto, team=env_team_name):
flag = flag.strip()
log.success(('Flag: %r' % flag))
data = '\n'.join([flag, exploit, target, team, ''])
if os.path.exists(env_file):
write(env_file, data)
return
try:
with remote(server, int(port)) as r:
r.send(data)
return r.recvall(timeout=1)
except Exception:
log.warn(('Could not submit flag %r to %s:%s' % (flag, server, port)))
| [
"def",
"submit_flag",
"(",
"flag",
",",
"exploit",
"=",
"env_exploit_name",
",",
"target",
"=",
"env_target_host",
",",
"server",
"=",
"env_server",
",",
"port",
"=",
"env_port",
",",
"proto",
"=",
"env_proto",
",",
"team",
"=",
"env_team_name",
")",
":",
"flag",
"=",
"flag",
".",
"strip",
"(",
")",
"log",
".",
"success",
"(",
"(",
"'Flag: %r'",
"%",
"flag",
")",
")",
"data",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"flag",
",",
"exploit",
",",
"target",
",",
"team",
",",
"''",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"env_file",
")",
":",
"write",
"(",
"env_file",
",",
"data",
")",
"return",
"try",
":",
"with",
"remote",
"(",
"server",
",",
"int",
"(",
"port",
")",
")",
"as",
"r",
":",
"r",
".",
"send",
"(",
"data",
")",
"return",
"r",
".",
"recvall",
"(",
"timeout",
"=",
"1",
")",
"except",
"Exception",
":",
"log",
".",
"warn",
"(",
"(",
"'Could not submit flag %r to %s:%s'",
"%",
"(",
"flag",
",",
"server",
",",
"port",
")",
")",
")"
] | submits a flag to the game server arguments: flag: the flag to submit . | train | false |
39,480 | def return_traceback_in_unhandled_exceptions():
global get_fault_string_from_exception
import traceback
def _get_fault_string_from_exception(e):
return traceback.format_exc()
get_fault_string_from_exception = _get_fault_string_from_exception
| [
"def",
"return_traceback_in_unhandled_exceptions",
"(",
")",
":",
"global",
"get_fault_string_from_exception",
"import",
"traceback",
"def",
"_get_fault_string_from_exception",
"(",
"e",
")",
":",
"return",
"traceback",
".",
"format_exc",
"(",
")",
"get_fault_string_from_exception",
"=",
"_get_fault_string_from_exception"
] | call this function first thing in your main function to return original python errors to your clients in case of unhandled exceptions . | train | false |
39,482 | def s3_populate_browser_compatibility(request):
features = Storage()
try:
from pywurfl.algorithms import TwoStepAnalysis
except ImportError:
current.log.warning('pywurfl python module has not been installed, browser compatibility listing will not be populated. Download pywurfl from http://pypi.python.org/pypi/pywurfl/')
return False
import wurfl
device = wurfl.devices.select_ua(unicode(request.env.http_user_agent), search=TwoStepAnalysis(wurfl.devices))
browser = Storage()
for feature in device:
if ((feature[0] in features) and (feature[1] in features[feature[0]])):
browser[feature[0]][feature[1]] = feature[2]
return browser
| [
"def",
"s3_populate_browser_compatibility",
"(",
"request",
")",
":",
"features",
"=",
"Storage",
"(",
")",
"try",
":",
"from",
"pywurfl",
".",
"algorithms",
"import",
"TwoStepAnalysis",
"except",
"ImportError",
":",
"current",
".",
"log",
".",
"warning",
"(",
"'pywurfl python module has not been installed, browser compatibility listing will not be populated. Download pywurfl from http://pypi.python.org/pypi/pywurfl/'",
")",
"return",
"False",
"import",
"wurfl",
"device",
"=",
"wurfl",
".",
"devices",
".",
"select_ua",
"(",
"unicode",
"(",
"request",
".",
"env",
".",
"http_user_agent",
")",
",",
"search",
"=",
"TwoStepAnalysis",
"(",
"wurfl",
".",
"devices",
")",
")",
"browser",
"=",
"Storage",
"(",
")",
"for",
"feature",
"in",
"device",
":",
"if",
"(",
"(",
"feature",
"[",
"0",
"]",
"in",
"features",
")",
"and",
"(",
"feature",
"[",
"1",
"]",
"in",
"features",
"[",
"feature",
"[",
"0",
"]",
"]",
")",
")",
":",
"browser",
"[",
"feature",
"[",
"0",
"]",
"]",
"[",
"feature",
"[",
"1",
"]",
"]",
"=",
"feature",
"[",
"2",
"]",
"return",
"browser"
] | use wurfl for browser compatibility detection @todo: define a list of features to store . | train | false |
39,484 | def expected_cost_for_region(short_number, region_dialing_from):
if isinstance(short_number, PhoneNumber):
short_number = national_significant_number(short_number)
metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from)
if (metadata is None):
return ShortNumberCost.UNKNOWN_COST
if _is_number_matching_desc(short_number, metadata.premium_rate):
return ShortNumberCost.PREMIUM_RATE
if _is_number_matching_desc(short_number, metadata.standard_rate):
return ShortNumberCost.STANDARD_RATE
if _is_number_matching_desc(short_number, metadata.toll_free):
return ShortNumberCost.TOLL_FREE
if is_emergency_number(short_number, region_dialing_from):
return ShortNumberCost.TOLL_FREE
return ShortNumberCost.UNKNOWN_COST
| [
"def",
"expected_cost_for_region",
"(",
"short_number",
",",
"region_dialing_from",
")",
":",
"if",
"isinstance",
"(",
"short_number",
",",
"PhoneNumber",
")",
":",
"short_number",
"=",
"national_significant_number",
"(",
"short_number",
")",
"metadata",
"=",
"PhoneMetadata",
".",
"short_metadata_for_region",
"(",
"region_dialing_from",
")",
"if",
"(",
"metadata",
"is",
"None",
")",
":",
"return",
"ShortNumberCost",
".",
"UNKNOWN_COST",
"if",
"_is_number_matching_desc",
"(",
"short_number",
",",
"metadata",
".",
"premium_rate",
")",
":",
"return",
"ShortNumberCost",
".",
"PREMIUM_RATE",
"if",
"_is_number_matching_desc",
"(",
"short_number",
",",
"metadata",
".",
"standard_rate",
")",
":",
"return",
"ShortNumberCost",
".",
"STANDARD_RATE",
"if",
"_is_number_matching_desc",
"(",
"short_number",
",",
"metadata",
".",
"toll_free",
")",
":",
"return",
"ShortNumberCost",
".",
"TOLL_FREE",
"if",
"is_emergency_number",
"(",
"short_number",
",",
"region_dialing_from",
")",
":",
"return",
"ShortNumberCost",
".",
"TOLL_FREE",
"return",
"ShortNumberCost",
".",
"UNKNOWN_COST"
] | gets the expected cost category of a short number when dialled from a region . | train | false |
39,485 | def seqids_from_otu_to_seqid(otu_to_seqid):
return set(flatten(otu_to_seqid.values()))
| [
"def",
"seqids_from_otu_to_seqid",
"(",
"otu_to_seqid",
")",
":",
"return",
"set",
"(",
"flatten",
"(",
"otu_to_seqid",
".",
"values",
"(",
")",
")",
")"
] | returns set of all seq ids from libs . | train | false |
39,487 | def GetNodes(node, match_tag):
return (child for child in node.getchildren() if (GetTag(child) == match_tag))
| [
"def",
"GetNodes",
"(",
"node",
",",
"match_tag",
")",
":",
"return",
"(",
"child",
"for",
"child",
"in",
"node",
".",
"getchildren",
"(",
")",
"if",
"(",
"GetTag",
"(",
"child",
")",
"==",
"match_tag",
")",
")"
] | gets all children of a node with the desired tag . | train | false |
39,488 | def volume_update(context, volume_id, values):
return IMPL.volume_update(context, volume_id, values)
| [
"def",
"volume_update",
"(",
"context",
",",
"volume_id",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"volume_update",
"(",
"context",
",",
"volume_id",
",",
"values",
")"
] | set the given properties on an volume and update it . | train | false |
39,490 | def is_type(obj, typestr_or_type):
if (typestr_or_type == 'all'):
return True
if (type(typestr_or_type) == type):
test_type = typestr_or_type
else:
test_type = typestr2type.get(typestr_or_type, False)
if test_type:
return isinstance(obj, test_type)
return False
| [
"def",
"is_type",
"(",
"obj",
",",
"typestr_or_type",
")",
":",
"if",
"(",
"typestr_or_type",
"==",
"'all'",
")",
":",
"return",
"True",
"if",
"(",
"type",
"(",
"typestr_or_type",
")",
"==",
"type",
")",
":",
"test_type",
"=",
"typestr_or_type",
"else",
":",
"test_type",
"=",
"typestr2type",
".",
"get",
"(",
"typestr_or_type",
",",
"False",
")",
"if",
"test_type",
":",
"return",
"isinstance",
"(",
"obj",
",",
"test_type",
")",
"return",
"False"
] | is_type verifies if obj is of a certain type . | train | true |
39,491 | def test_find_links_relative_path(script, data):
result = script.pip('install', 'parent==0.1', '--no-index', '--find-links', 'packages/', cwd=data.root)
egg_info_folder = ((script.site_packages / 'parent-0.1-py%s.egg-info') % pyversion)
initools_folder = (script.site_packages / 'parent')
assert (egg_info_folder in result.files_created), str(result)
assert (initools_folder in result.files_created), str(result)
| [
"def",
"test_find_links_relative_path",
"(",
"script",
",",
"data",
")",
":",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'parent==0.1'",
",",
"'--no-index'",
",",
"'--find-links'",
",",
"'packages/'",
",",
"cwd",
"=",
"data",
".",
"root",
")",
"egg_info_folder",
"=",
"(",
"(",
"script",
".",
"site_packages",
"/",
"'parent-0.1-py%s.egg-info'",
")",
"%",
"pyversion",
")",
"initools_folder",
"=",
"(",
"script",
".",
"site_packages",
"/",
"'parent'",
")",
"assert",
"(",
"egg_info_folder",
"in",
"result",
".",
"files_created",
")",
",",
"str",
"(",
"result",
")",
"assert",
"(",
"initools_folder",
"in",
"result",
".",
"files_created",
")",
",",
"str",
"(",
"result",
")"
] | test find-links as a relative path . | train | false |
39,492 | def make_get_public_certificates_call(rpc):
request = app_identity_service_pb.GetPublicCertificateForAppRequest()
response = app_identity_service_pb.GetPublicCertificateForAppResponse()
def get_certs_result(rpc):
'Check success, handle exceptions, and return converted RPC result.\n\n This method waits for the RPC if it has not yet finished, and calls the\n post-call hooks on the first invocation.\n\n Args:\n rpc: A UserRPC object.\n\n Returns:\n A list of PublicCertificate object.\n '
assert (rpc.service == _APP_IDENTITY_SERVICE_NAME), repr(rpc.service)
assert (rpc.method == _GET_CERTS_METHOD_NAME), repr(rpc.method)
try:
rpc.check_success()
except apiproxy_errors.ApplicationError as err:
raise _to_app_identity_error(err)
result = []
for cert in response.public_certificate_list_list():
result.append(PublicCertificate(cert.key_name(), cert.x509_certificate_pem()))
return result
rpc.make_call(_GET_CERTS_METHOD_NAME, request, response, get_certs_result)
| [
"def",
"make_get_public_certificates_call",
"(",
"rpc",
")",
":",
"request",
"=",
"app_identity_service_pb",
".",
"GetPublicCertificateForAppRequest",
"(",
")",
"response",
"=",
"app_identity_service_pb",
".",
"GetPublicCertificateForAppResponse",
"(",
")",
"def",
"get_certs_result",
"(",
"rpc",
")",
":",
"assert",
"(",
"rpc",
".",
"service",
"==",
"_APP_IDENTITY_SERVICE_NAME",
")",
",",
"repr",
"(",
"rpc",
".",
"service",
")",
"assert",
"(",
"rpc",
".",
"method",
"==",
"_GET_CERTS_METHOD_NAME",
")",
",",
"repr",
"(",
"rpc",
".",
"method",
")",
"try",
":",
"rpc",
".",
"check_success",
"(",
")",
"except",
"apiproxy_errors",
".",
"ApplicationError",
"as",
"err",
":",
"raise",
"_to_app_identity_error",
"(",
"err",
")",
"result",
"=",
"[",
"]",
"for",
"cert",
"in",
"response",
".",
"public_certificate_list_list",
"(",
")",
":",
"result",
".",
"append",
"(",
"PublicCertificate",
"(",
"cert",
".",
"key_name",
"(",
")",
",",
"cert",
".",
"x509_certificate_pem",
"(",
")",
")",
")",
"return",
"result",
"rpc",
".",
"make_call",
"(",
"_GET_CERTS_METHOD_NAME",
",",
"request",
",",
"response",
",",
"get_certs_result",
")"
] | executes the rpc call to get a list of public certificates . | train | false |
39,493 | def writeElementNode(derivation, fileNames, target):
xmlObject = target.xmlObject
if (xmlObject == None):
print 'Warning, writeTarget in write could not get xmlObject for:'
print target
print derivation.elementNode
return
parserDirectory = os.path.dirname(derivation.elementNode.getOwnerDocument().fileName)
absoluteFolderDirectory = os.path.abspath(os.path.join(parserDirectory, derivation.folderName))
if ('/models' not in absoluteFolderDirectory):
print 'Warning, models/ was not in the absolute file path, so for security nothing will be done for:'
print derivation.elementNode
print 'For which the absolute folder path is:'
print absoluteFolderDirectory
print 'The write tool can only write a file which has models/ in the file path.'
print 'To write the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.'
return
quantity = evaluate.getEvaluatedInt(1, target, 'quantity')
for itemIndex in xrange(quantity):
writeXMLObject(absoluteFolderDirectory, derivation, fileNames, target, xmlObject)
| [
"def",
"writeElementNode",
"(",
"derivation",
",",
"fileNames",
",",
"target",
")",
":",
"xmlObject",
"=",
"target",
".",
"xmlObject",
"if",
"(",
"xmlObject",
"==",
"None",
")",
":",
"print",
"'Warning, writeTarget in write could not get xmlObject for:'",
"print",
"target",
"print",
"derivation",
".",
"elementNode",
"return",
"parserDirectory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"derivation",
".",
"elementNode",
".",
"getOwnerDocument",
"(",
")",
".",
"fileName",
")",
"absoluteFolderDirectory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"parserDirectory",
",",
"derivation",
".",
"folderName",
")",
")",
"if",
"(",
"'/models'",
"not",
"in",
"absoluteFolderDirectory",
")",
":",
"print",
"'Warning, models/ was not in the absolute file path, so for security nothing will be done for:'",
"print",
"derivation",
".",
"elementNode",
"print",
"'For which the absolute folder path is:'",
"print",
"absoluteFolderDirectory",
"print",
"'The write tool can only write a file which has models/ in the file path.'",
"print",
"'To write the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.'",
"return",
"quantity",
"=",
"evaluate",
".",
"getEvaluatedInt",
"(",
"1",
",",
"target",
",",
"'quantity'",
")",
"for",
"itemIndex",
"in",
"xrange",
"(",
"quantity",
")",
":",
"writeXMLObject",
"(",
"absoluteFolderDirectory",
",",
"derivation",
",",
"fileNames",
",",
"target",
",",
"xmlObject",
")"
] | write a quantity of the target . | train | false |
39,495 | def add_reload_hook(fn):
_reload_hooks.append(fn)
| [
"def",
"add_reload_hook",
"(",
"fn",
")",
":",
"_reload_hooks",
".",
"append",
"(",
"fn",
")"
] | add a function to be called before reloading the process . | train | false |
39,496 | def union_q(token):
query = Q()
operation = 'and'
negation = False
for t in token:
if (type(t) is ParseResults):
query &= union_q(t)
elif (t in ('or', 'and')):
operation = t
elif (t == '-'):
negation = True
else:
if negation:
t = (~ t)
if (operation == 'or'):
query |= t
else:
query &= t
return query
| [
"def",
"union_q",
"(",
"token",
")",
":",
"query",
"=",
"Q",
"(",
")",
"operation",
"=",
"'and'",
"negation",
"=",
"False",
"for",
"t",
"in",
"token",
":",
"if",
"(",
"type",
"(",
"t",
")",
"is",
"ParseResults",
")",
":",
"query",
"&=",
"union_q",
"(",
"t",
")",
"elif",
"(",
"t",
"in",
"(",
"'or'",
",",
"'and'",
")",
")",
":",
"operation",
"=",
"t",
"elif",
"(",
"t",
"==",
"'-'",
")",
":",
"negation",
"=",
"True",
"else",
":",
"if",
"negation",
":",
"t",
"=",
"(",
"~",
"t",
")",
"if",
"(",
"operation",
"==",
"'or'",
")",
":",
"query",
"|=",
"t",
"else",
":",
"query",
"&=",
"t",
"return",
"query"
] | appends all the q() objects . | train | true |
39,498 | def _get_picks(raw):
return [0, 1, 2, 6, 7, 8, 306, 340, 341, 342]
| [
"def",
"_get_picks",
"(",
"raw",
")",
":",
"return",
"[",
"0",
",",
"1",
",",
"2",
",",
"6",
",",
"7",
",",
"8",
",",
"306",
",",
"340",
",",
"341",
",",
"342",
"]"
] | get picks . | train | false |
39,500 | def savepoint_rollback(sid, using=None):
if (using is None):
using = DEFAULT_DB_ALIAS
connection = connections[using]
thread_ident = thread.get_ident()
if ((thread_ident in savepoint_state) and (using in savepoint_state[thread_ident])):
connection._savepoint_rollback(sid)
| [
"def",
"savepoint_rollback",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"if",
"(",
"using",
"is",
"None",
")",
":",
"using",
"=",
"DEFAULT_DB_ALIAS",
"connection",
"=",
"connections",
"[",
"using",
"]",
"thread_ident",
"=",
"thread",
".",
"get_ident",
"(",
")",
"if",
"(",
"(",
"thread_ident",
"in",
"savepoint_state",
")",
"and",
"(",
"using",
"in",
"savepoint_state",
"[",
"thread_ident",
"]",
")",
")",
":",
"connection",
".",
"_savepoint_rollback",
"(",
"sid",
")"
] | rolls back the most recent savepoint . | train | false |
39,501 | def import_finder(dotted_path):
try:
finder_module = import_module(dotted_path)
return finder_module.find_embed
except ImportError as e:
try:
return import_string(dotted_path)
except ImportError:
six.reraise(ImportError, e, sys.exc_info()[2])
| [
"def",
"import_finder",
"(",
"dotted_path",
")",
":",
"try",
":",
"finder_module",
"=",
"import_module",
"(",
"dotted_path",
")",
"return",
"finder_module",
".",
"find_embed",
"except",
"ImportError",
"as",
"e",
":",
"try",
":",
"return",
"import_string",
"(",
"dotted_path",
")",
"except",
"ImportError",
":",
"six",
".",
"reraise",
"(",
"ImportError",
",",
"e",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")"
] | imports a finder function from a dotted path . | train | false |
39,502 | def acme_from_config_key(config, key):
net = acme_client.ClientNetwork(key, verify_ssl=(not config.no_verify_ssl), user_agent=determine_user_agent(config))
return acme_client.Client(config.server, key=key, net=net)
| [
"def",
"acme_from_config_key",
"(",
"config",
",",
"key",
")",
":",
"net",
"=",
"acme_client",
".",
"ClientNetwork",
"(",
"key",
",",
"verify_ssl",
"=",
"(",
"not",
"config",
".",
"no_verify_ssl",
")",
",",
"user_agent",
"=",
"determine_user_agent",
"(",
"config",
")",
")",
"return",
"acme_client",
".",
"Client",
"(",
"config",
".",
"server",
",",
"key",
"=",
"key",
",",
"net",
"=",
"net",
")"
] | wrangle acme client construction . | train | false |
39,503 | def _dirtyPatches():
httplib._MAXLINE = ((1 * 1024) * 1024)
| [
"def",
"_dirtyPatches",
"(",
")",
":",
"httplib",
".",
"_MAXLINE",
"=",
"(",
"(",
"1",
"*",
"1024",
")",
"*",
"1024",
")"
] | place for "dirty" python related patches . | train | false |
39,504 | def get_zone_by_name(conn, module, zone_name, want_private, zone_id, want_vpc_id):
for zone in conn.get_zones():
private_zone = module.boolean(zone.config.get('PrivateZone', False))
if ((private_zone == want_private) and (((zone.name == zone_name) and (zone_id == None)) or (zone.id.replace('/hostedzone/', '') == zone_id))):
if want_vpc_id:
zone_details = conn.get_hosted_zone(zone.id)['GetHostedZoneResponse']
if isinstance(zone_details['VPCs'], dict):
if (zone_details['VPCs']['VPC']['VPCId'] == want_vpc_id):
return zone
elif (want_vpc_id in [v['VPCId'] for v in zone_details['VPCs']]):
return zone
else:
return zone
return None
| [
"def",
"get_zone_by_name",
"(",
"conn",
",",
"module",
",",
"zone_name",
",",
"want_private",
",",
"zone_id",
",",
"want_vpc_id",
")",
":",
"for",
"zone",
"in",
"conn",
".",
"get_zones",
"(",
")",
":",
"private_zone",
"=",
"module",
".",
"boolean",
"(",
"zone",
".",
"config",
".",
"get",
"(",
"'PrivateZone'",
",",
"False",
")",
")",
"if",
"(",
"(",
"private_zone",
"==",
"want_private",
")",
"and",
"(",
"(",
"(",
"zone",
".",
"name",
"==",
"zone_name",
")",
"and",
"(",
"zone_id",
"==",
"None",
")",
")",
"or",
"(",
"zone",
".",
"id",
".",
"replace",
"(",
"'/hostedzone/'",
",",
"''",
")",
"==",
"zone_id",
")",
")",
")",
":",
"if",
"want_vpc_id",
":",
"zone_details",
"=",
"conn",
".",
"get_hosted_zone",
"(",
"zone",
".",
"id",
")",
"[",
"'GetHostedZoneResponse'",
"]",
"if",
"isinstance",
"(",
"zone_details",
"[",
"'VPCs'",
"]",
",",
"dict",
")",
":",
"if",
"(",
"zone_details",
"[",
"'VPCs'",
"]",
"[",
"'VPC'",
"]",
"[",
"'VPCId'",
"]",
"==",
"want_vpc_id",
")",
":",
"return",
"zone",
"elif",
"(",
"want_vpc_id",
"in",
"[",
"v",
"[",
"'VPCId'",
"]",
"for",
"v",
"in",
"zone_details",
"[",
"'VPCs'",
"]",
"]",
")",
":",
"return",
"zone",
"else",
":",
"return",
"zone",
"return",
"None"
] | finds a zone by name or zone_id . | train | false |
39,505 | def base64_encodefile(fname):
encoded_f = StringIO.StringIO()
with open(fname, 'rb') as f:
base64.encode(f, encoded_f)
encoded_f.seek(0)
return encoded_f.read()
| [
"def",
"base64_encodefile",
"(",
"fname",
")",
":",
"encoded_f",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"f",
":",
"base64",
".",
"encode",
"(",
"f",
",",
"encoded_f",
")",
"encoded_f",
".",
"seek",
"(",
"0",
")",
"return",
"encoded_f",
".",
"read",
"(",
")"
] | read a file from the file system and return as a base64 encoded string . | train | false |
39,507 | def nd_option_def(cls):
_nd_options[cls.TYPE] = cls
return cls
| [
"def",
"nd_option_def",
"(",
"cls",
")",
":",
"_nd_options",
"[",
"cls",
".",
"TYPE",
"]",
"=",
"cls",
"return",
"cls"
] | neighbor discovery option decorator . | train | false |
39,508 | @onlyif_unicode_paths
def test_unicode_in_filename():
try:
path.get_py_filename('foo\xc3\xa9\xc3\xa8.py', force_win32=False)
except IOError as ex:
str(ex)
| [
"@",
"onlyif_unicode_paths",
"def",
"test_unicode_in_filename",
"(",
")",
":",
"try",
":",
"path",
".",
"get_py_filename",
"(",
"'foo\\xc3\\xa9\\xc3\\xa8.py'",
",",
"force_win32",
"=",
"False",
")",
"except",
"IOError",
"as",
"ex",
":",
"str",
"(",
"ex",
")"
] | when a file doesnt exist . | train | false |
39,510 | def get_installed_version(dist_name, lookup_dirs=None):
req = pkg_resources.Requirement.parse(dist_name)
if (lookup_dirs is None):
working_set = pkg_resources.WorkingSet()
else:
working_set = pkg_resources.WorkingSet(lookup_dirs)
dist = working_set.find(req)
return (dist.version if dist else None)
| [
"def",
"get_installed_version",
"(",
"dist_name",
",",
"lookup_dirs",
"=",
"None",
")",
":",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"dist_name",
")",
"if",
"(",
"lookup_dirs",
"is",
"None",
")",
":",
"working_set",
"=",
"pkg_resources",
".",
"WorkingSet",
"(",
")",
"else",
":",
"working_set",
"=",
"pkg_resources",
".",
"WorkingSet",
"(",
"lookup_dirs",
")",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"return",
"(",
"dist",
".",
"version",
"if",
"dist",
"else",
"None",
")"
] | get the installed version of dist_name avoiding pkg_resources cache . | train | true |
39,511 | def DjangoVersion():
try:
__import__(('django.' + _DESIRED_DJANGO_VERSION))
except ImportError:
pass
import django
try:
return distutils.version.LooseVersion('.'.join(map(str, django.VERSION)))
except AttributeError:
return LooseVersion(django.VERSION)
| [
"def",
"DjangoVersion",
"(",
")",
":",
"try",
":",
"__import__",
"(",
"(",
"'django.'",
"+",
"_DESIRED_DJANGO_VERSION",
")",
")",
"except",
"ImportError",
":",
"pass",
"import",
"django",
"try",
":",
"return",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"django",
".",
"VERSION",
")",
")",
")",
"except",
"AttributeError",
":",
"return",
"LooseVersion",
"(",
"django",
".",
"VERSION",
")"
] | discover the version of django installed . | train | false |
39,512 | def ValidateHandlers(handlers, is_include_file=False):
if (not handlers):
return
for handler in handlers:
handler.FixSecureDefaults()
handler.WarnReservedURLs()
if (not is_include_file):
handler.ErrorOnPositionForAppInfo()
| [
"def",
"ValidateHandlers",
"(",
"handlers",
",",
"is_include_file",
"=",
"False",
")",
":",
"if",
"(",
"not",
"handlers",
")",
":",
"return",
"for",
"handler",
"in",
"handlers",
":",
"handler",
".",
"FixSecureDefaults",
"(",
")",
"handler",
".",
"WarnReservedURLs",
"(",
")",
"if",
"(",
"not",
"is_include_file",
")",
":",
"handler",
".",
"ErrorOnPositionForAppInfo",
"(",
")"
] | validates a list of handler objects . | train | false |
39,513 | def interactive_debug(sig, frame):
d = {'_frame': frame}
d.update(frame.f_globals)
d.update(frame.f_locals)
message = 'Signal received : entering python shell.\nTraceback:\n'
message += ''.join(traceback.format_stack(frame))
i = code.InteractiveConsole(d)
i.interact(message)
| [
"def",
"interactive_debug",
"(",
"sig",
",",
"frame",
")",
":",
"d",
"=",
"{",
"'_frame'",
":",
"frame",
"}",
"d",
".",
"update",
"(",
"frame",
".",
"f_globals",
")",
"d",
".",
"update",
"(",
"frame",
".",
"f_locals",
")",
"message",
"=",
"'Signal received : entering python shell.\\nTraceback:\\n'",
"message",
"+=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
"frame",
")",
")",
"i",
"=",
"code",
".",
"InteractiveConsole",
"(",
"d",
")",
"i",
".",
"interact",
"(",
"message",
")"
] | interrupt running process . | train | true |
39,514 | def dup_add_ground(f, c, K):
return dup_add_term(f, c, 0, K)
| [
"def",
"dup_add_ground",
"(",
"f",
",",
"c",
",",
"K",
")",
":",
"return",
"dup_add_term",
"(",
"f",
",",
"c",
",",
"0",
",",
"K",
")"
] | add an element of the ground domain to f . | train | false |
39,515 | def get_module_file_attribute(package):
try:
loader = pkgutil.find_loader(package)
attr = loader.get_filename(package)
except (AttributeError, ImportError):
__file__statement = '\n import %s as p\n print(p.__file__)\n '
attr = exec_statement((__file__statement % package))
if (not attr.strip()):
raise ImportError
return attr
| [
"def",
"get_module_file_attribute",
"(",
"package",
")",
":",
"try",
":",
"loader",
"=",
"pkgutil",
".",
"find_loader",
"(",
"package",
")",
"attr",
"=",
"loader",
".",
"get_filename",
"(",
"package",
")",
"except",
"(",
"AttributeError",
",",
"ImportError",
")",
":",
"__file__statement",
"=",
"'\\n import %s as p\\n print(p.__file__)\\n '",
"attr",
"=",
"exec_statement",
"(",
"(",
"__file__statement",
"%",
"package",
")",
")",
"if",
"(",
"not",
"attr",
".",
"strip",
"(",
")",
")",
":",
"raise",
"ImportError",
"return",
"attr"
] | get the absolute path of the module with the passed name . | train | false |
39,516 | def drop_model_tables(models, **drop_table_kwargs):
for m in reversed(sort_models_topologically(models)):
m.drop_table(**drop_table_kwargs)
| [
"def",
"drop_model_tables",
"(",
"models",
",",
"**",
"drop_table_kwargs",
")",
":",
"for",
"m",
"in",
"reversed",
"(",
"sort_models_topologically",
"(",
"models",
")",
")",
":",
"m",
".",
"drop_table",
"(",
"**",
"drop_table_kwargs",
")"
] | drop tables for all given models . | train | true |
39,517 | def console_auth_token_destroy_expired_by_host(context, host):
return IMPL.console_auth_token_destroy_expired_by_host(context, host)
| [
"def",
"console_auth_token_destroy_expired_by_host",
"(",
"context",
",",
"host",
")",
":",
"return",
"IMPL",
".",
"console_auth_token_destroy_expired_by_host",
"(",
"context",
",",
"host",
")"
] | delete expired console authorizations belonging to the host . | train | false |
39,519 | def get_datastore_id(kwargs=None, call=None):
if (call == 'action'):
raise SaltCloudSystemExit('The get_datastore_id function must be called with -f or --function.')
if (kwargs is None):
kwargs = {}
name = kwargs.get('name', None)
if (name is None):
raise SaltCloudSystemExit('The get_datastore_id function requires a name.')
try:
ret = list_datastores()[name]['id']
except KeyError:
raise SaltCloudSystemExit("The datastore '{0}' could not be found.".format(name))
return ret
| [
"def",
"get_datastore_id",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"==",
"'action'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The get_datastore_id function must be called with -f or --function.'",
")",
"if",
"(",
"kwargs",
"is",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"if",
"(",
"name",
"is",
"None",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The get_datastore_id function requires a name.'",
")",
"try",
":",
"ret",
"=",
"list_datastores",
"(",
")",
"[",
"name",
"]",
"[",
"'id'",
"]",
"except",
"KeyError",
":",
"raise",
"SaltCloudSystemExit",
"(",
"\"The datastore '{0}' could not be found.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"ret"
] | returns a data stores id from the given data store name . | train | true |
39,520 | def apply_path_dir_wildcard(dirs, path_dir_wildcard):
path_globs = tuple((pg for d in dirs.dependencies for pg in PathGlob.create_from_spec(d.stat, d.path, path_dir_wildcard.remainder)))
return PathsExpansion(Paths(tuple()), path_globs)
| [
"def",
"apply_path_dir_wildcard",
"(",
"dirs",
",",
"path_dir_wildcard",
")",
":",
"path_globs",
"=",
"tuple",
"(",
"(",
"pg",
"for",
"d",
"in",
"dirs",
".",
"dependencies",
"for",
"pg",
"in",
"PathGlob",
".",
"create_from_spec",
"(",
"d",
".",
"stat",
",",
"d",
".",
"path",
",",
"path_dir_wildcard",
".",
"remainder",
")",
")",
")",
"return",
"PathsExpansion",
"(",
"Paths",
"(",
"tuple",
"(",
")",
")",
",",
"path_globs",
")"
] | given a pathdirwildcard . | train | false |
39,521 | def _do_mb_put(path):
return _mb_request(path, 'PUT', AUTH_YES, True)
| [
"def",
"_do_mb_put",
"(",
"path",
")",
":",
"return",
"_mb_request",
"(",
"path",
",",
"'PUT'",
",",
"AUTH_YES",
",",
"True",
")"
] | send a put request for the specified object . | train | false |
39,523 | def transform_matrix_offset_center(matrix, x, y):
o_x = ((float(x) / 2) + 0.5)
o_y = ((float(y) / 2) + 0.5)
offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])
reset_matrix = np.array([[1, 0, (- o_x)], [0, 1, (- o_y)], [0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)
return transform_matrix
| [
"def",
"transform_matrix_offset_center",
"(",
"matrix",
",",
"x",
",",
"y",
")",
":",
"o_x",
"=",
"(",
"(",
"float",
"(",
"x",
")",
"/",
"2",
")",
"+",
"0.5",
")",
"o_y",
"=",
"(",
"(",
"float",
"(",
"y",
")",
"/",
"2",
")",
"+",
"0.5",
")",
"offset_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"o_x",
"]",
",",
"[",
"0",
",",
"1",
",",
"o_y",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"reset_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"(",
"-",
"o_x",
")",
"]",
",",
"[",
"0",
",",
"1",
",",
"(",
"-",
"o_y",
")",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"offset_matrix",
",",
"matrix",
")",
",",
"reset_matrix",
")",
"return",
"transform_matrix"
] | return transform matrix offset center . | train | true |
39,526 | def sanitize_index_lists(ind):
if (not isinstance(ind, (list, np.ndarray))):
return ind
if isinstance(ind, np.ndarray):
ind = ind.tolist()
if (isinstance(ind, list) and ind and isinstance(ind[0], bool)):
ind = [a for (a, b) in enumerate(ind) if b]
return ind
| [
"def",
"sanitize_index_lists",
"(",
"ind",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"ind",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
")",
":",
"return",
"ind",
"if",
"isinstance",
"(",
"ind",
",",
"np",
".",
"ndarray",
")",
":",
"ind",
"=",
"ind",
".",
"tolist",
"(",
")",
"if",
"(",
"isinstance",
"(",
"ind",
",",
"list",
")",
"and",
"ind",
"and",
"isinstance",
"(",
"ind",
"[",
"0",
"]",
",",
"bool",
")",
")",
":",
"ind",
"=",
"[",
"a",
"for",
"(",
"a",
",",
"b",
")",
"in",
"enumerate",
"(",
"ind",
")",
"if",
"b",
"]",
"return",
"ind"
] | handle lists/arrays of integers/bools as indexes . | train | false |
39,527 | def plot_rank_abundance_graph(otu_count_vector, color='red', absolute=False, label=None):
f = make_sorted_frequencies(otu_count_vector, absolute)
x = arange(1, (len(f) + 1))
plot(x, f, color=color, alpha=0.8, label=label)
ax = gca()
return ax
| [
"def",
"plot_rank_abundance_graph",
"(",
"otu_count_vector",
",",
"color",
"=",
"'red'",
",",
"absolute",
"=",
"False",
",",
"label",
"=",
"None",
")",
":",
"f",
"=",
"make_sorted_frequencies",
"(",
"otu_count_vector",
",",
"absolute",
")",
"x",
"=",
"arange",
"(",
"1",
",",
"(",
"len",
"(",
"f",
")",
"+",
"1",
")",
")",
"plot",
"(",
"x",
",",
"f",
",",
"color",
"=",
"color",
",",
"alpha",
"=",
"0.8",
",",
"label",
"=",
"label",
")",
"ax",
"=",
"gca",
"(",
")",
"return",
"ax"
] | plots rank-abundance curve . | train | false |
39,528 | def inp(address):
return port.DlPortReadPortUchar(address)
| [
"def",
"inp",
"(",
"address",
")",
":",
"return",
"port",
".",
"DlPortReadPortUchar",
"(",
"address",
")"
] | the usual in function . | train | false |
39,529 | def get_valid_graph_obj(obj, obj_type=None):
from plotly.graph_objs import graph_objs
try:
cls = getattr(graph_objs, obj_type)
except (AttributeError, KeyError):
raise exceptions.PlotlyError("'{}' is not a recognized graph_obj.".format(obj_type))
return cls(obj, _raise=False)
| [
"def",
"get_valid_graph_obj",
"(",
"obj",
",",
"obj_type",
"=",
"None",
")",
":",
"from",
"plotly",
".",
"graph_objs",
"import",
"graph_objs",
"try",
":",
"cls",
"=",
"getattr",
"(",
"graph_objs",
",",
"obj_type",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"'{}' is not a recognized graph_obj.\"",
".",
"format",
"(",
"obj_type",
")",
")",
"return",
"cls",
"(",
"obj",
",",
"_raise",
"=",
"False",
")"
] | returns a new graph object that wont raise . | train | false |
39,530 | def test_basic_call_on_method_coroutine():
class API(object, ):
@hug.call()
@asyncio.coroutine
def hello_world(self=None):
return 'Hello World!'
api_instance = API()
assert api_instance.hello_world.interface.http
assert (loop.run_until_complete(api_instance.hello_world()) == 'Hello World!')
assert (hug.test.get(api, '/hello_world').data == 'Hello World!')
| [
"def",
"test_basic_call_on_method_coroutine",
"(",
")",
":",
"class",
"API",
"(",
"object",
",",
")",
":",
"@",
"hug",
".",
"call",
"(",
")",
"@",
"asyncio",
".",
"coroutine",
"def",
"hello_world",
"(",
"self",
"=",
"None",
")",
":",
"return",
"'Hello World!'",
"api_instance",
"=",
"API",
"(",
")",
"assert",
"api_instance",
".",
"hello_world",
".",
"interface",
".",
"http",
"assert",
"(",
"loop",
".",
"run_until_complete",
"(",
"api_instance",
".",
"hello_world",
"(",
")",
")",
"==",
"'Hello World!'",
")",
"assert",
"(",
"hug",
".",
"test",
".",
"get",
"(",
"api",
",",
"'/hello_world'",
")",
".",
"data",
"==",
"'Hello World!'",
")"
] | test to ensure the most basic call still works if applied to a method . | train | false |
39,531 | @logic.side_effect_free
def datastore_search_sql(context, data_dict):
sql = _get_or_bust(data_dict, 'sql')
if (not datastore_helpers.is_single_statement(sql)):
raise p.toolkit.ValidationError({'query': ['Query is not a single statement.']})
p.toolkit.check_access('datastore_search_sql', context, data_dict)
data_dict['connection_url'] = config['ckan.datastore.read_url']
result = db.search_sql(context, data_dict)
result.pop('id', None)
result.pop('connection_url')
return result
| [
"@",
"logic",
".",
"side_effect_free",
"def",
"datastore_search_sql",
"(",
"context",
",",
"data_dict",
")",
":",
"sql",
"=",
"_get_or_bust",
"(",
"data_dict",
",",
"'sql'",
")",
"if",
"(",
"not",
"datastore_helpers",
".",
"is_single_statement",
"(",
"sql",
")",
")",
":",
"raise",
"p",
".",
"toolkit",
".",
"ValidationError",
"(",
"{",
"'query'",
":",
"[",
"'Query is not a single statement.'",
"]",
"}",
")",
"p",
".",
"toolkit",
".",
"check_access",
"(",
"'datastore_search_sql'",
",",
"context",
",",
"data_dict",
")",
"data_dict",
"[",
"'connection_url'",
"]",
"=",
"config",
"[",
"'ckan.datastore.read_url'",
"]",
"result",
"=",
"db",
".",
"search_sql",
"(",
"context",
",",
"data_dict",
")",
"result",
".",
"pop",
"(",
"'id'",
",",
"None",
")",
"result",
".",
"pop",
"(",
"'connection_url'",
")",
"return",
"result"
] | execute sql queries on the datastore . | train | false |
39,532 | def blockname(ch):
assert (isinstance(ch, text_type) and (len(ch) == 1)), repr(ch)
cp = ord(ch)
i = (bisect_right(_starts, cp) - 1)
end = _ends[i]
if (cp > end):
return None
return _names[i]
| [
"def",
"blockname",
"(",
"ch",
")",
":",
"assert",
"(",
"isinstance",
"(",
"ch",
",",
"text_type",
")",
"and",
"(",
"len",
"(",
"ch",
")",
"==",
"1",
")",
")",
",",
"repr",
"(",
"ch",
")",
"cp",
"=",
"ord",
"(",
"ch",
")",
"i",
"=",
"(",
"bisect_right",
"(",
"_starts",
",",
"cp",
")",
"-",
"1",
")",
"end",
"=",
"_ends",
"[",
"i",
"]",
"if",
"(",
"cp",
">",
"end",
")",
":",
"return",
"None",
"return",
"_names",
"[",
"i",
"]"
] | return the unicode block name for ch . | train | false |
39,533 | @treeio_login_required
@handle_response_format
@module_admin_required('treeio.sales')
def product_add(request, parent_id=None, response_format='html'):
all_products = Object.filter_by_request(request, Product.objects.filter(parent__isnull=True))
if request.POST:
if ('cancel' not in request.POST):
product = Product()
form = ProductForm(request.user.profile, None, request.POST, instance=product)
if form.is_valid():
product = form.save()
product.set_user_from_request(request)
return HttpResponseRedirect(reverse('sales_product_view', args=[product.id]))
else:
return HttpResponseRedirect(reverse('sales_product_index'))
else:
form = ProductForm(request.user.profile, parent_id)
return render_to_response('sales/product_add', {'form': form, 'products': all_products}, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"treeio_login_required",
"@",
"handle_response_format",
"@",
"module_admin_required",
"(",
"'treeio.sales'",
")",
"def",
"product_add",
"(",
"request",
",",
"parent_id",
"=",
"None",
",",
"response_format",
"=",
"'html'",
")",
":",
"all_products",
"=",
"Object",
".",
"filter_by_request",
"(",
"request",
",",
"Product",
".",
"objects",
".",
"filter",
"(",
"parent__isnull",
"=",
"True",
")",
")",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'cancel'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"product",
"=",
"Product",
"(",
")",
"form",
"=",
"ProductForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"None",
",",
"request",
".",
"POST",
",",
"instance",
"=",
"product",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"product",
"=",
"form",
".",
"save",
"(",
")",
"product",
".",
"set_user_from_request",
"(",
"request",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'sales_product_view'",
",",
"args",
"=",
"[",
"product",
".",
"id",
"]",
")",
")",
"else",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'sales_product_index'",
")",
")",
"else",
":",
"form",
"=",
"ProductForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"parent_id",
")",
"return",
"render_to_response",
"(",
"'sales/product_add'",
",",
"{",
"'form'",
":",
"form",
",",
"'products'",
":",
"all_products",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | product add . | train | false |
39,534 | def add_mock_s3_data(mock_s3_fs, data, time_modified=None, location=None):
if (time_modified is None):
time_modified = datetime.utcnow()
for (bucket_name, key_name_to_bytes) in data.items():
bucket = mock_s3_fs.setdefault(bucket_name, {'keys': {}, 'location': ''})
for (key_name, key_data) in key_name_to_bytes.items():
if (not isinstance(key_data, bytes)):
raise TypeError('mock s3 data must be bytes')
bucket['keys'][key_name] = (key_data, time_modified)
if (location is not None):
bucket['location'] = location
| [
"def",
"add_mock_s3_data",
"(",
"mock_s3_fs",
",",
"data",
",",
"time_modified",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"if",
"(",
"time_modified",
"is",
"None",
")",
":",
"time_modified",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"(",
"bucket_name",
",",
"key_name_to_bytes",
")",
"in",
"data",
".",
"items",
"(",
")",
":",
"bucket",
"=",
"mock_s3_fs",
".",
"setdefault",
"(",
"bucket_name",
",",
"{",
"'keys'",
":",
"{",
"}",
",",
"'location'",
":",
"''",
"}",
")",
"for",
"(",
"key_name",
",",
"key_data",
")",
"in",
"key_name_to_bytes",
".",
"items",
"(",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"key_data",
",",
"bytes",
")",
")",
":",
"raise",
"TypeError",
"(",
"'mock s3 data must be bytes'",
")",
"bucket",
"[",
"'keys'",
"]",
"[",
"key_name",
"]",
"=",
"(",
"key_data",
",",
"time_modified",
")",
"if",
"(",
"location",
"is",
"not",
"None",
")",
":",
"bucket",
"[",
"'location'",
"]",
"=",
"location"
] | update mock_s3_fs with a map from bucket name to key name to data and time last modified . | train | false |
39,535 | def bsd_jail_path(jid):
if (jid != 0):
jls_output = call((GET_BSD_JAIL_PATH % jid), [])
if ((len(jls_output) == 2) and (len(jls_output[1].split()) == 4)):
return jls_output[1].split()[3]
return None
| [
"def",
"bsd_jail_path",
"(",
"jid",
")",
":",
"if",
"(",
"jid",
"!=",
"0",
")",
":",
"jls_output",
"=",
"call",
"(",
"(",
"GET_BSD_JAIL_PATH",
"%",
"jid",
")",
",",
"[",
"]",
")",
"if",
"(",
"(",
"len",
"(",
"jls_output",
")",
"==",
"2",
")",
"and",
"(",
"len",
"(",
"jls_output",
"[",
"1",
"]",
".",
"split",
"(",
")",
")",
"==",
"4",
")",
")",
":",
"return",
"jls_output",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"3",
"]",
"return",
"None"
] | provides the path of the given freebsd jail . | train | false |
39,538 | def neuron(w, x):
return sigmoid((w[0] + np.inner(w[1:], x)))
| [
"def",
"neuron",
"(",
"w",
",",
"x",
")",
":",
"return",
"sigmoid",
"(",
"(",
"w",
"[",
"0",
"]",
"+",
"np",
".",
"inner",
"(",
"w",
"[",
"1",
":",
"]",
",",
"x",
")",
")",
")"
] | return the output from the sigmoid neuron with weights w and inputs x . | train | false |
39,540 | def in6_cidr2mask(m):
if ((m > 128) or (m < 0)):
raise Scapy_Exception(('value provided to in6_cidr2mask outside [0, 128] domain (%d)' % m))
t = []
for i in xrange(0, 4):
t.append(max(0, ((2 ** 32) - (2 ** (32 - min(32, m))))))
m -= 32
return ''.join(map((lambda x: struct.pack('!I', x)), t))
| [
"def",
"in6_cidr2mask",
"(",
"m",
")",
":",
"if",
"(",
"(",
"m",
">",
"128",
")",
"or",
"(",
"m",
"<",
"0",
")",
")",
":",
"raise",
"Scapy_Exception",
"(",
"(",
"'value provided to in6_cidr2mask outside [0, 128] domain (%d)'",
"%",
"m",
")",
")",
"t",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"4",
")",
":",
"t",
".",
"append",
"(",
"max",
"(",
"0",
",",
"(",
"(",
"2",
"**",
"32",
")",
"-",
"(",
"2",
"**",
"(",
"32",
"-",
"min",
"(",
"32",
",",
"m",
")",
")",
")",
")",
")",
")",
"m",
"-=",
"32",
"return",
"''",
".",
"join",
"(",
"map",
"(",
"(",
"lambda",
"x",
":",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"x",
")",
")",
",",
"t",
")",
")"
] | return the mask associated with provided length value . | train | false |
39,542 | def setup_requests_scheme(config):
settings = config.get_settings()
http_scheme = settings['http_scheme']
http_host = settings['http_host']
def on_new_request(event):
if http_scheme:
event.request.scheme = http_scheme
if http_host:
event.request.host = http_host
if (http_scheme or http_host):
config.add_subscriber(on_new_request, NewRequest)
| [
"def",
"setup_requests_scheme",
"(",
"config",
")",
":",
"settings",
"=",
"config",
".",
"get_settings",
"(",
")",
"http_scheme",
"=",
"settings",
"[",
"'http_scheme'",
"]",
"http_host",
"=",
"settings",
"[",
"'http_host'",
"]",
"def",
"on_new_request",
"(",
"event",
")",
":",
"if",
"http_scheme",
":",
"event",
".",
"request",
".",
"scheme",
"=",
"http_scheme",
"if",
"http_host",
":",
"event",
".",
"request",
".",
"host",
"=",
"http_host",
"if",
"(",
"http_scheme",
"or",
"http_host",
")",
":",
"config",
".",
"add_subscriber",
"(",
"on_new_request",
",",
"NewRequest",
")"
] | force server scheme . | train | false |
39,544 | def pgrep(pattern, user=None, full=False):
procs = []
for proc in psutil.process_iter():
name_match = ((pattern in ' '.join(_get_proc_cmdline(proc))) if full else (pattern in _get_proc_name(proc)))
user_match = (True if (user is None) else (user == _get_proc_username(proc)))
if (name_match and user_match):
procs.append(_get_proc_pid(proc))
return (procs or None)
| [
"def",
"pgrep",
"(",
"pattern",
",",
"user",
"=",
"None",
",",
"full",
"=",
"False",
")",
":",
"procs",
"=",
"[",
"]",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"name_match",
"=",
"(",
"(",
"pattern",
"in",
"' '",
".",
"join",
"(",
"_get_proc_cmdline",
"(",
"proc",
")",
")",
")",
"if",
"full",
"else",
"(",
"pattern",
"in",
"_get_proc_name",
"(",
"proc",
")",
")",
")",
"user_match",
"=",
"(",
"True",
"if",
"(",
"user",
"is",
"None",
")",
"else",
"(",
"user",
"==",
"_get_proc_username",
"(",
"proc",
")",
")",
")",
"if",
"(",
"name_match",
"and",
"user_match",
")",
":",
"procs",
".",
"append",
"(",
"_get_proc_pid",
"(",
"proc",
")",
")",
"return",
"(",
"procs",
"or",
"None",
")"
] | return the pids for processes matching a pattern . | train | false |
39,545 | def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=(-1)):
(parent, buf) = get_parent(globals, level)
(head, name, buf) = load_next(parent, (None if (level < 0) else parent), name, buf)
tail = head
while name:
(tail, name, buf) = load_next(tail, tail, name, buf)
if (tail is None):
raise ValueError('Empty module name')
if (not fromlist):
return head
ensure_fromlist(tail, fromlist, buf, 0)
return tail
| [
"def",
"deep_import_hook",
"(",
"name",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
",",
"fromlist",
"=",
"None",
",",
"level",
"=",
"(",
"-",
"1",
")",
")",
":",
"(",
"parent",
",",
"buf",
")",
"=",
"get_parent",
"(",
"globals",
",",
"level",
")",
"(",
"head",
",",
"name",
",",
"buf",
")",
"=",
"load_next",
"(",
"parent",
",",
"(",
"None",
"if",
"(",
"level",
"<",
"0",
")",
"else",
"parent",
")",
",",
"name",
",",
"buf",
")",
"tail",
"=",
"head",
"while",
"name",
":",
"(",
"tail",
",",
"name",
",",
"buf",
")",
"=",
"load_next",
"(",
"tail",
",",
"tail",
",",
"name",
",",
"buf",
")",
"if",
"(",
"tail",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"'Empty module name'",
")",
"if",
"(",
"not",
"fromlist",
")",
":",
"return",
"head",
"ensure_fromlist",
"(",
"tail",
",",
"fromlist",
",",
"buf",
",",
"0",
")",
"return",
"tail"
] | replacement for __import__() . | train | true |
39,547 | def _attach_volume_and_wait_for_device(volume, attach_to, attach_volume, detach_volume, device, blockdevices):
try:
attach_volume(volume.blockdevice_id, attach_to, device)
except ClientError as e:
if (e.response['Error']['Code'] == u'InvalidParameterValue'):
return False
raise
else:
device_path = _wait_for_new_device(base=blockdevices, expected_size=volume.size)
if (_expected_device(device) != device_path):
detach_volume(volume.blockdevice_id)
raise AttachedUnexpectedDevice(FilePath(device), device_path)
return True
| [
"def",
"_attach_volume_and_wait_for_device",
"(",
"volume",
",",
"attach_to",
",",
"attach_volume",
",",
"detach_volume",
",",
"device",
",",
"blockdevices",
")",
":",
"try",
":",
"attach_volume",
"(",
"volume",
".",
"blockdevice_id",
",",
"attach_to",
",",
"device",
")",
"except",
"ClientError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"response",
"[",
"'Error'",
"]",
"[",
"'Code'",
"]",
"==",
"u'InvalidParameterValue'",
")",
":",
"return",
"False",
"raise",
"else",
":",
"device_path",
"=",
"_wait_for_new_device",
"(",
"base",
"=",
"blockdevices",
",",
"expected_size",
"=",
"volume",
".",
"size",
")",
"if",
"(",
"_expected_device",
"(",
"device",
")",
"!=",
"device_path",
")",
":",
"detach_volume",
"(",
"volume",
".",
"blockdevice_id",
")",
"raise",
"AttachedUnexpectedDevice",
"(",
"FilePath",
"(",
"device",
")",
",",
"device_path",
")",
"return",
"True"
] | attempt to attach an ebs volume to an ec2 instance and wait for the corresponding os device to become available . | train | false |
39,548 | def random_permutation(iterable, r=None):
pool = tuple(iterable)
r = (len(pool) if (r is None) else r)
return tuple(random.sample(pool, r))
| [
"def",
"random_permutation",
"(",
"iterable",
",",
"r",
"=",
"None",
")",
":",
"pool",
"=",
"tuple",
"(",
"iterable",
")",
"r",
"=",
"(",
"len",
"(",
"pool",
")",
"if",
"(",
"r",
"is",
"None",
")",
"else",
"r",
")",
"return",
"tuple",
"(",
"random",
".",
"sample",
"(",
"pool",
",",
"r",
")",
")"
] | random_product -> tuple arguments: iterable: an iterable . | train | true |
39,550 | def test_coercing_fill_value_type():
t = Table({'a': ['1']}, masked=True)
t['a'].set_fill_value('0')
t2 = Table(t, names=['a'], dtype=[np.int32])
assert isinstance(t2['a'].fill_value, np.int32)
c = MaskedColumn(['1'])
c.set_fill_value('0')
c2 = MaskedColumn(c, dtype=np.int32)
assert isinstance(c2.fill_value, np.int32)
| [
"def",
"test_coercing_fill_value_type",
"(",
")",
":",
"t",
"=",
"Table",
"(",
"{",
"'a'",
":",
"[",
"'1'",
"]",
"}",
",",
"masked",
"=",
"True",
")",
"t",
"[",
"'a'",
"]",
".",
"set_fill_value",
"(",
"'0'",
")",
"t2",
"=",
"Table",
"(",
"t",
",",
"names",
"=",
"[",
"'a'",
"]",
",",
"dtype",
"=",
"[",
"np",
".",
"int32",
"]",
")",
"assert",
"isinstance",
"(",
"t2",
"[",
"'a'",
"]",
".",
"fill_value",
",",
"np",
".",
"int32",
")",
"c",
"=",
"MaskedColumn",
"(",
"[",
"'1'",
"]",
")",
"c",
".",
"set_fill_value",
"(",
"'0'",
")",
"c2",
"=",
"MaskedColumn",
"(",
"c",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"assert",
"isinstance",
"(",
"c2",
".",
"fill_value",
",",
"np",
".",
"int32",
")"
] | test that masked column fill_value is coerced into the correct column type . | train | false |
39,551 | def two_product(a, b):
x = (a * b)
(ah, al) = split(a)
(bh, bl) = split(b)
y1 = (ah * bh)
y = (x - y1)
y2 = (al * bh)
y -= y2
y3 = (ah * bl)
y -= y3
y4 = (al * bl)
y = (y4 - y)
return (x, y)
| [
"def",
"two_product",
"(",
"a",
",",
"b",
")",
":",
"x",
"=",
"(",
"a",
"*",
"b",
")",
"(",
"ah",
",",
"al",
")",
"=",
"split",
"(",
"a",
")",
"(",
"bh",
",",
"bl",
")",
"=",
"split",
"(",
"b",
")",
"y1",
"=",
"(",
"ah",
"*",
"bh",
")",
"y",
"=",
"(",
"x",
"-",
"y1",
")",
"y2",
"=",
"(",
"al",
"*",
"bh",
")",
"y",
"-=",
"y2",
"y3",
"=",
"(",
"ah",
"*",
"bl",
")",
"y",
"-=",
"y3",
"y4",
"=",
"(",
"al",
"*",
"bl",
")",
"y",
"=",
"(",
"y4",
"-",
"y",
")",
"return",
"(",
"x",
",",
"y",
")"
] | multiple a and b exactly . | train | false |
39,552 | def public_gists(number=(-1), etag=None):
return gh.public_gists(number, etag)
| [
"def",
"public_gists",
"(",
"number",
"=",
"(",
"-",
"1",
")",
",",
"etag",
"=",
"None",
")",
":",
"return",
"gh",
".",
"public_gists",
"(",
"number",
",",
"etag",
")"
] | iterate over all public gists . | train | false |
39,553 | def classification_rate(features):
labels = _knn.predict(trainset[N_TRAIN:], features)
return (sum(((x == y) for (x, y) in zip(labels, trainlabels[N_TRAIN:]))) / float(len(trainlabels[N_TRAIN:])))
| [
"def",
"classification_rate",
"(",
"features",
")",
":",
"labels",
"=",
"_knn",
".",
"predict",
"(",
"trainset",
"[",
"N_TRAIN",
":",
"]",
",",
"features",
")",
"return",
"(",
"sum",
"(",
"(",
"(",
"x",
"==",
"y",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"labels",
",",
"trainlabels",
"[",
"N_TRAIN",
":",
"]",
")",
")",
")",
"/",
"float",
"(",
"len",
"(",
"trainlabels",
"[",
"N_TRAIN",
":",
"]",
")",
")",
")"
] | returns the classification rate of the default knn . | train | false |
39,555 | def stack_pages(pages, memmap=False, tempdir=None, *args, **kwargs):
if (len(pages) == 0):
raise ValueError('no pages')
if (len(pages) == 1):
return pages[0].asarray(memmap=memmap, *args, **kwargs)
data0 = pages[0].asarray(*args, **kwargs)
shape = ((len(pages),) + data0.shape)
if memmap:
with tempfile.NamedTemporaryFile(dir=tempdir) as fh:
data = numpy.memmap(fh, dtype=data0.dtype, shape=shape)
else:
data = numpy.empty(shape, dtype=data0.dtype)
data[0] = data0
if memmap:
data.flush()
del data0
for (i, page) in enumerate(pages[1:]):
data[(i + 1)] = page.asarray(*args, **kwargs)
if memmap:
data.flush()
return data
| [
"def",
"stack_pages",
"(",
"pages",
",",
"memmap",
"=",
"False",
",",
"tempdir",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"len",
"(",
"pages",
")",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'no pages'",
")",
"if",
"(",
"len",
"(",
"pages",
")",
"==",
"1",
")",
":",
"return",
"pages",
"[",
"0",
"]",
".",
"asarray",
"(",
"memmap",
"=",
"memmap",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"data0",
"=",
"pages",
"[",
"0",
"]",
".",
"asarray",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"shape",
"=",
"(",
"(",
"len",
"(",
"pages",
")",
",",
")",
"+",
"data0",
".",
"shape",
")",
"if",
"memmap",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"tempdir",
")",
"as",
"fh",
":",
"data",
"=",
"numpy",
".",
"memmap",
"(",
"fh",
",",
"dtype",
"=",
"data0",
".",
"dtype",
",",
"shape",
"=",
"shape",
")",
"else",
":",
"data",
"=",
"numpy",
".",
"empty",
"(",
"shape",
",",
"dtype",
"=",
"data0",
".",
"dtype",
")",
"data",
"[",
"0",
"]",
"=",
"data0",
"if",
"memmap",
":",
"data",
".",
"flush",
"(",
")",
"del",
"data0",
"for",
"(",
"i",
",",
"page",
")",
"in",
"enumerate",
"(",
"pages",
"[",
"1",
":",
"]",
")",
":",
"data",
"[",
"(",
"i",
"+",
"1",
")",
"]",
"=",
"page",
".",
"asarray",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"if",
"memmap",
":",
"data",
".",
"flush",
"(",
")",
"return",
"data"
] | read data from sequence of tiffpage and stack them vertically . | train | false |
39,557 | def assert_attr_equal(attr, left, right, obj='Attributes'):
left_attr = getattr(left, attr)
right_attr = getattr(right, attr)
if (left_attr is right_attr):
return True
elif (is_number(left_attr) and np.isnan(left_attr) and is_number(right_attr) and np.isnan(right_attr)):
return True
try:
result = (left_attr == right_attr)
except TypeError:
result = False
if (not isinstance(result, bool)):
result = result.all()
if result:
return True
else:
raise_assert_detail(obj, 'Attribute "{0}" are different'.format(attr), left_attr, right_attr)
| [
"def",
"assert_attr_equal",
"(",
"attr",
",",
"left",
",",
"right",
",",
"obj",
"=",
"'Attributes'",
")",
":",
"left_attr",
"=",
"getattr",
"(",
"left",
",",
"attr",
")",
"right_attr",
"=",
"getattr",
"(",
"right",
",",
"attr",
")",
"if",
"(",
"left_attr",
"is",
"right_attr",
")",
":",
"return",
"True",
"elif",
"(",
"is_number",
"(",
"left_attr",
")",
"and",
"np",
".",
"isnan",
"(",
"left_attr",
")",
"and",
"is_number",
"(",
"right_attr",
")",
"and",
"np",
".",
"isnan",
"(",
"right_attr",
")",
")",
":",
"return",
"True",
"try",
":",
"result",
"=",
"(",
"left_attr",
"==",
"right_attr",
")",
"except",
"TypeError",
":",
"result",
"=",
"False",
"if",
"(",
"not",
"isinstance",
"(",
"result",
",",
"bool",
")",
")",
":",
"result",
"=",
"result",
".",
"all",
"(",
")",
"if",
"result",
":",
"return",
"True",
"else",
":",
"raise_assert_detail",
"(",
"obj",
",",
"'Attribute \"{0}\" are different'",
".",
"format",
"(",
"attr",
")",
",",
"left_attr",
",",
"right_attr",
")"
] | checks attributes are equal . | train | false |
39,558 | def getfqdn(name=''):
name = name.strip()
if ((not name) or (name == '0.0.0.0')):
name = gethostname()
try:
(hostname, aliases, ipaddrs) = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if ('.' in name):
break
else:
name = hostname
return name
| [
"def",
"getfqdn",
"(",
"name",
"=",
"''",
")",
":",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"if",
"(",
"(",
"not",
"name",
")",
"or",
"(",
"name",
"==",
"'0.0.0.0'",
")",
")",
":",
"name",
"=",
"gethostname",
"(",
")",
"try",
":",
"(",
"hostname",
",",
"aliases",
",",
"ipaddrs",
")",
"=",
"gethostbyaddr",
"(",
"name",
")",
"except",
"error",
":",
"pass",
"else",
":",
"aliases",
".",
"insert",
"(",
"0",
",",
"hostname",
")",
"for",
"name",
"in",
"aliases",
":",
"if",
"(",
"'.'",
"in",
"name",
")",
":",
"break",
"else",
":",
"name",
"=",
"hostname",
"return",
"name"
] | get fully qualified domain name from name . | train | true |
39,559 | def repo_exists(module, repodata, overwrite_multiple):
existing_repos = _parse_repos(module)
repos = []
for kw in ['alias', 'url']:
name = repodata[kw]
for oldr in existing_repos:
if ((repodata[kw] == oldr[kw]) and (oldr not in repos)):
repos.append(oldr)
if (len(repos) == 0):
return (False, False, None)
elif (len(repos) == 1):
has_changes = _repo_changes(repos[0], repodata)
return (True, has_changes, repos)
elif (len(repos) >= 2):
if overwrite_multiple:
return (True, True, repos)
else:
errmsg = ('More than one repo matched "%s": "%s".' % (name, repos))
errmsg += ' Use overwrite_multiple to allow more than one repo to be overwritten'
module.fail_json(msg=errmsg)
| [
"def",
"repo_exists",
"(",
"module",
",",
"repodata",
",",
"overwrite_multiple",
")",
":",
"existing_repos",
"=",
"_parse_repos",
"(",
"module",
")",
"repos",
"=",
"[",
"]",
"for",
"kw",
"in",
"[",
"'alias'",
",",
"'url'",
"]",
":",
"name",
"=",
"repodata",
"[",
"kw",
"]",
"for",
"oldr",
"in",
"existing_repos",
":",
"if",
"(",
"(",
"repodata",
"[",
"kw",
"]",
"==",
"oldr",
"[",
"kw",
"]",
")",
"and",
"(",
"oldr",
"not",
"in",
"repos",
")",
")",
":",
"repos",
".",
"append",
"(",
"oldr",
")",
"if",
"(",
"len",
"(",
"repos",
")",
"==",
"0",
")",
":",
"return",
"(",
"False",
",",
"False",
",",
"None",
")",
"elif",
"(",
"len",
"(",
"repos",
")",
"==",
"1",
")",
":",
"has_changes",
"=",
"_repo_changes",
"(",
"repos",
"[",
"0",
"]",
",",
"repodata",
")",
"return",
"(",
"True",
",",
"has_changes",
",",
"repos",
")",
"elif",
"(",
"len",
"(",
"repos",
")",
">=",
"2",
")",
":",
"if",
"overwrite_multiple",
":",
"return",
"(",
"True",
",",
"True",
",",
"repos",
")",
"else",
":",
"errmsg",
"=",
"(",
"'More than one repo matched \"%s\": \"%s\".'",
"%",
"(",
"name",
",",
"repos",
")",
")",
"errmsg",
"+=",
"' Use overwrite_multiple to allow more than one repo to be overwritten'",
"module",
".",
"fail_json",
"(",
"msg",
"=",
"errmsg",
")"
] | check whether the repository already exists . | train | false |
39,560 | def cnv_family(attribute, arg, element):
if (str(arg) not in ('text', 'paragraph', 'section', 'ruby', 'table', 'table-column', 'table-row', 'table-cell', 'graphic', 'presentation', 'drawing-page', 'chart')):
raise ValueError(("'%s' not allowed" % str(arg)))
return str(arg)
| [
"def",
"cnv_family",
"(",
"attribute",
",",
"arg",
",",
"element",
")",
":",
"if",
"(",
"str",
"(",
"arg",
")",
"not",
"in",
"(",
"'text'",
",",
"'paragraph'",
",",
"'section'",
",",
"'ruby'",
",",
"'table'",
",",
"'table-column'",
",",
"'table-row'",
",",
"'table-cell'",
",",
"'graphic'",
",",
"'presentation'",
",",
"'drawing-page'",
",",
"'chart'",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"'%s' not allowed\"",
"%",
"str",
"(",
"arg",
")",
")",
")",
"return",
"str",
"(",
"arg",
")"
] | a style family . | train | false |
39,562 | def necklaces(n, k, free=False):
return uniq((minlex(i, directed=(not free)) for i in variations(list(range(k)), n, repetition=True)))
| [
"def",
"necklaces",
"(",
"n",
",",
"k",
",",
"free",
"=",
"False",
")",
":",
"return",
"uniq",
"(",
"(",
"minlex",
"(",
"i",
",",
"directed",
"=",
"(",
"not",
"free",
")",
")",
"for",
"i",
"in",
"variations",
"(",
"list",
"(",
"range",
"(",
"k",
")",
")",
",",
"n",
",",
"repetition",
"=",
"True",
")",
")",
")"
] | a routine to generate necklaces that may or may not be turned over to be viewed . | train | false |
39,564 | def get_all_types(context, inactive=0, filters=None, marker=None, limit=None, sort_keys=None, sort_dirs=None, offset=None, list_result=False):
vol_types = db.volume_type_get_all(context, inactive, filters=filters, marker=marker, limit=limit, sort_keys=sort_keys, sort_dirs=sort_dirs, offset=offset, list_result=list_result)
return vol_types
| [
"def",
"get_all_types",
"(",
"context",
",",
"inactive",
"=",
"0",
",",
"filters",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"sort_keys",
"=",
"None",
",",
"sort_dirs",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"list_result",
"=",
"False",
")",
":",
"vol_types",
"=",
"db",
".",
"volume_type_get_all",
"(",
"context",
",",
"inactive",
",",
"filters",
"=",
"filters",
",",
"marker",
"=",
"marker",
",",
"limit",
"=",
"limit",
",",
"sort_keys",
"=",
"sort_keys",
",",
"sort_dirs",
"=",
"sort_dirs",
",",
"offset",
"=",
"offset",
",",
"list_result",
"=",
"list_result",
")",
"return",
"vol_types"
] | get all non-deleted volume_types . | train | false |
39,567 | def prep_service_parms(args):
serv = [os.path.normpath(os.path.abspath(sys.argv[0]))]
for arg in args:
serv.append(arg[0])
if arg[1]:
serv.append(arg[1])
serv.append('-d')
return serv
| [
"def",
"prep_service_parms",
"(",
"args",
")",
":",
"serv",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"]",
"for",
"arg",
"in",
"args",
":",
"serv",
".",
"append",
"(",
"arg",
"[",
"0",
"]",
")",
"if",
"arg",
"[",
"1",
"]",
":",
"serv",
".",
"append",
"(",
"arg",
"[",
"1",
"]",
")",
"serv",
".",
"append",
"(",
"'-d'",
")",
"return",
"serv"
] | prepare parameter list for service . | train | false |
39,571 | def get_cache():
return requests.Session().cache
| [
"def",
"get_cache",
"(",
")",
":",
"return",
"requests",
".",
"Session",
"(",
")",
".",
"cache"
] | attempt to get the cache object and update till it works . | train | false |
39,572 | def split_pem(s):
pem_strings = []
while (s != ''):
start_idx = s.find('-----BEGIN')
if (start_idx == (-1)):
break
end_idx = s.find('-----END')
end_idx = (s.find('\n', end_idx) + 1)
pem_strings.append(s[start_idx:end_idx])
s = s[end_idx:]
return pem_strings
| [
"def",
"split_pem",
"(",
"s",
")",
":",
"pem_strings",
"=",
"[",
"]",
"while",
"(",
"s",
"!=",
"''",
")",
":",
"start_idx",
"=",
"s",
".",
"find",
"(",
"'-----BEGIN'",
")",
"if",
"(",
"start_idx",
"==",
"(",
"-",
"1",
")",
")",
":",
"break",
"end_idx",
"=",
"s",
".",
"find",
"(",
"'-----END'",
")",
"end_idx",
"=",
"(",
"s",
".",
"find",
"(",
"'\\n'",
",",
"end_idx",
")",
"+",
"1",
")",
"pem_strings",
".",
"append",
"(",
"s",
"[",
"start_idx",
":",
"end_idx",
"]",
")",
"s",
"=",
"s",
"[",
"end_idx",
":",
"]",
"return",
"pem_strings"
] | split pem objects . | train | false |
39,573 | def upload_prev(ver, doc_root='./', user='pandas'):
local_dir = (doc_root + 'build/html')
remote_dir = ('/usr/share/nginx/pandas/pandas-docs/version/%s/' % ver)
cmd = 'cd %s; rsync -avz . %s@pandas.pydata.org:%s -essh'
cmd = (cmd % (local_dir, user, remote_dir))
print(cmd)
if os.system(cmd):
raise SystemExit(('Upload to %s from %s failed' % (remote_dir, local_dir)))
local_dir = (doc_root + 'build/latex')
pdf_cmd = 'cd %s; scp pandas.pdf %s@pandas.pydata.org:%s'
pdf_cmd = (pdf_cmd % (local_dir, user, remote_dir))
if os.system(pdf_cmd):
raise SystemExit(('Upload PDF to %s from %s failed' % (ver, doc_root)))
| [
"def",
"upload_prev",
"(",
"ver",
",",
"doc_root",
"=",
"'./'",
",",
"user",
"=",
"'pandas'",
")",
":",
"local_dir",
"=",
"(",
"doc_root",
"+",
"'build/html'",
")",
"remote_dir",
"=",
"(",
"'/usr/share/nginx/pandas/pandas-docs/version/%s/'",
"%",
"ver",
")",
"cmd",
"=",
"'cd %s; rsync -avz . %s@pandas.pydata.org:%s -essh'",
"cmd",
"=",
"(",
"cmd",
"%",
"(",
"local_dir",
",",
"user",
",",
"remote_dir",
")",
")",
"print",
"(",
"cmd",
")",
"if",
"os",
".",
"system",
"(",
"cmd",
")",
":",
"raise",
"SystemExit",
"(",
"(",
"'Upload to %s from %s failed'",
"%",
"(",
"remote_dir",
",",
"local_dir",
")",
")",
")",
"local_dir",
"=",
"(",
"doc_root",
"+",
"'build/latex'",
")",
"pdf_cmd",
"=",
"'cd %s; scp pandas.pdf %s@pandas.pydata.org:%s'",
"pdf_cmd",
"=",
"(",
"pdf_cmd",
"%",
"(",
"local_dir",
",",
"user",
",",
"remote_dir",
")",
")",
"if",
"os",
".",
"system",
"(",
"pdf_cmd",
")",
":",
"raise",
"SystemExit",
"(",
"(",
"'Upload PDF to %s from %s failed'",
"%",
"(",
"ver",
",",
"doc_root",
")",
")",
")"
] | push a copy of older release to appropriate version directory . | train | true |
39,574 | def track_index_changed(item, track_info):
return (item.track not in (track_info.medium_index, track_info.index))
| [
"def",
"track_index_changed",
"(",
"item",
",",
"track_info",
")",
":",
"return",
"(",
"item",
".",
"track",
"not",
"in",
"(",
"track_info",
".",
"medium_index",
",",
"track_info",
".",
"index",
")",
")"
] | returns true if the item and track info index is different . | train | false |
39,577 | def _handle_change_selection(event, params):
radio = params['fig_selection'].radio
ydata = event.ydata
labels = [label._text for label in radio.labels]
offset = 0
for (idx, label) in enumerate(labels):
nchans = len(params['selections'][label])
offset += nchans
if (ydata < offset):
_set_radio_button(idx, params)
return
| [
"def",
"_handle_change_selection",
"(",
"event",
",",
"params",
")",
":",
"radio",
"=",
"params",
"[",
"'fig_selection'",
"]",
".",
"radio",
"ydata",
"=",
"event",
".",
"ydata",
"labels",
"=",
"[",
"label",
".",
"_text",
"for",
"label",
"in",
"radio",
".",
"labels",
"]",
"offset",
"=",
"0",
"for",
"(",
"idx",
",",
"label",
")",
"in",
"enumerate",
"(",
"labels",
")",
":",
"nchans",
"=",
"len",
"(",
"params",
"[",
"'selections'",
"]",
"[",
"label",
"]",
")",
"offset",
"+=",
"nchans",
"if",
"(",
"ydata",
"<",
"offset",
")",
":",
"_set_radio_button",
"(",
"idx",
",",
"params",
")",
"return"
] | helper for handling clicks on vertical scrollbar using selections . | train | false |
39,579 | def _add_junction(item):
(type_, channels) = _expand_one_key_dictionary(item)
junction = UnnamedStatement(type='junction')
for item in channels:
(type_, value) = _expand_one_key_dictionary(item)
channel = UnnamedStatement(type='channel')
for val in value:
if _is_reference(val):
_add_reference(val, channel)
elif _is_inline_definition(val):
_add_inline_definition(val, channel)
junction.add_child(channel)
_current_statement.add_child(junction)
| [
"def",
"_add_junction",
"(",
"item",
")",
":",
"(",
"type_",
",",
"channels",
")",
"=",
"_expand_one_key_dictionary",
"(",
"item",
")",
"junction",
"=",
"UnnamedStatement",
"(",
"type",
"=",
"'junction'",
")",
"for",
"item",
"in",
"channels",
":",
"(",
"type_",
",",
"value",
")",
"=",
"_expand_one_key_dictionary",
"(",
"item",
")",
"channel",
"=",
"UnnamedStatement",
"(",
"type",
"=",
"'channel'",
")",
"for",
"val",
"in",
"value",
":",
"if",
"_is_reference",
"(",
"val",
")",
":",
"_add_reference",
"(",
"val",
",",
"channel",
")",
"elif",
"_is_inline_definition",
"(",
"val",
")",
":",
"_add_inline_definition",
"(",
"val",
",",
"channel",
")",
"junction",
".",
"add_child",
"(",
"channel",
")",
"_current_statement",
".",
"add_child",
"(",
"junction",
")"
] | adds a junction to the _current_statement . | train | true |
39,580 | def _process_item(v):
rpc_type = None
if isinstance(v, Column):
if isinstance(v.type, sqlalchemy.Enum):
if v.type.convert_unicode:
rpc_type = primitive.Unicode(values=v.type.enums)
else:
rpc_type = primitive.String(values=v.type.enums)
elif (v.type in _type_map):
rpc_type = _type_map[v.type]
elif (type(v.type) in _type_map):
rpc_type = _type_map[type(v.type)]
else:
raise Exception(('soap_type was not found. maybe _type_map needs a new entry. %r' % v))
elif isinstance(v, RelationshipProperty):
v.enable_typechecks = False
rpc_type = Array(v.argument)
return rpc_type
| [
"def",
"_process_item",
"(",
"v",
")",
":",
"rpc_type",
"=",
"None",
"if",
"isinstance",
"(",
"v",
",",
"Column",
")",
":",
"if",
"isinstance",
"(",
"v",
".",
"type",
",",
"sqlalchemy",
".",
"Enum",
")",
":",
"if",
"v",
".",
"type",
".",
"convert_unicode",
":",
"rpc_type",
"=",
"primitive",
".",
"Unicode",
"(",
"values",
"=",
"v",
".",
"type",
".",
"enums",
")",
"else",
":",
"rpc_type",
"=",
"primitive",
".",
"String",
"(",
"values",
"=",
"v",
".",
"type",
".",
"enums",
")",
"elif",
"(",
"v",
".",
"type",
"in",
"_type_map",
")",
":",
"rpc_type",
"=",
"_type_map",
"[",
"v",
".",
"type",
"]",
"elif",
"(",
"type",
"(",
"v",
".",
"type",
")",
"in",
"_type_map",
")",
":",
"rpc_type",
"=",
"_type_map",
"[",
"type",
"(",
"v",
".",
"type",
")",
"]",
"else",
":",
"raise",
"Exception",
"(",
"(",
"'soap_type was not found. maybe _type_map needs a new entry. %r'",
"%",
"v",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"RelationshipProperty",
")",
":",
"v",
".",
"enable_typechecks",
"=",
"False",
"rpc_type",
"=",
"Array",
"(",
"v",
".",
"argument",
")",
"return",
"rpc_type"
] | this function maps sqlalchemy types to spyne types . | train | false |
39,581 | def tag_show(context, data_dict):
model = context['model']
id = _get_or_bust(data_dict, 'id')
include_datasets = asbool(data_dict.get('include_datasets', False))
tag = model.Tag.get(id, vocab_id_or_name=data_dict.get('vocabulary_id'))
context['tag'] = tag
if (tag is None):
raise NotFound
_check_access('tag_show', context, data_dict)
return model_dictize.tag_dictize(tag, context, include_datasets=include_datasets)
| [
"def",
"tag_show",
"(",
"context",
",",
"data_dict",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"id",
"=",
"_get_or_bust",
"(",
"data_dict",
",",
"'id'",
")",
"include_datasets",
"=",
"asbool",
"(",
"data_dict",
".",
"get",
"(",
"'include_datasets'",
",",
"False",
")",
")",
"tag",
"=",
"model",
".",
"Tag",
".",
"get",
"(",
"id",
",",
"vocab_id_or_name",
"=",
"data_dict",
".",
"get",
"(",
"'vocabulary_id'",
")",
")",
"context",
"[",
"'tag'",
"]",
"=",
"tag",
"if",
"(",
"tag",
"is",
"None",
")",
":",
"raise",
"NotFound",
"_check_access",
"(",
"'tag_show'",
",",
"context",
",",
"data_dict",
")",
"return",
"model_dictize",
".",
"tag_dictize",
"(",
"tag",
",",
"context",
",",
"include_datasets",
"=",
"include_datasets",
")"
] | return the details of a tag and all its datasets . | train | false |
39,584 | def unlink_cohort_partition_group(cohort):
CourseUserGroupPartitionGroup.objects.filter(course_user_group=cohort).delete()
| [
"def",
"unlink_cohort_partition_group",
"(",
"cohort",
")",
":",
"CourseUserGroupPartitionGroup",
".",
"objects",
".",
"filter",
"(",
"course_user_group",
"=",
"cohort",
")",
".",
"delete",
"(",
")"
] | remove any existing cohort to partition_id/group_id link . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.