repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
rainwoodman/kdcount | kdcount/utils.py | bincount | def bincount(dig, weight, minlength):
""" bincount supporting scalar and vector weight """
if numpy.isscalar(weight):
return numpy.bincount(dig, minlength=minlength) * weight
else:
return numpy.bincount(dig, weight, minlength) | python | def bincount(dig, weight, minlength):
""" bincount supporting scalar and vector weight """
if numpy.isscalar(weight):
return numpy.bincount(dig, minlength=minlength) * weight
else:
return numpy.bincount(dig, weight, minlength) | [
"def",
"bincount",
"(",
"dig",
",",
"weight",
",",
"minlength",
")",
":",
"if",
"numpy",
".",
"isscalar",
"(",
"weight",
")",
":",
"return",
"numpy",
".",
"bincount",
"(",
"dig",
",",
"minlength",
"=",
"minlength",
")",
"*",
"weight",
"else",
":",
"r... | bincount supporting scalar and vector weight | [
"bincount",
"supporting",
"scalar",
"and",
"vector",
"weight"
] | 483548f6d27a4f245cd5d98880b5f4edd6cc8dc1 | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/utils.py#L27-L32 | train | 51,200 |
timothycrosley/concentration | concentration/run.py | reset_network | def reset_network(message):
"""Resets the users network to make changes take effect"""
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | python | def reset_network(message):
"""Resets the users network to make changes take effect"""
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | [
"def",
"reset_network",
"(",
"message",
")",
":",
"for",
"command",
"in",
"settings",
".",
"RESTART_NETWORK",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
")",
"except",
":",
"pass",
"print",
"(",
"message",
")"
] | Resets the users network to make changes take effect | [
"Resets",
"the",
"users",
"network",
"to",
"make",
"changes",
"take",
"effect"
] | 5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4 | https://github.com/timothycrosley/concentration/blob/5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4/concentration/run.py#L15-L22 | train | 51,201 |
timothycrosley/concentration | concentration/run.py | improve | def improve():
"""Disables access to websites that are defined as 'distractors'"""
with open(settings.HOSTS_FILE, "r+") as hosts_file:
contents = hosts_file.read()
if not settings.START_TOKEN in contents and not settings.END_TOKEN in contents:
hosts_file.write(settings.START_TOKEN + "\n")
for site in set(settings.DISTRACTORS):
hosts_file.write("{0}\t{1}\n".format(settings.REDIRECT_TO, site))
for sub_domain in settings.SUB_DOMAINS:
hosts_file.write("{0}\t{1}.{2}\n".format(settings.REDIRECT_TO, sub_domain, site))
hosts_file.write(settings.END_TOKEN + "\n")
reset_network("Concentration is now improved :D!") | python | def improve():
"""Disables access to websites that are defined as 'distractors'"""
with open(settings.HOSTS_FILE, "r+") as hosts_file:
contents = hosts_file.read()
if not settings.START_TOKEN in contents and not settings.END_TOKEN in contents:
hosts_file.write(settings.START_TOKEN + "\n")
for site in set(settings.DISTRACTORS):
hosts_file.write("{0}\t{1}\n".format(settings.REDIRECT_TO, site))
for sub_domain in settings.SUB_DOMAINS:
hosts_file.write("{0}\t{1}.{2}\n".format(settings.REDIRECT_TO, sub_domain, site))
hosts_file.write(settings.END_TOKEN + "\n")
reset_network("Concentration is now improved :D!") | [
"def",
"improve",
"(",
")",
":",
"with",
"open",
"(",
"settings",
".",
"HOSTS_FILE",
",",
"\"r+\"",
")",
"as",
"hosts_file",
":",
"contents",
"=",
"hosts_file",
".",
"read",
"(",
")",
"if",
"not",
"settings",
".",
"START_TOKEN",
"in",
"contents",
"and",
... | Disables access to websites that are defined as 'distractors | [
"Disables",
"access",
"to",
"websites",
"that",
"are",
"defined",
"as",
"distractors"
] | 5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4 | https://github.com/timothycrosley/concentration/blob/5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4/concentration/run.py#L26-L38 | train | 51,202 |
timothycrosley/concentration | concentration/run.py | lose | def lose():
"""Enables access to websites that are defined as 'distractors'"""
changed = False
with open(settings.HOSTS_FILE, "r") as hosts_file:
new_file = []
in_block = False
for line in hosts_file:
if in_block:
if line.strip() == settings.END_TOKEN:
in_block = False
changed = True
elif line.strip() == settings.START_TOKEN:
in_block = True
else:
new_file.append(line)
if changed:
with open(settings.HOSTS_FILE, "w") as hosts_file:
hosts_file.write("".join(new_file))
reset_network("Concentration is now lost :(.") | python | def lose():
"""Enables access to websites that are defined as 'distractors'"""
changed = False
with open(settings.HOSTS_FILE, "r") as hosts_file:
new_file = []
in_block = False
for line in hosts_file:
if in_block:
if line.strip() == settings.END_TOKEN:
in_block = False
changed = True
elif line.strip() == settings.START_TOKEN:
in_block = True
else:
new_file.append(line)
if changed:
with open(settings.HOSTS_FILE, "w") as hosts_file:
hosts_file.write("".join(new_file))
reset_network("Concentration is now lost :(.") | [
"def",
"lose",
"(",
")",
":",
"changed",
"=",
"False",
"with",
"open",
"(",
"settings",
".",
"HOSTS_FILE",
",",
"\"r\"",
")",
"as",
"hosts_file",
":",
"new_file",
"=",
"[",
"]",
"in_block",
"=",
"False",
"for",
"line",
"in",
"hosts_file",
":",
"if",
... | Enables access to websites that are defined as 'distractors | [
"Enables",
"access",
"to",
"websites",
"that",
"are",
"defined",
"as",
"distractors"
] | 5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4 | https://github.com/timothycrosley/concentration/blob/5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4/concentration/run.py#L42-L61 | train | 51,203 |
timothycrosley/concentration | concentration/run.py | take_break | def take_break(minutes: hug.types.number=5):
"""Enables temporarily breaking concentration"""
print("")
print("######################################### ARE YOU SURE? #####################################")
try:
for remaining in range(60, -1, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds to change your mind. Won't you prefer programming? Or a book?".format(remaining))
sys.stdout.flush()
time.sleep(1)
except KeyboardInterrupt:
print("")
print("")
print(":D :D :D\nGood on you! <3")
return
# The user insisted on breaking concentration.
lose()
print("")
print("######################################### TAKING A BREAK ####################################")
try:
for remaining in range(minutes * 60, -1, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining without concentration.".format(remaining))
sys.stdout.flush()
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
sys.stdout.write("\rEnough distraction! \n")
print("######################################### BREAK OVER :) #####################################")
print("")
improve() | python | def take_break(minutes: hug.types.number=5):
"""Enables temporarily breaking concentration"""
print("")
print("######################################### ARE YOU SURE? #####################################")
try:
for remaining in range(60, -1, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds to change your mind. Won't you prefer programming? Or a book?".format(remaining))
sys.stdout.flush()
time.sleep(1)
except KeyboardInterrupt:
print("")
print("")
print(":D :D :D\nGood on you! <3")
return
# The user insisted on breaking concentration.
lose()
print("")
print("######################################### TAKING A BREAK ####################################")
try:
for remaining in range(minutes * 60, -1, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining without concentration.".format(remaining))
sys.stdout.flush()
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
sys.stdout.write("\rEnough distraction! \n")
print("######################################### BREAK OVER :) #####################################")
print("")
improve() | [
"def",
"take_break",
"(",
"minutes",
":",
"hug",
".",
"types",
".",
"number",
"=",
"5",
")",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"######################################### ARE YOU SURE? #####################################\"",
")",
"try",
":",
"for",
"r... | Enables temporarily breaking concentration | [
"Enables",
"temporarily",
"breaking",
"concentration"
] | 5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4 | https://github.com/timothycrosley/concentration/blob/5d07a79cdf56054c42b6e2d1c95ea51bc6678fc4/concentration/run.py#L65-L97 | train | 51,204 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | _si | def _si(number):
"""Format a number using base-2 SI prefixes"""
prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
while number > 1024:
number /= 1024.0
prefixes.pop(0)
return '%0.2f%s' % (number, prefixes.pop(0)) | python | def _si(number):
"""Format a number using base-2 SI prefixes"""
prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
while number > 1024:
number /= 1024.0
prefixes.pop(0)
return '%0.2f%s' % (number, prefixes.pop(0)) | [
"def",
"_si",
"(",
"number",
")",
":",
"prefixes",
"=",
"[",
"''",
",",
"'K'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
",",
"'E'",
",",
"'Z'",
",",
"'Y'",
"]",
"while",
"number",
">",
"1024",
":",
"number",
"/=",
"1024.0",
"prefixes",
"... | Format a number using base-2 SI prefixes | [
"Format",
"a",
"number",
"using",
"base",
"-",
"2",
"SI",
"prefixes"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L72-L78 | train | 51,205 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | _get_url | def _get_url(url):
"""Retrieve requested URL"""
try:
data = HTTP_SESSION.get(url, stream=True)
data.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
return data | python | def _get_url(url):
"""Retrieve requested URL"""
try:
data = HTTP_SESSION.get(url, stream=True)
data.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
return data | [
"def",
"_get_url",
"(",
"url",
")",
":",
"try",
":",
"data",
"=",
"HTTP_SESSION",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"data",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
... | Retrieve requested URL | [
"Retrieve",
"requested",
"URL"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L81-L89 | train | 51,206 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | _extract_file | def _extract_file(zip_fp, info, path):
"""Extract files while explicitly setting the proper permissions"""
zip_fp.extract(info.filename, path=path)
out_path = os.path.join(path, info.filename)
perm = info.external_attr >> 16
perm |= stat.S_IREAD # make sure we're not accidentally setting this to 0
os.chmod(out_path, perm) | python | def _extract_file(zip_fp, info, path):
"""Extract files while explicitly setting the proper permissions"""
zip_fp.extract(info.filename, path=path)
out_path = os.path.join(path, info.filename)
perm = info.external_attr >> 16
perm |= stat.S_IREAD # make sure we're not accidentally setting this to 0
os.chmod(out_path, perm) | [
"def",
"_extract_file",
"(",
"zip_fp",
",",
"info",
",",
"path",
")",
":",
"zip_fp",
".",
"extract",
"(",
"info",
".",
"filename",
",",
"path",
"=",
"path",
")",
"out_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"info",
".",
"filen... | Extract files while explicitly setting the proper permissions | [
"Extract",
"files",
"while",
"explicitly",
"setting",
"the",
"proper",
"permissions"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L110-L117 | train | 51,207 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | BuildFlags.build_string | def build_string(self):
"""
Taskcluster denotes builds in one of two formats - i.e. linux64-asan or linux64-asan-opt
The latter is generated. If it fails, the caller should try the former.
"""
return (('-ccov' if self.coverage else '') +
('-fuzzing' if self.fuzzing else '') +
('-asan' if self.asan else '') +
('-valgrind' if self.valgrind else '') +
('-debug' if self.debug else '-opt')) | python | def build_string(self):
"""
Taskcluster denotes builds in one of two formats - i.e. linux64-asan or linux64-asan-opt
The latter is generated. If it fails, the caller should try the former.
"""
return (('-ccov' if self.coverage else '') +
('-fuzzing' if self.fuzzing else '') +
('-asan' if self.asan else '') +
('-valgrind' if self.valgrind else '') +
('-debug' if self.debug else '-opt')) | [
"def",
"build_string",
"(",
"self",
")",
":",
"return",
"(",
"(",
"'-ccov'",
"if",
"self",
".",
"coverage",
"else",
"''",
")",
"+",
"(",
"'-fuzzing'",
"if",
"self",
".",
"fuzzing",
"else",
"''",
")",
"+",
"(",
"'-asan'",
"if",
"self",
".",
"asan",
... | Taskcluster denotes builds in one of two formats - i.e. linux64-asan or linux64-asan-opt
The latter is generated. If it fails, the caller should try the former. | [
"Taskcluster",
"denotes",
"builds",
"in",
"one",
"of",
"two",
"formats",
"-",
"i",
".",
"e",
".",
"linux64",
"-",
"asan",
"or",
"linux64",
"-",
"asan",
"-",
"opt",
"The",
"latter",
"is",
"generated",
".",
"If",
"it",
"fails",
"the",
"caller",
"should",... | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L129-L138 | train | 51,208 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Platform.auto_name_prefix | def auto_name_prefix(self):
"""
Generate platform prefix for cross-platform downloads.
"""
# if the platform is not native, auto_name would clobber native downloads.
# make a prefix to avoid this
native_system = std_platform.system()
native_machine = self.CPU_ALIASES.get(std_platform.machine(), std_platform.machine())
if native_system == self.system and native_machine == self.machine:
return ''
platform = {
'linux': 'linux32',
'android-api-16': 'android-arm',
'android-aarch64': 'android-arm64',
}.get(self.gecko_platform, self.gecko_platform)
return platform + '-' | python | def auto_name_prefix(self):
"""
Generate platform prefix for cross-platform downloads.
"""
# if the platform is not native, auto_name would clobber native downloads.
# make a prefix to avoid this
native_system = std_platform.system()
native_machine = self.CPU_ALIASES.get(std_platform.machine(), std_platform.machine())
if native_system == self.system and native_machine == self.machine:
return ''
platform = {
'linux': 'linux32',
'android-api-16': 'android-arm',
'android-aarch64': 'android-arm64',
}.get(self.gecko_platform, self.gecko_platform)
return platform + '-' | [
"def",
"auto_name_prefix",
"(",
"self",
")",
":",
"# if the platform is not native, auto_name would clobber native downloads.",
"# make a prefix to avoid this",
"native_system",
"=",
"std_platform",
".",
"system",
"(",
")",
"native_machine",
"=",
"self",
".",
"CPU_ALIASES",
"... | Generate platform prefix for cross-platform downloads. | [
"Generate",
"platform",
"prefix",
"for",
"cross",
"-",
"platform",
"downloads",
"."
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L171-L186 | train | 51,209 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | BuildTask.iterall | def iterall(cls, build, branch, flags, platform=None):
"""Generator for all possible BuildTasks with these parameters"""
# Prepare build type
if platform is None:
platform = Platform()
target_platform = platform.gecko_platform
is_namespace = False
if cls.RE_DATE.match(build):
task_urls = map(''.join,
itertools.product(cls._pushdate_urls(build.replace('-', '.'), branch, target_platform),
(flags.build_string(),)))
elif cls.RE_REV.match(build):
task_urls = (cls._revision_url(build.lower(), branch, target_platform) + flags.build_string(),)
elif build == 'latest':
namespace = 'gecko.v2.mozilla-' + branch + '.latest'
product = 'mobile' if 'android' in target_platform else 'firefox'
task_urls = (cls.URL_BASE + '/task/' + namespace + '.' + product + '.' + target_platform +
flags.build_string(),)
else:
# try to use build argument directly as a namespace
task_urls = (cls.URL_BASE + '/task/' + build,)
is_namespace = True
for (url, try_wo_opt) in itertools.product(task_urls, (False, True)):
if try_wo_opt:
if '-opt' not in url or is_namespace:
continue
url = url.replace('-opt', '')
try:
data = HTTP_SESSION.get(url)
data.raise_for_status()
except requests.exceptions.RequestException:
continue
obj = cls(None, None, None, _blank=True)
obj.url = url
obj._data = data.json() # pylint: disable=protected-access
LOG.debug('Found archive for %s', cls._debug_str(build))
yield obj | python | def iterall(cls, build, branch, flags, platform=None):
"""Generator for all possible BuildTasks with these parameters"""
# Prepare build type
if platform is None:
platform = Platform()
target_platform = platform.gecko_platform
is_namespace = False
if cls.RE_DATE.match(build):
task_urls = map(''.join,
itertools.product(cls._pushdate_urls(build.replace('-', '.'), branch, target_platform),
(flags.build_string(),)))
elif cls.RE_REV.match(build):
task_urls = (cls._revision_url(build.lower(), branch, target_platform) + flags.build_string(),)
elif build == 'latest':
namespace = 'gecko.v2.mozilla-' + branch + '.latest'
product = 'mobile' if 'android' in target_platform else 'firefox'
task_urls = (cls.URL_BASE + '/task/' + namespace + '.' + product + '.' + target_platform +
flags.build_string(),)
else:
# try to use build argument directly as a namespace
task_urls = (cls.URL_BASE + '/task/' + build,)
is_namespace = True
for (url, try_wo_opt) in itertools.product(task_urls, (False, True)):
if try_wo_opt:
if '-opt' not in url or is_namespace:
continue
url = url.replace('-opt', '')
try:
data = HTTP_SESSION.get(url)
data.raise_for_status()
except requests.exceptions.RequestException:
continue
obj = cls(None, None, None, _blank=True)
obj.url = url
obj._data = data.json() # pylint: disable=protected-access
LOG.debug('Found archive for %s', cls._debug_str(build))
yield obj | [
"def",
"iterall",
"(",
"cls",
",",
"build",
",",
"branch",
",",
"flags",
",",
"platform",
"=",
"None",
")",
":",
"# Prepare build type",
"if",
"platform",
"is",
"None",
":",
"platform",
"=",
"Platform",
"(",
")",
"target_platform",
"=",
"platform",
".",
... | Generator for all possible BuildTasks with these parameters | [
"Generator",
"for",
"all",
"possible",
"BuildTasks",
"with",
"these",
"parameters"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L220-L265 | train | 51,210 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | BuildTask._pushdate_urls | def _pushdate_urls(cls, pushdate, branch, target_platform):
"""Multiple entries exist per push date. Iterate over all until a working entry is found"""
url_base = cls.URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate
try:
base = HTTP_SESSION.post(url_base, json={})
base.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
product = 'mobile' if 'android' in target_platform else 'firefox'
json = base.json()
for namespace in sorted(json['namespaces'], key=lambda x: x['name']):
yield cls.URL_BASE + '/task/' + namespace['namespace'] + '.' + product + '.' + target_platform | python | def _pushdate_urls(cls, pushdate, branch, target_platform):
"""Multiple entries exist per push date. Iterate over all until a working entry is found"""
url_base = cls.URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate
try:
base = HTTP_SESSION.post(url_base, json={})
base.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
product = 'mobile' if 'android' in target_platform else 'firefox'
json = base.json()
for namespace in sorted(json['namespaces'], key=lambda x: x['name']):
yield cls.URL_BASE + '/task/' + namespace['namespace'] + '.' + product + '.' + target_platform | [
"def",
"_pushdate_urls",
"(",
"cls",
",",
"pushdate",
",",
"branch",
",",
"target_platform",
")",
":",
"url_base",
"=",
"cls",
".",
"URL_BASE",
"+",
"'/namespaces/gecko.v2.mozilla-'",
"+",
"branch",
"+",
"'.pushdate.'",
"+",
"pushdate",
"try",
":",
"base",
"="... | Multiple entries exist per push date. Iterate over all until a working entry is found | [
"Multiple",
"entries",
"exist",
"per",
"push",
"date",
".",
"Iterate",
"over",
"all",
"until",
"a",
"working",
"entry",
"is",
"found"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L273-L286 | train | 51,211 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | BuildTask._revision_url | def _revision_url(cls, rev, branch, target_platform):
"""Retrieve the URL for revision based builds"""
namespace = 'gecko.v2.mozilla-' + branch + '.revision.' + rev
product = 'mobile' if 'android' in target_platform else 'firefox'
return cls.URL_BASE + '/task/' + namespace + '.' + product + '.' + target_platform | python | def _revision_url(cls, rev, branch, target_platform):
"""Retrieve the URL for revision based builds"""
namespace = 'gecko.v2.mozilla-' + branch + '.revision.' + rev
product = 'mobile' if 'android' in target_platform else 'firefox'
return cls.URL_BASE + '/task/' + namespace + '.' + product + '.' + target_platform | [
"def",
"_revision_url",
"(",
"cls",
",",
"rev",
",",
"branch",
",",
"target_platform",
")",
":",
"namespace",
"=",
"'gecko.v2.mozilla-'",
"+",
"branch",
"+",
"'.revision.'",
"+",
"rev",
"product",
"=",
"'mobile'",
"if",
"'android'",
"in",
"target_platform",
"e... | Retrieve the URL for revision based builds | [
"Retrieve",
"the",
"URL",
"for",
"revision",
"based",
"builds"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L289-L293 | train | 51,212 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.iterall | def iterall(cls, target, branch, build, flags, platform=None):
"""Return an iterable for all available builds matching a particular build type"""
flags = BuildFlags(*flags)
for task in BuildTask.iterall(build, branch, flags, platform):
yield cls(target, branch, task, flags, platform) | python | def iterall(cls, target, branch, build, flags, platform=None):
"""Return an iterable for all available builds matching a particular build type"""
flags = BuildFlags(*flags)
for task in BuildTask.iterall(build, branch, flags, platform):
yield cls(target, branch, task, flags, platform) | [
"def",
"iterall",
"(",
"cls",
",",
"target",
",",
"branch",
",",
"build",
",",
"flags",
",",
"platform",
"=",
"None",
")",
":",
"flags",
"=",
"BuildFlags",
"(",
"*",
"flags",
")",
"for",
"task",
"in",
"BuildTask",
".",
"iterall",
"(",
"build",
",",
... | Return an iterable for all available builds matching a particular build type | [
"Return",
"an",
"iterable",
"for",
"all",
"available",
"builds",
"matching",
"a",
"particular",
"build",
"type"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L386-L390 | train | 51,213 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher._artifacts | def _artifacts(self):
"""Retrieve the artifacts json object"""
if '_artifacts' not in self._memo:
json = _get_url(self._artifacts_url).json()
self._memo['_artifacts'] = json['artifacts']
return self._memo['_artifacts'] | python | def _artifacts(self):
"""Retrieve the artifacts json object"""
if '_artifacts' not in self._memo:
json = _get_url(self._artifacts_url).json()
self._memo['_artifacts'] = json['artifacts']
return self._memo['_artifacts'] | [
"def",
"_artifacts",
"(",
"self",
")",
":",
"if",
"'_artifacts'",
"not",
"in",
"self",
".",
"_memo",
":",
"json",
"=",
"_get_url",
"(",
"self",
".",
"_artifacts_url",
")",
".",
"json",
"(",
")",
"self",
".",
"_memo",
"[",
"'_artifacts'",
"]",
"=",
"j... | Retrieve the artifacts json object | [
"Retrieve",
"the",
"artifacts",
"json",
"object"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L393-L398 | train | 51,214 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher._artifact_base | def _artifact_base(self):
"""
Build the artifact basename
Builds are base.tar.bz2, info is base.json, shell is base.jsshell.zip...
"""
if '_artifact_base' not in self._memo:
for artifact in self._artifacts:
if self.re_target.search(artifact['name']) is not None:
artifact_base = os.path.splitext(artifact['name'])[0]
break
else:
raise FetcherException('Could not find build info in artifacts')
self._memo['_artifact_base'] = artifact_base
return self._memo['_artifact_base'] | python | def _artifact_base(self):
"""
Build the artifact basename
Builds are base.tar.bz2, info is base.json, shell is base.jsshell.zip...
"""
if '_artifact_base' not in self._memo:
for artifact in self._artifacts:
if self.re_target.search(artifact['name']) is not None:
artifact_base = os.path.splitext(artifact['name'])[0]
break
else:
raise FetcherException('Could not find build info in artifacts')
self._memo['_artifact_base'] = artifact_base
return self._memo['_artifact_base'] | [
"def",
"_artifact_base",
"(",
"self",
")",
":",
"if",
"'_artifact_base'",
"not",
"in",
"self",
".",
"_memo",
":",
"for",
"artifact",
"in",
"self",
".",
"_artifacts",
":",
"if",
"self",
".",
"re_target",
".",
"search",
"(",
"artifact",
"[",
"'name'",
"]",... | Build the artifact basename
Builds are base.tar.bz2, info is base.json, shell is base.jsshell.zip... | [
"Build",
"the",
"artifact",
"basename",
"Builds",
"are",
"base",
".",
"tar",
".",
"bz2",
"info",
"is",
"base",
".",
"json",
"shell",
"is",
"base",
".",
"jsshell",
".",
"zip",
"..."
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L401-L414 | train | 51,215 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.build_info | def build_info(self):
"""Return the build's info"""
if 'build_info' not in self._memo:
self._memo['build_info'] = _get_url(self.artifact_url('json')).json()
return self._memo['build_info'] | python | def build_info(self):
"""Return the build's info"""
if 'build_info' not in self._memo:
self._memo['build_info'] = _get_url(self.artifact_url('json')).json()
return self._memo['build_info'] | [
"def",
"build_info",
"(",
"self",
")",
":",
"if",
"'build_info'",
"not",
"in",
"self",
".",
"_memo",
":",
"self",
".",
"_memo",
"[",
"'build_info'",
"]",
"=",
"_get_url",
"(",
"self",
".",
"artifact_url",
"(",
"'json'",
")",
")",
".",
"json",
"(",
")... | Return the build's info | [
"Return",
"the",
"build",
"s",
"info"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L432-L436 | train | 51,216 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.moz_info | def moz_info(self):
"""Return the build's mozinfo"""
if 'moz_info' not in self._memo:
self._memo['moz_info'] = _get_url(self.artifact_url('mozinfo.json')).json()
return self._memo['moz_info'] | python | def moz_info(self):
"""Return the build's mozinfo"""
if 'moz_info' not in self._memo:
self._memo['moz_info'] = _get_url(self.artifact_url('mozinfo.json')).json()
return self._memo['moz_info'] | [
"def",
"moz_info",
"(",
"self",
")",
":",
"if",
"'moz_info'",
"not",
"in",
"self",
".",
"_memo",
":",
"self",
".",
"_memo",
"[",
"'moz_info'",
"]",
"=",
"_get_url",
"(",
"self",
".",
"artifact_url",
"(",
"'mozinfo.json'",
")",
")",
".",
"json",
"(",
... | Return the build's mozinfo | [
"Return",
"the",
"build",
"s",
"mozinfo"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L444-L448 | train | 51,217 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher._layout_for_domfuzz | def _layout_for_domfuzz(self, path):
"""
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
"""
old_dir = os.getcwd()
os.chdir(os.path.join(path))
try:
os.mkdir('dist')
link_name = os.path.join('dist', 'bin')
if self._platform.system == 'Darwin' and self._target == 'firefox':
ff_loc = glob.glob('*.app/Contents/MacOS/firefox')
assert len(ff_loc) == 1
os.symlink(os.path.join(os.pardir, os.path.dirname(ff_loc[0])), # pylint: disable=no-member
link_name)
os.symlink(os.path.join(os.pardir, os.pardir, os.pardir, 'symbols'), # pylint: disable=no-member
os.path.join(os.path.dirname(ff_loc[0]), 'symbols'))
elif self._platform.system == 'Linux':
os.symlink(os.pardir, link_name) # pylint: disable=no-member
elif self._platform.system == 'Windows':
# create a junction point at dist\bin pointing to the firefox.exe path
junction_path.symlink(os.curdir, link_name)
finally:
os.chdir(old_dir) | python | def _layout_for_domfuzz(self, path):
"""
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
"""
old_dir = os.getcwd()
os.chdir(os.path.join(path))
try:
os.mkdir('dist')
link_name = os.path.join('dist', 'bin')
if self._platform.system == 'Darwin' and self._target == 'firefox':
ff_loc = glob.glob('*.app/Contents/MacOS/firefox')
assert len(ff_loc) == 1
os.symlink(os.path.join(os.pardir, os.path.dirname(ff_loc[0])), # pylint: disable=no-member
link_name)
os.symlink(os.path.join(os.pardir, os.pardir, os.pardir, 'symbols'), # pylint: disable=no-member
os.path.join(os.path.dirname(ff_loc[0]), 'symbols'))
elif self._platform.system == 'Linux':
os.symlink(os.pardir, link_name) # pylint: disable=no-member
elif self._platform.system == 'Windows':
# create a junction point at dist\bin pointing to the firefox.exe path
junction_path.symlink(os.curdir, link_name)
finally:
os.chdir(old_dir) | [
"def",
"_layout_for_domfuzz",
"(",
"self",
",",
"path",
")",
":",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
")",
")",
"try",
":",
"os",
".",
"mkdir",
"(",
"'dist'",
")",
... | Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path | [
"Update",
"directory",
"to",
"work",
"with",
"DOMFuzz"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L571-L596 | train | 51,218 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher._write_fuzzmanagerconf | def _write_fuzzmanagerconf(self, path):
"""
Write fuzzmanager config file for selected build
@type path: basestring
@param path: A string representation of the fuzzmanager config path
"""
output = configparser.RawConfigParser()
output.add_section('Main')
output.set('Main', 'platform', self.moz_info['processor'].replace('_', '-'))
output.set('Main', 'product', 'mozilla-' + self._branch)
output.set('Main', 'product_version', '%.8s-%.12s' % (self.build_id, self.changeset))
# make sure 'os' match what FM expects
os_name = self.moz_info['os'].lower()
if os_name.startswith('android'):
output.set('Main', 'os', 'android')
elif os_name.startswith('lin'):
output.set('Main', 'os', 'linux')
elif os_name.startswith('mac'):
output.set('Main', 'os', 'macosx')
elif os_name.startswith('win'):
output.set('Main', 'os', 'windows')
else:
output.set('Main', 'os', self.moz_info['os'])
output.add_section('Metadata')
output.set('Metadata', 'pathPrefix', self.moz_info['topsrcdir'])
output.set('Metadata', 'buildFlags', self._flags.build_string().lstrip('-'))
if self._platform.system == "Windows":
fm_name = self._target + '.exe.fuzzmanagerconf'
conf_path = os.path.join(path, 'dist', 'bin', fm_name)
elif self._platform.system == "Android":
conf_path = os.path.join(path, 'target.apk.fuzzmanagerconf')
else:
fm_name = self._target + '.fuzzmanagerconf'
conf_path = os.path.join(path, 'dist', 'bin', fm_name)
with open(conf_path, 'w') as conf_fp:
output.write(conf_fp) | python | def _write_fuzzmanagerconf(self, path):
"""
Write fuzzmanager config file for selected build
@type path: basestring
@param path: A string representation of the fuzzmanager config path
"""
output = configparser.RawConfigParser()
output.add_section('Main')
output.set('Main', 'platform', self.moz_info['processor'].replace('_', '-'))
output.set('Main', 'product', 'mozilla-' + self._branch)
output.set('Main', 'product_version', '%.8s-%.12s' % (self.build_id, self.changeset))
# make sure 'os' match what FM expects
os_name = self.moz_info['os'].lower()
if os_name.startswith('android'):
output.set('Main', 'os', 'android')
elif os_name.startswith('lin'):
output.set('Main', 'os', 'linux')
elif os_name.startswith('mac'):
output.set('Main', 'os', 'macosx')
elif os_name.startswith('win'):
output.set('Main', 'os', 'windows')
else:
output.set('Main', 'os', self.moz_info['os'])
output.add_section('Metadata')
output.set('Metadata', 'pathPrefix', self.moz_info['topsrcdir'])
output.set('Metadata', 'buildFlags', self._flags.build_string().lstrip('-'))
if self._platform.system == "Windows":
fm_name = self._target + '.exe.fuzzmanagerconf'
conf_path = os.path.join(path, 'dist', 'bin', fm_name)
elif self._platform.system == "Android":
conf_path = os.path.join(path, 'target.apk.fuzzmanagerconf')
else:
fm_name = self._target + '.fuzzmanagerconf'
conf_path = os.path.join(path, 'dist', 'bin', fm_name)
with open(conf_path, 'w') as conf_fp:
output.write(conf_fp) | [
"def",
"_write_fuzzmanagerconf",
"(",
"self",
",",
"path",
")",
":",
"output",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"output",
".",
"add_section",
"(",
"'Main'",
")",
"output",
".",
"set",
"(",
"'Main'",
",",
"'platform'",
",",
"self",
"."... | Write fuzzmanager config file for selected build
@type path: basestring
@param path: A string representation of the fuzzmanager config path | [
"Write",
"fuzzmanager",
"config",
"file",
"for",
"selected",
"build"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L598-L635 | train | 51,219 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.extract_zip | def extract_zip(self, suffix, path='.'):
"""
Download and extract a zip artifact
@type suffix:
@param suffix:
@type path:
@param path:
"""
zip_fd, zip_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.zip')
os.close(zip_fd)
try:
_download_url(self.artifact_url(suffix), zip_fn)
LOG.info('.. extracting')
with zipfile.ZipFile(zip_fn) as zip_fp:
for info in zip_fp.infolist():
_extract_file(zip_fp, info, path)
finally:
os.unlink(zip_fn) | python | def extract_zip(self, suffix, path='.'):
"""
Download and extract a zip artifact
@type suffix:
@param suffix:
@type path:
@param path:
"""
zip_fd, zip_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.zip')
os.close(zip_fd)
try:
_download_url(self.artifact_url(suffix), zip_fn)
LOG.info('.. extracting')
with zipfile.ZipFile(zip_fn) as zip_fp:
for info in zip_fp.infolist():
_extract_file(zip_fp, info, path)
finally:
os.unlink(zip_fn) | [
"def",
"extract_zip",
"(",
"self",
",",
"suffix",
",",
"path",
"=",
"'.'",
")",
":",
"zip_fd",
",",
"zip_fn",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'fuzzfetch-'",
",",
"suffix",
"=",
"'.zip'",
")",
"os",
".",
"close",
"(",
"zip_fd",
"... | Download and extract a zip artifact
@type suffix:
@param suffix:
@type path:
@param path: | [
"Download",
"and",
"extract",
"a",
"zip",
"artifact"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L637-L656 | train | 51,220 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.download_apk | def download_apk(self, path='.'):
"""
Download Android .apk
@type path:
@param path:
"""
apk_fd, apk_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.apk')
os.close(apk_fd)
try:
_download_url(self.artifact_url('apk'), apk_fn)
shutil.copy(apk_fn, os.path.join(path, 'target.apk'))
finally:
os.unlink(apk_fn) | python | def download_apk(self, path='.'):
"""
Download Android .apk
@type path:
@param path:
"""
apk_fd, apk_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.apk')
os.close(apk_fd)
try:
_download_url(self.artifact_url('apk'), apk_fn)
shutil.copy(apk_fn, os.path.join(path, 'target.apk'))
finally:
os.unlink(apk_fn) | [
"def",
"download_apk",
"(",
"self",
",",
"path",
"=",
"'.'",
")",
":",
"apk_fd",
",",
"apk_fn",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'fuzzfetch-'",
",",
"suffix",
"=",
"'.apk'",
")",
"os",
".",
"close",
"(",
"apk_fd",
")",
"try",
":"... | Download Android .apk
@type path:
@param path: | [
"Download",
"Android",
".",
"apk"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L688-L701 | train | 51,221 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.extract_dmg | def extract_dmg(self, path='.'):
"""
Extract builds with .dmg extension
Will only work if `hdiutil` is available.
@type path:
@param path:
"""
dmg_fd, dmg_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.dmg')
os.close(dmg_fd)
out_tmp = tempfile.mkdtemp(prefix='fuzzfetch-', suffix='.tmp')
try:
_download_url(self.artifact_url('dmg'), dmg_fn)
if std_platform.system() == 'Darwin':
LOG.info('.. extracting')
subprocess.check_call(['hdiutil', 'attach', '-quiet', '-mountpoint', out_tmp, dmg_fn])
try:
apps = [mt for mt in os.listdir(out_tmp) if mt.endswith('app')]
assert len(apps) == 1
shutil.copytree(os.path.join(out_tmp, apps[0]), os.path.join(path, apps[0]), symlinks=True)
finally:
subprocess.check_call(['hdiutil', 'detach', '-quiet', out_tmp])
else:
LOG.warning('.. can\'t extract target.dmg on %s', std_platform.system())
shutil.copy(dmg_fn, os.path.join(path, 'target.dmg'))
finally:
shutil.rmtree(out_tmp, onerror=onerror)
os.unlink(dmg_fn) | python | def extract_dmg(self, path='.'):
"""
Extract builds with .dmg extension
Will only work if `hdiutil` is available.
@type path:
@param path:
"""
dmg_fd, dmg_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.dmg')
os.close(dmg_fd)
out_tmp = tempfile.mkdtemp(prefix='fuzzfetch-', suffix='.tmp')
try:
_download_url(self.artifact_url('dmg'), dmg_fn)
if std_platform.system() == 'Darwin':
LOG.info('.. extracting')
subprocess.check_call(['hdiutil', 'attach', '-quiet', '-mountpoint', out_tmp, dmg_fn])
try:
apps = [mt for mt in os.listdir(out_tmp) if mt.endswith('app')]
assert len(apps) == 1
shutil.copytree(os.path.join(out_tmp, apps[0]), os.path.join(path, apps[0]), symlinks=True)
finally:
subprocess.check_call(['hdiutil', 'detach', '-quiet', out_tmp])
else:
LOG.warning('.. can\'t extract target.dmg on %s', std_platform.system())
shutil.copy(dmg_fn, os.path.join(path, 'target.dmg'))
finally:
shutil.rmtree(out_tmp, onerror=onerror)
os.unlink(dmg_fn) | [
"def",
"extract_dmg",
"(",
"self",
",",
"path",
"=",
"'.'",
")",
":",
"dmg_fd",
",",
"dmg_fn",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'fuzzfetch-'",
",",
"suffix",
"=",
"'.dmg'",
")",
"os",
".",
"close",
"(",
"dmg_fd",
")",
"out_tmp",
... | Extract builds with .dmg extension
Will only work if `hdiutil` is available.
@type path:
@param path: | [
"Extract",
"builds",
"with",
".",
"dmg",
"extension"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L703-L731 | train | 51,222 |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | Fetcher.main | def main(cls):
"""
fuzzfetch main entry point
Run with --help for usage
"""
log_level = logging.INFO
log_fmt = '[%(asctime)s] %(message)s'
if bool(os.getenv('DEBUG')):
log_level = logging.DEBUG
log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s'
logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log_level)
logging.getLogger('requests').setLevel(logging.WARNING)
obj, extract_args = cls.from_args()
LOG.info('Identified task: %s', obj.task_url)
LOG.info('> Task ID: %s', obj.task_id)
LOG.info('> Rank: %s', obj.rank)
LOG.info('> Changeset: %s', obj.changeset)
LOG.info('> Build ID: %s', obj.build_id)
if extract_args['dry_run']:
return
out = extract_args['out']
os.mkdir(out)
try:
obj.extract_build(out, tests=extract_args['tests'], full_symbols=extract_args['full_symbols'])
os.makedirs(os.path.join(out, 'download'))
with open(os.path.join(out, 'download', 'firefox-temp.txt'), 'a') as dl_fd:
dl_fd.write('buildID=' + obj.build_id + os.linesep)
except: # noqa
if os.path.isdir(out):
junction_path.rmtree(out)
raise | python | def main(cls):
"""
fuzzfetch main entry point
Run with --help for usage
"""
log_level = logging.INFO
log_fmt = '[%(asctime)s] %(message)s'
if bool(os.getenv('DEBUG')):
log_level = logging.DEBUG
log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s'
logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log_level)
logging.getLogger('requests').setLevel(logging.WARNING)
obj, extract_args = cls.from_args()
LOG.info('Identified task: %s', obj.task_url)
LOG.info('> Task ID: %s', obj.task_id)
LOG.info('> Rank: %s', obj.rank)
LOG.info('> Changeset: %s', obj.changeset)
LOG.info('> Build ID: %s', obj.build_id)
if extract_args['dry_run']:
return
out = extract_args['out']
os.mkdir(out)
try:
obj.extract_build(out, tests=extract_args['tests'], full_symbols=extract_args['full_symbols'])
os.makedirs(os.path.join(out, 'download'))
with open(os.path.join(out, 'download', 'firefox-temp.txt'), 'a') as dl_fd:
dl_fd.write('buildID=' + obj.build_id + os.linesep)
except: # noqa
if os.path.isdir(out):
junction_path.rmtree(out)
raise | [
"def",
"main",
"(",
"cls",
")",
":",
"log_level",
"=",
"logging",
".",
"INFO",
"log_fmt",
"=",
"'[%(asctime)s] %(message)s'",
"if",
"bool",
"(",
"os",
".",
"getenv",
"(",
"'DEBUG'",
")",
")",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"log_fmt",
"="... | fuzzfetch main entry point
Run with --help for usage | [
"fuzzfetch",
"main",
"entry",
"point"
] | 166cbfc71b679db019b9ac777dce12ccfdfc2c10 | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L852-L888 | train | 51,223 |
ClericPy/torequests | torequests/crawlers.py | CleanRequest.sort_url_qsl | def sort_url_qsl(cls, raw_url, **kwargs):
"""Do nothing but sort the params of url.
raw_url: the raw url to be sorted;
kwargs: (optional) same kwargs for ``sorted``.
"""
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
return cls._join_url(parsed_url, sorted(qsl, **kwargs)) | python | def sort_url_qsl(cls, raw_url, **kwargs):
"""Do nothing but sort the params of url.
raw_url: the raw url to be sorted;
kwargs: (optional) same kwargs for ``sorted``.
"""
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
return cls._join_url(parsed_url, sorted(qsl, **kwargs)) | [
"def",
"sort_url_qsl",
"(",
"cls",
",",
"raw_url",
",",
"*",
"*",
"kwargs",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"raw_url",
")",
"qsl",
"=",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
")",
"return",
"cls",
".",
"_join_url",
"(",
"parsed_url",... | Do nothing but sort the params of url.
raw_url: the raw url to be sorted;
kwargs: (optional) same kwargs for ``sorted``. | [
"Do",
"nothing",
"but",
"sort",
"the",
"params",
"of",
"url",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L174-L182 | train | 51,224 |
ClericPy/torequests | torequests/crawlers.py | CleanRequest.clean_url | def clean_url(self):
"""Only clean the url params and return self."""
raw_url = self.request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
for qs in qsl:
new_url = self._join_url(parsed_url,
[i for i in qsl if i is not qs])
new_request = deepcopy(self.request)
new_request['url'] = new_url
self._add_task('qsl', qs, new_request)
return self | python | def clean_url(self):
"""Only clean the url params and return self."""
raw_url = self.request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
for qs in qsl:
new_url = self._join_url(parsed_url,
[i for i in qsl if i is not qs])
new_request = deepcopy(self.request)
new_request['url'] = new_url
self._add_task('qsl', qs, new_request)
return self | [
"def",
"clean_url",
"(",
"self",
")",
":",
"raw_url",
"=",
"self",
".",
"request",
"[",
"'url'",
"]",
"parsed_url",
"=",
"urlparse",
"(",
"raw_url",
")",
"qsl",
"=",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
")",
"for",
"qs",
"in",
"qsl",
":",
"n... | Only clean the url params and return self. | [
"Only",
"clean",
"the",
"url",
"params",
"and",
"return",
"self",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L201-L212 | train | 51,225 |
ClericPy/torequests | torequests/crawlers.py | CleanRequest.clean_cookie | def clean_cookie(self):
"""Only clean the cookie from headers and return self."""
if not self.is_cookie_necessary:
return self
headers = self.request.get('headers', {})
cookies = SimpleCookie(headers['Cookie'])
for k, v in cookies.items():
new_cookie = '; '.join(
[i.OutputString() for i in cookies.values() if i != v])
new_request = deepcopy(self.request)
new_request['headers']['Cookie'] = new_cookie
self._add_task('Cookie', k, new_request)
return self | python | def clean_cookie(self):
"""Only clean the cookie from headers and return self."""
if not self.is_cookie_necessary:
return self
headers = self.request.get('headers', {})
cookies = SimpleCookie(headers['Cookie'])
for k, v in cookies.items():
new_cookie = '; '.join(
[i.OutputString() for i in cookies.values() if i != v])
new_request = deepcopy(self.request)
new_request['headers']['Cookie'] = new_cookie
self._add_task('Cookie', k, new_request)
return self | [
"def",
"clean_cookie",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_cookie_necessary",
":",
"return",
"self",
"headers",
"=",
"self",
".",
"request",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
"cookies",
"=",
"SimpleCookie",
"(",
"headers"... | Only clean the cookie from headers and return self. | [
"Only",
"clean",
"the",
"cookie",
"from",
"headers",
"and",
"return",
"self",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L250-L262 | train | 51,226 |
ClericPy/torequests | torequests/crawlers.py | CleanRequest.reset_new_request | def reset_new_request(self):
"""Remove the non-sense args from the self.ignore, return self.new_request"""
raw_url = self.new_request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
new_url = self._join_url(
parsed_url, [i for i in qsl if i not in self.ignore['qsl']])
self.new_request['url'] = new_url
self.logger_function('ignore: %s' % self.ignore)
for key in self.ignore['headers']:
self.new_request['headers'].pop(key)
if not self.new_request.get('headers'):
self.new_request.pop('headers', None)
if self.ignore['Cookie'] and 'Cookie' not in self.ignore['headers']:
headers = self.new_request['headers']
headers = {key.title(): headers[key] for key in headers}
if 'Cookie' in headers:
cookies = SimpleCookie(headers['Cookie'])
new_cookie = '; '.join([
i[1].OutputString()
for i in cookies.items()
if i[0] not in self.ignore['Cookie']
])
self.new_request['headers']['Cookie'] = new_cookie
if self.new_request['method'] == 'post':
data = self.new_request.get('data')
if data:
if isinstance(data, dict):
for key in self.ignore['form_data']:
data.pop(key)
if (not data) or self.ignore['total_data']:
# not need data any more
self.new_request.pop('data', None)
if self.has_json_data and 'data' in self.new_request:
json_data = json.loads(data.decode(self.encoding))
for key in self.ignore['json_data']:
json_data.pop(key)
self.new_request['data'] = json.dumps(json_data).encode(
self.encoding)
return self.new_request | python | def reset_new_request(self):
"""Remove the non-sense args from the self.ignore, return self.new_request"""
raw_url = self.new_request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
new_url = self._join_url(
parsed_url, [i for i in qsl if i not in self.ignore['qsl']])
self.new_request['url'] = new_url
self.logger_function('ignore: %s' % self.ignore)
for key in self.ignore['headers']:
self.new_request['headers'].pop(key)
if not self.new_request.get('headers'):
self.new_request.pop('headers', None)
if self.ignore['Cookie'] and 'Cookie' not in self.ignore['headers']:
headers = self.new_request['headers']
headers = {key.title(): headers[key] for key in headers}
if 'Cookie' in headers:
cookies = SimpleCookie(headers['Cookie'])
new_cookie = '; '.join([
i[1].OutputString()
for i in cookies.items()
if i[0] not in self.ignore['Cookie']
])
self.new_request['headers']['Cookie'] = new_cookie
if self.new_request['method'] == 'post':
data = self.new_request.get('data')
if data:
if isinstance(data, dict):
for key in self.ignore['form_data']:
data.pop(key)
if (not data) or self.ignore['total_data']:
# not need data any more
self.new_request.pop('data', None)
if self.has_json_data and 'data' in self.new_request:
json_data = json.loads(data.decode(self.encoding))
for key in self.ignore['json_data']:
json_data.pop(key)
self.new_request['data'] = json.dumps(json_data).encode(
self.encoding)
return self.new_request | [
"def",
"reset_new_request",
"(",
"self",
")",
":",
"raw_url",
"=",
"self",
".",
"new_request",
"[",
"'url'",
"]",
"parsed_url",
"=",
"urlparse",
"(",
"raw_url",
")",
"qsl",
"=",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
")",
"new_url",
"=",
"self",
"... | Remove the non-sense args from the self.ignore, return self.new_request | [
"Remove",
"the",
"non",
"-",
"sense",
"args",
"from",
"the",
"self",
".",
"ignore",
"return",
"self",
".",
"new_request"
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L282-L323 | train | 51,227 |
ClericPy/torequests | torequests/crawlers.py | CleanRequest.result | def result(self):
"""Whole task, clean_all + reset_new_request, return self.new_request."""
if not self.tasks:
self.clean_all()
tasks_length = len(self.tasks)
self.logger_function(
'%s tasks of request, will cost at least %s seconds.' %
(tasks_length,
round(self.req.interval / self.req.n * tasks_length, 2)))
self.req.x
for task in self.tasks:
key, value, fut = task
if fut.x and fut.cx:
# fut.x == req success & fut.cx == response not changed.
self.ignore[key].append(value)
return self.reset_new_request() | python | def result(self):
"""Whole task, clean_all + reset_new_request, return self.new_request."""
if not self.tasks:
self.clean_all()
tasks_length = len(self.tasks)
self.logger_function(
'%s tasks of request, will cost at least %s seconds.' %
(tasks_length,
round(self.req.interval / self.req.n * tasks_length, 2)))
self.req.x
for task in self.tasks:
key, value, fut = task
if fut.x and fut.cx:
# fut.x == req success & fut.cx == response not changed.
self.ignore[key].append(value)
return self.reset_new_request() | [
"def",
"result",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"self",
".",
"clean_all",
"(",
")",
"tasks_length",
"=",
"len",
"(",
"self",
".",
"tasks",
")",
"self",
".",
"logger_function",
"(",
"'%s tasks of request, will cost at least %s ... | Whole task, clean_all + reset_new_request, return self.new_request. | [
"Whole",
"task",
"clean_all",
"+",
"reset_new_request",
"return",
"self",
".",
"new_request",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L329-L344 | train | 51,228 |
vsoch/helpme | helpme/client/__init__.py | main | def main():
'''the main entry point for the HelpMe Command line application. Currently,
the user can request help or set config values for a particular helper.
'''
# Customize parser
parser = get_parser()
subparsers = get_subparsers(parser)
def help(return_code=0):
'''print help, including the software version and active client
and exit with return code.
'''
version = helpme.__version__
bot.custom(message='Command Line Tool v%s' %version,
prefix='\n[HelpMe] ',
color='CYAN')
parser.print_help()
sys.exit(return_code)
# If the user didn't provide any arguments, show the full help
if len(sys.argv) == 1:
help()
try:
args, unknown = parser.parse_known_args()
except:
sys.exit(0)
extras = None
if args.command in HELPME_HELPERS and len(unknown) > 0:
extras = unknown
# if environment logging variable not set, make silent
if args.debug is False:
os.environ['MESSAGELEVEL'] = "INFO"
# Show the version and exit
if args.version is True:
print(helpme.__version__)
sys.exit(0)
if args.command == "config": from .config import main
if args.command == "list": from .list import main
if args.command in HELPME_HELPERS: from .help import main
# Pass on to the correct parser
return_code = 0
try:
main(args, extras)
sys.exit(return_code)
except UnboundLocalError:
return_code = 1
help(return_code) | python | def main():
'''the main entry point for the HelpMe Command line application. Currently,
the user can request help or set config values for a particular helper.
'''
# Customize parser
parser = get_parser()
subparsers = get_subparsers(parser)
def help(return_code=0):
'''print help, including the software version and active client
and exit with return code.
'''
version = helpme.__version__
bot.custom(message='Command Line Tool v%s' %version,
prefix='\n[HelpMe] ',
color='CYAN')
parser.print_help()
sys.exit(return_code)
# If the user didn't provide any arguments, show the full help
if len(sys.argv) == 1:
help()
try:
args, unknown = parser.parse_known_args()
except:
sys.exit(0)
extras = None
if args.command in HELPME_HELPERS and len(unknown) > 0:
extras = unknown
# if environment logging variable not set, make silent
if args.debug is False:
os.environ['MESSAGELEVEL'] = "INFO"
# Show the version and exit
if args.version is True:
print(helpme.__version__)
sys.exit(0)
if args.command == "config": from .config import main
if args.command == "list": from .list import main
if args.command in HELPME_HELPERS: from .help import main
# Pass on to the correct parser
return_code = 0
try:
main(args, extras)
sys.exit(return_code)
except UnboundLocalError:
return_code = 1
help(return_code) | [
"def",
"main",
"(",
")",
":",
"# Customize parser",
"parser",
"=",
"get_parser",
"(",
")",
"subparsers",
"=",
"get_subparsers",
"(",
"parser",
")",
"def",
"help",
"(",
"return_code",
"=",
"0",
")",
":",
"'''print help, including the software version and active clien... | the main entry point for the HelpMe Command line application. Currently,
the user can request help or set config values for a particular helper. | [
"the",
"main",
"entry",
"point",
"for",
"the",
"HelpMe",
"Command",
"line",
"application",
".",
"Currently",
"the",
"user",
"can",
"request",
"help",
"or",
"set",
"config",
"values",
"for",
"a",
"particular",
"helper",
"."
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/client/__init__.py#L95-L153 | train | 51,229 |
mjirik/io3d | io3d/datawriter.py | saveOverlayToDicomCopy | def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
crinfo, orig_shape):
""" Save overlay to dicom. """
from . import datawriter as dwriter
# import qmisc
if not os.path.exists(output_dicom_dir):
os.makedirs(output_dicom_dir)
import imtools.image_manipulation
# uncrop all overlays
for key in overlays:
overlays[key] = imtools.image_manipulation.uncrop(overlays[key], crinfo, orig_shape)
dw = dwriter.DataWriter()
dw.DataCopyWithOverlay(input_dcmfilelist, output_dicom_dir, overlays) | python | def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
crinfo, orig_shape):
""" Save overlay to dicom. """
from . import datawriter as dwriter
# import qmisc
if not os.path.exists(output_dicom_dir):
os.makedirs(output_dicom_dir)
import imtools.image_manipulation
# uncrop all overlays
for key in overlays:
overlays[key] = imtools.image_manipulation.uncrop(overlays[key], crinfo, orig_shape)
dw = dwriter.DataWriter()
dw.DataCopyWithOverlay(input_dcmfilelist, output_dicom_dir, overlays) | [
"def",
"saveOverlayToDicomCopy",
"(",
"input_dcmfilelist",
",",
"output_dicom_dir",
",",
"overlays",
",",
"crinfo",
",",
"orig_shape",
")",
":",
"from",
".",
"import",
"datawriter",
"as",
"dwriter",
"# import qmisc",
"if",
"not",
"os",
".",
"path",
".",
"exists"... | Save overlay to dicom. | [
"Save",
"overlay",
"to",
"dicom",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datawriter.py#L527-L542 | train | 51,230 |
mjirik/io3d | io3d/datawriter.py | DataWriter.__get_segmentation_path | def __get_segmentation_path(self, path):
""" Create path with "_segmentation" suffix and keep extension.
:param path:
:return:
"""
startpath, ext = os.path.splitext(path)
segmentation_path = startpath + "_segmentation" + ext
return segmentation_path | python | def __get_segmentation_path(self, path):
""" Create path with "_segmentation" suffix and keep extension.
:param path:
:return:
"""
startpath, ext = os.path.splitext(path)
segmentation_path = startpath + "_segmentation" + ext
return segmentation_path | [
"def",
"__get_segmentation_path",
"(",
"self",
",",
"path",
")",
":",
"startpath",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"segmentation_path",
"=",
"startpath",
"+",
"\"_segmentation\"",
"+",
"ext",
"return",
"segmentation_path"... | Create path with "_segmentation" suffix and keep extension.
:param path:
:return: | [
"Create",
"path",
"with",
"_segmentation",
"suffix",
"and",
"keep",
"extension",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datawriter.py#L48-L56 | train | 51,231 |
mjirik/io3d | io3d/datawriter.py | DataWriter.add_overlay_to_slice_file | def add_overlay_to_slice_file(
self,
filename,
overlay,
i_overlay,
filename_out=None
):
""" Function adds overlay to existing file.
"""
if filename_out is None:
filename_out = filename
filename = op.expanduser(filename)
data = dicom.read_file(filename)
data = self.encode_overlay_slice(data, overlay, i_overlay)
data.save_as(filename_out) | python | def add_overlay_to_slice_file(
self,
filename,
overlay,
i_overlay,
filename_out=None
):
""" Function adds overlay to existing file.
"""
if filename_out is None:
filename_out = filename
filename = op.expanduser(filename)
data = dicom.read_file(filename)
data = self.encode_overlay_slice(data, overlay, i_overlay)
data.save_as(filename_out) | [
"def",
"add_overlay_to_slice_file",
"(",
"self",
",",
"filename",
",",
"overlay",
",",
"i_overlay",
",",
"filename_out",
"=",
"None",
")",
":",
"if",
"filename_out",
"is",
"None",
":",
"filename_out",
"=",
"filename",
"filename",
"=",
"op",
".",
"expanduser",
... | Function adds overlay to existing file. | [
"Function",
"adds",
"overlay",
"to",
"existing",
"file",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datawriter.py#L240-L254 | train | 51,232 |
mjirik/io3d | io3d/deprecation.py | deprecated | def deprecated(instructions):
"""
Flags a method as deprecated.
:param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.'
:return: DeprecatedWarning
"""
def decorator(func):
"""This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
message = 'Call to deprecated function {}. {}'.format(func.__name__,
instructions)
frame = inspect.currentframe().f_back
warnings.warn_explicit(message,
category=DeprecatedWarning,
filename=inspect.getfile(frame.f_code),
lineno=frame.f_lineno)
return func(*args, **kwargs)
return wrapper
return decorator | python | def deprecated(instructions):
"""
Flags a method as deprecated.
:param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.'
:return: DeprecatedWarning
"""
def decorator(func):
"""This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
message = 'Call to deprecated function {}. {}'.format(func.__name__,
instructions)
frame = inspect.currentframe().f_back
warnings.warn_explicit(message,
category=DeprecatedWarning,
filename=inspect.getfile(frame.f_code),
lineno=frame.f_lineno)
return func(*args, **kwargs)
return wrapper
return decorator | [
"def",
"deprecated",
"(",
"instructions",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"This is a decorator which can be used to mark functions as deprecated.\n\n It will result in a warning being emitted when the function is used.\n \"\"\"",
"@",
"functools",... | Flags a method as deprecated.
:param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.'
:return: DeprecatedWarning | [
"Flags",
"a",
"method",
"as",
"deprecated",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/deprecation.py#L15-L38 | train | 51,233 |
SetBased/py-stratum | pystratum/style/PyStratumStyle.py | PyStratumStyle.log_verbose | def log_verbose(self, message):
"""
Logs a message only when logging level is verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERBOSE:
self.writeln(message) | python | def log_verbose(self, message):
"""
Logs a message only when logging level is verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERBOSE:
self.writeln(message) | [
"def",
"log_verbose",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
">=",
"Output",
".",
"VERBOSITY_VERBOSE",
":",
"self",
".",
"writeln",
"(",
"message",
")"
] | Logs a message only when logging level is verbose.
:param str|list[str] message: The message. | [
"Logs",
"a",
"message",
"only",
"when",
"logging",
"level",
"is",
"verbose",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/style/PyStratumStyle.py#L50-L57 | train | 51,234 |
SetBased/py-stratum | pystratum/style/PyStratumStyle.py | PyStratumStyle.log_very_verbose | def log_very_verbose(self, message):
"""
Logs a message only when logging level is very verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE:
self.writeln(message) | python | def log_very_verbose(self, message):
"""
Logs a message only when logging level is very verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE:
self.writeln(message) | [
"def",
"log_very_verbose",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
">=",
"Output",
".",
"VERBOSITY_VERY_VERBOSE",
":",
"self",
".",
"writeln",
"(",
"message",
")"
] | Logs a message only when logging level is very verbose.
:param str|list[str] message: The message. | [
"Logs",
"a",
"message",
"only",
"when",
"logging",
"level",
"is",
"very",
"verbose",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/style/PyStratumStyle.py#L60-L67 | train | 51,235 |
PlaidWeb/Pushl | pushl/feeds.py | get_feed | async def get_feed(config, url):
""" Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed
"""
LOGGER.debug("++WAIT: cache get feed %s", url)
previous = config.cache.get(
'feed', url, schema_version=SCHEMA_VERSION) if config.cache else None
LOGGER.debug("++DONE: cache get feed %s", url)
headers = previous.caching if previous else None
LOGGER.debug("++WAIT: request get %s", url)
request = await utils.retry_get(config, url, headers=headers)
LOGGER.debug("++DONE: request get %s", url)
if not request or not request.success:
LOGGER.error("Could not get feed %s: %d",
url,
request.status if request else -1)
return None, previous, False
if request.cached:
LOGGER.debug("%s: Reusing cached version", url)
return previous, previous, False
current = Feed(request)
if config.cache:
LOGGER.debug("%s: Saving to cache", url)
LOGGER.debug("++WAIT: cache set feed %s", url)
config.cache.set('feed', url, current)
LOGGER.debug("++DONE: cache set feed %s", url)
LOGGER.debug("%s: Returning new content", url)
return current, previous, (not previous
or current.digest != previous.digest
or current.status != previous.status) | python | async def get_feed(config, url):
""" Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed
"""
LOGGER.debug("++WAIT: cache get feed %s", url)
previous = config.cache.get(
'feed', url, schema_version=SCHEMA_VERSION) if config.cache else None
LOGGER.debug("++DONE: cache get feed %s", url)
headers = previous.caching if previous else None
LOGGER.debug("++WAIT: request get %s", url)
request = await utils.retry_get(config, url, headers=headers)
LOGGER.debug("++DONE: request get %s", url)
if not request or not request.success:
LOGGER.error("Could not get feed %s: %d",
url,
request.status if request else -1)
return None, previous, False
if request.cached:
LOGGER.debug("%s: Reusing cached version", url)
return previous, previous, False
current = Feed(request)
if config.cache:
LOGGER.debug("%s: Saving to cache", url)
LOGGER.debug("++WAIT: cache set feed %s", url)
config.cache.set('feed', url, current)
LOGGER.debug("++DONE: cache set feed %s", url)
LOGGER.debug("%s: Returning new content", url)
return current, previous, (not previous
or current.digest != previous.digest
or current.status != previous.status) | [
"async",
"def",
"get_feed",
"(",
"config",
",",
"url",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"++WAIT: cache get feed %s\"",
",",
"url",
")",
"previous",
"=",
"config",
".",
"cache",
".",
"get",
"(",
"'feed'",
",",
"url",
",",
"schema_version",
"=",
"S... | Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed | [
"Get",
"a",
"feed"
] | 5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/feeds.py#L95-L137 | train | 51,236 |
PlaidWeb/Pushl | pushl/feeds.py | Feed.archive_namespace | def archive_namespace(self):
""" Returns the known namespace of the RFC5005 extension, if any """
try:
for ns_prefix, url in self.feed.namespaces.items():
if url == 'http://purl.org/syndication/history/1.0':
return ns_prefix
except AttributeError:
pass
return None | python | def archive_namespace(self):
""" Returns the known namespace of the RFC5005 extension, if any """
try:
for ns_prefix, url in self.feed.namespaces.items():
if url == 'http://purl.org/syndication/history/1.0':
return ns_prefix
except AttributeError:
pass
return None | [
"def",
"archive_namespace",
"(",
"self",
")",
":",
"try",
":",
"for",
"ns_prefix",
",",
"url",
"in",
"self",
".",
"feed",
".",
"namespaces",
".",
"items",
"(",
")",
":",
"if",
"url",
"==",
"'http://purl.org/syndication/history/1.0'",
":",
"return",
"ns_prefi... | Returns the known namespace of the RFC5005 extension, if any | [
"Returns",
"the",
"known",
"namespace",
"of",
"the",
"RFC5005",
"extension",
"if",
"any"
] | 5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/feeds.py#L33-L41 | train | 51,237 |
PlaidWeb/Pushl | pushl/feeds.py | Feed.is_archive | def is_archive(self):
""" Given a parsed feed, returns True if this is an archive feed """
ns_prefix = self.archive_namespace
if ns_prefix:
if ns_prefix + '_archive' in self.feed.feed:
# This is declared to be an archive view
return True
if ns_prefix + '_current' in self.feed.feed:
# This is declared to be the current view
return False
# Either we don't have the namespace, or the view wasn't declared.
rels = collections.defaultdict(list)
for link in self.feed.feed.links:
rels[link.rel].append(link.href)
return ('current' in rels and
('self' not in rels or
rels['self'] != rels['current'])) | python | def is_archive(self):
""" Given a parsed feed, returns True if this is an archive feed """
ns_prefix = self.archive_namespace
if ns_prefix:
if ns_prefix + '_archive' in self.feed.feed:
# This is declared to be an archive view
return True
if ns_prefix + '_current' in self.feed.feed:
# This is declared to be the current view
return False
# Either we don't have the namespace, or the view wasn't declared.
rels = collections.defaultdict(list)
for link in self.feed.feed.links:
rels[link.rel].append(link.href)
return ('current' in rels and
('self' not in rels or
rels['self'] != rels['current'])) | [
"def",
"is_archive",
"(",
"self",
")",
":",
"ns_prefix",
"=",
"self",
".",
"archive_namespace",
"if",
"ns_prefix",
":",
"if",
"ns_prefix",
"+",
"'_archive'",
"in",
"self",
".",
"feed",
".",
"feed",
":",
"# This is declared to be an archive view",
"return",
"True... | Given a parsed feed, returns True if this is an archive feed | [
"Given",
"a",
"parsed",
"feed",
"returns",
"True",
"if",
"this",
"is",
"an",
"archive",
"feed"
] | 5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/feeds.py#L51-L70 | train | 51,238 |
PlaidWeb/Pushl | pushl/feeds.py | Feed.update_websub | async def update_websub(self, config, hub):
""" Update WebSub hub to know about this feed """
try:
LOGGER.debug("WebSub: Notifying %s of %s", hub, self.url)
request = await utils.retry_post(
config,
hub,
data={
'hub.mode': 'publish',
'hub.url': self.url
})
if request.success:
LOGGER.info("%s: WebSub notification sent to %s",
self.url, hub)
else:
LOGGER.warning("%s: Hub %s returned status code %s: %s", self.url, hub,
request.status, request.text)
except Exception as err: # pylint:disable=broad-except
LOGGER.warning("WebSub %s: got %s: %s",
hub, err.__class__.__name__, err) | python | async def update_websub(self, config, hub):
""" Update WebSub hub to know about this feed """
try:
LOGGER.debug("WebSub: Notifying %s of %s", hub, self.url)
request = await utils.retry_post(
config,
hub,
data={
'hub.mode': 'publish',
'hub.url': self.url
})
if request.success:
LOGGER.info("%s: WebSub notification sent to %s",
self.url, hub)
else:
LOGGER.warning("%s: Hub %s returned status code %s: %s", self.url, hub,
request.status, request.text)
except Exception as err: # pylint:disable=broad-except
LOGGER.warning("WebSub %s: got %s: %s",
hub, err.__class__.__name__, err) | [
"async",
"def",
"update_websub",
"(",
"self",
",",
"config",
",",
"hub",
")",
":",
"try",
":",
"LOGGER",
".",
"debug",
"(",
"\"WebSub: Notifying %s of %s\"",
",",
"hub",
",",
"self",
".",
"url",
")",
"request",
"=",
"await",
"utils",
".",
"retry_post",
"... | Update WebSub hub to know about this feed | [
"Update",
"WebSub",
"hub",
"to",
"know",
"about",
"this",
"feed"
] | 5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c | https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/feeds.py#L72-L92 | train | 51,239 |
SetBased/py-stratum | pystratum/DocBlockReflection.py | DocBlockReflection.get_tags | def get_tags(self, name):
"""
Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str]
"""
tags = list()
for tag in self._tags:
if tag[0] == name:
tags.append(tag[1])
return tags | python | def get_tags(self, name):
"""
Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str]
"""
tags = list()
for tag in self._tags:
if tag[0] == name:
tags.append(tag[1])
return tags | [
"def",
"get_tags",
"(",
"self",
",",
"name",
")",
":",
"tags",
"=",
"list",
"(",
")",
"for",
"tag",
"in",
"self",
".",
"_tags",
":",
"if",
"tag",
"[",
"0",
"]",
"==",
"name",
":",
"tags",
".",
"append",
"(",
"tag",
"[",
"1",
"]",
")",
"return... | Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str] | [
"Returns",
"a",
"list",
"of",
"tags",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/DocBlockReflection.py#L68-L81 | train | 51,240 |
SetBased/py-stratum | pystratum/DocBlockReflection.py | DocBlockReflection.__clean_doc_block | def __clean_doc_block(self):
"""
Cleans the DocBlock from leading and trailing white space and comment tokens.
"""
# Return immediately if the DockBlock is empty.
if not self._comment:
return
for i in range(1, len(self._comment) - 1):
self._comment[i] = re.sub(r'^\s*\*', '', self._comment[i])
self._comment[0] = re.sub(r'^\s*/\*\*', '', self._comment[0])
self._comment[-1] = re.sub(r'\*/\s*$', '', self._comment[-1])
for i, line in enumerate(self._comment):
self._comment[i] = line.strip()
self._comment = self.__remove_leading_empty_lines(self._comment)
self._comment = self.__remove_trailing_empty_lines(self._comment) | python | def __clean_doc_block(self):
"""
Cleans the DocBlock from leading and trailing white space and comment tokens.
"""
# Return immediately if the DockBlock is empty.
if not self._comment:
return
for i in range(1, len(self._comment) - 1):
self._comment[i] = re.sub(r'^\s*\*', '', self._comment[i])
self._comment[0] = re.sub(r'^\s*/\*\*', '', self._comment[0])
self._comment[-1] = re.sub(r'\*/\s*$', '', self._comment[-1])
for i, line in enumerate(self._comment):
self._comment[i] = line.strip()
self._comment = self.__remove_leading_empty_lines(self._comment)
self._comment = self.__remove_trailing_empty_lines(self._comment) | [
"def",
"__clean_doc_block",
"(",
"self",
")",
":",
"# Return immediately if the DockBlock is empty.",
"if",
"not",
"self",
".",
"_comment",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"_comment",
")",
"-",
"1",
")",
":... | Cleans the DocBlock from leading and trailing white space and comment tokens. | [
"Cleans",
"the",
"DocBlock",
"from",
"leading",
"and",
"trailing",
"white",
"space",
"and",
"comment",
"tokens",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/DocBlockReflection.py#L125-L144 | train | 51,241 |
SetBased/py-stratum | pystratum/DocBlockReflection.py | DocBlockReflection.__extract_description | def __extract_description(self):
"""
Extracts the description from the DocBlock. The description start at the first line and stops at the first tag
or the end of the DocBlock.
"""
tmp = list()
for line in self._comment:
if len(line) >= 1 and line[0] == '@':
break
tmp.append(line)
tmp = self.__remove_trailing_empty_lines(tmp)
self._description = os.linesep.join(tmp) | python | def __extract_description(self):
"""
Extracts the description from the DocBlock. The description start at the first line and stops at the first tag
or the end of the DocBlock.
"""
tmp = list()
for line in self._comment:
if len(line) >= 1 and line[0] == '@':
break
tmp.append(line)
tmp = self.__remove_trailing_empty_lines(tmp)
self._description = os.linesep.join(tmp) | [
"def",
"__extract_description",
"(",
"self",
")",
":",
"tmp",
"=",
"list",
"(",
")",
"for",
"line",
"in",
"self",
".",
"_comment",
":",
"if",
"len",
"(",
"line",
")",
">=",
"1",
"and",
"line",
"[",
"0",
"]",
"==",
"'@'",
":",
"break",
"tmp",
".",... | Extracts the description from the DocBlock. The description start at the first line and stops at the first tag
or the end of the DocBlock. | [
"Extracts",
"the",
"description",
"from",
"the",
"DocBlock",
".",
"The",
"description",
"start",
"at",
"the",
"first",
"line",
"and",
"stops",
"at",
"the",
"first",
"tag",
"or",
"the",
"end",
"of",
"the",
"DocBlock",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/DocBlockReflection.py#L147-L161 | train | 51,242 |
SetBased/py-stratum | pystratum/DocBlockReflection.py | DocBlockReflection.__extract_tags | def __extract_tags(self):
"""
Extract tags from the DocBlock.
"""
tags = list()
current = None
for line in self._comment:
parts = re.match(r'^@(\w+)', line)
if parts:
current = (parts.group(1), list())
tags.append(current)
if current:
if line == '':
current = None
else:
current[1].append(line)
for tag in tags:
self._tags.append((tag[0], os.linesep.join(tag[1]))) | python | def __extract_tags(self):
"""
Extract tags from the DocBlock.
"""
tags = list()
current = None
for line in self._comment:
parts = re.match(r'^@(\w+)', line)
if parts:
current = (parts.group(1), list())
tags.append(current)
if current:
if line == '':
current = None
else:
current[1].append(line)
for tag in tags:
self._tags.append((tag[0], os.linesep.join(tag[1]))) | [
"def",
"__extract_tags",
"(",
"self",
")",
":",
"tags",
"=",
"list",
"(",
")",
"current",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"_comment",
":",
"parts",
"=",
"re",
".",
"match",
"(",
"r'^@(\\w+)'",
",",
"line",
")",
"if",
"parts",
":",
"c... | Extract tags from the DocBlock. | [
"Extract",
"tags",
"from",
"the",
"DocBlock",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/DocBlockReflection.py#L164-L183 | train | 51,243 |
SetBased/py-stratum | pystratum/command/ConstantsCommand.py | ConstantsCommand.handle | def handle(self):
"""
Executes constants command when PyStratumCommand is activated.
"""
self.output = PyStratumStyle(self.input, self.output)
config_file = self.input.get_argument('config_file')
self.run_command(config_file) | python | def handle(self):
"""
Executes constants command when PyStratumCommand is activated.
"""
self.output = PyStratumStyle(self.input, self.output)
config_file = self.input.get_argument('config_file')
self.run_command(config_file) | [
"def",
"handle",
"(",
"self",
")",
":",
"self",
".",
"output",
"=",
"PyStratumStyle",
"(",
"self",
".",
"input",
",",
"self",
".",
"output",
")",
"config_file",
"=",
"self",
".",
"input",
".",
"get_argument",
"(",
"'config_file'",
")",
"self",
".",
"ru... | Executes constants command when PyStratumCommand is activated. | [
"Executes",
"constants",
"command",
"when",
"PyStratumCommand",
"is",
"activated",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/command/ConstantsCommand.py#L28-L35 | train | 51,244 |
launchdarkly/relayCommander | relay_commander/redis_wrapper.py | RedisWrapper._format_key_name | def _format_key_name(self) -> str:
"""Return formatted redis key name."""
key_name = 'ld:{0}:{1}:features'.format(
self.project_key,
self.environment_key
)
return key_name | python | def _format_key_name(self) -> str:
"""Return formatted redis key name."""
key_name = 'ld:{0}:{1}:features'.format(
self.project_key,
self.environment_key
)
return key_name | [
"def",
"_format_key_name",
"(",
"self",
")",
"->",
"str",
":",
"key_name",
"=",
"'ld:{0}:{1}:features'",
".",
"format",
"(",
"self",
".",
"project_key",
",",
"self",
".",
"environment_key",
")",
"return",
"key_name"
] | Return formatted redis key name. | [
"Return",
"formatted",
"redis",
"key",
"name",
"."
] | eee7fa22f04edc3854dd53c3ec2db8c599ad1e89 | https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/redis_wrapper.py#L59-L65 | train | 51,245 |
launchdarkly/relayCommander | relay_commander/redis_wrapper.py | RedisWrapper.connection_string_parser | def connection_string_parser(uri: str) -> list:
"""
Parse Connection string to extract host and port.
:param uri: full URI for redis connection in the form of host:port
:returns: list of RedisConnection objects
"""
redis_connections = []
raw_connections = uri.split(',')
connections = [
connection for connection in raw_connections if len(connection) > 0
]
for connection in connections:
raw_connection = connection.split(':')
if len(raw_connection) == 1:
host = raw_connection[0].strip()
port = _DEFAULT_REDIS_PORT
elif len(raw_connection) == 2:
host = raw_connection[0].strip()
port = int(raw_connection[1])
else:
raise RuntimeError(
"Unable to parse redis connection string: {0}".format(
raw_connection
)
)
redis_connection = _RedisConnection(host, port)
redis_connections.append(redis_connection)
return redis_connections | python | def connection_string_parser(uri: str) -> list:
"""
Parse Connection string to extract host and port.
:param uri: full URI for redis connection in the form of host:port
:returns: list of RedisConnection objects
"""
redis_connections = []
raw_connections = uri.split(',')
connections = [
connection for connection in raw_connections if len(connection) > 0
]
for connection in connections:
raw_connection = connection.split(':')
if len(raw_connection) == 1:
host = raw_connection[0].strip()
port = _DEFAULT_REDIS_PORT
elif len(raw_connection) == 2:
host = raw_connection[0].strip()
port = int(raw_connection[1])
else:
raise RuntimeError(
"Unable to parse redis connection string: {0}".format(
raw_connection
)
)
redis_connection = _RedisConnection(host, port)
redis_connections.append(redis_connection)
return redis_connections | [
"def",
"connection_string_parser",
"(",
"uri",
":",
"str",
")",
"->",
"list",
":",
"redis_connections",
"=",
"[",
"]",
"raw_connections",
"=",
"uri",
".",
"split",
"(",
"','",
")",
"connections",
"=",
"[",
"connection",
"for",
"connection",
"in",
"raw_connec... | Parse Connection string to extract host and port.
:param uri: full URI for redis connection in the form of host:port
:returns: list of RedisConnection objects | [
"Parse",
"Connection",
"string",
"to",
"extract",
"host",
"and",
"port",
"."
] | eee7fa22f04edc3854dd53c3ec2db8c599ad1e89 | https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/redis_wrapper.py#L68-L100 | train | 51,246 |
launchdarkly/relayCommander | relay_commander/redis_wrapper.py | RedisWrapper.get_flag_record | def get_flag_record(self, feature_key: str) -> str:
"""Get feature flag record from redis.
:param feature_key: key for feature flag
:return: value of feature flag key in redis.
:raises: KeyError if key is not found.
"""
key_name = self._format_key_name()
flag = self.redis.hget(key_name, feature_key)
if flag is None:
raise KeyError('Redis key: {0} not found.'.format(key_name))
return flag | python | def get_flag_record(self, feature_key: str) -> str:
"""Get feature flag record from redis.
:param feature_key: key for feature flag
:return: value of feature flag key in redis.
:raises: KeyError if key is not found.
"""
key_name = self._format_key_name()
flag = self.redis.hget(key_name, feature_key)
if flag is None:
raise KeyError('Redis key: {0} not found.'.format(key_name))
return flag | [
"def",
"get_flag_record",
"(",
"self",
",",
"feature_key",
":",
"str",
")",
"->",
"str",
":",
"key_name",
"=",
"self",
".",
"_format_key_name",
"(",
")",
"flag",
"=",
"self",
".",
"redis",
".",
"hget",
"(",
"key_name",
",",
"feature_key",
")",
"if",
"f... | Get feature flag record from redis.
:param feature_key: key for feature flag
:return: value of feature flag key in redis.
:raises: KeyError if key is not found. | [
"Get",
"feature",
"flag",
"record",
"from",
"redis",
"."
] | eee7fa22f04edc3854dd53c3ec2db8c599ad1e89 | https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/redis_wrapper.py#L102-L117 | train | 51,247 |
launchdarkly/relayCommander | relay_commander/redis_wrapper.py | RedisWrapper.update_flag_record | def update_flag_record(self, state: str, feature_key: str) -> None:
"""Update redis record with new state.
:param state: state for feature flag.
:param feature_key: key for feature flag.
"""
key_name = self._format_key_name()
try:
parsed_flag = json.loads(self.get_flag_record(feature_key).decode('utf-8'))
parsed_flag['on'] = state
parsed_flag['version'] += 1
updated_flag = json.dumps(parsed_flag).encode('utf-8')
except KeyError as ex:
LOG.error(ex)
sys.exit(1)
LOG.info('updating %s to %s', feature_key, state)
self.redis.hset(key_name, feature_key, updated_flag) | python | def update_flag_record(self, state: str, feature_key: str) -> None:
"""Update redis record with new state.
:param state: state for feature flag.
:param feature_key: key for feature flag.
"""
key_name = self._format_key_name()
try:
parsed_flag = json.loads(self.get_flag_record(feature_key).decode('utf-8'))
parsed_flag['on'] = state
parsed_flag['version'] += 1
updated_flag = json.dumps(parsed_flag).encode('utf-8')
except KeyError as ex:
LOG.error(ex)
sys.exit(1)
LOG.info('updating %s to %s', feature_key, state)
self.redis.hset(key_name, feature_key, updated_flag) | [
"def",
"update_flag_record",
"(",
"self",
",",
"state",
":",
"str",
",",
"feature_key",
":",
"str",
")",
"->",
"None",
":",
"key_name",
"=",
"self",
".",
"_format_key_name",
"(",
")",
"try",
":",
"parsed_flag",
"=",
"json",
".",
"loads",
"(",
"self",
"... | Update redis record with new state.
:param state: state for feature flag.
:param feature_key: key for feature flag. | [
"Update",
"redis",
"record",
"with",
"new",
"state",
"."
] | eee7fa22f04edc3854dd53c3ec2db8c599ad1e89 | https://github.com/launchdarkly/relayCommander/blob/eee7fa22f04edc3854dd53c3ec2db8c599ad1e89/relay_commander/redis_wrapper.py#L119-L137 | train | 51,248 |
ClericPy/torequests | torequests/dummy.py | Asyncme | def Asyncme(func, n=None, interval=0, default_callback=None, loop=None):
"""Wrap coro_function into the function return NewTask."""
return coros(n, interval, default_callback, loop)(func) | python | def Asyncme(func, n=None, interval=0, default_callback=None, loop=None):
"""Wrap coro_function into the function return NewTask."""
return coros(n, interval, default_callback, loop)(func) | [
"def",
"Asyncme",
"(",
"func",
",",
"n",
"=",
"None",
",",
"interval",
"=",
"0",
",",
"default_callback",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"return",
"coros",
"(",
"n",
",",
"interval",
",",
"default_callback",
",",
"loop",
")",
"(",
... | Wrap coro_function into the function return NewTask. | [
"Wrap",
"coro_function",
"into",
"the",
"function",
"return",
"NewTask",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L332-L334 | train | 51,249 |
ClericPy/torequests | torequests/dummy.py | coros | def coros(n=None, interval=0, default_callback=None, loop=None):
"""Decorator for wrap coro_function into the function return NewTask."""
submitter = Loop(
n=n, interval=interval, default_callback=default_callback, loop=loop
).submitter
return submitter | python | def coros(n=None, interval=0, default_callback=None, loop=None):
"""Decorator for wrap coro_function into the function return NewTask."""
submitter = Loop(
n=n, interval=interval, default_callback=default_callback, loop=loop
).submitter
return submitter | [
"def",
"coros",
"(",
"n",
"=",
"None",
",",
"interval",
"=",
"0",
",",
"default_callback",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"submitter",
"=",
"Loop",
"(",
"n",
"=",
"n",
",",
"interval",
"=",
"interval",
",",
"default_callback",
"=",
... | Decorator for wrap coro_function into the function return NewTask. | [
"Decorator",
"for",
"wrap",
"coro_function",
"into",
"the",
"function",
"return",
"NewTask",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L337-L343 | train | 51,250 |
ClericPy/torequests | torequests/dummy.py | NewTask.wrap_callback | def wrap_callback(function):
"""Set the callback's result as self._callback_result."""
@wraps(function)
def wrapped(task):
task._callback_result = function(task)
return task._callback_result
return wrapped | python | def wrap_callback(function):
"""Set the callback's result as self._callback_result."""
@wraps(function)
def wrapped(task):
task._callback_result = function(task)
return task._callback_result
return wrapped | [
"def",
"wrap_callback",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapped",
"(",
"task",
")",
":",
"task",
".",
"_callback_result",
"=",
"function",
"(",
"task",
")",
"return",
"task",
".",
"_callback_result",
"return",
"wrappe... | Set the callback's result as self._callback_result. | [
"Set",
"the",
"callback",
"s",
"result",
"as",
"self",
".",
"_callback_result",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L65-L73 | train | 51,251 |
ClericPy/torequests | torequests/dummy.py | NewTask.callback_result | def callback_result(self):
"""Blocking until the task finish and return the callback_result.until"""
if self._state == self._PENDING:
self._loop.run_until_complete(self)
if self._callbacks:
result = self._callback_result
else:
result = self.result()
return result | python | def callback_result(self):
"""Blocking until the task finish and return the callback_result.until"""
if self._state == self._PENDING:
self._loop.run_until_complete(self)
if self._callbacks:
result = self._callback_result
else:
result = self.result()
return result | [
"def",
"callback_result",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"self",
".",
"_PENDING",
":",
"self",
".",
"_loop",
".",
"run_until_complete",
"(",
"self",
")",
"if",
"self",
".",
"_callbacks",
":",
"result",
"=",
"self",
".",
"_cal... | Blocking until the task finish and return the callback_result.until | [
"Blocking",
"until",
"the",
"task",
"finish",
"and",
"return",
"the",
"callback_result",
".",
"until"
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L99-L107 | train | 51,252 |
ClericPy/torequests | torequests/dummy.py | Loop.run_coroutine_threadsafe | def run_coroutine_threadsafe(self, coro, loop=None, callback=None):
"""Be used when loop running in a single non-main thread."""
if not asyncio.iscoroutine(coro):
raise TypeError("A await in coroutines. object is required")
loop = loop or self.loop
future = NewFuture(callback=callback)
def callback_func():
try:
asyncio.futures._chain_future(NewTask(coro, loop=loop), future)
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
raise
loop.call_soon_threadsafe(callback_func)
return future | python | def run_coroutine_threadsafe(self, coro, loop=None, callback=None):
"""Be used when loop running in a single non-main thread."""
if not asyncio.iscoroutine(coro):
raise TypeError("A await in coroutines. object is required")
loop = loop or self.loop
future = NewFuture(callback=callback)
def callback_func():
try:
asyncio.futures._chain_future(NewTask(coro, loop=loop), future)
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
raise
loop.call_soon_threadsafe(callback_func)
return future | [
"def",
"run_coroutine_threadsafe",
"(",
"self",
",",
"coro",
",",
"loop",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutine",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"\"A await in coroutines. object is req... | Be used when loop running in a single non-main thread. | [
"Be",
"used",
"when",
"loop",
"running",
"in",
"a",
"single",
"non",
"-",
"main",
"thread",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L190-L206 | train | 51,253 |
ClericPy/torequests | torequests/dummy.py | Loop.submit | def submit(self, coro, callback=None):
"""Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
return (loop.frequency, i)
coro = test(0)
task = loop.submit(coro)
print(task)
# loop.x can be ignore
loop.x
print(task.x)
# <NewTask pending coro=<test() running at torequests/temp_code.py:58>>
# (Frequency(sem=<0/0>, interval=0, name=loop_sem), 0)
"""
callback = callback or self.default_callback
if self.async_running:
return self.run_coroutine_threadsafe(coro, callback=callback)
else:
return NewTask(coro, loop=self.loop, callback=callback) | python | def submit(self, coro, callback=None):
"""Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
return (loop.frequency, i)
coro = test(0)
task = loop.submit(coro)
print(task)
# loop.x can be ignore
loop.x
print(task.x)
# <NewTask pending coro=<test() running at torequests/temp_code.py:58>>
# (Frequency(sem=<0/0>, interval=0, name=loop_sem), 0)
"""
callback = callback or self.default_callback
if self.async_running:
return self.run_coroutine_threadsafe(coro, callback=callback)
else:
return NewTask(coro, loop=self.loop, callback=callback) | [
"def",
"submit",
"(",
"self",
",",
"coro",
",",
"callback",
"=",
"None",
")",
":",
"callback",
"=",
"callback",
"or",
"self",
".",
"default_callback",
"if",
"self",
".",
"async_running",
":",
"return",
"self",
".",
"run_coroutine_threadsafe",
"(",
"coro",
... | Submit a coro as NewTask to self.loop without loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
result = await asyncio.sleep(1)
return (loop.frequency, i)
coro = test(0)
task = loop.submit(coro)
print(task)
# loop.x can be ignore
loop.x
print(task.x)
# <NewTask pending coro=<test() running at torequests/temp_code.py:58>>
# (Frequency(sem=<0/0>, interval=0, name=loop_sem), 0) | [
"Submit",
"a",
"coro",
"as",
"NewTask",
"to",
"self",
".",
"loop",
"without",
"loop",
".",
"frequncy",
"control",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L235-L262 | train | 51,254 |
ClericPy/torequests | torequests/dummy.py | Loop.submitter | def submitter(self, f):
"""Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop."""
f = self._wrap_coro_function_with_sem(f)
@wraps(f)
def wrapped(*args, **kwargs):
return self.submit(f(*args, **kwargs))
return wrapped | python | def submitter(self, f):
"""Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop."""
f = self._wrap_coro_function_with_sem(f)
@wraps(f)
def wrapped(*args, **kwargs):
return self.submit(f(*args, **kwargs))
return wrapped | [
"def",
"submitter",
"(",
"self",
",",
"f",
")",
":",
"f",
"=",
"self",
".",
"_wrap_coro_function_with_sem",
"(",
"f",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
... | Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop. | [
"Decorator",
"to",
"submit",
"a",
"coro",
"-",
"function",
"as",
"NewTask",
"to",
"self",
".",
"loop",
"with",
"sem",
"control",
".",
"Use",
"default_callback",
"frequency",
"of",
"loop",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L264-L273 | train | 51,255 |
ClericPy/torequests | torequests/dummy.py | Loop.todo_tasks | def todo_tasks(self):
"""Return tasks in loop which its state is pending."""
tasks = [task for task in self.all_tasks if task._state == NewTask._PENDING]
return tasks | python | def todo_tasks(self):
"""Return tasks in loop which its state is pending."""
tasks = [task for task in self.all_tasks if task._state == NewTask._PENDING]
return tasks | [
"def",
"todo_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"[",
"task",
"for",
"task",
"in",
"self",
".",
"all_tasks",
"if",
"task",
".",
"_state",
"==",
"NewTask",
".",
"_PENDING",
"]",
"return",
"tasks"
] | Return tasks in loop which its state is pending. | [
"Return",
"tasks",
"in",
"loop",
"which",
"its",
"state",
"is",
"pending",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L281-L284 | train | 51,256 |
ClericPy/torequests | torequests/dummy.py | Loop.done_tasks | def done_tasks(self):
"""Return tasks in loop which its state is not pending."""
tasks = [task for task in self.all_tasks if task._state != NewTask._PENDING]
return tasks | python | def done_tasks(self):
"""Return tasks in loop which its state is not pending."""
tasks = [task for task in self.all_tasks if task._state != NewTask._PENDING]
return tasks | [
"def",
"done_tasks",
"(",
"self",
")",
":",
"tasks",
"=",
"[",
"task",
"for",
"task",
"in",
"self",
".",
"all_tasks",
"if",
"task",
".",
"_state",
"!=",
"NewTask",
".",
"_PENDING",
"]",
"return",
"tasks"
] | Return tasks in loop which its state is not pending. | [
"Return",
"tasks",
"in",
"loop",
"which",
"its",
"state",
"is",
"not",
"pending",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L287-L290 | train | 51,257 |
ClericPy/torequests | torequests/dummy.py | Loop.run | def run(self, tasks=None, timeout=None):
"""Block, run loop until all tasks completed."""
timeout = self._timeout if timeout is None else timeout
if self.async_running or self.loop.is_running():
return self.wait_all_tasks_done(timeout)
else:
tasks = tasks or self.todo_tasks
return self.loop.run_until_complete(asyncio.gather(*tasks, loop=self.loop)) | python | def run(self, tasks=None, timeout=None):
"""Block, run loop until all tasks completed."""
timeout = self._timeout if timeout is None else timeout
if self.async_running or self.loop.is_running():
return self.wait_all_tasks_done(timeout)
else:
tasks = tasks or self.todo_tasks
return self.loop.run_until_complete(asyncio.gather(*tasks, loop=self.loop)) | [
"def",
"run",
"(",
"self",
",",
"tasks",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"if",
"timeout",
"is",
"None",
"else",
"timeout",
"if",
"self",
".",
"async_running",
"or",
"self",
".",
"loop",
"."... | Block, run loop until all tasks completed. | [
"Block",
"run",
"loop",
"until",
"all",
"tasks",
"completed",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L292-L299 | train | 51,258 |
ClericPy/torequests | torequests/dummy.py | Loop.wait_all_tasks_done | def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1):
"""Block, only be used while loop running in a single non-main thread."""
timeout = self._timeout if timeout is None else timeout
timeout = timeout or float("inf")
start_time = time.time()
time.sleep(delay)
while 1:
if not self.todo_tasks:
return self.all_tasks
if time.time() - start_time > timeout:
return self.done_tasks
time.sleep(interval) | python | def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1):
"""Block, only be used while loop running in a single non-main thread."""
timeout = self._timeout if timeout is None else timeout
timeout = timeout or float("inf")
start_time = time.time()
time.sleep(delay)
while 1:
if not self.todo_tasks:
return self.all_tasks
if time.time() - start_time > timeout:
return self.done_tasks
time.sleep(interval) | [
"def",
"wait_all_tasks_done",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"delay",
"=",
"0.5",
",",
"interval",
"=",
"0.1",
")",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"if",
"timeout",
"is",
"None",
"else",
"timeout",
"timeout",
"=",
"timeout",... | Block, only be used while loop running in a single non-main thread. | [
"Block",
"only",
"be",
"used",
"while",
"loop",
"running",
"in",
"a",
"single",
"non",
"-",
"main",
"thread",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L301-L312 | train | 51,259 |
ClericPy/torequests | torequests/dummy.py | Requests.ensure_frequencies | def ensure_frequencies(self, frequencies):
"""Ensure frequencies is dict of host-frequencies."""
if not frequencies:
return {}
if not isinstance(frequencies, dict):
raise ValueError("frequencies should be dict")
frequencies = {
host: Frequency.ensure_frequency(frequencies[host]) for host in frequencies
}
return frequencies | python | def ensure_frequencies(self, frequencies):
"""Ensure frequencies is dict of host-frequencies."""
if not frequencies:
return {}
if not isinstance(frequencies, dict):
raise ValueError("frequencies should be dict")
frequencies = {
host: Frequency.ensure_frequency(frequencies[host]) for host in frequencies
}
return frequencies | [
"def",
"ensure_frequencies",
"(",
"self",
",",
"frequencies",
")",
":",
"if",
"not",
"frequencies",
":",
"return",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"frequencies",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"frequencies should be dict\"",
")"... | Ensure frequencies is dict of host-frequencies. | [
"Ensure",
"frequencies",
"is",
"dict",
"of",
"host",
"-",
"frequencies",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L493-L502 | train | 51,260 |
ClericPy/torequests | torequests/dummy.py | Requests.set_frequency | def set_frequency(self, host, sem=None, interval=None):
"""Set frequency for host with sem and interval."""
# single sem or global sem
sem = sem or self.sem
interval = self.interval if interval is None else interval
frequency = Frequency(sem, interval, host)
frequencies = {host: frequency}
self.update_frequency(frequencies)
return frequency | python | def set_frequency(self, host, sem=None, interval=None):
"""Set frequency for host with sem and interval."""
# single sem or global sem
sem = sem or self.sem
interval = self.interval if interval is None else interval
frequency = Frequency(sem, interval, host)
frequencies = {host: frequency}
self.update_frequency(frequencies)
return frequency | [
"def",
"set_frequency",
"(",
"self",
",",
"host",
",",
"sem",
"=",
"None",
",",
"interval",
"=",
"None",
")",
":",
"# single sem or global sem",
"sem",
"=",
"sem",
"or",
"self",
".",
"sem",
"interval",
"=",
"self",
".",
"interval",
"if",
"interval",
"is"... | Set frequency for host with sem and interval. | [
"Set",
"frequency",
"for",
"host",
"with",
"sem",
"and",
"interval",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L504-L512 | train | 51,261 |
DreamLab/VmShepherd | src/vmshepherd/iaas/openstack_driver.py | OpenStackDriver.openstack_exception | def openstack_exception(func):
'''
Openstack exceptions decorator
'''
async def wrap(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
logging.error(e)
raise IaasException
return wrap | python | def openstack_exception(func):
'''
Openstack exceptions decorator
'''
async def wrap(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
logging.error(e)
raise IaasException
return wrap | [
"def",
"openstack_exception",
"(",
"func",
")",
":",
"async",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"await",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e... | Openstack exceptions decorator | [
"Openstack",
"exceptions",
"decorator"
] | 709a412c372b897d53808039c5c64a8b69c12c8d | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/openstack_driver.py#L18-L28 | train | 51,262 |
DreamLab/VmShepherd | src/vmshepherd/iaas/openstack_driver.py | OpenStackDriver.initialize_openstack | def initialize_openstack(func):
'''
Initialize and refresh openstack connection
'''
async def wrap(self, *args, **kwargs):
if not hasattr(self, 'auth') or not self.auth.is_token_valid():
self.auth = AuthPassword(auth_url=self.config['auth_url'],
username=self.config['username'],
password=self.config['password'],
project_name=self.config['project_name'],
user_domain_name=self.config['user_domain_name'],
project_domain_name=self.config['project_domain_name'])
self.nova = NovaClient(session=self.auth)
self.glance = GlanceClient(session=self.auth)
await self.nova.init_api(timeout=self.config.get('http_timeout', 10))
await self.glance.init_api(timeout=self.config.get('http_timeout', 10))
if not hasattr(self, 'last_init') or self.last_init < (time.time() - 60):
await self.initialize()
self.last_init = time.time()
return await func(self, *args, **kwargs)
return wrap | python | def initialize_openstack(func):
'''
Initialize and refresh openstack connection
'''
async def wrap(self, *args, **kwargs):
if not hasattr(self, 'auth') or not self.auth.is_token_valid():
self.auth = AuthPassword(auth_url=self.config['auth_url'],
username=self.config['username'],
password=self.config['password'],
project_name=self.config['project_name'],
user_domain_name=self.config['user_domain_name'],
project_domain_name=self.config['project_domain_name'])
self.nova = NovaClient(session=self.auth)
self.glance = GlanceClient(session=self.auth)
await self.nova.init_api(timeout=self.config.get('http_timeout', 10))
await self.glance.init_api(timeout=self.config.get('http_timeout', 10))
if not hasattr(self, 'last_init') or self.last_init < (time.time() - 60):
await self.initialize()
self.last_init = time.time()
return await func(self, *args, **kwargs)
return wrap | [
"def",
"initialize_openstack",
"(",
"func",
")",
":",
"async",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'auth'",
")",
"or",
"not",
"self",
".",
"auth",
".",
"is_toke... | Initialize and refresh openstack connection | [
"Initialize",
"and",
"refresh",
"openstack",
"connection"
] | 709a412c372b897d53808039c5c64a8b69c12c8d | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/openstack_driver.py#L30-L52 | train | 51,263 |
DreamLab/VmShepherd | src/vmshepherd/iaas/openstack_driver.py | OpenStackDriver.initialize | async def initialize(self):
'''
Initialize static data like images and flavores and set it as object property
'''
flavors = await self._list_flavors()
images = await self._list_images()
self.flavors_map = bidict()
self.images_map = bidict()
self.images_details = {}
for flavor in flavors:
self.flavors_map.put(flavor['id'], flavor['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE')
for image in images:
# @TODO filetes :
# @TODO filtering by owner
# if hasattr(image, 'owner_id') and image.owner_id in self.config['image_owner_ids']:
# @TODO enable filtering by tag
# if 'lastest' in image.tags:
self.images_details[image['id']] = {
'name': image['name'],
'created_at': image['created_at'],
'latest': 'latest' in image['tags']
}
self.images_map.put(image['id'], image['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE') | python | async def initialize(self):
'''
Initialize static data like images and flavores and set it as object property
'''
flavors = await self._list_flavors()
images = await self._list_images()
self.flavors_map = bidict()
self.images_map = bidict()
self.images_details = {}
for flavor in flavors:
self.flavors_map.put(flavor['id'], flavor['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE')
for image in images:
# @TODO filetes :
# @TODO filtering by owner
# if hasattr(image, 'owner_id') and image.owner_id in self.config['image_owner_ids']:
# @TODO enable filtering by tag
# if 'lastest' in image.tags:
self.images_details[image['id']] = {
'name': image['name'],
'created_at': image['created_at'],
'latest': 'latest' in image['tags']
}
self.images_map.put(image['id'], image['name'], on_dup_key='OVERWRITE', on_dup_val='OVERWRITE') | [
"async",
"def",
"initialize",
"(",
"self",
")",
":",
"flavors",
"=",
"await",
"self",
".",
"_list_flavors",
"(",
")",
"images",
"=",
"await",
"self",
".",
"_list_images",
"(",
")",
"self",
".",
"flavors_map",
"=",
"bidict",
"(",
")",
"self",
".",
"imag... | Initialize static data like images and flavores and set it as object property | [
"Initialize",
"static",
"data",
"like",
"images",
"and",
"flavores",
"and",
"set",
"it",
"as",
"object",
"property"
] | 709a412c372b897d53808039c5c64a8b69c12c8d | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/openstack_driver.py#L54-L79 | train | 51,264 |
mjirik/io3d | io3d/datareaderqt.py | _set_label_text | def _set_label_text(obj, text, tooltip=None, replace_all=False):
"""
Keep text before first colon and replace the rest with new text.
If there is no colon in the
:param obj:
:param text:
:param tooltip:
:param replace_all: No colon is searched and whole text is replaced
:return:
"""
dlab = str(obj.text())
index_of_colon = dlab.find(': ')
if index_of_colon == -1:
index_of_colon = 0
else:
index_of_colon += 2
if replace_all:
index_of_colon = 0
obj.setText(dlab[:index_of_colon] + '%s' % text)
if tooltip is not None:
obj.setToolTip(tooltip) | python | def _set_label_text(obj, text, tooltip=None, replace_all=False):
"""
Keep text before first colon and replace the rest with new text.
If there is no colon in the
:param obj:
:param text:
:param tooltip:
:param replace_all: No colon is searched and whole text is replaced
:return:
"""
dlab = str(obj.text())
index_of_colon = dlab.find(': ')
if index_of_colon == -1:
index_of_colon = 0
else:
index_of_colon += 2
if replace_all:
index_of_colon = 0
obj.setText(dlab[:index_of_colon] + '%s' % text)
if tooltip is not None:
obj.setToolTip(tooltip) | [
"def",
"_set_label_text",
"(",
"obj",
",",
"text",
",",
"tooltip",
"=",
"None",
",",
"replace_all",
"=",
"False",
")",
":",
"dlab",
"=",
"str",
"(",
"obj",
".",
"text",
"(",
")",
")",
"index_of_colon",
"=",
"dlab",
".",
"find",
"(",
"': '",
")",
"i... | Keep text before first colon and replace the rest with new text.
If there is no colon in the
:param obj:
:param text:
:param tooltip:
:param replace_all: No colon is searched and whole text is replaced
:return: | [
"Keep",
"text",
"before",
"first",
"colon",
"and",
"replace",
"the",
"rest",
"with",
"new",
"text",
"."
] | ccaf3e378dcc967f2565d477fc27583fd0f61fcc | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datareaderqt.py#L271-L292 | train | 51,265 |
SetBased/py-stratum | pystratum/RoutineWrapperGenerator.py | RoutineWrapperGenerator.main | def main(self, config_filename):
"""
The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred.
:param str config_filename: The name of the configuration file.
:rtype: int
"""
self._read_configuration_file(config_filename)
if self._wrapper_class_name:
self._io.title('Wrapper')
self.__generate_wrapper_class()
else:
self._io.log_verbose('Wrapper not enabled')
return 0 | python | def main(self, config_filename):
"""
The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred.
:param str config_filename: The name of the configuration file.
:rtype: int
"""
self._read_configuration_file(config_filename)
if self._wrapper_class_name:
self._io.title('Wrapper')
self.__generate_wrapper_class()
else:
self._io.log_verbose('Wrapper not enabled')
return 0 | [
"def",
"main",
"(",
"self",
",",
"config_filename",
")",
":",
"self",
".",
"_read_configuration_file",
"(",
"config_filename",
")",
"if",
"self",
".",
"_wrapper_class_name",
":",
"self",
".",
"_io",
".",
"title",
"(",
"'Wrapper'",
")",
"self",
".",
"__genera... | The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred.
:param str config_filename: The name of the configuration file.
:rtype: int | [
"The",
"main",
"of",
"the",
"wrapper",
"generator",
".",
"Returns",
"0",
"on",
"success",
"1",
"if",
"one",
"or",
"more",
"errors",
"occurred",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineWrapperGenerator.py#L81-L98 | train | 51,266 |
SetBased/py-stratum | pystratum/RoutineWrapperGenerator.py | RoutineWrapperGenerator.__generate_wrapper_class | def __generate_wrapper_class(self):
"""
Generates the wrapper class.
"""
routines = self._read_routine_metadata()
self._write_class_header()
if routines:
for routine_name in sorted(routines):
if routines[routine_name]['designation'] != 'hidden':
self._write_routine_function(routines[routine_name])
else:
self._io.error('No files with stored routines found')
self._write_class_trailer()
Util.write_two_phases(self._wrapper_filename, self._code, self._io) | python | def __generate_wrapper_class(self):
"""
Generates the wrapper class.
"""
routines = self._read_routine_metadata()
self._write_class_header()
if routines:
for routine_name in sorted(routines):
if routines[routine_name]['designation'] != 'hidden':
self._write_routine_function(routines[routine_name])
else:
self._io.error('No files with stored routines found')
self._write_class_trailer()
Util.write_two_phases(self._wrapper_filename, self._code, self._io) | [
"def",
"__generate_wrapper_class",
"(",
"self",
")",
":",
"routines",
"=",
"self",
".",
"_read_routine_metadata",
"(",
")",
"self",
".",
"_write_class_header",
"(",
")",
"if",
"routines",
":",
"for",
"routine_name",
"in",
"sorted",
"(",
"routines",
")",
":",
... | Generates the wrapper class. | [
"Generates",
"the",
"wrapper",
"class",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineWrapperGenerator.py#L101-L118 | train | 51,267 |
SetBased/py-stratum | pystratum/RoutineWrapperGenerator.py | RoutineWrapperGenerator._read_routine_metadata | def _read_routine_metadata(self):
"""
Returns the metadata of stored routines.
:rtype: dict
"""
metadata = {}
if os.path.isfile(self._metadata_filename):
with open(self._metadata_filename, 'r') as file:
metadata = json.load(file)
return metadata | python | def _read_routine_metadata(self):
"""
Returns the metadata of stored routines.
:rtype: dict
"""
metadata = {}
if os.path.isfile(self._metadata_filename):
with open(self._metadata_filename, 'r') as file:
metadata = json.load(file)
return metadata | [
"def",
"_read_routine_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_metadata_filename",
")",
":",
"with",
"open",
"(",
"self",
".",
"_metadata_filename",
",",
"'r'",
")",
"as",
... | Returns the metadata of stored routines.
:rtype: dict | [
"Returns",
"the",
"metadata",
"of",
"stored",
"routines",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineWrapperGenerator.py#L138-L149 | train | 51,268 |
SetBased/py-stratum | pystratum/RoutineWrapperGenerator.py | RoutineWrapperGenerator._write_class_header | def _write_class_header(self):
"""
Generate a class header for stored routine wrapper.
"""
self._write_line('from {0!s} import {1!s}'.format(self._parent_class_namespace, self._parent_class_name))
self._write_line()
self._write_line()
self._write_line('# ' + ('-' * 118))
self._write_line('class {0!s}({1!s}):'.format(self._wrapper_class_name, self._parent_class_name))
self._write_line(' """')
self._write_line(' The stored routines wrappers.')
self._write_line(' """') | python | def _write_class_header(self):
"""
Generate a class header for stored routine wrapper.
"""
self._write_line('from {0!s} import {1!s}'.format(self._parent_class_namespace, self._parent_class_name))
self._write_line()
self._write_line()
self._write_line('# ' + ('-' * 118))
self._write_line('class {0!s}({1!s}):'.format(self._wrapper_class_name, self._parent_class_name))
self._write_line(' """')
self._write_line(' The stored routines wrappers.')
self._write_line(' """') | [
"def",
"_write_class_header",
"(",
"self",
")",
":",
"self",
".",
"_write_line",
"(",
"'from {0!s} import {1!s}'",
".",
"format",
"(",
"self",
".",
"_parent_class_namespace",
",",
"self",
".",
"_parent_class_name",
")",
")",
"self",
".",
"_write_line",
"(",
")",... | Generate a class header for stored routine wrapper. | [
"Generate",
"a",
"class",
"header",
"for",
"stored",
"routine",
"wrapper",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineWrapperGenerator.py#L152-L163 | train | 51,269 |
SetBased/py-stratum | pystratum/RoutineWrapperGenerator.py | RoutineWrapperGenerator._write_line | def _write_line(self, text=''):
"""
Writes a line with Python code to the generate code buffer.
:param str text: The line with Python code.
"""
if text:
self._code += str(text) + "\n"
else:
self._code += "\n" | python | def _write_line(self, text=''):
"""
Writes a line with Python code to the generate code buffer.
:param str text: The line with Python code.
"""
if text:
self._code += str(text) + "\n"
else:
self._code += "\n" | [
"def",
"_write_line",
"(",
"self",
",",
"text",
"=",
"''",
")",
":",
"if",
"text",
":",
"self",
".",
"_code",
"+=",
"str",
"(",
"text",
")",
"+",
"\"\\n\"",
"else",
":",
"self",
".",
"_code",
"+=",
"\"\\n\""
] | Writes a line with Python code to the generate code buffer.
:param str text: The line with Python code. | [
"Writes",
"a",
"line",
"with",
"Python",
"code",
"to",
"the",
"generate",
"code",
"buffer",
"."
] | 7c5ffaa2fdd03f865832a5190b5897ff2c0e3155 | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineWrapperGenerator.py#L166-L175 | train | 51,270 |
ClericPy/torequests | torequests/main.py | Async | def Async(f, n=None, timeout=None):
"""Concise usage for pool.submit.
Basic Usage Asnyc & threads ::
from torequests.main import Async, threads
import time
def use_submit(i):
time.sleep(i)
result = 'use_submit: %s' % i
print(result)
return result
@threads()
def use_decorator(i):
time.sleep(i)
result = 'use_decorator: %s' % i
print(result)
return result
new_use_submit = Async(use_submit)
tasks = [new_use_submit(i) for i in (2, 1, 0)
] + [use_decorator(i) for i in (2, 1, 0)]
print([type(i) for i in tasks])
results = [i.x for i in tasks]
print(results)
# use_submit: 0
# use_decorator: 0
# [<class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>]
# use_submit: 1
# use_decorator: 1
# use_submit: 2
# use_decorator: 2
# ['use_submit: 2', 'use_submit: 1', 'use_submit: 0', 'use_decorator: 2', 'use_decorator: 1', 'use_decorator: 0']
"""
return threads(n=n, timeout=timeout)(f) | python | def Async(f, n=None, timeout=None):
"""Concise usage for pool.submit.
Basic Usage Asnyc & threads ::
from torequests.main import Async, threads
import time
def use_submit(i):
time.sleep(i)
result = 'use_submit: %s' % i
print(result)
return result
@threads()
def use_decorator(i):
time.sleep(i)
result = 'use_decorator: %s' % i
print(result)
return result
new_use_submit = Async(use_submit)
tasks = [new_use_submit(i) for i in (2, 1, 0)
] + [use_decorator(i) for i in (2, 1, 0)]
print([type(i) for i in tasks])
results = [i.x for i in tasks]
print(results)
# use_submit: 0
# use_decorator: 0
# [<class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>]
# use_submit: 1
# use_decorator: 1
# use_submit: 2
# use_decorator: 2
# ['use_submit: 2', 'use_submit: 1', 'use_submit: 0', 'use_decorator: 2', 'use_decorator: 1', 'use_decorator: 0']
"""
return threads(n=n, timeout=timeout)(f) | [
"def",
"Async",
"(",
"f",
",",
"n",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"threads",
"(",
"n",
"=",
"n",
",",
"timeout",
"=",
"timeout",
")",
"(",
"f",
")"
] | Concise usage for pool.submit.
Basic Usage Asnyc & threads ::
from torequests.main import Async, threads
import time
def use_submit(i):
time.sleep(i)
result = 'use_submit: %s' % i
print(result)
return result
@threads()
def use_decorator(i):
time.sleep(i)
result = 'use_decorator: %s' % i
print(result)
return result
new_use_submit = Async(use_submit)
tasks = [new_use_submit(i) for i in (2, 1, 0)
] + [use_decorator(i) for i in (2, 1, 0)]
print([type(i) for i in tasks])
results = [i.x for i in tasks]
print(results)
# use_submit: 0
# use_decorator: 0
# [<class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>, <class 'torequests.main.NewFuture'>]
# use_submit: 1
# use_decorator: 1
# use_submit: 2
# use_decorator: 2
# ['use_submit: 2', 'use_submit: 1', 'use_submit: 0', 'use_decorator: 2', 'use_decorator: 1', 'use_decorator: 0'] | [
"Concise",
"usage",
"for",
"pool",
".",
"submit",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L394-L434 | train | 51,271 |
ClericPy/torequests | torequests/main.py | get_results_generator | def get_results_generator(future_list, timeout=None, sort_by_completed=False):
"""Return as a generator of tasks order by completed sequence."""
try:
# python2 not support yield from
if sort_by_completed:
for future in as_completed(future_list, timeout=timeout):
yield future.x
else:
for future in future_list:
yield future.x
except TimeoutError:
return | python | def get_results_generator(future_list, timeout=None, sort_by_completed=False):
"""Return as a generator of tasks order by completed sequence."""
try:
# python2 not support yield from
if sort_by_completed:
for future in as_completed(future_list, timeout=timeout):
yield future.x
else:
for future in future_list:
yield future.x
except TimeoutError:
return | [
"def",
"get_results_generator",
"(",
"future_list",
",",
"timeout",
"=",
"None",
",",
"sort_by_completed",
"=",
"False",
")",
":",
"try",
":",
"# python2 not support yield from",
"if",
"sort_by_completed",
":",
"for",
"future",
"in",
"as_completed",
"(",
"future_lis... | Return as a generator of tasks order by completed sequence. | [
"Return",
"as",
"a",
"generator",
"of",
"tasks",
"order",
"by",
"completed",
"sequence",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L442-L453 | train | 51,272 |
ClericPy/torequests | torequests/main.py | run_after_async | def run_after_async(seconds, func, *args, **kwargs):
"""Run the function after seconds asynchronously."""
t = Timer(seconds, func, args, kwargs)
t.daemon = True
t.start()
return t | python | def run_after_async(seconds, func, *args, **kwargs):
"""Run the function after seconds asynchronously."""
t = Timer(seconds, func, args, kwargs)
t.daemon = True
t.start()
return t | [
"def",
"run_after_async",
"(",
"seconds",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Timer",
"(",
"seconds",
",",
"func",
",",
"args",
",",
"kwargs",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
... | Run the function after seconds asynchronously. | [
"Run",
"the",
"function",
"after",
"seconds",
"asynchronously",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L456-L461 | train | 51,273 |
ClericPy/torequests | torequests/main.py | NewExecutorPoolMixin.async_func | def async_func(self, function):
"""Decorator for let a normal function return the NewFuture"""
@wraps(function)
def wrapped(*args, **kwargs):
return self.submit(function, *args, **kwargs)
return wrapped | python | def async_func(self, function):
"""Decorator for let a normal function return the NewFuture"""
@wraps(function)
def wrapped(*args, **kwargs):
return self.submit(function, *args, **kwargs)
return wrapped | [
"def",
"async_func",
"(",
"self",
",",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"submit",
"(",
"function",
",",
"*",
"args",
",",
"*",
... | Decorator for let a normal function return the NewFuture | [
"Decorator",
"for",
"let",
"a",
"normal",
"function",
"return",
"the",
"NewFuture"
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L73-L80 | train | 51,274 |
ClericPy/torequests | torequests/main.py | NewExecutorPoolMixin._get_cpu_count | def _get_cpu_count(self):
"""Get the cpu count."""
try:
from multiprocessing import cpu_count
return cpu_count()
except Exception as e:
Config.main_logger.error("_get_cpu_count failed for %s" % e) | python | def _get_cpu_count(self):
"""Get the cpu count."""
try:
from multiprocessing import cpu_count
return cpu_count()
except Exception as e:
Config.main_logger.error("_get_cpu_count failed for %s" % e) | [
"def",
"_get_cpu_count",
"(",
"self",
")",
":",
"try",
":",
"from",
"multiprocessing",
"import",
"cpu_count",
"return",
"cpu_count",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"Config",
".",
"main_logger",
".",
"error",
"(",
"\"_get_cpu_count failed for %s... | Get the cpu count. | [
"Get",
"the",
"cpu",
"count",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L86-L93 | train | 51,275 |
ClericPy/torequests | torequests/main.py | NewFuture._invoke_callbacks | def _invoke_callbacks(self):
"""Record the task_end_time & task_cost_time, set result for self._callback_result."""
self.task_end_time = time.time()
self.task_cost_time = self.task_end_time - self.task_start_time
with self._condition:
for callback in self._done_callbacks:
try:
result = callback(self)
if callback in self._user_callbacks:
self._callback_result = result
except Exception as e:
Config.main_logger.error("exception calling callback for %s" % e)
self._condition.notify_all() | python | def _invoke_callbacks(self):
"""Record the task_end_time & task_cost_time, set result for self._callback_result."""
self.task_end_time = time.time()
self.task_cost_time = self.task_end_time - self.task_start_time
with self._condition:
for callback in self._done_callbacks:
try:
result = callback(self)
if callback in self._user_callbacks:
self._callback_result = result
except Exception as e:
Config.main_logger.error("exception calling callback for %s" % e)
self._condition.notify_all() | [
"def",
"_invoke_callbacks",
"(",
"self",
")",
":",
"self",
".",
"task_end_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"task_cost_time",
"=",
"self",
".",
"task_end_time",
"-",
"self",
".",
"task_start_time",
"with",
"self",
".",
"_condition",
"... | Record the task_end_time & task_cost_time, set result for self._callback_result. | [
"Record",
"the",
"task_end_time",
"&",
"task_cost_time",
"set",
"result",
"for",
"self",
".",
"_callback_result",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L332-L344 | train | 51,276 |
ClericPy/torequests | torequests/main.py | NewFuture.callback_result | def callback_result(self):
"""Block the main thead until future finish, return the future.callback_result."""
if self._state in [PENDING, RUNNING]:
self.x
if self._user_callbacks:
return self._callback_result
else:
return self.x | python | def callback_result(self):
"""Block the main thead until future finish, return the future.callback_result."""
if self._state in [PENDING, RUNNING]:
self.x
if self._user_callbacks:
return self._callback_result
else:
return self.x | [
"def",
"callback_result",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"in",
"[",
"PENDING",
",",
"RUNNING",
"]",
":",
"self",
".",
"x",
"if",
"self",
".",
"_user_callbacks",
":",
"return",
"self",
".",
"_callback_result",
"else",
":",
"return",
... | Block the main thead until future finish, return the future.callback_result. | [
"Block",
"the",
"main",
"thead",
"until",
"future",
"finish",
"return",
"the",
"future",
".",
"callback_result",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L357-L364 | train | 51,277 |
ClericPy/torequests | torequests/main.py | tPool.close | def close(self, wait=False):
"""Close session, shutdown pool."""
self.session.close()
self.pool.shutdown(wait=wait) | python | def close(self, wait=False):
"""Close session, shutdown pool."""
self.session.close()
self.pool.shutdown(wait=wait) | [
"def",
"close",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"self",
".",
"session",
".",
"close",
"(",
")",
"self",
".",
"pool",
".",
"shutdown",
"(",
"wait",
"=",
"wait",
")"
] | Close session, shutdown pool. | [
"Close",
"session",
"shutdown",
"pool",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L553-L556 | train | 51,278 |
ClericPy/torequests | torequests/main.py | tPool.request | def request(self, method, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.request`, but return as NewFuture."""
return self.pool.submit(
self._request,
method=method,
url=url,
retry=retry,
callback=callback or self.default_callback,
**kwargs
) | python | def request(self, method, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.request`, but return as NewFuture."""
return self.pool.submit(
self._request,
method=method,
url=url,
retry=retry,
callback=callback or self.default_callback,
**kwargs
) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"pool",
".",
"submit",
"(",
"self",
".",
"_request",
",",
"method",
"=",
"me... | Similar to `requests.request`, but return as NewFuture. | [
"Similar",
"to",
"requests",
".",
"request",
"but",
"return",
"as",
"NewFuture",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L604-L613 | train | 51,279 |
ClericPy/torequests | torequests/main.py | tPool.get | def get(self, url, params=None, callback=None, retry=0, **kwargs):
"""Similar to `requests.get`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", True)
return self.request(
"get", url=url, params=params, callback=callback, retry=retry, **kwargs
) | python | def get(self, url, params=None, callback=None, retry=0, **kwargs):
"""Similar to `requests.get`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", True)
return self.request(
"get", url=url, params=params, callback=callback, retry=retry, **kwargs
) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"allow_redirects\"",
",",
"True",
")",
"return",
"self",
... | Similar to `requests.get`, but return as NewFuture. | [
"Similar",
"to",
"requests",
".",
"get",
"but",
"return",
"as",
"NewFuture",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L615-L620 | train | 51,280 |
ClericPy/torequests | torequests/main.py | tPool.post | def post(self, url, data=None, json=None, callback=None, retry=0, **kwargs):
"""Similar to `requests.post`, but return as NewFuture."""
return self.request(
"post",
url=url,
data=data,
json=json,
callback=callback,
retry=retry,
**kwargs
) | python | def post(self, url, data=None, json=None, callback=None, retry=0, **kwargs):
"""Similar to `requests.post`, but return as NewFuture."""
return self.request(
"post",
url=url,
data=data,
json=json,
callback=callback,
retry=retry,
**kwargs
) | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"post\"",
",",
"url",
... | Similar to `requests.post`, but return as NewFuture. | [
"Similar",
"to",
"requests",
".",
"post",
"but",
"return",
"as",
"NewFuture",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L622-L632 | train | 51,281 |
ClericPy/torequests | torequests/main.py | tPool.head | def head(self, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.head`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", False)
return self.request("head", url=url, callback=callback, retry=retry, **kwargs) | python | def head(self, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.head`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", False)
return self.request("head", url=url, callback=callback, retry=retry, **kwargs) | [
"def",
"head",
"(",
"self",
",",
"url",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"allow_redirects\"",
",",
"False",
")",
"return",
"self",
".",
"request",
"(",
"\"hea... | Similar to `requests.head`, but return as NewFuture. | [
"Similar",
"to",
"requests",
".",
"head",
"but",
"return",
"as",
"NewFuture",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L644-L647 | train | 51,282 |
ClericPy/torequests | torequests/main.py | tPool.options | def options(self, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.options`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", True)
return self.request(
"options", url=url, callback=callback, retry=retry, **kwargs
) | python | def options(self, url, callback=None, retry=0, **kwargs):
"""Similar to `requests.options`, but return as NewFuture."""
kwargs.setdefault("allow_redirects", True)
return self.request(
"options", url=url, callback=callback, retry=retry, **kwargs
) | [
"def",
"options",
"(",
"self",
",",
"url",
",",
"callback",
"=",
"None",
",",
"retry",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"allow_redirects\"",
",",
"True",
")",
"return",
"self",
".",
"request",
"(",
"\"o... | Similar to `requests.options`, but return as NewFuture. | [
"Similar",
"to",
"requests",
".",
"options",
"but",
"return",
"as",
"NewFuture",
"."
] | 1793261688d7a47e1c3a0830d83f8552f5e3e5d9 | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/main.py#L649-L654 | train | 51,283 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getLinkInfo | def getLinkInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get basic WAN link information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: basic WAN link information's
:rtype: WanLinkInfo
"""
namespace = Wan.getServiceType("getLinkInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return WanLinkInfo(results) | python | def getLinkInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get basic WAN link information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: basic WAN link information's
:rtype: WanLinkInfo
"""
namespace = Wan.getServiceType("getLinkInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return WanLinkInfo(results) | [
"def",
"getLinkInfo",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getLinkInfo\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
"getCont... | Execute GetInfo action to get basic WAN link information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: basic WAN link information's
:rtype: WanLinkInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"basic",
"WAN",
"link",
"information",
"s",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L93-L106 | train | 51,284 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getLinkProperties | def getLinkProperties(self, wanInterfaceId=1, timeout=1):
"""Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:rtype: WanLinkProperties
"""
namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCommonLinkProperties", timeout=timeout)
return WanLinkProperties(results) | python | def getLinkProperties(self, wanInterfaceId=1, timeout=1):
"""Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:rtype: WanLinkProperties
"""
namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetCommonLinkProperties", timeout=timeout)
return WanLinkProperties(results) | [
"def",
"getLinkProperties",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getLinkProperties\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
"."... | Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:rtype: WanLinkProperties | [
"Execute",
"GetCommonLinkProperties",
"action",
"to",
"get",
"WAN",
"link",
"properties",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L108-L121 | train | 51,285 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getADSLInfo | def getADSLInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get basic ADSL information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: ADSL informations.
:rtype: ADSLInfo
"""
namespace = Wan.getServiceType("getADSLInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ADSLInfo(results) | python | def getADSLInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get basic ADSL information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: ADSL informations.
:rtype: ADSLInfo
"""
namespace = Wan.getServiceType("getADSLInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ADSLInfo(results) | [
"def",
"getADSLInfo",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getADSLInfo\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
"getCont... | Execute GetInfo action to get basic ADSL information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: ADSL informations.
:rtype: ADSLInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"basic",
"ADSL",
"information",
"s",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L123-L136 | train | 51,286 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getEthernetLinkStatus | def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1):
"""Execute GetEthernetLinkStatus action to get the status of the ethernet link.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: status of the ethernet link
:rtype: str
"""
namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetEthernetLinkStatus", timeout=timeout)
return results["NewEthernetLinkStatus"] | python | def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1):
"""Execute GetEthernetLinkStatus action to get the status of the ethernet link.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: status of the ethernet link
:rtype: str
"""
namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetEthernetLinkStatus", timeout=timeout)
return results["NewEthernetLinkStatus"] | [
"def",
"getEthernetLinkStatus",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getEthernetLinkStatus\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self... | Execute GetEthernetLinkStatus action to get the status of the ethernet link.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: status of the ethernet link
:rtype: str | [
"Execute",
"GetEthernetLinkStatus",
"action",
"to",
"get",
"the",
"status",
"of",
"the",
"ethernet",
"link",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L138-L151 | train | 51,287 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getByteStatistic | def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two values, total bytes sent and total bytes received
:rtype: list[int]
"""
namespace = Wan.getServiceType("getByteStatistic") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetTotalBytesSent", timeout=timeout)
results2 = self.execute(uri, namespace, "GetTotalBytesReceived", timeout=timeout)
return [int(results["NewTotalBytesSent"]),
int(results2["NewTotalBytesReceived"])] | python | def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two values, total bytes sent and total bytes received
:rtype: list[int]
"""
namespace = Wan.getServiceType("getByteStatistic") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetTotalBytesSent", timeout=timeout)
results2 = self.execute(uri, namespace, "GetTotalBytesReceived", timeout=timeout)
return [int(results["NewTotalBytesSent"]),
int(results2["NewTotalBytesReceived"])] | [
"def",
"getByteStatistic",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getByteStatistic\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
... | Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two values, total bytes sent and total bytes received
:rtype: list[int] | [
"Execute",
"GetTotalBytesSent&GetTotalBytesReceived",
"actions",
"to",
"get",
"WAN",
"statistics",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L153-L168 | train | 51,288 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.getConnectionInfo | def getConnectionInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
:rtype: ConnectionInfo
"""
namespace = Wan.getServiceType("getConnectionInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ConnectionInfo(results) | python | def getConnectionInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
:rtype: ConnectionInfo
"""
namespace = Wan.getServiceType("getConnectionInfo") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetInfo", timeout=timeout)
return ConnectionInfo(results) | [
"def",
"getConnectionInfo",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getConnectionInfo\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
"."... | Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
:rtype: ConnectionInfo | [
"Execute",
"GetInfo",
"action",
"to",
"get",
"WAN",
"connection",
"information",
"s",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L187-L200 | train | 51,289 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.setEnable | def setEnable(self, status, wanInterfaceId=1, timeout=1):
"""Set enable status for a WAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Wan.getServiceType("setEnable") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | python | def setEnable(self, status, wanInterfaceId=1, timeout=1):
"""Set enable status for a WAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Wan.getServiceType("setEnable") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
self.execute(uri, namespace, "SetEnable", timeout=timeout, NewEnable=setStatus) | [
"def",
"setEnable",
"(",
"self",
",",
"status",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"setEnable\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
... | Set enable status for a WAN interface, be careful you don't cut yourself off.
:param bool status: enable or disable the interface
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed | [
"Set",
"enable",
"status",
"for",
"a",
"WAN",
"interface",
"be",
"careful",
"you",
"don",
"t",
"cut",
"yourself",
"off",
"."
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L202-L217 | train | 51,290 |
bpannier/simpletr64 | simpletr64/actions/wan.py | Wan.requestConnection | def requestConnection(self, wanInterfaceId=1, timeout=1):
"""Request the connection to be established
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Wan.getServiceType("requestConnection") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "RequestConnection", timeout=timeout) | python | def requestConnection(self, wanInterfaceId=1, timeout=1):
"""Request the connection to be established
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed
"""
namespace = Wan.getServiceType("requestConnection") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
self.execute(uri, namespace, "RequestConnection", timeout=timeout) | [
"def",
"requestConnection",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"requestConnection\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
"."... | Request the connection to be established
:param int wanInterfaceId: the id of the WAN interface
:param float timeout: the timeout to wait for the action to be executed | [
"Request",
"the",
"connection",
"to",
"be",
"established"
] | 31081139f4e6c85084a56de1617df73927135466 | https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/wan.py#L219-L228 | train | 51,291 |
vsoch/helpme | helpme/utils/fileio.py | write_config | def write_config(filename, config, mode="w"):
'''use configparser to write a config object to filename
'''
with open(filename, mode) as filey:
config.write(filey)
return filename | python | def write_config(filename, config, mode="w"):
'''use configparser to write a config object to filename
'''
with open(filename, mode) as filey:
config.write(filey)
return filename | [
"def",
"write_config",
"(",
"filename",
",",
"config",
",",
"mode",
"=",
"\"w\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"filey",
":",
"config",
".",
"write",
"(",
"filey",
")",
"return",
"filename"
] | use configparser to write a config object to filename | [
"use",
"configparser",
"to",
"write",
"a",
"config",
"object",
"to",
"filename"
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/fileio.py#L55-L60 | train | 51,292 |
vsoch/helpme | helpme/utils/fileio.py | copyfile | def copyfile(source, destination, force=True):
'''copy a file from a source to its destination.
'''
if os.path.exists(destination) and force is True:
os.remove(destination)
shutil.copyfile(source, destination)
return destination | python | def copyfile(source, destination, force=True):
'''copy a file from a source to its destination.
'''
if os.path.exists(destination) and force is True:
os.remove(destination)
shutil.copyfile(source, destination)
return destination | [
"def",
"copyfile",
"(",
"source",
",",
"destination",
",",
"force",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"destination",
")",
"and",
"force",
"is",
"True",
":",
"os",
".",
"remove",
"(",
"destination",
")",
"shutil",
"."... | copy a file from a source to its destination. | [
"copy",
"a",
"file",
"from",
"a",
"source",
"to",
"its",
"destination",
"."
] | e609172260b10cddadb2d2023ab26da8082a9feb | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/fileio.py#L87-L93 | train | 51,293 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper.full_inventory | def full_inventory(self):
"""
Returns a full inventory
Some additional work required to provide consistent and consumable
output.
Inventory output only contains values, no keys - Add the keys to
the output so that it can be consumed more easily.
"""
if self._full_inventory:
return self._full_inventory
resp, inventory = self.get('Inventory')
keys = ['host_id', 'hostname', 'ip_address', 'chassis',
'used_count', 'current_state', 'comment', 'distro',
'rel', 'centos_version', 'architecture', 'node_pool',
'console_port', 'flavor']
real_inventory = dict()
for host in inventory:
real_inventory[host[1]] = dict()
for key in keys:
real_inventory[host[1]][key] = host[keys.index(key)]
self._full_inventory = real_inventory
return self._full_inventory | python | def full_inventory(self):
"""
Returns a full inventory
Some additional work required to provide consistent and consumable
output.
Inventory output only contains values, no keys - Add the keys to
the output so that it can be consumed more easily.
"""
if self._full_inventory:
return self._full_inventory
resp, inventory = self.get('Inventory')
keys = ['host_id', 'hostname', 'ip_address', 'chassis',
'used_count', 'current_state', 'comment', 'distro',
'rel', 'centos_version', 'architecture', 'node_pool',
'console_port', 'flavor']
real_inventory = dict()
for host in inventory:
real_inventory[host[1]] = dict()
for key in keys:
real_inventory[host[1]][key] = host[keys.index(key)]
self._full_inventory = real_inventory
return self._full_inventory | [
"def",
"full_inventory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_full_inventory",
":",
"return",
"self",
".",
"_full_inventory",
"resp",
",",
"inventory",
"=",
"self",
".",
"get",
"(",
"'Inventory'",
")",
"keys",
"=",
"[",
"'host_id'",
",",
"'hostname'... | Returns a full inventory
Some additional work required to provide consistent and consumable
output.
Inventory output only contains values, no keys - Add the keys to
the output so that it can be consumed more easily. | [
"Returns",
"a",
"full",
"inventory",
"Some",
"additional",
"work",
"required",
"to",
"provide",
"consistent",
"and",
"consumable",
"output",
".",
"Inventory",
"output",
"only",
"contains",
"values",
"no",
"keys",
"-",
"Add",
"the",
"keys",
"to",
"the",
"output... | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L55-L81 | train | 51,294 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper.self_inventory | def self_inventory(self):
"""
Inventory output will only contain the server name and the session ID
when a key is provided. Provide the same format as with the full
inventory instead for consistency.
"""
if self.api_key is None:
return {}
if self._self_inventory:
return self._self_inventory
resp, self_inventory = self.get('Inventory?key=%s' % self.api_key)
real_self_inventory = dict()
for host in self_inventory:
real_self_inventory[host[0]] = self.full_inventory[host[0]]
self._self_inventory = real_self_inventory
return self._self_inventory | python | def self_inventory(self):
"""
Inventory output will only contain the server name and the session ID
when a key is provided. Provide the same format as with the full
inventory instead for consistency.
"""
if self.api_key is None:
return {}
if self._self_inventory:
return self._self_inventory
resp, self_inventory = self.get('Inventory?key=%s' % self.api_key)
real_self_inventory = dict()
for host in self_inventory:
real_self_inventory[host[0]] = self.full_inventory[host[0]]
self._self_inventory = real_self_inventory
return self._self_inventory | [
"def",
"self_inventory",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_key",
"is",
"None",
":",
"return",
"{",
"}",
"if",
"self",
".",
"_self_inventory",
":",
"return",
"self",
".",
"_self_inventory",
"resp",
",",
"self_inventory",
"=",
"self",
".",
"ge... | Inventory output will only contain the server name and the session ID
when a key is provided. Provide the same format as with the full
inventory instead for consistency. | [
"Inventory",
"output",
"will",
"only",
"contain",
"the",
"server",
"name",
"and",
"the",
"session",
"ID",
"when",
"a",
"key",
"is",
"provided",
".",
"Provide",
"the",
"same",
"format",
"as",
"with",
"the",
"full",
"inventory",
"instead",
"for",
"consistency"... | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L84-L104 | train | 51,295 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper._ssid_inventory | def _ssid_inventory(self, inventory, ssid):
"""
Filters an inventory to only return servers matching ssid
"""
matching_hosts = {}
for host in inventory:
if inventory[host]['comment'] == ssid:
matching_hosts[host] = inventory[host]
return matching_hosts | python | def _ssid_inventory(self, inventory, ssid):
"""
Filters an inventory to only return servers matching ssid
"""
matching_hosts = {}
for host in inventory:
if inventory[host]['comment'] == ssid:
matching_hosts[host] = inventory[host]
return matching_hosts | [
"def",
"_ssid_inventory",
"(",
"self",
",",
"inventory",
",",
"ssid",
")",
":",
"matching_hosts",
"=",
"{",
"}",
"for",
"host",
"in",
"inventory",
":",
"if",
"inventory",
"[",
"host",
"]",
"[",
"'comment'",
"]",
"==",
"ssid",
":",
"matching_hosts",
"[",
... | Filters an inventory to only return servers matching ssid | [
"Filters",
"an",
"inventory",
"to",
"only",
"return",
"servers",
"matching",
"ssid"
] | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L106-L115 | train | 51,296 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper.inventory | def inventory(self, all=False, ssid=None):
"""
Returns a node inventory. If an API key is specified, only the nodes
provisioned by this key will be returned.
:return: { inventory }
"""
if all or self.api_key is None:
if ssid is not None:
return self._ssid_inventory(self.full_inventory, ssid)
else:
return self.full_inventory
else:
if ssid is not None:
return self._ssid_inventory(self.self_inventory, ssid)
else:
return self.self_inventory | python | def inventory(self, all=False, ssid=None):
"""
Returns a node inventory. If an API key is specified, only the nodes
provisioned by this key will be returned.
:return: { inventory }
"""
if all or self.api_key is None:
if ssid is not None:
return self._ssid_inventory(self.full_inventory, ssid)
else:
return self.full_inventory
else:
if ssid is not None:
return self._ssid_inventory(self.self_inventory, ssid)
else:
return self.self_inventory | [
"def",
"inventory",
"(",
"self",
",",
"all",
"=",
"False",
",",
"ssid",
"=",
"None",
")",
":",
"if",
"all",
"or",
"self",
".",
"api_key",
"is",
"None",
":",
"if",
"ssid",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_ssid_inventory",
"(",
"sel... | Returns a node inventory. If an API key is specified, only the nodes
provisioned by this key will be returned.
:return: { inventory } | [
"Returns",
"a",
"node",
"inventory",
".",
"If",
"an",
"API",
"key",
"is",
"specified",
"only",
"the",
"nodes",
"provisioned",
"by",
"this",
"key",
"will",
"be",
"returned",
"."
] | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L117-L133 | train | 51,297 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper.node_get | def node_get(self, arch=None, ver=None, flavor=None, count=1,
retry_count=1, retry_interval=10):
"""
Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: Number of servers (ex: 2)
:parma flavor: The flavor of machine to use (multi-arch only)
:param retry_count: Number of times to retry in case of failure (ex: 5)
:param retry_interval: Wait in seconds between each retry (ex: 30)
:return: [ [ requested_hosts ], ssid ]
"""
if self.api_key is None:
raise exceptions.ApiKeyRequired
args = "key=%s" % self.api_key
if arch is not None:
args += "&arch=%s" % arch
if ver is not None:
args += "&ver=%s" % ver
if flavor is not None:
args += "&flavor=%s" % flavor
args += "&count=%s" % count
resp, body = self.get('Node/get?%s' % args)
if not body:
for _ in range(retry_count):
time.sleep(retry_interval)
resp, body = self.get('Node/get?%s' % args)
if body:
break
if not body:
raise exceptions.NoInventory
# Get the hosts that were requested.
# Note: We have to iterate over full inventory instead of just the
# hosts we got back from the response because the reply contains the
# fqdn of the host while the full inventory only contains a short name.
requested_hosts = dict()
for host in self.full_inventory:
for full_host in body['hosts']:
if host in full_host:
requested_hosts[host] = self.full_inventory[host]
return requested_hosts, body['ssid'] | python | def node_get(self, arch=None, ver=None, flavor=None, count=1,
retry_count=1, retry_interval=10):
"""
Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: Number of servers (ex: 2)
:parma flavor: The flavor of machine to use (multi-arch only)
:param retry_count: Number of times to retry in case of failure (ex: 5)
:param retry_interval: Wait in seconds between each retry (ex: 30)
:return: [ [ requested_hosts ], ssid ]
"""
if self.api_key is None:
raise exceptions.ApiKeyRequired
args = "key=%s" % self.api_key
if arch is not None:
args += "&arch=%s" % arch
if ver is not None:
args += "&ver=%s" % ver
if flavor is not None:
args += "&flavor=%s" % flavor
args += "&count=%s" % count
resp, body = self.get('Node/get?%s' % args)
if not body:
for _ in range(retry_count):
time.sleep(retry_interval)
resp, body = self.get('Node/get?%s' % args)
if body:
break
if not body:
raise exceptions.NoInventory
# Get the hosts that were requested.
# Note: We have to iterate over full inventory instead of just the
# hosts we got back from the response because the reply contains the
# fqdn of the host while the full inventory only contains a short name.
requested_hosts = dict()
for host in self.full_inventory:
for full_host in body['hosts']:
if host in full_host:
requested_hosts[host] = self.full_inventory[host]
return requested_hosts, body['ssid'] | [
"def",
"node_get",
"(",
"self",
",",
"arch",
"=",
"None",
",",
"ver",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"count",
"=",
"1",
",",
"retry_count",
"=",
"1",
",",
"retry_interval",
"=",
"10",
")",
":",
"if",
"self",
".",
"api_key",
"is",
"... | Requests specified number of nodes with the provided parameters.
:param arch: Server architecture (ex: x86_64)
:param ver: CentOS version (ex: 7)
:param count: Number of servers (ex: 2)
:parma flavor: The flavor of machine to use (multi-arch only)
:param retry_count: Number of times to retry in case of failure (ex: 5)
:param retry_interval: Wait in seconds between each retry (ex: 30)
:return: [ [ requested_hosts ], ssid ] | [
"Requests",
"specified",
"number",
"of",
"nodes",
"with",
"the",
"provided",
"parameters",
"."
] | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L135-L181 | train | 51,298 |
CentOS/python-cicoclient | cicoclient/wrapper.py | CicoWrapper.node_done | def node_done(self, ssid=None):
"""
Release the servers for the specified ssid.
The API doesn't provide any kind of output, try to be helpful by
providing the list of servers to be released.
:param ssid: ssid of the server pool
:return: [ requested_hosts ]
"""
if self.api_key is None:
raise exceptions.ApiKeyRequired
if ssid is None:
raise exceptions.SsidRequired
# There is no body replied in this call so at least get the hosts for
# the specified ssid to return them.
requested_hosts = dict()
for host in self.self_inventory:
if ssid == self.self_inventory[host]['comment']:
requested_hosts[host] = self.full_inventory[host]
args = "key={key}&ssid={ssid}".format(key=self.api_key, ssid=ssid)
resp, body = self.get('Node/done?%s' % args)
return requested_hosts | python | def node_done(self, ssid=None):
"""
Release the servers for the specified ssid.
The API doesn't provide any kind of output, try to be helpful by
providing the list of servers to be released.
:param ssid: ssid of the server pool
:return: [ requested_hosts ]
"""
if self.api_key is None:
raise exceptions.ApiKeyRequired
if ssid is None:
raise exceptions.SsidRequired
# There is no body replied in this call so at least get the hosts for
# the specified ssid to return them.
requested_hosts = dict()
for host in self.self_inventory:
if ssid == self.self_inventory[host]['comment']:
requested_hosts[host] = self.full_inventory[host]
args = "key={key}&ssid={ssid}".format(key=self.api_key, ssid=ssid)
resp, body = self.get('Node/done?%s' % args)
return requested_hosts | [
"def",
"node_done",
"(",
"self",
",",
"ssid",
"=",
"None",
")",
":",
"if",
"self",
".",
"api_key",
"is",
"None",
":",
"raise",
"exceptions",
".",
"ApiKeyRequired",
"if",
"ssid",
"is",
"None",
":",
"raise",
"exceptions",
".",
"SsidRequired",
"# There is no ... | Release the servers for the specified ssid.
The API doesn't provide any kind of output, try to be helpful by
providing the list of servers to be released.
:param ssid: ssid of the server pool
:return: [ requested_hosts ] | [
"Release",
"the",
"servers",
"for",
"the",
"specified",
"ssid",
".",
"The",
"API",
"doesn",
"t",
"provide",
"any",
"kind",
"of",
"output",
"try",
"to",
"be",
"helpful",
"by",
"providing",
"the",
"list",
"of",
"servers",
"to",
"be",
"released",
"."
] | ffee34f446ceb25348b13a500d5c545df202c182 | https://github.com/CentOS/python-cicoclient/blob/ffee34f446ceb25348b13a500d5c545df202c182/cicoclient/wrapper.py#L183-L209 | train | 51,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.