id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
25,280 | @pytest.mark.cmd
@pytest.mark.django_db
@pytest.mark.skipif((sys.platform == 'win32'), reason='No Elasticsearch in Windows testing')
def test_update_tmserver_files(capfd, settings, tmpdir):
settings.POOTLE_TM_SERVER = {'external': {'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend', 'HOST': 'localhost', 'PORT': 9200, 'INDEX_NAME': 'translations-external'}}
p = tmpdir.mkdir('tmserver_files').join('tutorial.po')
p.write('msgid "rest"\nmsgstr "test"\n ')
with pytest.raises(CommandError) as e:
call_command('update_tmserver', '--tm=external', '--display-name=Test', os.path.join(p.dirname, p.basename))
assert ('Unable to determine target language' in str(e))
call_command('update_tmserver', '--tm=external', '--display-name=Test', '--target-language=af', os.path.join(p.dirname, p.basename))
(out, err) = capfd.readouterr()
assert ('1 translations to index' in out)
| [
"@",
"pytest",
".",
"mark",
".",
"cmd",
"@",
"pytest",
".",
"mark",
".",
"django_db",
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
",",
"reason",
"=",
"'No Elasticsearch in Windows testing'",
")",
"def",
"test_update_tmserver_files",
"(",
"capfd",
",",
"settings",
",",
"tmpdir",
")",
":",
"settings",
".",
"POOTLE_TM_SERVER",
"=",
"{",
"'external'",
":",
"{",
"'ENGINE'",
":",
"'pootle.core.search.backends.ElasticSearchBackend'",
",",
"'HOST'",
":",
"'localhost'",
",",
"'PORT'",
":",
"9200",
",",
"'INDEX_NAME'",
":",
"'translations-external'",
"}",
"}",
"p",
"=",
"tmpdir",
".",
"mkdir",
"(",
"'tmserver_files'",
")",
".",
"join",
"(",
"'tutorial.po'",
")",
"p",
".",
"write",
"(",
"'msgid \"rest\"\\nmsgstr \"test\"\\n '",
")",
"with",
"pytest",
".",
"raises",
"(",
"CommandError",
")",
"as",
"e",
":",
"call_command",
"(",
"'update_tmserver'",
",",
"'--tm=external'",
",",
"'--display-name=Test'",
",",
"os",
".",
"path",
".",
"join",
"(",
"p",
".",
"dirname",
",",
"p",
".",
"basename",
")",
")",
"assert",
"(",
"'Unable to determine target language'",
"in",
"str",
"(",
"e",
")",
")",
"call_command",
"(",
"'update_tmserver'",
",",
"'--tm=external'",
",",
"'--display-name=Test'",
",",
"'--target-language=af'",
",",
"os",
".",
"path",
".",
"join",
"(",
"p",
".",
"dirname",
",",
"p",
".",
"basename",
")",
")",
"(",
"out",
",",
"err",
")",
"=",
"capfd",
".",
"readouterr",
"(",
")",
"assert",
"(",
"'1 translations to index'",
"in",
"out",
")"
] | load tm from files . | train | false |
25,282 | def disableCache():
_entityCache = _NullCache()
| [
"def",
"disableCache",
"(",
")",
":",
"_entityCache",
"=",
"_NullCache",
"(",
")"
] | disable the entity cache . | train | false |
25,284 | def get_repository_owner(cleaned_repository_url):
items = cleaned_repository_url.split('/repos/')
repo_path = items[1]
if repo_path.startswith('/'):
repo_path = repo_path.replace('/', '', 1)
return repo_path.lstrip('/').split('/')[0]
| [
"def",
"get_repository_owner",
"(",
"cleaned_repository_url",
")",
":",
"items",
"=",
"cleaned_repository_url",
".",
"split",
"(",
"'/repos/'",
")",
"repo_path",
"=",
"items",
"[",
"1",
"]",
"if",
"repo_path",
".",
"startswith",
"(",
"'/'",
")",
":",
"repo_path",
"=",
"repo_path",
".",
"replace",
"(",
"'/'",
",",
"''",
",",
"1",
")",
"return",
"repo_path",
".",
"lstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]"
] | gvien a "cleaned" repository clone url . | train | false |
25,285 | def register_opts(conf):
conf.register_opts(auth_token.opts, group=OPT_GROUP_NAME)
auth_token.CONF = conf
| [
"def",
"register_opts",
"(",
"conf",
")",
":",
"conf",
".",
"register_opts",
"(",
"auth_token",
".",
"opts",
",",
"group",
"=",
"OPT_GROUP_NAME",
")",
"auth_token",
".",
"CONF",
"=",
"conf"
] | register keystoneclient middleware options . | train | false |
25,286 | def scale_taxa_data_matrix(coords, pct_var):
return (coords[:, :len(pct_var)] * (pct_var / pct_var.max()))
| [
"def",
"scale_taxa_data_matrix",
"(",
"coords",
",",
"pct_var",
")",
":",
"return",
"(",
"coords",
"[",
":",
",",
":",
"len",
"(",
"pct_var",
")",
"]",
"*",
"(",
"pct_var",
"/",
"pct_var",
".",
"max",
"(",
")",
")",
")"
] | scales pc data matrix by percent variation . | train | false |
25,289 | def get_featured_activity_summary_dicts(language_codes):
activity_references = activity_services.get_featured_activity_references()
(exploration_ids, collection_ids) = activity_services.split_by_type(activity_references)
exp_summary_dicts = get_displayable_exp_summary_dicts_matching_ids(exploration_ids)
col_summary_dicts = get_displayable_collection_summary_dicts_matching_ids(collection_ids)
summary_dicts_by_id = {feconf.ACTIVITY_TYPE_EXPLORATION: {summary_dict['id']: summary_dict for summary_dict in exp_summary_dicts}, feconf.ACTIVITY_TYPE_COLLECTION: {summary_dict['id']: summary_dict for summary_dict in col_summary_dicts}}
featured_summary_dicts = []
for reference in activity_references:
if (reference.id in summary_dicts_by_id[reference.type]):
summary_dict = summary_dicts_by_id[reference.type][reference.id]
if (summary_dict and (summary_dict['language_code'] in language_codes)):
featured_summary_dicts.append(summary_dict)
return featured_summary_dicts
| [
"def",
"get_featured_activity_summary_dicts",
"(",
"language_codes",
")",
":",
"activity_references",
"=",
"activity_services",
".",
"get_featured_activity_references",
"(",
")",
"(",
"exploration_ids",
",",
"collection_ids",
")",
"=",
"activity_services",
".",
"split_by_type",
"(",
"activity_references",
")",
"exp_summary_dicts",
"=",
"get_displayable_exp_summary_dicts_matching_ids",
"(",
"exploration_ids",
")",
"col_summary_dicts",
"=",
"get_displayable_collection_summary_dicts_matching_ids",
"(",
"collection_ids",
")",
"summary_dicts_by_id",
"=",
"{",
"feconf",
".",
"ACTIVITY_TYPE_EXPLORATION",
":",
"{",
"summary_dict",
"[",
"'id'",
"]",
":",
"summary_dict",
"for",
"summary_dict",
"in",
"exp_summary_dicts",
"}",
",",
"feconf",
".",
"ACTIVITY_TYPE_COLLECTION",
":",
"{",
"summary_dict",
"[",
"'id'",
"]",
":",
"summary_dict",
"for",
"summary_dict",
"in",
"col_summary_dicts",
"}",
"}",
"featured_summary_dicts",
"=",
"[",
"]",
"for",
"reference",
"in",
"activity_references",
":",
"if",
"(",
"reference",
".",
"id",
"in",
"summary_dicts_by_id",
"[",
"reference",
".",
"type",
"]",
")",
":",
"summary_dict",
"=",
"summary_dicts_by_id",
"[",
"reference",
".",
"type",
"]",
"[",
"reference",
".",
"id",
"]",
"if",
"(",
"summary_dict",
"and",
"(",
"summary_dict",
"[",
"'language_code'",
"]",
"in",
"language_codes",
")",
")",
":",
"featured_summary_dicts",
".",
"append",
"(",
"summary_dict",
")",
"return",
"featured_summary_dicts"
] | returns a list of featured activities with the given language codes . | train | false |
25,291 | def _HandleResponse(method, response):
if (response.code != 200):
raise AdminAPIError(('%s failed: %s' % (method, response.read())))
else:
response_dict = json.loads(response.read())
if ('error' in response_dict):
raise AdminAPIError(('%s failed: %s' % (method, response_dict['error']['message'])))
return response_dict
| [
"def",
"_HandleResponse",
"(",
"method",
",",
"response",
")",
":",
"if",
"(",
"response",
".",
"code",
"!=",
"200",
")",
":",
"raise",
"AdminAPIError",
"(",
"(",
"'%s failed: %s'",
"%",
"(",
"method",
",",
"response",
".",
"read",
"(",
")",
")",
")",
")",
"else",
":",
"response_dict",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
")",
"if",
"(",
"'error'",
"in",
"response_dict",
")",
":",
"raise",
"AdminAPIError",
"(",
"(",
"'%s failed: %s'",
"%",
"(",
"method",
",",
"response_dict",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
")",
")",
")",
"return",
"response_dict"
] | verifies the response and returns the json dict of the response body on success . | train | false |
25,292 | def serve_webapp(webapp, port=None, host=None):
server = None
if (port is not None):
server = httpserver.serve(webapp, host=host, port=port, start_loop=False)
else:
random.seed()
for i in range(0, 9):
try:
port = str(random.randint(8000, 10000))
server = httpserver.serve(webapp, host=host, port=port, start_loop=False)
break
except socket.error as e:
if (e[0] == 98):
continue
raise
else:
raise Exception(('Unable to open a port between %s and %s to start Galaxy server' % (8000, 1000)))
t = threading.Thread(target=server.serve_forever)
t.start()
return (server, port)
| [
"def",
"serve_webapp",
"(",
"webapp",
",",
"port",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"server",
"=",
"None",
"if",
"(",
"port",
"is",
"not",
"None",
")",
":",
"server",
"=",
"httpserver",
".",
"serve",
"(",
"webapp",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"start_loop",
"=",
"False",
")",
"else",
":",
"random",
".",
"seed",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"9",
")",
":",
"try",
":",
"port",
"=",
"str",
"(",
"random",
".",
"randint",
"(",
"8000",
",",
"10000",
")",
")",
"server",
"=",
"httpserver",
".",
"serve",
"(",
"webapp",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"start_loop",
"=",
"False",
")",
"break",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"(",
"e",
"[",
"0",
"]",
"==",
"98",
")",
":",
"continue",
"raise",
"else",
":",
"raise",
"Exception",
"(",
"(",
"'Unable to open a port between %s and %s to start Galaxy server'",
"%",
"(",
"8000",
",",
"1000",
")",
")",
")",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"server",
".",
"serve_forever",
")",
"t",
".",
"start",
"(",
")",
"return",
"(",
"server",
",",
"port",
")"
] | serve the webapp on a recommend port or a free one . | train | false |
25,293 | def xl_col_to_name(col_num, col_abs=False):
col_num += 1
col_str = ''
col_abs = ('$' if col_abs else '')
while col_num:
remainder = (col_num % 26)
if (remainder == 0):
remainder = 26
col_letter = chr(((ord('A') + remainder) - 1))
col_str = (col_letter + col_str)
col_num = int(((col_num - 1) / 26))
return (col_abs + col_str)
| [
"def",
"xl_col_to_name",
"(",
"col_num",
",",
"col_abs",
"=",
"False",
")",
":",
"col_num",
"+=",
"1",
"col_str",
"=",
"''",
"col_abs",
"=",
"(",
"'$'",
"if",
"col_abs",
"else",
"''",
")",
"while",
"col_num",
":",
"remainder",
"=",
"(",
"col_num",
"%",
"26",
")",
"if",
"(",
"remainder",
"==",
"0",
")",
":",
"remainder",
"=",
"26",
"col_letter",
"=",
"chr",
"(",
"(",
"(",
"ord",
"(",
"'A'",
")",
"+",
"remainder",
")",
"-",
"1",
")",
")",
"col_str",
"=",
"(",
"col_letter",
"+",
"col_str",
")",
"col_num",
"=",
"int",
"(",
"(",
"(",
"col_num",
"-",
"1",
")",
"/",
"26",
")",
")",
"return",
"(",
"col_abs",
"+",
"col_str",
")"
] | convert a zero indexed column cell reference to a string . | train | false |
25,294 | def test_pmf_hist_basics():
out = utils.pmf_hist(a_norm)
assert_equal(len(out), 3)
(x, h, w) = out
assert_equal(len(x), len(h))
a = np.arange(10)
(x, h, w) = utils.pmf_hist(a, 10)
nose.tools.assert_true(np.all((h == h[0])))
| [
"def",
"test_pmf_hist_basics",
"(",
")",
":",
"out",
"=",
"utils",
".",
"pmf_hist",
"(",
"a_norm",
")",
"assert_equal",
"(",
"len",
"(",
"out",
")",
",",
"3",
")",
"(",
"x",
",",
"h",
",",
"w",
")",
"=",
"out",
"assert_equal",
"(",
"len",
"(",
"x",
")",
",",
"len",
"(",
"h",
")",
")",
"a",
"=",
"np",
".",
"arange",
"(",
"10",
")",
"(",
"x",
",",
"h",
",",
"w",
")",
"=",
"utils",
".",
"pmf_hist",
"(",
"a",
",",
"10",
")",
"nose",
".",
"tools",
".",
"assert_true",
"(",
"np",
".",
"all",
"(",
"(",
"h",
"==",
"h",
"[",
"0",
"]",
")",
")",
")"
] | test the function to return barplot args for pmf hist . | train | false |
25,295 | @cacheit
def _simplify_delta(expr):
from sympy.solvers import solve
if isinstance(expr, KroneckerDelta):
try:
slns = solve((expr.args[0] - expr.args[1]), dict=True)
if (slns and (len(slns) == 1)):
return Mul(*[KroneckerDelta(*(key, value)) for (key, value) in slns[0].items()])
except NotImplementedError:
pass
return expr
| [
"@",
"cacheit",
"def",
"_simplify_delta",
"(",
"expr",
")",
":",
"from",
"sympy",
".",
"solvers",
"import",
"solve",
"if",
"isinstance",
"(",
"expr",
",",
"KroneckerDelta",
")",
":",
"try",
":",
"slns",
"=",
"solve",
"(",
"(",
"expr",
".",
"args",
"[",
"0",
"]",
"-",
"expr",
".",
"args",
"[",
"1",
"]",
")",
",",
"dict",
"=",
"True",
")",
"if",
"(",
"slns",
"and",
"(",
"len",
"(",
"slns",
")",
"==",
"1",
")",
")",
":",
"return",
"Mul",
"(",
"*",
"[",
"KroneckerDelta",
"(",
"*",
"(",
"key",
",",
"value",
")",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"slns",
"[",
"0",
"]",
".",
"items",
"(",
")",
"]",
")",
"except",
"NotImplementedError",
":",
"pass",
"return",
"expr"
] | rewrite a kroneckerdeltas indices in its simplest form . | train | false |
25,297 | def getProfileCopyright(profile):
try:
if (not isinstance(profile, ImageCmsProfile)):
profile = ImageCmsProfile(profile)
return (profile.profile.product_copyright + '\n')
except (AttributeError, IOError, TypeError, ValueError) as v:
raise PyCMSError(v)
| [
"def",
"getProfileCopyright",
"(",
"profile",
")",
":",
"try",
":",
"if",
"(",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"product_copyright",
"+",
"'\\n'",
")",
"except",
"(",
"AttributeError",
",",
"IOError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")"
] | gets the copyright for the given profile . | train | false |
25,298 | def can_disable_rate_limit(clz):
if (not issubclass(clz, APIView)):
msg = u'{clz} is not a Django Rest Framework APIView subclass.'.format(clz=clz)
LOGGER.warning(msg)
return clz
if hasattr(clz, 'check_throttles'):
clz.check_throttles = _check_throttles_decorator(clz.check_throttles)
return clz
| [
"def",
"can_disable_rate_limit",
"(",
"clz",
")",
":",
"if",
"(",
"not",
"issubclass",
"(",
"clz",
",",
"APIView",
")",
")",
":",
"msg",
"=",
"u'{clz} is not a Django Rest Framework APIView subclass.'",
".",
"format",
"(",
"clz",
"=",
"clz",
")",
"LOGGER",
".",
"warning",
"(",
"msg",
")",
"return",
"clz",
"if",
"hasattr",
"(",
"clz",
",",
"'check_throttles'",
")",
":",
"clz",
".",
"check_throttles",
"=",
"_check_throttles_decorator",
"(",
"clz",
".",
"check_throttles",
")",
"return",
"clz"
] | class decorator that allows rate limiting to be disabled . | train | false |
25,300 | def getGeometryOutputByStep(end, loop, steps, stepVector, xmlElement):
stepsFloor = int(math.floor(abs(steps)))
for stepIndex in xrange(1, stepsFloor):
loop.append((loop[(stepIndex - 1)] + stepVector))
loop.append(end)
return lineation.getGeometryOutputByLoop(lineation.SideLoop(loop), xmlElement)
| [
"def",
"getGeometryOutputByStep",
"(",
"end",
",",
"loop",
",",
"steps",
",",
"stepVector",
",",
"xmlElement",
")",
":",
"stepsFloor",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"abs",
"(",
"steps",
")",
")",
")",
"for",
"stepIndex",
"in",
"xrange",
"(",
"1",
",",
"stepsFloor",
")",
":",
"loop",
".",
"append",
"(",
"(",
"loop",
"[",
"(",
"stepIndex",
"-",
"1",
")",
"]",
"+",
"stepVector",
")",
")",
"loop",
".",
"append",
"(",
"end",
")",
"return",
"lineation",
".",
"getGeometryOutputByLoop",
"(",
"lineation",
".",
"SideLoop",
"(",
"loop",
")",
",",
"xmlElement",
")"
] | get line geometry output by the end . | train | false |
25,301 | def signal_to_exception(signum, frame):
if (signum == signal.SIGALRM):
raise SIGALRMException()
if (signum == signal.SIGHUP):
raise SIGHUPException()
if (signum == signal.SIGUSR1):
raise SIGUSR1Exception()
if (signum == signal.SIGUSR2):
raise SIGUSR2Exception()
raise SignalException(signum)
| [
"def",
"signal_to_exception",
"(",
"signum",
",",
"frame",
")",
":",
"if",
"(",
"signum",
"==",
"signal",
".",
"SIGALRM",
")",
":",
"raise",
"SIGALRMException",
"(",
")",
"if",
"(",
"signum",
"==",
"signal",
".",
"SIGHUP",
")",
":",
"raise",
"SIGHUPException",
"(",
")",
"if",
"(",
"signum",
"==",
"signal",
".",
"SIGUSR1",
")",
":",
"raise",
"SIGUSR1Exception",
"(",
")",
"if",
"(",
"signum",
"==",
"signal",
".",
"SIGUSR2",
")",
":",
"raise",
"SIGUSR2Exception",
"(",
")",
"raise",
"SignalException",
"(",
"signum",
")"
] | called by the timeout alarm during the collector run time . | train | true |
25,302 | def _session():
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
| [
"def",
"_session",
"(",
")",
":",
"config",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'zenoss'",
")",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"session",
".",
"auth",
"=",
"(",
"config",
".",
"get",
"(",
"'username'",
")",
",",
"config",
".",
"get",
"(",
"'password'",
")",
")",
"session",
".",
"verify",
"=",
"False",
"session",
".",
"headers",
".",
"update",
"(",
"{",
"'Content-type'",
":",
"'application/json; charset=utf-8'",
"}",
")",
"return",
"session"
] | create a session to be used when connecting to zenoss . | train | true |
25,304 | def migrate(verbose=True, rebuild_website=False):
clear_global_cache()
frappe.modules.patch_handler.run_all()
frappe.model.sync.sync_all(verbose=verbose)
frappe.translate.clear_cache()
sync_fixtures()
sync_customizations()
sync_desktop_icons()
sync_languages()
frappe.get_doc(u'Portal Settings', u'Portal Settings').sync_menu()
render.clear_cache()
frappe.db.commit()
if (not frappe.conf.get(u'global_help_setup')):
frappe.utils.help.sync()
clear_notifications()
frappe.publish_realtime(u'version-update')
| [
"def",
"migrate",
"(",
"verbose",
"=",
"True",
",",
"rebuild_website",
"=",
"False",
")",
":",
"clear_global_cache",
"(",
")",
"frappe",
".",
"modules",
".",
"patch_handler",
".",
"run_all",
"(",
")",
"frappe",
".",
"model",
".",
"sync",
".",
"sync_all",
"(",
"verbose",
"=",
"verbose",
")",
"frappe",
".",
"translate",
".",
"clear_cache",
"(",
")",
"sync_fixtures",
"(",
")",
"sync_customizations",
"(",
")",
"sync_desktop_icons",
"(",
")",
"sync_languages",
"(",
")",
"frappe",
".",
"get_doc",
"(",
"u'Portal Settings'",
",",
"u'Portal Settings'",
")",
".",
"sync_menu",
"(",
")",
"render",
".",
"clear_cache",
"(",
")",
"frappe",
".",
"db",
".",
"commit",
"(",
")",
"if",
"(",
"not",
"frappe",
".",
"conf",
".",
"get",
"(",
"u'global_help_setup'",
")",
")",
":",
"frappe",
".",
"utils",
".",
"help",
".",
"sync",
"(",
")",
"clear_notifications",
"(",
")",
"frappe",
".",
"publish_realtime",
"(",
"u'version-update'",
")"
] | perform a migration . | train | false |
25,305 | def attachment_upload_to(instance, filename):
now = datetime.now()
return ('attachments/%(date)s/%(id)s/%(md5)s/%(filename)s' % {'date': now.strftime('%Y/%m/%d'), 'id': instance.attachment.id, 'md5': hashlib.md5(str(now)).hexdigest(), 'filename': filename})
| [
"def",
"attachment_upload_to",
"(",
"instance",
",",
"filename",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"return",
"(",
"'attachments/%(date)s/%(id)s/%(md5)s/%(filename)s'",
"%",
"{",
"'date'",
":",
"now",
".",
"strftime",
"(",
"'%Y/%m/%d'",
")",
",",
"'id'",
":",
"instance",
".",
"attachment",
".",
"id",
",",
"'md5'",
":",
"hashlib",
".",
"md5",
"(",
"str",
"(",
"now",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"'filename'",
":",
"filename",
"}",
")"
] | generate a path to store a file attachment . | train | false |
25,306 | def format_dateaxis(subplot, freq):
majlocator = TimeSeries_DateLocator(freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot)
minlocator = TimeSeries_DateLocator(freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot)
subplot.xaxis.set_major_locator(majlocator)
subplot.xaxis.set_minor_locator(minlocator)
majformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot)
minformatter = TimeSeries_DateFormatter(freq, dynamic_mode=True, minor_locator=True, plot_obj=subplot)
subplot.xaxis.set_major_formatter(majformatter)
subplot.xaxis.set_minor_formatter(minformatter)
subplot.format_coord = (lambda t, y: 't = {0} y = {1:8f}'.format(Period(ordinal=int(t), freq=freq), y))
pylab.draw_if_interactive()
| [
"def",
"format_dateaxis",
"(",
"subplot",
",",
"freq",
")",
":",
"majlocator",
"=",
"TimeSeries_DateLocator",
"(",
"freq",
",",
"dynamic_mode",
"=",
"True",
",",
"minor_locator",
"=",
"False",
",",
"plot_obj",
"=",
"subplot",
")",
"minlocator",
"=",
"TimeSeries_DateLocator",
"(",
"freq",
",",
"dynamic_mode",
"=",
"True",
",",
"minor_locator",
"=",
"True",
",",
"plot_obj",
"=",
"subplot",
")",
"subplot",
".",
"xaxis",
".",
"set_major_locator",
"(",
"majlocator",
")",
"subplot",
".",
"xaxis",
".",
"set_minor_locator",
"(",
"minlocator",
")",
"majformatter",
"=",
"TimeSeries_DateFormatter",
"(",
"freq",
",",
"dynamic_mode",
"=",
"True",
",",
"minor_locator",
"=",
"False",
",",
"plot_obj",
"=",
"subplot",
")",
"minformatter",
"=",
"TimeSeries_DateFormatter",
"(",
"freq",
",",
"dynamic_mode",
"=",
"True",
",",
"minor_locator",
"=",
"True",
",",
"plot_obj",
"=",
"subplot",
")",
"subplot",
".",
"xaxis",
".",
"set_major_formatter",
"(",
"majformatter",
")",
"subplot",
".",
"xaxis",
".",
"set_minor_formatter",
"(",
"minformatter",
")",
"subplot",
".",
"format_coord",
"=",
"(",
"lambda",
"t",
",",
"y",
":",
"'t = {0} y = {1:8f}'",
".",
"format",
"(",
"Period",
"(",
"ordinal",
"=",
"int",
"(",
"t",
")",
",",
"freq",
"=",
"freq",
")",
",",
"y",
")",
")",
"pylab",
".",
"draw_if_interactive",
"(",
")"
] | pretty-formats the date axis . | train | false |
25,307 | def csvheader(parent, nodelist):
header = ''
for subnode in nodelist:
if (subnode.nodeType == subnode.ELEMENT_NODE):
header = ((((header + ',') + parent) + '.') + subnode.tagName)
return (header[1:] + '\n')
| [
"def",
"csvheader",
"(",
"parent",
",",
"nodelist",
")",
":",
"header",
"=",
"''",
"for",
"subnode",
"in",
"nodelist",
":",
"if",
"(",
"subnode",
".",
"nodeType",
"==",
"subnode",
".",
"ELEMENT_NODE",
")",
":",
"header",
"=",
"(",
"(",
"(",
"(",
"header",
"+",
"','",
")",
"+",
"parent",
")",
"+",
"'.'",
")",
"+",
"subnode",
".",
"tagName",
")",
"return",
"(",
"header",
"[",
"1",
":",
"]",
"+",
"'\\n'",
")"
] | gives the header for the csv @todo: deprecate . | train | false |
25,308 | def get_module_for_student(student, usage_key, request=None, course=None):
if (request is None):
request = DummyRequest()
request.user = student
descriptor = modulestore().get_item(usage_key, depth=0)
field_data_cache = FieldDataCache([descriptor], usage_key.course_key, student)
return get_module(student, request, usage_key, field_data_cache, course=course)
| [
"def",
"get_module_for_student",
"(",
"student",
",",
"usage_key",
",",
"request",
"=",
"None",
",",
"course",
"=",
"None",
")",
":",
"if",
"(",
"request",
"is",
"None",
")",
":",
"request",
"=",
"DummyRequest",
"(",
")",
"request",
".",
"user",
"=",
"student",
"descriptor",
"=",
"modulestore",
"(",
")",
".",
"get_item",
"(",
"usage_key",
",",
"depth",
"=",
"0",
")",
"field_data_cache",
"=",
"FieldDataCache",
"(",
"[",
"descriptor",
"]",
",",
"usage_key",
".",
"course_key",
",",
"student",
")",
"return",
"get_module",
"(",
"student",
",",
"request",
",",
"usage_key",
",",
"field_data_cache",
",",
"course",
"=",
"course",
")"
] | return the module for the using a dummyrequest . | train | false |
25,309 | @click.command('backup-all-sites')
def backup_all_sites():
from bench.utils import backup_all_sites
backup_all_sites(bench_path='.')
| [
"@",
"click",
".",
"command",
"(",
"'backup-all-sites'",
")",
"def",
"backup_all_sites",
"(",
")",
":",
"from",
"bench",
".",
"utils",
"import",
"backup_all_sites",
"backup_all_sites",
"(",
"bench_path",
"=",
"'.'",
")"
] | backup all sites . | train | false |
25,310 | def shor(N):
a = (random.randrange((N - 2)) + 2)
if (igcd(N, a) != 1):
print('got lucky with rand')
return igcd(N, a)
print('a= ', a)
print('N= ', N)
r = period_find(a, N)
print('r= ', r)
if ((r % 2) == 1):
print('r is not even, begin again')
shor(N)
answer = (igcd(((a ** (r / 2)) - 1), N), igcd(((a ** (r / 2)) + 1), N))
return answer
| [
"def",
"shor",
"(",
"N",
")",
":",
"a",
"=",
"(",
"random",
".",
"randrange",
"(",
"(",
"N",
"-",
"2",
")",
")",
"+",
"2",
")",
"if",
"(",
"igcd",
"(",
"N",
",",
"a",
")",
"!=",
"1",
")",
":",
"print",
"(",
"'got lucky with rand'",
")",
"return",
"igcd",
"(",
"N",
",",
"a",
")",
"print",
"(",
"'a= '",
",",
"a",
")",
"print",
"(",
"'N= '",
",",
"N",
")",
"r",
"=",
"period_find",
"(",
"a",
",",
"N",
")",
"print",
"(",
"'r= '",
",",
"r",
")",
"if",
"(",
"(",
"r",
"%",
"2",
")",
"==",
"1",
")",
":",
"print",
"(",
"'r is not even, begin again'",
")",
"shor",
"(",
"N",
")",
"answer",
"=",
"(",
"igcd",
"(",
"(",
"(",
"a",
"**",
"(",
"r",
"/",
"2",
")",
")",
"-",
"1",
")",
",",
"N",
")",
",",
"igcd",
"(",
"(",
"(",
"a",
"**",
"(",
"r",
"/",
"2",
")",
")",
"+",
"1",
")",
",",
"N",
")",
")",
"return",
"answer"
] | this function implements shors factoring algorithm on the integer n the algorithm starts by picking a random number (a) and seeing if it is coprime with n . | train | false |
25,311 | def add_service_port(service, port):
if (service not in get_services(permanent=True)):
raise CommandExecutionError('The service does not exist.')
cmd = '--permanent --service={0} --add-port={1}'.format(service, port)
return __firewall_cmd(cmd)
| [
"def",
"add_service_port",
"(",
"service",
",",
"port",
")",
":",
"if",
"(",
"service",
"not",
"in",
"get_services",
"(",
"permanent",
"=",
"True",
")",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'The service does not exist.'",
")",
"cmd",
"=",
"'--permanent --service={0} --add-port={1}'",
".",
"format",
"(",
"service",
",",
"port",
")",
"return",
"__firewall_cmd",
"(",
"cmd",
")"
] | add a new port to the specified service . | train | true |
25,312 | def locateNodes(nodeList, key, value, noNesting=1):
returnList = []
if (not isinstance(nodeList, type([]))):
return locateNodes(nodeList.childNodes, key, value, noNesting)
for childNode in nodeList:
if (not hasattr(childNode, 'getAttribute')):
continue
if (str(childNode.getAttribute(key)) == value):
returnList.append(childNode)
if noNesting:
continue
returnList.extend(locateNodes(childNode, key, value, noNesting))
return returnList
| [
"def",
"locateNodes",
"(",
"nodeList",
",",
"key",
",",
"value",
",",
"noNesting",
"=",
"1",
")",
":",
"returnList",
"=",
"[",
"]",
"if",
"(",
"not",
"isinstance",
"(",
"nodeList",
",",
"type",
"(",
"[",
"]",
")",
")",
")",
":",
"return",
"locateNodes",
"(",
"nodeList",
".",
"childNodes",
",",
"key",
",",
"value",
",",
"noNesting",
")",
"for",
"childNode",
"in",
"nodeList",
":",
"if",
"(",
"not",
"hasattr",
"(",
"childNode",
",",
"'getAttribute'",
")",
")",
":",
"continue",
"if",
"(",
"str",
"(",
"childNode",
".",
"getAttribute",
"(",
"key",
")",
")",
"==",
"value",
")",
":",
"returnList",
".",
"append",
"(",
"childNode",
")",
"if",
"noNesting",
":",
"continue",
"returnList",
".",
"extend",
"(",
"locateNodes",
"(",
"childNode",
",",
"key",
",",
"value",
",",
"noNesting",
")",
")",
"return",
"returnList"
] | find subnodes in the given node where the given attribute has the given value . | train | false |
25,313 | def _huge(deployment_prototype, node_prototype):
return deployment_prototype.update_node(huge_node(node_prototype))
| [
"def",
"_huge",
"(",
"deployment_prototype",
",",
"node_prototype",
")",
":",
"return",
"deployment_prototype",
".",
"update_node",
"(",
"huge_node",
"(",
"node_prototype",
")",
")"
] | return a deployment with many applications . | train | false |
25,314 | def get_poster(video):
if (not video.bumper.get('enabled')):
return
poster = OrderedDict({'url': '', 'type': ''})
if video.youtube_streams:
youtube_id = video.youtube_streams.split('1.00:')[1].split(',')[0]
poster['url'] = settings.YOUTUBE['IMAGE_API'].format(youtube_id=youtube_id)
poster['type'] = 'youtube'
else:
poster['url'] = 'https://www.edx.org/sites/default/files/theme/edx-logo-header.png'
poster['type'] = 'html5'
return poster
| [
"def",
"get_poster",
"(",
"video",
")",
":",
"if",
"(",
"not",
"video",
".",
"bumper",
".",
"get",
"(",
"'enabled'",
")",
")",
":",
"return",
"poster",
"=",
"OrderedDict",
"(",
"{",
"'url'",
":",
"''",
",",
"'type'",
":",
"''",
"}",
")",
"if",
"video",
".",
"youtube_streams",
":",
"youtube_id",
"=",
"video",
".",
"youtube_streams",
".",
"split",
"(",
"'1.00:'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
"poster",
"[",
"'url'",
"]",
"=",
"settings",
".",
"YOUTUBE",
"[",
"'IMAGE_API'",
"]",
".",
"format",
"(",
"youtube_id",
"=",
"youtube_id",
")",
"poster",
"[",
"'type'",
"]",
"=",
"'youtube'",
"else",
":",
"poster",
"[",
"'url'",
"]",
"=",
"'https://www.edx.org/sites/default/files/theme/edx-logo-header.png'",
"poster",
"[",
"'type'",
"]",
"=",
"'html5'",
"return",
"poster"
] | generate poster metadata . | train | false |
25,315 | def try_int(candidate, default_value=0):
try:
return int(candidate)
except (ValueError, TypeError):
return default_value
| [
"def",
"try_int",
"(",
"candidate",
",",
"default_value",
"=",
"0",
")",
":",
"try",
":",
"return",
"int",
"(",
"candidate",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"default_value"
] | try to convert candidate to int . | train | false |
25,316 | def test_unicode():
tstr = u'\x00xCAFE'
def badapp(environ, start_response):
start_response('200 OK', [])
raise HTTPBadRequest(tstr)
newapp = HTTPExceptionHandler(badapp)
assert (tstr.encode('utf-8') in ''.join(newapp({'HTTP_ACCEPT': 'text/html'}, (lambda a, b, c=None: None))))
assert (tstr.encode('utf-8') in ''.join(newapp({'HTTP_ACCEPT': 'text/plain'}, (lambda a, b, c=None: None))))
| [
"def",
"test_unicode",
"(",
")",
":",
"tstr",
"=",
"u'\\x00xCAFE'",
"def",
"badapp",
"(",
"environ",
",",
"start_response",
")",
":",
"start_response",
"(",
"'200 OK'",
",",
"[",
"]",
")",
"raise",
"HTTPBadRequest",
"(",
"tstr",
")",
"newapp",
"=",
"HTTPExceptionHandler",
"(",
"badapp",
")",
"assert",
"(",
"tstr",
".",
"encode",
"(",
"'utf-8'",
")",
"in",
"''",
".",
"join",
"(",
"newapp",
"(",
"{",
"'HTTP_ACCEPT'",
":",
"'text/html'",
"}",
",",
"(",
"lambda",
"a",
",",
"b",
",",
"c",
"=",
"None",
":",
"None",
")",
")",
")",
")",
"assert",
"(",
"tstr",
".",
"encode",
"(",
"'utf-8'",
")",
"in",
"''",
".",
"join",
"(",
"newapp",
"(",
"{",
"'HTTP_ACCEPT'",
":",
"'text/plain'",
"}",
",",
"(",
"lambda",
"a",
",",
"b",
",",
"c",
"=",
"None",
":",
"None",
")",
")",
")",
")"
] | verify unicode output . | train | false |
25,317 | def parsedoc(path, format=None):
if isinstance(path, basestring):
if ((format == 'pdf') or path.endswith('.pdf')):
return parsepdf(path)
if ((format == 'docx') or path.endswith('.docx')):
return parsedocx(path)
if ((format == 'html') or path.endswith(('.htm', '.html', '.xhtml'))):
return parsehtml(path)
for f in (parsepdf, parsedocx, parsehtml):
try:
return f(path)
except:
pass
| [
"def",
"parsedoc",
"(",
"path",
",",
"format",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"if",
"(",
"(",
"format",
"==",
"'pdf'",
")",
"or",
"path",
".",
"endswith",
"(",
"'.pdf'",
")",
")",
":",
"return",
"parsepdf",
"(",
"path",
")",
"if",
"(",
"(",
"format",
"==",
"'docx'",
")",
"or",
"path",
".",
"endswith",
"(",
"'.docx'",
")",
")",
":",
"return",
"parsedocx",
"(",
"path",
")",
"if",
"(",
"(",
"format",
"==",
"'html'",
")",
"or",
"path",
".",
"endswith",
"(",
"(",
"'.htm'",
",",
"'.html'",
",",
"'.xhtml'",
")",
")",
")",
":",
"return",
"parsehtml",
"(",
"path",
")",
"for",
"f",
"in",
"(",
"parsepdf",
",",
"parsedocx",
",",
"parsehtml",
")",
":",
"try",
":",
"return",
"f",
"(",
"path",
")",
"except",
":",
"pass"
] | returns the content as a unicode string from the given document . | train | false |
25,318 | def clear_memo():
if available:
cupy.clear_memo()
| [
"def",
"clear_memo",
"(",
")",
":",
"if",
"available",
":",
"cupy",
".",
"clear_memo",
"(",
")"
] | clears the memoized results for all functions decorated by memoize . | train | false |
25,319 | def firebase_patch(path, value=None):
(response, content) = _get_http().request(path, method='PATCH', body=value)
return json.loads(content)
| [
"def",
"firebase_patch",
"(",
"path",
",",
"value",
"=",
"None",
")",
":",
"(",
"response",
",",
"content",
")",
"=",
"_get_http",
"(",
")",
".",
"request",
"(",
"path",
",",
"method",
"=",
"'PATCH'",
",",
"body",
"=",
"value",
")",
"return",
"json",
".",
"loads",
"(",
"content",
")"
] | update specific children or fields an http patch allows specific children or fields to be updated without overwriting the entire object . | train | false |
25,320 | def _expm_multiply_interval_core_0(A, X, h, mu, m_star, s, q):
for k in range(q):
X[(k + 1)] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s)
return (X, 0)
| [
"def",
"_expm_multiply_interval_core_0",
"(",
"A",
",",
"X",
",",
"h",
",",
"mu",
",",
"m_star",
",",
"s",
",",
"q",
")",
":",
"for",
"k",
"in",
"range",
"(",
"q",
")",
":",
"X",
"[",
"(",
"k",
"+",
"1",
")",
"]",
"=",
"_expm_multiply_simple_core",
"(",
"A",
",",
"X",
"[",
"k",
"]",
",",
"h",
",",
"mu",
",",
"m_star",
",",
"s",
")",
"return",
"(",
"X",
",",
"0",
")"
] | a helper function . | train | false |
25,321 | def xxd(shift, data, bytes_per_line, bytes_per_sentence):
current = 0
for current in xrange(0, len(data), bytes_per_line):
line = data[current:(current + bytes_per_line)]
line_printable = mask_not_alphanumeric(line)[1]
line_ordinals = map(ord, line)
offsets = range(0, len(line_ordinals), bytes_per_sentence)
line_ordinal_words = [line_ordinals[x:(x + bytes_per_sentence)] for x in offsets]
(yield ((shift + current), line_ordinal_words, line_printable))
| [
"def",
"xxd",
"(",
"shift",
",",
"data",
",",
"bytes_per_line",
",",
"bytes_per_sentence",
")",
":",
"current",
"=",
"0",
"for",
"current",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"bytes_per_line",
")",
":",
"line",
"=",
"data",
"[",
"current",
":",
"(",
"current",
"+",
"bytes_per_line",
")",
"]",
"line_printable",
"=",
"mask_not_alphanumeric",
"(",
"line",
")",
"[",
"1",
"]",
"line_ordinals",
"=",
"map",
"(",
"ord",
",",
"line",
")",
"offsets",
"=",
"range",
"(",
"0",
",",
"len",
"(",
"line_ordinals",
")",
",",
"bytes_per_sentence",
")",
"line_ordinal_words",
"=",
"[",
"line_ordinals",
"[",
"x",
":",
"(",
"x",
"+",
"bytes_per_sentence",
")",
"]",
"for",
"x",
"in",
"offsets",
"]",
"(",
"yield",
"(",
"(",
"shift",
"+",
"current",
")",
",",
"line_ordinal_words",
",",
"line_printable",
")",
")"
] | a generator of strings . | train | false |
25,322 | def digest_auth(realm, get_ha1, key, debug=False):
request = cherrypy.serving.request
auth_header = request.headers.get('authorization')
nonce_is_stale = False
if (auth_header is not None):
with cherrypy.HTTPError.handle(ValueError, 400, 'The Authorization header could not be parsed.'):
auth = HttpDigestAuthorization(auth_header, request.method, debug=debug)
if debug:
TRACE(str(auth))
if auth.validate_nonce(realm, key):
ha1 = get_ha1(realm, auth.username)
if (ha1 is not None):
digest = auth.request_digest(ha1, entity_body=request.body)
if (digest == auth.response):
if debug:
TRACE('digest matches auth.response')
nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600)
if (not nonce_is_stale):
request.login = auth.username
if debug:
TRACE(('authentication of %s successful' % auth.username))
return
header = www_authenticate(realm, key, stale=nonce_is_stale)
if debug:
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
raise cherrypy.HTTPError(401, 'You are not authorized to access that resource')
| [
"def",
"digest_auth",
"(",
"realm",
",",
"get_ha1",
",",
"key",
",",
"debug",
"=",
"False",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"auth_header",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'authorization'",
")",
"nonce_is_stale",
"=",
"False",
"if",
"(",
"auth_header",
"is",
"not",
"None",
")",
":",
"with",
"cherrypy",
".",
"HTTPError",
".",
"handle",
"(",
"ValueError",
",",
"400",
",",
"'The Authorization header could not be parsed.'",
")",
":",
"auth",
"=",
"HttpDigestAuthorization",
"(",
"auth_header",
",",
"request",
".",
"method",
",",
"debug",
"=",
"debug",
")",
"if",
"debug",
":",
"TRACE",
"(",
"str",
"(",
"auth",
")",
")",
"if",
"auth",
".",
"validate_nonce",
"(",
"realm",
",",
"key",
")",
":",
"ha1",
"=",
"get_ha1",
"(",
"realm",
",",
"auth",
".",
"username",
")",
"if",
"(",
"ha1",
"is",
"not",
"None",
")",
":",
"digest",
"=",
"auth",
".",
"request_digest",
"(",
"ha1",
",",
"entity_body",
"=",
"request",
".",
"body",
")",
"if",
"(",
"digest",
"==",
"auth",
".",
"response",
")",
":",
"if",
"debug",
":",
"TRACE",
"(",
"'digest matches auth.response'",
")",
"nonce_is_stale",
"=",
"auth",
".",
"is_nonce_stale",
"(",
"max_age_seconds",
"=",
"600",
")",
"if",
"(",
"not",
"nonce_is_stale",
")",
":",
"request",
".",
"login",
"=",
"auth",
".",
"username",
"if",
"debug",
":",
"TRACE",
"(",
"(",
"'authentication of %s successful'",
"%",
"auth",
".",
"username",
")",
")",
"return",
"header",
"=",
"www_authenticate",
"(",
"realm",
",",
"key",
",",
"stale",
"=",
"nonce_is_stale",
")",
"if",
"debug",
":",
"TRACE",
"(",
"header",
")",
"cherrypy",
".",
"serving",
".",
"response",
".",
"headers",
"[",
"'WWW-Authenticate'",
"]",
"=",
"header",
"raise",
"cherrypy",
".",
"HTTPError",
"(",
"401",
",",
"'You are not authorized to access that resource'",
")"
] | if auth fails . | train | false |
25,323 | def p_assignment_expression_2(t):
pass
| [
"def",
"p_assignment_expression_2",
"(",
"t",
")",
":",
"pass"
] | assignment_expression : unary_expression assignment_operator assignment_expression . | train | false |
25,324 | def parse_opcode_signature(env, sig, signode):
m = opcode_sig_re.match(sig)
if (m is None):
raise ValueError
(opname, arglist) = m.groups()
signode += addnodes.desc_name(opname, opname)
if (arglist is not None):
paramlist = addnodes.desc_parameterlist()
signode += paramlist
paramlist += addnodes.desc_parameter(arglist, arglist)
return opname.strip()
| [
"def",
"parse_opcode_signature",
"(",
"env",
",",
"sig",
",",
"signode",
")",
":",
"m",
"=",
"opcode_sig_re",
".",
"match",
"(",
"sig",
")",
"if",
"(",
"m",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"opname",
",",
"arglist",
")",
"=",
"m",
".",
"groups",
"(",
")",
"signode",
"+=",
"addnodes",
".",
"desc_name",
"(",
"opname",
",",
"opname",
")",
"if",
"(",
"arglist",
"is",
"not",
"None",
")",
":",
"paramlist",
"=",
"addnodes",
".",
"desc_parameterlist",
"(",
")",
"signode",
"+=",
"paramlist",
"paramlist",
"+=",
"addnodes",
".",
"desc_parameter",
"(",
"arglist",
",",
"arglist",
")",
"return",
"opname",
".",
"strip",
"(",
")"
] | transform an opcode signature into rst nodes . | train | false |
25,325 | def set_http_proxy(server, port, user=None, password=None, network_service='Ethernet', bypass_hosts=None):
if (__grains__['os'] == 'Windows'):
return _set_proxy_windows(server, port, ['http'], bypass_hosts)
return _set_proxy_osx('setwebproxy', server, port, user, password, network_service)
| [
"def",
"set_http_proxy",
"(",
"server",
",",
"port",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"network_service",
"=",
"'Ethernet'",
",",
"bypass_hosts",
"=",
"None",
")",
":",
"if",
"(",
"__grains__",
"[",
"'os'",
"]",
"==",
"'Windows'",
")",
":",
"return",
"_set_proxy_windows",
"(",
"server",
",",
"port",
",",
"[",
"'http'",
"]",
",",
"bypass_hosts",
")",
"return",
"_set_proxy_osx",
"(",
"'setwebproxy'",
",",
"server",
",",
"port",
",",
"user",
",",
"password",
",",
"network_service",
")"
] | sets the http proxy settings . | train | false |
25,326 | def test_local_repo_typo(tmpdir):
template_path = os.path.join('tests', 'unknown-repo')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(template_path, abbreviations={}, clone_to_dir=str(tmpdir), checkout=None, no_input=True)
assert (str(err.value) == 'A valid repository for "{}" could not be found in the following locations:\n{}'.format(template_path, '\n'.join([template_path, str((tmpdir / 'tests/unknown-repo'))])))
| [
"def",
"test_local_repo_typo",
"(",
"tmpdir",
")",
":",
"template_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'tests'",
",",
"'unknown-repo'",
")",
"with",
"pytest",
".",
"raises",
"(",
"exceptions",
".",
"RepositoryNotFound",
")",
"as",
"err",
":",
"repository",
".",
"determine_repo_dir",
"(",
"template_path",
",",
"abbreviations",
"=",
"{",
"}",
",",
"clone_to_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"checkout",
"=",
"None",
",",
"no_input",
"=",
"True",
")",
"assert",
"(",
"str",
"(",
"err",
".",
"value",
")",
"==",
"'A valid repository for \"{}\" could not be found in the following locations:\\n{}'",
".",
"format",
"(",
"template_path",
",",
"'\\n'",
".",
"join",
"(",
"[",
"template_path",
",",
"str",
"(",
"(",
"tmpdir",
"/",
"'tests/unknown-repo'",
")",
")",
"]",
")",
")",
")"
] | an unknown local repository should raise a repositorynotfound exception . | train | false |
25,327 | def undirected_connected_components(gr):
if gr.DIRECTED:
raise Exception('This method works only with a undirected graph')
explored = set([])
con_components = []
for node in gr.nodes():
if (node not in explored):
reachable_nodes = BFS(gr, node)
con_components.append(reachable_nodes)
explored |= reachable_nodes
return con_components
| [
"def",
"undirected_connected_components",
"(",
"gr",
")",
":",
"if",
"gr",
".",
"DIRECTED",
":",
"raise",
"Exception",
"(",
"'This method works only with a undirected graph'",
")",
"explored",
"=",
"set",
"(",
"[",
"]",
")",
"con_components",
"=",
"[",
"]",
"for",
"node",
"in",
"gr",
".",
"nodes",
"(",
")",
":",
"if",
"(",
"node",
"not",
"in",
"explored",
")",
":",
"reachable_nodes",
"=",
"BFS",
"(",
"gr",
",",
"node",
")",
"con_components",
".",
"append",
"(",
"reachable_nodes",
")",
"explored",
"|=",
"reachable_nodes",
"return",
"con_components"
] | returns a list of connected components in an undirected graph . | train | false |
25,328 | def _prefix_env_vars(command, local=False):
env_vars = {}
path = env.path
if path:
if (env.path_behavior == 'append'):
path = ('$PATH:"%s"' % path)
elif (env.path_behavior == 'prepend'):
path = ('"%s":$PATH' % path)
elif (env.path_behavior == 'replace'):
path = ('"%s"' % path)
env_vars['PATH'] = path
env_vars.update(env.shell_env)
if env_vars:
(set_cmd, exp_cmd) = ('', '')
if (win32 and local):
set_cmd = 'SET '
else:
exp_cmd = 'export '
exports = ' '.join((('%s%s="%s"' % (set_cmd, k, (v if (k == 'PATH') else _shell_escape(v)))) for (k, v) in env_vars.iteritems()))
shell_env_str = ('%s%s && ' % (exp_cmd, exports))
else:
shell_env_str = ''
return (shell_env_str + command)
| [
"def",
"_prefix_env_vars",
"(",
"command",
",",
"local",
"=",
"False",
")",
":",
"env_vars",
"=",
"{",
"}",
"path",
"=",
"env",
".",
"path",
"if",
"path",
":",
"if",
"(",
"env",
".",
"path_behavior",
"==",
"'append'",
")",
":",
"path",
"=",
"(",
"'$PATH:\"%s\"'",
"%",
"path",
")",
"elif",
"(",
"env",
".",
"path_behavior",
"==",
"'prepend'",
")",
":",
"path",
"=",
"(",
"'\"%s\":$PATH'",
"%",
"path",
")",
"elif",
"(",
"env",
".",
"path_behavior",
"==",
"'replace'",
")",
":",
"path",
"=",
"(",
"'\"%s\"'",
"%",
"path",
")",
"env_vars",
"[",
"'PATH'",
"]",
"=",
"path",
"env_vars",
".",
"update",
"(",
"env",
".",
"shell_env",
")",
"if",
"env_vars",
":",
"(",
"set_cmd",
",",
"exp_cmd",
")",
"=",
"(",
"''",
",",
"''",
")",
"if",
"(",
"win32",
"and",
"local",
")",
":",
"set_cmd",
"=",
"'SET '",
"else",
":",
"exp_cmd",
"=",
"'export '",
"exports",
"=",
"' '",
".",
"join",
"(",
"(",
"(",
"'%s%s=\"%s\"'",
"%",
"(",
"set_cmd",
",",
"k",
",",
"(",
"v",
"if",
"(",
"k",
"==",
"'PATH'",
")",
"else",
"_shell_escape",
"(",
"v",
")",
")",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"env_vars",
".",
"iteritems",
"(",
")",
")",
")",
"shell_env_str",
"=",
"(",
"'%s%s && '",
"%",
"(",
"exp_cmd",
",",
"exports",
")",
")",
"else",
":",
"shell_env_str",
"=",
"''",
"return",
"(",
"shell_env_str",
"+",
"command",
")"
] | prefixes command with any shell environment vars . | train | false |
25,329 | def _check_return(ret, description):
if (ret == ''):
raise TimeoutException(description)
elif (ret[(-1)] == OptiCAL._NACK):
raise NACKException(description)
| [
"def",
"_check_return",
"(",
"ret",
",",
"description",
")",
":",
"if",
"(",
"ret",
"==",
"''",
")",
":",
"raise",
"TimeoutException",
"(",
"description",
")",
"elif",
"(",
"ret",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"OptiCAL",
".",
"_NACK",
")",
":",
"raise",
"NACKException",
"(",
"description",
")"
] | check the return value of a read . | train | false |
25,330 | @TaskGenerator
def compute_texture(im):
from features import texture
imc = mh.imread(im)
return texture(mh.colors.rgb2grey(imc))
| [
"@",
"TaskGenerator",
"def",
"compute_texture",
"(",
"im",
")",
":",
"from",
"features",
"import",
"texture",
"imc",
"=",
"mh",
".",
"imread",
"(",
"im",
")",
"return",
"texture",
"(",
"mh",
".",
"colors",
".",
"rgb2grey",
"(",
"imc",
")",
")"
] | compute features for an image parameters im : str filepath for image to process returns fs : ndarray 1-d array of features . | train | false |
25,331 | def _test_revamp():
imputil.ImportManager().install()
sys.path.insert(0, PathImporter())
sys.path.insert(0, imputil.BuiltinImporter())
| [
"def",
"_test_revamp",
"(",
")",
":",
"imputil",
".",
"ImportManager",
"(",
")",
".",
"install",
"(",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"PathImporter",
"(",
")",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"imputil",
".",
"BuiltinImporter",
"(",
")",
")"
] | debug/test function for the revamped import system . | train | false |
25,332 | def rsentence(length=4):
return ' '.join((rword(random.randint(4, 9)) for i in range(length)))
| [
"def",
"rsentence",
"(",
"length",
"=",
"4",
")",
":",
"return",
"' '",
".",
"join",
"(",
"(",
"rword",
"(",
"random",
".",
"randint",
"(",
"4",
",",
"9",
")",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
")",
")"
] | generate a random sentence-like string . | train | false |
25,333 | def selectSome(strings, requiredsubstrings=[], requireAll=True):
if (len(requiredsubstrings) == 0):
return strings
res = []
for s in strings:
if requireAll:
bad = False
for rs in requiredsubstrings:
if (s.find(rs) < 0):
bad = True
break
if (not bad):
res.append(s)
else:
for rs in requiredsubstrings:
if (s.find(rs) >= 0):
res.append(s)
break
return res
| [
"def",
"selectSome",
"(",
"strings",
",",
"requiredsubstrings",
"=",
"[",
"]",
",",
"requireAll",
"=",
"True",
")",
":",
"if",
"(",
"len",
"(",
"requiredsubstrings",
")",
"==",
"0",
")",
":",
"return",
"strings",
"res",
"=",
"[",
"]",
"for",
"s",
"in",
"strings",
":",
"if",
"requireAll",
":",
"bad",
"=",
"False",
"for",
"rs",
"in",
"requiredsubstrings",
":",
"if",
"(",
"s",
".",
"find",
"(",
"rs",
")",
"<",
"0",
")",
":",
"bad",
"=",
"True",
"break",
"if",
"(",
"not",
"bad",
")",
":",
"res",
".",
"append",
"(",
"s",
")",
"else",
":",
"for",
"rs",
"in",
"requiredsubstrings",
":",
"if",
"(",
"s",
".",
"find",
"(",
"rs",
")",
">=",
"0",
")",
":",
"res",
".",
"append",
"(",
"s",
")",
"break",
"return",
"res"
] | filter the list of strings to only contain those that have at least one of the required substrings . | train | false |
25,335 | def get_permission_types():
return _PERMISSION_TYPES.keys()
| [
"def",
"get_permission_types",
"(",
")",
":",
"return",
"_PERMISSION_TYPES",
".",
"keys",
"(",
")"
] | get the permission types that can be configured for communities . | train | false |
25,337 | @with_device
def push(local_path, remote_path):
msg = ('Pushing %r to %r' % (local_path, remote_path))
remote_filename = os.path.basename(local_path)
if log.isEnabledFor(logging.DEBUG):
msg += (' (%s)' % context.device)
with log.waitfor(msg) as w:
with AdbClient() as c:
stat_ = c.stat(remote_path)
if (not stat_):
remote_filename = os.path.basename(remote_path)
remote_path = os.path.dirname(remote_path)
stat_ = c.stat(remote_path)
if (not stat_):
log.error(('Could not stat %r' % remote_path))
mode = stat_['mode']
if stat.S_ISDIR(mode):
remote_path = os.path.join(remote_path, remote_filename)
return c.write(remote_path, misc.read(local_path), callback=_create_adb_push_pull_callback(w))
| [
"@",
"with_device",
"def",
"push",
"(",
"local_path",
",",
"remote_path",
")",
":",
"msg",
"=",
"(",
"'Pushing %r to %r'",
"%",
"(",
"local_path",
",",
"remote_path",
")",
")",
"remote_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_path",
")",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"msg",
"+=",
"(",
"' (%s)'",
"%",
"context",
".",
"device",
")",
"with",
"log",
".",
"waitfor",
"(",
"msg",
")",
"as",
"w",
":",
"with",
"AdbClient",
"(",
")",
"as",
"c",
":",
"stat_",
"=",
"c",
".",
"stat",
"(",
"remote_path",
")",
"if",
"(",
"not",
"stat_",
")",
":",
"remote_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"remote_path",
")",
"remote_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"remote_path",
")",
"stat_",
"=",
"c",
".",
"stat",
"(",
"remote_path",
")",
"if",
"(",
"not",
"stat_",
")",
":",
"log",
".",
"error",
"(",
"(",
"'Could not stat %r'",
"%",
"remote_path",
")",
")",
"mode",
"=",
"stat_",
"[",
"'mode'",
"]",
"if",
"stat",
".",
"S_ISDIR",
"(",
"mode",
")",
":",
"remote_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"remote_path",
",",
"remote_filename",
")",
"return",
"c",
".",
"write",
"(",
"remote_path",
",",
"misc",
".",
"read",
"(",
"local_path",
")",
",",
"callback",
"=",
"_create_adb_push_pull_callback",
"(",
"w",
")",
")"
] | push an image onto the shared image stack . | train | false |
25,341 | @conf.commands.register
def srploop(pkts, *args, **kargs):
return __sr_loop(srp, pkts, *args, **kargs)
| [
"@",
"conf",
".",
"commands",
".",
"register",
"def",
"srploop",
"(",
"pkts",
",",
"*",
"args",
",",
"**",
"kargs",
")",
":",
"return",
"__sr_loop",
"(",
"srp",
",",
"pkts",
",",
"*",
"args",
",",
"**",
"kargs",
")"
] | send a packet at layer 2 in loop and print the answer each time srloop --> none . | train | false |
25,342 | def gf_trace_map(a, b, c, n, f, p, K):
u = gf_compose_mod(a, b, f, p, K)
v = b
if (n & 1):
U = gf_add(a, u, p, K)
V = b
else:
U = a
V = c
n >>= 1
while n:
u = gf_add(u, gf_compose_mod(u, v, f, p, K), p, K)
v = gf_compose_mod(v, v, f, p, K)
if (n & 1):
U = gf_add(U, gf_compose_mod(u, V, f, p, K), p, K)
V = gf_compose_mod(v, V, f, p, K)
n >>= 1
return (gf_compose_mod(a, V, f, p, K), U)
| [
"def",
"gf_trace_map",
"(",
"a",
",",
"b",
",",
"c",
",",
"n",
",",
"f",
",",
"p",
",",
"K",
")",
":",
"u",
"=",
"gf_compose_mod",
"(",
"a",
",",
"b",
",",
"f",
",",
"p",
",",
"K",
")",
"v",
"=",
"b",
"if",
"(",
"n",
"&",
"1",
")",
":",
"U",
"=",
"gf_add",
"(",
"a",
",",
"u",
",",
"p",
",",
"K",
")",
"V",
"=",
"b",
"else",
":",
"U",
"=",
"a",
"V",
"=",
"c",
"n",
">>=",
"1",
"while",
"n",
":",
"u",
"=",
"gf_add",
"(",
"u",
",",
"gf_compose_mod",
"(",
"u",
",",
"v",
",",
"f",
",",
"p",
",",
"K",
")",
",",
"p",
",",
"K",
")",
"v",
"=",
"gf_compose_mod",
"(",
"v",
",",
"v",
",",
"f",
",",
"p",
",",
"K",
")",
"if",
"(",
"n",
"&",
"1",
")",
":",
"U",
"=",
"gf_add",
"(",
"U",
",",
"gf_compose_mod",
"(",
"u",
",",
"V",
",",
"f",
",",
"p",
",",
"K",
")",
",",
"p",
",",
"K",
")",
"V",
"=",
"gf_compose_mod",
"(",
"v",
",",
"V",
",",
"f",
",",
"p",
",",
"K",
")",
"n",
">>=",
"1",
"return",
"(",
"gf_compose_mod",
"(",
"a",
",",
"V",
",",
"f",
",",
"p",
",",
"K",
")",
",",
"U",
")"
] | compute polynomial trace map in gf(p)[x]/(f) . | train | false |
25,343 | def locationUpdatingAccept(MobileId_presence=0, FollowOnProceed_presence=0, CtsPermission_presence=0):
a = TpPd(pd=5)
b = MessageType(mesType=2)
c = LocalAreaId()
packet = ((a / b) / c)
if (MobileId_presence is 1):
d = MobileIdHdr(ieiMI=23, eightBitMI=0)
packet = (packet / d)
if (FollowOnProceed_presence is 1):
e = FollowOnProceed(ieiFOP=161)
packet = (packet / e)
if (CtsPermission_presence is 1):
f = CtsPermissionHdr(ieiCP=162, eightBitCP=0)
packet = (packet / f)
return packet
| [
"def",
"locationUpdatingAccept",
"(",
"MobileId_presence",
"=",
"0",
",",
"FollowOnProceed_presence",
"=",
"0",
",",
"CtsPermission_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"5",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"2",
")",
"c",
"=",
"LocalAreaId",
"(",
")",
"packet",
"=",
"(",
"(",
"a",
"/",
"b",
")",
"/",
"c",
")",
"if",
"(",
"MobileId_presence",
"is",
"1",
")",
":",
"d",
"=",
"MobileIdHdr",
"(",
"ieiMI",
"=",
"23",
",",
"eightBitMI",
"=",
"0",
")",
"packet",
"=",
"(",
"packet",
"/",
"d",
")",
"if",
"(",
"FollowOnProceed_presence",
"is",
"1",
")",
":",
"e",
"=",
"FollowOnProceed",
"(",
"ieiFOP",
"=",
"161",
")",
"packet",
"=",
"(",
"packet",
"/",
"e",
")",
"if",
"(",
"CtsPermission_presence",
"is",
"1",
")",
":",
"f",
"=",
"CtsPermissionHdr",
"(",
"ieiCP",
"=",
"162",
",",
"eightBitCP",
"=",
"0",
")",
"packet",
"=",
"(",
"packet",
"/",
"f",
")",
"return",
"packet"
] | location updating accept section 9 . | train | true |
25,344 | def month_to_index(year, month):
assert (12 >= month >= 1)
return ((((year - 1) * 12) + month) - 1)
| [
"def",
"month_to_index",
"(",
"year",
",",
"month",
")",
":",
"assert",
"(",
"12",
">=",
"month",
">=",
"1",
")",
"return",
"(",
"(",
"(",
"(",
"year",
"-",
"1",
")",
"*",
"12",
")",
"+",
"month",
")",
"-",
"1",
")"
] | convert a year and month to a single value: the number of months between this month and 1 ad . | train | false |
25,345 | def get_application_call(var):
return get_annotation(var, ApplicationCall)
| [
"def",
"get_application_call",
"(",
"var",
")",
":",
"return",
"get_annotation",
"(",
"var",
",",
"ApplicationCall",
")"
] | retrieves the application call that created this variable . | train | false |
25,346 | def eglob(pattern, directory='.'):
pieces = pathsplit(pattern)
return __find_matches(pieces, directory)
| [
"def",
"eglob",
"(",
"pattern",
",",
"directory",
"=",
"'.'",
")",
":",
"pieces",
"=",
"pathsplit",
"(",
"pattern",
")",
"return",
"__find_matches",
"(",
"pieces",
",",
"directory",
")"
] | extended glob function that supports the all the wildcards supported by the python standard glob routine . | train | false |
25,347 | def _check_symlink_ownership(path, user, group):
(cur_user, cur_group) = _get_symlink_ownership(path)
return ((cur_user == user) and (cur_group == group))
| [
"def",
"_check_symlink_ownership",
"(",
"path",
",",
"user",
",",
"group",
")",
":",
"(",
"cur_user",
",",
"cur_group",
")",
"=",
"_get_symlink_ownership",
"(",
"path",
")",
"return",
"(",
"(",
"cur_user",
"==",
"user",
")",
"and",
"(",
"cur_group",
"==",
"group",
")",
")"
] | check if the symlink ownership matches the specified user and group . | train | false |
25,348 | def remote_user_auth_view(request):
t = Template('Username is {{ user }}.')
c = RequestContext(request, {})
return HttpResponse(t.render(c))
| [
"def",
"remote_user_auth_view",
"(",
"request",
")",
":",
"t",
"=",
"Template",
"(",
"'Username is {{ user }}.'",
")",
"c",
"=",
"RequestContext",
"(",
"request",
",",
"{",
"}",
")",
"return",
"HttpResponse",
"(",
"t",
".",
"render",
"(",
"c",
")",
")"
] | dummy view for remote user tests . | train | false |
25,349 | def hmget(key, *fields, **options):
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
| [
"def",
"hmget",
"(",
"key",
",",
"*",
"fields",
",",
"**",
"options",
")",
":",
"host",
"=",
"options",
".",
"get",
"(",
"'host'",
",",
"None",
")",
"port",
"=",
"options",
".",
"get",
"(",
"'port'",
",",
"None",
")",
"database",
"=",
"options",
".",
"get",
"(",
"'db'",
",",
"None",
")",
"password",
"=",
"options",
".",
"get",
"(",
"'password'",
",",
"None",
")",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"database",
",",
"password",
")",
"return",
"server",
".",
"hmget",
"(",
"key",
",",
"*",
"fields",
")"
] | returns the values of all the given hash fields . | train | true |
25,350 | def decipher_affine(msg, key, symbols=None):
return encipher_affine(msg, key, symbols, _inverse=True)
| [
"def",
"decipher_affine",
"(",
"msg",
",",
"key",
",",
"symbols",
"=",
"None",
")",
":",
"return",
"encipher_affine",
"(",
"msg",
",",
"key",
",",
"symbols",
",",
"_inverse",
"=",
"True",
")"
] | return the deciphered text that was made from the mapping . | train | false |
25,354 | def check_list(list, ignore=0):
if ignore:
try:
list[int(ignore)]
except:
raise ValueError('non-integer ignore index or ignore index not in list')
list1 = list[:ignore]
list2 = list[ignore:]
try:
first_none = list2.index(None)
except:
return tuple((list1 + list2))
for i in range(first_none, len(list2)):
if list2[i]:
raise ValueError('non-None entry after None entry in list at index {0}'.format(i))
while True:
list2.remove(None)
try:
list2.index(None)
except:
break
return tuple((list1 + list2))
| [
"def",
"check_list",
"(",
"list",
",",
"ignore",
"=",
"0",
")",
":",
"if",
"ignore",
":",
"try",
":",
"list",
"[",
"int",
"(",
"ignore",
")",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"'non-integer ignore index or ignore index not in list'",
")",
"list1",
"=",
"list",
"[",
":",
"ignore",
"]",
"list2",
"=",
"list",
"[",
"ignore",
":",
"]",
"try",
":",
"first_none",
"=",
"list2",
".",
"index",
"(",
"None",
")",
"except",
":",
"return",
"tuple",
"(",
"(",
"list1",
"+",
"list2",
")",
")",
"for",
"i",
"in",
"range",
"(",
"first_none",
",",
"len",
"(",
"list2",
")",
")",
":",
"if",
"list2",
"[",
"i",
"]",
":",
"raise",
"ValueError",
"(",
"'non-None entry after None entry in list at index {0}'",
".",
"format",
"(",
"i",
")",
")",
"while",
"True",
":",
"list2",
".",
"remove",
"(",
"None",
")",
"try",
":",
"list2",
".",
"index",
"(",
"None",
")",
"except",
":",
"break",
"return",
"tuple",
"(",
"(",
"list1",
"+",
"list2",
")",
")"
] | checks a list for none elements . | train | false |
25,356 | def forbid_multi_line_headers(name, val, encoding):
encoding = (encoding or settings.DEFAULT_CHARSET)
val = force_text(val)
if (('\n' in val) or ('\r' in val)):
raise BadHeaderError(("Header values can't contain newlines (got %r for header %r)" % (val, name)))
try:
val.encode('ascii')
except UnicodeEncodeError:
if (name.lower() in ADDRESS_HEADERS):
val = ', '.join((sanitize_address(addr, encoding) for addr in getaddresses((val,))))
else:
val = Header(val, encoding).encode()
else:
if (name.lower() == 'subject'):
val = Header(val).encode()
return (name, val)
| [
"def",
"forbid_multi_line_headers",
"(",
"name",
",",
"val",
",",
"encoding",
")",
":",
"encoding",
"=",
"(",
"encoding",
"or",
"settings",
".",
"DEFAULT_CHARSET",
")",
"val",
"=",
"force_text",
"(",
"val",
")",
"if",
"(",
"(",
"'\\n'",
"in",
"val",
")",
"or",
"(",
"'\\r'",
"in",
"val",
")",
")",
":",
"raise",
"BadHeaderError",
"(",
"(",
"\"Header values can't contain newlines (got %r for header %r)\"",
"%",
"(",
"val",
",",
"name",
")",
")",
")",
"try",
":",
"val",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"if",
"(",
"name",
".",
"lower",
"(",
")",
"in",
"ADDRESS_HEADERS",
")",
":",
"val",
"=",
"', '",
".",
"join",
"(",
"(",
"sanitize_address",
"(",
"addr",
",",
"encoding",
")",
"for",
"addr",
"in",
"getaddresses",
"(",
"(",
"val",
",",
")",
")",
")",
")",
"else",
":",
"val",
"=",
"Header",
"(",
"val",
",",
"encoding",
")",
".",
"encode",
"(",
")",
"else",
":",
"if",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'subject'",
")",
":",
"val",
"=",
"Header",
"(",
"val",
")",
".",
"encode",
"(",
")",
"return",
"(",
"name",
",",
"val",
")"
] | forbids multi-line headers . | train | false |
25,357 | def _bound_state_log_lik(X, initial_bound, precs, means, covariance_type):
(n_components, n_features) = means.shape
n_samples = X.shape[0]
bound = np.empty((n_samples, n_components))
bound[:] = initial_bound
if (covariance_type in ['diag', 'spherical']):
for k in range(n_components):
d = (X - means[k])
bound[:, k] -= (0.5 * np.sum(((d * d) * precs[k]), axis=1))
elif (covariance_type == 'tied'):
for k in range(n_components):
bound[:, k] -= (0.5 * _sym_quad_form(X, means[k], precs))
elif (covariance_type == 'full'):
for k in range(n_components):
bound[:, k] -= (0.5 * _sym_quad_form(X, means[k], precs[k]))
return bound
| [
"def",
"_bound_state_log_lik",
"(",
"X",
",",
"initial_bound",
",",
"precs",
",",
"means",
",",
"covariance_type",
")",
":",
"(",
"n_components",
",",
"n_features",
")",
"=",
"means",
".",
"shape",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"bound",
"=",
"np",
".",
"empty",
"(",
"(",
"n_samples",
",",
"n_components",
")",
")",
"bound",
"[",
":",
"]",
"=",
"initial_bound",
"if",
"(",
"covariance_type",
"in",
"[",
"'diag'",
",",
"'spherical'",
"]",
")",
":",
"for",
"k",
"in",
"range",
"(",
"n_components",
")",
":",
"d",
"=",
"(",
"X",
"-",
"means",
"[",
"k",
"]",
")",
"bound",
"[",
":",
",",
"k",
"]",
"-=",
"(",
"0.5",
"*",
"np",
".",
"sum",
"(",
"(",
"(",
"d",
"*",
"d",
")",
"*",
"precs",
"[",
"k",
"]",
")",
",",
"axis",
"=",
"1",
")",
")",
"elif",
"(",
"covariance_type",
"==",
"'tied'",
")",
":",
"for",
"k",
"in",
"range",
"(",
"n_components",
")",
":",
"bound",
"[",
":",
",",
"k",
"]",
"-=",
"(",
"0.5",
"*",
"_sym_quad_form",
"(",
"X",
",",
"means",
"[",
"k",
"]",
",",
"precs",
")",
")",
"elif",
"(",
"covariance_type",
"==",
"'full'",
")",
":",
"for",
"k",
"in",
"range",
"(",
"n_components",
")",
":",
"bound",
"[",
":",
",",
"k",
"]",
"-=",
"(",
"0.5",
"*",
"_sym_quad_form",
"(",
"X",
",",
"means",
"[",
"k",
"]",
",",
"precs",
"[",
"k",
"]",
")",
")",
"return",
"bound"
] | update the bound with likelihood terms . | train | false |
25,358 | def has_installed_samples(shop):
return bool((get_installed_products(shop) or get_installed_categories(shop) or get_installed_carousel(shop)))
| [
"def",
"has_installed_samples",
"(",
"shop",
")",
":",
"return",
"bool",
"(",
"(",
"get_installed_products",
"(",
"shop",
")",
"or",
"get_installed_categories",
"(",
"shop",
")",
"or",
"get_installed_carousel",
"(",
"shop",
")",
")",
")"
] | returns whether there is some sample data installed . | train | false |
25,359 | def restricted(ccode, environment=None, layer='Unknown'):
if (environment is None):
environment = {}
environment['__file__'] = layer
environment['__name__'] = '__restricted__'
try:
exec ccode in environment
except HTTP:
raise
except RestrictedError:
raise
except Exception as error:
(etype, evalue, tb) = sys.exc_info()
if (__debug__ and ('WINGDB_ACTIVE' in os.environ)):
sys.excepthook(etype, evalue, tb)
del tb
output = ('%s %s' % (etype, evalue))
raise RestrictedError(layer, ccode, output, environment)
| [
"def",
"restricted",
"(",
"ccode",
",",
"environment",
"=",
"None",
",",
"layer",
"=",
"'Unknown'",
")",
":",
"if",
"(",
"environment",
"is",
"None",
")",
":",
"environment",
"=",
"{",
"}",
"environment",
"[",
"'__file__'",
"]",
"=",
"layer",
"environment",
"[",
"'__name__'",
"]",
"=",
"'__restricted__'",
"try",
":",
"exec",
"ccode",
"in",
"environment",
"except",
"HTTP",
":",
"raise",
"except",
"RestrictedError",
":",
"raise",
"except",
"Exception",
"as",
"error",
":",
"(",
"etype",
",",
"evalue",
",",
"tb",
")",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"(",
"__debug__",
"and",
"(",
"'WINGDB_ACTIVE'",
"in",
"os",
".",
"environ",
")",
")",
":",
"sys",
".",
"excepthook",
"(",
"etype",
",",
"evalue",
",",
"tb",
")",
"del",
"tb",
"output",
"=",
"(",
"'%s %s'",
"%",
"(",
"etype",
",",
"evalue",
")",
")",
"raise",
"RestrictedError",
"(",
"layer",
",",
"ccode",
",",
"output",
",",
"environment",
")"
] | runs code in environment and returns the output . | train | false |
25,360 | def vserver_sslcert_exists(v_name, sc_name, **connection_args):
return (_vserver_sslcert_get(v_name, sc_name, **connection_args) is not None)
| [
"def",
"vserver_sslcert_exists",
"(",
"v_name",
",",
"sc_name",
",",
"**",
"connection_args",
")",
":",
"return",
"(",
"_vserver_sslcert_get",
"(",
"v_name",
",",
"sc_name",
",",
"**",
"connection_args",
")",
"is",
"not",
"None",
")"
] | checks if a ssl certificate is tied to a vserver cli example: . | train | false |
25,361 | def _plot_legend(pos, colors, axis, bads, outlines, loc):
from mpl_toolkits.axes_grid.inset_locator import inset_axes
bbox = axis.get_window_extent()
ratio = (bbox.width / bbox.height)
ax = inset_axes(axis, width=(str((30 / ratio)) + '%'), height='30%', loc=loc)
(pos_x, pos_y) = _prepare_topomap(pos, ax)
ax.scatter(pos_x, pos_y, color=colors, s=25, marker='.', zorder=1)
for idx in bads:
ax.scatter(pos_x[idx], pos_y[idx], s=5, marker='.', color='w', zorder=1)
if isinstance(outlines, dict):
_draw_outlines(ax, outlines)
| [
"def",
"_plot_legend",
"(",
"pos",
",",
"colors",
",",
"axis",
",",
"bads",
",",
"outlines",
",",
"loc",
")",
":",
"from",
"mpl_toolkits",
".",
"axes_grid",
".",
"inset_locator",
"import",
"inset_axes",
"bbox",
"=",
"axis",
".",
"get_window_extent",
"(",
")",
"ratio",
"=",
"(",
"bbox",
".",
"width",
"/",
"bbox",
".",
"height",
")",
"ax",
"=",
"inset_axes",
"(",
"axis",
",",
"width",
"=",
"(",
"str",
"(",
"(",
"30",
"/",
"ratio",
")",
")",
"+",
"'%'",
")",
",",
"height",
"=",
"'30%'",
",",
"loc",
"=",
"loc",
")",
"(",
"pos_x",
",",
"pos_y",
")",
"=",
"_prepare_topomap",
"(",
"pos",
",",
"ax",
")",
"ax",
".",
"scatter",
"(",
"pos_x",
",",
"pos_y",
",",
"color",
"=",
"colors",
",",
"s",
"=",
"25",
",",
"marker",
"=",
"'.'",
",",
"zorder",
"=",
"1",
")",
"for",
"idx",
"in",
"bads",
":",
"ax",
".",
"scatter",
"(",
"pos_x",
"[",
"idx",
"]",
",",
"pos_y",
"[",
"idx",
"]",
",",
"s",
"=",
"5",
",",
"marker",
"=",
"'.'",
",",
"color",
"=",
"'w'",
",",
"zorder",
"=",
"1",
")",
"if",
"isinstance",
"(",
"outlines",
",",
"dict",
")",
":",
"_draw_outlines",
"(",
"ax",
",",
"outlines",
")"
] | plot color/channel legends for butterfly plots with spatial colors . | train | false |
25,362 | def parse_full_atom(data):
if (len(data) < 4):
raise ValueError('not enough data')
version = ord(data[0:1])
flags = cdata.uint_be(('\x00' + data[1:4]))
return (version, flags, data[4:])
| [
"def",
"parse_full_atom",
"(",
"data",
")",
":",
"if",
"(",
"len",
"(",
"data",
")",
"<",
"4",
")",
":",
"raise",
"ValueError",
"(",
"'not enough data'",
")",
"version",
"=",
"ord",
"(",
"data",
"[",
"0",
":",
"1",
"]",
")",
"flags",
"=",
"cdata",
".",
"uint_be",
"(",
"(",
"'\\x00'",
"+",
"data",
"[",
"1",
":",
"4",
"]",
")",
")",
"return",
"(",
"version",
",",
"flags",
",",
"data",
"[",
"4",
":",
"]",
")"
] | some atoms are versioned . | train | true |
25,363 | def _rewriter_middleware(request_rewriter_chain, response_rewriter_chain, application, environ, start_response):
response_dict = {'headers_sent': False}
write_body = cStringIO.StringIO()
def wrapped_start_response(status, response_headers, exc_info=None):
if (exc_info and response_dict['headers_sent']):
raise exc_info[0], exc_info[1], exc_info[2]
response_dict['status'] = status
response_dict['response_headers'] = response_headers
return write_body.write
for rewriter in request_rewriter_chain:
rewriter(environ)
response_body = iter(application(environ, wrapped_start_response))
first = write_body.getvalue()
while (not first):
try:
first = response_body.next()
except StopIteration:
break
response_dict['headers_sent'] = True
try:
status = response_dict['status']
response_headers = response_dict['response_headers']
except KeyError:
raise AssertionError('Application yielded before calling start_response.')
def reconstructed_body():
(yield first)
for string in response_body:
(yield string)
body = reconstructed_body()
state = RewriterState(environ, status, response_headers, body)
for rewriter in response_rewriter_chain:
rewriter(state)
start_response(state.status, state.headers.items())
return state.body
| [
"def",
"_rewriter_middleware",
"(",
"request_rewriter_chain",
",",
"response_rewriter_chain",
",",
"application",
",",
"environ",
",",
"start_response",
")",
":",
"response_dict",
"=",
"{",
"'headers_sent'",
":",
"False",
"}",
"write_body",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"def",
"wrapped_start_response",
"(",
"status",
",",
"response_headers",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"(",
"exc_info",
"and",
"response_dict",
"[",
"'headers_sent'",
"]",
")",
":",
"raise",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"1",
"]",
",",
"exc_info",
"[",
"2",
"]",
"response_dict",
"[",
"'status'",
"]",
"=",
"status",
"response_dict",
"[",
"'response_headers'",
"]",
"=",
"response_headers",
"return",
"write_body",
".",
"write",
"for",
"rewriter",
"in",
"request_rewriter_chain",
":",
"rewriter",
"(",
"environ",
")",
"response_body",
"=",
"iter",
"(",
"application",
"(",
"environ",
",",
"wrapped_start_response",
")",
")",
"first",
"=",
"write_body",
".",
"getvalue",
"(",
")",
"while",
"(",
"not",
"first",
")",
":",
"try",
":",
"first",
"=",
"response_body",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"break",
"response_dict",
"[",
"'headers_sent'",
"]",
"=",
"True",
"try",
":",
"status",
"=",
"response_dict",
"[",
"'status'",
"]",
"response_headers",
"=",
"response_dict",
"[",
"'response_headers'",
"]",
"except",
"KeyError",
":",
"raise",
"AssertionError",
"(",
"'Application yielded before calling start_response.'",
")",
"def",
"reconstructed_body",
"(",
")",
":",
"(",
"yield",
"first",
")",
"for",
"string",
"in",
"response_body",
":",
"(",
"yield",
"string",
")",
"body",
"=",
"reconstructed_body",
"(",
")",
"state",
"=",
"RewriterState",
"(",
"environ",
",",
"status",
",",
"response_headers",
",",
"body",
")",
"for",
"rewriter",
"in",
"response_rewriter_chain",
":",
"rewriter",
"(",
"state",
")",
"start_response",
"(",
"state",
".",
"status",
",",
"state",
".",
"headers",
".",
"items",
"(",
")",
")",
"return",
"state",
".",
"body"
] | wraps an application and applies a chain of rewriters to its response . | train | false |
25,364 | def process_or_group_name(name):
s = str(name).strip()
if ((' ' in s) or (':' in s) or ('/' in s)):
raise ValueError(('Invalid name: ' + repr(name)))
return s
| [
"def",
"process_or_group_name",
"(",
"name",
")",
":",
"s",
"=",
"str",
"(",
"name",
")",
".",
"strip",
"(",
")",
"if",
"(",
"(",
"' '",
"in",
"s",
")",
"or",
"(",
"':'",
"in",
"s",
")",
"or",
"(",
"'/'",
"in",
"s",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid name: '",
"+",
"repr",
"(",
"name",
")",
")",
")",
"return",
"s"
] | ensures that a process or group name is not created with characters that break the eventlistener protocol or web ui urls . | train | false |
25,365 | def leaky_relu(x=None, alpha=0.1, name='LeakyReLU'):
with tf.name_scope(name) as scope:
x = tf.maximum(x, (alpha * x))
return x
| [
"def",
"leaky_relu",
"(",
"x",
"=",
"None",
",",
"alpha",
"=",
"0.1",
",",
"name",
"=",
"'LeakyReLU'",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
"as",
"scope",
":",
"x",
"=",
"tf",
".",
"maximum",
"(",
"x",
",",
"(",
"alpha",
"*",
"x",
")",
")",
"return",
"x"
] | the leakyrelu . | train | false |
25,367 | def get_current_task():
return _task_stack.top
| [
"def",
"get_current_task",
"(",
")",
":",
"return",
"_task_stack",
".",
"top"
] | currently executing task . | train | false |
25,368 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialise module . | train | false |
25,369 | def _shell_wrap(command, shell_escape, shell=True, sudo_prefix=None):
if (shell and (not env.use_shell)):
shell = False
if (sudo_prefix is None):
sudo_prefix = ''
else:
sudo_prefix += ' '
if shell:
shell = (env.shell + ' ')
if shell_escape:
command = _shell_escape(command)
command = ('"%s"' % command)
else:
shell = ''
return ((sudo_prefix + shell) + command)
| [
"def",
"_shell_wrap",
"(",
"command",
",",
"shell_escape",
",",
"shell",
"=",
"True",
",",
"sudo_prefix",
"=",
"None",
")",
":",
"if",
"(",
"shell",
"and",
"(",
"not",
"env",
".",
"use_shell",
")",
")",
":",
"shell",
"=",
"False",
"if",
"(",
"sudo_prefix",
"is",
"None",
")",
":",
"sudo_prefix",
"=",
"''",
"else",
":",
"sudo_prefix",
"+=",
"' '",
"if",
"shell",
":",
"shell",
"=",
"(",
"env",
".",
"shell",
"+",
"' '",
")",
"if",
"shell_escape",
":",
"command",
"=",
"_shell_escape",
"(",
"command",
")",
"command",
"=",
"(",
"'\"%s\"'",
"%",
"command",
")",
"else",
":",
"shell",
"=",
"''",
"return",
"(",
"(",
"sudo_prefix",
"+",
"shell",
")",
"+",
"command",
")"
] | conditionally wrap given command in env . | train | false |
25,370 | @pytest.mark.django_db
def test_format_registry_template_extension(no_formats):
registry = FormatRegistry()
filetype = registry.register('foo', 'foo', template_extension='bar')
assert (str(filetype.template_extension) == 'bar')
_test_formats(registry, ['foo'])
filetype2 = registry.register('special_foo', 'foo', template_extension='bar')
assert (str(filetype.template_extension) == 'bar')
assert (str(filetype2.template_extension) == 'bar')
_test_formats(registry, ['foo', 'special_foo'])
| [
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_format_registry_template_extension",
"(",
"no_formats",
")",
":",
"registry",
"=",
"FormatRegistry",
"(",
")",
"filetype",
"=",
"registry",
".",
"register",
"(",
"'foo'",
",",
"'foo'",
",",
"template_extension",
"=",
"'bar'",
")",
"assert",
"(",
"str",
"(",
"filetype",
".",
"template_extension",
")",
"==",
"'bar'",
")",
"_test_formats",
"(",
"registry",
",",
"[",
"'foo'",
"]",
")",
"filetype2",
"=",
"registry",
".",
"register",
"(",
"'special_foo'",
",",
"'foo'",
",",
"template_extension",
"=",
"'bar'",
")",
"assert",
"(",
"str",
"(",
"filetype",
".",
"template_extension",
")",
"==",
"'bar'",
")",
"assert",
"(",
"str",
"(",
"filetype2",
".",
"template_extension",
")",
"==",
"'bar'",
")",
"_test_formats",
"(",
"registry",
",",
"[",
"'foo'",
",",
"'special_foo'",
"]",
")"
] | tests the creation of a file extension . | train | false |
25,372 | def volume_attached(context, volume_id, instance_id, mountpoint):
return IMPL.volume_attached(context, volume_id, instance_id, mountpoint)
| [
"def",
"volume_attached",
"(",
"context",
",",
"volume_id",
",",
"instance_id",
",",
"mountpoint",
")",
":",
"return",
"IMPL",
".",
"volume_attached",
"(",
"context",
",",
"volume_id",
",",
"instance_id",
",",
"mountpoint",
")"
] | this method updates a volume attachment entry . | train | false |
25,373 | def convex_hull_object(image, neighbors=8):
if (image.ndim > 2):
raise ValueError('Input must be a 2D image')
if ((neighbors != 4) and (neighbors != 8)):
raise ValueError('Neighbors must be either 4 or 8.')
labeled_im = label(image, neighbors, background=0)
convex_obj = np.zeros(image.shape, dtype=bool)
convex_img = np.zeros(image.shape, dtype=bool)
for i in range(1, (labeled_im.max() + 1)):
convex_obj = convex_hull_image((labeled_im == i))
convex_img = np.logical_or(convex_img, convex_obj)
return convex_img
| [
"def",
"convex_hull_object",
"(",
"image",
",",
"neighbors",
"=",
"8",
")",
":",
"if",
"(",
"image",
".",
"ndim",
">",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Input must be a 2D image'",
")",
"if",
"(",
"(",
"neighbors",
"!=",
"4",
")",
"and",
"(",
"neighbors",
"!=",
"8",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Neighbors must be either 4 or 8.'",
")",
"labeled_im",
"=",
"label",
"(",
"image",
",",
"neighbors",
",",
"background",
"=",
"0",
")",
"convex_obj",
"=",
"np",
".",
"zeros",
"(",
"image",
".",
"shape",
",",
"dtype",
"=",
"bool",
")",
"convex_img",
"=",
"np",
".",
"zeros",
"(",
"image",
".",
"shape",
",",
"dtype",
"=",
"bool",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"(",
"labeled_im",
".",
"max",
"(",
")",
"+",
"1",
")",
")",
":",
"convex_obj",
"=",
"convex_hull_image",
"(",
"(",
"labeled_im",
"==",
"i",
")",
")",
"convex_img",
"=",
"np",
".",
"logical_or",
"(",
"convex_img",
",",
"convex_obj",
")",
"return",
"convex_img"
] | compute the convex hull image of individual objects in a binary image . | train | false |
25,377 | @register.inclusion_tag(u'generic/includes/rating.html', takes_context=True)
def rating_for(context, obj):
context[u'rating_object'] = context[u'rating_obj'] = obj
context[u'rating_form'] = RatingForm(context[u'request'], obj)
ratings = context[u'request'].COOKIES.get(u'mezzanine-rating', u'')
rating_string = (u'%s.%s' % (obj._meta, obj.pk))
context[u'rated'] = (rating_string in ratings)
rating_name = obj.get_ratingfield_name()
for f in (u'average', u'count', u'sum'):
context[(u'rating_' + f)] = getattr(obj, (u'%s_%s' % (rating_name, f)))
return context
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"u'generic/includes/rating.html'",
",",
"takes_context",
"=",
"True",
")",
"def",
"rating_for",
"(",
"context",
",",
"obj",
")",
":",
"context",
"[",
"u'rating_object'",
"]",
"=",
"context",
"[",
"u'rating_obj'",
"]",
"=",
"obj",
"context",
"[",
"u'rating_form'",
"]",
"=",
"RatingForm",
"(",
"context",
"[",
"u'request'",
"]",
",",
"obj",
")",
"ratings",
"=",
"context",
"[",
"u'request'",
"]",
".",
"COOKIES",
".",
"get",
"(",
"u'mezzanine-rating'",
",",
"u''",
")",
"rating_string",
"=",
"(",
"u'%s.%s'",
"%",
"(",
"obj",
".",
"_meta",
",",
"obj",
".",
"pk",
")",
")",
"context",
"[",
"u'rated'",
"]",
"=",
"(",
"rating_string",
"in",
"ratings",
")",
"rating_name",
"=",
"obj",
".",
"get_ratingfield_name",
"(",
")",
"for",
"f",
"in",
"(",
"u'average'",
",",
"u'count'",
",",
"u'sum'",
")",
":",
"context",
"[",
"(",
"u'rating_'",
"+",
"f",
")",
"]",
"=",
"getattr",
"(",
"obj",
",",
"(",
"u'%s_%s'",
"%",
"(",
"rating_name",
",",
"f",
")",
")",
")",
"return",
"context"
] | provides a generic context variable name for the object that ratings are being rendered for . | train | false |
25,380 | def white_tophat(input, size=None, footprint=None, structure=None, output=None, mode='reflect', cval=0.0, origin=0):
tmp = grey_erosion(input, size, footprint, structure, None, mode, cval, origin)
if isinstance(output, numpy.ndarray):
grey_dilation(tmp, size, footprint, structure, output, mode, cval, origin)
return numpy.subtract(input, output, output)
else:
tmp = grey_dilation(tmp, size, footprint, structure, None, mode, cval, origin)
return (input - tmp)
| [
"def",
"white_tophat",
"(",
"input",
",",
"size",
"=",
"None",
",",
"footprint",
"=",
"None",
",",
"structure",
"=",
"None",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"'reflect'",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"0",
")",
":",
"tmp",
"=",
"grey_erosion",
"(",
"input",
",",
"size",
",",
"footprint",
",",
"structure",
",",
"None",
",",
"mode",
",",
"cval",
",",
"origin",
")",
"if",
"isinstance",
"(",
"output",
",",
"numpy",
".",
"ndarray",
")",
":",
"grey_dilation",
"(",
"tmp",
",",
"size",
",",
"footprint",
",",
"structure",
",",
"output",
",",
"mode",
",",
"cval",
",",
"origin",
")",
"return",
"numpy",
".",
"subtract",
"(",
"input",
",",
"output",
",",
"output",
")",
"else",
":",
"tmp",
"=",
"grey_dilation",
"(",
"tmp",
",",
"size",
",",
"footprint",
",",
"structure",
",",
"None",
",",
"mode",
",",
"cval",
",",
"origin",
")",
"return",
"(",
"input",
"-",
"tmp",
")"
] | return white top hat of an image . | train | false |
25,381 | def add_course_content_milestone(course_id, content_id, relationship, milestone):
if (not settings.FEATURES.get('MILESTONES_APP')):
return None
return milestones_api.add_course_content_milestone(course_id, content_id, relationship, milestone)
| [
"def",
"add_course_content_milestone",
"(",
"course_id",
",",
"content_id",
",",
"relationship",
",",
"milestone",
")",
":",
"if",
"(",
"not",
"settings",
".",
"FEATURES",
".",
"get",
"(",
"'MILESTONES_APP'",
")",
")",
":",
"return",
"None",
"return",
"milestones_api",
".",
"add_course_content_milestone",
"(",
"course_id",
",",
"content_id",
",",
"relationship",
",",
"milestone",
")"
] | client api operation adapter/wrapper . | train | false |
25,382 | def _transpose_named_matrix(mat):
(mat['nrow'], mat['ncol']) = (mat['ncol'], mat['nrow'])
(mat['row_names'], mat['col_names']) = (mat['col_names'], mat['row_names'])
mat['data'] = mat['data'].T
| [
"def",
"_transpose_named_matrix",
"(",
"mat",
")",
":",
"(",
"mat",
"[",
"'nrow'",
"]",
",",
"mat",
"[",
"'ncol'",
"]",
")",
"=",
"(",
"mat",
"[",
"'ncol'",
"]",
",",
"mat",
"[",
"'nrow'",
"]",
")",
"(",
"mat",
"[",
"'row_names'",
"]",
",",
"mat",
"[",
"'col_names'",
"]",
")",
"=",
"(",
"mat",
"[",
"'col_names'",
"]",
",",
"mat",
"[",
"'row_names'",
"]",
")",
"mat",
"[",
"'data'",
"]",
"=",
"mat",
"[",
"'data'",
"]",
".",
"T"
] | transpose mat inplace . | train | false |
25,383 | @utils.arg('name', metavar='<name>', help=_('Server group name.'))
@utils.arg('policy', metavar='<policy>', nargs='+', help=_('Policies for the server groups.'))
def do_server_group_create(cs, args):
kwargs = {'name': args.name, 'policies': args.policy}
server_group = cs.server_groups.create(**kwargs)
_print_server_group_details(cs, [server_group])
| [
"@",
"utils",
".",
"arg",
"(",
"'name'",
",",
"metavar",
"=",
"'<name>'",
",",
"help",
"=",
"_",
"(",
"'Server group name.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'policy'",
",",
"metavar",
"=",
"'<policy>'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"_",
"(",
"'Policies for the server groups.'",
")",
")",
"def",
"do_server_group_create",
"(",
"cs",
",",
"args",
")",
":",
"kwargs",
"=",
"{",
"'name'",
":",
"args",
".",
"name",
",",
"'policies'",
":",
"args",
".",
"policy",
"}",
"server_group",
"=",
"cs",
".",
"server_groups",
".",
"create",
"(",
"**",
"kwargs",
")",
"_print_server_group_details",
"(",
"cs",
",",
"[",
"server_group",
"]",
")"
] | create a new server group with the specified details . | train | false |
25,384 | @treeio_login_required
@handle_response_format
def event_add(request, date=None, hour=12, response_format='html'):
if request.POST:
if ('cancel' not in request.POST):
event = Event()
form = EventForm(request.user.profile, date, hour, request.POST, instance=event)
if form.is_valid():
event = form.save()
event.set_user_from_request(request)
return HttpResponseRedirect(reverse('events_event_view', args=[event.id]))
else:
return HttpResponseRedirect(reverse('events'))
else:
form = EventForm(request.user.profile, date, hour)
return render_to_response('events/event_add', {'form': form}, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"treeio_login_required",
"@",
"handle_response_format",
"def",
"event_add",
"(",
"request",
",",
"date",
"=",
"None",
",",
"hour",
"=",
"12",
",",
"response_format",
"=",
"'html'",
")",
":",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'cancel'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"event",
"=",
"Event",
"(",
")",
"form",
"=",
"EventForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"date",
",",
"hour",
",",
"request",
".",
"POST",
",",
"instance",
"=",
"event",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"event",
"=",
"form",
".",
"save",
"(",
")",
"event",
".",
"set_user_from_request",
"(",
"request",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'events_event_view'",
",",
"args",
"=",
"[",
"event",
".",
"id",
"]",
")",
")",
"else",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'events'",
")",
")",
"else",
":",
"form",
"=",
"EventForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"date",
",",
"hour",
")",
"return",
"render_to_response",
"(",
"'events/event_add'",
",",
"{",
"'form'",
":",
"form",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | event add form . | train | false |
25,385 | def einfo(**keywds):
cgi = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi'
variables = {}
variables.update(keywds)
return _open(cgi, variables)
| [
"def",
"einfo",
"(",
"**",
"keywds",
")",
":",
"cgi",
"=",
"'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi'",
"variables",
"=",
"{",
"}",
"variables",
".",
"update",
"(",
"keywds",
")",
"return",
"_open",
"(",
"cgi",
",",
"variables",
")"
] | einfo returns a summary of the entez databases as a results handle . | train | false |
25,386 | def contains_softmax(f):
raise NotImplementedError('TODO: implement this function.')
| [
"def",
"contains_softmax",
"(",
"f",
")",
":",
"raise",
"NotImplementedError",
"(",
"'TODO: implement this function.'",
")"
] | f: a theano function returns true if f contains a t . | train | false |
25,388 | def convert_FloatProperty(model, prop, kwargs):
return f.FloatField(**kwargs)
| [
"def",
"convert_FloatProperty",
"(",
"model",
",",
"prop",
",",
"kwargs",
")",
":",
"return",
"f",
".",
"FloatField",
"(",
"**",
"kwargs",
")"
] | returns a form field for a db . | train | false |
25,389 | def fetch_single_equity(api_key, symbol, start_date, end_date, retries=5):
for _ in range(retries):
try:
return pd.read_csv(format_wiki_url(api_key, symbol, start_date, end_date), parse_dates=['Date'], index_col='Date', usecols=['Open', 'High', 'Low', 'Close', 'Volume', 'Date', 'Ex-Dividend', 'Split Ratio'], na_values=['NA']).rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Volume': 'volume', 'Date': 'date', 'Ex-Dividend': 'ex_dividend', 'Split Ratio': 'split_ratio'})
except Exception:
log.exception('Exception raised reading Quandl data. Retrying.')
else:
raise ValueError(('Failed to download data for %r after %d attempts.' % (symbol, retries)))
| [
"def",
"fetch_single_equity",
"(",
"api_key",
",",
"symbol",
",",
"start_date",
",",
"end_date",
",",
"retries",
"=",
"5",
")",
":",
"for",
"_",
"in",
"range",
"(",
"retries",
")",
":",
"try",
":",
"return",
"pd",
".",
"read_csv",
"(",
"format_wiki_url",
"(",
"api_key",
",",
"symbol",
",",
"start_date",
",",
"end_date",
")",
",",
"parse_dates",
"=",
"[",
"'Date'",
"]",
",",
"index_col",
"=",
"'Date'",
",",
"usecols",
"=",
"[",
"'Open'",
",",
"'High'",
",",
"'Low'",
",",
"'Close'",
",",
"'Volume'",
",",
"'Date'",
",",
"'Ex-Dividend'",
",",
"'Split Ratio'",
"]",
",",
"na_values",
"=",
"[",
"'NA'",
"]",
")",
".",
"rename",
"(",
"columns",
"=",
"{",
"'Open'",
":",
"'open'",
",",
"'High'",
":",
"'high'",
",",
"'Low'",
":",
"'low'",
",",
"'Close'",
":",
"'close'",
",",
"'Volume'",
":",
"'volume'",
",",
"'Date'",
":",
"'date'",
",",
"'Ex-Dividend'",
":",
"'ex_dividend'",
",",
"'Split Ratio'",
":",
"'split_ratio'",
"}",
")",
"except",
"Exception",
":",
"log",
".",
"exception",
"(",
"'Exception raised reading Quandl data. Retrying.'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'Failed to download data for %r after %d attempts.'",
"%",
"(",
"symbol",
",",
"retries",
")",
")",
")"
] | download data for a single equity . | train | false |
25,390 | def guess_kern_ipc_maxsockbuf():
if (TRUENAS and ((hardware[0] == 'Z50') or (hardware[0] == 'Z35'))):
return (16 * MB)
elif (TRUENAS and (hardware[0] == 'Z30')):
return (8 * MB)
elif (TRUENAS and (hardware[0] == 'Z20')):
return (4 * MB)
elif (HW_PHYSMEM_GB > 180):
return (16 * MB)
elif (HW_PHYSMEM_GB > 84):
return (8 * MB)
elif (HW_PHYSMEM_GB > 44):
return (4 * MB)
else:
return (2 * MB)
| [
"def",
"guess_kern_ipc_maxsockbuf",
"(",
")",
":",
"if",
"(",
"TRUENAS",
"and",
"(",
"(",
"hardware",
"[",
"0",
"]",
"==",
"'Z50'",
")",
"or",
"(",
"hardware",
"[",
"0",
"]",
"==",
"'Z35'",
")",
")",
")",
":",
"return",
"(",
"16",
"*",
"MB",
")",
"elif",
"(",
"TRUENAS",
"and",
"(",
"hardware",
"[",
"0",
"]",
"==",
"'Z30'",
")",
")",
":",
"return",
"(",
"8",
"*",
"MB",
")",
"elif",
"(",
"TRUENAS",
"and",
"(",
"hardware",
"[",
"0",
"]",
"==",
"'Z20'",
")",
")",
":",
"return",
"(",
"4",
"*",
"MB",
")",
"elif",
"(",
"HW_PHYSMEM_GB",
">",
"180",
")",
":",
"return",
"(",
"16",
"*",
"MB",
")",
"elif",
"(",
"HW_PHYSMEM_GB",
">",
"84",
")",
":",
"return",
"(",
"8",
"*",
"MB",
")",
"elif",
"(",
"HW_PHYSMEM_GB",
">",
"44",
")",
":",
"return",
"(",
"4",
"*",
"MB",
")",
"else",
":",
"return",
"(",
"2",
"*",
"MB",
")"
] | maximum socket buffer . | train | false |
25,391 | def resolved(rpath):
return realpath(abspath(rpath))
| [
"def",
"resolved",
"(",
"rpath",
")",
":",
"return",
"realpath",
"(",
"abspath",
"(",
"rpath",
")",
")"
] | returns the canonical absolute path of rpath . | train | false |
25,392 | def cache_from_env(env):
return item_from_env(env, 'swift.cache')
| [
"def",
"cache_from_env",
"(",
"env",
")",
":",
"return",
"item_from_env",
"(",
"env",
",",
"'swift.cache'",
")"
] | get memcache connection pool from the environment (which had been previously set by the memcache middleware . | train | false |
25,393 | def Median(xs):
cdf = Cdf(xs)
return cdf.Value(0.5)
| [
"def",
"Median",
"(",
"xs",
")",
":",
"cdf",
"=",
"Cdf",
"(",
"xs",
")",
"return",
"cdf",
".",
"Value",
"(",
"0.5",
")"
] | computes the median of a sequence . | train | false |
25,396 | def get_all_subscriptions_by_topic(name, region=None, key=None, keyid=None, profile=None):
cache_key = _subscriptions_cache_key(name)
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.get_all_subscriptions_by_topic(get_arn(name, region, key, keyid, profile))
__context__[cache_key] = ret['ListSubscriptionsByTopicResponse']['ListSubscriptionsByTopicResult']['Subscriptions']
return __context__[cache_key]
| [
"def",
"get_all_subscriptions_by_topic",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"_subscriptions_cache_key",
"(",
"name",
")",
"try",
":",
"return",
"__context__",
"[",
"cache_key",
"]",
"except",
"KeyError",
":",
"pass",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"ret",
"=",
"conn",
".",
"get_all_subscriptions_by_topic",
"(",
"get_arn",
"(",
"name",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
")",
"__context__",
"[",
"cache_key",
"]",
"=",
"ret",
"[",
"'ListSubscriptionsByTopicResponse'",
"]",
"[",
"'ListSubscriptionsByTopicResult'",
"]",
"[",
"'Subscriptions'",
"]",
"return",
"__context__",
"[",
"cache_key",
"]"
] | get list of all subscriptions to a specific topic . | train | true |
25,397 | def hash_conda_packages(conda_packages, conda_target=None):
h = hashlib.new('sha256')
for conda_package in conda_packages:
h.update(conda_package.install_environment)
return h.hexdigest()
| [
"def",
"hash_conda_packages",
"(",
"conda_packages",
",",
"conda_target",
"=",
"None",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'sha256'",
")",
"for",
"conda_package",
"in",
"conda_packages",
":",
"h",
".",
"update",
"(",
"conda_package",
".",
"install_environment",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | produce a unique hash on supplied packages . | train | false |
25,398 | def test_gaussian_vis_layer_make_state():
n = 5
rows = None
cols = None
channels = None
num_samples = 1000
tol = 0.042
beta = (1 / tol)
layer = GaussianVisLayer(nvis=n, init_beta=beta)
rng = np.random.RandomState([2012, 11, 1])
mean = rng.uniform(1e-06, (1.0 - 1e-06), (n,))
z = mean
layer.set_biases(z.astype(config.floatX))
init_state = layer.make_state(num_examples=num_samples, numpy_rng=rng)
value = init_state.get_value()
check_gaussian_samples(value, num_samples, n, rows, cols, channels, mean, tol)
| [
"def",
"test_gaussian_vis_layer_make_state",
"(",
")",
":",
"n",
"=",
"5",
"rows",
"=",
"None",
"cols",
"=",
"None",
"channels",
"=",
"None",
"num_samples",
"=",
"1000",
"tol",
"=",
"0.042",
"beta",
"=",
"(",
"1",
"/",
"tol",
")",
"layer",
"=",
"GaussianVisLayer",
"(",
"nvis",
"=",
"n",
",",
"init_beta",
"=",
"beta",
")",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"[",
"2012",
",",
"11",
",",
"1",
"]",
")",
"mean",
"=",
"rng",
".",
"uniform",
"(",
"1e-06",
",",
"(",
"1.0",
"-",
"1e-06",
")",
",",
"(",
"n",
",",
")",
")",
"z",
"=",
"mean",
"layer",
".",
"set_biases",
"(",
"z",
".",
"astype",
"(",
"config",
".",
"floatX",
")",
")",
"init_state",
"=",
"layer",
".",
"make_state",
"(",
"num_examples",
"=",
"num_samples",
",",
"numpy_rng",
"=",
"rng",
")",
"value",
"=",
"init_state",
".",
"get_value",
"(",
")",
"check_gaussian_samples",
"(",
"value",
",",
"num_samples",
",",
"n",
",",
"rows",
",",
"cols",
",",
"channels",
",",
"mean",
",",
"tol",
")"
] | verifies that gaussianvislayer . | train | false |
25,399 | @task
def clean():
path('build').rmtree()
path('dist').rmtree()
| [
"@",
"task",
"def",
"clean",
"(",
")",
":",
"path",
"(",
"'build'",
")",
".",
"rmtree",
"(",
")",
"path",
"(",
"'dist'",
")",
".",
"rmtree",
"(",
")"
] | remove build . | train | false |
25,400 | def remove_trailing_data_field(fields):
try:
get_model_from_relation(fields[(-1)])
except NotRelationField:
fields = fields[:(-1)]
return fields
| [
"def",
"remove_trailing_data_field",
"(",
"fields",
")",
":",
"try",
":",
"get_model_from_relation",
"(",
"fields",
"[",
"(",
"-",
"1",
")",
"]",
")",
"except",
"NotRelationField",
":",
"fields",
"=",
"fields",
"[",
":",
"(",
"-",
"1",
")",
"]",
"return",
"fields"
] | discard trailing non-relation field if extant . | train | false |
25,401 | def _cast_inplace(terms, acceptable_dtypes, dtype):
dt = np.dtype(dtype)
for term in terms:
if (term.type in acceptable_dtypes):
continue
try:
new_value = term.value.astype(dt)
except AttributeError:
new_value = dt.type(term.value)
term.update(new_value)
| [
"def",
"_cast_inplace",
"(",
"terms",
",",
"acceptable_dtypes",
",",
"dtype",
")",
":",
"dt",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"for",
"term",
"in",
"terms",
":",
"if",
"(",
"term",
".",
"type",
"in",
"acceptable_dtypes",
")",
":",
"continue",
"try",
":",
"new_value",
"=",
"term",
".",
"value",
".",
"astype",
"(",
"dt",
")",
"except",
"AttributeError",
":",
"new_value",
"=",
"dt",
".",
"type",
"(",
"term",
".",
"value",
")",
"term",
".",
"update",
"(",
"new_value",
")"
] | cast an expression inplace . | train | true |
25,403 | def test_abstract():
app = BaseApplicationBackend()
for fun in (app._vispy_get_backend_name, app._vispy_process_events, app._vispy_run, app._vispy_quit):
assert_raises(NotImplementedError, fun)
| [
"def",
"test_abstract",
"(",
")",
":",
"app",
"=",
"BaseApplicationBackend",
"(",
")",
"for",
"fun",
"in",
"(",
"app",
".",
"_vispy_get_backend_name",
",",
"app",
".",
"_vispy_process_events",
",",
"app",
".",
"_vispy_run",
",",
"app",
".",
"_vispy_quit",
")",
":",
"assert_raises",
"(",
"NotImplementedError",
",",
"fun",
")"
] | test app abstract template . | train | false |
25,404 | def _format_error_helper(error):
result = ''
hadoop_error = error.get('hadoop_error')
if hadoop_error:
result += hadoop_error.get('message', '')
if hadoop_error.get('path'):
result += ('\n\n(from %s)' % _describe_source(hadoop_error))
task_error = error.get('task_error')
if task_error:
if hadoop_error:
result += ('\n\ncaused by:\n\n%s' % task_error.get('message', ''))
else:
result += task_error.get('message', '')
if task_error.get('path'):
result += ('\n\n(from %s)' % _describe_source(task_error))
split = error.get('split')
if (split and split.get('path')):
result += ('\n\nwhile reading input from %s' % _describe_source(split))
return result
| [
"def",
"_format_error_helper",
"(",
"error",
")",
":",
"result",
"=",
"''",
"hadoop_error",
"=",
"error",
".",
"get",
"(",
"'hadoop_error'",
")",
"if",
"hadoop_error",
":",
"result",
"+=",
"hadoop_error",
".",
"get",
"(",
"'message'",
",",
"''",
")",
"if",
"hadoop_error",
".",
"get",
"(",
"'path'",
")",
":",
"result",
"+=",
"(",
"'\\n\\n(from %s)'",
"%",
"_describe_source",
"(",
"hadoop_error",
")",
")",
"task_error",
"=",
"error",
".",
"get",
"(",
"'task_error'",
")",
"if",
"task_error",
":",
"if",
"hadoop_error",
":",
"result",
"+=",
"(",
"'\\n\\ncaused by:\\n\\n%s'",
"%",
"task_error",
".",
"get",
"(",
"'message'",
",",
"''",
")",
")",
"else",
":",
"result",
"+=",
"task_error",
".",
"get",
"(",
"'message'",
",",
"''",
")",
"if",
"task_error",
".",
"get",
"(",
"'path'",
")",
":",
"result",
"+=",
"(",
"'\\n\\n(from %s)'",
"%",
"_describe_source",
"(",
"task_error",
")",
")",
"split",
"=",
"error",
".",
"get",
"(",
"'split'",
")",
"if",
"(",
"split",
"and",
"split",
".",
"get",
"(",
"'path'",
")",
")",
":",
"result",
"+=",
"(",
"'\\n\\nwhile reading input from %s'",
"%",
"_describe_source",
"(",
"split",
")",
")",
"return",
"result"
] | return string to log/print explaining the given error . | train | false |
25,405 | def format_filesize(size):
for suffix in ('bytes', 'KB', 'MB', 'GB', 'TB'):
if (size < 1024.0):
if (suffix in ('GB', 'TB')):
return '{0:3.2f} {1}'.format(size, suffix)
else:
return '{0:3.1f} {1}'.format(size, suffix)
size /= 1024.0
| [
"def",
"format_filesize",
"(",
"size",
")",
":",
"for",
"suffix",
"in",
"(",
"'bytes'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
")",
":",
"if",
"(",
"size",
"<",
"1024.0",
")",
":",
"if",
"(",
"suffix",
"in",
"(",
"'GB'",
",",
"'TB'",
")",
")",
":",
"return",
"'{0:3.2f} {1}'",
".",
"format",
"(",
"size",
",",
"suffix",
")",
"else",
":",
"return",
"'{0:3.1f} {1}'",
".",
"format",
"(",
"size",
",",
"suffix",
")",
"size",
"/=",
"1024.0"
] | formats the file size into a human readable format . | train | true |
25,406 | def parse_soup_page(soup):
(titles, authors, links) = (list(), list(), list())
for div in soup.findAll('div'):
if ((div.name == 'div') and (div.get('class') == 'gs_ri')):
links.append(div.a['href'])
div_pub = div.findAll('div')
for d in div_pub:
if ((d.name == 'div') and (d.get('class') == 'gs_a')):
authors.append(d.text)
titles.append(div.a.text)
return (titles, authors, links)
| [
"def",
"parse_soup_page",
"(",
"soup",
")",
":",
"(",
"titles",
",",
"authors",
",",
"links",
")",
"=",
"(",
"list",
"(",
")",
",",
"list",
"(",
")",
",",
"list",
"(",
")",
")",
"for",
"div",
"in",
"soup",
".",
"findAll",
"(",
"'div'",
")",
":",
"if",
"(",
"(",
"div",
".",
"name",
"==",
"'div'",
")",
"and",
"(",
"div",
".",
"get",
"(",
"'class'",
")",
"==",
"'gs_ri'",
")",
")",
":",
"links",
".",
"append",
"(",
"div",
".",
"a",
"[",
"'href'",
"]",
")",
"div_pub",
"=",
"div",
".",
"findAll",
"(",
"'div'",
")",
"for",
"d",
"in",
"div_pub",
":",
"if",
"(",
"(",
"d",
".",
"name",
"==",
"'div'",
")",
"and",
"(",
"d",
".",
"get",
"(",
"'class'",
")",
"==",
"'gs_a'",
")",
")",
":",
"authors",
".",
"append",
"(",
"d",
".",
"text",
")",
"titles",
".",
"append",
"(",
"div",
".",
"a",
".",
"text",
")",
"return",
"(",
"titles",
",",
"authors",
",",
"links",
")"
] | parse the page using beautifulsoup . | train | false |
25,407 | @compute.register(Expr, object)
def compute_single_object(expr, o, **kwargs):
ts = set([x for x in expr._subterms() if isinstance(x, Symbol)])
if (len(ts) == 1):
return compute(expr, {first(ts): o}, **kwargs)
else:
raise ValueError(('Give compute dictionary input, got %s' % str(o)))
| [
"@",
"compute",
".",
"register",
"(",
"Expr",
",",
"object",
")",
"def",
"compute_single_object",
"(",
"expr",
",",
"o",
",",
"**",
"kwargs",
")",
":",
"ts",
"=",
"set",
"(",
"[",
"x",
"for",
"x",
"in",
"expr",
".",
"_subterms",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"Symbol",
")",
"]",
")",
"if",
"(",
"len",
"(",
"ts",
")",
"==",
"1",
")",
":",
"return",
"compute",
"(",
"expr",
",",
"{",
"first",
"(",
"ts",
")",
":",
"o",
"}",
",",
"**",
"kwargs",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'Give compute dictionary input, got %s'",
"%",
"str",
"(",
"o",
")",
")",
")"
] | compute against single input assumes that only one symbol exists in expression . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.