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 |
|---|---|---|---|---|---|
23,230 | def test_ee_fit_invalid_ratio():
ratio = (1.0 / 10000.0)
ee = EasyEnsemble(ratio=ratio, random_state=RND_SEED)
assert_raises(RuntimeError, ee.fit, X, Y)
| [
"def",
"test_ee_fit_invalid_ratio",
"(",
")",
":",
"ratio",
"=",
"(",
"1.0",
"/",
"10000.0",
")",
"ee",
"=",
"EasyEnsemble",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"RuntimeError",
",",
"ee",
".",
"fit",
",",
"X",
",",
"Y",
")"
] | test either if an error is raised when the balancing ratio to fit is smaller than the one of the data . | train | false |
23,231 | def create_connect_viewer(N, N1, imgs, count, W2):
pv = PatchViewer((N, count), imgs.shape[1:3], is_color=(imgs.shape[3] == 3))
for i in xrange(N):
w = W2[:, i]
wneg = w[(w < 0.0)]
wpos = w[(w > 0.0)]
w /= np.abs(w).max()
wa = np.abs(w)
to_sort = zip(wa, range(N1), w)
s = sorted(to_sort)
for j in xrange(count):
idx = s[((N1 - j) - 1)][1]
mag = s[((N1 - j) - 1)][2]
if (mag > 0):
act = (mag, 0)
else:
act = (0, (- mag))
pv.add_patch(imgs[idx, ...], rescale=True, activation=act)
return pv
| [
"def",
"create_connect_viewer",
"(",
"N",
",",
"N1",
",",
"imgs",
",",
"count",
",",
"W2",
")",
":",
"pv",
"=",
"PatchViewer",
"(",
"(",
"N",
",",
"count",
")",
",",
"imgs",
".",
"shape",
"[",
"1",
":",
"3",
"]",
",",
"is_color",
"=",
"(",
"imgs",
".",
"shape",
"[",
"3",
"]",
"==",
"3",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"N",
")",
":",
"w",
"=",
"W2",
"[",
":",
",",
"i",
"]",
"wneg",
"=",
"w",
"[",
"(",
"w",
"<",
"0.0",
")",
"]",
"wpos",
"=",
"w",
"[",
"(",
"w",
">",
"0.0",
")",
"]",
"w",
"/=",
"np",
".",
"abs",
"(",
"w",
")",
".",
"max",
"(",
")",
"wa",
"=",
"np",
".",
"abs",
"(",
"w",
")",
"to_sort",
"=",
"zip",
"(",
"wa",
",",
"range",
"(",
"N1",
")",
",",
"w",
")",
"s",
"=",
"sorted",
"(",
"to_sort",
")",
"for",
"j",
"in",
"xrange",
"(",
"count",
")",
":",
"idx",
"=",
"s",
"[",
"(",
"(",
"N1",
"-",
"j",
")",
"-",
"1",
")",
"]",
"[",
"1",
"]",
"mag",
"=",
"s",
"[",
"(",
"(",
"N1",
"-",
"j",
")",
"-",
"1",
")",
"]",
"[",
"2",
"]",
"if",
"(",
"mag",
">",
"0",
")",
":",
"act",
"=",
"(",
"mag",
",",
"0",
")",
"else",
":",
"act",
"=",
"(",
"0",
",",
"(",
"-",
"mag",
")",
")",
"pv",
".",
"add_patch",
"(",
"imgs",
"[",
"idx",
",",
"...",
"]",
",",
"rescale",
"=",
"True",
",",
"activation",
"=",
"act",
")",
"return",
"pv"
] | create the patch to show connections between layers . | train | false |
23,232 | def mpi_send_wait_key(a):
if isinstance(a.op, (MPIRecvWait, MPISendWait)):
return 1
if isinstance(a.op, (MPIRecv, MPISend)):
return (-1)
return 0
| [
"def",
"mpi_send_wait_key",
"(",
"a",
")",
":",
"if",
"isinstance",
"(",
"a",
".",
"op",
",",
"(",
"MPIRecvWait",
",",
"MPISendWait",
")",
")",
":",
"return",
"1",
"if",
"isinstance",
"(",
"a",
".",
"op",
",",
"(",
"MPIRecv",
",",
"MPISend",
")",
")",
":",
"return",
"(",
"-",
"1",
")",
"return",
"0"
] | wait as long as possible on waits . | train | false |
23,234 | def libvlc_media_retain(p_md):
f = (_Cfunctions.get('libvlc_media_retain', None) or _Cfunction('libvlc_media_retain', ((1,),), None, None, Media))
return f(p_md)
| [
"def",
"libvlc_media_retain",
"(",
"p_md",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_retain'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_retain'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
",",
"None",
",",
"None",
",",
"Media",
")",
")",
"return",
"f",
"(",
"p_md",
")"
] | retain a reference to a media descriptor object . | train | false |
23,235 | def encode_html(unicode_data, encoding=u'ascii'):
try:
return unicode_data.encode(encoding, u'xmlcharrefreplace')
except ValueError:
return _xmlcharref_encode(unicode_data, encoding)
| [
"def",
"encode_html",
"(",
"unicode_data",
",",
"encoding",
"=",
"u'ascii'",
")",
":",
"try",
":",
"return",
"unicode_data",
".",
"encode",
"(",
"encoding",
",",
"u'xmlcharrefreplace'",
")",
"except",
"ValueError",
":",
"return",
"_xmlcharref_encode",
"(",
"unicode_data",
",",
"encoding",
")"
] | encode unicode_data for use as xml or html . | train | false |
23,236 | def color_config(text):
theme = idleConf.CurrentTheme()
normal_colors = idleConf.GetHighlight(theme, 'normal')
cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
select_colors = idleConf.GetHighlight(theme, 'hilite')
text.config(foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'], inactiveselectbackground=select_colors['background'])
| [
"def",
"color_config",
"(",
"text",
")",
":",
"theme",
"=",
"idleConf",
".",
"CurrentTheme",
"(",
")",
"normal_colors",
"=",
"idleConf",
".",
"GetHighlight",
"(",
"theme",
",",
"'normal'",
")",
"cursor_color",
"=",
"idleConf",
".",
"GetHighlight",
"(",
"theme",
",",
"'cursor'",
",",
"fgBg",
"=",
"'fg'",
")",
"select_colors",
"=",
"idleConf",
".",
"GetHighlight",
"(",
"theme",
",",
"'hilite'",
")",
"text",
".",
"config",
"(",
"foreground",
"=",
"normal_colors",
"[",
"'foreground'",
"]",
",",
"background",
"=",
"normal_colors",
"[",
"'background'",
"]",
",",
"insertbackground",
"=",
"cursor_color",
",",
"selectforeground",
"=",
"select_colors",
"[",
"'foreground'",
"]",
",",
"selectbackground",
"=",
"select_colors",
"[",
"'background'",
"]",
",",
"inactiveselectbackground",
"=",
"select_colors",
"[",
"'background'",
"]",
")"
] | set color opitons of text widget . | train | false |
23,237 | def _rshift_nearest(x, shift):
(b, q) = ((1L << shift), (x >> shift))
return (q + (((2 * (x & (b - 1))) + (q & 1)) > b))
| [
"def",
"_rshift_nearest",
"(",
"x",
",",
"shift",
")",
":",
"(",
"b",
",",
"q",
")",
"=",
"(",
"(",
"1",
"L",
"<<",
"shift",
")",
",",
"(",
"x",
">>",
"shift",
")",
")",
"return",
"(",
"q",
"+",
"(",
"(",
"(",
"2",
"*",
"(",
"x",
"&",
"(",
"b",
"-",
"1",
")",
")",
")",
"+",
"(",
"q",
"&",
"1",
")",
")",
">",
"b",
")",
")"
] | given an integer x and a nonnegative integer shift . | train | false |
23,238 | def collection_backup(collection_name, location, backup_name=None, **kwargs):
if (not collection_exists(collection_name, **kwargs)):
raise ValueError("Collection doesn't exists")
if (backup_name is not None):
backup_name = '&name={0}'.format(backup_name)
else:
backup_name = ''
_query('{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json'.format(collection=collection_name, backup_name=backup_name, location=location), **kwargs)
| [
"def",
"collection_backup",
"(",
"collection_name",
",",
"location",
",",
"backup_name",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"collection_exists",
"(",
"collection_name",
",",
"**",
"kwargs",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Collection doesn't exists\"",
")",
"if",
"(",
"backup_name",
"is",
"not",
"None",
")",
":",
"backup_name",
"=",
"'&name={0}'",
".",
"format",
"(",
"backup_name",
")",
"else",
":",
"backup_name",
"=",
"''",
"_query",
"(",
"'{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json'",
".",
"format",
"(",
"collection",
"=",
"collection_name",
",",
"backup_name",
"=",
"backup_name",
",",
"location",
"=",
"location",
")",
",",
"**",
"kwargs",
")"
] | create a backup for a collection . | train | true |
23,239 | def activate_foreign_keys(sender, connection, **kwargs):
if (connection.vendor == 'sqlite'):
cursor = connection.cursor()
cursor.execute('PRAGMA foreign_keys = ON;')
| [
"def",
"activate_foreign_keys",
"(",
"sender",
",",
"connection",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"connection",
".",
"vendor",
"==",
"'sqlite'",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'PRAGMA foreign_keys = ON;'",
")"
] | enable integrity constraint with sqlite . | train | false |
23,240 | def notify_systemd():
try:
import systemd.daemon
except ImportError:
if (salt.utils.which('systemd-notify') and systemd_notify_call('--booted')):
return systemd_notify_call('--ready')
return False
if systemd.daemon.booted():
try:
return systemd.daemon.notify('READY=1')
except SystemError:
pass
| [
"def",
"notify_systemd",
"(",
")",
":",
"try",
":",
"import",
"systemd",
".",
"daemon",
"except",
"ImportError",
":",
"if",
"(",
"salt",
".",
"utils",
".",
"which",
"(",
"'systemd-notify'",
")",
"and",
"systemd_notify_call",
"(",
"'--booted'",
")",
")",
":",
"return",
"systemd_notify_call",
"(",
"'--ready'",
")",
"return",
"False",
"if",
"systemd",
".",
"daemon",
".",
"booted",
"(",
")",
":",
"try",
":",
"return",
"systemd",
".",
"daemon",
".",
"notify",
"(",
"'READY=1'",
")",
"except",
"SystemError",
":",
"pass"
] | notify systemd that this process has started . | train | false |
23,241 | def variant_str(variant):
if (variant is None):
return ''
return variant
| [
"def",
"variant_str",
"(",
"variant",
")",
":",
"if",
"(",
"variant",
"is",
"None",
")",
":",
"return",
"''",
"return",
"variant"
] | return a string representation of variant . | train | false |
23,243 | def declare_declarations_in_scope(declaration_string, env, private_type=True, *args, **kwargs):
CythonUtilityCode(declaration_string, *args, **kwargs).declare_in_scope(env)
| [
"def",
"declare_declarations_in_scope",
"(",
"declaration_string",
",",
"env",
",",
"private_type",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"CythonUtilityCode",
"(",
"declaration_string",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
".",
"declare_in_scope",
"(",
"env",
")"
] | declare some declarations given as cython code in declaration_string in scope env . | train | false |
23,244 | @task(name=u'openedx.core.djangoapps.bookmarks.tasks.update_xblock_cache')
def update_xblocks_cache(course_id):
if (not isinstance(course_id, basestring)):
raise ValueError('course_id must be a string. {} is not acceptable.'.format(type(course_id)))
course_key = CourseKey.from_string(course_id)
log.info(u'Starting XBlockCaches update for course_key: %s', course_id)
_update_xblocks_cache(course_key)
log.info(u'Ending XBlockCaches update for course_key: %s', course_id)
| [
"@",
"task",
"(",
"name",
"=",
"u'openedx.core.djangoapps.bookmarks.tasks.update_xblock_cache'",
")",
"def",
"update_xblocks_cache",
"(",
"course_id",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"course_id",
",",
"basestring",
")",
")",
":",
"raise",
"ValueError",
"(",
"'course_id must be a string. {} is not acceptable.'",
".",
"format",
"(",
"type",
"(",
"course_id",
")",
")",
")",
"course_key",
"=",
"CourseKey",
".",
"from_string",
"(",
"course_id",
")",
"log",
".",
"info",
"(",
"u'Starting XBlockCaches update for course_key: %s'",
",",
"course_id",
")",
"_update_xblocks_cache",
"(",
"course_key",
")",
"log",
".",
"info",
"(",
"u'Ending XBlockCaches update for course_key: %s'",
",",
"course_id",
")"
] | update the xblocks cache for a course . | train | false |
23,245 | def create_jsonschema_from_metaschema(metaschema, required_fields=False, is_reviewer=False):
json_schema = base_metaschema(metaschema)
required = []
for page in metaschema['pages']:
for question in page['questions']:
if (is_required(question) and required_fields):
required.append(question['qid'])
json_schema['properties'][question['qid']] = {'type': 'object', 'additionalProperties': False, 'properties': extract_question_values(question, required_fields, is_reviewer)}
if required_fields:
json_schema['properties'][question['qid']]['required'] = ['value']
if (required and required_fields):
json_schema['required'] = required
return json_schema
| [
"def",
"create_jsonschema_from_metaschema",
"(",
"metaschema",
",",
"required_fields",
"=",
"False",
",",
"is_reviewer",
"=",
"False",
")",
":",
"json_schema",
"=",
"base_metaschema",
"(",
"metaschema",
")",
"required",
"=",
"[",
"]",
"for",
"page",
"in",
"metaschema",
"[",
"'pages'",
"]",
":",
"for",
"question",
"in",
"page",
"[",
"'questions'",
"]",
":",
"if",
"(",
"is_required",
"(",
"question",
")",
"and",
"required_fields",
")",
":",
"required",
".",
"append",
"(",
"question",
"[",
"'qid'",
"]",
")",
"json_schema",
"[",
"'properties'",
"]",
"[",
"question",
"[",
"'qid'",
"]",
"]",
"=",
"{",
"'type'",
":",
"'object'",
",",
"'additionalProperties'",
":",
"False",
",",
"'properties'",
":",
"extract_question_values",
"(",
"question",
",",
"required_fields",
",",
"is_reviewer",
")",
"}",
"if",
"required_fields",
":",
"json_schema",
"[",
"'properties'",
"]",
"[",
"question",
"[",
"'qid'",
"]",
"]",
"[",
"'required'",
"]",
"=",
"[",
"'value'",
"]",
"if",
"(",
"required",
"and",
"required_fields",
")",
":",
"json_schema",
"[",
"'required'",
"]",
"=",
"required",
"return",
"json_schema"
] | creates jsonschema from registration metaschema for validation . | train | false |
23,247 | def cost_fig(cost_data, plot_height, plot_width, epoch_axis=True):
fig = figure(plot_height=plot_height, plot_width=plot_width, title='Cost', x_axis_label=x_label(epoch_axis), y_axis_label='Cross Entropy Error (%)')
num_colors_required = len(cost_data)
assert (num_colors_required <= 11), 'Insufficient colors in predefined palette.'
colors = list(brewer['Spectral'][max(3, len(cost_data))])
if (num_colors_required < 3):
colors[0] = brewer['Spectral'][6][0]
if (num_colors_required == 2):
colors[1] = brewer['Spectral'][6][(-1)]
for (name, x, y) in cost_data:
fig.line(x, y, legend=name, color=colors.pop(0), line_width=2)
return fig
| [
"def",
"cost_fig",
"(",
"cost_data",
",",
"plot_height",
",",
"plot_width",
",",
"epoch_axis",
"=",
"True",
")",
":",
"fig",
"=",
"figure",
"(",
"plot_height",
"=",
"plot_height",
",",
"plot_width",
"=",
"plot_width",
",",
"title",
"=",
"'Cost'",
",",
"x_axis_label",
"=",
"x_label",
"(",
"epoch_axis",
")",
",",
"y_axis_label",
"=",
"'Cross Entropy Error (%)'",
")",
"num_colors_required",
"=",
"len",
"(",
"cost_data",
")",
"assert",
"(",
"num_colors_required",
"<=",
"11",
")",
",",
"'Insufficient colors in predefined palette.'",
"colors",
"=",
"list",
"(",
"brewer",
"[",
"'Spectral'",
"]",
"[",
"max",
"(",
"3",
",",
"len",
"(",
"cost_data",
")",
")",
"]",
")",
"if",
"(",
"num_colors_required",
"<",
"3",
")",
":",
"colors",
"[",
"0",
"]",
"=",
"brewer",
"[",
"'Spectral'",
"]",
"[",
"6",
"]",
"[",
"0",
"]",
"if",
"(",
"num_colors_required",
"==",
"2",
")",
":",
"colors",
"[",
"1",
"]",
"=",
"brewer",
"[",
"'Spectral'",
"]",
"[",
"6",
"]",
"[",
"(",
"-",
"1",
")",
"]",
"for",
"(",
"name",
",",
"x",
",",
"y",
")",
"in",
"cost_data",
":",
"fig",
".",
"line",
"(",
"x",
",",
"y",
",",
"legend",
"=",
"name",
",",
"color",
"=",
"colors",
".",
"pop",
"(",
"0",
")",
",",
"line_width",
"=",
"2",
")",
"return",
"fig"
] | generate a figure with lines for each element in cost_data . | train | false |
23,249 | def top_hottt(start=0, results=15, buckets=None, limit=False):
buckets = (buckets or [])
kwargs = {}
if start:
kwargs['start'] = start
if results:
kwargs['results'] = results
if buckets:
kwargs['bucket'] = buckets
if limit:
kwargs['limit'] = 'true'
'Get top hottt artists'
result = util.callm(('%s/%s' % ('artist', 'top_hottt')), kwargs)
return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]
| [
"def",
"top_hottt",
"(",
"start",
"=",
"0",
",",
"results",
"=",
"15",
",",
"buckets",
"=",
"None",
",",
"limit",
"=",
"False",
")",
":",
"buckets",
"=",
"(",
"buckets",
"or",
"[",
"]",
")",
"kwargs",
"=",
"{",
"}",
"if",
"start",
":",
"kwargs",
"[",
"'start'",
"]",
"=",
"start",
"if",
"results",
":",
"kwargs",
"[",
"'results'",
"]",
"=",
"results",
"if",
"buckets",
":",
"kwargs",
"[",
"'bucket'",
"]",
"=",
"buckets",
"if",
"limit",
":",
"kwargs",
"[",
"'limit'",
"]",
"=",
"'true'",
"'Get top hottt artists'",
"result",
"=",
"util",
".",
"callm",
"(",
"(",
"'%s/%s'",
"%",
"(",
"'artist'",
",",
"'top_hottt'",
")",
")",
",",
"kwargs",
")",
"return",
"[",
"Artist",
"(",
"**",
"util",
".",
"fix",
"(",
"a_dict",
")",
")",
"for",
"a_dict",
"in",
"result",
"[",
"'response'",
"]",
"[",
"'artists'",
"]",
"]"
] | get the top hotttest artists . | train | true |
23,251 | def valid_publish_topic(value):
return valid_subscribe_topic(value, invalid_chars='#+\x00')
| [
"def",
"valid_publish_topic",
"(",
"value",
")",
":",
"return",
"valid_subscribe_topic",
"(",
"value",
",",
"invalid_chars",
"=",
"'#+\\x00'",
")"
] | validate that we can publish using this mqtt topic . | train | false |
23,252 | def document_form_initial(document):
return {'title': document.title, 'slug': document.slug, 'is_localizable': document.is_localizable, 'tags': list(document.tags.names())}
| [
"def",
"document_form_initial",
"(",
"document",
")",
":",
"return",
"{",
"'title'",
":",
"document",
".",
"title",
",",
"'slug'",
":",
"document",
".",
"slug",
",",
"'is_localizable'",
":",
"document",
".",
"is_localizable",
",",
"'tags'",
":",
"list",
"(",
"document",
".",
"tags",
".",
"names",
"(",
")",
")",
"}"
] | return a dict with the document data pertinent for the form . | train | false |
23,253 | def get_text(xmlns, rich_node):
text_node = rich_node.find(QName(xmlns, 't').text)
partial_text = (text_node.text or '')
if (text_node.get(QName(NAMESPACES['xml'], 'space').text) != 'preserve'):
partial_text = partial_text.strip()
return str(partial_text)
| [
"def",
"get_text",
"(",
"xmlns",
",",
"rich_node",
")",
":",
"text_node",
"=",
"rich_node",
".",
"find",
"(",
"QName",
"(",
"xmlns",
",",
"'t'",
")",
".",
"text",
")",
"partial_text",
"=",
"(",
"text_node",
".",
"text",
"or",
"''",
")",
"if",
"(",
"text_node",
".",
"get",
"(",
"QName",
"(",
"NAMESPACES",
"[",
"'xml'",
"]",
",",
"'space'",
")",
".",
"text",
")",
"!=",
"'preserve'",
")",
":",
"partial_text",
"=",
"partial_text",
".",
"strip",
"(",
")",
"return",
"str",
"(",
"partial_text",
")"
] | read rich text . | train | false |
23,254 | def isportopen(host, port):
if (not (1 <= int(port) <= 65535)):
return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
out = sock.connect_ex((sanitize_host(host), int(port)))
return out
| [
"def",
"isportopen",
"(",
"host",
",",
"port",
")",
":",
"if",
"(",
"not",
"(",
"1",
"<=",
"int",
"(",
"port",
")",
"<=",
"65535",
")",
")",
":",
"return",
"False",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"out",
"=",
"sock",
".",
"connect_ex",
"(",
"(",
"sanitize_host",
"(",
"host",
")",
",",
"int",
"(",
"port",
")",
")",
")",
"return",
"out"
] | return status of a port . | train | true |
23,255 | def convert_back(raw_im, image_mean=None, idx=0):
raw_im = np.copy(raw_im)
if (image_mean is not None):
raw_im += image_mean[idx, :, 8:120, 29:141].squeeze()
raw_im = raw_im[::(-1), :, :]
im = np.array(np.swapaxes(np.swapaxes(raw_im, 1, 0), 2, 1), np.uint8)
return im
| [
"def",
"convert_back",
"(",
"raw_im",
",",
"image_mean",
"=",
"None",
",",
"idx",
"=",
"0",
")",
":",
"raw_im",
"=",
"np",
".",
"copy",
"(",
"raw_im",
")",
"if",
"(",
"image_mean",
"is",
"not",
"None",
")",
":",
"raw_im",
"+=",
"image_mean",
"[",
"idx",
",",
":",
",",
"8",
":",
"120",
",",
"29",
":",
"141",
"]",
".",
"squeeze",
"(",
")",
"raw_im",
"=",
"raw_im",
"[",
":",
":",
"(",
"-",
"1",
")",
",",
":",
",",
":",
"]",
"im",
"=",
"np",
".",
"array",
"(",
"np",
".",
"swapaxes",
"(",
"np",
".",
"swapaxes",
"(",
"raw_im",
",",
"1",
",",
"0",
")",
",",
"2",
",",
"1",
")",
",",
"np",
".",
"uint8",
")",
"return",
"im"
] | converts a caffe format image back to the standard format . | train | false |
23,256 | def local_uri_to_file_uri(uri, media_dir):
return path_to_file_uri(local_uri_to_path(uri, media_dir))
| [
"def",
"local_uri_to_file_uri",
"(",
"uri",
",",
"media_dir",
")",
":",
"return",
"path_to_file_uri",
"(",
"local_uri_to_path",
"(",
"uri",
",",
"media_dir",
")",
")"
] | convert local track or directory uri to file uri . | train | false |
23,257 | def es_search_cmd(query, pages=1, log=log):
from kitsune.sumo.tests import LocalizingClient
from kitsune.sumo.urlresolvers import reverse
client = LocalizingClient()
output = []
output.append(('Search for: %s' % query))
output.append('')
data = {'q': query, 'format': 'json'}
url = reverse('search')
for pageno in range(pages):
pageno = (pageno + 1)
data['page'] = pageno
resp = client.get(url, data)
if (resp.status_code != 200):
output.append(('ERROR: %s' % resp.content))
break
else:
content = json.loads(resp.content)
results = content[u'results']
for mem in results:
output.append((u'%4d %5.2f %-10s %-20s' % (mem['rank'], mem['score'], mem['type'], mem['title'])))
output.append('')
for line in output:
log.info(line.encode('ascii', 'ignore'))
| [
"def",
"es_search_cmd",
"(",
"query",
",",
"pages",
"=",
"1",
",",
"log",
"=",
"log",
")",
":",
"from",
"kitsune",
".",
"sumo",
".",
"tests",
"import",
"LocalizingClient",
"from",
"kitsune",
".",
"sumo",
".",
"urlresolvers",
"import",
"reverse",
"client",
"=",
"LocalizingClient",
"(",
")",
"output",
"=",
"[",
"]",
"output",
".",
"append",
"(",
"(",
"'Search for: %s'",
"%",
"query",
")",
")",
"output",
".",
"append",
"(",
"''",
")",
"data",
"=",
"{",
"'q'",
":",
"query",
",",
"'format'",
":",
"'json'",
"}",
"url",
"=",
"reverse",
"(",
"'search'",
")",
"for",
"pageno",
"in",
"range",
"(",
"pages",
")",
":",
"pageno",
"=",
"(",
"pageno",
"+",
"1",
")",
"data",
"[",
"'page'",
"]",
"=",
"pageno",
"resp",
"=",
"client",
".",
"get",
"(",
"url",
",",
"data",
")",
"if",
"(",
"resp",
".",
"status_code",
"!=",
"200",
")",
":",
"output",
".",
"append",
"(",
"(",
"'ERROR: %s'",
"%",
"resp",
".",
"content",
")",
")",
"break",
"else",
":",
"content",
"=",
"json",
".",
"loads",
"(",
"resp",
".",
"content",
")",
"results",
"=",
"content",
"[",
"u'results'",
"]",
"for",
"mem",
"in",
"results",
":",
"output",
".",
"append",
"(",
"(",
"u'%4d %5.2f %-10s %-20s'",
"%",
"(",
"mem",
"[",
"'rank'",
"]",
",",
"mem",
"[",
"'score'",
"]",
",",
"mem",
"[",
"'type'",
"]",
",",
"mem",
"[",
"'title'",
"]",
")",
")",
")",
"output",
".",
"append",
"(",
"''",
")",
"for",
"line",
"in",
"output",
":",
"log",
".",
"info",
"(",
"line",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
")"
] | simulates a front page search . | train | false |
23,259 | def get_repository_ids_requiring_prior_import_or_install(app, tsr_ids, repository_dependencies):
prior_tsr_ids = []
if repository_dependencies:
for (key, rd_tups) in repository_dependencies.items():
if (key in ['description', 'root_key']):
continue
for rd_tup in rd_tups:
(tool_shed, name, owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td) = common_util.parse_repository_dependency_tuple(rd_tup)
if (not util.asbool(only_if_compiling_contained_td)):
if util.asbool(prior_installation_required):
if is_tool_shed_client(app):
tool_shed = common_util.remove_protocol_from_tool_shed_url(tool_shed)
repository = get_repository_for_dependency_relationship(app, tool_shed, name, owner, changeset_revision)
else:
repository = get_repository_by_name_and_owner(app, name, owner)
if repository:
encoded_repository_id = app.security.encode_id(repository.id)
if (encoded_repository_id in tsr_ids):
prior_tsr_ids.append(encoded_repository_id)
return prior_tsr_ids
| [
"def",
"get_repository_ids_requiring_prior_import_or_install",
"(",
"app",
",",
"tsr_ids",
",",
"repository_dependencies",
")",
":",
"prior_tsr_ids",
"=",
"[",
"]",
"if",
"repository_dependencies",
":",
"for",
"(",
"key",
",",
"rd_tups",
")",
"in",
"repository_dependencies",
".",
"items",
"(",
")",
":",
"if",
"(",
"key",
"in",
"[",
"'description'",
",",
"'root_key'",
"]",
")",
":",
"continue",
"for",
"rd_tup",
"in",
"rd_tups",
":",
"(",
"tool_shed",
",",
"name",
",",
"owner",
",",
"changeset_revision",
",",
"prior_installation_required",
",",
"only_if_compiling_contained_td",
")",
"=",
"common_util",
".",
"parse_repository_dependency_tuple",
"(",
"rd_tup",
")",
"if",
"(",
"not",
"util",
".",
"asbool",
"(",
"only_if_compiling_contained_td",
")",
")",
":",
"if",
"util",
".",
"asbool",
"(",
"prior_installation_required",
")",
":",
"if",
"is_tool_shed_client",
"(",
"app",
")",
":",
"tool_shed",
"=",
"common_util",
".",
"remove_protocol_from_tool_shed_url",
"(",
"tool_shed",
")",
"repository",
"=",
"get_repository_for_dependency_relationship",
"(",
"app",
",",
"tool_shed",
",",
"name",
",",
"owner",
",",
"changeset_revision",
")",
"else",
":",
"repository",
"=",
"get_repository_by_name_and_owner",
"(",
"app",
",",
"name",
",",
"owner",
")",
"if",
"repository",
":",
"encoded_repository_id",
"=",
"app",
".",
"security",
".",
"encode_id",
"(",
"repository",
".",
"id",
")",
"if",
"(",
"encoded_repository_id",
"in",
"tsr_ids",
")",
":",
"prior_tsr_ids",
".",
"append",
"(",
"encoded_repository_id",
")",
"return",
"prior_tsr_ids"
] | this method is used in the tool shed when exporting a repository and its dependencies . | train | false |
23,260 | def get_hooks(hook=None, default=None, app_name=None):
def load_app_hooks(app_name=None):
hooks = {}
for app in ([app_name] if app_name else get_installed_apps(sort=True)):
app = (u'frappe' if (app == u'webnotes') else app)
try:
app_hooks = get_module((app + u'.hooks'))
except ImportError:
if local.flags.in_install_app:
pass
print u'Could not find app "{0}"'.format(app_name)
if (not request):
sys.exit(1)
raise
for key in dir(app_hooks):
if (not key.startswith(u'_')):
append_hook(hooks, key, getattr(app_hooks, key))
return hooks
if app_name:
hooks = _dict(load_app_hooks(app_name))
else:
hooks = _dict(cache().get_value(u'app_hooks', load_app_hooks))
if hook:
return (hooks.get(hook) or (default if (default is not None) else []))
else:
return hooks
| [
"def",
"get_hooks",
"(",
"hook",
"=",
"None",
",",
"default",
"=",
"None",
",",
"app_name",
"=",
"None",
")",
":",
"def",
"load_app_hooks",
"(",
"app_name",
"=",
"None",
")",
":",
"hooks",
"=",
"{",
"}",
"for",
"app",
"in",
"(",
"[",
"app_name",
"]",
"if",
"app_name",
"else",
"get_installed_apps",
"(",
"sort",
"=",
"True",
")",
")",
":",
"app",
"=",
"(",
"u'frappe'",
"if",
"(",
"app",
"==",
"u'webnotes'",
")",
"else",
"app",
")",
"try",
":",
"app_hooks",
"=",
"get_module",
"(",
"(",
"app",
"+",
"u'.hooks'",
")",
")",
"except",
"ImportError",
":",
"if",
"local",
".",
"flags",
".",
"in_install_app",
":",
"pass",
"print",
"u'Could not find app \"{0}\"'",
".",
"format",
"(",
"app_name",
")",
"if",
"(",
"not",
"request",
")",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"raise",
"for",
"key",
"in",
"dir",
"(",
"app_hooks",
")",
":",
"if",
"(",
"not",
"key",
".",
"startswith",
"(",
"u'_'",
")",
")",
":",
"append_hook",
"(",
"hooks",
",",
"key",
",",
"getattr",
"(",
"app_hooks",
",",
"key",
")",
")",
"return",
"hooks",
"if",
"app_name",
":",
"hooks",
"=",
"_dict",
"(",
"load_app_hooks",
"(",
"app_name",
")",
")",
"else",
":",
"hooks",
"=",
"_dict",
"(",
"cache",
"(",
")",
".",
"get_value",
"(",
"u'app_hooks'",
",",
"load_app_hooks",
")",
")",
"if",
"hook",
":",
"return",
"(",
"hooks",
".",
"get",
"(",
"hook",
")",
"or",
"(",
"default",
"if",
"(",
"default",
"is",
"not",
"None",
")",
"else",
"[",
"]",
")",
")",
"else",
":",
"return",
"hooks"
] | returns the dict for the spec hookspath and runtime_hooks values . | train | false |
23,262 | def get_role_by_id(app, role_id):
sa_session = app.model.context.current
return sa_session.query(app.model.Role).get(app.security.decode_id(role_id))
| [
"def",
"get_role_by_id",
"(",
"app",
",",
"role_id",
")",
":",
"sa_session",
"=",
"app",
".",
"model",
".",
"context",
".",
"current",
"return",
"sa_session",
".",
"query",
"(",
"app",
".",
"model",
".",
"Role",
")",
".",
"get",
"(",
"app",
".",
"security",
".",
"decode_id",
"(",
"role_id",
")",
")"
] | get a role from the database by id . | train | false |
23,263 | def difftool_launch_with_head(filenames, staged, head):
if (head == u'HEAD'):
left = None
else:
left = head
difftool_launch(left=left, staged=staged, paths=filenames)
| [
"def",
"difftool_launch_with_head",
"(",
"filenames",
",",
"staged",
",",
"head",
")",
":",
"if",
"(",
"head",
"==",
"u'HEAD'",
")",
":",
"left",
"=",
"None",
"else",
":",
"left",
"=",
"head",
"difftool_launch",
"(",
"left",
"=",
"left",
",",
"staged",
"=",
"staged",
",",
"paths",
"=",
"filenames",
")"
] | launch difftool against the provided head . | train | false |
23,264 | def _endpoint_from_image_ref(image_href):
parts = image_href.split('/')
image_id = parts[(-1)]
endpoint = '/'.join(parts[:(-3)])
return (image_id, endpoint)
| [
"def",
"_endpoint_from_image_ref",
"(",
"image_href",
")",
":",
"parts",
"=",
"image_href",
".",
"split",
"(",
"'/'",
")",
"image_id",
"=",
"parts",
"[",
"(",
"-",
"1",
")",
"]",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"parts",
"[",
":",
"(",
"-",
"3",
")",
"]",
")",
"return",
"(",
"image_id",
",",
"endpoint",
")"
] | return the image_ref and guessed endpoint from an image url . | train | false |
23,265 | def _git_str():
if (BASEDIR is None):
return None
if (not os.path.isdir(os.path.join(BASEDIR, '.git'))):
return None
try:
cid = subprocess.check_output(['git', 'describe', '--tags', '--dirty', '--always'], cwd=BASEDIR).decode('UTF-8').strip()
date = subprocess.check_output(['git', 'show', '-s', '--format=%ci', 'HEAD'], cwd=BASEDIR).decode('UTF-8').strip()
return '{} ({})'.format(cid, date)
except (subprocess.CalledProcessError, OSError):
return None
| [
"def",
"_git_str",
"(",
")",
":",
"if",
"(",
"BASEDIR",
"is",
"None",
")",
":",
"return",
"None",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"BASEDIR",
",",
"'.git'",
")",
")",
")",
":",
"return",
"None",
"try",
":",
"cid",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
",",
"'--tags'",
",",
"'--dirty'",
",",
"'--always'",
"]",
",",
"cwd",
"=",
"BASEDIR",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"strip",
"(",
")",
"date",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'show'",
",",
"'-s'",
",",
"'--format=%ci'",
",",
"'HEAD'",
"]",
",",
"cwd",
"=",
"BASEDIR",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"strip",
"(",
")",
"return",
"'{} ({})'",
".",
"format",
"(",
"cid",
",",
"date",
")",
"except",
"(",
"subprocess",
".",
"CalledProcessError",
",",
"OSError",
")",
":",
"return",
"None"
] | try to find out git version . | train | false |
23,266 | def ConvertVCMacrosToMSBuild(s):
if ('$' in s):
replace_map = {'$(ConfigurationName)': '$(Configuration)', '$(InputDir)': '%(RelativeDir)', '$(InputExt)': '%(Extension)', '$(InputFileName)': '%(Filename)%(Extension)', '$(InputName)': '%(Filename)', '$(InputPath)': '%(Identity)', '$(ParentName)': '$(ProjectFileName)', '$(PlatformName)': '$(Platform)', '$(SafeInputName)': '%(Filename)'}
for (old, new) in replace_map.iteritems():
s = s.replace(old, new)
s = FixVCMacroSlashes(s)
return s
| [
"def",
"ConvertVCMacrosToMSBuild",
"(",
"s",
")",
":",
"if",
"(",
"'$'",
"in",
"s",
")",
":",
"replace_map",
"=",
"{",
"'$(ConfigurationName)'",
":",
"'$(Configuration)'",
",",
"'$(InputDir)'",
":",
"'%(RelativeDir)'",
",",
"'$(InputExt)'",
":",
"'%(Extension)'",
",",
"'$(InputFileName)'",
":",
"'%(Filename)%(Extension)'",
",",
"'$(InputName)'",
":",
"'%(Filename)'",
",",
"'$(InputPath)'",
":",
"'%(Identity)'",
",",
"'$(ParentName)'",
":",
"'$(ProjectFileName)'",
",",
"'$(PlatformName)'",
":",
"'$(Platform)'",
",",
"'$(SafeInputName)'",
":",
"'%(Filename)'",
"}",
"for",
"(",
"old",
",",
"new",
")",
"in",
"replace_map",
".",
"iteritems",
"(",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"old",
",",
"new",
")",
"s",
"=",
"FixVCMacroSlashes",
"(",
"s",
")",
"return",
"s"
] | convert the the msvs macros found in the string to the msbuild equivalent . | train | false |
23,267 | @step((STEP_PREFIX + 'I clear my email outbox'))
def mail_clear(step):
mail.EmailMessage.send = GOOD_MAIL
mail.outbox = []
| [
"@",
"step",
"(",
"(",
"STEP_PREFIX",
"+",
"'I clear my email outbox'",
")",
")",
"def",
"mail_clear",
"(",
"step",
")",
":",
"mail",
".",
"EmailMessage",
".",
"send",
"=",
"GOOD_MAIL",
"mail",
".",
"outbox",
"=",
"[",
"]"
] | i clear my email outbox . | train | false |
23,268 | def write_alembic_ini(alembic_ini='alembic.ini', db_url='sqlite:///jupyterhub.sqlite'):
with open(ALEMBIC_INI_TEMPLATE_PATH) as f:
alembic_ini_tpl = f.read()
with open(alembic_ini, 'w') as f:
f.write(alembic_ini_tpl.format(alembic_dir=ALEMBIC_DIR, db_url=db_url))
| [
"def",
"write_alembic_ini",
"(",
"alembic_ini",
"=",
"'alembic.ini'",
",",
"db_url",
"=",
"'sqlite:///jupyterhub.sqlite'",
")",
":",
"with",
"open",
"(",
"ALEMBIC_INI_TEMPLATE_PATH",
")",
"as",
"f",
":",
"alembic_ini_tpl",
"=",
"f",
".",
"read",
"(",
")",
"with",
"open",
"(",
"alembic_ini",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"alembic_ini_tpl",
".",
"format",
"(",
"alembic_dir",
"=",
"ALEMBIC_DIR",
",",
"db_url",
"=",
"db_url",
")",
")"
] | write a complete alembic . | train | false |
23,269 | def list_installed_patterns():
return _get_patterns(installed_only=True)
| [
"def",
"list_installed_patterns",
"(",
")",
":",
"return",
"_get_patterns",
"(",
"installed_only",
"=",
"True",
")"
] | list installed patterns on the system . | train | false |
23,270 | def get_config_defaults():
return dict(FILE_CONTENT[CONFIG_FILE])
| [
"def",
"get_config_defaults",
"(",
")",
":",
"return",
"dict",
"(",
"FILE_CONTENT",
"[",
"CONFIG_FILE",
"]",
")"
] | convenience function to check current settings against defaults . | train | false |
23,271 | def pil_to_array(pilImage):
def toarray(im):
'return a 1D array of floats'
x_str = im.tostring('raw', im.mode, 0, (-1))
x = np.fromstring(x_str, np.uint8)
return x
if (pilImage.mode in ('RGBA', 'RGBX')):
im = pilImage
elif (pilImage.mode == 'L'):
im = pilImage
x = toarray(im)
x.shape = (im.size[1], im.size[0])
return x
elif (pilImage.mode == 'RGB'):
im = pilImage
x = toarray(im)
x.shape = (im.size[1], im.size[0], 3)
return x
else:
try:
im = pilImage.convert('RGBA')
except ValueError:
raise RuntimeError('Unknown image mode')
x = toarray(im)
x.shape = (im.size[1], im.size[0], 4)
return x
| [
"def",
"pil_to_array",
"(",
"pilImage",
")",
":",
"def",
"toarray",
"(",
"im",
")",
":",
"x_str",
"=",
"im",
".",
"tostring",
"(",
"'raw'",
",",
"im",
".",
"mode",
",",
"0",
",",
"(",
"-",
"1",
")",
")",
"x",
"=",
"np",
".",
"fromstring",
"(",
"x_str",
",",
"np",
".",
"uint8",
")",
"return",
"x",
"if",
"(",
"pilImage",
".",
"mode",
"in",
"(",
"'RGBA'",
",",
"'RGBX'",
")",
")",
":",
"im",
"=",
"pilImage",
"elif",
"(",
"pilImage",
".",
"mode",
"==",
"'L'",
")",
":",
"im",
"=",
"pilImage",
"x",
"=",
"toarray",
"(",
"im",
")",
"x",
".",
"shape",
"=",
"(",
"im",
".",
"size",
"[",
"1",
"]",
",",
"im",
".",
"size",
"[",
"0",
"]",
")",
"return",
"x",
"elif",
"(",
"pilImage",
".",
"mode",
"==",
"'RGB'",
")",
":",
"im",
"=",
"pilImage",
"x",
"=",
"toarray",
"(",
"im",
")",
"x",
".",
"shape",
"=",
"(",
"im",
".",
"size",
"[",
"1",
"]",
",",
"im",
".",
"size",
"[",
"0",
"]",
",",
"3",
")",
"return",
"x",
"else",
":",
"try",
":",
"im",
"=",
"pilImage",
".",
"convert",
"(",
"'RGBA'",
")",
"except",
"ValueError",
":",
"raise",
"RuntimeError",
"(",
"'Unknown image mode'",
")",
"x",
"=",
"toarray",
"(",
"im",
")",
"x",
".",
"shape",
"=",
"(",
"im",
".",
"size",
"[",
"1",
"]",
",",
"im",
".",
"size",
"[",
"0",
"]",
",",
"4",
")",
"return",
"x"
] | load a pil image and return it as a numpy array of uint8 . | train | false |
23,273 | def df_obs(x, *args):
(sslm, word_counts, totals, mean_deriv_mtx, word, deriv) = args
sslm.obs[word] = x
(sslm.mean[word], sslm.fwd_mean[word]) = sslm.compute_post_mean(word, sslm.chain_variance)
model = 'DTM'
if (model == 'DTM'):
deriv = sslm.compute_obs_deriv(word, word_counts, totals, mean_deriv_mtx, deriv)
elif (model == 'DIM'):
deriv = sslm.compute_obs_deriv_fixed(p.word, p.word_counts, p.totals, p.sslm, p.mean_deriv_mtx, deriv)
return np.negative(deriv)
| [
"def",
"df_obs",
"(",
"x",
",",
"*",
"args",
")",
":",
"(",
"sslm",
",",
"word_counts",
",",
"totals",
",",
"mean_deriv_mtx",
",",
"word",
",",
"deriv",
")",
"=",
"args",
"sslm",
".",
"obs",
"[",
"word",
"]",
"=",
"x",
"(",
"sslm",
".",
"mean",
"[",
"word",
"]",
",",
"sslm",
".",
"fwd_mean",
"[",
"word",
"]",
")",
"=",
"sslm",
".",
"compute_post_mean",
"(",
"word",
",",
"sslm",
".",
"chain_variance",
")",
"model",
"=",
"'DTM'",
"if",
"(",
"model",
"==",
"'DTM'",
")",
":",
"deriv",
"=",
"sslm",
".",
"compute_obs_deriv",
"(",
"word",
",",
"word_counts",
",",
"totals",
",",
"mean_deriv_mtx",
",",
"deriv",
")",
"elif",
"(",
"model",
"==",
"'DIM'",
")",
":",
"deriv",
"=",
"sslm",
".",
"compute_obs_deriv_fixed",
"(",
"p",
".",
"word",
",",
"p",
".",
"word_counts",
",",
"p",
".",
"totals",
",",
"p",
".",
"sslm",
",",
"p",
".",
"mean_deriv_mtx",
",",
"deriv",
")",
"return",
"np",
".",
"negative",
"(",
"deriv",
")"
] | derivative of function which optimises obs . | train | false |
23,275 | def test_takes_arguments():
assert (hug.introspect.takes_arguments(function_with_kwargs, 'argument1', 'argument3') == set(('argument1',)))
assert (hug.introspect.takes_arguments(function_with_args, 'bacon') == set())
assert (hug.introspect.takes_arguments(function_with_neither, 'argument1', 'argument2') == set(('argument1', 'argument2')))
assert (hug.introspect.takes_arguments(function_with_both, 'argument3', 'bacon') == set(('argument3',)))
| [
"def",
"test_takes_arguments",
"(",
")",
":",
"assert",
"(",
"hug",
".",
"introspect",
".",
"takes_arguments",
"(",
"function_with_kwargs",
",",
"'argument1'",
",",
"'argument3'",
")",
"==",
"set",
"(",
"(",
"'argument1'",
",",
")",
")",
")",
"assert",
"(",
"hug",
".",
"introspect",
".",
"takes_arguments",
"(",
"function_with_args",
",",
"'bacon'",
")",
"==",
"set",
"(",
")",
")",
"assert",
"(",
"hug",
".",
"introspect",
".",
"takes_arguments",
"(",
"function_with_neither",
",",
"'argument1'",
",",
"'argument2'",
")",
"==",
"set",
"(",
"(",
"'argument1'",
",",
"'argument2'",
")",
")",
")",
"assert",
"(",
"hug",
".",
"introspect",
".",
"takes_arguments",
"(",
"function_with_both",
",",
"'argument3'",
",",
"'bacon'",
")",
"==",
"set",
"(",
"(",
"'argument3'",
",",
")",
")",
")"
] | test to ensure hug introspection can correctly identify which arguments supplied a function will take . | train | false |
23,276 | def set_pixels(pixels):
_sensehat.set_pixels(pixels)
return {'pixels': pixels}
| [
"def",
"set_pixels",
"(",
"pixels",
")",
":",
"_sensehat",
".",
"set_pixels",
"(",
"pixels",
")",
"return",
"{",
"'pixels'",
":",
"pixels",
"}"
] | sets the entire led matrix based on a list of 64 pixel values pixels a list of 64 color values [r . | train | false |
23,277 | def datetimeToString(msSinceEpoch=None):
if (msSinceEpoch == None):
msSinceEpoch = time.time()
(year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(msSinceEpoch)
s = networkString(('%s, %02d %3s %4d %02d:%02d:%02d GMT' % (weekdayname[wd], day, monthname[month], year, hh, mm, ss)))
return s
| [
"def",
"datetimeToString",
"(",
"msSinceEpoch",
"=",
"None",
")",
":",
"if",
"(",
"msSinceEpoch",
"==",
"None",
")",
":",
"msSinceEpoch",
"=",
"time",
".",
"time",
"(",
")",
"(",
"year",
",",
"month",
",",
"day",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"wd",
",",
"y",
",",
"z",
")",
"=",
"time",
".",
"gmtime",
"(",
"msSinceEpoch",
")",
"s",
"=",
"networkString",
"(",
"(",
"'%s, %02d %3s %4d %02d:%02d:%02d GMT'",
"%",
"(",
"weekdayname",
"[",
"wd",
"]",
",",
"day",
",",
"monthname",
"[",
"month",
"]",
",",
"year",
",",
"hh",
",",
"mm",
",",
"ss",
")",
")",
")",
"return",
"s"
] | convert seconds since epoch to http datetime string . | train | false |
23,278 | def solve_poly_inequalities(polys):
from sympy import Union
return Union(*[solve_poly_inequality(*p) for p in polys])
| [
"def",
"solve_poly_inequalities",
"(",
"polys",
")",
":",
"from",
"sympy",
"import",
"Union",
"return",
"Union",
"(",
"*",
"[",
"solve_poly_inequality",
"(",
"*",
"p",
")",
"for",
"p",
"in",
"polys",
"]",
")"
] | solve polynomial inequalities with rational coefficients . | train | false |
23,279 | def distrib_id():
with settings(hide('running', 'stdout')):
kernel = run('uname -s')
if (kernel == 'Linux'):
if is_file('/usr/bin/lsb_release'):
id_ = run('lsb_release --id --short')
if (id in ['arch', 'Archlinux']):
id_ = 'Arch'
return id_
if (id in ['SUSE LINUX', 'openSUSE project']):
id_ = 'SUSE'
elif is_file('/etc/debian_version'):
return 'Debian'
elif is_file('/etc/fedora-release'):
return 'Fedora'
elif is_file('/etc/arch-release'):
return 'Arch'
elif is_file('/etc/redhat-release'):
release = run('cat /etc/redhat-release')
if release.startswith('Red Hat Enterprise Linux'):
return 'RHEL'
elif release.startswith('CentOS'):
return 'CentOS'
elif release.startswith('Scientific Linux'):
return 'SLES'
elif is_file('/etc/gentoo-release'):
return 'Gentoo'
elif (kernel == 'SunOS'):
return 'SunOS'
| [
"def",
"distrib_id",
"(",
")",
":",
"with",
"settings",
"(",
"hide",
"(",
"'running'",
",",
"'stdout'",
")",
")",
":",
"kernel",
"=",
"run",
"(",
"'uname -s'",
")",
"if",
"(",
"kernel",
"==",
"'Linux'",
")",
":",
"if",
"is_file",
"(",
"'/usr/bin/lsb_release'",
")",
":",
"id_",
"=",
"run",
"(",
"'lsb_release --id --short'",
")",
"if",
"(",
"id",
"in",
"[",
"'arch'",
",",
"'Archlinux'",
"]",
")",
":",
"id_",
"=",
"'Arch'",
"return",
"id_",
"if",
"(",
"id",
"in",
"[",
"'SUSE LINUX'",
",",
"'openSUSE project'",
"]",
")",
":",
"id_",
"=",
"'SUSE'",
"elif",
"is_file",
"(",
"'/etc/debian_version'",
")",
":",
"return",
"'Debian'",
"elif",
"is_file",
"(",
"'/etc/fedora-release'",
")",
":",
"return",
"'Fedora'",
"elif",
"is_file",
"(",
"'/etc/arch-release'",
")",
":",
"return",
"'Arch'",
"elif",
"is_file",
"(",
"'/etc/redhat-release'",
")",
":",
"release",
"=",
"run",
"(",
"'cat /etc/redhat-release'",
")",
"if",
"release",
".",
"startswith",
"(",
"'Red Hat Enterprise Linux'",
")",
":",
"return",
"'RHEL'",
"elif",
"release",
".",
"startswith",
"(",
"'CentOS'",
")",
":",
"return",
"'CentOS'",
"elif",
"release",
".",
"startswith",
"(",
"'Scientific Linux'",
")",
":",
"return",
"'SLES'",
"elif",
"is_file",
"(",
"'/etc/gentoo-release'",
")",
":",
"return",
"'Gentoo'",
"elif",
"(",
"kernel",
"==",
"'SunOS'",
")",
":",
"return",
"'SunOS'"
] | get the os distribution id . | train | false |
23,280 | def create_socket_pair(module, port=0):
have_socketpair = hasattr(module, 'socketpair')
if have_socketpair:
(client_sock, srv_sock) = module.socketpair()
return (client_sock, srv_sock)
temp_srv_sock = module.socket()
temp_srv_sock.setblocking(False)
temp_srv_sock.bind(('', port))
port = temp_srv_sock.getsockname()[1]
temp_srv_sock.listen(1)
client_sock = module.socket()
client_sock.setblocking(False)
try:
client_sock.connect(('localhost', port))
except module.error as err:
if (err.errno != errno.EWOULDBLOCK):
raise
timeout = 1
readable = select.select([temp_srv_sock], [], [], timeout)[0]
if (temp_srv_sock not in readable):
raise Exception(('Client socket not connected in %s second(s)' % timeout))
(srv_sock, _) = temp_srv_sock.accept()
return (client_sock, srv_sock)
| [
"def",
"create_socket_pair",
"(",
"module",
",",
"port",
"=",
"0",
")",
":",
"have_socketpair",
"=",
"hasattr",
"(",
"module",
",",
"'socketpair'",
")",
"if",
"have_socketpair",
":",
"(",
"client_sock",
",",
"srv_sock",
")",
"=",
"module",
".",
"socketpair",
"(",
")",
"return",
"(",
"client_sock",
",",
"srv_sock",
")",
"temp_srv_sock",
"=",
"module",
".",
"socket",
"(",
")",
"temp_srv_sock",
".",
"setblocking",
"(",
"False",
")",
"temp_srv_sock",
".",
"bind",
"(",
"(",
"''",
",",
"port",
")",
")",
"port",
"=",
"temp_srv_sock",
".",
"getsockname",
"(",
")",
"[",
"1",
"]",
"temp_srv_sock",
".",
"listen",
"(",
"1",
")",
"client_sock",
"=",
"module",
".",
"socket",
"(",
")",
"client_sock",
".",
"setblocking",
"(",
"False",
")",
"try",
":",
"client_sock",
".",
"connect",
"(",
"(",
"'localhost'",
",",
"port",
")",
")",
"except",
"module",
".",
"error",
"as",
"err",
":",
"if",
"(",
"err",
".",
"errno",
"!=",
"errno",
".",
"EWOULDBLOCK",
")",
":",
"raise",
"timeout",
"=",
"1",
"readable",
"=",
"select",
".",
"select",
"(",
"[",
"temp_srv_sock",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"[",
"0",
"]",
"if",
"(",
"temp_srv_sock",
"not",
"in",
"readable",
")",
":",
"raise",
"Exception",
"(",
"(",
"'Client socket not connected in %s second(s)'",
"%",
"timeout",
")",
")",
"(",
"srv_sock",
",",
"_",
")",
"=",
"temp_srv_sock",
".",
"accept",
"(",
")",
"return",
"(",
"client_sock",
",",
"srv_sock",
")"
] | create socket pair . | train | false |
23,282 | def load_setup_wizard_panes(shop, request=None, visible_only=True):
panes = []
for pane_spec in getattr(settings, 'SHUUP_SETUP_WIZARD_PANE_SPEC', []):
pane_class = load(pane_spec)
pane_inst = pane_class(request=request, object=shop)
if (pane_inst.valid() and ((not visible_only) or pane_inst.visible())):
panes.append(pane_inst)
return panes
| [
"def",
"load_setup_wizard_panes",
"(",
"shop",
",",
"request",
"=",
"None",
",",
"visible_only",
"=",
"True",
")",
":",
"panes",
"=",
"[",
"]",
"for",
"pane_spec",
"in",
"getattr",
"(",
"settings",
",",
"'SHUUP_SETUP_WIZARD_PANE_SPEC'",
",",
"[",
"]",
")",
":",
"pane_class",
"=",
"load",
"(",
"pane_spec",
")",
"pane_inst",
"=",
"pane_class",
"(",
"request",
"=",
"request",
",",
"object",
"=",
"shop",
")",
"if",
"(",
"pane_inst",
".",
"valid",
"(",
")",
"and",
"(",
"(",
"not",
"visible_only",
")",
"or",
"pane_inst",
".",
"visible",
"(",
")",
")",
")",
":",
"panes",
".",
"append",
"(",
"pane_inst",
")",
"return",
"panes"
] | load the setup wizard panes . | train | false |
23,283 | @app.route('/scans/<int:scan_id>/exceptions/<int:exception_id>', methods=['GET'])
@requires_auth
def get_exception_details(scan_id, exception_id):
scan_info = get_scan_info_from_id(scan_id)
if (scan_info is None):
abort(404, 'Scan not found')
all_exceptions = scan_info.w3af_core.exception_handler.get_all_exceptions()
for (i_exception_id, exception_data) in enumerate(all_exceptions):
if (exception_id == i_exception_id):
return jsonify(exception_to_json(exception_data, scan_id, exception_id, detailed=True))
abort(404, 'Not found')
| [
"@",
"app",
".",
"route",
"(",
"'/scans/<int:scan_id>/exceptions/<int:exception_id>'",
",",
"methods",
"=",
"[",
"'GET'",
"]",
")",
"@",
"requires_auth",
"def",
"get_exception_details",
"(",
"scan_id",
",",
"exception_id",
")",
":",
"scan_info",
"=",
"get_scan_info_from_id",
"(",
"scan_id",
")",
"if",
"(",
"scan_info",
"is",
"None",
")",
":",
"abort",
"(",
"404",
",",
"'Scan not found'",
")",
"all_exceptions",
"=",
"scan_info",
".",
"w3af_core",
".",
"exception_handler",
".",
"get_all_exceptions",
"(",
")",
"for",
"(",
"i_exception_id",
",",
"exception_data",
")",
"in",
"enumerate",
"(",
"all_exceptions",
")",
":",
"if",
"(",
"exception_id",
"==",
"i_exception_id",
")",
":",
"return",
"jsonify",
"(",
"exception_to_json",
"(",
"exception_data",
",",
"scan_id",
",",
"exception_id",
",",
"detailed",
"=",
"True",
")",
")",
"abort",
"(",
"404",
",",
"'Not found'",
")"
] | the whole information related to the specified exception id . | train | false |
23,284 | @pytest.mark.skipif('not HAS_YAML')
def test_bad_delimiter():
out = StringIO()
with pytest.raises(ValueError) as err:
T_DTYPES.write(out, format='ascii.ecsv', delimiter='|')
assert ('only space and comma are allowed' in str(err.value))
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"'not HAS_YAML'",
")",
"def",
"test_bad_delimiter",
"(",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
"as",
"err",
":",
"T_DTYPES",
".",
"write",
"(",
"out",
",",
"format",
"=",
"'ascii.ecsv'",
",",
"delimiter",
"=",
"'|'",
")",
"assert",
"(",
"'only space and comma are allowed'",
"in",
"str",
"(",
"err",
".",
"value",
")",
")"
] | passing a delimiter other than space or comma gives an exception . | train | false |
23,285 | def p_command_dim_bad(p):
p[0] = 'MALFORMED VARIABLE LIST IN DIM'
| [
"def",
"p_command_dim_bad",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"'MALFORMED VARIABLE LIST IN DIM'"
] | command : dim error . | train | false |
23,287 | def _serial_sanitizer(instr):
length = len(instr)
index = int(math.floor((length * 0.75)))
return '{0}{1}'.format(instr[:index], ('X' * (length - index)))
| [
"def",
"_serial_sanitizer",
"(",
"instr",
")",
":",
"length",
"=",
"len",
"(",
"instr",
")",
"index",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"(",
"length",
"*",
"0.75",
")",
")",
")",
"return",
"'{0}{1}'",
".",
"format",
"(",
"instr",
"[",
":",
"index",
"]",
",",
"(",
"'X'",
"*",
"(",
"length",
"-",
"index",
")",
")",
")"
] | replaces the last 1/4 of a string with xs . | train | true |
23,288 | def _cache_for_link(cache_dir, link):
key_parts = [link.url_without_fragment]
if ((link.hash_name is not None) and (link.hash is not None)):
key_parts.append('='.join([link.hash_name, link.hash]))
key_url = '#'.join(key_parts)
hashed = hashlib.sha224(key_url.encode()).hexdigest()
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return os.path.join(cache_dir, 'wheels', *parts)
| [
"def",
"_cache_for_link",
"(",
"cache_dir",
",",
"link",
")",
":",
"key_parts",
"=",
"[",
"link",
".",
"url_without_fragment",
"]",
"if",
"(",
"(",
"link",
".",
"hash_name",
"is",
"not",
"None",
")",
"and",
"(",
"link",
".",
"hash",
"is",
"not",
"None",
")",
")",
":",
"key_parts",
".",
"append",
"(",
"'='",
".",
"join",
"(",
"[",
"link",
".",
"hash_name",
",",
"link",
".",
"hash",
"]",
")",
")",
"key_url",
"=",
"'#'",
".",
"join",
"(",
"key_parts",
")",
"hashed",
"=",
"hashlib",
".",
"sha224",
"(",
"key_url",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"parts",
"=",
"[",
"hashed",
"[",
":",
"2",
"]",
",",
"hashed",
"[",
"2",
":",
"4",
"]",
",",
"hashed",
"[",
"4",
":",
"6",
"]",
",",
"hashed",
"[",
"6",
":",
"]",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"'wheels'",
",",
"*",
"parts",
")"
] | return a directory to store cached wheels in for link . | train | true |
23,292 | def jinja2_getattr(self, obj, attribute):
try:
value = getattr(obj, attribute)
if isinstance(value, property):
value = value.fget()
return value
except AttributeError:
pass
try:
value = obj[attribute]
if isinstance(value, property):
value = value.fget()
return value
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute)
| [
"def",
"jinja2_getattr",
"(",
"self",
",",
"obj",
",",
"attribute",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"attribute",
")",
"if",
"isinstance",
"(",
"value",
",",
"property",
")",
":",
"value",
"=",
"value",
".",
"fget",
"(",
")",
"return",
"value",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"value",
"=",
"obj",
"[",
"attribute",
"]",
"if",
"isinstance",
"(",
"value",
",",
"property",
")",
":",
"value",
"=",
"value",
".",
"fget",
"(",
")",
"return",
"value",
"except",
"(",
"TypeError",
",",
"LookupError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"undefined",
"(",
"obj",
"=",
"obj",
",",
"name",
"=",
"attribute",
")"
] | get an item or attribute of an object but prefer the attribute . | train | false |
23,294 | def _get_windows_network_adapters():
import win32com.client
wbem_locator = win32com.client.Dispatch('WbemScripting.SWbemLocator')
wbem_service = wbem_locator.ConnectServer('.', 'root\\cimv2')
wbem_network_adapters = wbem_service.InstancesOf('Win32_NetworkAdapter')
network_adapters = []
for adapter in wbem_network_adapters:
if ((adapter.NetConnectionStatus == 2) or (adapter.NetConnectionStatus == 7)):
adapter_name = adapter.NetConnectionID
mac_address = adapter.MacAddress.lower()
config = adapter.associators_('Win32_NetworkAdapterSetting', 'Win32_NetworkAdapterConfiguration')[0]
ip_address = ''
subnet_mask = ''
if config.IPEnabled:
ip_address = config.IPAddress[0]
subnet_mask = config.IPSubnet[0]
network_adapters.append({'name': adapter_name, 'mac-address': mac_address, 'ip-address': ip_address, 'subnet-mask': subnet_mask})
return network_adapters
| [
"def",
"_get_windows_network_adapters",
"(",
")",
":",
"import",
"win32com",
".",
"client",
"wbem_locator",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'WbemScripting.SWbemLocator'",
")",
"wbem_service",
"=",
"wbem_locator",
".",
"ConnectServer",
"(",
"'.'",
",",
"'root\\\\cimv2'",
")",
"wbem_network_adapters",
"=",
"wbem_service",
".",
"InstancesOf",
"(",
"'Win32_NetworkAdapter'",
")",
"network_adapters",
"=",
"[",
"]",
"for",
"adapter",
"in",
"wbem_network_adapters",
":",
"if",
"(",
"(",
"adapter",
".",
"NetConnectionStatus",
"==",
"2",
")",
"or",
"(",
"adapter",
".",
"NetConnectionStatus",
"==",
"7",
")",
")",
":",
"adapter_name",
"=",
"adapter",
".",
"NetConnectionID",
"mac_address",
"=",
"adapter",
".",
"MacAddress",
".",
"lower",
"(",
")",
"config",
"=",
"adapter",
".",
"associators_",
"(",
"'Win32_NetworkAdapterSetting'",
",",
"'Win32_NetworkAdapterConfiguration'",
")",
"[",
"0",
"]",
"ip_address",
"=",
"''",
"subnet_mask",
"=",
"''",
"if",
"config",
".",
"IPEnabled",
":",
"ip_address",
"=",
"config",
".",
"IPAddress",
"[",
"0",
"]",
"subnet_mask",
"=",
"config",
".",
"IPSubnet",
"[",
"0",
"]",
"network_adapters",
".",
"append",
"(",
"{",
"'name'",
":",
"adapter_name",
",",
"'mac-address'",
":",
"mac_address",
",",
"'ip-address'",
":",
"ip_address",
",",
"'subnet-mask'",
":",
"subnet_mask",
"}",
")",
"return",
"network_adapters"
] | get the list of windows network adapters . | train | false |
23,295 | def signed_to_unsigned(signed):
(unsigned,) = struct.unpack('L', struct.pack('l', signed))
return unsigned
| [
"def",
"signed_to_unsigned",
"(",
"signed",
")",
":",
"(",
"unsigned",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"'L'",
",",
"struct",
".",
"pack",
"(",
"'l'",
",",
"signed",
")",
")",
"return",
"unsigned"
] | convert a long to unsigned hex . | train | false |
23,296 | def load_params(path, params):
pp = numpy.load(path)
for (kk, vv) in params.iteritems():
if (kk not in pp):
warnings.warn(('%s is not in the archive' % kk))
continue
params[kk] = pp[kk]
return params
| [
"def",
"load_params",
"(",
"path",
",",
"params",
")",
":",
"pp",
"=",
"numpy",
".",
"load",
"(",
"path",
")",
"for",
"(",
"kk",
",",
"vv",
")",
"in",
"params",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"kk",
"not",
"in",
"pp",
")",
":",
"warnings",
".",
"warn",
"(",
"(",
"'%s is not in the archive'",
"%",
"kk",
")",
")",
"continue",
"params",
"[",
"kk",
"]",
"=",
"pp",
"[",
"kk",
"]",
"return",
"params"
] | load parameters . | train | false |
23,297 | def emr_initialize(cli):
cli.register('building-command-table.emr', register_commands)
cli.register('building-argument-table.emr.add-tags', modify_tags_argument)
cli.register('building-argument-table.emr.list-clusters', modify_list_clusters_argument)
cli.register('before-building-argument-table-parser.emr.*', override_args_required_option)
| [
"def",
"emr_initialize",
"(",
"cli",
")",
":",
"cli",
".",
"register",
"(",
"'building-command-table.emr'",
",",
"register_commands",
")",
"cli",
".",
"register",
"(",
"'building-argument-table.emr.add-tags'",
",",
"modify_tags_argument",
")",
"cli",
".",
"register",
"(",
"'building-argument-table.emr.list-clusters'",
",",
"modify_list_clusters_argument",
")",
"cli",
".",
"register",
"(",
"'before-building-argument-table-parser.emr.*'",
",",
"override_args_required_option",
")"
] | the entry point for emr high level commands . | train | false |
23,298 | def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull):
from pandas.hashtable import unique_label_indices
if (not xnull):
lift = np.fromiter(((a == (-1)).any() for a in labels), dtype='i8')
shape = (np.asarray(shape, dtype='i8') + lift)
if (not _int64_overflow_possible(shape)):
out = decons_group_index(obs_ids, shape)
return (out if (xnull or (not lift.any())) else [(x - y) for (x, y) in zip(out, lift)])
i = unique_label_indices(comp_ids)
i8copy = (lambda a: a.astype('i8', subok=False, copy=True))
return [i8copy(lab[i]) for lab in labels]
| [
"def",
"decons_obs_group_ids",
"(",
"comp_ids",
",",
"obs_ids",
",",
"shape",
",",
"labels",
",",
"xnull",
")",
":",
"from",
"pandas",
".",
"hashtable",
"import",
"unique_label_indices",
"if",
"(",
"not",
"xnull",
")",
":",
"lift",
"=",
"np",
".",
"fromiter",
"(",
"(",
"(",
"a",
"==",
"(",
"-",
"1",
")",
")",
".",
"any",
"(",
")",
"for",
"a",
"in",
"labels",
")",
",",
"dtype",
"=",
"'i8'",
")",
"shape",
"=",
"(",
"np",
".",
"asarray",
"(",
"shape",
",",
"dtype",
"=",
"'i8'",
")",
"+",
"lift",
")",
"if",
"(",
"not",
"_int64_overflow_possible",
"(",
"shape",
")",
")",
":",
"out",
"=",
"decons_group_index",
"(",
"obs_ids",
",",
"shape",
")",
"return",
"(",
"out",
"if",
"(",
"xnull",
"or",
"(",
"not",
"lift",
".",
"any",
"(",
")",
")",
")",
"else",
"[",
"(",
"x",
"-",
"y",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"out",
",",
"lift",
")",
"]",
")",
"i",
"=",
"unique_label_indices",
"(",
"comp_ids",
")",
"i8copy",
"=",
"(",
"lambda",
"a",
":",
"a",
".",
"astype",
"(",
"'i8'",
",",
"subok",
"=",
"False",
",",
"copy",
"=",
"True",
")",
")",
"return",
"[",
"i8copy",
"(",
"lab",
"[",
"i",
"]",
")",
"for",
"lab",
"in",
"labels",
"]"
] | reconstruct labels from observed group ids parameters xnull: boolean . | train | true |
23,299 | def GetGeneratedFileName(clsid, lcid, major, minor):
return (str(clsid).upper()[1:(-1)] + ('x%sx%sx%s' % (lcid, major, minor)))
| [
"def",
"GetGeneratedFileName",
"(",
"clsid",
",",
"lcid",
",",
"major",
",",
"minor",
")",
":",
"return",
"(",
"str",
"(",
"clsid",
")",
".",
"upper",
"(",
")",
"[",
"1",
":",
"(",
"-",
"1",
")",
"]",
"+",
"(",
"'x%sx%sx%s'",
"%",
"(",
"lcid",
",",
"major",
",",
"minor",
")",
")",
")"
] | given the clsid . | train | false |
23,300 | def _render_value_in_context(value, context):
value = localize(value, use_l10n=context.use_l10n)
value = force_unicode(value)
if ((context.autoescape and (not isinstance(value, SafeData))) or isinstance(value, EscapeData)):
return escape(value)
else:
return value
| [
"def",
"_render_value_in_context",
"(",
"value",
",",
"context",
")",
":",
"value",
"=",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"context",
".",
"use_l10n",
")",
"value",
"=",
"force_unicode",
"(",
"value",
")",
"if",
"(",
"(",
"context",
".",
"autoescape",
"and",
"(",
"not",
"isinstance",
"(",
"value",
",",
"SafeData",
")",
")",
")",
"or",
"isinstance",
"(",
"value",
",",
"EscapeData",
")",
")",
":",
"return",
"escape",
"(",
"value",
")",
"else",
":",
"return",
"value"
] | converts any value to a string to become part of a rendered template . | train | false |
23,301 | def create_environ(path='/', query_string='', protocol='HTTP/1.1', scheme='http', host=DEFAULT_HOST, port=None, headers=None, app='', body='', method='GET', wsgierrors=None, file_wrapper=None):
if (query_string and query_string.startswith('?')):
raise ValueError("query_string should not start with '?'")
body = io.BytesIO((body.encode('utf-8') if isinstance(body, six.text_type) else body))
path = uri.decode(path)
if six.PY3:
path = path.encode('utf-8').decode('iso-8859-1')
if (six.PY2 and isinstance(path, six.text_type)):
path = path.encode('utf-8')
scheme = scheme.lower()
if (port is None):
port = ('80' if (scheme == 'http') else '443')
else:
port = str(port)
env = {'SERVER_PROTOCOL': protocol, 'SERVER_SOFTWARE': 'gunicorn/0.17.0', 'SCRIPT_NAME': app, 'REQUEST_METHOD': method, 'PATH_INFO': path, 'QUERY_STRING': query_string, 'HTTP_USER_AGENT': 'curl/7.24.0 (x86_64-apple-darwin12.0)', 'REMOTE_PORT': '65133', 'RAW_URI': '/', 'REMOTE_ADDR': '127.0.0.1', 'SERVER_NAME': host, 'SERVER_PORT': port, 'wsgi.version': (1, 0), 'wsgi.url_scheme': scheme, 'wsgi.input': body, 'wsgi.errors': (wsgierrors or sys.stderr), 'wsgi.multithread': False, 'wsgi.multiprocess': True, 'wsgi.run_once': False}
if (file_wrapper is not None):
env['wsgi.file_wrapper'] = file_wrapper
if (protocol != 'HTTP/1.0'):
host_header = host
if (scheme == 'https'):
if (port != '443'):
host_header += (':' + port)
elif (port != '80'):
host_header += (':' + port)
env['HTTP_HOST'] = host_header
content_length = body.seek(0, 2)
body.seek(0)
if (content_length != 0):
env['CONTENT_LENGTH'] = str(content_length)
if (headers is not None):
_add_headers_to_environ(env, headers)
return env
| [
"def",
"create_environ",
"(",
"path",
"=",
"'/'",
",",
"query_string",
"=",
"''",
",",
"protocol",
"=",
"'HTTP/1.1'",
",",
"scheme",
"=",
"'http'",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"app",
"=",
"''",
",",
"body",
"=",
"''",
",",
"method",
"=",
"'GET'",
",",
"wsgierrors",
"=",
"None",
",",
"file_wrapper",
"=",
"None",
")",
":",
"if",
"(",
"query_string",
"and",
"query_string",
".",
"startswith",
"(",
"'?'",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"query_string should not start with '?'\"",
")",
"body",
"=",
"io",
".",
"BytesIO",
"(",
"(",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"body",
",",
"six",
".",
"text_type",
")",
"else",
"body",
")",
")",
"path",
"=",
"uri",
".",
"decode",
"(",
"path",
")",
"if",
"six",
".",
"PY3",
":",
"path",
"=",
"path",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"decode",
"(",
"'iso-8859-1'",
")",
"if",
"(",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
")",
":",
"path",
"=",
"path",
".",
"encode",
"(",
"'utf-8'",
")",
"scheme",
"=",
"scheme",
".",
"lower",
"(",
")",
"if",
"(",
"port",
"is",
"None",
")",
":",
"port",
"=",
"(",
"'80'",
"if",
"(",
"scheme",
"==",
"'http'",
")",
"else",
"'443'",
")",
"else",
":",
"port",
"=",
"str",
"(",
"port",
")",
"env",
"=",
"{",
"'SERVER_PROTOCOL'",
":",
"protocol",
",",
"'SERVER_SOFTWARE'",
":",
"'gunicorn/0.17.0'",
",",
"'SCRIPT_NAME'",
":",
"app",
",",
"'REQUEST_METHOD'",
":",
"method",
",",
"'PATH_INFO'",
":",
"path",
",",
"'QUERY_STRING'",
":",
"query_string",
",",
"'HTTP_USER_AGENT'",
":",
"'curl/7.24.0 (x86_64-apple-darwin12.0)'",
",",
"'REMOTE_PORT'",
":",
"'65133'",
",",
"'RAW_URI'",
":",
"'/'",
",",
"'REMOTE_ADDR'",
":",
"'127.0.0.1'",
",",
"'SERVER_NAME'",
":",
"host",
",",
"'SERVER_PORT'",
":",
"port",
",",
"'wsgi.version'",
":",
"(",
"1",
",",
"0",
")",
",",
"'wsgi.url_scheme'",
":",
"scheme",
",",
"'wsgi.input'",
":",
"body",
",",
"'wsgi.errors'",
":",
"(",
"wsgierrors",
"or",
"sys",
".",
"stderr",
")",
",",
"'wsgi.multithread'",
":",
"False",
",",
"'wsgi.multiprocess'",
":",
"True",
",",
"'wsgi.run_once'",
":",
"False",
"}",
"if",
"(",
"file_wrapper",
"is",
"not",
"None",
")",
":",
"env",
"[",
"'wsgi.file_wrapper'",
"]",
"=",
"file_wrapper",
"if",
"(",
"protocol",
"!=",
"'HTTP/1.0'",
")",
":",
"host_header",
"=",
"host",
"if",
"(",
"scheme",
"==",
"'https'",
")",
":",
"if",
"(",
"port",
"!=",
"'443'",
")",
":",
"host_header",
"+=",
"(",
"':'",
"+",
"port",
")",
"elif",
"(",
"port",
"!=",
"'80'",
")",
":",
"host_header",
"+=",
"(",
"':'",
"+",
"port",
")",
"env",
"[",
"'HTTP_HOST'",
"]",
"=",
"host_header",
"content_length",
"=",
"body",
".",
"seek",
"(",
"0",
",",
"2",
")",
"body",
".",
"seek",
"(",
"0",
")",
"if",
"(",
"content_length",
"!=",
"0",
")",
":",
"env",
"[",
"'CONTENT_LENGTH'",
"]",
"=",
"str",
"(",
"content_length",
")",
"if",
"(",
"headers",
"is",
"not",
"None",
")",
":",
"_add_headers_to_environ",
"(",
"env",
",",
"headers",
")",
"return",
"env"
] | create a new wsgi environ dict based on the values passed . | train | false |
23,302 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
23,303 | def model_key(model):
return ('%s.%s' % (model._meta.app_label, model._meta.object_name.lower()))
| [
"def",
"model_key",
"(",
"model",
")",
":",
"return",
"(",
"'%s.%s'",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
")",
")"
] | for a given model . | train | false |
23,304 | def validate_commands(config):
if (CONF_COMMANDS not in config):
config[CONF_COMMANDS] = {}
elif (not isinstance(config[CONF_COMMANDS], dict)):
_LOGGER.warning('Universal Media Player (%s) specified commands not dict in config. They will be ignored.', config[CONF_NAME])
config[CONF_COMMANDS] = {}
| [
"def",
"validate_commands",
"(",
"config",
")",
":",
"if",
"(",
"CONF_COMMANDS",
"not",
"in",
"config",
")",
":",
"config",
"[",
"CONF_COMMANDS",
"]",
"=",
"{",
"}",
"elif",
"(",
"not",
"isinstance",
"(",
"config",
"[",
"CONF_COMMANDS",
"]",
",",
"dict",
")",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"'Universal Media Player (%s) specified commands not dict in config. They will be ignored.'",
",",
"config",
"[",
"CONF_NAME",
"]",
")",
"config",
"[",
"CONF_COMMANDS",
"]",
"=",
"{",
"}"
] | validate commands . | train | false |
23,306 | def assert_has_text(output, text):
assert (output.find(text) >= 0), ("Output file did not contain expected text '%s' (output '%s')" % (text, output))
| [
"def",
"assert_has_text",
"(",
"output",
",",
"text",
")",
":",
"assert",
"(",
"output",
".",
"find",
"(",
"text",
")",
">=",
"0",
")",
",",
"(",
"\"Output file did not contain expected text '%s' (output '%s')\"",
"%",
"(",
"text",
",",
"output",
")",
")"
] | asserts specified output contains the substring specified by the argument text . | train | false |
23,307 | def cluster_type():
return s3_rest_controller()
| [
"def",
"cluster_type",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | volunteer cluster types controller . | train | false |
23,308 | def _array_like(x, x0):
x = np.reshape(x, np.shape(x0))
wrap = getattr(x0, '__array_wrap__', x.__array_wrap__)
return wrap(x)
| [
"def",
"_array_like",
"(",
"x",
",",
"x0",
")",
":",
"x",
"=",
"np",
".",
"reshape",
"(",
"x",
",",
"np",
".",
"shape",
"(",
"x0",
")",
")",
"wrap",
"=",
"getattr",
"(",
"x0",
",",
"'__array_wrap__'",
",",
"x",
".",
"__array_wrap__",
")",
"return",
"wrap",
"(",
"x",
")"
] | return ndarray x as same array subclass and shape as x0 . | train | false |
23,309 | def partners():
get_vars['organisation_type.name'] = 'Academic,Bilateral,Government,Intergovernmental,NGO,UN agency'
table = s3db.org_organisation
s3.crud_strings.org_organisation = Storage(label_create=T('Create Partner Organization'), title_display=T('Partner Organization Details'), title_list=T('Partner Organizations'), title_update=T('Edit Partner Organization'), title_upload=T('Import Partner Organizations'), label_list_button=T('List Partner Organizations'), label_delete_button=T('Delete Partner Organization'), msg_record_created=T('Partner Organization added'), msg_record_modified=T('Partner Organization updated'), msg_record_deleted=T('Partner Organization deleted'), msg_list_empty=T('No Partner Organizations currently registered'))
return s3db.org_organisation_controller()
| [
"def",
"partners",
"(",
")",
":",
"get_vars",
"[",
"'organisation_type.name'",
"]",
"=",
"'Academic,Bilateral,Government,Intergovernmental,NGO,UN agency'",
"table",
"=",
"s3db",
".",
"org_organisation",
"s3",
".",
"crud_strings",
".",
"org_organisation",
"=",
"Storage",
"(",
"label_create",
"=",
"T",
"(",
"'Create Partner Organization'",
")",
",",
"title_display",
"=",
"T",
"(",
"'Partner Organization Details'",
")",
",",
"title_list",
"=",
"T",
"(",
"'Partner Organizations'",
")",
",",
"title_update",
"=",
"T",
"(",
"'Edit Partner Organization'",
")",
",",
"title_upload",
"=",
"T",
"(",
"'Import Partner Organizations'",
")",
",",
"label_list_button",
"=",
"T",
"(",
"'List Partner Organizations'",
")",
",",
"label_delete_button",
"=",
"T",
"(",
"'Delete Partner Organization'",
")",
",",
"msg_record_created",
"=",
"T",
"(",
"'Partner Organization added'",
")",
",",
"msg_record_modified",
"=",
"T",
"(",
"'Partner Organization updated'",
")",
",",
"msg_record_deleted",
"=",
"T",
"(",
"'Partner Organization deleted'",
")",
",",
"msg_list_empty",
"=",
"T",
"(",
"'No Partner Organizations currently registered'",
")",
")",
"return",
"s3db",
".",
"org_organisation_controller",
"(",
")"
] | landing page for partners . | train | false |
23,310 | def serialize_remote_exception(failure_info, log_failure=True):
tb = traceback.format_exception(*failure_info)
failure = failure_info[1]
if log_failure:
LOG.error(_('Returning exception %s to caller'), six.text_type(failure))
LOG.error(tb)
kwargs = {}
if hasattr(failure, 'kwargs'):
kwargs = failure.kwargs
cls_name = str(failure.__class__.__name__)
mod_name = str(failure.__class__.__module__)
if (cls_name.endswith(_REMOTE_POSTFIX) and mod_name.endswith(_REMOTE_POSTFIX)):
cls_name = cls_name[:(- len(_REMOTE_POSTFIX))]
mod_name = mod_name[:(- len(_REMOTE_POSTFIX))]
data = {'class': cls_name, 'module': mod_name, 'message': six.text_type(failure), 'tb': tb, 'args': failure.args, 'kwargs': kwargs}
json_data = jsonutils.dumps(data)
return json_data
| [
"def",
"serialize_remote_exception",
"(",
"failure_info",
",",
"log_failure",
"=",
"True",
")",
":",
"tb",
"=",
"traceback",
".",
"format_exception",
"(",
"*",
"failure_info",
")",
"failure",
"=",
"failure_info",
"[",
"1",
"]",
"if",
"log_failure",
":",
"LOG",
".",
"error",
"(",
"_",
"(",
"'Returning exception %s to caller'",
")",
",",
"six",
".",
"text_type",
"(",
"failure",
")",
")",
"LOG",
".",
"error",
"(",
"tb",
")",
"kwargs",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"failure",
",",
"'kwargs'",
")",
":",
"kwargs",
"=",
"failure",
".",
"kwargs",
"cls_name",
"=",
"str",
"(",
"failure",
".",
"__class__",
".",
"__name__",
")",
"mod_name",
"=",
"str",
"(",
"failure",
".",
"__class__",
".",
"__module__",
")",
"if",
"(",
"cls_name",
".",
"endswith",
"(",
"_REMOTE_POSTFIX",
")",
"and",
"mod_name",
".",
"endswith",
"(",
"_REMOTE_POSTFIX",
")",
")",
":",
"cls_name",
"=",
"cls_name",
"[",
":",
"(",
"-",
"len",
"(",
"_REMOTE_POSTFIX",
")",
")",
"]",
"mod_name",
"=",
"mod_name",
"[",
":",
"(",
"-",
"len",
"(",
"_REMOTE_POSTFIX",
")",
")",
"]",
"data",
"=",
"{",
"'class'",
":",
"cls_name",
",",
"'module'",
":",
"mod_name",
",",
"'message'",
":",
"six",
".",
"text_type",
"(",
"failure",
")",
",",
"'tb'",
":",
"tb",
",",
"'args'",
":",
"failure",
".",
"args",
",",
"'kwargs'",
":",
"kwargs",
"}",
"json_data",
"=",
"jsonutils",
".",
"dumps",
"(",
"data",
")",
"return",
"json_data"
] | prepares exception data to be sent over rpc . | train | false |
23,311 | def test_pmf_hist_bins():
(x, h, w) = utils.pmf_hist(a_norm, 20)
assert_equal(len(x), 20)
| [
"def",
"test_pmf_hist_bins",
"(",
")",
":",
"(",
"x",
",",
"h",
",",
"w",
")",
"=",
"utils",
".",
"pmf_hist",
"(",
"a_norm",
",",
"20",
")",
"assert_equal",
"(",
"len",
"(",
"x",
")",
",",
"20",
")"
] | test bin specification . | train | false |
23,312 | def _do_db_create():
server = BioSeqDatabase.open_database(driver=DBDRIVER, host=DBHOST, user=DBUSER, passwd=DBPASSWD)
if (DBDRIVER == 'pgdb'):
server.adaptor.cursor.execute('COMMIT')
else:
try:
server.adaptor.autocommit()
except AttributeError:
pass
try:
time.sleep(1)
sql = ('DROP DATABASE ' + TESTDB)
server.adaptor.cursor.execute(sql, ())
except (server.module.OperationalError, server.module.Error, server.module.DatabaseError) as e:
pass
except (server.module.IntegrityError, server.module.ProgrammingError) as e:
if (str(e).find(('database "%s" does not exist' % TESTDB)) == (-1)):
server.close()
raise
sql = ('CREATE DATABASE ' + TESTDB)
server.adaptor.execute(sql, ())
server.close()
| [
"def",
"_do_db_create",
"(",
")",
":",
"server",
"=",
"BioSeqDatabase",
".",
"open_database",
"(",
"driver",
"=",
"DBDRIVER",
",",
"host",
"=",
"DBHOST",
",",
"user",
"=",
"DBUSER",
",",
"passwd",
"=",
"DBPASSWD",
")",
"if",
"(",
"DBDRIVER",
"==",
"'pgdb'",
")",
":",
"server",
".",
"adaptor",
".",
"cursor",
".",
"execute",
"(",
"'COMMIT'",
")",
"else",
":",
"try",
":",
"server",
".",
"adaptor",
".",
"autocommit",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"sql",
"=",
"(",
"'DROP DATABASE '",
"+",
"TESTDB",
")",
"server",
".",
"adaptor",
".",
"cursor",
".",
"execute",
"(",
"sql",
",",
"(",
")",
")",
"except",
"(",
"server",
".",
"module",
".",
"OperationalError",
",",
"server",
".",
"module",
".",
"Error",
",",
"server",
".",
"module",
".",
"DatabaseError",
")",
"as",
"e",
":",
"pass",
"except",
"(",
"server",
".",
"module",
".",
"IntegrityError",
",",
"server",
".",
"module",
".",
"ProgrammingError",
")",
"as",
"e",
":",
"if",
"(",
"str",
"(",
"e",
")",
".",
"find",
"(",
"(",
"'database \"%s\" does not exist'",
"%",
"TESTDB",
")",
")",
"==",
"(",
"-",
"1",
")",
")",
":",
"server",
".",
"close",
"(",
")",
"raise",
"sql",
"=",
"(",
"'CREATE DATABASE '",
"+",
"TESTDB",
")",
"server",
".",
"adaptor",
".",
"execute",
"(",
"sql",
",",
"(",
")",
")",
"server",
".",
"close",
"(",
")"
] | do the actual work of database creation . | train | false |
23,313 | def gf_int(a, p):
if (a <= (p // 2)):
return a
else:
return (a - p)
| [
"def",
"gf_int",
"(",
"a",
",",
"p",
")",
":",
"if",
"(",
"a",
"<=",
"(",
"p",
"//",
"2",
")",
")",
":",
"return",
"a",
"else",
":",
"return",
"(",
"a",
"-",
"p",
")"
] | coerce a mod p to an integer in the range [-p/2 . | train | false |
23,316 | def triu2flat(m):
dim = m.shape[0]
res = zeros(((dim * (dim + 1)) / 2))
index = 0
for row in range(dim):
res[index:((index + dim) - row)] = m[row, row:]
index += (dim - row)
return res
| [
"def",
"triu2flat",
"(",
"m",
")",
":",
"dim",
"=",
"m",
".",
"shape",
"[",
"0",
"]",
"res",
"=",
"zeros",
"(",
"(",
"(",
"dim",
"*",
"(",
"dim",
"+",
"1",
")",
")",
"/",
"2",
")",
")",
"index",
"=",
"0",
"for",
"row",
"in",
"range",
"(",
"dim",
")",
":",
"res",
"[",
"index",
":",
"(",
"(",
"index",
"+",
"dim",
")",
"-",
"row",
")",
"]",
"=",
"m",
"[",
"row",
",",
"row",
":",
"]",
"index",
"+=",
"(",
"dim",
"-",
"row",
")",
"return",
"res"
] | flattens an upper triangular matrix . | train | false |
23,317 | def restart_cluster(name):
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
if __opts__['test']:
ret['comment'] = 'Restarting cluster'
return ret
__salt__['trafficserver.restart_cluster']()
ret['result'] = True
ret['comment'] = 'Restarted cluster'
return ret
| [
"def",
"restart_cluster",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Restarting cluster'",
"return",
"ret",
"__salt__",
"[",
"'trafficserver.restart_cluster'",
"]",
"(",
")",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'Restarted cluster'",
"return",
"ret"
] | restart the traffic_manager process and the traffic_server process on all the nodes in a cluster . | train | true |
23,318 | def lesser(x, y):
return tf.less(x, y)
| [
"def",
"lesser",
"(",
"x",
",",
"y",
")",
":",
"return",
"tf",
".",
"less",
"(",
"x",
",",
"y",
")"
] | element-wise truth value of . | train | false |
23,319 | def extract_ipv4(roster_order, ipv4):
for ip_type in roster_order:
for ip_ in ipv4:
if (':' in ip_):
continue
if (not salt.utils.validate.net.ipv4_addr(ip_)):
continue
if ((ip_type == 'local') and ip_.startswith('127.')):
return ip_
elif ((ip_type == 'private') and (not salt.utils.cloud.is_public_ip(ip_))):
return ip_
elif ((ip_type == 'public') and salt.utils.cloud.is_public_ip(ip_)):
return ip_
return None
| [
"def",
"extract_ipv4",
"(",
"roster_order",
",",
"ipv4",
")",
":",
"for",
"ip_type",
"in",
"roster_order",
":",
"for",
"ip_",
"in",
"ipv4",
":",
"if",
"(",
"':'",
"in",
"ip_",
")",
":",
"continue",
"if",
"(",
"not",
"salt",
".",
"utils",
".",
"validate",
".",
"net",
".",
"ipv4_addr",
"(",
"ip_",
")",
")",
":",
"continue",
"if",
"(",
"(",
"ip_type",
"==",
"'local'",
")",
"and",
"ip_",
".",
"startswith",
"(",
"'127.'",
")",
")",
":",
"return",
"ip_",
"elif",
"(",
"(",
"ip_type",
"==",
"'private'",
")",
"and",
"(",
"not",
"salt",
".",
"utils",
".",
"cloud",
".",
"is_public_ip",
"(",
"ip_",
")",
")",
")",
":",
"return",
"ip_",
"elif",
"(",
"(",
"ip_type",
"==",
"'public'",
")",
"and",
"salt",
".",
"utils",
".",
"cloud",
".",
"is_public_ip",
"(",
"ip_",
")",
")",
":",
"return",
"ip_",
"return",
"None"
] | extract the preferred ip address from the ipv4 grain . | train | true |
23,320 | def test_summary_without_address(request_cart_with_item, client):
response = client.get(reverse('checkout:summary'))
assert (response.status_code == 302)
assert (get_redirect_location(response) == reverse('checkout:shipping-method'))
| [
"def",
"test_summary_without_address",
"(",
"request_cart_with_item",
",",
"client",
")",
":",
"response",
"=",
"client",
".",
"get",
"(",
"reverse",
"(",
"'checkout:summary'",
")",
")",
"assert",
"(",
"response",
".",
"status_code",
"==",
"302",
")",
"assert",
"(",
"get_redirect_location",
"(",
"response",
")",
"==",
"reverse",
"(",
"'checkout:shipping-method'",
")",
")"
] | user tries to get summary step without saved shipping method - if is redirected to shipping method step . | train | false |
23,321 | def _strip(g, base, orbits, transversals):
h = g._array_form
base_len = len(base)
for i in range(base_len):
beta = h[base[i]]
if (beta == base[i]):
continue
if (beta not in orbits[i]):
return (_af_new(h), (i + 1))
u = transversals[i][beta]._array_form
h = _af_rmul(_af_invert(u), h)
return (_af_new(h), (base_len + 1))
| [
"def",
"_strip",
"(",
"g",
",",
"base",
",",
"orbits",
",",
"transversals",
")",
":",
"h",
"=",
"g",
".",
"_array_form",
"base_len",
"=",
"len",
"(",
"base",
")",
"for",
"i",
"in",
"range",
"(",
"base_len",
")",
":",
"beta",
"=",
"h",
"[",
"base",
"[",
"i",
"]",
"]",
"if",
"(",
"beta",
"==",
"base",
"[",
"i",
"]",
")",
":",
"continue",
"if",
"(",
"beta",
"not",
"in",
"orbits",
"[",
"i",
"]",
")",
":",
"return",
"(",
"_af_new",
"(",
"h",
")",
",",
"(",
"i",
"+",
"1",
")",
")",
"u",
"=",
"transversals",
"[",
"i",
"]",
"[",
"beta",
"]",
".",
"_array_form",
"h",
"=",
"_af_rmul",
"(",
"_af_invert",
"(",
"u",
")",
",",
"h",
")",
"return",
"(",
"_af_new",
"(",
"h",
")",
",",
"(",
"base_len",
"+",
"1",
")",
")"
] | attempt to decompose a permutation using a bsgs structure . | train | false |
23,322 | def _localized_name(val, klass):
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang='en')
| [
"def",
"_localized_name",
"(",
"val",
",",
"klass",
")",
":",
"try",
":",
"(",
"text",
",",
"lang",
")",
"=",
"val",
"return",
"klass",
"(",
"text",
"=",
"text",
",",
"lang",
"=",
"lang",
")",
"except",
"ValueError",
":",
"return",
"klass",
"(",
"text",
"=",
"val",
",",
"lang",
"=",
"'en'",
")"
] | if no language is defined en is the default . | train | true |
23,324 | def _is_db_connection_error(args):
conn_err_codes = ('2002', '2003', '2006')
for err_code in conn_err_codes:
if (args.find(err_code) != (-1)):
return True
return False
| [
"def",
"_is_db_connection_error",
"(",
"args",
")",
":",
"conn_err_codes",
"=",
"(",
"'2002'",
",",
"'2003'",
",",
"'2006'",
")",
"for",
"err_code",
"in",
"conn_err_codes",
":",
"if",
"(",
"args",
".",
"find",
"(",
"err_code",
")",
"!=",
"(",
"-",
"1",
")",
")",
":",
"return",
"True",
"return",
"False"
] | return true if error in connecting to db . | train | false |
23,327 | def run_as_contextmanager(ctx, fn, *arg, **kw):
obj = ctx.__enter__()
try:
result = fn(obj, *arg, **kw)
ctx.__exit__(None, None, None)
return result
except:
exc_info = sys.exc_info()
raise_ = ctx.__exit__(*exc_info)
if (raise_ is None):
raise
else:
return raise_
| [
"def",
"run_as_contextmanager",
"(",
"ctx",
",",
"fn",
",",
"*",
"arg",
",",
"**",
"kw",
")",
":",
"obj",
"=",
"ctx",
".",
"__enter__",
"(",
")",
"try",
":",
"result",
"=",
"fn",
"(",
"obj",
",",
"*",
"arg",
",",
"**",
"kw",
")",
"ctx",
".",
"__exit__",
"(",
"None",
",",
"None",
",",
"None",
")",
"return",
"result",
"except",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise_",
"=",
"ctx",
".",
"__exit__",
"(",
"*",
"exc_info",
")",
"if",
"(",
"raise_",
"is",
"None",
")",
":",
"raise",
"else",
":",
"return",
"raise_"
] | run the given function under the given contextmanager . | train | false |
23,328 | def is_dominating_set(G, nbunch):
testset = set((n for n in nbunch if (n in G)))
nbrs = set(chain.from_iterable((G[n] for n in testset)))
return (len(((set(G) - testset) - nbrs)) == 0)
| [
"def",
"is_dominating_set",
"(",
"G",
",",
"nbunch",
")",
":",
"testset",
"=",
"set",
"(",
"(",
"n",
"for",
"n",
"in",
"nbunch",
"if",
"(",
"n",
"in",
"G",
")",
")",
")",
"nbrs",
"=",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
"G",
"[",
"n",
"]",
"for",
"n",
"in",
"testset",
")",
")",
")",
"return",
"(",
"len",
"(",
"(",
"(",
"set",
"(",
"G",
")",
"-",
"testset",
")",
"-",
"nbrs",
")",
")",
"==",
"0",
")"
] | checks if nbunch is a dominating set for g . | train | false |
23,329 | def get_python_lib_zip(contentstore, course_id):
asset_key = course_id.make_asset_key('asset', PYTHON_LIB_ZIP)
zip_lib = contentstore().find(asset_key, throw_on_not_found=False)
if (zip_lib is not None):
return zip_lib.data
else:
return None
| [
"def",
"get_python_lib_zip",
"(",
"contentstore",
",",
"course_id",
")",
":",
"asset_key",
"=",
"course_id",
".",
"make_asset_key",
"(",
"'asset'",
",",
"PYTHON_LIB_ZIP",
")",
"zip_lib",
"=",
"contentstore",
"(",
")",
".",
"find",
"(",
"asset_key",
",",
"throw_on_not_found",
"=",
"False",
")",
"if",
"(",
"zip_lib",
"is",
"not",
"None",
")",
":",
"return",
"zip_lib",
".",
"data",
"else",
":",
"return",
"None"
] | return the bytes of the python_lib . | train | false |
23,330 | def safe_display_name(numobj, lang, script=None, region=None):
if is_mobile_number_portable_region(region_code_for_number(numobj)):
return U_EMPTY_STRING
return name_for_number(numobj, lang, script, region)
| [
"def",
"safe_display_name",
"(",
"numobj",
",",
"lang",
",",
"script",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"if",
"is_mobile_number_portable_region",
"(",
"region_code_for_number",
"(",
"numobj",
")",
")",
":",
"return",
"U_EMPTY_STRING",
"return",
"name_for_number",
"(",
"numobj",
",",
"lang",
",",
"script",
",",
"region",
")"
] | gets the name of the carrier for the given phonenumber object only when it is safe to display to users . | train | true |
23,334 | def names(root=None):
if (not root):
root = Tkinter._default_root
return root.tk.splitlist(root.tk.call('font', 'names'))
| [
"def",
"names",
"(",
"root",
"=",
"None",
")",
":",
"if",
"(",
"not",
"root",
")",
":",
"root",
"=",
"Tkinter",
".",
"_default_root",
"return",
"root",
".",
"tk",
".",
"splitlist",
"(",
"root",
".",
"tk",
".",
"call",
"(",
"'font'",
",",
"'names'",
")",
")"
] | returns a list of definition objects . | train | false |
23,335 | def get_time_points(interval, start_time=None, stop_time=None):
def truncate_datetime(dt):
dt = dt.replace(minute=0, second=0, microsecond=0)
if (interval in ('day', 'month')):
dt = dt.replace(hour=0)
if (interval == 'month'):
dt = dt.replace(day=1)
return dt
if (start_time and stop_time):
(start_time, stop_time) = sorted([start_time, stop_time])
stop_time = truncate_datetime(stop_time)
else:
stop_time = datetime.datetime.utcnow()
stop_time = truncate_datetime(stop_time)
range = time_range_by_interval[interval]
start_time = (stop_time - range)
step = timedelta_by_name(interval)
current_time = stop_time
time_points = []
while (current_time >= start_time):
time_points.append(current_time)
if (interval != 'month'):
current_time -= step
else:
current_time = decrement_month(current_time)
return time_points
| [
"def",
"get_time_points",
"(",
"interval",
",",
"start_time",
"=",
"None",
",",
"stop_time",
"=",
"None",
")",
":",
"def",
"truncate_datetime",
"(",
"dt",
")",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"if",
"(",
"interval",
"in",
"(",
"'day'",
",",
"'month'",
")",
")",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"hour",
"=",
"0",
")",
"if",
"(",
"interval",
"==",
"'month'",
")",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"day",
"=",
"1",
")",
"return",
"dt",
"if",
"(",
"start_time",
"and",
"stop_time",
")",
":",
"(",
"start_time",
",",
"stop_time",
")",
"=",
"sorted",
"(",
"[",
"start_time",
",",
"stop_time",
"]",
")",
"stop_time",
"=",
"truncate_datetime",
"(",
"stop_time",
")",
"else",
":",
"stop_time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"stop_time",
"=",
"truncate_datetime",
"(",
"stop_time",
")",
"range",
"=",
"time_range_by_interval",
"[",
"interval",
"]",
"start_time",
"=",
"(",
"stop_time",
"-",
"range",
")",
"step",
"=",
"timedelta_by_name",
"(",
"interval",
")",
"current_time",
"=",
"stop_time",
"time_points",
"=",
"[",
"]",
"while",
"(",
"current_time",
">=",
"start_time",
")",
":",
"time_points",
".",
"append",
"(",
"current_time",
")",
"if",
"(",
"interval",
"!=",
"'month'",
")",
":",
"current_time",
"-=",
"step",
"else",
":",
"current_time",
"=",
"decrement_month",
"(",
"current_time",
")",
"return",
"time_points"
] | return time points for given interval type . | train | false |
23,336 | def libvlc_media_event_manager(p_md):
f = (_Cfunctions.get('libvlc_media_event_manager', None) or _Cfunction('libvlc_media_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, Media))
return f(p_md)
| [
"def",
"libvlc_media_event_manager",
"(",
"p_md",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_event_manager'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_event_manager'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
",",
"class_result",
"(",
"EventManager",
")",
",",
"ctypes",
".",
"c_void_p",
",",
"Media",
")",
")",
"return",
"f",
"(",
"p_md",
")"
] | get event manager from media descriptor object . | train | true |
23,337 | @receiver(PROBLEM_WEIGHTED_SCORE_CHANGED)
def handle_score_changed(**kwargs):
course = modulestore().get_course(CourseKey.from_string(kwargs.get('course_id')))
block = modulestore().get_item(UsageKey.from_string(kwargs.get('usage_id')))
gating_api.evaluate_prerequisite(course, block, kwargs.get('user_id'))
gating_api.evaluate_entrance_exam(course, block, kwargs.get('user_id'))
| [
"@",
"receiver",
"(",
"PROBLEM_WEIGHTED_SCORE_CHANGED",
")",
"def",
"handle_score_changed",
"(",
"**",
"kwargs",
")",
":",
"course",
"=",
"modulestore",
"(",
")",
".",
"get_course",
"(",
"CourseKey",
".",
"from_string",
"(",
"kwargs",
".",
"get",
"(",
"'course_id'",
")",
")",
")",
"block",
"=",
"modulestore",
"(",
")",
".",
"get_item",
"(",
"UsageKey",
".",
"from_string",
"(",
"kwargs",
".",
"get",
"(",
"'usage_id'",
")",
")",
")",
"gating_api",
".",
"evaluate_prerequisite",
"(",
"course",
",",
"block",
",",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
")",
"gating_api",
".",
"evaluate_entrance_exam",
"(",
"course",
",",
"block",
",",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
")"
] | receives the problem_weighted_score_changed signal sent by lms when a students score has changed for a given component and triggers the evaluation of any milestone relationships which are attached to the updated content . | train | false |
23,338 | def _CreateConfigParserFromConfigFile(config_filename):
if (not os.path.exists(config_filename)):
raise StyleConfigError('"{0}" is not a valid style or file path'.format(config_filename))
with open(config_filename) as style_file:
config = py3compat.ConfigParser()
config.read_file(style_file)
if config_filename.endswith(SETUP_CONFIG):
if (not config.has_section('yapf')):
raise StyleConfigError('Unable to find section [yapf] in {0}'.format(config_filename))
elif config_filename.endswith(LOCAL_STYLE):
if (not config.has_section('style')):
raise StyleConfigError('Unable to find section [style] in {0}'.format(config_filename))
elif (not config.has_section('style')):
raise StyleConfigError('Unable to find section [style] in {0}'.format(config_filename))
return config
| [
"def",
"_CreateConfigParserFromConfigFile",
"(",
"config_filename",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_filename",
")",
")",
":",
"raise",
"StyleConfigError",
"(",
"'\"{0}\" is not a valid style or file path'",
".",
"format",
"(",
"config_filename",
")",
")",
"with",
"open",
"(",
"config_filename",
")",
"as",
"style_file",
":",
"config",
"=",
"py3compat",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read_file",
"(",
"style_file",
")",
"if",
"config_filename",
".",
"endswith",
"(",
"SETUP_CONFIG",
")",
":",
"if",
"(",
"not",
"config",
".",
"has_section",
"(",
"'yapf'",
")",
")",
":",
"raise",
"StyleConfigError",
"(",
"'Unable to find section [yapf] in {0}'",
".",
"format",
"(",
"config_filename",
")",
")",
"elif",
"config_filename",
".",
"endswith",
"(",
"LOCAL_STYLE",
")",
":",
"if",
"(",
"not",
"config",
".",
"has_section",
"(",
"'style'",
")",
")",
":",
"raise",
"StyleConfigError",
"(",
"'Unable to find section [style] in {0}'",
".",
"format",
"(",
"config_filename",
")",
")",
"elif",
"(",
"not",
"config",
".",
"has_section",
"(",
"'style'",
")",
")",
":",
"raise",
"StyleConfigError",
"(",
"'Unable to find section [style] in {0}'",
".",
"format",
"(",
"config_filename",
")",
")",
"return",
"config"
] | read the file and return a configparser object . | train | false |
23,339 | def url_filter(http_url_req):
if http_url_req:
d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff']
if any((http_url_req.endswith(i) for i in d)):
return
return http_url_req
| [
"def",
"url_filter",
"(",
"http_url_req",
")",
":",
"if",
"http_url_req",
":",
"d",
"=",
"[",
"'.jpg'",
",",
"'.jpeg'",
",",
"'.gif'",
",",
"'.png'",
",",
"'.css'",
",",
"'.ico'",
",",
"'.js'",
",",
"'.svg'",
",",
"'.woff'",
"]",
"if",
"any",
"(",
"(",
"http_url_req",
".",
"endswith",
"(",
"i",
")",
"for",
"i",
"in",
"d",
")",
")",
":",
"return",
"return",
"http_url_req"
] | filter out the common but uninteresting urls . | train | false |
23,340 | def parse_mapreduce_yaml(contents):
try:
builder = yaml_object.ObjectBuilder(MapReduceYaml)
handler = yaml_builder.BuilderHandler(builder)
listener = yaml_listener.EventListener(handler)
listener.Parse(contents)
mr_info = handler.GetResults()
except (ValueError, yaml_errors.EventError) as e:
raise BadYamlError(e)
if (len(mr_info) < 1):
raise BadYamlError('No configs found in mapreduce.yaml')
if (len(mr_info) > 1):
raise MultipleDocumentsInMrYaml(('Found %d YAML documents' % len(mr_info)))
jobs = mr_info[0]
job_names = set((j.name for j in jobs.mapreduce))
if (len(jobs.mapreduce) != len(job_names)):
raise BadYamlError('Overlapping mapreduce names; names must be unique')
return jobs
| [
"def",
"parse_mapreduce_yaml",
"(",
"contents",
")",
":",
"try",
":",
"builder",
"=",
"yaml_object",
".",
"ObjectBuilder",
"(",
"MapReduceYaml",
")",
"handler",
"=",
"yaml_builder",
".",
"BuilderHandler",
"(",
"builder",
")",
"listener",
"=",
"yaml_listener",
".",
"EventListener",
"(",
"handler",
")",
"listener",
".",
"Parse",
"(",
"contents",
")",
"mr_info",
"=",
"handler",
".",
"GetResults",
"(",
")",
"except",
"(",
"ValueError",
",",
"yaml_errors",
".",
"EventError",
")",
"as",
"e",
":",
"raise",
"BadYamlError",
"(",
"e",
")",
"if",
"(",
"len",
"(",
"mr_info",
")",
"<",
"1",
")",
":",
"raise",
"BadYamlError",
"(",
"'No configs found in mapreduce.yaml'",
")",
"if",
"(",
"len",
"(",
"mr_info",
")",
">",
"1",
")",
":",
"raise",
"MultipleDocumentsInMrYaml",
"(",
"(",
"'Found %d YAML documents'",
"%",
"len",
"(",
"mr_info",
")",
")",
")",
"jobs",
"=",
"mr_info",
"[",
"0",
"]",
"job_names",
"=",
"set",
"(",
"(",
"j",
".",
"name",
"for",
"j",
"in",
"jobs",
".",
"mapreduce",
")",
")",
"if",
"(",
"len",
"(",
"jobs",
".",
"mapreduce",
")",
"!=",
"len",
"(",
"job_names",
")",
")",
":",
"raise",
"BadYamlError",
"(",
"'Overlapping mapreduce names; names must be unique'",
")",
"return",
"jobs"
] | parses mapreduce . | train | true |
23,343 | def extract_email(email):
addresses = email_split(email)
return (addresses[0] if addresses else '')
| [
"def",
"extract_email",
"(",
"email",
")",
":",
"addresses",
"=",
"email_split",
"(",
"email",
")",
"return",
"(",
"addresses",
"[",
"0",
"]",
"if",
"addresses",
"else",
"''",
")"
] | extract the email address from a user-friendly email address . | train | false |
23,344 | @_docstring('recording')
def get_recordings_by_isrc(isrc, includes=[], release_status=[], release_type=[]):
params = _check_filter_and_make_params('isrc', includes, release_status, release_type)
return _do_mb_query('isrc', isrc, includes, params)
| [
"@",
"_docstring",
"(",
"'recording'",
")",
"def",
"get_recordings_by_isrc",
"(",
"isrc",
",",
"includes",
"=",
"[",
"]",
",",
"release_status",
"=",
"[",
"]",
",",
"release_type",
"=",
"[",
"]",
")",
":",
"params",
"=",
"_check_filter_and_make_params",
"(",
"'isrc'",
",",
"includes",
",",
"release_status",
",",
"release_type",
")",
"return",
"_do_mb_query",
"(",
"'isrc'",
",",
"isrc",
",",
"includes",
",",
"params",
")"
] | search for recordings with an :musicbrainz:isrc . | train | false |
23,345 | def proj_transform_clip(xs, ys, zs, M):
vec = vec_pad_ones(xs, ys, zs)
return proj_transform_vec_clip(vec, M)
| [
"def",
"proj_transform_clip",
"(",
"xs",
",",
"ys",
",",
"zs",
",",
"M",
")",
":",
"vec",
"=",
"vec_pad_ones",
"(",
"xs",
",",
"ys",
",",
"zs",
")",
"return",
"proj_transform_vec_clip",
"(",
"vec",
",",
"M",
")"
] | transform the points by the projection matrix and return the clipping result returns txs . | train | false |
23,347 | def forward_socket(local, remote, timeout, bufsize):
try:
tick = 1
timecount = timeout
while 1:
timecount -= tick
if (timecount <= 0):
break
(ins, _, errors) = select.select([local, remote], [], [local, remote], tick)
if errors:
break
for sock in ins:
data = sock.recv(bufsize)
if (not data):
break
if (sock is remote):
local.sendall(data)
timecount = timeout
else:
remote.sendall(data)
timecount = timeout
except socket.timeout:
pass
except (socket.error, ssl.SSLError, OpenSSL.SSL.Error) as e:
if (e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE)):
raise
if (e.args[0] in (errno.EBADF,)):
return
finally:
for sock in (remote, local):
try:
sock.close()
except StandardError:
pass
| [
"def",
"forward_socket",
"(",
"local",
",",
"remote",
",",
"timeout",
",",
"bufsize",
")",
":",
"try",
":",
"tick",
"=",
"1",
"timecount",
"=",
"timeout",
"while",
"1",
":",
"timecount",
"-=",
"tick",
"if",
"(",
"timecount",
"<=",
"0",
")",
":",
"break",
"(",
"ins",
",",
"_",
",",
"errors",
")",
"=",
"select",
".",
"select",
"(",
"[",
"local",
",",
"remote",
"]",
",",
"[",
"]",
",",
"[",
"local",
",",
"remote",
"]",
",",
"tick",
")",
"if",
"errors",
":",
"break",
"for",
"sock",
"in",
"ins",
":",
"data",
"=",
"sock",
".",
"recv",
"(",
"bufsize",
")",
"if",
"(",
"not",
"data",
")",
":",
"break",
"if",
"(",
"sock",
"is",
"remote",
")",
":",
"local",
".",
"sendall",
"(",
"data",
")",
"timecount",
"=",
"timeout",
"else",
":",
"remote",
".",
"sendall",
"(",
"data",
")",
"timecount",
"=",
"timeout",
"except",
"socket",
".",
"timeout",
":",
"pass",
"except",
"(",
"socket",
".",
"error",
",",
"ssl",
".",
"SSLError",
",",
"OpenSSL",
".",
"SSL",
".",
"Error",
")",
"as",
"e",
":",
"if",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"not",
"in",
"(",
"errno",
".",
"ECONNABORTED",
",",
"errno",
".",
"ECONNRESET",
",",
"errno",
".",
"ENOTCONN",
",",
"errno",
".",
"EPIPE",
")",
")",
":",
"raise",
"if",
"(",
"e",
".",
"args",
"[",
"0",
"]",
"in",
"(",
"errno",
".",
"EBADF",
",",
")",
")",
":",
"return",
"finally",
":",
"for",
"sock",
"in",
"(",
"remote",
",",
"local",
")",
":",
"try",
":",
"sock",
".",
"close",
"(",
")",
"except",
"StandardError",
":",
"pass"
] | forward socket . | train | false |
23,348 | def makeReviewResult(message, *labels):
return dict(message=message, labels=dict(labels))
| [
"def",
"makeReviewResult",
"(",
"message",
",",
"*",
"labels",
")",
":",
"return",
"dict",
"(",
"message",
"=",
"message",
",",
"labels",
"=",
"dict",
"(",
"labels",
")",
")"
] | helper to produce a review result . | train | false |
23,349 | def parse_tz_offset(s):
tz_off = (((int(s[1:3]) * 60) * 60) + (int(s[3:5]) * 60))
if (s[0] == '-'):
return (- tz_off)
return tz_off
| [
"def",
"parse_tz_offset",
"(",
"s",
")",
":",
"tz_off",
"=",
"(",
"(",
"(",
"int",
"(",
"s",
"[",
"1",
":",
"3",
"]",
")",
"*",
"60",
")",
"*",
"60",
")",
"+",
"(",
"int",
"(",
"s",
"[",
"3",
":",
"5",
"]",
")",
"*",
"60",
")",
")",
"if",
"(",
"s",
"[",
"0",
"]",
"==",
"'-'",
")",
":",
"return",
"(",
"-",
"tz_off",
")",
"return",
"tz_off"
] | utc offset in seconds . | train | false |
23,350 | @deprecated(u'1.0', message=DEPRECATION_MESSAGE)
def join(left, right, keys=None, join_type=u'inner', uniq_col_name=u'{col_name}_{table_name}', table_names=[u'1', u'2'], col_name_map=None):
_col_name_map = col_name_map
if (join_type not in (u'inner', u'outer', u'left', u'right')):
raise ValueError(u"The 'join_type' argument should be in 'inner', 'outer', 'left' or 'right' (got '{0}' instead)".format(join_type))
if (keys is None):
keys = tuple((name for name in left.dtype.names if (name in right.dtype.names)))
if (len(keys) == 0):
raise TableMergeError(u'No keys in common between left and right tables')
elif isinstance(keys, six.string_types):
keys = (keys,)
for (arr, arr_label) in ((left, u'Left'), (right, u'Right')):
for name in keys:
if (name not in arr.dtype.names):
raise TableMergeError(u'{0} table does not have key column {1!r}'.format(arr_label, name))
if (hasattr(arr[name], u'mask') and np.any(arr[name].mask)):
raise TableMergeError(u'{0} key column {1!r} has missing values'.format(arr_label, name))
left = left.ravel()
right = right.ravel()
(len_left, len_right) = (len(left), len(right))
(left_names, right_names) = (left.dtype.names, right.dtype.names)
col_name_map = get_col_name_map([left, right], keys, uniq_col_name, table_names)
out_descrs = get_descrs([left, right], col_name_map)
out_keys_dtype = [descr for descr in out_descrs if (descr[0] in keys)]
out_keys = np.empty((len_left + len_right), dtype=out_keys_dtype)
for key in keys:
out_keys[key][:len_left] = left[key]
out_keys[key][len_left:] = right[key]
idx_sort = out_keys.argsort(order=keys)
out_keys = out_keys[idx_sort]
diffs = np.concatenate(([True], (out_keys[1:] != out_keys[:(-1)]), [True]))
idxs = np.flatnonzero(diffs)
int_join_type = {u'inner': 0, u'outer': 1, u'left': 2, u'right': 3}[join_type]
(masked, n_out, left_out, left_mask, right_out, right_mask) = _np_utils.join_inner(idxs, idx_sort, len_left, int_join_type)
if any((isinstance(array, ma.MaskedArray) for array in (left, right))):
masked = True
if masked:
out = ma.empty(n_out, dtype=out_descrs)
else:
out = np.empty(n_out, dtype=out_descrs)
if (len(left) == 0):
left = left.__class__(1, dtype=left.dtype)
if (len(right) == 0):
right = right.__class__(1, dtype=right.dtype)
for (out_name, left_right_names) in six.iteritems(col_name_map):
(left_name, right_name) = left_right_names
if (left_name and right_name):
out[out_name] = np.where(right_mask, left[left_name].take(left_out), right[right_name].take(right_out))
continue
elif left_name:
(name, array, array_out, array_mask) = (left_name, left, left_out, left_mask)
elif right_name:
(name, array, array_out, array_mask) = (right_name, right, right_out, right_mask)
else:
raise TableMergeError(u'Unexpected column names (maybe one is ""?)')
out[out_name] = array[name].take(array_out, axis=0)
if masked:
if isinstance(array, ma.MaskedArray):
array_mask = (array_mask | array[name].mask.take(array_out))
out[out_name].mask = array_mask
if isinstance(_col_name_map, collections.Mapping):
_col_name_map.update(col_name_map)
return out
| [
"@",
"deprecated",
"(",
"u'1.0'",
",",
"message",
"=",
"DEPRECATION_MESSAGE",
")",
"def",
"join",
"(",
"left",
",",
"right",
",",
"keys",
"=",
"None",
",",
"join_type",
"=",
"u'inner'",
",",
"uniq_col_name",
"=",
"u'{col_name}_{table_name}'",
",",
"table_names",
"=",
"[",
"u'1'",
",",
"u'2'",
"]",
",",
"col_name_map",
"=",
"None",
")",
":",
"_col_name_map",
"=",
"col_name_map",
"if",
"(",
"join_type",
"not",
"in",
"(",
"u'inner'",
",",
"u'outer'",
",",
"u'left'",
",",
"u'right'",
")",
")",
":",
"raise",
"ValueError",
"(",
"u\"The 'join_type' argument should be in 'inner', 'outer', 'left' or 'right' (got '{0}' instead)\"",
".",
"format",
"(",
"join_type",
")",
")",
"if",
"(",
"keys",
"is",
"None",
")",
":",
"keys",
"=",
"tuple",
"(",
"(",
"name",
"for",
"name",
"in",
"left",
".",
"dtype",
".",
"names",
"if",
"(",
"name",
"in",
"right",
".",
"dtype",
".",
"names",
")",
")",
")",
"if",
"(",
"len",
"(",
"keys",
")",
"==",
"0",
")",
":",
"raise",
"TableMergeError",
"(",
"u'No keys in common between left and right tables'",
")",
"elif",
"isinstance",
"(",
"keys",
",",
"six",
".",
"string_types",
")",
":",
"keys",
"=",
"(",
"keys",
",",
")",
"for",
"(",
"arr",
",",
"arr_label",
")",
"in",
"(",
"(",
"left",
",",
"u'Left'",
")",
",",
"(",
"right",
",",
"u'Right'",
")",
")",
":",
"for",
"name",
"in",
"keys",
":",
"if",
"(",
"name",
"not",
"in",
"arr",
".",
"dtype",
".",
"names",
")",
":",
"raise",
"TableMergeError",
"(",
"u'{0} table does not have key column {1!r}'",
".",
"format",
"(",
"arr_label",
",",
"name",
")",
")",
"if",
"(",
"hasattr",
"(",
"arr",
"[",
"name",
"]",
",",
"u'mask'",
")",
"and",
"np",
".",
"any",
"(",
"arr",
"[",
"name",
"]",
".",
"mask",
")",
")",
":",
"raise",
"TableMergeError",
"(",
"u'{0} key column {1!r} has missing values'",
".",
"format",
"(",
"arr_label",
",",
"name",
")",
")",
"left",
"=",
"left",
".",
"ravel",
"(",
")",
"right",
"=",
"right",
".",
"ravel",
"(",
")",
"(",
"len_left",
",",
"len_right",
")",
"=",
"(",
"len",
"(",
"left",
")",
",",
"len",
"(",
"right",
")",
")",
"(",
"left_names",
",",
"right_names",
")",
"=",
"(",
"left",
".",
"dtype",
".",
"names",
",",
"right",
".",
"dtype",
".",
"names",
")",
"col_name_map",
"=",
"get_col_name_map",
"(",
"[",
"left",
",",
"right",
"]",
",",
"keys",
",",
"uniq_col_name",
",",
"table_names",
")",
"out_descrs",
"=",
"get_descrs",
"(",
"[",
"left",
",",
"right",
"]",
",",
"col_name_map",
")",
"out_keys_dtype",
"=",
"[",
"descr",
"for",
"descr",
"in",
"out_descrs",
"if",
"(",
"descr",
"[",
"0",
"]",
"in",
"keys",
")",
"]",
"out_keys",
"=",
"np",
".",
"empty",
"(",
"(",
"len_left",
"+",
"len_right",
")",
",",
"dtype",
"=",
"out_keys_dtype",
")",
"for",
"key",
"in",
"keys",
":",
"out_keys",
"[",
"key",
"]",
"[",
":",
"len_left",
"]",
"=",
"left",
"[",
"key",
"]",
"out_keys",
"[",
"key",
"]",
"[",
"len_left",
":",
"]",
"=",
"right",
"[",
"key",
"]",
"idx_sort",
"=",
"out_keys",
".",
"argsort",
"(",
"order",
"=",
"keys",
")",
"out_keys",
"=",
"out_keys",
"[",
"idx_sort",
"]",
"diffs",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"True",
"]",
",",
"(",
"out_keys",
"[",
"1",
":",
"]",
"!=",
"out_keys",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
",",
"[",
"True",
"]",
")",
")",
"idxs",
"=",
"np",
".",
"flatnonzero",
"(",
"diffs",
")",
"int_join_type",
"=",
"{",
"u'inner'",
":",
"0",
",",
"u'outer'",
":",
"1",
",",
"u'left'",
":",
"2",
",",
"u'right'",
":",
"3",
"}",
"[",
"join_type",
"]",
"(",
"masked",
",",
"n_out",
",",
"left_out",
",",
"left_mask",
",",
"right_out",
",",
"right_mask",
")",
"=",
"_np_utils",
".",
"join_inner",
"(",
"idxs",
",",
"idx_sort",
",",
"len_left",
",",
"int_join_type",
")",
"if",
"any",
"(",
"(",
"isinstance",
"(",
"array",
",",
"ma",
".",
"MaskedArray",
")",
"for",
"array",
"in",
"(",
"left",
",",
"right",
")",
")",
")",
":",
"masked",
"=",
"True",
"if",
"masked",
":",
"out",
"=",
"ma",
".",
"empty",
"(",
"n_out",
",",
"dtype",
"=",
"out_descrs",
")",
"else",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"n_out",
",",
"dtype",
"=",
"out_descrs",
")",
"if",
"(",
"len",
"(",
"left",
")",
"==",
"0",
")",
":",
"left",
"=",
"left",
".",
"__class__",
"(",
"1",
",",
"dtype",
"=",
"left",
".",
"dtype",
")",
"if",
"(",
"len",
"(",
"right",
")",
"==",
"0",
")",
":",
"right",
"=",
"right",
".",
"__class__",
"(",
"1",
",",
"dtype",
"=",
"right",
".",
"dtype",
")",
"for",
"(",
"out_name",
",",
"left_right_names",
")",
"in",
"six",
".",
"iteritems",
"(",
"col_name_map",
")",
":",
"(",
"left_name",
",",
"right_name",
")",
"=",
"left_right_names",
"if",
"(",
"left_name",
"and",
"right_name",
")",
":",
"out",
"[",
"out_name",
"]",
"=",
"np",
".",
"where",
"(",
"right_mask",
",",
"left",
"[",
"left_name",
"]",
".",
"take",
"(",
"left_out",
")",
",",
"right",
"[",
"right_name",
"]",
".",
"take",
"(",
"right_out",
")",
")",
"continue",
"elif",
"left_name",
":",
"(",
"name",
",",
"array",
",",
"array_out",
",",
"array_mask",
")",
"=",
"(",
"left_name",
",",
"left",
",",
"left_out",
",",
"left_mask",
")",
"elif",
"right_name",
":",
"(",
"name",
",",
"array",
",",
"array_out",
",",
"array_mask",
")",
"=",
"(",
"right_name",
",",
"right",
",",
"right_out",
",",
"right_mask",
")",
"else",
":",
"raise",
"TableMergeError",
"(",
"u'Unexpected column names (maybe one is \"\"?)'",
")",
"out",
"[",
"out_name",
"]",
"=",
"array",
"[",
"name",
"]",
".",
"take",
"(",
"array_out",
",",
"axis",
"=",
"0",
")",
"if",
"masked",
":",
"if",
"isinstance",
"(",
"array",
",",
"ma",
".",
"MaskedArray",
")",
":",
"array_mask",
"=",
"(",
"array_mask",
"|",
"array",
"[",
"name",
"]",
".",
"mask",
".",
"take",
"(",
"array_out",
")",
")",
"out",
"[",
"out_name",
"]",
".",
"mask",
"=",
"array_mask",
"if",
"isinstance",
"(",
"_col_name_map",
",",
"collections",
".",
"Mapping",
")",
":",
"_col_name_map",
".",
"update",
"(",
"col_name_map",
")",
"return",
"out"
] | joins a list with a string . | train | false |
23,352 | def pbdv_seq(v, x):
if (not (isscalar(v) and isscalar(x))):
raise ValueError('arguments must be scalars.')
n = int(v)
v0 = (v - n)
if (n < 1):
n1 = 1
else:
n1 = n
v1 = (n1 + v0)
(dv, dp, pdf, pdd) = specfun.pbdv(v1, x)
return (dv[:(n1 + 1)], dp[:(n1 + 1)])
| [
"def",
"pbdv_seq",
"(",
"v",
",",
"x",
")",
":",
"if",
"(",
"not",
"(",
"isscalar",
"(",
"v",
")",
"and",
"isscalar",
"(",
"x",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'arguments must be scalars.'",
")",
"n",
"=",
"int",
"(",
"v",
")",
"v0",
"=",
"(",
"v",
"-",
"n",
")",
"if",
"(",
"n",
"<",
"1",
")",
":",
"n1",
"=",
"1",
"else",
":",
"n1",
"=",
"n",
"v1",
"=",
"(",
"n1",
"+",
"v0",
")",
"(",
"dv",
",",
"dp",
",",
"pdf",
",",
"pdd",
")",
"=",
"specfun",
".",
"pbdv",
"(",
"v1",
",",
"x",
")",
"return",
"(",
"dv",
"[",
":",
"(",
"n1",
"+",
"1",
")",
"]",
",",
"dp",
"[",
":",
"(",
"n1",
"+",
"1",
")",
"]",
")"
] | parabolic cylinder functions dv(x) and derivatives . | train | false |
23,353 | def create_floating_ip(kwargs=None, call=None):
if (call != 'function'):
log.error('The create_floating_ip function must be called with -f or --function.')
return False
if (not kwargs):
kwargs = {}
if ('droplet_id' in kwargs):
result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post')
return result
elif ('region' in kwargs):
result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
| [
"def",
"create_floating_ip",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"log",
".",
"error",
"(",
"'The create_floating_ip function must be called with -f or --function.'",
")",
"return",
"False",
"if",
"(",
"not",
"kwargs",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"(",
"'droplet_id'",
"in",
"kwargs",
")",
":",
"result",
"=",
"query",
"(",
"method",
"=",
"'floating_ips'",
",",
"args",
"=",
"{",
"'droplet_id'",
":",
"kwargs",
"[",
"'droplet_id'",
"]",
"}",
",",
"http_method",
"=",
"'post'",
")",
"return",
"result",
"elif",
"(",
"'region'",
"in",
"kwargs",
")",
":",
"result",
"=",
"query",
"(",
"method",
"=",
"'floating_ips'",
",",
"args",
"=",
"{",
"'region'",
":",
"kwargs",
"[",
"'region'",
"]",
"}",
",",
"http_method",
"=",
"'post'",
")",
"return",
"result",
"else",
":",
"log",
".",
"error",
"(",
"'A droplet_id or region is required.'",
")",
"return",
"False"
] | create a new floating ip . | train | true |
23,356 | def parse_nick_template(string, template_regex, outtemplate):
match = template_regex.match(string)
if match:
return outtemplate.format(**match.groupdict())
return string
| [
"def",
"parse_nick_template",
"(",
"string",
",",
"template_regex",
",",
"outtemplate",
")",
":",
"match",
"=",
"template_regex",
".",
"match",
"(",
"string",
")",
"if",
"match",
":",
"return",
"outtemplate",
".",
"format",
"(",
"**",
"match",
".",
"groupdict",
"(",
")",
")",
"return",
"string"
] | parse a text using a template and map it to another template args: string : the input string to processj template_regex : a template regex created with initialize_nick_template . | train | false |
23,358 | def test_base_of_reduce_preferred():
dsk = dict(((('a', i), (f, ('a', (i - 1)), ('b', i))) for i in [1, 2, 3]))
dsk[('a', 0)] = (f, ('b', 0))
dsk.update(dict(((('b', i), (f, 'c', 1)) for i in [0, 1, 2, 3])))
dsk['c'] = 1
o = order(dsk)
assert (o == {('a', 3): 0, ('a', 2): 1, ('a', 1): 2, ('a', 0): 3, ('b', 0): 4, 'c': 5, ('b', 1): 6, ('b', 2): 7, ('b', 3): 8})
assert (min([('b', i) for i in [0, 1, 2, 3]], key=o.get) == ('b', 0))
| [
"def",
"test_base_of_reduce_preferred",
"(",
")",
":",
"dsk",
"=",
"dict",
"(",
"(",
"(",
"(",
"'a'",
",",
"i",
")",
",",
"(",
"f",
",",
"(",
"'a'",
",",
"(",
"i",
"-",
"1",
")",
")",
",",
"(",
"'b'",
",",
"i",
")",
")",
")",
"for",
"i",
"in",
"[",
"1",
",",
"2",
",",
"3",
"]",
")",
")",
"dsk",
"[",
"(",
"'a'",
",",
"0",
")",
"]",
"=",
"(",
"f",
",",
"(",
"'b'",
",",
"0",
")",
")",
"dsk",
".",
"update",
"(",
"dict",
"(",
"(",
"(",
"(",
"'b'",
",",
"i",
")",
",",
"(",
"f",
",",
"'c'",
",",
"1",
")",
")",
"for",
"i",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
")",
")",
")",
"dsk",
"[",
"'c'",
"]",
"=",
"1",
"o",
"=",
"order",
"(",
"dsk",
")",
"assert",
"(",
"o",
"==",
"{",
"(",
"'a'",
",",
"3",
")",
":",
"0",
",",
"(",
"'a'",
",",
"2",
")",
":",
"1",
",",
"(",
"'a'",
",",
"1",
")",
":",
"2",
",",
"(",
"'a'",
",",
"0",
")",
":",
"3",
",",
"(",
"'b'",
",",
"0",
")",
":",
"4",
",",
"'c'",
":",
"5",
",",
"(",
"'b'",
",",
"1",
")",
":",
"6",
",",
"(",
"'b'",
",",
"2",
")",
":",
"7",
",",
"(",
"'b'",
",",
"3",
")",
":",
"8",
"}",
")",
"assert",
"(",
"min",
"(",
"[",
"(",
"'b'",
",",
"i",
")",
"for",
"i",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
"]",
",",
"key",
"=",
"o",
".",
"get",
")",
"==",
"(",
"'b'",
",",
"0",
")",
")"
] | a3 a2 | a1 | | a0 | | | b0 b1 b2 b3 c we really want to run b0 quickly . | train | false |
23,359 | def lazy_import(scope, text, lazy_import_class=None):
proc = ImportProcessor(lazy_import_class=lazy_import_class)
return proc.lazy_import(scope, text)
| [
"def",
"lazy_import",
"(",
"scope",
",",
"text",
",",
"lazy_import_class",
"=",
"None",
")",
":",
"proc",
"=",
"ImportProcessor",
"(",
"lazy_import_class",
"=",
"lazy_import_class",
")",
"return",
"proc",
".",
"lazy_import",
"(",
"scope",
",",
"text",
")"
] | create lazy imports for all of the imports in text . | train | false |
23,360 | @node('SimpleNode')
def simple_tag(writer, node):
name = node.tag_name
if (writer.env and (name not in writer.env.filters) and (name not in writer._filters_warned)):
writer._filters_warned.add(name)
writer.warn(("Filter %s probably doesn't exist in Jinja" % name))
if (not node.vars_to_resolve):
writer.start_variable()
writer.write('request|')
writer.write(name)
writer.end_variable()
return
first_var = node.vars_to_resolve[0]
args = node.vars_to_resolve[1:]
writer.start_variable()
writer.node(first_var)
writer.write('|')
writer.write(name)
if args:
writer.write('(')
for (idx, var) in enumerate(args):
if idx:
writer.write(', ')
if var.var:
writer.node(var)
else:
writer.literal(var.literal)
writer.write(')')
writer.end_variable()
| [
"@",
"node",
"(",
"'SimpleNode'",
")",
"def",
"simple_tag",
"(",
"writer",
",",
"node",
")",
":",
"name",
"=",
"node",
".",
"tag_name",
"if",
"(",
"writer",
".",
"env",
"and",
"(",
"name",
"not",
"in",
"writer",
".",
"env",
".",
"filters",
")",
"and",
"(",
"name",
"not",
"in",
"writer",
".",
"_filters_warned",
")",
")",
":",
"writer",
".",
"_filters_warned",
".",
"add",
"(",
"name",
")",
"writer",
".",
"warn",
"(",
"(",
"\"Filter %s probably doesn't exist in Jinja\"",
"%",
"name",
")",
")",
"if",
"(",
"not",
"node",
".",
"vars_to_resolve",
")",
":",
"writer",
".",
"start_variable",
"(",
")",
"writer",
".",
"write",
"(",
"'request|'",
")",
"writer",
".",
"write",
"(",
"name",
")",
"writer",
".",
"end_variable",
"(",
")",
"return",
"first_var",
"=",
"node",
".",
"vars_to_resolve",
"[",
"0",
"]",
"args",
"=",
"node",
".",
"vars_to_resolve",
"[",
"1",
":",
"]",
"writer",
".",
"start_variable",
"(",
")",
"writer",
".",
"node",
"(",
"first_var",
")",
"writer",
".",
"write",
"(",
"'|'",
")",
"writer",
".",
"write",
"(",
"name",
")",
"if",
"args",
":",
"writer",
".",
"write",
"(",
"'('",
")",
"for",
"(",
"idx",
",",
"var",
")",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"idx",
":",
"writer",
".",
"write",
"(",
"', '",
")",
"if",
"var",
".",
"var",
":",
"writer",
".",
"node",
"(",
"var",
")",
"else",
":",
"writer",
".",
"literal",
"(",
"var",
".",
"literal",
")",
"writer",
".",
"write",
"(",
"')'",
")",
"writer",
".",
"end_variable",
"(",
")"
] | check if the simple tag exist as a filter in . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.