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 |
|---|---|---|---|---|---|
32,829 | def backup_apps(storage, bucket):
full_bucket_name = ''
if (storage == StorageTypes.GCS):
full_bucket_name = 'gs://{0}'.format(bucket)
return BR.app_backup(storage, full_bucket_name=full_bucket_name)
| [
"def",
"backup_apps",
"(",
"storage",
",",
"bucket",
")",
":",
"full_bucket_name",
"=",
"''",
"if",
"(",
"storage",
"==",
"StorageTypes",
".",
"GCS",
")",
":",
"full_bucket_name",
"=",
"'gs://{0}'",
".",
"format",
"(",
"bucket",
")",
"return",
"BR",
".",
... | triggers a backup of the source code of deployed apps . | train | false |
32,831 | def getCentersFromLoop(loop, radius):
circleNodes = getCircleNodesFromLoop(loop, radius)
return getCentersFromCircleNodes(circleNodes, radius)
| [
"def",
"getCentersFromLoop",
"(",
"loop",
",",
"radius",
")",
":",
"circleNodes",
"=",
"getCircleNodesFromLoop",
"(",
"loop",
",",
"radius",
")",
"return",
"getCentersFromCircleNodes",
"(",
"circleNodes",
",",
"radius",
")"
] | get the centers of the loop . | train | false |
32,832 | def _ensure_directory(path):
dirname = os.path.dirname(path)
if (not os.path.isdir(dirname)):
os.makedirs(dirname)
| [
"def",
"_ensure_directory",
"(",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")"
] | ensure that the parent directory of path exists . | train | true |
32,834 | def BuildCloudMetadataRequests():
amazon_collection_map = {'/'.join((AMAZON_URL_BASE, 'instance-id')): 'instance_id', '/'.join((AMAZON_URL_BASE, 'ami-id')): 'ami_id', '/'.join((AMAZON_URL_BASE, 'hostname')): 'hostname', '/'.join((AMAZON_URL_BASE, 'public-hostname')): 'public_hostname', '/'.join((AMAZON_URL_BASE, 'instance-type')): 'instance_type'}
google_collection_map = {'/'.join((GOOGLE_URL_BASE, 'instance/id')): 'instance_id', '/'.join((GOOGLE_URL_BASE, 'instance/zone')): 'zone', '/'.join((GOOGLE_URL_BASE, 'project/project-id')): 'project_id', '/'.join((GOOGLE_URL_BASE, 'instance/hostname')): 'hostname', '/'.join((GOOGLE_URL_BASE, 'instance/machine-type')): 'machine_type'}
return CloudMetadataRequests(requests=_MakeArgs(amazon_collection_map, google_collection_map))
| [
"def",
"BuildCloudMetadataRequests",
"(",
")",
":",
"amazon_collection_map",
"=",
"{",
"'/'",
".",
"join",
"(",
"(",
"AMAZON_URL_BASE",
",",
"'instance-id'",
")",
")",
":",
"'instance_id'",
",",
"'/'",
".",
"join",
"(",
"(",
"AMAZON_URL_BASE",
",",
"'ami-id'",... | build the standard set of cloud metadata to collect during interrogate . | train | true |
32,836 | def exclude_entry(enabled, filter_type, language_list, language):
exclude = True
if enabled:
if (filter_type == 'blacklist'):
exclude = False
if (language is not None):
for item in language_list:
if (language == item.lower()):
exclude = True
break
elif (filter_type == 'whitelist'):
if (language is not None):
for item in language_list:
if (language == item.lower()):
exclude = False
break
return exclude
| [
"def",
"exclude_entry",
"(",
"enabled",
",",
"filter_type",
",",
"language_list",
",",
"language",
")",
":",
"exclude",
"=",
"True",
"if",
"enabled",
":",
"if",
"(",
"filter_type",
"==",
"'blacklist'",
")",
":",
"exclude",
"=",
"False",
"if",
"(",
"languag... | exclude bracket wrapping entry by filter . | train | false |
32,837 | def has_handshake_aircrack(target, capfile):
if (not program_exists('aircrack-ng')):
return False
crack = ((('echo "" | aircrack-ng -a 2 -w - -b ' + target.bssid) + ' ') + capfile)
proc_crack = Popen(crack, stdout=PIPE, stderr=DN, shell=True)
proc_crack.wait()
txt = proc_crack.communicate()[0]
return (txt.find('Passphrase not in dictionary') != (-1))
| [
"def",
"has_handshake_aircrack",
"(",
"target",
",",
"capfile",
")",
":",
"if",
"(",
"not",
"program_exists",
"(",
"'aircrack-ng'",
")",
")",
":",
"return",
"False",
"crack",
"=",
"(",
"(",
"(",
"'echo \"\" | aircrack-ng -a 2 -w - -b '",
"+",
"target",
".",
"b... | uses aircrack-ng to check for handshake . | train | false |
32,839 | def is_self(conn, target):
if re.search('(^..?.?.?self|{})'.format(re.escape(conn.nick)), target, re.I):
return True
else:
return False
| [
"def",
"is_self",
"(",
"conn",
",",
"target",
")",
":",
"if",
"re",
".",
"search",
"(",
"'(^..?.?.?self|{})'",
".",
"format",
"(",
"re",
".",
"escape",
"(",
"conn",
".",
"nick",
")",
")",
",",
"target",
",",
"re",
".",
"I",
")",
":",
"return",
"T... | checks if a string is "****self" or contains conn . | train | false |
32,840 | @cache_permission
def can_remove_translation(user, project):
return check_permission(user, project, 'trans.delete_translation')
| [
"@",
"cache_permission",
"def",
"can_remove_translation",
"(",
"user",
",",
"project",
")",
":",
"return",
"check_permission",
"(",
"user",
",",
"project",
",",
"'trans.delete_translation'",
")"
] | checks whether user can view reports on given project . | train | false |
32,841 | def _fraction_decomp(expr):
if (not isinstance(expr, Mul)):
return (expr, 1)
num = []
den = []
for a in expr.args:
if (a.is_Pow and (a.args[1] < 0)):
den.append((1 / a))
else:
num.append(a)
if (not den):
return (expr, 1)
num = Mul(*num)
den = Mul(*den)
return (num, den)
| [
"def",
"_fraction_decomp",
"(",
"expr",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"expr",
",",
"Mul",
")",
")",
":",
"return",
"(",
"expr",
",",
"1",
")",
"num",
"=",
"[",
"]",
"den",
"=",
"[",
"]",
"for",
"a",
"in",
"expr",
".",
"args",
... | return num . | train | false |
32,843 | def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None):
if isinstance(identifier, six.string_types):
res = None
if (identifier in _GLOBAL_CUSTOM_OBJECTS):
res = _GLOBAL_CUSTOM_OBJECTS[identifier]
if (not res):
res = module_params.get(identifier)
if (not res):
raise ValueError(((('Invalid ' + str(module_name)) + ': ') + str(identifier)))
if (instantiate and (not kwargs)):
return res()
elif (instantiate and kwargs):
return res(**kwargs)
else:
return res
elif isinstance(identifier, dict):
name = identifier.pop('name')
res = None
if (name in _GLOBAL_CUSTOM_OBJECTS):
res = _GLOBAL_CUSTOM_OBJECTS[name]
if (not res):
res = module_params.get(name)
if res:
return res(**identifier)
else:
raise ValueError(((('Invalid ' + str(module_name)) + ': ') + str(identifier)))
return identifier
| [
"def",
"get_from_module",
"(",
"identifier",
",",
"module_params",
",",
"module_name",
",",
"instantiate",
"=",
"False",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"identifier",
",",
"six",
".",
"string_types",
")",
":",
"res",
"=",
"No... | retrieves a class or function member of a module . | train | true |
32,844 | def erf(x):
return (1.0 - erfc(x))
| [
"def",
"erf",
"(",
"x",
")",
":",
"return",
"(",
"1.0",
"-",
"erfc",
"(",
"x",
")",
")"
] | returns the error function at x . | train | false |
32,845 | def _get_sub_dirs(parent):
return [child for child in os.listdir(parent) if os.path.isdir(os.path.join(parent, child))]
| [
"def",
"_get_sub_dirs",
"(",
"parent",
")",
":",
"return",
"[",
"child",
"for",
"child",
"in",
"os",
".",
"listdir",
"(",
"parent",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"parent",
",",
"child",
")",
... | returns a list of the child directories of the given parent directory . | train | true |
32,846 | @register.tag
def get_permission_request(parser, token):
return PermissionForObjectNode.handle_token(parser, token, approved=False, name='"permission_request"')
| [
"@",
"register",
".",
"tag",
"def",
"get_permission_request",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PermissionForObjectNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"approved",
"=",
"False",
",",
"name",
"=",
"'\"permission_request\"'... | performs a permission request check with the given signature . | train | true |
32,847 | @cronjobs.register
def update_collections_votes():
up = CollectionVote.objects.values('collection_id').annotate(count=Count('collection')).filter(vote=1).extra(where=['DATE(created)=%s'], params=[date.today()])
down = CollectionVote.objects.values('collection_id').annotate(count=Count('collection')).filter(vote=(-1)).extra(where=['DATE(created)=%s'], params=[date.today()])
ts = [_update_collections_votes.subtask(args=[chunk, 'new_votes_up']) for chunk in chunked(up, 1000)]
TaskSet(ts).apply_async()
ts = [_update_collections_votes.subtask(args=[chunk, 'new_votes_down']) for chunk in chunked(down, 1000)]
TaskSet(ts).apply_async()
| [
"@",
"cronjobs",
".",
"register",
"def",
"update_collections_votes",
"(",
")",
":",
"up",
"=",
"CollectionVote",
".",
"objects",
".",
"values",
"(",
"'collection_id'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'collection'",
")",
")",
".",
"f... | update collections votes . | train | false |
32,848 | def _extract_doc_comment_standard(content, line, column, markers):
pos = content[line].find(markers[2], column)
if (pos != (-1)):
return (line, (pos + len(markers[2])), content[line][column:pos])
doc_comment = content[line][column:]
line += 1
while (line < len(content)):
pos = content[line].find(markers[2])
each_line_pos = content[line].find(markers[1])
if (pos == (-1)):
if (each_line_pos == (-1)):
return None
doc_comment += content[line][(each_line_pos + len(markers[1])):]
else:
if ((each_line_pos != (-1)) and ((each_line_pos + 1) < pos)):
doc_comment += content[line][(each_line_pos + len(markers[1])):pos]
return (line, (pos + len(markers[2])), doc_comment)
line += 1
return None
| [
"def",
"_extract_doc_comment_standard",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")",
":",
"pos",
"=",
"content",
"[",
"line",
"]",
".",
"find",
"(",
"markers",
"[",
"2",
"]",
",",
"column",
")",
"if",
"(",
"pos",
"!=",
"(",
"-",
... | extract a documentation that starts at given beginning with standard layout . | train | false |
32,849 | def w(message):
print_log(message, YELLOW)
| [
"def",
"w",
"(",
"message",
")",
":",
"print_log",
"(",
"message",
",",
"YELLOW",
")"
] | return a list of logged in users for this minion . | train | false |
32,850 | @register.tag
@blocktag(end_prefix=u'end_')
def for_review_request_fieldset(context, nodelist, review_request_details):
s = []
is_first = True
review_request = review_request_details.get_review_request()
user = context[u'request'].user
fieldset_classes = get_review_request_fieldsets(include_main=False)
for fieldset_cls in fieldset_classes:
try:
if (not fieldset_cls.is_empty()):
try:
fieldset = fieldset_cls(review_request_details)
except Exception as e:
logging.error(u'Error instantiating ReviewRequestFieldset %r: %s', fieldset_cls, e, exc_info=1)
context.push()
context.update({u'fieldset': fieldset, u'show_fieldset_required': (fieldset.show_required and (review_request.status == ReviewRequest.PENDING_REVIEW) and review_request.is_mutable_by(user)), u'forloop': {u'first': is_first}})
s.append(nodelist.render(context))
context.pop()
is_first = False
except Exception as e:
logging.error(u'Error running is_empty for ReviewRequestFieldset %r: %s', fieldset_cls, e, exc_info=1)
return u''.join(s)
| [
"@",
"register",
".",
"tag",
"@",
"blocktag",
"(",
"end_prefix",
"=",
"u'end_'",
")",
"def",
"for_review_request_fieldset",
"(",
"context",
",",
"nodelist",
",",
"review_request_details",
")",
":",
"s",
"=",
"[",
"]",
"is_first",
"=",
"True",
"review_request",... | loops through all fieldsets . | train | false |
32,852 | def accumulate(iterable, func=operator.add):
it = iter(iterable)
total = next(it)
(yield total)
for element in it:
total = func(total, element)
(yield total)
| [
"def",
"accumulate",
"(",
"iterable",
",",
"func",
"=",
"operator",
".",
"add",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"total",
"=",
"next",
"(",
"it",
")",
"(",
"yield",
"total",
")",
"for",
"element",
"in",
"it",
":",
"total",
"=",
... | return running totals . | train | true |
32,853 | def _parse_snapshots(data, filesystem):
result = []
for line in data.splitlines():
(dataset, snapshot) = line.split('@', 1)
if (dataset == filesystem.name):
result.append(snapshot)
return result
| [
"def",
"_parse_snapshots",
"(",
"data",
",",
"filesystem",
")",
":",
"result",
"=",
"[",
"]",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
":",
"(",
"dataset",
",",
"snapshot",
")",
"=",
"line",
".",
"split",
"(",
"'@'",
",",
"1",
")",... | parse the output of a zfs list command (like the one defined by _list_snapshots_command into a list of bytes . | train | false |
32,855 | def _load_config():
config = {}
if os.path.isfile('/usbkey/config'):
with salt.utils.fopen('/usbkey/config', 'r') as config_file:
for optval in config_file:
if (optval[0] == '#'):
continue
if ('=' not in optval):
continue
optval = optval.split('=')
config[optval[0].lower()] = optval[1].strip().strip('"')
log.debug('smartos.config - read /usbkey/config: {0}'.format(config))
return config
| [
"def",
"_load_config",
"(",
")",
":",
"config",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'/usbkey/config'",
")",
":",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"'/usbkey/config'",
",",
"'r'",
")",
"as",
"config_file",
":",
... | safely load a config file . | train | false |
32,857 | def libvlc_video_get_adjust_float(p_mi, option):
f = (_Cfunctions.get('libvlc_video_get_adjust_float', None) or _Cfunction('libvlc_video_get_adjust_float', ((1,), (1,)), None, ctypes.c_float, MediaPlayer, ctypes.c_uint))
return f(p_mi, option)
| [
"def",
"libvlc_video_get_adjust_float",
"(",
"p_mi",
",",
"option",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_video_get_adjust_float'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_video_get_adjust_float'",
",",
"(",
"(",
"1",
",",... | get float adjust option . | train | true |
32,858 | def send_deploy_event(module, key, revision_id, deployed_by='Ansible', deployed_to=None, repository=None):
deploy_api = 'https://event-gateway.stackdriver.com/v1/deployevent'
params = {}
params['revision_id'] = revision_id
params['deployed_by'] = deployed_by
if deployed_to:
params['deployed_to'] = deployed_to
if repository:
params['repository'] = repository
return do_send_request(module, deploy_api, params, key)
| [
"def",
"send_deploy_event",
"(",
"module",
",",
"key",
",",
"revision_id",
",",
"deployed_by",
"=",
"'Ansible'",
",",
"deployed_to",
"=",
"None",
",",
"repository",
"=",
"None",
")",
":",
"deploy_api",
"=",
"'https://event-gateway.stackdriver.com/v1/deployevent'",
"... | send a deploy event to stackdriver . | train | false |
32,859 | def prefix_encode_all(ls):
last = u('')
for w in ls:
i = first_diff(last, w)
(yield (chr(i) + w[i:].encode('utf8')))
last = w
| [
"def",
"prefix_encode_all",
"(",
"ls",
")",
":",
"last",
"=",
"u",
"(",
"''",
")",
"for",
"w",
"in",
"ls",
":",
"i",
"=",
"first_diff",
"(",
"last",
",",
"w",
")",
"(",
"yield",
"(",
"chr",
"(",
"i",
")",
"+",
"w",
"[",
"i",
":",
"]",
".",
... | compresses the given list of strings by storing each string as an integer representing the prefix it shares with its predecessor . | train | false |
32,860 | def test_instantiation_FileLinks():
fls = display.FileLinks('example')
| [
"def",
"test_instantiation_FileLinks",
"(",
")",
":",
"fls",
"=",
"display",
".",
"FileLinks",
"(",
"'example'",
")"
] | filelinks: test class can be instantiated . | train | false |
32,861 | def get_rdp_jarpath():
return getenv('RDP_JAR_PATH')
| [
"def",
"get_rdp_jarpath",
"(",
")",
":",
"return",
"getenv",
"(",
"'RDP_JAR_PATH'",
")"
] | return jar file name for rdp classifier . | train | false |
32,862 | def _get_explicit_graded(block):
field_value = getattr(block.transformer_data[GradesTransformer], GradesTransformer.EXPLICIT_GRADED_FIELD_NAME, None)
return (True if (field_value is None) else field_value)
| [
"def",
"_get_explicit_graded",
"(",
"block",
")",
":",
"field_value",
"=",
"getattr",
"(",
"block",
".",
"transformer_data",
"[",
"GradesTransformer",
"]",
",",
"GradesTransformer",
".",
"EXPLICIT_GRADED_FIELD_NAME",
",",
"None",
")",
"return",
"(",
"True",
"if",
... | returns the explicit graded field value for the given block . | train | false |
32,863 | def unpause_all():
global PAUSED_ALL
PAUSED_ALL = False
Downloader.do.resume()
logging.debug('PAUSED_ALL inactive')
| [
"def",
"unpause_all",
"(",
")",
":",
"global",
"PAUSED_ALL",
"PAUSED_ALL",
"=",
"False",
"Downloader",
".",
"do",
".",
"resume",
"(",
")",
"logging",
".",
"debug",
"(",
"'PAUSED_ALL inactive'",
")"
] | resume all activities . | train | false |
32,864 | def literal_destringizer(rep):
if isinstance(rep, (str, unicode)):
orig_rep = rep
if (rtp_fix_unicode is not None):
rep = rtp_fix_unicode(rep)
try:
return literal_eval(rep)
except SyntaxError:
raise ValueError(('%r is not a valid Python literal' % (orig_rep,)))
else:
raise ValueError(('%r is not a string' % (rep,)))
| [
"def",
"literal_destringizer",
"(",
"rep",
")",
":",
"if",
"isinstance",
"(",
"rep",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"orig_rep",
"=",
"rep",
"if",
"(",
"rtp_fix_unicode",
"is",
"not",
"None",
")",
":",
"rep",
"=",
"rtp_fix_unicode",
"("... | convert a python literal to the value it represents . | train | false |
32,865 | def sort_schedule_fn(*cmps):
dependence = make_dependence_cmp()
cmps = ((dependence,) + cmps)
def schedule(fgraph):
'\n Order nodes in a FunctionGraph.\n\n '
return sort_apply_nodes(fgraph.inputs, fgraph.outputs, cmps)
return schedule
| [
"def",
"sort_schedule_fn",
"(",
"*",
"cmps",
")",
":",
"dependence",
"=",
"make_dependence_cmp",
"(",
")",
"cmps",
"=",
"(",
"(",
"dependence",
",",
")",
"+",
"cmps",
")",
"def",
"schedule",
"(",
"fgraph",
")",
":",
"return",
"sort_apply_nodes",
"(",
"fg... | make a schedule function from comparators . | train | false |
32,866 | def trainSpeakerModelsScript():
mtWin = 2.0
mtStep = 2.0
stWin = 0.02
stStep = 0.02
dirName = 'DIARIZATION_ALL/all'
listOfDirs = [os.path.join(dirName, name) for name in os.listdir(dirName) if os.path.isdir(os.path.join(dirName, name))]
featureAndTrain(listOfDirs, mtWin, mtStep, stWin, stStep, 'knn', 'data/knnSpeakerAll', computeBEAT=False, perTrain=0.5)
dirName = 'DIARIZATION_ALL/female_male'
listOfDirs = [os.path.join(dirName, name) for name in os.listdir(dirName) if os.path.isdir(os.path.join(dirName, name))]
featureAndTrain(listOfDirs, mtWin, mtStep, stWin, stStep, 'knn', 'data/knnSpeakerFemaleMale', computeBEAT=False, perTrain=0.5)
| [
"def",
"trainSpeakerModelsScript",
"(",
")",
":",
"mtWin",
"=",
"2.0",
"mtStep",
"=",
"2.0",
"stWin",
"=",
"0.02",
"stStep",
"=",
"0.02",
"dirName",
"=",
"'DIARIZATION_ALL/all'",
"listOfDirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirName",
",",
... | this script is used to train the speaker-related models import audiotraintest as at at . | train | false |
32,867 | def __checkIsFinalizedName(filename):
if filename.split('/')[2].startswith(_CREATION_HANDLE_PREFIX):
raise InvalidFileNameError(('File %s should have finalized filename' % filename))
| [
"def",
"__checkIsFinalizedName",
"(",
"filename",
")",
":",
"if",
"filename",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
".",
"startswith",
"(",
"_CREATION_HANDLE_PREFIX",
")",
":",
"raise",
"InvalidFileNameError",
"(",
"(",
"'File %s should have finalized file... | check if a filename is finalized . | train | false |
32,868 | def prevprime(n):
from sympy.functions.elementary.integers import ceiling
n = int(ceiling(n))
if (n < 3):
raise ValueError('no preceding primes')
if (n < 8):
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
if (n <= sieve._list[(-1)]):
(l, u) = sieve.search(n)
if (l == u):
return sieve[(l - 1)]
else:
return sieve[l]
nn = (6 * (n // 6))
if ((n - nn) <= 1):
n = (nn - 1)
if isprime(n):
return n
n -= 4
else:
n = (nn + 1)
while 1:
if isprime(n):
return n
n -= 2
if isprime(n):
return n
n -= 4
| [
"def",
"prevprime",
"(",
"n",
")",
":",
"from",
"sympy",
".",
"functions",
".",
"elementary",
".",
"integers",
"import",
"ceiling",
"n",
"=",
"int",
"(",
"ceiling",
"(",
"n",
")",
")",
"if",
"(",
"n",
"<",
"3",
")",
":",
"raise",
"ValueError",
"(",... | return the largest prime smaller than n . | train | false |
32,869 | def array_complex_attr(context, builder, typ, value, attr):
if ((attr not in ['real', 'imag']) or (typ.dtype not in types.complex_domain)):
raise NotImplementedError('cannot get attribute `{}`'.format(attr))
arrayty = make_array(typ)
array = arrayty(context, builder, value)
flty = typ.dtype.underlying_float
sizeof_flty = context.get_abi_sizeof(context.get_data_type(flty))
itemsize = array.itemsize.type(sizeof_flty)
llfltptrty = context.get_value_type(flty).as_pointer()
dataptr = builder.bitcast(array.data, llfltptrty)
if (attr == 'imag'):
dataptr = builder.gep(dataptr, [ir.IntType(32)(1)])
resultty = typ.copy(dtype=flty, layout='A')
result = make_array(resultty)(context, builder)
repl = dict(data=dataptr, itemsize=itemsize)
cgutils.copy_struct(result, array, repl)
return impl_ret_borrowed(context, builder, resultty, result._getvalue())
| [
"def",
"array_complex_attr",
"(",
"context",
",",
"builder",
",",
"typ",
",",
"value",
",",
"attr",
")",
":",
"if",
"(",
"(",
"attr",
"not",
"in",
"[",
"'real'",
",",
"'imag'",
"]",
")",
"or",
"(",
"typ",
".",
"dtype",
"not",
"in",
"types",
".",
... | given a complex array . | train | false |
32,870 | def get_selection_for_new_device(selection, insert_left=False):
selected = selection.selected_object
if (isinstance(selected, Live.DrumPad.DrumPad) and selected.chains and selected.chains[0].devices):
index = (0 if insert_left else (-1))
selected = selected.chains[0].devices[index]
elif (not isinstance(selected, Live.Device.Device)):
selected = selection.selected_device
return selected
| [
"def",
"get_selection_for_new_device",
"(",
"selection",
",",
"insert_left",
"=",
"False",
")",
":",
"selected",
"=",
"selection",
".",
"selected_object",
"if",
"(",
"isinstance",
"(",
"selected",
",",
"Live",
".",
"DrumPad",
".",
"DrumPad",
")",
"and",
"selec... | returns a device . | train | false |
32,871 | def get_sidebar():
return _sidebar
| [
"def",
"get_sidebar",
"(",
")",
":",
"return",
"_sidebar"
] | returns plugin classes that should connect to the sidebar . | train | false |
32,873 | def notice_content(url):
try:
html = lxml.html.parse(url)
res = html.xpath('//div[@id="content"]/pre/text()')[0]
return res.strip()
except Exception as er:
print str(er)
| [
"def",
"notice_content",
"(",
"url",
")",
":",
"try",
":",
"html",
"=",
"lxml",
".",
"html",
".",
"parse",
"(",
"url",
")",
"res",
"=",
"html",
".",
"xpath",
"(",
"'//div[@id=\"content\"]/pre/text()'",
")",
"[",
"0",
"]",
"return",
"res",
".",
"strip",... | parameter url:内容链接 return string:信息内容 . | train | false |
32,874 | def IsInitializerList(clean_lines, linenum):
for i in xrange(linenum, 1, (-1)):
line = clean_lines.elided[i]
if (i == linenum):
remove_function_body = Match('^(.*)\\{\\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search('\\s:\\s*\\w+[({]', line):
return True
if Search('\\}\\s*,\\s*$', line):
return True
if Search('[{};]\\s*$', line):
return False
return False
| [
"def",
"IsInitializerList",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"1",
",",
"(",
"-",
"1",
")",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"if",
"(",
"i",
"==",
"li... | check if current line is inside constructor initializer list . | train | false |
32,876 | def _ppoly_eval_1(c, x, xps):
out = np.zeros((len(xps), c.shape[2]))
for (i, xp) in enumerate(xps):
if ((xp < 0) or (xp > 1)):
out[i, :] = np.nan
continue
j = (np.searchsorted(x, xp) - 1)
d = (xp - x[j])
assert_((x[j] <= xp < x[(j + 1)]))
r = sum(((c[(k, j)] * (d ** ((c.shape[0] - k) - 1))) for k in range(c.shape[0])))
out[i, :] = r
return out
| [
"def",
"_ppoly_eval_1",
"(",
"c",
",",
"x",
",",
"xps",
")",
":",
"out",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"xps",
")",
",",
"c",
".",
"shape",
"[",
"2",
"]",
")",
")",
"for",
"(",
"i",
",",
"xp",
")",
"in",
"enumerate",
"(",
... | evaluate piecewise polynomial manually . | train | false |
32,877 | def get_proxy_info(hostname, is_secure, proxy_host=None, proxy_port=0, proxy_auth=None, no_proxy=None):
if _is_no_proxy_host(hostname, no_proxy):
return (None, 0, None)
if proxy_host:
port = proxy_port
auth = proxy_auth
return (proxy_host, port, auth)
env_keys = ['http_proxy']
if is_secure:
env_keys.insert(0, 'https_proxy')
for key in env_keys:
value = os.environ.get(key, None)
if value:
proxy = urlparse(value)
auth = ((proxy.username, proxy.password) if proxy.username else None)
return (proxy.hostname, proxy.port, auth)
return (None, 0, None)
| [
"def",
"get_proxy_info",
"(",
"hostname",
",",
"is_secure",
",",
"proxy_host",
"=",
"None",
",",
"proxy_port",
"=",
"0",
",",
"proxy_auth",
"=",
"None",
",",
"no_proxy",
"=",
"None",
")",
":",
"if",
"_is_no_proxy_host",
"(",
"hostname",
",",
"no_proxy",
")... | try to retrieve proxy host and port from environment if not provided in options . | train | true |
32,878 | def endian_int(arr):
arr.reverse()
return int(''.join(arr), 16)
| [
"def",
"endian_int",
"(",
"arr",
")",
":",
"arr",
".",
"reverse",
"(",
")",
"return",
"int",
"(",
"''",
".",
"join",
"(",
"arr",
")",
",",
"16",
")"
] | parse string array bytes into an int . | train | false |
32,880 | def make_log_record_output(category, level, message, format=None, datefmt=None, **kwargs):
if ((not category) or (category == '__ROOT__')):
category = 'root'
levelname = logging.getLevelName(level)
record_data = dict(name=category, levelname=levelname, msg=message)
record_data.update(kwargs)
record = logging.makeLogRecord(record_data)
formatter = logging.Formatter(format, datefmt=datefmt)
return formatter.format(record)
| [
"def",
"make_log_record_output",
"(",
"category",
",",
"level",
",",
"message",
",",
"format",
"=",
"None",
",",
"datefmt",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"(",
"not",
"category",
")",
"or",
"(",
"category",
"==",
"'__ROOT__'",
"... | create the output for a log record . | train | true |
32,883 | def Thing2Str(s, d):
return str(s)
| [
"def",
"Thing2Str",
"(",
"s",
",",
"d",
")",
":",
"return",
"str",
"(",
"s",
")"
] | convert something into a string via str() . | train | false |
32,884 | def build_counting_args(descr=None, epilog=None, citations=None):
parser = build_graph_args(descr=descr, epilog=epilog, citations=citations)
parser.add_argument(u'--small-count', default=False, action=u'store_true', help=u'Reduce memory usage by using a smaller counter for individual kmers.')
return parser
| [
"def",
"build_counting_args",
"(",
"descr",
"=",
"None",
",",
"epilog",
"=",
"None",
",",
"citations",
"=",
"None",
")",
":",
"parser",
"=",
"build_graph_args",
"(",
"descr",
"=",
"descr",
",",
"epilog",
"=",
"epilog",
",",
"citations",
"=",
"citations",
... | build an argumentparser with args for countgraph based scripts . | train | false |
32,885 | def build_translation(option, opt, value, parser):
raise ConfigurationException('This function is not implemented yet')
try:
with open(value, 'r') as input:
data = pickle.load(input)
except:
raise ConfigurationException(('File Not Found %s' % value))
with open((value + '.trans'), 'w') as output:
pass
exit()
| [
"def",
"build_translation",
"(",
"option",
",",
"opt",
",",
"value",
",",
"parser",
")",
":",
"raise",
"ConfigurationException",
"(",
"'This function is not implemented yet'",
")",
"try",
":",
"with",
"open",
"(",
"value",
",",
"'r'",
")",
"as",
"input",
":",
... | converts a register dump list to a pickeld datastore . | train | false |
32,887 | @utils.arg('aggregate', metavar='<aggregate>', help=_('Name or ID of aggregate to update.'))
@utils.arg('metadata', metavar='<key=value>', nargs='+', action='append', default=[], help=_('Metadata to add/update to aggregate. Specify only the key to delete a metadata item.'))
def do_aggregate_set_metadata(cs, args):
aggregate = _find_aggregate(cs, args.aggregate)
metadata = _extract_metadata(args)
currentmetadata = getattr(aggregate, 'metadata', {})
if (set(metadata.items()) & set(currentmetadata.items())):
raise exceptions.CommandError(_('metadata already exists'))
for (key, value) in metadata.items():
if ((value is None) and (key not in currentmetadata)):
raise exceptions.CommandError((_('metadata key %s does not exist hence can not be deleted') % key))
aggregate = cs.aggregates.set_metadata(aggregate.id, metadata)
print((_('Metadata has been successfully updated for aggregate %s.') % aggregate.id))
_print_aggregate_details(cs, aggregate)
| [
"@",
"utils",
".",
"arg",
"(",
"'aggregate'",
",",
"metavar",
"=",
"'<aggregate>'",
",",
"help",
"=",
"_",
"(",
"'Name or ID of aggregate to update.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'metadata'",
",",
"metavar",
"=",
"'<key=value>'",
",",
"nargs",... | update the metadata associated with the aggregate . | train | false |
32,888 | @flake8ext
def check_asserttruefalse(logical_line, filename):
if ('neutron/tests/' in filename):
if re.search('assertEqual\\(\\s*True,[^,]*(,[^,]*)?', logical_line):
msg = 'N328: Use assertTrue(observed) instead of assertEqual(True, observed)'
(yield (0, msg))
if re.search('assertEqual\\([^,]*,\\s*True(,[^,]*)?', logical_line):
msg = 'N328: Use assertTrue(observed) instead of assertEqual(True, observed)'
(yield (0, msg))
if re.search('assertEqual\\(\\s*False,[^,]*(,[^,]*)?', logical_line):
msg = 'N328: Use assertFalse(observed) instead of assertEqual(False, observed)'
(yield (0, msg))
if re.search('assertEqual\\([^,]*,\\s*False(,[^,]*)?', logical_line):
msg = 'N328: Use assertFalse(observed) instead of assertEqual(False, observed)'
(yield (0, msg))
| [
"@",
"flake8ext",
"def",
"check_asserttruefalse",
"(",
"logical_line",
",",
"filename",
")",
":",
"if",
"(",
"'neutron/tests/'",
"in",
"filename",
")",
":",
"if",
"re",
".",
"search",
"(",
"'assertEqual\\\\(\\\\s*True,[^,]*(,[^,]*)?'",
",",
"logical_line",
")",
":... | n328 - dont use assertequal . | train | false |
32,890 | def check_all_files(dir_path=theano.__path__[0], pattern='*.py'):
with open('theano_filelist.txt', 'a') as f_txt:
for (dir, _, files) in os.walk(dir_path):
for f in files:
if fnmatch(f, pattern):
error_num = flake8.main.check_file(os.path.join(dir, f), ignore=ignore)
if (error_num > 0):
path = os.path.relpath(os.path.join(dir, f), theano.__path__[0])
f_txt.write((('"' + path) + '",\n'))
| [
"def",
"check_all_files",
"(",
"dir_path",
"=",
"theano",
".",
"__path__",
"[",
"0",
"]",
",",
"pattern",
"=",
"'*.py'",
")",
":",
"with",
"open",
"(",
"'theano_filelist.txt'",
",",
"'a'",
")",
"as",
"f_txt",
":",
"for",
"(",
"dir",
",",
"_",
",",
"f... | list all . | train | false |
32,892 | @with_device
def product():
return str(properties.ro.build.product)
| [
"@",
"with_device",
"def",
"product",
"(",
")",
":",
"return",
"str",
"(",
"properties",
".",
"ro",
".",
"build",
".",
"product",
")"
] | taken from URL#itertools . | train | false |
32,895 | def unconvert_from_RGB_255(colors):
return ((colors[0] / 255.0), (colors[1] / 255.0), (colors[2] / 255.0))
| [
"def",
"unconvert_from_RGB_255",
"(",
"colors",
")",
":",
"return",
"(",
"(",
"colors",
"[",
"0",
"]",
"/",
"255.0",
")",
",",
"(",
"colors",
"[",
"1",
"]",
"/",
"255.0",
")",
",",
"(",
"colors",
"[",
"2",
"]",
"/",
"255.0",
")",
")"
] | return a tuple where each element gets divided by 255 takes a color tuple(s) where each element is between 0 and 255 . | train | false |
32,896 | def _redirect_eliot_logs_for_trial():
import os
import sys
if (os.path.basename(sys.argv[0]) == 'trial'):
from eliot.twisted import redirectLogsForTrial
redirectLogsForTrial()
| [
"def",
"_redirect_eliot_logs_for_trial",
"(",
")",
":",
"import",
"os",
"import",
"sys",
"if",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"==",
"'trial'",
")",
":",
"from",
"eliot",
".",
"twisted",
"import",
... | enable eliot logging to the _trial/test . | train | false |
32,897 | def cmp_debug_levels(level1, level2):
level_ints = {False: 0, 'merge': 1, True: 2}
try:
cmp = (lambda a, b: ((a > b) - (a < b)))
return cmp(level_ints[level1], level_ints[level2])
except KeyError as e:
raise BundleError(('Invalid debug value: %s' % e))
| [
"def",
"cmp_debug_levels",
"(",
"level1",
",",
"level2",
")",
":",
"level_ints",
"=",
"{",
"False",
":",
"0",
",",
"'merge'",
":",
"1",
",",
"True",
":",
"2",
"}",
"try",
":",
"cmp",
"=",
"(",
"lambda",
"a",
",",
"b",
":",
"(",
"(",
"a",
">",
... | cmp() for debug levels . | train | false |
32,899 | def comment_form_target():
return comments.get_form_target()
| [
"def",
"comment_form_target",
"(",
")",
":",
"return",
"comments",
".",
"get_form_target",
"(",
")"
] | get the target url for the comment form . | train | false |
32,900 | def fromqimage(im):
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
if im.hasAlphaChannel():
im.save(buffer, 'png')
else:
im.save(buffer, 'ppm')
b = BytesIO()
try:
b.write(buffer.data())
except TypeError:
b.write(str(buffer.data()))
buffer.close()
b.seek(0)
return Image.open(b)
| [
"def",
"fromqimage",
"(",
"im",
")",
":",
"buffer",
"=",
"QBuffer",
"(",
")",
"buffer",
".",
"open",
"(",
"QIODevice",
".",
"ReadWrite",
")",
"if",
"im",
".",
"hasAlphaChannel",
"(",
")",
":",
"im",
".",
"save",
"(",
"buffer",
",",
"'png'",
")",
"e... | creates an image instance from a qimage image . | train | false |
32,902 | def cmd_list_resources(args, opts):
for x in json_get(opts, '')['resources']:
print(x)
| [
"def",
"cmd_list_resources",
"(",
"args",
",",
"opts",
")",
":",
"for",
"x",
"in",
"json_get",
"(",
"opts",
",",
"''",
")",
"[",
"'resources'",
"]",
":",
"print",
"(",
"x",
")"
] | list-resources - list available web service resources . | train | false |
32,903 | def get_url_shortener():
try:
backend_module = import_module(URL_SHORTENER_BACKEND)
backend = getattr(backend_module, 'backend')
except (ImportError, AttributeError):
warnings.warn(('%s backend cannot be imported' % URL_SHORTENER_BACKEND), RuntimeWarning)
backend = default_backend
except ImproperlyConfigured as e:
warnings.warn(str(e), RuntimeWarning)
backend = default_backend
return backend
| [
"def",
"get_url_shortener",
"(",
")",
":",
"try",
":",
"backend_module",
"=",
"import_module",
"(",
"URL_SHORTENER_BACKEND",
")",
"backend",
"=",
"getattr",
"(",
"backend_module",
",",
"'backend'",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
"... | return the selected url shortener backend . | train | true |
32,904 | def smart_int(string, fallback=0):
try:
return int(float(string))
except (ValueError, TypeError, OverflowError):
return fallback
| [
"def",
"smart_int",
"(",
"string",
",",
"fallback",
"=",
"0",
")",
":",
"try",
":",
"return",
"int",
"(",
"float",
"(",
"string",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"OverflowError",
")",
":",
"return",
"fallback"
] | convert a string to int . | train | false |
32,905 | def timedelta_as_seconds(td):
return ((td.days * 86400) + td.seconds)
| [
"def",
"timedelta_as_seconds",
"(",
"td",
")",
":",
"return",
"(",
"(",
"td",
".",
"days",
"*",
"86400",
")",
"+",
"td",
".",
"seconds",
")"
] | returns the value of the entire timedelta as integer seconds . | train | false |
32,907 | def get_training_model():
(x, conv_layer, conv_vars) = convolutional_layers()
W_fc1 = weight_variable([((32 * 8) * 128), 2048])
b_fc1 = bias_variable([2048])
conv_layer_flat = tf.reshape(conv_layer, [(-1), ((32 * 8) * 128)])
h_fc1 = tf.nn.relu((tf.matmul(conv_layer_flat, W_fc1) + b_fc1))
W_fc2 = weight_variable([2048, (1 + (7 * len(common.CHARS)))])
b_fc2 = bias_variable([(1 + (7 * len(common.CHARS)))])
y = (tf.matmul(h_fc1, W_fc2) + b_fc2)
return (x, y, (conv_vars + [W_fc1, b_fc1, W_fc2, b_fc2]))
| [
"def",
"get_training_model",
"(",
")",
":",
"(",
"x",
",",
"conv_layer",
",",
"conv_vars",
")",
"=",
"convolutional_layers",
"(",
")",
"W_fc1",
"=",
"weight_variable",
"(",
"[",
"(",
"(",
"32",
"*",
"8",
")",
"*",
"128",
")",
",",
"2048",
"]",
")",
... | the training model acts on a batch of 128x64 windows . | train | false |
32,908 | def s3_comments_widget(field, value, **attr):
if ('_id' not in attr):
_id = ('%s_%s' % (field._tablename, field.name))
else:
_id = attr['_id']
if ('_name' not in attr):
_name = field.name
else:
_name = attr['_name']
return TEXTAREA(_name=_name, _id=_id, _class=('comments %s' % field.type), value=value, requires=field.requires)
| [
"def",
"s3_comments_widget",
"(",
"field",
",",
"value",
",",
"**",
"attr",
")",
":",
"if",
"(",
"'_id'",
"not",
"in",
"attr",
")",
":",
"_id",
"=",
"(",
"'%s_%s'",
"%",
"(",
"field",
".",
"_tablename",
",",
"field",
".",
"name",
")",
")",
"else",
... | a smaller-than-normal textarea to be used by the s3 . | train | false |
32,910 | def parse_www_authenticate_header(value, on_update=None):
if (not value):
return WWWAuthenticate(on_update=on_update)
try:
(auth_type, auth_info) = value.split(None, 1)
auth_type = auth_type.lower()
except (ValueError, AttributeError):
return WWWAuthenticate(value.strip().lower(), on_update=on_update)
return WWWAuthenticate(auth_type, parse_dict_header(auth_info), on_update)
| [
"def",
"parse_www_authenticate_header",
"(",
"value",
",",
"on_update",
"=",
"None",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"WWWAuthenticate",
"(",
"on_update",
"=",
"on_update",
")",
"try",
":",
"(",
"auth_type",
",",
"auth_info",
")",
"... | parse an http www-authenticate header into a :class:~werkzeug . | train | true |
32,911 | def history_get():
state = _open_state()
if (HISTORY_KEY not in state):
return set()
return state[HISTORY_KEY]
| [
"def",
"history_get",
"(",
")",
":",
"state",
"=",
"_open_state",
"(",
")",
"if",
"(",
"HISTORY_KEY",
"not",
"in",
"state",
")",
":",
"return",
"set",
"(",
")",
"return",
"state",
"[",
"HISTORY_KEY",
"]"
] | get the set of completed path tuples in incremental imports . | train | false |
32,912 | def get_unique_open_realm():
if settings.REALMS_HAVE_SUBDOMAINS:
return None
realms = Realm.objects.filter(deactivated=False)
realms = realms.exclude(string_id__in=settings.SYSTEM_ONLY_REALMS)
if (len(realms) != 1):
return None
realm = realms[0]
if (realm.invite_required or realm.restricted_to_domain):
return None
return realm
| [
"def",
"get_unique_open_realm",
"(",
")",
":",
"if",
"settings",
".",
"REALMS_HAVE_SUBDOMAINS",
":",
"return",
"None",
"realms",
"=",
"Realm",
".",
"objects",
".",
"filter",
"(",
"deactivated",
"=",
"False",
")",
"realms",
"=",
"realms",
".",
"exclude",
"(",... | we only return a realm if there is a unique non-system-only realm . | train | false |
32,914 | def delete_interface(call=None, kwargs=None):
global netconn
if (not netconn):
netconn = get_conn(NetworkManagementClient)
if (kwargs.get('resource_group') is None):
kwargs['resource_group'] = config.get_cloud_config_value('resource_group', {}, __opts__, search_global=True)
ips = []
iface = netconn.network_interfaces.get(kwargs['resource_group'], kwargs['iface_name'])
iface_name = iface.name
for ip_ in iface.ip_configurations:
ips.append(ip_.name)
poller = netconn.network_interfaces.delete(kwargs['resource_group'], kwargs['iface_name'])
poller.wait()
for ip_ in ips:
poller = netconn.public_ip_addresses.delete(kwargs['resource_group'], ip_)
poller.wait()
return {iface_name: ips}
| [
"def",
"delete_interface",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"global",
"netconn",
"if",
"(",
"not",
"netconn",
")",
":",
"netconn",
"=",
"get_conn",
"(",
"NetworkManagementClient",
")",
"if",
"(",
"kwargs",
".",
"get",
"(",
... | create a network interface . | train | true |
32,915 | def extract_key_values(key, d):
if (key in d):
(yield d[key])
for k in d:
if isinstance(d[k], dict):
for j in extract_key_values(key, d[k]):
(yield j)
| [
"def",
"extract_key_values",
"(",
"key",
",",
"d",
")",
":",
"if",
"(",
"key",
"in",
"d",
")",
":",
"(",
"yield",
"d",
"[",
"key",
"]",
")",
"for",
"k",
"in",
"d",
":",
"if",
"isinstance",
"(",
"d",
"[",
"k",
"]",
",",
"dict",
")",
":",
"fo... | extracts all values that match a key . | train | false |
32,916 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
32,917 | @task
def migrate_search(ctx, delete=False, index=settings.ELASTIC_INDEX):
from website.app import init_app
init_app(routes=False, set_backends=False)
from website.search_migration.migrate import migrate
migrate(delete, index=index)
| [
"@",
"task",
"def",
"migrate_search",
"(",
"ctx",
",",
"delete",
"=",
"False",
",",
"index",
"=",
"settings",
".",
"ELASTIC_INDEX",
")",
":",
"from",
"website",
".",
"app",
"import",
"init_app",
"init_app",
"(",
"routes",
"=",
"False",
",",
"set_backends",... | migrate the search-enabled models . | train | false |
32,918 | def example_exc_handler(tries_remaining, exception, delay):
print >>sys.stderr, ("Caught '%s', %d tries remaining, sleeping for %s seconds" % (exception, tries_remaining, delay))
| [
"def",
"example_exc_handler",
"(",
"tries_remaining",
",",
"exception",
",",
"delay",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"(",
"\"Caught '%s', %d tries remaining, sleeping for %s seconds\"",
"%",
"(",
"exception",
",",
"tries_remaining",
",",
"delay",
... | example exception handler; prints a warning to stderr . | train | true |
32,919 | def lineparse(inline, options=None, **keywargs):
p = LineParser(options, **keywargs)
return p.feed(inline)
| [
"def",
"lineparse",
"(",
"inline",
",",
"options",
"=",
"None",
",",
"**",
"keywargs",
")",
":",
"p",
"=",
"LineParser",
"(",
"options",
",",
"**",
"keywargs",
")",
"return",
"p",
".",
"feed",
"(",
"inline",
")"
] | a compatibility function that mimics the old lineparse . | train | false |
32,920 | def _getRightsAssignments(user_right):
sids = []
polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS)
sids = win32security.LsaEnumerateAccountsWithUserRight(polHandle, user_right)
return sids
| [
"def",
"_getRightsAssignments",
"(",
"user_right",
")",
":",
"sids",
"=",
"[",
"]",
"polHandle",
"=",
"win32security",
".",
"LsaOpenPolicy",
"(",
"None",
",",
"win32security",
".",
"POLICY_ALL_ACCESS",
")",
"sids",
"=",
"win32security",
".",
"LsaEnumerateAccountsW... | helper function to return all the user rights assignments/users . | train | true |
32,921 | def test_one_sample_allowed():
encoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)])
decoding_model = MLP(layers=[Linear(layer_name='h', dim=10, irange=0.01)])
prior = DiagonalGaussianPrior()
conditional = BernoulliVector(mlp=decoding_model, name='conditional')
posterior = DiagonalGaussian(mlp=encoding_model, name='posterior')
vae = VAE(nvis=10, prior=prior, conditional=conditional, posterior=posterior, nhid=5)
X = T.matrix('X')
lower_bound = vae.log_likelihood_lower_bound(X, num_samples=1)
f = theano.function(inputs=[X], outputs=lower_bound)
rng = make_np_rng(default_seed=11223)
f(as_floatX(rng.uniform(size=(10, 10))))
| [
"def",
"test_one_sample_allowed",
"(",
")",
":",
"encoding_model",
"=",
"MLP",
"(",
"layers",
"=",
"[",
"Linear",
"(",
"layer_name",
"=",
"'h'",
",",
"dim",
"=",
"10",
",",
"irange",
"=",
"0.01",
")",
"]",
")",
"decoding_model",
"=",
"MLP",
"(",
"layer... | vae allows one sample per data point . | train | false |
32,922 | def _unwrapx(input, output, repeat):
pow2 = np.array([128, 64, 32, 16, 8, 4, 2, 1], dtype='uint8')
nbytes = (((repeat - 1) // 8) + 1)
for i in range(nbytes):
_min = (i * 8)
_max = min(((i + 1) * 8), repeat)
for j in range(_min, _max):
output[..., j] = np.bitwise_and(input[..., i], pow2[(j - (i * 8))])
| [
"def",
"_unwrapx",
"(",
"input",
",",
"output",
",",
"repeat",
")",
":",
"pow2",
"=",
"np",
".",
"array",
"(",
"[",
"128",
",",
"64",
",",
"32",
",",
"16",
",",
"8",
",",
"4",
",",
"2",
",",
"1",
"]",
",",
"dtype",
"=",
"'uint8'",
")",
"nby... | unwrap the x format column into a boolean array . | train | false |
32,924 | def vm_cputime(vm_=None):
host_cpus = __get_conn().getInfo()[2]
def _info(vm_):
dom = _get_domain(vm_)
raw = dom.info()
vcpus = int(raw[3])
cputime = int(raw[4])
cputime_percent = 0
if cputime:
cputime_percent = (((1e-07 * cputime) / host_cpus) / vcpus)
return {'cputime': int(raw[4]), 'cputime_percent': int('{0:.0f}'.format(cputime_percent))}
info = {}
if vm_:
info[vm_] = _info(vm_)
else:
for vm_ in list_domains():
info[vm_] = _info(vm_)
return info
| [
"def",
"vm_cputime",
"(",
"vm_",
"=",
"None",
")",
":",
"host_cpus",
"=",
"__get_conn",
"(",
")",
".",
"getInfo",
"(",
")",
"[",
"2",
"]",
"def",
"_info",
"(",
"vm_",
")",
":",
"dom",
"=",
"_get_domain",
"(",
"vm_",
")",
"raw",
"=",
"dom",
".",
... | return cputime used by the vms on this hyper in a list of dicts: . | train | false |
32,926 | def right(method):
def _inner(self, other):
return method(other, self)
return _inner
| [
"def",
"right",
"(",
"method",
")",
":",
"def",
"_inner",
"(",
"self",
",",
"other",
")",
":",
"return",
"method",
"(",
"other",
",",
"self",
")",
"return",
"_inner"
] | wrapper to create right version of operator given left version . | train | false |
32,928 | @testing.requires_testing_data
def test_read_curv():
fname_curv = op.join(data_path, 'subjects', 'fsaverage', 'surf', 'lh.curv')
fname_surf = op.join(data_path, 'subjects', 'fsaverage', 'surf', 'lh.inflated')
bin_curv = read_curvature(fname_curv)
rr = read_surface(fname_surf)[0]
assert_true((len(bin_curv) == len(rr)))
assert_true(np.logical_or((bin_curv == 0), (bin_curv == 1)).all())
| [
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_read_curv",
"(",
")",
":",
"fname_curv",
"=",
"op",
".",
"join",
"(",
"data_path",
",",
"'subjects'",
",",
"'fsaverage'",
",",
"'surf'",
",",
"'lh.curv'",
")",
"fname_surf",
"=",
"op",
".",
"join",
... | test reading curvature data . | train | false |
32,929 | def _allow_join(statement):
if ((not statement) or (not statement.tokens)):
return False
last_tok = statement.token_prev(len(statement.tokens))[1]
return (last_tok.value.lower().endswith('join') and (last_tok.value.lower() not in ('cross join', 'natural join')))
| [
"def",
"_allow_join",
"(",
"statement",
")",
":",
"if",
"(",
"(",
"not",
"statement",
")",
"or",
"(",
"not",
"statement",
".",
"tokens",
")",
")",
":",
"return",
"False",
"last_tok",
"=",
"statement",
".",
"token_prev",
"(",
"len",
"(",
"statement",
".... | tests if a join should be suggested we need this to avoid bad suggestions when entering e . | train | false |
32,930 | def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None):
query = 'select keyspace_name\n from system.schema_keyspaces;'
ret = {}
try:
ret = cql_query(query, contact_points, port, cql_user, cql_pass)
except CommandExecutionError:
log.critical('Could not list keyspaces.')
raise
except BaseException as e:
log.critical('Unexpected error while listing keyspaces: {0}'.format(str(e)))
raise
return ret
| [
"def",
"list_keyspaces",
"(",
"contact_points",
"=",
"None",
",",
"port",
"=",
"None",
",",
"cql_user",
"=",
"None",
",",
"cql_pass",
"=",
"None",
")",
":",
"query",
"=",
"'select keyspace_name\\n from system.schema_keyspaces;'",
"ret",
"=",
"{",
"... | list keyspaces in a cassandra cluster . | train | false |
32,932 | def auth_token_required(fn):
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated
| [
"def",
"auth_token_required",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"_check_token",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
... | decorator that protects endpoints using token authentication . | train | true |
32,933 | def _make_dictnames(tmp_arr, offset=0):
col_map = {}
for (i, col_name) in enumerate(tmp_arr):
col_map.update({(i + offset): col_name})
return col_map
| [
"def",
"_make_dictnames",
"(",
"tmp_arr",
",",
"offset",
"=",
"0",
")",
":",
"col_map",
"=",
"{",
"}",
"for",
"(",
"i",
",",
"col_name",
")",
"in",
"enumerate",
"(",
"tmp_arr",
")",
":",
"col_map",
".",
"update",
"(",
"{",
"(",
"i",
"+",
"offset",
... | helper function to create a dictionary mapping a column number to the name in tmp_arr . | train | false |
32,934 | def decode_udp_packet(data):
offset = 0
(rsv, frag, address_type) = struct.unpack_from('!HBB', data, offset)
offset += 4
(offset, destination_address) = __decode_address(address_type, offset, data)
(destination_port,) = struct.unpack_from('!H', data, offset)
offset += 2
payload = data[offset:]
return UdpRequest(rsv, frag, address_type, destination_address, destination_port, payload)
| [
"def",
"decode_udp_packet",
"(",
"data",
")",
":",
"offset",
"=",
"0",
"(",
"rsv",
",",
"frag",
",",
"address_type",
")",
"=",
"struct",
".",
"unpack_from",
"(",
"'!HBB'",
",",
"data",
",",
"offset",
")",
"offset",
"+=",
"4",
"(",
"offset",
",",
"des... | decodes a socks5 udp packet . | train | false |
32,935 | def get_subscription(document_class, sub_id, topic=None):
topic = _get_document_topic(document_class, topic)
return prospective_search.get_subscription(datastore.Entity, sub_id, topic=topic)
| [
"def",
"get_subscription",
"(",
"document_class",
",",
"sub_id",
",",
"topic",
"=",
"None",
")",
":",
"topic",
"=",
"_get_document_topic",
"(",
"document_class",
",",
"topic",
")",
"return",
"prospective_search",
".",
"get_subscription",
"(",
"datastore",
".",
"... | get subscription information . | train | false |
32,938 | def post_delete_resource(instance, sender, **kwargs):
current_site = Site.objects.get_current()
master_site = Site.objects.get(id=1)
SiteResources.objects.get(site=current_site).resources.remove(instance.get_self_resource())
SiteResources.objects.get(site=master_site).resources.remove(instance.get_self_resource())
| [
"def",
"post_delete_resource",
"(",
"instance",
",",
"sender",
",",
"**",
"kwargs",
")",
":",
"current_site",
"=",
"Site",
".",
"objects",
".",
"get_current",
"(",
")",
"master_site",
"=",
"Site",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"1",
")",
"... | signal to ensure that on resource delete it get remove from the siteresources as well . | train | false |
32,939 | def dmp_one(u, K):
return dmp_ground(K.one, u)
| [
"def",
"dmp_one",
"(",
"u",
",",
"K",
")",
":",
"return",
"dmp_ground",
"(",
"K",
".",
"one",
",",
"u",
")"
] | return a multivariate one over k . | train | false |
32,940 | def convert_from_missing_indexer_tuple(indexer, axes):
def get_indexer(_i, _idx):
return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else _idx)
return tuple([get_indexer(_i, _idx) for (_i, _idx) in enumerate(indexer)])
| [
"def",
"convert_from_missing_indexer_tuple",
"(",
"indexer",
",",
"axes",
")",
":",
"def",
"get_indexer",
"(",
"_i",
",",
"_idx",
")",
":",
"return",
"(",
"axes",
"[",
"_i",
"]",
".",
"get_loc",
"(",
"_idx",
"[",
"'key'",
"]",
")",
"if",
"isinstance",
... | create a filtered indexer that doesnt have any missing indexers . | train | true |
32,941 | def DeleteOldFeedItems(client, feed_item_ids, feed):
if (not feed_item_ids):
return
feed_item_service = client.GetService('FeedItemService', 'v201607')
operations = [{'operator': 'REMOVE', 'operand': {'feedId': feed['id'], 'feedItemId': feed_item_id}} for feed_item_id in feed_item_ids]
feed_item_service.mutate(operations)
| [
"def",
"DeleteOldFeedItems",
"(",
"client",
",",
"feed_item_ids",
",",
"feed",
")",
":",
"if",
"(",
"not",
"feed_item_ids",
")",
":",
"return",
"feed_item_service",
"=",
"client",
".",
"GetService",
"(",
"'FeedItemService'",
",",
"'v201607'",
")",
"operations",
... | deletes the old feed items for which extension settings have been created . | train | true |
32,943 | @pytest.mark.skipif(is_windows, reason='Pretty redirect not supported under Windows')
def test_pretty_redirected_stream(httpbin):
with open(BIN_FILE_PATH, 'rb') as f:
env = TestEnvironment(colors=256, stdin=f, stdin_isatty=False, stdout_isatty=False)
r = http('--verbose', '--pretty=all', '--stream', 'GET', (httpbin.url + '/get'), env=env)
assert (BINARY_SUPPRESSED_NOTICE.decode() in r)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"is_windows",
",",
"reason",
"=",
"'Pretty redirect not supported under Windows'",
")",
"def",
"test_pretty_redirected_stream",
"(",
"httpbin",
")",
":",
"with",
"open",
"(",
"BIN_FILE_PATH",
",",
"'rb'",
")",
"as",
... | test that --stream works with prettified redirected output . | train | false |
32,944 | def validate_octal(value):
if (not value):
return (None, value)
try:
int(value, 8)
return (None, value)
except:
return ((T('%s is not a correct octal value') % value), None)
| [
"def",
"validate_octal",
"(",
"value",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"(",
"None",
",",
"value",
")",
"try",
":",
"int",
"(",
"value",
",",
"8",
")",
"return",
"(",
"None",
",",
"value",
")",
"except",
":",
"return",
"("... | check if string is valid octal number . | train | false |
32,945 | def log_db_contents(msg=None):
text = (msg or '')
content = pprint.pformat(_db_content)
LOG.debug((_('%(text)s: _db_content => %(content)s') % locals()))
| [
"def",
"log_db_contents",
"(",
"msg",
"=",
"None",
")",
":",
"text",
"=",
"(",
"msg",
"or",
"''",
")",
"content",
"=",
"pprint",
".",
"pformat",
"(",
"_db_content",
")",
"LOG",
".",
"debug",
"(",
"(",
"_",
"(",
"'%(text)s: _db_content => %(content)s'",
"... | log db contents . | train | false |
32,946 | def get_reversed_changelog_changesets(repo):
reversed_changelog = []
for changeset in repo.changelog:
reversed_changelog.insert(0, changeset)
return reversed_changelog
| [
"def",
"get_reversed_changelog_changesets",
"(",
"repo",
")",
":",
"reversed_changelog",
"=",
"[",
"]",
"for",
"changeset",
"in",
"repo",
".",
"changelog",
":",
"reversed_changelog",
".",
"insert",
"(",
"0",
",",
"changeset",
")",
"return",
"reversed_changelog"
] | return a list of changesets in reverse order from that provided by the repository manifest . | train | false |
32,948 | def import_doc(d, doctype, overwrite, row_idx, submit=False, ignore_links=False):
if (d.get(u'name') and frappe.db.exists(doctype, d[u'name'])):
if overwrite:
doc = frappe.get_doc(doctype, d[u'name'])
doc.flags.ignore_links = ignore_links
doc.update(d)
if (d.get(u'docstatus') == 1):
doc.update_after_submit()
else:
doc.save()
return (u'Updated row (#%d) %s' % ((row_idx + 1), getlink(doctype, d[u'name'])))
else:
return (u'Ignored row (#%d) %s (exists)' % ((row_idx + 1), getlink(doctype, d[u'name'])))
else:
doc = frappe.get_doc(d)
doc.flags.ignore_links = ignore_links
doc.insert()
if submit:
doc.submit()
return (u'Inserted row (#%d) %s' % ((row_idx + 1), getlink(doctype, doc.get(u'name'))))
| [
"def",
"import_doc",
"(",
"d",
",",
"doctype",
",",
"overwrite",
",",
"row_idx",
",",
"submit",
"=",
"False",
",",
"ignore_links",
"=",
"False",
")",
":",
"if",
"(",
"d",
".",
"get",
"(",
"u'name'",
")",
"and",
"frappe",
".",
"db",
".",
"exists",
"... | import a file using data import tool . | train | false |
32,949 | def _empty_info(sfreq):
from ..transforms import Transform
_none_keys = ('acq_pars', 'acq_stim', 'buffer_size_sec', 'ctf_head_t', 'description', 'dev_ctf_t', 'dig', 'experimenter', 'file_id', 'highpass', 'hpi_subsystem', 'kit_system_id', 'line_freq', 'lowpass', 'meas_date', 'meas_id', 'proj_id', 'proj_name', 'subject_info', 'xplotter_layout')
_list_keys = ('bads', 'chs', 'comps', 'events', 'hpi_meas', 'hpi_results', 'projs')
info = Info()
for k in _none_keys:
info[k] = None
for k in _list_keys:
info[k] = list()
info['custom_ref_applied'] = False
info['dev_head_t'] = Transform('meg', 'head')
info['highpass'] = 0.0
info['sfreq'] = float(sfreq)
info['lowpass'] = (info['sfreq'] / 2.0)
info._update_redundant()
info._check_consistency()
return info
| [
"def",
"_empty_info",
"(",
"sfreq",
")",
":",
"from",
".",
".",
"transforms",
"import",
"Transform",
"_none_keys",
"=",
"(",
"'acq_pars'",
",",
"'acq_stim'",
",",
"'buffer_size_sec'",
",",
"'ctf_head_t'",
",",
"'description'",
",",
"'dev_ctf_t'",
",",
"'dig'",
... | create an empty info dictionary . | train | false |
32,950 | def test_single_feature_single_tag():
feature = Feature.from_string(FEATURE18)
assert that(feature.scenarios[0].tags).deep_equals(['runme1', 'feature_runme'])
assert that(feature.scenarios[1].tags).deep_equals(['runme2', 'feature_runme'])
assert that(feature.scenarios[2].tags).deep_equals(['runme3', 'feature_runme'])
| [
"def",
"test_single_feature_single_tag",
"(",
")",
":",
"feature",
"=",
"Feature",
".",
"from_string",
"(",
"FEATURE18",
")",
"assert",
"that",
"(",
"feature",
".",
"scenarios",
"[",
"0",
"]",
".",
"tags",
")",
".",
"deep_equals",
"(",
"[",
"'runme1'",
","... | all scenarios within a feature inherit the features tags . | train | false |
32,951 | def walk_class_hierarchy(clazz, encountered=None):
if (not encountered):
encountered = []
for subclass in clazz.__subclasses__():
if (subclass not in encountered):
encountered.append(subclass)
for subsubclass in walk_class_hierarchy(subclass, encountered):
(yield subsubclass)
(yield subclass)
| [
"def",
"walk_class_hierarchy",
"(",
"clazz",
",",
"encountered",
"=",
"None",
")",
":",
"if",
"(",
"not",
"encountered",
")",
":",
"encountered",
"=",
"[",
"]",
"for",
"subclass",
"in",
"clazz",
".",
"__subclasses__",
"(",
")",
":",
"if",
"(",
"subclass"... | walk class hierarchy . | train | false |
32,952 | def recurrence_memo(initial):
cache = initial
def decorator(f):
@wraps(f)
def g(n):
L = len(cache)
if (n <= (L - 1)):
return cache[n]
for i in range(L, (n + 1)):
cache.append(f(i, cache))
return cache[(-1)]
return g
return decorator
| [
"def",
"recurrence_memo",
"(",
"initial",
")",
":",
"cache",
"=",
"initial",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"g",
"(",
"n",
")",
":",
"L",
"=",
"len",
"(",
"cache",
")",
"if",
"(",
"n",
"<=",
"(",
"... | memo decorator for sequences defined by recurrence see usage examples e . | train | false |
32,953 | def getAllVertexes(vertexes, xmlObject):
for archivableObject in xmlObject.archivableObjects:
vertexes += archivableObject.getVertexes()
return vertexes
| [
"def",
"getAllVertexes",
"(",
"vertexes",
",",
"xmlObject",
")",
":",
"for",
"archivableObject",
"in",
"xmlObject",
".",
"archivableObjects",
":",
"vertexes",
"+=",
"archivableObject",
".",
"getVertexes",
"(",
")",
"return",
"vertexes"
] | get all vertexes . | train | false |
32,954 | def rewrite_long_table_names():
table_objs = metadata.tables.values()
for table in table_objs:
table._original_name = table.name
if (len(table.name) > 30):
for letter in 'aeiouy':
table.name = table.name.replace(letter, '')
| [
"def",
"rewrite_long_table_names",
"(",
")",
":",
"table_objs",
"=",
"metadata",
".",
"tables",
".",
"values",
"(",
")",
"for",
"table",
"in",
"table_objs",
":",
"table",
".",
"_original_name",
"=",
"table",
".",
"name",
"if",
"(",
"len",
"(",
"table",
"... | disemvowels all table names over thirty characters . | train | false |
32,955 | def default_get_identifier(obj_or_string):
if isinstance(obj_or_string, six.string_types):
if (not IDENTIFIER_REGEX.match(obj_or_string)):
raise AttributeError((u"Provided string '%s' is not a valid identifier." % obj_or_string))
return obj_or_string
return (u'%s.%s' % (get_model_ct(obj_or_string), obj_or_string._get_pk_val()))
| [
"def",
"default_get_identifier",
"(",
"obj_or_string",
")",
":",
"if",
"isinstance",
"(",
"obj_or_string",
",",
"six",
".",
"string_types",
")",
":",
"if",
"(",
"not",
"IDENTIFIER_REGEX",
".",
"match",
"(",
"obj_or_string",
")",
")",
":",
"raise",
"AttributeEr... | get an unique identifier for the object or a string representing the object . | train | false |
32,957 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialise module . | train | false |
32,958 | def DedentLevel(by=1):
IndentLevel((- by))
| [
"def",
"DedentLevel",
"(",
"by",
"=",
"1",
")",
":",
"IndentLevel",
"(",
"(",
"-",
"by",
")",
")"
] | decrement the indentation level by one . | train | false |
32,959 | @decorator.decorator
def audio_video_fx(f, clip, *a, **k):
if hasattr(clip, 'audio'):
newclip = clip.copy()
if (clip.audio is not None):
newclip.audio = f(clip.audio, *a, **k)
return newclip
else:
return f(clip, *a, **k)
| [
"@",
"decorator",
".",
"decorator",
"def",
"audio_video_fx",
"(",
"f",
",",
"clip",
",",
"*",
"a",
",",
"**",
"k",
")",
":",
"if",
"hasattr",
"(",
"clip",
",",
"'audio'",
")",
":",
"newclip",
"=",
"clip",
".",
"copy",
"(",
")",
"if",
"(",
"clip",... | use an audio function on a video/audio clip this decorator tells that the function f can be also used on a video clip . | train | false |
32,960 | def add_class(classname, cls):
if (classname in cls._decl_class_registry):
existing = cls._decl_class_registry[classname]
if (not isinstance(existing, _MultipleClassMarker)):
existing = cls._decl_class_registry[classname] = _MultipleClassMarker([cls, existing])
else:
cls._decl_class_registry[classname] = cls
try:
root_module = cls._decl_class_registry['_sa_module_registry']
except KeyError:
cls._decl_class_registry['_sa_module_registry'] = root_module = _ModuleMarker('_sa_module_registry', None)
tokens = cls.__module__.split('.')
while tokens:
token = tokens.pop(0)
module = root_module.get_module(token)
for token in tokens:
module = module.get_module(token)
module.add_class(classname, cls)
| [
"def",
"add_class",
"(",
"classname",
",",
"cls",
")",
":",
"if",
"(",
"classname",
"in",
"cls",
".",
"_decl_class_registry",
")",
":",
"existing",
"=",
"cls",
".",
"_decl_class_registry",
"[",
"classname",
"]",
"if",
"(",
"not",
"isinstance",
"(",
"existi... | URL inserts classes into template variables that contain html tags . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.