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 |
|---|---|---|---|---|---|
47,618 | def _api_get_config(name, output, kwargs):
(_, data) = config.get_dconfig(kwargs.get('section'), kwargs.get('keyword'))
return report(output, keyword='config', data=data)
| [
"def",
"_api_get_config",
"(",
"name",
",",
"output",
",",
"kwargs",
")",
":",
"(",
"_",
",",
"data",
")",
"=",
"config",
".",
"get_dconfig",
"(",
"kwargs",
".",
"get",
"(",
"'section'",
")",
",",
"kwargs",
".",
"get",
"(",
"'keyword'",
")",
")",
"... | api: accepts output . | train | false |
47,619 | def start_stub(name):
service = SERVICES.get(name, None)
if service:
fake_server = service['class'](port_num=service['port'])
setattr(world, name, fake_server)
| [
"def",
"start_stub",
"(",
"name",
")",
":",
"service",
"=",
"SERVICES",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"service",
":",
"fake_server",
"=",
"service",
"[",
"'class'",
"]",
"(",
"port_num",
"=",
"service",
"[",
"'port'",
"]",
")",
"se... | start the required stub service running on a local port . | train | false |
47,620 | def get_model_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
| [
"def",
"get_model_or_none",
"(",
"model",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"model",
".",
"objects",
".",
"get",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"model",
".",
"DoesNotExist",
":",
"return",
"... | get model object or return none . | train | false |
47,623 | def check_free_space_in_dir(path, size):
from ..utils.console import human_file_size
space = get_free_space_in_dir(path)
if (space < size):
raise IOError(u"Not enough free space in '{0}' to download a {1} file".format(path, human_file_size(size)))
| [
"def",
"check_free_space_in_dir",
"(",
"path",
",",
"size",
")",
":",
"from",
".",
".",
"utils",
".",
"console",
"import",
"human_file_size",
"space",
"=",
"get_free_space_in_dir",
"(",
"path",
")",
"if",
"(",
"space",
"<",
"size",
")",
":",
"raise",
"IOEr... | determines if a given directory has enough space to hold a file of a given size . | train | false |
47,624 | def find_listen_pids_namespace(namespace):
ip = ip_lib.IPWrapper(namespace=namespace)
pids = set()
cmd = ['netstat', '-nlp']
output = ip.netns.execute(cmd, run_as_root=True)
for line in output.splitlines():
m = NETSTAT_PIDS_REGEX.match(line)
if m:
pids.add(m.group('pid'))
return pids
| [
"def",
"find_listen_pids_namespace",
"(",
"namespace",
")",
":",
"ip",
"=",
"ip_lib",
".",
"IPWrapper",
"(",
"namespace",
"=",
"namespace",
")",
"pids",
"=",
"set",
"(",
")",
"cmd",
"=",
"[",
"'netstat'",
",",
"'-nlp'",
"]",
"output",
"=",
"ip",
".",
"... | retrieve a list of pids of listening processes within the given netns . | train | false |
47,625 | def zset_score_pairs(response, **options):
if ((not response) or (not options['withscores'])):
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(response)
return list(izip(it, imap(score_cast_func, it)))
| [
"def",
"zset_score_pairs",
"(",
"response",
",",
"**",
"options",
")",
":",
"if",
"(",
"(",
"not",
"response",
")",
"or",
"(",
"not",
"options",
"[",
"'withscores'",
"]",
")",
")",
":",
"return",
"response",
"score_cast_func",
"=",
"options",
".",
"get",... | if withscores is specified in the options . | train | true |
47,628 | def split_delimited_symbol(symbol):
if (symbol in _delimited_symbol_default_triggers):
return ('', '')
symbol = symbol.upper()
split_list = re.split(pattern=_delimited_symbol_delimiters_regex, string=symbol, maxsplit=1)
company_symbol = split_list[0]
if (len(split_list) > 1):
share_class_symbol = split_list[1]
else:
share_class_symbol = ''
return (company_symbol, share_class_symbol)
| [
"def",
"split_delimited_symbol",
"(",
"symbol",
")",
":",
"if",
"(",
"symbol",
"in",
"_delimited_symbol_default_triggers",
")",
":",
"return",
"(",
"''",
",",
"''",
")",
"symbol",
"=",
"symbol",
".",
"upper",
"(",
")",
"split_list",
"=",
"re",
".",
"split"... | takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol . | train | true |
47,631 | def groupmean_d(x, d):
x = np.asarray(x)
nvars = (x.ndim + 1)
sli = (([slice(None)] + ([None] * (nvars - 2))) + [slice(None)])
return (((x[..., None] * d[sli]).sum(0) * 1.0) / d.sum(0))
| [
"def",
"groupmean_d",
"(",
"x",
",",
"d",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"nvars",
"=",
"(",
"x",
".",
"ndim",
"+",
"1",
")",
"sli",
"=",
"(",
"(",
"[",
"slice",
"(",
"None",
")",
"]",
"+",
"(",
"[",
"None",
"]",
... | groupmeans using dummy variables parameters x : array_like . | train | false |
47,632 | def _get_vnic_manager(host_reference):
return host_reference.configManager.virtualNicManager
| [
"def",
"_get_vnic_manager",
"(",
"host_reference",
")",
":",
"return",
"host_reference",
".",
"configManager",
".",
"virtualNicManager"
] | helper function that returns a list of virtual nicmanagers and their information . | train | false |
47,633 | def _makeHeaderIPv6(sig=V2_SIGNATURE, verCom='!', famProto='!', addrLength='\x00$', addrs=((('\x00' * 15) + '\x01') * 2), ports='\x1f\x90"\xb8'):
return (((((sig + verCom) + famProto) + addrLength) + addrs) + ports)
| [
"def",
"_makeHeaderIPv6",
"(",
"sig",
"=",
"V2_SIGNATURE",
",",
"verCom",
"=",
"'!'",
",",
"famProto",
"=",
"'!'",
",",
"addrLength",
"=",
"'\\x00$'",
",",
"addrs",
"=",
"(",
"(",
"(",
"'\\x00'",
"*",
"15",
")",
"+",
"'\\x01'",
")",
"*",
"2",
")",
... | construct a version 2 ipv6 header with custom bytes . | train | false |
47,635 | def convert_rgb_to_hsv(rgb):
(red, green, blue) = [(_ / BYTE_MAX) for _ in rgb]
(hue, saturation, brightness) = colorsys.rgb_to_hsv(red, green, blue)
return [int((hue * SHORT_MAX)), int((saturation * SHORT_MAX)), int((brightness * SHORT_MAX))]
| [
"def",
"convert_rgb_to_hsv",
"(",
"rgb",
")",
":",
"(",
"red",
",",
"green",
",",
"blue",
")",
"=",
"[",
"(",
"_",
"/",
"BYTE_MAX",
")",
"for",
"_",
"in",
"rgb",
"]",
"(",
"hue",
",",
"saturation",
",",
"brightness",
")",
"=",
"colorsys",
".",
"r... | convert home assistant rgb values to hsv values . | train | false |
47,636 | def table_description():
if (connection.vendor == u'sqlite'):
fields = connection.introspection.get_table_description(connection.cursor(), u'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute(u"\n SELECT column_name\n FROM information_schema.columns\n WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()")
rows = cursor.fetchall()
return [r[0] for r in rows]
| [
"def",
"table_description",
"(",
")",
":",
"if",
"(",
"connection",
".",
"vendor",
"==",
"u'sqlite'",
")",
":",
"fields",
"=",
"connection",
".",
"introspection",
".",
"get_table_description",
"(",
"connection",
".",
"cursor",
"(",
")",
",",
"u'course_overview... | handle mysql/pg vs sqlite . | train | false |
47,638 | def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
available = [a.lower() for a in available if a]
for locale in preferred:
ll = locale.lower()
if (ll in available):
return locale
if aliases:
alias = aliases.get(ll)
if alias:
alias = alias.replace('_', sep)
if (alias.lower() in available):
return alias
parts = locale.split(sep)
if ((len(parts) > 1) and (parts[0].lower() in available)):
return parts[0]
return None
| [
"def",
"negotiate_locale",
"(",
"preferred",
",",
"available",
",",
"sep",
"=",
"'_'",
",",
"aliases",
"=",
"LOCALE_ALIASES",
")",
":",
"available",
"=",
"[",
"a",
".",
"lower",
"(",
")",
"for",
"a",
"in",
"available",
"if",
"a",
"]",
"for",
"locale",
... | find the best match between available and requested locale strings . | train | false |
47,639 | def _isnan(num):
num = str(num).lower()
if (not num):
return 0
sign = 0
if (num[0] == '+'):
num = num[1:]
elif (num[0] == '-'):
num = num[1:]
sign = 1
if num.startswith('nan'):
if ((len(num) > 3) and (not num[3:].isdigit())):
return 0
return (1, sign, num[3:].lstrip('0'))
if num.startswith('snan'):
if ((len(num) > 4) and (not num[4:].isdigit())):
return 0
return (2, sign, num[4:].lstrip('0'))
return 0
| [
"def",
"_isnan",
"(",
"num",
")",
":",
"num",
"=",
"str",
"(",
"num",
")",
".",
"lower",
"(",
")",
"if",
"(",
"not",
"num",
")",
":",
"return",
"0",
"sign",
"=",
"0",
"if",
"(",
"num",
"[",
"0",
"]",
"==",
"'+'",
")",
":",
"num",
"=",
"nu... | determines whether a string or float is nan => nan => snan 0 => not a nan . | train | false |
47,641 | def get_names_from_cert(csr, typ=OpenSSL.crypto.FILETYPE_PEM):
return _get_names_from_cert_or_req(csr, OpenSSL.crypto.load_certificate, typ)
| [
"def",
"get_names_from_cert",
"(",
"csr",
",",
"typ",
"=",
"OpenSSL",
".",
"crypto",
".",
"FILETYPE_PEM",
")",
":",
"return",
"_get_names_from_cert_or_req",
"(",
"csr",
",",
"OpenSSL",
".",
"crypto",
".",
"load_certificate",
",",
"typ",
")"
] | get a list of domains from a cert . | train | false |
47,642 | def parse_mime_headers(doc_file):
headers = []
while True:
line = doc_file.readline()
done = (line in ('\r\n', '\n', ''))
if six.PY3:
try:
line = line.decode('utf-8')
except UnicodeDecodeError:
line = line.decode('latin1')
headers.append(line)
if done:
break
if six.PY3:
header_string = ''.join(headers)
else:
header_string = ''.join(headers)
headers = email.parser.Parser().parsestr(header_string)
return HeaderKeyDict(headers)
| [
"def",
"parse_mime_headers",
"(",
"doc_file",
")",
":",
"headers",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"doc_file",
".",
"readline",
"(",
")",
"done",
"=",
"(",
"line",
"in",
"(",
"'\\r\\n'",
",",
"'\\n'",
",",
"''",
")",
")",
"if",
"s... | takes a file-like object containing a mime document and returns a headerkeydict containing the headers . | train | false |
47,643 | def get_forms_for_user(user):
editable_forms = UserPagePermissionsProxy(user).editable_pages()
editable_forms = editable_forms.filter(content_type__in=get_form_types())
for fn in hooks.get_hooks(u'filter_form_submissions_for_user'):
editable_forms = fn(user, editable_forms)
return editable_forms
| [
"def",
"get_forms_for_user",
"(",
"user",
")",
":",
"editable_forms",
"=",
"UserPagePermissionsProxy",
"(",
"user",
")",
".",
"editable_pages",
"(",
")",
"editable_forms",
"=",
"editable_forms",
".",
"filter",
"(",
"content_type__in",
"=",
"get_form_types",
"(",
"... | return a queryset of form pages that this user is allowed to access the submissions for . | train | false |
47,644 | def scale_to_unit_interval(ndar, eps=1e-08):
ndar = ndar.copy()
ndar -= ndar.min()
ndar *= (1.0 / (ndar.max() + eps))
return ndar
| [
"def",
"scale_to_unit_interval",
"(",
"ndar",
",",
"eps",
"=",
"1e-08",
")",
":",
"ndar",
"=",
"ndar",
".",
"copy",
"(",
")",
"ndar",
"-=",
"ndar",
".",
"min",
"(",
")",
"ndar",
"*=",
"(",
"1.0",
"/",
"(",
"ndar",
".",
"max",
"(",
")",
"+",
"ep... | scales all values in the ndarray ndar to be between 0 and 1 . | train | false |
47,645 | def renew(config, unused_plugins):
try:
renewal.handle_renewal_request(config)
finally:
hooks.run_saved_post_hooks()
| [
"def",
"renew",
"(",
"config",
",",
"unused_plugins",
")",
":",
"try",
":",
"renewal",
".",
"handle_renewal_request",
"(",
"config",
")",
"finally",
":",
"hooks",
".",
"run_saved_post_hooks",
"(",
")"
] | renew previously-obtained certificates . | train | false |
47,647 | def volume_present(name, volume_size, sparse=False, create_parent=False, properties=None, cloned_from=None):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
if (not properties):
properties = {}
log.debug('zfs.volume_present::{0}::config::volume_size = {1}'.format(name, volume_size))
log.debug('zfs.volume_present::{0}::config::sparse = {1}'.format(name, sparse))
log.debug('zfs.volume_present::{0}::config::create_parent = {1}'.format(name, create_parent))
log.debug('zfs.volume_present::{0}::config::cloned_from = {1}'.format(name, cloned_from))
log.debug('zfs.volume_present::{0}::config::properties = {1}'.format(name, properties))
for prop in properties.keys():
if isinstance(properties[prop], bool):
properties[prop] = ('on' if properties[prop] else 'off')
if (('@' in name) or ('#' in name)):
ret['result'] = False
ret['comment'] = 'invalid filesystem or volume name: {0}'.format(name)
if cloned_from:
cloned_parent = cloned_from[:cloned_from.index('@')]
if ('@' not in cloned_from):
ret['result'] = False
ret['comment'] = '{0} is not a snapshot'.format(cloned_from)
elif (cloned_from not in __salt__['zfs.list'](cloned_from, **{'type': 'snapshot'})):
ret['result'] = False
ret['comment'] = 'snapshot {0} does not exist'.format(cloned_from)
elif (cloned_parent not in __salt__['zfs.list'](cloned_parent, **{'type': 'volume'})):
ret['result'] = False
ret['comment'] = 'snapshot {0} is not from a volume'.format(cloned_from)
if ret['result']:
if (name in __salt__['zfs.list'](name, **{'type': 'volume'})):
properties['volsize'] = volume_size
result = __salt__['zfs.get'](name, **{'properties': ','.join(properties.keys()), 'fields': 'value', 'depth': 1})
for prop in properties.keys():
if (properties[prop] != result[name][prop]['value']):
if (name not in ret['changes']):
ret['changes'][name] = {}
ret['changes'][name][prop] = properties[prop]
if (len(ret['changes']) > 0):
if (not __opts__['test']):
result = __salt__['zfs.set'](name, **ret['changes'][name])
if (name not in result):
ret['result'] = False
else:
for prop in result[name].keys():
if (result[name][prop] != 'set'):
ret['result'] = False
if ret['result']:
ret['comment'] = 'volume {0} was updated'.format(name)
else:
ret['changes'] = {}
ret['comment'] = 'volume {0} failed to be updated'.format(name)
else:
ret['comment'] = 'volume {0} is up to date'.format(name)
else:
result = {name: 'created'}
if (not __opts__['test']):
if (not cloned_from):
result = __salt__['zfs.create'](name, **{'volume_size': volume_size, 'sparse': sparse, 'create_parent': create_parent, 'properties': properties})
else:
result = __salt__['zfs.clone'](cloned_from, name, **{'create_parent': create_parent, 'properties': properties})
ret['result'] = (name in result)
if ret['result']:
ret['result'] = ((result[name] == 'created') or result[name].startswith('cloned'))
if ret['result']:
ret['changes'][name] = (properties if (len(properties) > 0) else result[name])
ret['comment'] = 'volume {0} was created'.format(name)
else:
ret['comment'] = 'failed to create volume {0}'.format(name)
if (name in result):
ret['comment'] = result[name]
return ret
| [
"def",
"volume_present",
"(",
"name",
",",
"volume_size",
",",
"sparse",
"=",
"False",
",",
"create_parent",
"=",
"False",
",",
"properties",
"=",
"None",
",",
"cloned_from",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'"... | check that a block volume exists . | train | false |
47,648 | def get_carrier_id():
carrier = get_carrier()
if (carrier is None):
return carrier
for carr in CARRIERS:
if (carr.slug == carrier):
return carr.id
return mkt.constants.carriers.UNKNOWN_CARRIER.id
| [
"def",
"get_carrier_id",
"(",
")",
":",
"carrier",
"=",
"get_carrier",
"(",
")",
"if",
"(",
"carrier",
"is",
"None",
")",
":",
"return",
"carrier",
"for",
"carr",
"in",
"CARRIERS",
":",
"if",
"(",
"carr",
".",
"slug",
"==",
"carrier",
")",
":",
"retu... | returns the carrier id for the request lifecycle . | train | false |
47,650 | def arcball_map_to_sphere(point, center, radius):
v0 = ((point[0] - center[0]) / radius)
v1 = ((center[1] - point[1]) / radius)
n = ((v0 * v0) + (v1 * v1))
if (n > 1.0):
n = math.sqrt(n)
return numpy.array([(v0 / n), (v1 / n), 0.0])
else:
return numpy.array([v0, v1, math.sqrt((1.0 - n))])
| [
"def",
"arcball_map_to_sphere",
"(",
"point",
",",
"center",
",",
"radius",
")",
":",
"v0",
"=",
"(",
"(",
"point",
"[",
"0",
"]",
"-",
"center",
"[",
"0",
"]",
")",
"/",
"radius",
")",
"v1",
"=",
"(",
"(",
"center",
"[",
"1",
"]",
"-",
"point"... | return unit sphere coordinates from window coordinates . | train | true |
47,651 | def arr_dtype_number(arr, num):
return np.dtype((arr.dtype.str[:2] + str(num)))
| [
"def",
"arr_dtype_number",
"(",
"arr",
",",
"num",
")",
":",
"return",
"np",
".",
"dtype",
"(",
"(",
"arr",
".",
"dtype",
".",
"str",
"[",
":",
"2",
"]",
"+",
"str",
"(",
"num",
")",
")",
")"
] | return dtype for given number of items per element . | train | false |
47,652 | def atomic_group_remove_labels(id, labels):
label_objs = models.Label.smart_get_bulk(labels)
models.AtomicGroup.smart_get(id).label_set.remove(*label_objs)
| [
"def",
"atomic_group_remove_labels",
"(",
"id",
",",
"labels",
")",
":",
"label_objs",
"=",
"models",
".",
"Label",
".",
"smart_get_bulk",
"(",
"labels",
")",
"models",
".",
"AtomicGroup",
".",
"smart_get",
"(",
"id",
")",
".",
"label_set",
".",
"remove",
... | remove labels from atomic group . | train | false |
47,653 | def HandleCommandLine(cls, serviceClassString=None, argv=None, customInstallOptions='', customOptionHandler=None):
err = 0
if (argv is None):
argv = sys.argv
if (len(argv) <= 1):
usage()
serviceName = cls._svc_name_
serviceDisplayName = cls._svc_display_name_
if (serviceClassString is None):
serviceClassString = GetServiceClassString(cls)
import getopt
try:
(opts, args) = getopt.getopt(argv[1:], customInstallOptions, ['password=', 'username=', 'startup=', 'perfmonini=', 'perfmondll=', 'interactive', 'wait='])
except getopt.error as details:
print details
usage()
userName = None
password = None
perfMonIni = perfMonDll = None
startup = None
interactive = None
waitSecs = 0
for (opt, val) in opts:
if (opt == '--username'):
userName = val
elif (opt == '--password'):
password = val
elif (opt == '--perfmonini'):
perfMonIni = val
elif (opt == '--perfmondll'):
perfMonDll = val
elif (opt == '--interactive'):
interactive = 1
elif (opt == '--startup'):
map = {'manual': win32service.SERVICE_DEMAND_START, 'auto': win32service.SERVICE_AUTO_START, 'disabled': win32service.SERVICE_DISABLED}
try:
startup = map[val.lower()]
except KeyError:
print ("'%s' is not a valid startup option" % val)
elif (opt == '--wait'):
try:
waitSecs = int(val)
except ValueError:
print '--wait must specify an integer number of seconds.'
usage()
arg = args[0]
knownArg = 0
if (arg == 'start'):
knownArg = 1
print ('Starting service %s' % serviceName)
try:
StartService(serviceName, args[1:])
if waitSecs:
WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
except win32service.error as exc:
print ('Error starting service: %s' % exc.strerror)
elif (arg == 'restart'):
knownArg = 1
print ('Restarting service %s' % serviceName)
RestartService(serviceName, args[1:])
if waitSecs:
WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
elif (arg == 'debug'):
knownArg = 1
if (not hasattr(sys, 'frozen')):
svcArgs = ' '.join(args[1:])
try:
exeName = LocateSpecificServiceExe(serviceName)
except win32api.error as exc:
if (exc[0] == winerror.ERROR_FILE_NOT_FOUND):
print 'The service does not appear to be installed.'
print 'Please install the service before debugging it.'
sys.exit(1)
raise
try:
os.system(('%s -debug %s %s' % (exeName, serviceName, svcArgs)))
except KeyboardInterrupt:
pass
else:
DebugService(cls, args)
if ((not knownArg) and (len(args) != 1)):
usage()
if (arg == 'install'):
knownArg = 1
try:
serviceDeps = cls._svc_deps_
except AttributeError:
serviceDeps = None
try:
exeName = cls._exe_name_
except AttributeError:
exeName = None
try:
exeArgs = cls._exe_args_
except AttributeError:
exeArgs = None
try:
description = cls._svc_description_
except AttributeError:
description = None
print ('Installing service %s' % (serviceName,))
try:
InstallService(serviceClassString, serviceName, serviceDisplayName, serviceDeps=serviceDeps, startType=startup, bRunInteractive=interactive, userName=userName, password=password, exeName=exeName, perfMonIni=perfMonIni, perfMonDll=perfMonDll, exeArgs=exeArgs, description=description)
if customOptionHandler:
customOptionHandler(*(opts,))
print 'Service installed'
except win32service.error as exc:
if (exc.winerror == winerror.ERROR_SERVICE_EXISTS):
arg = 'update'
else:
print ('Error installing service: %s (%d)' % (exc.strerror, exc.winerror))
err = exc.winerror
except ValueError as msg:
print ('Error installing service: %s' % str(msg))
err = (-1)
try:
RemoveService(serviceName)
except win32api.error:
print 'Warning - could not remove the partially installed service.'
if (arg == 'update'):
knownArg = 1
try:
serviceDeps = cls._svc_deps_
except AttributeError:
serviceDeps = None
try:
exeName = cls._exe_name_
except AttributeError:
exeName = None
try:
exeArgs = cls._exe_args_
except AttributeError:
exeArgs = None
try:
description = cls._svc_description_
except AttributeError:
description = None
print 'Changing service configuration'
try:
ChangeServiceConfig(serviceClassString, serviceName, serviceDeps=serviceDeps, startType=startup, bRunInteractive=interactive, userName=userName, password=password, exeName=exeName, displayName=serviceDisplayName, perfMonIni=perfMonIni, perfMonDll=perfMonDll, exeArgs=exeArgs, description=description)
if customOptionHandler:
customOptionHandler(*(opts,))
print 'Service updated'
except win32service.error as exc:
print ('Error changing service configuration: %s (%d)' % (exc.strerror, exc.winerror))
err = exc.winerror
elif (arg == 'remove'):
knownArg = 1
print ('Removing service %s' % serviceName)
try:
RemoveService(serviceName)
print 'Service removed'
except win32service.error as exc:
print ('Error removing service: %s (%d)' % (exc.strerror, exc.winerror))
err = exc.winerror
elif (arg == 'stop'):
knownArg = 1
print ('Stopping service %s' % serviceName)
try:
if waitSecs:
StopServiceWithDeps(serviceName, waitSecs=waitSecs)
else:
StopService(serviceName)
except win32service.error as exc:
print ('Error stopping service: %s (%d)' % (exc.strerror, exc.winerror))
err = exc.winerror
if (not knownArg):
err = (-1)
print ("Unknown command - '%s'" % arg)
usage()
return err
| [
"def",
"HandleCommandLine",
"(",
"cls",
",",
"serviceClassString",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"customInstallOptions",
"=",
"''",
",",
"customOptionHandler",
"=",
"None",
")",
":",
"err",
"=",
"0",
"if",
"(",
"argv",
"is",
"None",
")",
":... | handle command line for a windows service prescribed name that will be called by py2exe . | train | false |
47,655 | def _kde_support(data, bw, gridsize, cut, clip):
support_min = max((data.min() - (bw * cut)), clip[0])
support_max = min((data.max() + (bw * cut)), clip[1])
return np.linspace(support_min, support_max, gridsize)
| [
"def",
"_kde_support",
"(",
"data",
",",
"bw",
",",
"gridsize",
",",
"cut",
",",
"clip",
")",
":",
"support_min",
"=",
"max",
"(",
"(",
"data",
".",
"min",
"(",
")",
"-",
"(",
"bw",
"*",
"cut",
")",
")",
",",
"clip",
"[",
"0",
"]",
")",
"supp... | establish support for a kernel density estimate . | train | false |
47,656 | def write_config(config, path, variables=None):
f = file(path, 'w')
try:
f.write('<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>\n<configuration>\n')
keys = ((variables and (variables,)) or (config.keys(),))[0]
for name in keys:
value = config[name]
f.write(' <property>\n')
f.write((' <name>%s</name>\n' % name))
f.write((' <value>%s</value>\n' % value))
f.write(' </property>\n')
f.write('</configuration>\n')
finally:
f.close()
| [
"def",
"write_config",
"(",
"config",
",",
"path",
",",
"variables",
"=",
"None",
")",
":",
"f",
"=",
"file",
"(",
"path",
",",
"'w'",
")",
"try",
":",
"f",
".",
"write",
"(",
"'<?xml version=\"1.0\"?>\\n<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\... | minimal utility to write hadoop-style configuration from a configuration map . | train | false |
47,657 | def InitSecretsForTest():
GetSharedSecretsManager(can_prompt=False)
| [
"def",
"InitSecretsForTest",
"(",
")",
":",
"GetSharedSecretsManager",
"(",
"can_prompt",
"=",
"False",
")"
] | init secrets for test . | train | false |
47,658 | def URLFreqRespTime(urlstatsdict):
resptime = []
binner = _ExponentialBinner(10, 2)
maxbins = 0
for (url, urlstats) in urlstatsdict.iteritems():
urlresptime = sorted(urlstats.GetResponseTimeList())
urlbin = binner.Bin(urlresptime)
maxbins = max(maxbins, len(urlbin))
resptime.append((url, urlresptime, urlbin))
resptime.sort(key=(lambda triple: len(triple[1])), reverse=True)
intervals = binner.Intervals(maxbins)
return (resptime, intervals)
| [
"def",
"URLFreqRespTime",
"(",
"urlstatsdict",
")",
":",
"resptime",
"=",
"[",
"]",
"binner",
"=",
"_ExponentialBinner",
"(",
"10",
",",
"2",
")",
"maxbins",
"=",
"0",
"for",
"(",
"url",
",",
"urlstats",
")",
"in",
"urlstatsdict",
".",
"iteritems",
"(",
... | computes request counts in different response time ranges for histograms . | train | false |
47,659 | def exec_payload(shell_obj, payload_name, args=(), use_api=False):
payload_inst = get_payload_instance(payload_name, shell_obj)
if use_api:
result = payload_inst.run_api(*args)
else:
result = payload_inst.run(*args)
return result
| [
"def",
"exec_payload",
"(",
"shell_obj",
",",
"payload_name",
",",
"args",
"=",
"(",
")",
",",
"use_api",
"=",
"False",
")",
":",
"payload_inst",
"=",
"get_payload_instance",
"(",
"payload_name",
",",
"shell_obj",
")",
"if",
"use_api",
":",
"result",
"=",
... | now i execute the payload . | train | false |
47,661 | def remove_indents(txt):
txt = re.sub('(?miu)^\\s+', '', txt)
return txt
| [
"def",
"remove_indents",
"(",
"txt",
")",
":",
"txt",
"=",
"re",
".",
"sub",
"(",
"'(?miu)^\\\\s+'",
",",
"''",
",",
"txt",
")",
"return",
"txt"
] | remove whitespace at the beginning of each line . | train | false |
47,662 | def rand_uuid():
return uuidutils.generate_uuid()
| [
"def",
"rand_uuid",
"(",
")",
":",
"return",
"uuidutils",
".",
"generate_uuid",
"(",
")"
] | generate a random uuid string :return: a random uuid :rtype: string . | train | false |
47,663 | def duck_type_collection(specimen, default=None):
if hasattr(specimen, '__emulates__'):
if ((specimen.__emulates__ is not None) and issubclass(specimen.__emulates__, set)):
return set
else:
return specimen.__emulates__
isa = ((isinstance(specimen, type) and issubclass) or isinstance)
if isa(specimen, list):
return list
elif isa(specimen, set):
return set
elif isa(specimen, dict):
return dict
if hasattr(specimen, 'append'):
return list
elif hasattr(specimen, 'add'):
return set
elif hasattr(specimen, 'set'):
return dict
else:
return default
| [
"def",
"duck_type_collection",
"(",
"specimen",
",",
"default",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"specimen",
",",
"'__emulates__'",
")",
":",
"if",
"(",
"(",
"specimen",
".",
"__emulates__",
"is",
"not",
"None",
")",
"and",
"issubclass",
"(",
... | given an instance or class . | train | false |
47,664 | def BuildToken(request, execution_time):
token = access_control.ACLToken(username=request.user, reason=request.REQ.get('reason', ''), process='GRRAdminUI', expiry=(rdfvalue.RDFDatetime.Now() + execution_time))
for field in ['REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR']:
remote_addr = request.META.get(field, '')
if remote_addr:
token.source_ips.append(remote_addr)
return token
| [
"def",
"BuildToken",
"(",
"request",
",",
"execution_time",
")",
":",
"token",
"=",
"access_control",
".",
"ACLToken",
"(",
"username",
"=",
"request",
".",
"user",
",",
"reason",
"=",
"request",
".",
"REQ",
".",
"get",
"(",
"'reason'",
",",
"''",
")",
... | build an acltoken from the request . | train | false |
47,665 | def update_order_line_from_product(pricing_context, order_line, product, quantity=1, supplier=None):
if order_line.pk:
raise Exception('set_from_product may not be used on saved lines')
if (not product):
raise Exception('set_from_product may not be used without product')
order_line.supplier = supplier
order_line.type = OrderLineType.PRODUCT
order_line.product = product
order_line.quantity = quantity
order_line.sku = product.sku
order_line.text = (product.safe_translation_getter('name') or product.sku)
order_line.accounting_identifier = product.accounting_identifier
order_line.require_verification = bool(getattr(product, 'require_verification', False))
order_line.verified = False
if pricing_context:
price_info = product.get_price_info(pricing_context, quantity=quantity)
order_line.base_unit_price = price_info.base_unit_price
order_line.discount_amount = price_info.discount_amount
assert (order_line.price == price_info.price)
else:
order_line.base_unit_price_value = 0
order_line.discount_amount_value = 0
| [
"def",
"update_order_line_from_product",
"(",
"pricing_context",
",",
"order_line",
",",
"product",
",",
"quantity",
"=",
"1",
",",
"supplier",
"=",
"None",
")",
":",
"if",
"order_line",
".",
"pk",
":",
"raise",
"Exception",
"(",
"'set_from_product may not be used... | update orderline data from a product . | train | false |
47,668 | def _get_numba_ufunc(expr):
if isinstance(expr, Broadcast):
leaves = expr._scalars
expr = expr._scalar_expr
else:
leaves = expr._leaves()
(s, scope) = funcstr(leaves, expr)
scope = dict(((k, (numba.jit(nopython=True)(v) if callable(v) else v)) for (k, v) in scope.items()))
func = eval(s, scope)
sig = compute_signature(expr)
with lock:
ufunc = numba.vectorize([sig], nopython=True)(func)
return ufunc
| [
"def",
"_get_numba_ufunc",
"(",
"expr",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"Broadcast",
")",
":",
"leaves",
"=",
"expr",
".",
"_scalars",
"expr",
"=",
"expr",
".",
"_scalar_expr",
"else",
":",
"leaves",
"=",
"expr",
".",
"_leaves",
"(",
")... | construct a numba ufunc from a blaze expression parameters expr : blaze . | train | false |
47,669 | def write_double_matrix(fid, kind, mat):
FIFFT_MATRIX = (1 << 30)
FIFFT_MATRIX_DOUBLE = (FIFF.FIFFT_DOUBLE | FIFFT_MATRIX)
data_size = ((8 * mat.size) + (4 * (mat.ndim + 1)))
fid.write(np.array(kind, dtype='>i4').tostring())
fid.write(np.array(FIFFT_MATRIX_DOUBLE, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tostring())
fid.write(np.array(mat, dtype='>f8').tostring())
dims = np.empty((mat.ndim + 1), dtype=np.int32)
dims[:mat.ndim] = mat.shape[::(-1)]
dims[(-1)] = mat.ndim
fid.write(np.array(dims, dtype='>i4').tostring())
check_fiff_length(fid)
| [
"def",
"write_double_matrix",
"(",
"fid",
",",
"kind",
",",
"mat",
")",
":",
"FIFFT_MATRIX",
"=",
"(",
"1",
"<<",
"30",
")",
"FIFFT_MATRIX_DOUBLE",
"=",
"(",
"FIFF",
".",
"FIFFT_DOUBLE",
"|",
"FIFFT_MATRIX",
")",
"data_size",
"=",
"(",
"(",
"8",
"*",
"... | write a double-precision floating-point matrix tag . | train | false |
47,670 | def fix_index(builder, idx, size):
is_negative = builder.icmp_signed('<', idx, ir.Constant(size.type, 0))
wrapped_index = builder.add(idx, size)
return builder.select(is_negative, wrapped_index, idx)
| [
"def",
"fix_index",
"(",
"builder",
",",
"idx",
",",
"size",
")",
":",
"is_negative",
"=",
"builder",
".",
"icmp_signed",
"(",
"'<'",
",",
"idx",
",",
"ir",
".",
"Constant",
"(",
"size",
".",
"type",
",",
"0",
")",
")",
"wrapped_index",
"=",
"builder... | fix negative index by adding *size* to it . | train | false |
47,671 | def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None):
if name:
log.warning('boto_vpc.route_table_exists: name parameter is deprecated use route_table_name instead.')
route_table_name = name
return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
| [
"def",
"route_table_exists",
"(",
"route_table_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"route_table_name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"... | checks if a route table exists . | train | true |
47,672 | def HTML(html):
return markupsafe.Markup(html)
| [
"def",
"HTML",
"(",
"html",
")",
":",
"return",
"markupsafe",
".",
"Markup",
"(",
"html",
")"
] | mark a string as already html . | train | false |
47,673 | def rm_r(path):
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
unlink(path)
| [
"def",
"rm_r",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"unlink",
"(",
"path",
")"
] | like rm -r command . | train | false |
47,674 | def volume_type_extra_specs_update_or_create(context, volume_type_id, extra_specs):
IMPL.volume_type_extra_specs_update_or_create(context, volume_type_id, extra_specs)
| [
"def",
"volume_type_extra_specs_update_or_create",
"(",
"context",
",",
"volume_type_id",
",",
"extra_specs",
")",
":",
"IMPL",
".",
"volume_type_extra_specs_update_or_create",
"(",
"context",
",",
"volume_type_id",
",",
"extra_specs",
")"
] | create or update volume type extra specs . | train | false |
47,677 | def _xfs_prune_output(out, uuid):
data = {}
cnt = []
cutpoint = False
for line in [l.strip() for l in out.split('\n') if l]:
if line.startswith('-'):
if cutpoint:
break
else:
cutpoint = True
continue
if cutpoint:
cnt.append(line)
for kset in [e for e in cnt[1:] if (':' in e)]:
(key, val) = [t.strip() for t in kset.split(':', 1)]
data[key.lower().replace(' ', '_')] = val
return (((data.get('uuid') == uuid) and data) or {})
| [
"def",
"_xfs_prune_output",
"(",
"out",
",",
"uuid",
")",
":",
"data",
"=",
"{",
"}",
"cnt",
"=",
"[",
"]",
"cutpoint",
"=",
"False",
"for",
"line",
"in",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"out",
".",
"split",
"(",
"'\\n'",
")... | parse prune output . | train | true |
47,680 | def channel_session_user_from_http(func):
@http_session_user
@channel_session
@functools.wraps(func)
def inner(message, *args, **kwargs):
if (message.http_session is not None):
transfer_user(message.http_session, message.channel_session)
return func(message, *args, **kwargs)
return inner
| [
"def",
"channel_session_user_from_http",
"(",
"func",
")",
":",
"@",
"http_session_user",
"@",
"channel_session",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"message",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
... | decorator that automatically transfers the user from http sessions to channel-based sessions . | train | false |
47,683 | def install_thread_excepthook():
import sys
run_old = Thread.run
def run(*args, **kwargs):
try:
run_old(*args, **kwargs)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.excepthook(*sys.exc_info())
Thread.run = run
| [
"def",
"install_thread_excepthook",
"(",
")",
":",
"import",
"sys",
"run_old",
"=",
"Thread",
".",
"run",
"def",
"run",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"run_old",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"(",... | workaround for sys . | train | false |
47,684 | def get_dataset_root():
return _dataset_root
| [
"def",
"get_dataset_root",
"(",
")",
":",
"return",
"_dataset_root"
] | gets the path to the root directory to download and cache datasets . | train | false |
47,685 | def _dict_from_tcltuple(ttuple, cut_minus=True):
opt_start = (1 if cut_minus else 0)
retdict = {}
it = iter(ttuple)
for (opt, val) in zip(it, it):
retdict[str(opt)[opt_start:]] = val
return tclobjs_to_py(retdict)
| [
"def",
"_dict_from_tcltuple",
"(",
"ttuple",
",",
"cut_minus",
"=",
"True",
")",
":",
"opt_start",
"=",
"(",
"1",
"if",
"cut_minus",
"else",
"0",
")",
"retdict",
"=",
"{",
"}",
"it",
"=",
"iter",
"(",
"ttuple",
")",
"for",
"(",
"opt",
",",
"val",
"... | break tuple in pairs . | train | false |
47,687 | def colordiff(a, b, highlight='text_highlight'):
if config['ui']['color']:
return _colordiff(a, b, highlight)
else:
return (six.text_type(a), six.text_type(b))
| [
"def",
"colordiff",
"(",
"a",
",",
"b",
",",
"highlight",
"=",
"'text_highlight'",
")",
":",
"if",
"config",
"[",
"'ui'",
"]",
"[",
"'color'",
"]",
":",
"return",
"_colordiff",
"(",
"a",
",",
"b",
",",
"highlight",
")",
"else",
":",
"return",
"(",
... | colorize differences between two values if color is enabled . | train | false |
47,688 | def _select_vs(v, p):
if (v >= 120.0):
return (60, 120, inf)
elif (v >= 60.0):
return (40, 60, 120)
elif (v >= 40.0):
return (30, 40, 60)
elif (v >= 30.0):
return (24, 30, 40)
elif (v >= 24.0):
return (20, 24, 30)
elif (v >= 19.5):
return (19, 20, 24)
if (p >= 0.9):
if (v < 2.5):
return (1, 2, 3)
elif (v < 3.5):
return (2, 3, 4)
vi = int(round(v))
return ((vi - 1), vi, (vi + 1))
| [
"def",
"_select_vs",
"(",
"v",
",",
"p",
")",
":",
"if",
"(",
"v",
">=",
"120.0",
")",
":",
"return",
"(",
"60",
",",
"120",
",",
"inf",
")",
"elif",
"(",
"v",
">=",
"60.0",
")",
":",
"return",
"(",
"40",
",",
"60",
",",
"120",
")",
"elif",... | returns the points to use for interpolating v . | train | true |
47,693 | def get_account_name(account_type=None, root_type=None, is_group=None, account_currency=None, company=None):
return frappe.db.get_value(u'Account', {u'account_type': (account_type or u''), u'root_type': (root_type or u''), u'is_group': (is_group or 0), u'account_currency': (account_currency or frappe.defaults.get_defaults().currency), u'company': (company or frappe.defaults.get_defaults().company)}, u'name')
| [
"def",
"get_account_name",
"(",
"account_type",
"=",
"None",
",",
"root_type",
"=",
"None",
",",
"is_group",
"=",
"None",
",",
"account_currency",
"=",
"None",
",",
"company",
"=",
"None",
")",
":",
"return",
"frappe",
".",
"db",
".",
"get_value",
"(",
"... | return account based on matching conditions . | train | false |
47,694 | @login_required
def choose_transcripts(request):
response = {'status': 'Error', 'subs': ''}
try:
(data, videos, item) = _validate_transcripts_data(request)
except TranscriptsRequestValidationException as e:
return error_response(response, e.message)
html5_id = data.get('html5_id')
html5_id_to_remove = [x for x in videos['html5'] if (x != html5_id)]
if html5_id_to_remove:
remove_subs_from_store(html5_id_to_remove, item)
if (item.sub != html5_id):
item.sub = html5_id
item.save_with_metadata(request.user)
response = {'status': 'Success', 'subs': item.sub}
return JsonResponse(response)
| [
"@",
"login_required",
"def",
"choose_transcripts",
"(",
"request",
")",
":",
"response",
"=",
"{",
"'status'",
":",
"'Error'",
",",
"'subs'",
":",
"''",
"}",
"try",
":",
"(",
"data",
",",
"videos",
",",
"item",
")",
"=",
"_validate_transcripts_data",
"(",... | replaces html5 subtitles . | train | false |
47,697 | def test_no_data_with_empty_series(Chart):
chart = Chart()
chart.add('Serie1', [])
chart.add('Serie2', [])
q = chart.render_pyquery()
assert (q('.text-overlay text').text() == 'No data')
| [
"def",
"test_no_data_with_empty_series",
"(",
"Chart",
")",
":",
"chart",
"=",
"Chart",
"(",
")",
"chart",
".",
"add",
"(",
"'Serie1'",
",",
"[",
"]",
")",
"chart",
".",
"add",
"(",
"'Serie2'",
",",
"[",
"]",
")",
"q",
"=",
"chart",
".",
"render_pyqu... | test no data for 2 empty series . | train | false |
47,699 | def evaluate_template(text, install_environment):
return Template(text).safe_substitute(get_env_var_values(install_environment))
| [
"def",
"evaluate_template",
"(",
"text",
",",
"install_environment",
")",
":",
"return",
"Template",
"(",
"text",
")",
".",
"safe_substitute",
"(",
"get_env_var_values",
"(",
"install_environment",
")",
")"
] | substitute variables defined in xml blocks from dependencies file . | train | false |
47,700 | def to_hex(num):
if (num < 0):
return ('-0x%x' % (- num))
else:
return ('0x%x' % num)
| [
"def",
"to_hex",
"(",
"num",
")",
":",
"if",
"(",
"num",
"<",
"0",
")",
":",
"return",
"(",
"'-0x%x'",
"%",
"(",
"-",
"num",
")",
")",
"else",
":",
"return",
"(",
"'0x%x'",
"%",
"num",
")"
] | convert c to a hex color . | train | false |
47,701 | def read_mri_cfg(subject, subjects_dir=None):
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg')
if (not os.path.exists(fname)):
raise IOError(('%r does not seem to be a scaled mri subject: %r does not exist.' % (subject, fname)))
logger.info(('Reading MRI cfg file %s' % fname))
config = configparser.RawConfigParser()
config.read(fname)
n_params = config.getint('MRI Scaling', 'n_params')
if (n_params == 1):
scale = config.getfloat('MRI Scaling', 'scale')
elif (n_params == 3):
scale_str = config.get('MRI Scaling', 'scale')
scale = np.array([float(s) for s in scale_str.split()])
else:
raise ValueError(('Invalid n_params value in MRI cfg: %i' % n_params))
out = {'subject_from': config.get('MRI Scaling', 'subject_from'), 'n_params': n_params, 'scale': scale}
return out
| [
"def",
"read_mri_cfg",
"(",
"subject",
",",
"subjects_dir",
"=",
"None",
")",
":",
"subjects_dir",
"=",
"get_subjects_dir",
"(",
"subjects_dir",
",",
"raise_error",
"=",
"True",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"subjects_dir",
",",
"... | read information from the cfg file of a scaled mri brain . | train | false |
47,704 | def _sanitize_text_helper(text, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X'):
out = []
for c in text:
if (c in valid_characters):
out.append(c)
elif (c in character_map):
out.append(character_map[c])
else:
out.append(invalid_character)
return ''.join(out)
| [
"def",
"_sanitize_text_helper",
"(",
"text",
",",
"valid_characters",
"=",
"valid_chars",
",",
"character_map",
"=",
"mapped_chars",
",",
"invalid_character",
"=",
"'X'",
")",
":",
"out",
"=",
"[",
"]",
"for",
"c",
"in",
"text",
":",
"if",
"(",
"c",
"in",
... | restricts the characters that are allowed in a string . | train | false |
47,706 | def get_image_download_script(caller):
if (caller == 'iplot'):
check_start = "if(document.readyState == 'complete') {{"
check_end = '}}'
elif (caller == 'plot'):
check_start = ''
check_end = ''
else:
raise ValueError('caller should only be one of `iplot` or `plot`')
return (((("<script>function downloadimage(format, height, width, filename) {{var p = document.getElementById('{plot_id}');Plotly.downloadImage(p, {{format: format, height: height, width: width, filename: filename}});}};" + check_start) + "{{downloadimage('{format}', {height}, {width}, '{filename}');}}") + check_end) + '</script>')
| [
"def",
"get_image_download_script",
"(",
"caller",
")",
":",
"if",
"(",
"caller",
"==",
"'iplot'",
")",
":",
"check_start",
"=",
"\"if(document.readyState == 'complete') {{\"",
"check_end",
"=",
"'}}'",
"elif",
"(",
"caller",
"==",
"'plot'",
")",
":",
"check_start... | this function will return a script that will download an image of a plotly plot . | train | false |
47,707 | def _name(expr):
if (expr in name_dict):
return name_dict[expr]
result = base = (expr._name or '_')
if (result in seen_names):
for i in itertools.count(1):
result = ('%s_%d' % (base, i))
if (result not in seen_names):
break
seen_names.add(result)
name_dict[expr] = result
return result
| [
"def",
"_name",
"(",
"expr",
")",
":",
"if",
"(",
"expr",
"in",
"name_dict",
")",
":",
"return",
"name_dict",
"[",
"expr",
"]",
"result",
"=",
"base",
"=",
"(",
"expr",
".",
"_name",
"or",
"'_'",
")",
"if",
"(",
"result",
"in",
"seen_names",
")",
... | a unique and deterministic name for an expression . | train | false |
47,708 | def _to_camel_case(label, divider='_', joiner=' '):
words = []
for entry in label.split(divider):
if (len(entry) == 0):
words.append('')
elif (len(entry) == 1):
words.append(entry.upper())
else:
words.append((entry[0].upper() + entry[1:].lower()))
return joiner.join(words)
| [
"def",
"_to_camel_case",
"(",
"label",
",",
"divider",
"=",
"'_'",
",",
"joiner",
"=",
"' '",
")",
":",
"words",
"=",
"[",
"]",
"for",
"entry",
"in",
"label",
".",
"split",
"(",
"divider",
")",
":",
"if",
"(",
"len",
"(",
"entry",
")",
"==",
"0",... | converts the given string to camel case . | train | false |
47,709 | def _read_volume_info(fobj):
volume_info = dict()
head = np.fromfile(fobj, '>i4', 1)
if (not np.array_equal(head, [20])):
head = np.concatenate([head, np.fromfile(fobj, '>i4', 2)])
if (not np.array_equal(head, [2, 0, 20])):
warnings.warn('Unknown extension code.')
return volume_info
volume_info['head'] = head
for key in ['valid', 'filename', 'volume', 'voxelsize', 'xras', 'yras', 'zras', 'cras']:
pair = fobj.readline().decode('utf-8').split('=')
if ((pair[0].strip() != key) or (len(pair) != 2)):
raise IOError('Error parsing volume info.')
if (key in ('valid', 'filename')):
volume_info[key] = pair[1].strip()
elif (key == 'volume'):
volume_info[key] = np.array(pair[1].split()).astype(int)
else:
volume_info[key] = np.array(pair[1].split()).astype(float)
return volume_info
| [
"def",
"_read_volume_info",
"(",
"fobj",
")",
":",
"volume_info",
"=",
"dict",
"(",
")",
"head",
"=",
"np",
".",
"fromfile",
"(",
"fobj",
",",
"'>i4'",
",",
"1",
")",
"if",
"(",
"not",
"np",
".",
"array_equal",
"(",
"head",
",",
"[",
"20",
"]",
"... | an implementation of nibabel . | train | false |
47,711 | def json_method(method):
def wrapper(self, url, params=NoDefault, **kw):
content_type = 'application/json'
if (params is not NoDefault):
params = dumps(params, cls=self.JSONEncoder)
kw.update(params=params, content_type=content_type, upload_files=None)
return self._gen_request(method, url, **kw)
subst = dict(lmethod=method.lower(), method=method)
wrapper.__doc__ = (json_method.__doc__ % subst)
wrapper.__name__ = str(('%(lmethod)s_json' % subst))
return wrapper
| [
"def",
"json_method",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"url",
",",
"params",
"=",
"NoDefault",
",",
"**",
"kw",
")",
":",
"content_type",
"=",
"'application/json'",
"if",
"(",
"params",
"is",
"not",
"NoDefault",
")",
":",
"p... | do a %s request . | train | false |
47,712 | def extendedMeasurementReport():
a = TpPd(pd=6)
b = MessageType(mesType=54)
c = ExtendedMeasurementResults()
packet = ((a / b) / c)
return packet
| [
"def",
"extendedMeasurementReport",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"54",
")",
"c",
"=",
"ExtendedMeasurementResults",
"(",
")",
"packet",
"=",
"(",
"(",
"a",
"/",
"b",
")",
"... | extended measurement report section 9 . | train | true |
47,713 | @core_helper
def remove_url_param(key, value=None, replace=None, controller=None, action=None, extras=None, alternative_url=None):
if isinstance(key, basestring):
keys = [key]
else:
keys = key
params_nopage = [(k, v) for (k, v) in request.params.items() if (k != 'page')]
params = list(params_nopage)
if value:
params.remove((keys[0], value))
else:
for key in keys:
[params.remove((k, v)) for (k, v) in params[:] if (k == key)]
if (replace is not None):
params.append((keys[0], replace))
if alternative_url:
return _url_with_params(alternative_url, params)
return _create_url_with_params(params=params, controller=controller, action=action, extras=extras)
| [
"@",
"core_helper",
"def",
"remove_url_param",
"(",
"key",
",",
"value",
"=",
"None",
",",
"replace",
"=",
"None",
",",
"controller",
"=",
"None",
",",
"action",
"=",
"None",
",",
"extras",
"=",
"None",
",",
"alternative_url",
"=",
"None",
")",
":",
"i... | remove one or multiple keys from the current parameters . | train | false |
47,714 | def sync_role_definitions():
logging.info(u'Syncing role definition')
get_or_create_main_db()
create_custom_permissions()
pvms = db.session.query(ab_models.PermissionView).all()
pvms = [p for p in pvms if (p.permission and p.view_menu)]
pvms_to_delete = [p for p in pvms if (not (p.permission and p.view_menu))]
for pvm_to_delete in pvms_to_delete:
sm.get_session.delete(pvm_to_delete)
set_role(u'Admin', pvms, is_admin_pvm)
set_role(u'Alpha', pvms, is_alpha_pvm)
set_role(u'Gamma', pvms, is_gamma_pvm)
set_role(u'granter', pvms, is_granter_pvm)
set_role(u'sql_lab', pvms, is_sql_lab_pvm)
if conf.get(u'PUBLIC_ROLE_LIKE_GAMMA', False):
set_role(u'Public', pvms, is_gamma_pvm)
view_menu_set = db.session.query(models.SqlaTable).all()
create_missing_datasource_perms(view_menu_set)
create_missing_database_perms(view_menu_set)
create_missing_metrics_perm(view_menu_set)
sm.get_session.commit()
| [
"def",
"sync_role_definitions",
"(",
")",
":",
"logging",
".",
"info",
"(",
"u'Syncing role definition'",
")",
"get_or_create_main_db",
"(",
")",
"create_custom_permissions",
"(",
")",
"pvms",
"=",
"db",
".",
"session",
".",
"query",
"(",
"ab_models",
".",
"Perm... | inits the superset application with security roles and such . | train | false |
47,717 | def get_modal_alert(browser):
WebDriverWait(browser, 6).until(EC.alert_is_present())
return browser.switch_to.alert
| [
"def",
"get_modal_alert",
"(",
"browser",
")",
":",
"WebDriverWait",
"(",
"browser",
",",
"6",
")",
".",
"until",
"(",
"EC",
".",
"alert_is_present",
"(",
")",
")",
"return",
"browser",
".",
"switch_to",
".",
"alert"
] | returns instance of modal alert box shown in browser after waiting for 6 seconds . | train | false |
47,718 | @error.context_aware
def vg_create(vg_name, pv_list, force=False):
error.context(("Creating volume group '%s' by using '%s'" % (vg_name, pv_list)), logging.info)
if vg_check(vg_name):
raise error.TestError(("Volume group '%s' already exist" % vg_name))
if force:
cmd = 'vgcreate -f'
else:
cmd = 'vgcreate'
cmd += (' %s %s' % (vg_name, pv_list))
result = utils.run(cmd)
logging.info(result.stdout.rstrip())
| [
"@",
"error",
".",
"context_aware",
"def",
"vg_create",
"(",
"vg_name",
",",
"pv_list",
",",
"force",
"=",
"False",
")",
":",
"error",
".",
"context",
"(",
"(",
"\"Creating volume group '%s' by using '%s'\"",
"%",
"(",
"vg_name",
",",
"pv_list",
")",
")",
",... | create a volume group by using the block special devices . | train | false |
47,719 | def url_to_path(url):
assert url.startswith('file:'), ('You can only turn file: urls into filenames (not %r)' % url)
(_, netloc, path, _, _) = urllib_parse.urlsplit(url)
if netloc:
netloc = ('\\\\' + netloc)
path = urllib_request.url2pathname((netloc + path))
return path
| [
"def",
"url_to_path",
"(",
"url",
")",
":",
"assert",
"url",
".",
"startswith",
"(",
"'file:'",
")",
",",
"(",
"'You can only turn file: urls into filenames (not %r)'",
"%",
"url",
")",
"(",
"_",
",",
"netloc",
",",
"path",
",",
"_",
",",
"_",
")",
"=",
... | convert a file: url to a path . | train | true |
47,720 | def delete_subscription(topic_name, subscription_name):
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
subscription = topic.subscription(subscription_name)
subscription.delete()
print 'Subscription {} deleted on topic {}.'.format(subscription.name, topic.name)
| [
"def",
"delete_subscription",
"(",
"topic_name",
",",
"subscription_name",
")",
":",
"pubsub_client",
"=",
"pubsub",
".",
"Client",
"(",
")",
"topic",
"=",
"pubsub_client",
".",
"topic",
"(",
"topic_name",
")",
"subscription",
"=",
"topic",
".",
"subscription",
... | deletes an existing pub/sub topic . | train | false |
47,721 | def get_temp_file_path(file_path):
return (file_path + '.tmp')
| [
"def",
"get_temp_file_path",
"(",
"file_path",
")",
":",
"return",
"(",
"file_path",
"+",
"'.tmp'",
")"
] | generates a temporary filename . | train | false |
47,722 | def cross_from_below(x, threshold):
x = np.asarray(x)
threshold = threshold
ind = np.nonzero(((x[:(-1)] < threshold) & (x[1:] >= threshold)))[0]
if len(ind):
return (ind + 1)
else:
return ind
| [
"def",
"cross_from_below",
"(",
"x",
",",
"threshold",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"threshold",
"=",
"threshold",
"ind",
"=",
"np",
".",
"nonzero",
"(",
"(",
"(",
"x",
"[",
":",
"(",
"-",
"1",
")",
"]",
"<",
"thresh... | return the indices into *x* where *x* crosses some threshold from below . | train | false |
47,723 | def correct_barcode_bitwise(query_seq, seq_possibilities, nt_to_bits=DEFAULT_GOLAY_NT_TO_BITS):
if (nt_to_bits is None):
nt_to_bits = DEFAULT_NT_TO_BITS
dists = []
query_seq_bits = seq_to_bits(query_seq, nt_to_bits)
for seq in seq_possibilities:
possible_seq_bits = seq_to_bits(seq, nt_to_bits)
dists.append(hamming_dist(query_seq_bits, possible_seq_bits))
min_dist = min(dists)
number_mins = dists.count(min_dist)
if (number_mins > 1):
return (None, min_dist)
else:
best_hit = seq_possibilities[dists.index(min_dist)]
return (best_hit, min_dist)
| [
"def",
"correct_barcode_bitwise",
"(",
"query_seq",
",",
"seq_possibilities",
",",
"nt_to_bits",
"=",
"DEFAULT_GOLAY_NT_TO_BITS",
")",
":",
"if",
"(",
"nt_to_bits",
"is",
"None",
")",
":",
"nt_to_bits",
"=",
"DEFAULT_NT_TO_BITS",
"dists",
"=",
"[",
"]",
"query_seq... | finds closest match to query_seq assumes: all sequences are same length no sequence appears twice in seq_possibilities returns * best_hit is closest sequence from seq_possibilities . | train | false |
47,724 | def test_saved_inner_graph():
x = tensor.tensor3()
recurrent = SimpleRecurrent(dim=3, activation=Tanh())
y = recurrent.apply(x)
application_call = get_application_call(y)
assert application_call.inner_inputs
assert application_call.inner_outputs
cg = ComputationGraph(application_call.inner_outputs)
assert (len(VariableFilter(applications=[recurrent.apply])(cg)) == 3)
assert is_same_graph(application_call.inner_outputs[0], recurrent.apply(iterate=False, *application_call.inner_inputs))
| [
"def",
"test_saved_inner_graph",
"(",
")",
":",
"x",
"=",
"tensor",
".",
"tensor3",
"(",
")",
"recurrent",
"=",
"SimpleRecurrent",
"(",
"dim",
"=",
"3",
",",
"activation",
"=",
"Tanh",
"(",
")",
")",
"y",
"=",
"recurrent",
".",
"apply",
"(",
"x",
")"... | make sure that the original inner graph is saved . | train | false |
47,725 | def test_basic(script, tmpdir):
expected = '--hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
result = script.pip('hash', _hello_file(tmpdir))
assert (expected in str(result))
| [
"def",
"test_basic",
"(",
"script",
",",
"tmpdir",
")",
":",
"expected",
"=",
"'--hash=sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'",
"result",
"=",
"script",
".",
"pip",
"(",
"'hash'",
",",
"_hello_file",
"(",
"tmpdir",
")",
")",
"assert",... | run pip hash through its default behavior . | train | false |
47,727 | def norm_rgb(r, g, b):
greatest = max([r, g, b])
if (greatest > 0):
r /= greatest
g /= greatest
b /= greatest
return (r, g, b)
| [
"def",
"norm_rgb",
"(",
"r",
",",
"g",
",",
"b",
")",
":",
"greatest",
"=",
"max",
"(",
"[",
"r",
",",
"g",
",",
"b",
"]",
")",
"if",
"(",
"greatest",
">",
"0",
")",
":",
"r",
"/=",
"greatest",
"g",
"/=",
"greatest",
"b",
"/=",
"greatest",
... | normalise rgb components so the most intense has a value of 1 . | train | false |
47,728 | def _set_thread_safe_app():
if (_local is not None):
WSGIApplication.app = WSGIApplication.active_instance = _local('app')
WSGIApplication.request = _local('request')
| [
"def",
"_set_thread_safe_app",
"(",
")",
":",
"if",
"(",
"_local",
"is",
"not",
"None",
")",
":",
"WSGIApplication",
".",
"app",
"=",
"WSGIApplication",
".",
"active_instance",
"=",
"_local",
"(",
"'app'",
")",
"WSGIApplication",
".",
"request",
"=",
"_local... | assigns wsgiapplication globals to a proxy pointing to thread-local . | train | false |
47,730 | def is_id_list(lst):
return all(map(is_gm_id, lst))
| [
"def",
"is_id_list",
"(",
"lst",
")",
":",
"return",
"all",
"(",
"map",
"(",
"is_gm_id",
",",
"lst",
")",
")"
] | returns true if the given list is made up of all strings in gm id form . | train | false |
47,731 | @cronjobs.register
def update_contributor_metrics(day=None):
if settings.STAGE:
return
update_support_forum_contributors_metric(day)
update_kb_contributors_metric(day)
update_aoa_contributors_metric(day)
| [
"@",
"cronjobs",
".",
"register",
"def",
"update_contributor_metrics",
"(",
"day",
"=",
"None",
")",
":",
"if",
"settings",
".",
"STAGE",
":",
"return",
"update_support_forum_contributors_metric",
"(",
"day",
")",
"update_kb_contributors_metric",
"(",
"day",
")",
... | calculate and save contributor metrics . | train | false |
47,732 | def overlay_image(img, canvas=None, left=0, top=0):
if (canvas is None):
canvas = QImage(img.size(), QImage.Format_RGB32)
canvas.fill(Qt.white)
(left, top) = (int(left), int(top))
imageops.overlay(img, canvas, left, top)
return canvas
| [
"def",
"overlay_image",
"(",
"img",
",",
"canvas",
"=",
"None",
",",
"left",
"=",
"0",
",",
"top",
"=",
"0",
")",
":",
"if",
"(",
"canvas",
"is",
"None",
")",
":",
"canvas",
"=",
"QImage",
"(",
"img",
".",
"size",
"(",
")",
",",
"QImage",
".",
... | overlay the img onto the canvas at the specified position . | train | false |
47,733 | def generate_id():
return get_id(uuid.uuid4())
| [
"def",
"generate_id",
"(",
")",
":",
"return",
"get_id",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")"
] | generate a short . | train | false |
47,734 | def is_valid_imdb_title_id(value):
if (not isinstance(value, basestring)):
raise TypeError(u'is_valid_imdb_title_id expects a string but got {0}'.format(type(value)))
return (re.match(u'tt[\\d]{7}', value) is not None)
| [
"def",
"is_valid_imdb_title_id",
"(",
"value",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
")",
":",
"raise",
"TypeError",
"(",
"u'is_valid_imdb_title_id expects a string but got {0}'",
".",
"format",
"(",
"type",
"(",
"value",
... | return true if value is a valid imdb id for titles . | train | false |
47,735 | def _set_binops_check_loose(self, obj):
return (isinstance(obj, (_set_binop_bases + (self.__class__,))) or (util.duck_type_collection(obj) == set))
| [
"def",
"_set_binops_check_loose",
"(",
"self",
",",
"obj",
")",
":",
"return",
"(",
"isinstance",
"(",
"obj",
",",
"(",
"_set_binop_bases",
"+",
"(",
"self",
".",
"__class__",
",",
")",
")",
")",
"or",
"(",
"util",
".",
"duck_type_collection",
"(",
"obj"... | allow anything set-like to participate in set binops . | train | false |
47,736 | def get_instance_availability_zone(context, instance):
host = instance.get('host')
if (not host):
az = instance.get('availability_zone')
return az
cache_key = _make_cache_key(host)
cache = _get_cache()
az = cache.get(cache_key)
az_inst = instance.get('availability_zone')
if ((az_inst is not None) and (az != az_inst)):
az = None
if (not az):
elevated = context.elevated()
az = get_host_availability_zone(elevated, host)
cache.set(cache_key, az)
return az
| [
"def",
"get_instance_availability_zone",
"(",
"context",
",",
"instance",
")",
":",
"host",
"=",
"instance",
".",
"get",
"(",
"'host'",
")",
"if",
"(",
"not",
"host",
")",
":",
"az",
"=",
"instance",
".",
"get",
"(",
"'availability_zone'",
")",
"return",
... | return availability zone of specified instance . | train | false |
47,737 | def BlankLine():
return Leaf(token.NEWLINE, u'')
| [
"def",
"BlankLine",
"(",
")",
":",
"return",
"Leaf",
"(",
"token",
".",
"NEWLINE",
",",
"u''",
")"
] | a blank line . | train | false |
47,738 | @set_database
def get_assessment_item_data(assessment_item_id=None, **kwargs):
try:
assessment_item = AssessmentItem.get((AssessmentItem.id == assessment_item_id))
return model_to_dict(assessment_item)
except OperationalError:
return {}
| [
"@",
"set_database",
"def",
"get_assessment_item_data",
"(",
"assessment_item_id",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"assessment_item",
"=",
"AssessmentItem",
".",
"get",
"(",
"(",
"AssessmentItem",
".",
"id",
"==",
"assessment_item_id",
")... | wrapper function to return assessment_item from database as a dictionary . | train | false |
47,740 | def _is_32bit():
return ((struct.calcsize('P') * 8) == 32)
| [
"def",
"_is_32bit",
"(",
")",
":",
"return",
"(",
"(",
"struct",
".",
"calcsize",
"(",
"'P'",
")",
"*",
"8",
")",
"==",
"32",
")"
] | detect if process is 32bit python . | train | false |
47,741 | def _write_messages(message_descriptors, out):
for message in (message_descriptors or []):
(out << '')
(out << '')
(out << ('class %s(messages.Message):' % message.name))
with out.indent():
if (not (message.enum_types or message.message_types or message.fields)):
(out << '')
(out << 'pass')
else:
_write_enums(message.enum_types, out)
_write_messages(message.message_types, out)
_write_fields(message.fields, out)
| [
"def",
"_write_messages",
"(",
"message_descriptors",
",",
"out",
")",
":",
"for",
"message",
"in",
"(",
"message_descriptors",
"or",
"[",
"]",
")",
":",
"(",
"out",
"<<",
"''",
")",
"(",
"out",
"<<",
"''",
")",
"(",
"out",
"<<",
"(",
"'class %s(messag... | write nested and non-nested message types . | train | false |
47,742 | def dirname(p):
return split(p)[0]
| [
"def",
"dirname",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"0",
"]"
] | return the head part of a path . | train | false |
47,743 | @pytest.fixture
def header_checker(caplog, stubs):
return HeaderChecker(caplog, stubs)
| [
"@",
"pytest",
".",
"fixture",
"def",
"header_checker",
"(",
"caplog",
",",
"stubs",
")",
":",
"return",
"HeaderChecker",
"(",
"caplog",
",",
"stubs",
")"
] | fixture that provides a headerchecker class for tests . | train | false |
47,744 | def _lookup_by_id_or_name_factory(iterator, element_name, doc):
def lookup_by_id_or_name(self, ref, before=None):
u'\n Given an key *ref*, finds the first element in the iterator\n with the attribute ID == *ref* or name == *ref*. If *before*\n is provided, will stop searching at the object *before*. This\n is important, since "forward references" are not allowed in\n the VOTABLE format.\n '
for element in getattr(self, iterator)():
if (element is before):
if (ref in (element.ID, element.name)):
vo_raise(u'{} references itself'.format(element_name), element._config, element._pos, KeyError)
break
if (ref in (element.ID, element.name)):
return element
raise KeyError(u"No {} with ID or name '{}' found before the referencing {}".format(element_name, ref, element_name))
lookup_by_id_or_name.__doc__ = doc
return lookup_by_id_or_name
| [
"def",
"_lookup_by_id_or_name_factory",
"(",
"iterator",
",",
"element_name",
",",
"doc",
")",
":",
"def",
"lookup_by_id_or_name",
"(",
"self",
",",
"ref",
",",
"before",
"=",
"None",
")",
":",
"for",
"element",
"in",
"getattr",
"(",
"self",
",",
"iterator",... | like _lookup_by_attr_factory . | train | false |
47,745 | def p_return_stmt(p):
p[0] = ast.Return(p[2])
| [
"def",
"p_return_stmt",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Return",
"(",
"p",
"[",
"2",
"]",
")"
] | return_stmt : return testlist . | train | false |
47,747 | def load_from_yahoo(indexes=None, stocks=None, start=None, end=None, adjusted=True):
data = _load_raw_yahoo_data(indexes, stocks, start, end)
if adjusted:
close_key = 'Adj Close'
else:
close_key = 'Close'
df = pd.DataFrame({key: d[close_key] for (key, d) in iteritems(data)})
df.index = df.index.tz_localize(pytz.utc)
return df
| [
"def",
"load_from_yahoo",
"(",
"indexes",
"=",
"None",
",",
"stocks",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"adjusted",
"=",
"True",
")",
":",
"data",
"=",
"_load_raw_yahoo_data",
"(",
"indexes",
",",
"stocks",
",",
"sta... | loads price data from yahoo into a dataframe for each of the indicated assets . | train | false |
47,748 | def key_pair_get(context, user_id, name):
return IMPL.key_pair_get(context, user_id, name)
| [
"def",
"key_pair_get",
"(",
"context",
",",
"user_id",
",",
"name",
")",
":",
"return",
"IMPL",
".",
"key_pair_get",
"(",
"context",
",",
"user_id",
",",
"name",
")"
] | get a key_pair or raise if it does not exist . | train | false |
47,749 | def get_install_key():
return sha1(settings.SECRET_KEY).hexdigest()
| [
"def",
"get_install_key",
"(",
")",
":",
"return",
"sha1",
"(",
"settings",
".",
"SECRET_KEY",
")",
".",
"hexdigest",
"(",
")"
] | return the installation key for this server . | train | false |
47,750 | def istask(x):
return ((type(x) is tuple) and x and callable(x[0]))
| [
"def",
"istask",
"(",
"x",
")",
":",
"return",
"(",
"(",
"type",
"(",
"x",
")",
"is",
"tuple",
")",
"and",
"x",
"and",
"callable",
"(",
"x",
"[",
"0",
"]",
")",
")"
] | is x a runnable task? a task is a tuple with a callable first argument examples . | train | false |
47,752 | def add_tooltips_columns(renderer, tooltips, group):
current_columns = renderer.data_source.data.keys()
if isinstance(tooltips[0], tuple):
tooltips_columns = [pair[1].replace('@', '') for pair in tooltips]
elif isinstance(tooltips[0], str):
tooltips_columns = tooltips
else:
tooltips_columns = []
for column in tooltips_columns:
if (column in current_columns):
continue
elif ('$' in column):
continue
renderer.data_source.add(group.get_values(column), column)
return renderer
| [
"def",
"add_tooltips_columns",
"(",
"renderer",
",",
"tooltips",
",",
"group",
")",
":",
"current_columns",
"=",
"renderer",
".",
"data_source",
".",
"data",
".",
"keys",
"(",
")",
"if",
"isinstance",
"(",
"tooltips",
"[",
"0",
"]",
",",
"tuple",
")",
":... | args: renderer : renderer for the glyph to be modified . | train | false |
47,755 | def getGeometryToolsPath(subName=''):
return getJoinedPath(getGeometryPath('geometry_tools'), subName)
| [
"def",
"getGeometryToolsPath",
"(",
"subName",
"=",
"''",
")",
":",
"return",
"getJoinedPath",
"(",
"getGeometryPath",
"(",
"'geometry_tools'",
")",
",",
"subName",
")"
] | get the geometry tools directory path . | train | false |
47,756 | def update_param(prefixed_name, input_values, new_value):
for key in input_values:
match = re.match((('^' + key) + '_(\\d+)\\|(.+)'), prefixed_name)
if (match and (not key.endswith('|__identifier__'))):
index = int(match.group(1))
if (isinstance(input_values[key], list) and (len(input_values[key]) > index)):
update_param(match.group(2), input_values[key][index], new_value)
else:
match = re.match((('^' + key) + '\\|(.+)'), prefixed_name)
if (isinstance(input_values[key], dict) and match):
update_param(match.group(1), input_values[key], new_value)
elif (prefixed_name == key):
input_values[key] = new_value
| [
"def",
"update_param",
"(",
"prefixed_name",
",",
"input_values",
",",
"new_value",
")",
":",
"for",
"key",
"in",
"input_values",
":",
"match",
"=",
"re",
".",
"match",
"(",
"(",
"(",
"'^'",
"+",
"key",
")",
"+",
"'_(\\\\d+)\\\\|(.+)'",
")",
",",
"prefix... | given a prefixed parameter name . | train | false |
47,758 | def client_list_entries_multi_project(client, to_delete):
PROJECT_IDS = ['one-project', 'another-project']
for entry in client.list_entries(project_ids=PROJECT_IDS):
do_something_with(entry)
| [
"def",
"client_list_entries_multi_project",
"(",
"client",
",",
"to_delete",
")",
":",
"PROJECT_IDS",
"=",
"[",
"'one-project'",
",",
"'another-project'",
"]",
"for",
"entry",
"in",
"client",
".",
"list_entries",
"(",
"project_ids",
"=",
"PROJECT_IDS",
")",
":",
... | list entries via client across multiple projects . | train | true |
47,759 | def get_project_description(project):
return _(u'{0} is translated into {1} languages using Weblate. Join the translation or start translating your own project.').format(project, project.get_language_count())
| [
"def",
"get_project_description",
"(",
"project",
")",
":",
"return",
"_",
"(",
"u'{0} is translated into {1} languages using Weblate. Join the translation or start translating your own project.'",
")",
".",
"format",
"(",
"project",
",",
"project",
".",
"get_language_count",
"... | returns verbose description for project translation . | train | false |
47,760 | def crc_check(path, target_crc):
try:
fp = open(path, 'rb')
except:
return False
crc = binascii.crc32('')
while 1:
data = fp.read(4096)
if (not data):
break
crc = binascii.crc32(data, crc)
fp.close()
crc = ('%08x' % ((crc & 4294967295),))
return (crc.lower() == target_crc.lower())
| [
"def",
"crc_check",
"(",
"path",
",",
"target_crc",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"except",
":",
"return",
"False",
"crc",
"=",
"binascii",
".",
"crc32",
"(",
"''",
")",
"while",
"1",
":",
"data",
"=",
"f... | return true if file matches crc . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.