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
22,694
def test_bad_stuff(): import sys Assert((sys.winver != 'HIJACKED')) import re Assert((re.compile != 'HIJACKED')) try: import fooCORRUPT raise Exception('Corrupted DLL was loaded') except ImportError as e: pass import fooDLLEXE AreEqual(fooDLLEXE.Foo().BAR, 1) try: import fooEXEONLY raise Exception("*.exe's should not be autoloaded!") except ImportError as e: pass except SystemError as e: print 'Work Item #189503' try: import fooTXTDLL raise Exception("*.txt's should not be autoloaded!") except ImportError as e: pass
[ "def", "test_bad_stuff", "(", ")", ":", "import", "sys", "Assert", "(", "(", "sys", ".", "winver", "!=", "'HIJACKED'", ")", ")", "import", "re", "Assert", "(", "(", "re", ".", "compile", "!=", "'HIJACKED'", ")", ")", "try", ":", "import", "fooCORRUPT", "raise", "Exception", "(", "'Corrupted DLL was loaded'", ")", "except", "ImportError", "as", "e", ":", "pass", "import", "fooDLLEXE", "AreEqual", "(", "fooDLLEXE", ".", "Foo", "(", ")", ".", "BAR", ",", "1", ")", "try", ":", "import", "fooEXEONLY", "raise", "Exception", "(", "\"*.exe's should not be autoloaded!\"", ")", "except", "ImportError", "as", "e", ":", "pass", "except", "SystemError", "as", "e", ":", "print", "'Work Item #189503'", "try", ":", "import", "fooTXTDLL", "raise", "Exception", "(", "\"*.txt's should not be autoloaded!\"", ")", "except", "ImportError", "as", "e", ":", "pass" ]
cases where ip should not load an assembly for one reason or another .
train
false
22,695
def _variable_on_cpu(name, shape, initializer): with tf.device('/cpu:0'): dtype = (tf.float16 if FLAGS.use_fp16 else tf.float32) var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype) return var
[ "def", "_variable_on_cpu", "(", "name", ",", "shape", ",", "initializer", ")", ":", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "dtype", "=", "(", "tf", ".", "float16", "if", "FLAGS", ".", "use_fp16", "else", "tf", ".", "float32", ")", "var", "=", "tf", ".", "get_variable", "(", "name", ",", "shape", ",", "initializer", "=", "initializer", ",", "dtype", "=", "dtype", ")", "return", "var" ]
helper to create a variable stored on cpu memory .
train
true
22,696
def republish(producer, message, exchange=None, routing_key=None, remove_props=[u'application_headers', u'content_type', u'content_encoding', u'headers']): body = ensure_bytes(message.body) (info, headers, props) = (message.delivery_info, message.headers, message.properties) exchange = (info[u'exchange'] if (exchange is None) else exchange) routing_key = (info[u'routing_key'] if (routing_key is None) else routing_key) (ctype, enc) = (message.content_type, message.content_encoding) compression = headers.pop(u'compression', None) for key in remove_props: props.pop(key, None) producer.publish(ensure_bytes(body), exchange=exchange, routing_key=routing_key, compression=compression, headers=headers, content_type=ctype, content_encoding=enc, **props)
[ "def", "republish", "(", "producer", ",", "message", ",", "exchange", "=", "None", ",", "routing_key", "=", "None", ",", "remove_props", "=", "[", "u'application_headers'", ",", "u'content_type'", ",", "u'content_encoding'", ",", "u'headers'", "]", ")", ":", "body", "=", "ensure_bytes", "(", "message", ".", "body", ")", "(", "info", ",", "headers", ",", "props", ")", "=", "(", "message", ".", "delivery_info", ",", "message", ".", "headers", ",", "message", ".", "properties", ")", "exchange", "=", "(", "info", "[", "u'exchange'", "]", "if", "(", "exchange", "is", "None", ")", "else", "exchange", ")", "routing_key", "=", "(", "info", "[", "u'routing_key'", "]", "if", "(", "routing_key", "is", "None", ")", "else", "routing_key", ")", "(", "ctype", ",", "enc", ")", "=", "(", "message", ".", "content_type", ",", "message", ".", "content_encoding", ")", "compression", "=", "headers", ".", "pop", "(", "u'compression'", ",", "None", ")", "for", "key", "in", "remove_props", ":", "props", ".", "pop", "(", "key", ",", "None", ")", "producer", ".", "publish", "(", "ensure_bytes", "(", "body", ")", ",", "exchange", "=", "exchange", ",", "routing_key", "=", "routing_key", ",", "compression", "=", "compression", ",", "headers", "=", "headers", ",", "content_type", "=", "ctype", ",", "content_encoding", "=", "enc", ",", "**", "props", ")" ]
republish message .
train
false
22,697
def setup_hook(config): metadata = config['metadata'] if (sys.platform == 'win32'): requires = metadata.get('requires_dist', '').split('\n') metadata['requires_dist'] = '\n'.join(requires) config['metadata'] = metadata metadata['version'] = str(version) from pbr import packaging def my_get_script_args(*args, **kwargs): return _main_module()._orig_get_script_args(*args, **kwargs) packaging.override_get_script_args = my_get_script_args easy_install.get_script_args = my_get_script_args orig_get_version = packaging.get_version def my_get_version(package_name, pre_version=None): if (package_name == 'ryu'): return str(version) return orig_get_version(package_name, pre_version) packaging.get_version = my_get_version
[ "def", "setup_hook", "(", "config", ")", ":", "metadata", "=", "config", "[", "'metadata'", "]", "if", "(", "sys", ".", "platform", "==", "'win32'", ")", ":", "requires", "=", "metadata", ".", "get", "(", "'requires_dist'", ",", "''", ")", ".", "split", "(", "'\\n'", ")", "metadata", "[", "'requires_dist'", "]", "=", "'\\n'", ".", "join", "(", "requires", ")", "config", "[", "'metadata'", "]", "=", "metadata", "metadata", "[", "'version'", "]", "=", "str", "(", "version", ")", "from", "pbr", "import", "packaging", "def", "my_get_script_args", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "_main_module", "(", ")", ".", "_orig_get_script_args", "(", "*", "args", ",", "**", "kwargs", ")", "packaging", ".", "override_get_script_args", "=", "my_get_script_args", "easy_install", ".", "get_script_args", "=", "my_get_script_args", "orig_get_version", "=", "packaging", ".", "get_version", "def", "my_get_version", "(", "package_name", ",", "pre_version", "=", "None", ")", ":", "if", "(", "package_name", "==", "'ryu'", ")", ":", "return", "str", "(", "version", ")", "return", "orig_get_version", "(", "package_name", ",", "pre_version", ")", "packaging", ".", "get_version", "=", "my_get_version" ]
filter config parsed from a setup .
train
true
22,698
def update_merge_tags(mailchimp, list_id, tag_names): mc_vars = mailchimp.listMergeVars(id=list_id) mc_names = set((v['name'] for v in mc_vars)) mc_merge = mailchimp.listMergeVarAdd tags = [v['tag'] for v in mc_vars] for name in tag_names: tag = name_to_tag(name) if ('FULLNAME' not in tags): result = mc_merge(id=list_id, tag='FULLNAME', name='Full Name', options={'field_type': 'text', 'public': False}) tags.append('FULLNAME') log.debug(result) if ((name not in mc_names) and (tag not in ['EMAIL', 'FULLNAME'])): ftype = FIELD_TYPES.get(name, 'number') result = mc_merge(id=list_id, tag=tag, name=name, options={'field_type': ftype, 'public': False}) tags.append(tag) log.debug(result)
[ "def", "update_merge_tags", "(", "mailchimp", ",", "list_id", ",", "tag_names", ")", ":", "mc_vars", "=", "mailchimp", ".", "listMergeVars", "(", "id", "=", "list_id", ")", "mc_names", "=", "set", "(", "(", "v", "[", "'name'", "]", "for", "v", "in", "mc_vars", ")", ")", "mc_merge", "=", "mailchimp", ".", "listMergeVarAdd", "tags", "=", "[", "v", "[", "'tag'", "]", "for", "v", "in", "mc_vars", "]", "for", "name", "in", "tag_names", ":", "tag", "=", "name_to_tag", "(", "name", ")", "if", "(", "'FULLNAME'", "not", "in", "tags", ")", ":", "result", "=", "mc_merge", "(", "id", "=", "list_id", ",", "tag", "=", "'FULLNAME'", ",", "name", "=", "'Full Name'", ",", "options", "=", "{", "'field_type'", ":", "'text'", ",", "'public'", ":", "False", "}", ")", "tags", ".", "append", "(", "'FULLNAME'", ")", "log", ".", "debug", "(", "result", ")", "if", "(", "(", "name", "not", "in", "mc_names", ")", "and", "(", "tag", "not", "in", "[", "'EMAIL'", ",", "'FULLNAME'", "]", ")", ")", ":", "ftype", "=", "FIELD_TYPES", ".", "get", "(", "name", ",", "'number'", ")", "result", "=", "mc_merge", "(", "id", "=", "list_id", ",", "tag", "=", "tag", ",", "name", "=", "name", ",", "options", "=", "{", "'field_type'", ":", "ftype", ",", "'public'", ":", "False", "}", ")", "tags", ".", "append", "(", "tag", ")", "log", ".", "debug", "(", "result", ")" ]
this function is rather inscrutable .
train
false
22,699
def evalUnits(unitStr): pass
[ "def", "evalUnits", "(", "unitStr", ")", ":", "pass" ]
evaluate a unit string into examples: n m/s^2 => a*s / v => .
train
false
22,701
def update_feed(doc, method=None): if (frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_import): return if ((doc._action != u'save') or doc.flags.ignore_feed): return if ((doc.doctype == u'Communication') or doc.meta.issingle): return if hasattr(doc, u'get_feed'): feed = doc.get_feed() if feed: if isinstance(feed, basestring): feed = {u'subject': feed} feed = frappe._dict(feed) doctype = (feed.doctype or doc.doctype) name = (feed.name or doc.name) frappe.db.sql(u"delete from `tabCommunication`\n DCTB DCTB DCTB DCTB where\n DCTB DCTB DCTB DCTB DCTB reference_doctype=%s and reference_name=%s\n DCTB DCTB DCTB DCTB DCTB and communication_type='Comment'\n DCTB DCTB DCTB DCTB DCTB and comment_type='Updated'", (doctype, name)) frappe.get_doc({u'doctype': u'Communication', u'communication_type': u'Comment', u'comment_type': u'Updated', u'reference_doctype': doctype, u'reference_name': name, u'subject': feed.subject, u'full_name': get_fullname(doc.owner), u'reference_owner': frappe.db.get_value(doctype, name, u'owner'), u'link_doctype': feed.link_doctype, u'link_name': feed.link_name}).insert(ignore_permissions=True)
[ "def", "update_feed", "(", "doc", ",", "method", "=", "None", ")", ":", "if", "(", "frappe", ".", "flags", ".", "in_patch", "or", "frappe", ".", "flags", ".", "in_install", "or", "frappe", ".", "flags", ".", "in_import", ")", ":", "return", "if", "(", "(", "doc", ".", "_action", "!=", "u'save'", ")", "or", "doc", ".", "flags", ".", "ignore_feed", ")", ":", "return", "if", "(", "(", "doc", ".", "doctype", "==", "u'Communication'", ")", "or", "doc", ".", "meta", ".", "issingle", ")", ":", "return", "if", "hasattr", "(", "doc", ",", "u'get_feed'", ")", ":", "feed", "=", "doc", ".", "get_feed", "(", ")", "if", "feed", ":", "if", "isinstance", "(", "feed", ",", "basestring", ")", ":", "feed", "=", "{", "u'subject'", ":", "feed", "}", "feed", "=", "frappe", ".", "_dict", "(", "feed", ")", "doctype", "=", "(", "feed", ".", "doctype", "or", "doc", ".", "doctype", ")", "name", "=", "(", "feed", ".", "name", "or", "doc", ".", "name", ")", "frappe", ".", "db", ".", "sql", "(", "u\"delete from `tabCommunication`\\n DCTB DCTB DCTB DCTB where\\n DCTB DCTB DCTB DCTB DCTB reference_doctype=%s and reference_name=%s\\n DCTB DCTB DCTB DCTB DCTB and communication_type='Comment'\\n DCTB DCTB DCTB DCTB DCTB and comment_type='Updated'\"", ",", "(", "doctype", ",", "name", ")", ")", "frappe", ".", "get_doc", "(", "{", "u'doctype'", ":", "u'Communication'", ",", "u'communication_type'", ":", "u'Comment'", ",", "u'comment_type'", ":", "u'Updated'", ",", "u'reference_doctype'", ":", "doctype", ",", "u'reference_name'", ":", "name", ",", "u'subject'", ":", "feed", ".", "subject", ",", "u'full_name'", ":", "get_fullname", "(", "doc", ".", "owner", ")", ",", "u'reference_owner'", ":", "frappe", ".", "db", ".", "get_value", "(", "doctype", ",", "name", ",", "u'owner'", ")", ",", "u'link_doctype'", ":", "feed", ".", "link_doctype", ",", "u'link_name'", ":", "feed", ".", "link_name", "}", ")", ".", "insert", "(", "ignore_permissions", "=", "True", ")" ]
save updated feed into path provided as argument .
train
false
22,702
def ColorfulPyPrint_set_verbose_level(verbose_level=1): global O_VERBOSE_LEVEL O_VERBOSE_LEVEL = verbose_level return O_VERBOSE_LEVEL
[ "def", "ColorfulPyPrint_set_verbose_level", "(", "verbose_level", "=", "1", ")", ":", "global", "O_VERBOSE_LEVEL", "O_VERBOSE_LEVEL", "=", "verbose_level", "return", "O_VERBOSE_LEVEL" ]
set output verbose level :type verbose_level: int .
train
false
22,703
def solr_literal(t): return ((u'"' + t.replace(u'"', u'')) + u'"')
[ "def", "solr_literal", "(", "t", ")", ":", "return", "(", "(", "u'\"'", "+", "t", ".", "replace", "(", "u'\"'", ",", "u''", ")", ")", "+", "u'\"'", ")" ]
return a safe literal string for a solr query .
train
false
22,704
def handle_conflicts(conflict_type='object'): _conflict_msg = 'Conflict %(conflict_type)s: %(details)s' def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): try: return method(*args, **kwargs) except db_exception.DBDuplicateEntry as e: LOG.debug(_conflict_msg, {'conflict_type': conflict_type, 'details': six.text_type(e)}) name = None field = None domain_id = None params = args[1:] for arg in params: if ('name' in arg): field = 'name' name = arg['name'] elif ('id' in arg): field = 'ID' name = arg['id'] if ('domain_id' in arg): domain_id = arg['domain_id'] msg = _('Duplicate entry') if (name and domain_id): msg = (_('Duplicate entry found with %(field)s %(name)s at domain ID %(domain_id)s') % {'field': field, 'name': name, 'domain_id': domain_id}) elif name: msg = (_('Duplicate entry found with %(field)s %(name)s') % {'field': field, 'name': name}) elif domain_id: msg = (_('Duplicate entry at domain ID %s') % domain_id) raise exception.Conflict(type=conflict_type, details=msg) except db_exception.DBError as e: if isinstance(e.inner_exception, IntegrityError): LOG.debug(_conflict_msg, {'conflict_type': conflict_type, 'details': six.text_type(e)}) raise exception.UnexpectedError((_('An unexpected error occurred when trying to store %s') % conflict_type)) raise return wrapper return decorator
[ "def", "handle_conflicts", "(", "conflict_type", "=", "'object'", ")", ":", "_conflict_msg", "=", "'Conflict %(conflict_type)s: %(details)s'", "def", "decorator", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "method", "(", "*", "args", ",", "**", "kwargs", ")", "except", "db_exception", ".", "DBDuplicateEntry", "as", "e", ":", "LOG", ".", "debug", "(", "_conflict_msg", ",", "{", "'conflict_type'", ":", "conflict_type", ",", "'details'", ":", "six", ".", "text_type", "(", "e", ")", "}", ")", "name", "=", "None", "field", "=", "None", "domain_id", "=", "None", "params", "=", "args", "[", "1", ":", "]", "for", "arg", "in", "params", ":", "if", "(", "'name'", "in", "arg", ")", ":", "field", "=", "'name'", "name", "=", "arg", "[", "'name'", "]", "elif", "(", "'id'", "in", "arg", ")", ":", "field", "=", "'ID'", "name", "=", "arg", "[", "'id'", "]", "if", "(", "'domain_id'", "in", "arg", ")", ":", "domain_id", "=", "arg", "[", "'domain_id'", "]", "msg", "=", "_", "(", "'Duplicate entry'", ")", "if", "(", "name", "and", "domain_id", ")", ":", "msg", "=", "(", "_", "(", "'Duplicate entry found with %(field)s %(name)s at domain ID %(domain_id)s'", ")", "%", "{", "'field'", ":", "field", ",", "'name'", ":", "name", ",", "'domain_id'", ":", "domain_id", "}", ")", "elif", "name", ":", "msg", "=", "(", "_", "(", "'Duplicate entry found with %(field)s %(name)s'", ")", "%", "{", "'field'", ":", "field", ",", "'name'", ":", "name", "}", ")", "elif", "domain_id", ":", "msg", "=", "(", "_", "(", "'Duplicate entry at domain ID %s'", ")", "%", "domain_id", ")", "raise", "exception", ".", "Conflict", "(", "type", "=", "conflict_type", ",", "details", "=", "msg", ")", "except", "db_exception", ".", "DBError", "as", "e", ":", "if", "isinstance", "(", "e", ".", "inner_exception", ",", "IntegrityError", ")", ":", "LOG", ".", "debug", "(", "_conflict_msg", ",", "{", "'conflict_type'", ":", "conflict_type", ",", "'details'", ":", "six", ".", "text_type", "(", "e", ")", "}", ")", "raise", "exception", ".", "UnexpectedError", "(", "(", "_", "(", "'An unexpected error occurred when trying to store %s'", ")", "%", "conflict_type", ")", ")", "raise", "return", "wrapper", "return", "decorator" ]
converts integrityerror into http 409 conflict .
train
false
22,706
def find_package_data(): package_data = {'IPython.core': ['profile/README*'], 'IPython.core.tests': ['*.png', '*.jpg', 'daft_extension/*.py'], 'IPython.lib.tests': ['*.wav'], 'IPython.testing.plugin': ['*.txt']} return package_data
[ "def", "find_package_data", "(", ")", ":", "package_data", "=", "{", "'IPython.core'", ":", "[", "'profile/README*'", "]", ",", "'IPython.core.tests'", ":", "[", "'*.png'", ",", "'*.jpg'", ",", "'daft_extension/*.py'", "]", ",", "'IPython.lib.tests'", ":", "[", "'*.wav'", "]", ",", "'IPython.testing.plugin'", ":", "[", "'*.txt'", "]", "}", "return", "package_data" ]
for a list of packages .
train
false
22,707
def localize_common(obj, trans): if ('label' in trans): obj.label = trans['label'] if ('description' in trans): obj.description = trans['description']
[ "def", "localize_common", "(", "obj", ",", "trans", ")", ":", "if", "(", "'label'", "in", "trans", ")", ":", "obj", ".", "label", "=", "trans", "[", "'label'", "]", "if", "(", "'description'", "in", "trans", ")", ":", "obj", ".", "description", "=", "trans", "[", "'description'", "]" ]
localize common attributes: label and description .
train
false
22,708
def _cast_other(binary_op): def cast_op(self, other): 'A wrapped binary operator that can handle non-Expression arguments.\n ' other = self.cast_to_const(other) return binary_op(self, other) return cast_op
[ "def", "_cast_other", "(", "binary_op", ")", ":", "def", "cast_op", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "cast_to_const", "(", "other", ")", "return", "binary_op", "(", "self", ",", "other", ")", "return", "cast_op" ]
casts the second argument of a binary operator as an expression .
train
false
22,709
def fromstring(*args, **kwargs): global ET _bootstrap() return ET.fromstring(*args, **kwargs)
[ "def", "fromstring", "(", "*", "args", ",", "**", "kwargs", ")", ":", "global", "ET", "_bootstrap", "(", ")", "return", "ET", ".", "fromstring", "(", "*", "args", ",", "**", "kwargs", ")" ]
return a dom representation of the string .
train
false
22,710
@lazyobject def SetConsoleCursorPosition(): sccp = ctypes.windll.kernel32.SetConsoleCursorPosition sccp.errcheck = check_zero sccp.argtypes = (HANDLE, COORD) sccp.restype = BOOL return sccp
[ "@", "lazyobject", "def", "SetConsoleCursorPosition", "(", ")", ":", "sccp", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "SetConsoleCursorPosition", "sccp", ".", "errcheck", "=", "check_zero", "sccp", ".", "argtypes", "=", "(", "HANDLE", ",", "COORD", ")", "sccp", ".", "restype", "=", "BOOL", "return", "sccp" ]
set cursor position in console .
train
false
22,711
def test_nm1_sample_wt_fit(): ratio = 'auto' nm1 = NearMiss(ratio=ratio, random_state=RND_SEED, version=VERSION_NEARMISS) assert_raises(RuntimeError, nm1.sample, X, Y)
[ "def", "test_nm1_sample_wt_fit", "(", ")", ":", "ratio", "=", "'auto'", "nm1", "=", "NearMiss", "(", "ratio", "=", "ratio", ",", "random_state", "=", "RND_SEED", ",", "version", "=", "VERSION_NEARMISS", ")", "assert_raises", "(", "RuntimeError", ",", "nm1", ".", "sample", ",", "X", ",", "Y", ")" ]
test either if an error is raised when sample is called before fitting .
train
false
22,716
def getCentersFromLoopDirection(isWiddershins, loop, radius): centers = getCentersFromLoop(loop, radius) return getLoopsFromLoopsDirection(isWiddershins, centers)
[ "def", "getCentersFromLoopDirection", "(", "isWiddershins", ",", "loop", ",", "radius", ")", ":", "centers", "=", "getCentersFromLoop", "(", "loop", ",", "radius", ")", "return", "getLoopsFromLoopsDirection", "(", "isWiddershins", ",", "centers", ")" ]
get the centers of the loop which go around in the given direction .
train
false
22,717
def pkgPath(root, path, rpath='/'): global data_files if (not os.path.exists(path)): return files = [] for spath in os.listdir(path): if (spath == 'test'): continue subpath = os.path.join(path, spath) spath = os.path.join(rpath, spath) if os.path.isfile(subpath): files.append(subpath) if os.path.isdir(subpath): pkgPath(root, subpath, spath) data_files.append(((root + rpath), files))
[ "def", "pkgPath", "(", "root", ",", "path", ",", "rpath", "=", "'/'", ")", ":", "global", "data_files", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ")", ":", "return", "files", "=", "[", "]", "for", "spath", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "(", "spath", "==", "'test'", ")", ":", "continue", "subpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "spath", ")", "spath", "=", "os", ".", "path", ".", "join", "(", "rpath", ",", "spath", ")", "if", "os", ".", "path", ".", "isfile", "(", "subpath", ")", ":", "files", ".", "append", "(", "subpath", ")", "if", "os", ".", "path", ".", "isdir", "(", "subpath", ")", ":", "pkgPath", "(", "root", ",", "subpath", ",", "spath", ")", "data_files", ".", "append", "(", "(", "(", "root", "+", "rpath", ")", ",", "files", ")", ")" ]
package up a path recursively .
train
true
22,718
def get_md5sum(src_file): with open(src_file, 'rb') as src_data: src_content = src_data.read() src_md5 = hashlib.md5(src_content).hexdigest() return src_md5
[ "def", "get_md5sum", "(", "src_file", ")", ":", "with", "open", "(", "src_file", ",", "'rb'", ")", "as", "src_data", ":", "src_content", "=", "src_data", ".", "read", "(", ")", "src_md5", "=", "hashlib", ".", "md5", "(", "src_content", ")", ".", "hexdigest", "(", ")", "return", "src_md5" ]
returns md5sum of file .
train
true
22,719
def FindUnixSocket(): for path in _POTENTIAL_SOCKET_LOCATIONS: if os.path.exists(path): return path
[ "def", "FindUnixSocket", "(", ")", ":", "for", "path", "in", "_POTENTIAL_SOCKET_LOCATIONS", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path" ]
find the unix socket for mysql by scanning some known locations .
train
false
22,720
def _get_defaults(func): code = func.__code__ pos_count = code.co_argcount arg_names = code.co_varnames arg_names = arg_names[:pos_count] defaults = (func.__defaults__ or ()) kwdefaults = func.__kwdefaults__ res = (dict(kwdefaults) if kwdefaults else {}) pos_offset = (pos_count - len(defaults)) for (name, value) in zip(arg_names[pos_offset:], defaults): assert (name not in res) res[name] = value return res
[ "def", "_get_defaults", "(", "func", ")", ":", "code", "=", "func", ".", "__code__", "pos_count", "=", "code", ".", "co_argcount", "arg_names", "=", "code", ".", "co_varnames", "arg_names", "=", "arg_names", "[", ":", "pos_count", "]", "defaults", "=", "(", "func", ".", "__defaults__", "or", "(", ")", ")", "kwdefaults", "=", "func", ".", "__kwdefaults__", "res", "=", "(", "dict", "(", "kwdefaults", ")", "if", "kwdefaults", "else", "{", "}", ")", "pos_offset", "=", "(", "pos_count", "-", "len", "(", "defaults", ")", ")", "for", "(", "name", ",", "value", ")", "in", "zip", "(", "arg_names", "[", "pos_offset", ":", "]", ",", "defaults", ")", ":", "assert", "(", "name", "not", "in", "res", ")", "res", "[", "name", "]", "=", "value", "return", "res" ]
internal helper to extract the default arguments .
train
true
22,721
@request_cached def get_cached_discussion_key(course_id, discussion_id): try: mapping = CourseStructure.objects.get(course_id=course_id).discussion_id_map if (not mapping): raise DiscussionIdMapIsNotCached() return mapping.get(discussion_id) except CourseStructure.DoesNotExist: raise DiscussionIdMapIsNotCached()
[ "@", "request_cached", "def", "get_cached_discussion_key", "(", "course_id", ",", "discussion_id", ")", ":", "try", ":", "mapping", "=", "CourseStructure", ".", "objects", ".", "get", "(", "course_id", "=", "course_id", ")", ".", "discussion_id_map", "if", "(", "not", "mapping", ")", ":", "raise", "DiscussionIdMapIsNotCached", "(", ")", "return", "mapping", ".", "get", "(", "discussion_id", ")", "except", "CourseStructure", ".", "DoesNotExist", ":", "raise", "DiscussionIdMapIsNotCached", "(", ")" ]
returns the usage key of the discussion xblock associated with discussion_id if it is cached .
train
false
22,722
def cr_uid_records_context(method): method._api = 'cr_uid_records_context' return method
[ "def", "cr_uid_records_context", "(", "method", ")", ":", "method", ".", "_api", "=", "'cr_uid_records_context'", "return", "method" ]
decorate a traditional-style method that takes cr .
train
false
22,723
def _create_blockdevice_id_for_test(dataset_id): return ('blockdevice-' + unicode(dataset_id))
[ "def", "_create_blockdevice_id_for_test", "(", "dataset_id", ")", ":", "return", "(", "'blockdevice-'", "+", "unicode", "(", "dataset_id", ")", ")" ]
generates a blockdevice_id from a dataset_id for tests that do not use an iblockdeviceapi .
train
false
22,725
def callUser(acc): try: getUserName() except: _skypeError() return skype(('CALL ' + acc))
[ "def", "callUser", "(", "acc", ")", ":", "try", ":", "getUserName", "(", ")", "except", ":", "_skypeError", "(", ")", "return", "skype", "(", "(", "'CALL '", "+", "acc", ")", ")" ]
call some user .
train
false
22,726
def get_cursor_offset(fd=1): csbi = get_console_screen_buffer_info(fd=fd) pos = csbi.dwCursorPosition size = csbi.dwSize return ((pos.Y * size.X) + pos.X)
[ "def", "get_cursor_offset", "(", "fd", "=", "1", ")", ":", "csbi", "=", "get_console_screen_buffer_info", "(", "fd", "=", "fd", ")", "pos", "=", "csbi", ".", "dwCursorPosition", "size", "=", "csbi", ".", "dwSize", "return", "(", "(", "pos", ".", "Y", "*", "size", ".", "X", ")", "+", "pos", ".", "X", ")" ]
gets the current cursor position as a total offset value .
train
false
22,728
def _deprecateGetPageClasses(): for klass in [HTTPPageGetter, HTTPPageDownloader, HTTPClientFactory, HTTPDownloader]: deprecatedModuleAttribute(Version('Twisted', 16, 7, 0), getDeprecationWarningString(klass, Version('Twisted', 16, 7, 0), replacement=_GETPAGE_REPLACEMENT_TEXT).split('; ')[1], klass.__module__, klass.__name__)
[ "def", "_deprecateGetPageClasses", "(", ")", ":", "for", "klass", "in", "[", "HTTPPageGetter", ",", "HTTPPageDownloader", ",", "HTTPClientFactory", ",", "HTTPDownloader", "]", ":", "deprecatedModuleAttribute", "(", "Version", "(", "'Twisted'", ",", "16", ",", "7", ",", "0", ")", ",", "getDeprecationWarningString", "(", "klass", ",", "Version", "(", "'Twisted'", ",", "16", ",", "7", ",", "0", ")", ",", "replacement", "=", "_GETPAGE_REPLACEMENT_TEXT", ")", ".", "split", "(", "'; '", ")", "[", "1", "]", ",", "klass", ".", "__module__", ",", "klass", ".", "__name__", ")" ]
mark the protocols and factories associated with l{getpage} and l{downloadpage} as deprecated .
train
false
22,729
def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if ('oauth_token' not in url.params): return None scopes = [] if (scopes_param_prefix in url.params): scopes = url.params[scopes_param_prefix].split(' ') token_key = url.params['oauth_token'] token = OAuthToken(key=token_key, scopes=scopes) return token
[ "def", "OAuthTokenFromUrl", "(", "url", ",", "scopes_param_prefix", "=", "'oauth_token_scope'", ")", ":", "if", "isinstance", "(", "url", ",", "(", "str", ",", "unicode", ")", ")", ":", "url", "=", "atom", ".", "url", ".", "parse_url", "(", "url", ")", "if", "(", "'oauth_token'", "not", "in", "url", ".", "params", ")", ":", "return", "None", "scopes", "=", "[", "]", "if", "(", "scopes_param_prefix", "in", "url", ".", "params", ")", ":", "scopes", "=", "url", ".", "params", "[", "scopes_param_prefix", "]", ".", "split", "(", "' '", ")", "token_key", "=", "url", ".", "params", "[", "'oauth_token'", "]", "token", "=", "OAuthToken", "(", "key", "=", "token_key", ",", "scopes", "=", "scopes", ")", "return", "token" ]
creates an oauthtoken and sets token key and scopes from url .
train
false
22,732
def dfs_predecessors(G, source=None): return dict(((t, s) for (s, t) in dfs_edges(G, source=source)))
[ "def", "dfs_predecessors", "(", "G", ",", "source", "=", "None", ")", ":", "return", "dict", "(", "(", "(", "t", ",", "s", ")", "for", "(", "s", ",", "t", ")", "in", "dfs_edges", "(", "G", ",", "source", "=", "source", ")", ")", ")" ]
return dictionary of predecessors in depth-first-search from source .
train
false
22,733
def from_rdata(ttl, *rdatas): return from_rdata_list(ttl, rdatas)
[ "def", "from_rdata", "(", "ttl", ",", "*", "rdatas", ")", ":", "return", "from_rdata_list", "(", "ttl", ",", "rdatas", ")" ]
create an rdataset with the specified ttl .
train
false
22,734
def setup_standalone_signals(instance): window = instance.get_widget('config-window') window.connect('delete-event', gtk.main_quit) button = instance.get_widget('button1') button.handler_block_by_func(instance.gtk_widget_destroy) button.connect('clicked', gtk.main_quit) return instance
[ "def", "setup_standalone_signals", "(", "instance", ")", ":", "window", "=", "instance", ".", "get_widget", "(", "'config-window'", ")", "window", ".", "connect", "(", "'delete-event'", ",", "gtk", ".", "main_quit", ")", "button", "=", "instance", ".", "get_widget", "(", "'button1'", ")", "button", ".", "handler_block_by_func", "(", "instance", ".", "gtk_widget_destroy", ")", "button", ".", "connect", "(", "'clicked'", ",", "gtk", ".", "main_quit", ")", "return", "instance" ]
called when prefs dialog is running in standalone mode .
train
true
22,735
def multiping(netsize, chunksize, seconds): topo = SingleSwitchTopo(netsize) net = Mininet(topo=topo) net.start() hosts = net.hosts subnets = chunks(hosts, chunksize) fds = [host.stdout.fileno() for host in hosts] poller = poll() for fd in fds: poller.register(fd, POLLIN) for subnet in subnets: ips = [host.IP() for host in subnet] ips.append('10.0.0.200') for host in subnet: startpings(host, ips) endTime = (time() + seconds) while (time() < endTime): readable = poller.poll(1000) for (fd, _mask) in readable: node = Node.outToNode[fd] info(('%s:' % node.name), node.monitor().strip(), '\n') for host in hosts: host.cmd('kill %while') net.stop()
[ "def", "multiping", "(", "netsize", ",", "chunksize", ",", "seconds", ")", ":", "topo", "=", "SingleSwitchTopo", "(", "netsize", ")", "net", "=", "Mininet", "(", "topo", "=", "topo", ")", "net", ".", "start", "(", ")", "hosts", "=", "net", ".", "hosts", "subnets", "=", "chunks", "(", "hosts", ",", "chunksize", ")", "fds", "=", "[", "host", ".", "stdout", ".", "fileno", "(", ")", "for", "host", "in", "hosts", "]", "poller", "=", "poll", "(", ")", "for", "fd", "in", "fds", ":", "poller", ".", "register", "(", "fd", ",", "POLLIN", ")", "for", "subnet", "in", "subnets", ":", "ips", "=", "[", "host", ".", "IP", "(", ")", "for", "host", "in", "subnet", "]", "ips", ".", "append", "(", "'10.0.0.200'", ")", "for", "host", "in", "subnet", ":", "startpings", "(", "host", ",", "ips", ")", "endTime", "=", "(", "time", "(", ")", "+", "seconds", ")", "while", "(", "time", "(", ")", "<", "endTime", ")", ":", "readable", "=", "poller", ".", "poll", "(", "1000", ")", "for", "(", "fd", ",", "_mask", ")", "in", "readable", ":", "node", "=", "Node", ".", "outToNode", "[", "fd", "]", "info", "(", "(", "'%s:'", "%", "node", ".", "name", ")", ",", "node", ".", "monitor", "(", ")", ".", "strip", "(", ")", ",", "'\\n'", ")", "for", "host", "in", "hosts", ":", "host", ".", "cmd", "(", "'kill %while'", ")", "net", ".", "stop", "(", ")" ]
ping subsets of size chunksize in net of size netsize .
train
false
22,736
def is_course_blocked(request, redeemed_registration_codes, course_key): blocked = False for redeemed_registration in redeemed_registration_codes: if redeemed_registration.invoice_item: if (not redeemed_registration.invoice_item.invoice.is_valid): blocked = True Optout.objects.get_or_create(user=request.user, course_id=course_key) log.info(u'User %s (%s) opted out of receiving emails from course %s', request.user.username, request.user.email, course_key) track.views.server_track(request, 'change-email1-settings', {'receive_emails': 'no', 'course': course_key.to_deprecated_string()}, page='dashboard') break return blocked
[ "def", "is_course_blocked", "(", "request", ",", "redeemed_registration_codes", ",", "course_key", ")", ":", "blocked", "=", "False", "for", "redeemed_registration", "in", "redeemed_registration_codes", ":", "if", "redeemed_registration", ".", "invoice_item", ":", "if", "(", "not", "redeemed_registration", ".", "invoice_item", ".", "invoice", ".", "is_valid", ")", ":", "blocked", "=", "True", "Optout", ".", "objects", ".", "get_or_create", "(", "user", "=", "request", ".", "user", ",", "course_id", "=", "course_key", ")", "log", ".", "info", "(", "u'User %s (%s) opted out of receiving emails from course %s'", ",", "request", ".", "user", ".", "username", ",", "request", ".", "user", ".", "email", ",", "course_key", ")", "track", ".", "views", ".", "server_track", "(", "request", ",", "'change-email1-settings'", ",", "{", "'receive_emails'", ":", "'no'", ",", "'course'", ":", "course_key", ".", "to_deprecated_string", "(", ")", "}", ",", "page", "=", "'dashboard'", ")", "break", "return", "blocked" ]
checking either registration is blocked or not .
train
false
22,737
def cleanedUpClassificationNetwork(original_network, num_categories): network = caffe_pb2.NetParameter() network.CopyFrom(original_network) for (i, layer) in enumerate(network.layer): if ('Data' in layer.type): assert (layer.type in ['Data', 'HDF5Data']), ('Unsupported data layer type %s' % layer.type) elif (layer.type == 'Input'): del network.layer[i] elif (layer.type == 'Accuracy'): if (layer.accuracy_param.HasField('top_k') and (layer.accuracy_param.top_k > num_categories)): del network.layer[i] elif (layer.type == 'InnerProduct'): if (not layer.inner_product_param.HasField('num_output')): layer.inner_product_param.num_output = num_categories return network
[ "def", "cleanedUpClassificationNetwork", "(", "original_network", ",", "num_categories", ")", ":", "network", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "network", ".", "CopyFrom", "(", "original_network", ")", "for", "(", "i", ",", "layer", ")", "in", "enumerate", "(", "network", ".", "layer", ")", ":", "if", "(", "'Data'", "in", "layer", ".", "type", ")", ":", "assert", "(", "layer", ".", "type", "in", "[", "'Data'", ",", "'HDF5Data'", "]", ")", ",", "(", "'Unsupported data layer type %s'", "%", "layer", ".", "type", ")", "elif", "(", "layer", ".", "type", "==", "'Input'", ")", ":", "del", "network", ".", "layer", "[", "i", "]", "elif", "(", "layer", ".", "type", "==", "'Accuracy'", ")", ":", "if", "(", "layer", ".", "accuracy_param", ".", "HasField", "(", "'top_k'", ")", "and", "(", "layer", ".", "accuracy_param", ".", "top_k", ">", "num_categories", ")", ")", ":", "del", "network", ".", "layer", "[", "i", "]", "elif", "(", "layer", ".", "type", "==", "'InnerProduct'", ")", ":", "if", "(", "not", "layer", ".", "inner_product_param", ".", "HasField", "(", "'num_output'", ")", ")", ":", "layer", ".", "inner_product_param", ".", "num_output", "=", "num_categories", "return", "network" ]
perform a few cleanup routines on a classification network returns a new netparameter .
train
false
22,740
def get_transversals(base, gens): if (not base): return [] stabs = _distribute_gens_by_base(base, gens) (orbits, transversals) = _orbits_transversals_from_bsgs(base, stabs) transversals = [{x: h._array_form for (x, h) in y.items()} for y in transversals] return transversals
[ "def", "get_transversals", "(", "base", ",", "gens", ")", ":", "if", "(", "not", "base", ")", ":", "return", "[", "]", "stabs", "=", "_distribute_gens_by_base", "(", "base", ",", "gens", ")", "(", "orbits", ",", "transversals", ")", "=", "_orbits_transversals_from_bsgs", "(", "base", ",", "stabs", ")", "transversals", "=", "[", "{", "x", ":", "h", ".", "_array_form", "for", "(", "x", ",", "h", ")", "in", "y", ".", "items", "(", ")", "}", "for", "y", "in", "transversals", "]", "return", "transversals" ]
return transversals for the group with bsgs base .
train
false
22,741
def delete_address(kwargs=None, call=None): if (call != 'function'): raise SaltCloudSystemExit('The delete_address function must be called with -f or --function.') if ((not kwargs) or ('name' not in kwargs)): log.error('A name must be specified when deleting an address.') return False if ((not kwargs) or ('region' not in kwargs)): log.error('A region must be specified when deleting an address.') return False name = kwargs['name'] ex_region = kwargs['region'] conn = get_conn() __utils__['cloud.fire_event']('event', 'delete address', 'salt/cloud/address/deleting', args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) try: result = conn.ex_destroy_address(conn.ex_get_address(name, ex_region)) except ResourceNotFoundError as exc: log.error('Address {0} could not be found (region {1})\nThe following exception was thrown by libcloud:\n{2}'.format(name, ex_region, exc), exc_info_on_loglevel=logging.DEBUG) return False __utils__['cloud.fire_event']('event', 'deleted address', 'salt/cloud/address/deleted', args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport']) log.info(('Deleted GCE Address ' + name)) return result
[ "def", "delete_address", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'function'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The delete_address function must be called with -f or --function.'", ")", "if", "(", "(", "not", "kwargs", ")", "or", "(", "'name'", "not", "in", "kwargs", ")", ")", ":", "log", ".", "error", "(", "'A name must be specified when deleting an address.'", ")", "return", "False", "if", "(", "(", "not", "kwargs", ")", "or", "(", "'region'", "not", "in", "kwargs", ")", ")", ":", "log", ".", "error", "(", "'A region must be specified when deleting an address.'", ")", "return", "False", "name", "=", "kwargs", "[", "'name'", "]", "ex_region", "=", "kwargs", "[", "'region'", "]", "conn", "=", "get_conn", "(", ")", "__utils__", "[", "'cloud.fire_event'", "]", "(", "'event'", ",", "'delete address'", ",", "'salt/cloud/address/deleting'", ",", "args", "=", "{", "'name'", ":", "name", "}", ",", "sock_dir", "=", "__opts__", "[", "'sock_dir'", "]", ",", "transport", "=", "__opts__", "[", "'transport'", "]", ")", "try", ":", "result", "=", "conn", ".", "ex_destroy_address", "(", "conn", ".", "ex_get_address", "(", "name", ",", "ex_region", ")", ")", "except", "ResourceNotFoundError", "as", "exc", ":", "log", ".", "error", "(", "'Address {0} could not be found (region {1})\\nThe following exception was thrown by libcloud:\\n{2}'", ".", "format", "(", "name", ",", "ex_region", ",", "exc", ")", ",", "exc_info_on_loglevel", "=", "logging", ".", "DEBUG", ")", "return", "False", "__utils__", "[", "'cloud.fire_event'", "]", "(", "'event'", ",", "'deleted address'", ",", "'salt/cloud/address/deleted'", ",", "args", "=", "{", "'name'", ":", "name", "}", ",", "sock_dir", "=", "__opts__", "[", "'sock_dir'", "]", ",", "transport", "=", "__opts__", "[", "'transport'", "]", ")", "log", ".", "info", "(", "(", "'Deleted GCE Address '", "+", "name", ")", ")", "return", "result" ]
permanently delete a static address .
train
true
22,742
def default_missing_value_for_dtype(dtype): try: return _FILLVALUE_DEFAULTS[dtype] except KeyError: raise NoDefaultMissingValue(('No default value registered for dtype %s.' % dtype))
[ "def", "default_missing_value_for_dtype", "(", "dtype", ")", ":", "try", ":", "return", "_FILLVALUE_DEFAULTS", "[", "dtype", "]", "except", "KeyError", ":", "raise", "NoDefaultMissingValue", "(", "(", "'No default value registered for dtype %s.'", "%", "dtype", ")", ")" ]
get the default fill value for dtype .
train
false
22,743
def construct_patch(self, path, data=u'', content_type=u'application/octet-stream', **extra): return self.generic(u'PATCH', path, data, content_type, **extra)
[ "def", "construct_patch", "(", "self", ",", "path", ",", "data", "=", "u''", ",", "content_type", "=", "u'application/octet-stream'", ",", "**", "extra", ")", ":", "return", "self", ".", "generic", "(", "u'PATCH'", ",", "path", ",", "data", ",", "content_type", ",", "**", "extra", ")" ]
construct a patch request .
train
false
22,744
def process_email(): streams = MessageStream.objects.filter(trash=False, incoming_server_username__isnull=False) for stream in streams: stream.process_email()
[ "def", "process_email", "(", ")", ":", "streams", "=", "MessageStream", ".", "objects", ".", "filter", "(", "trash", "=", "False", ",", "incoming_server_username__isnull", "=", "False", ")", "for", "stream", "in", "streams", ":", "stream", ".", "process_email", "(", ")" ]
parse emails and save activity log entry .
train
false
22,745
def parseSubscripts(subscr): if subscr: return subscr[1:(-1)].split(u',') return []
[ "def", "parseSubscripts", "(", "subscr", ")", ":", "if", "subscr", ":", "return", "subscr", "[", "1", ":", "(", "-", "1", ")", "]", ".", "split", "(", "u','", ")", "return", "[", "]" ]
parse the subscripts for a primitive category .
train
false
22,746
def _triage_meg_pick(ch, meg): if (meg is True): return True elif (ch['unit'] == FIFF.FIFF_UNIT_T_M): if (meg == 'grad'): return True elif ((meg == 'planar1') and ch['ch_name'].endswith('2')): return True elif ((meg == 'planar2') and ch['ch_name'].endswith('3')): return True elif ((meg == 'mag') and (ch['unit'] == FIFF.FIFF_UNIT_T)): return True return False
[ "def", "_triage_meg_pick", "(", "ch", ",", "meg", ")", ":", "if", "(", "meg", "is", "True", ")", ":", "return", "True", "elif", "(", "ch", "[", "'unit'", "]", "==", "FIFF", ".", "FIFF_UNIT_T_M", ")", ":", "if", "(", "meg", "==", "'grad'", ")", ":", "return", "True", "elif", "(", "(", "meg", "==", "'planar1'", ")", "and", "ch", "[", "'ch_name'", "]", ".", "endswith", "(", "'2'", ")", ")", ":", "return", "True", "elif", "(", "(", "meg", "==", "'planar2'", ")", "and", "ch", "[", "'ch_name'", "]", ".", "endswith", "(", "'3'", ")", ")", ":", "return", "True", "elif", "(", "(", "meg", "==", "'mag'", ")", "and", "(", "ch", "[", "'unit'", "]", "==", "FIFF", ".", "FIFF_UNIT_T", ")", ")", ":", "return", "True", "return", "False" ]
triage an meg pick type .
train
false
22,747
def isolates(G): return (n for (n, d) in G.degree() if (d == 0))
[ "def", "isolates", "(", "G", ")", ":", "return", "(", "n", "for", "(", "n", ",", "d", ")", "in", "G", ".", "degree", "(", ")", "if", "(", "d", "==", "0", ")", ")" ]
iterator over isolates in the graph .
train
false
22,748
def set_partition(df, index, divisions, max_branch=32, drop=True, shuffle=None, compute=None): if np.isscalar(index): partitions = df[index].map_partitions(set_partitions_pre, divisions=divisions, meta=pd.Series([0])) df2 = df.assign(_partitions=partitions) else: partitions = index.map_partitions(set_partitions_pre, divisions=divisions, meta=pd.Series([0])) df2 = df.assign(_partitions=partitions, _index=index) df3 = rearrange_by_column(df2, '_partitions', max_branch=max_branch, npartitions=(len(divisions) - 1), shuffle=shuffle, compute=compute) if np.isscalar(index): df4 = df3.map_partitions(set_index_post_scalar, index_name=index, drop=drop, column_dtype=df.columns.dtype) else: df4 = df3.map_partitions(set_index_post_series, index_name=index.name, drop=drop, column_dtype=df.columns.dtype) df4.divisions = divisions return df4.map_partitions(M.sort_index)
[ "def", "set_partition", "(", "df", ",", "index", ",", "divisions", ",", "max_branch", "=", "32", ",", "drop", "=", "True", ",", "shuffle", "=", "None", ",", "compute", "=", "None", ")", ":", "if", "np", ".", "isscalar", "(", "index", ")", ":", "partitions", "=", "df", "[", "index", "]", ".", "map_partitions", "(", "set_partitions_pre", ",", "divisions", "=", "divisions", ",", "meta", "=", "pd", ".", "Series", "(", "[", "0", "]", ")", ")", "df2", "=", "df", ".", "assign", "(", "_partitions", "=", "partitions", ")", "else", ":", "partitions", "=", "index", ".", "map_partitions", "(", "set_partitions_pre", ",", "divisions", "=", "divisions", ",", "meta", "=", "pd", ".", "Series", "(", "[", "0", "]", ")", ")", "df2", "=", "df", ".", "assign", "(", "_partitions", "=", "partitions", ",", "_index", "=", "index", ")", "df3", "=", "rearrange_by_column", "(", "df2", ",", "'_partitions'", ",", "max_branch", "=", "max_branch", ",", "npartitions", "=", "(", "len", "(", "divisions", ")", "-", "1", ")", ",", "shuffle", "=", "shuffle", ",", "compute", "=", "compute", ")", "if", "np", ".", "isscalar", "(", "index", ")", ":", "df4", "=", "df3", ".", "map_partitions", "(", "set_index_post_scalar", ",", "index_name", "=", "index", ",", "drop", "=", "drop", ",", "column_dtype", "=", "df", ".", "columns", ".", "dtype", ")", "else", ":", "df4", "=", "df3", ".", "map_partitions", "(", "set_index_post_series", ",", "index_name", "=", "index", ".", "name", ",", "drop", "=", "drop", ",", "column_dtype", "=", "df", ".", "columns", ".", "dtype", ")", "df4", ".", "divisions", "=", "divisions", "return", "df4", ".", "map_partitions", "(", "M", ".", "sort_index", ")" ]
extract a partition from a list of tuples this should be correctly called select largest disjoint sets .
train
false
22,749
def test_infomax_weights_ini(): X = np.random.random((3, 100)) weights = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float64) w1 = infomax(X, max_iter=0, weights=weights, extended=True) w2 = infomax(X, max_iter=0, weights=weights, extended=False) assert_almost_equal(w1, weights) assert_almost_equal(w2, weights)
[ "def", "test_infomax_weights_ini", "(", ")", ":", "X", "=", "np", ".", "random", ".", "random", "(", "(", "3", ",", "100", ")", ")", "weights", "=", "np", ".", "array", "(", "[", "[", "1", ",", "2", ",", "3", "]", ",", "[", "4", ",", "5", ",", "6", "]", ",", "[", "7", ",", "8", ",", "9", "]", "]", ",", "dtype", "=", "np", ".", "float64", ")", "w1", "=", "infomax", "(", "X", ",", "max_iter", "=", "0", ",", "weights", "=", "weights", ",", "extended", "=", "True", ")", "w2", "=", "infomax", "(", "X", ",", "max_iter", "=", "0", ",", "weights", "=", "weights", ",", "extended", "=", "False", ")", "assert_almost_equal", "(", "w1", ",", "weights", ")", "assert_almost_equal", "(", "w2", ",", "weights", ")" ]
test the infomax algorithm when user provides an initial weights matrix .
train
false
22,750
def GenerateOAuthRequestTokenUrl(oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): scopes_string = ' '.join([str(scope) for scope in scopes]) parameters = {'scope': scopes_string} if extra_parameters: parameters.update(extra_parameters) oauth_request = oauth.OAuthRequest.from_consumer_and_token(oauth_input_params.GetConsumer(), http_url=request_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None) return atom.url.parse_url(oauth_request.to_url())
[ "def", "GenerateOAuthRequestTokenUrl", "(", "oauth_input_params", ",", "scopes", ",", "request_token_url", "=", "'https://www.google.com/accounts/OAuthGetRequestToken'", ",", "extra_parameters", "=", "None", ")", ":", "scopes_string", "=", "' '", ".", "join", "(", "[", "str", "(", "scope", ")", "for", "scope", "in", "scopes", "]", ")", "parameters", "=", "{", "'scope'", ":", "scopes_string", "}", "if", "extra_parameters", ":", "parameters", ".", "update", "(", "extra_parameters", ")", "oauth_request", "=", "oauth", ".", "OAuthRequest", ".", "from_consumer_and_token", "(", "oauth_input_params", ".", "GetConsumer", "(", ")", ",", "http_url", "=", "request_token_url", ",", "parameters", "=", "parameters", ")", "oauth_request", ".", "sign_request", "(", "oauth_input_params", ".", "GetSignatureMethod", "(", ")", ",", "oauth_input_params", ".", "GetConsumer", "(", ")", ",", "None", ")", "return", "atom", ".", "url", ".", "parse_url", "(", "oauth_request", ".", "to_url", "(", ")", ")" ]
generate a url at which a request for oauth request token is to be sent .
train
false
22,751
def completed_chart(): series_id = get_vars.get('series_id') if (not series_id): return 'Programming Error: Series ID missing' question_id = get_vars.get('question_id') if (not question_id): return 'Programming Error: Question ID missing' q_type = get_vars.get('type') if (not q_type): return 'Programming Error: Question Type missing' getAnswers = s3db.survey_getAllAnswersForQuestionInSeries answers = getAnswers(question_id, series_id) analysisTool = s3db.survey_analysis_type[q_type](question_id, answers) qstnName = analysisTool.qstnWidget.question.name image = analysisTool.drawChart(series_id, output='png') return image
[ "def", "completed_chart", "(", ")", ":", "series_id", "=", "get_vars", ".", "get", "(", "'series_id'", ")", "if", "(", "not", "series_id", ")", ":", "return", "'Programming Error: Series ID missing'", "question_id", "=", "get_vars", ".", "get", "(", "'question_id'", ")", "if", "(", "not", "question_id", ")", ":", "return", "'Programming Error: Question ID missing'", "q_type", "=", "get_vars", ".", "get", "(", "'type'", ")", "if", "(", "not", "q_type", ")", ":", "return", "'Programming Error: Question Type missing'", "getAnswers", "=", "s3db", ".", "survey_getAllAnswersForQuestionInSeries", "answers", "=", "getAnswers", "(", "question_id", ",", "series_id", ")", "analysisTool", "=", "s3db", ".", "survey_analysis_type", "[", "q_type", "]", "(", "question_id", ",", "answers", ")", "qstnName", "=", "analysisTool", ".", "qstnWidget", ".", "question", ".", "name", "image", "=", "analysisTool", ".", "drawChart", "(", "series_id", ",", "output", "=", "'png'", ")", "return", "image" ]
allows the user to display all the data from the selected question in a simple chart .
train
false
22,753
def get_university_for_request(): return configuration_helpers.get_value('university')
[ "def", "get_university_for_request", "(", ")", ":", "return", "configuration_helpers", ".", "get_value", "(", "'university'", ")" ]
return the university name specified for the domain .
train
false
22,754
def fix_url(s, charset='utf-8'): if isinstance(s, unicode): s = s.encode(charset, 'ignore') (scheme, netloc, path, qs, anchor) = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
[ "def", "fix_url", "(", "s", ",", "charset", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "s", "=", "s", ".", "encode", "(", "charset", ",", "'ignore'", ")", "(", "scheme", ",", "netloc", ",", "path", ",", "qs", ",", "anchor", ")", "=", "urlparse", ".", "urlsplit", "(", "s", ")", "path", "=", "urllib", ".", "quote", "(", "path", ",", "'/%'", ")", "qs", "=", "urllib", ".", "quote_plus", "(", "qs", ",", "':&='", ")", "return", "urlparse", ".", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "qs", ",", "anchor", ")", ")" ]
fix the url so it is proper formatted and encoded .
train
false
22,755
def ent2chr(input_str): code = input_str.group(1) code_int = (int(code) if code.isdigit() else int(code[1:], 16)) return (chr(code_int) if (code_int < 256) else '?')
[ "def", "ent2chr", "(", "input_str", ")", ":", "code", "=", "input_str", ".", "group", "(", "1", ")", "code_int", "=", "(", "int", "(", "code", ")", "if", "code", ".", "isdigit", "(", ")", "else", "int", "(", "code", "[", "1", ":", "]", ",", "16", ")", ")", "return", "(", "chr", "(", "code_int", ")", "if", "(", "code_int", "<", "256", ")", "else", "'?'", ")" ]
function to unescape literal string in xml to symbols source : URL .
train
false
22,757
def gaussian_conj(s_in, z_r_in, f): (s_in, z_r_in, f) = map(sympify, (s_in, z_r_in, f)) s_out = (1 / (((-1) / (s_in + ((z_r_in ** 2) / (s_in - f)))) + (1 / f))) m = (1 / sqrt(((1 - ((s_in / f) ** 2)) + ((z_r_in / f) ** 2)))) z_r_out = (z_r_in / ((1 - ((s_in / f) ** 2)) + ((z_r_in / f) ** 2))) return (s_out, z_r_out, m)
[ "def", "gaussian_conj", "(", "s_in", ",", "z_r_in", ",", "f", ")", ":", "(", "s_in", ",", "z_r_in", ",", "f", ")", "=", "map", "(", "sympify", ",", "(", "s_in", ",", "z_r_in", ",", "f", ")", ")", "s_out", "=", "(", "1", "/", "(", "(", "(", "-", "1", ")", "/", "(", "s_in", "+", "(", "(", "z_r_in", "**", "2", ")", "/", "(", "s_in", "-", "f", ")", ")", ")", ")", "+", "(", "1", "/", "f", ")", ")", ")", "m", "=", "(", "1", "/", "sqrt", "(", "(", "(", "1", "-", "(", "(", "s_in", "/", "f", ")", "**", "2", ")", ")", "+", "(", "(", "z_r_in", "/", "f", ")", "**", "2", ")", ")", ")", ")", "z_r_out", "=", "(", "z_r_in", "/", "(", "(", "1", "-", "(", "(", "s_in", "/", "f", ")", "**", "2", ")", ")", "+", "(", "(", "z_r_in", "/", "f", ")", "**", "2", ")", ")", ")", "return", "(", "s_out", ",", "z_r_out", ",", "m", ")" ]
conjugation relation for gaussian beams .
train
false
22,758
def _get_float(data, position, dummy0, dummy1, dummy2): end = (position + 8) return (_UNPACK_FLOAT(data[position:end])[0], end)
[ "def", "_get_float", "(", "data", ",", "position", ",", "dummy0", ",", "dummy1", ",", "dummy2", ")", ":", "end", "=", "(", "position", "+", "8", ")", "return", "(", "_UNPACK_FLOAT", "(", "data", "[", "position", ":", "end", "]", ")", "[", "0", "]", ",", "end", ")" ]
decode a bson double to python float .
train
true
22,760
def move_entry(from_list, from_set, to_list, to_set): (i, mac) = get(from_list) if (mac is None): return from_list.delete(i) to_list.insert(END, mac) mac = EthAddr(mac) to_set.add(mac) from_set.remove(mac) if clear_tables_on_change: core.callLater(clear_flows)
[ "def", "move_entry", "(", "from_list", ",", "from_set", ",", "to_list", ",", "to_set", ")", ":", "(", "i", ",", "mac", ")", "=", "get", "(", "from_list", ")", "if", "(", "mac", "is", "None", ")", ":", "return", "from_list", ".", "delete", "(", "i", ")", "to_list", ".", "insert", "(", "END", ",", "mac", ")", "mac", "=", "EthAddr", "(", "mac", ")", "to_set", ".", "add", "(", "mac", ")", "from_set", ".", "remove", "(", "mac", ")", "if", "clear_tables_on_change", ":", "core", ".", "callLater", "(", "clear_flows", ")" ]
move entry from one list to another .
train
false
22,762
def _get_services(): handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE) try: services = win32service.EnumServicesStatusEx(handle_scm) except AttributeError: services = win32service.EnumServicesStatus(handle_scm) finally: win32service.CloseServiceHandle(handle_scm) return services
[ "def", "_get_services", "(", ")", ":", "handle_scm", "=", "win32service", ".", "OpenSCManager", "(", "None", ",", "None", ",", "win32service", ".", "SC_MANAGER_ENUMERATE_SERVICE", ")", "try", ":", "services", "=", "win32service", ".", "EnumServicesStatusEx", "(", "handle_scm", ")", "except", "AttributeError", ":", "services", "=", "win32service", ".", "EnumServicesStatus", "(", "handle_scm", ")", "finally", ":", "win32service", ".", "CloseServiceHandle", "(", "handle_scm", ")", "return", "services" ]
returns a list of all services on the system .
train
true
22,763
def dmp_strip(f, u): if (not u): return dup_strip(f) if dmp_zero_p(f, u): return f (i, v) = (0, (u - 1)) for c in f: if (not dmp_zero_p(c, v)): break else: i += 1 if (i == len(f)): return dmp_zero(u) else: return f[i:]
[ "def", "dmp_strip", "(", "f", ",", "u", ")", ":", "if", "(", "not", "u", ")", ":", "return", "dup_strip", "(", "f", ")", "if", "dmp_zero_p", "(", "f", ",", "u", ")", ":", "return", "f", "(", "i", ",", "v", ")", "=", "(", "0", ",", "(", "u", "-", "1", ")", ")", "for", "c", "in", "f", ":", "if", "(", "not", "dmp_zero_p", "(", "c", ",", "v", ")", ")", ":", "break", "else", ":", "i", "+=", "1", "if", "(", "i", "==", "len", "(", "f", ")", ")", ":", "return", "dmp_zero", "(", "u", ")", "else", ":", "return", "f", "[", "i", ":", "]" ]
remove leading zeros from f in k[x] .
train
false
22,764
@mock_ec2 def test_igw_delete(): conn = boto.connect_vpc(u'the_key', u'the_secret') vpc = conn.create_vpc(VPC_CIDR) conn.get_all_internet_gateways().should.have.length_of(0) igw = conn.create_internet_gateway() conn.get_all_internet_gateways().should.have.length_of(1) with assert_raises(JSONResponseError) as ex: conn.delete_internet_gateway(igw.id, dry_run=True) ex.exception.reason.should.equal(u'DryRunOperation') ex.exception.status.should.equal(400) ex.exception.message.should.equal(u'An error occurred (DryRunOperation) when calling the DeleteInternetGateway operation: Request would have succeeded, but DryRun flag is set') conn.delete_internet_gateway(igw.id) conn.get_all_internet_gateways().should.have.length_of(0)
[ "@", "mock_ec2", "def", "test_igw_delete", "(", ")", ":", "conn", "=", "boto", ".", "connect_vpc", "(", "u'the_key'", ",", "u'the_secret'", ")", "vpc", "=", "conn", ".", "create_vpc", "(", "VPC_CIDR", ")", "conn", ".", "get_all_internet_gateways", "(", ")", ".", "should", ".", "have", ".", "length_of", "(", "0", ")", "igw", "=", "conn", ".", "create_internet_gateway", "(", ")", "conn", ".", "get_all_internet_gateways", "(", ")", ".", "should", ".", "have", ".", "length_of", "(", "1", ")", "with", "assert_raises", "(", "JSONResponseError", ")", "as", "ex", ":", "conn", ".", "delete_internet_gateway", "(", "igw", ".", "id", ",", "dry_run", "=", "True", ")", "ex", ".", "exception", ".", "reason", ".", "should", ".", "equal", "(", "u'DryRunOperation'", ")", "ex", ".", "exception", ".", "status", ".", "should", ".", "equal", "(", "400", ")", "ex", ".", "exception", ".", "message", ".", "should", ".", "equal", "(", "u'An error occurred (DryRunOperation) when calling the DeleteInternetGateway operation: Request would have succeeded, but DryRun flag is set'", ")", "conn", ".", "delete_internet_gateway", "(", "igw", ".", "id", ")", "conn", ".", "get_all_internet_gateways", "(", ")", ".", "should", ".", "have", ".", "length_of", "(", "0", ")" ]
internet gateway delete .
train
false
22,765
def re_subm(pat, repl, string): r = re_compile(pat) proxy = _re_subm_proxy() r.sub(proxy.__call__, string) return (r.sub(repl, string), proxy.match)
[ "def", "re_subm", "(", "pat", ",", "repl", ",", "string", ")", ":", "r", "=", "re_compile", "(", "pat", ")", "proxy", "=", "_re_subm_proxy", "(", ")", "r", ".", "sub", "(", "proxy", ".", "__call__", ",", "string", ")", "return", "(", "r", ".", "sub", "(", "repl", ",", "string", ")", ",", "proxy", ".", "match", ")" ]
like re .
train
false
22,766
def enumValueToNameLookup(type_, value_): retVal = None for (name, value) in getPublicTypeMembers(type_): if (value == value_): retVal = name break return retVal
[ "def", "enumValueToNameLookup", "(", "type_", ",", "value_", ")", ":", "retVal", "=", "None", "for", "(", "name", ",", "value", ")", "in", "getPublicTypeMembers", "(", "type_", ")", ":", "if", "(", "value", "==", "value_", ")", ":", "retVal", "=", "name", "break", "return", "retVal" ]
returns name of a enum member with a given value .
train
false
22,767
def get_current_request(): return RequestCache.get_current_request()
[ "def", "get_current_request", "(", ")", ":", "return", "RequestCache", ".", "get_current_request", "(", ")" ]
return the currently active request or none if no request is currently active .
train
false
22,768
def hrm_training_onvalidation(form): form_vars = form.vars training_event_id = form_vars.get('training_event_id', None) if (not training_event_id): return db = current.db table = db.hrm_training_event record = db((table.id == training_event_id)).select(table.course_id, table.start_date, table.end_date, table.hours, cache=current.s3db.cache, limitby=(0, 1)).first() try: form_vars.course_id = record.course_id form_vars.date = record.start_date form_vars.end_date = record.end_date form_vars.hours = record.hours except: return
[ "def", "hrm_training_onvalidation", "(", "form", ")", ":", "form_vars", "=", "form", ".", "vars", "training_event_id", "=", "form_vars", ".", "get", "(", "'training_event_id'", ",", "None", ")", "if", "(", "not", "training_event_id", ")", ":", "return", "db", "=", "current", ".", "db", "table", "=", "db", ".", "hrm_training_event", "record", "=", "db", "(", "(", "table", ".", "id", "==", "training_event_id", ")", ")", ".", "select", "(", "table", ".", "course_id", ",", "table", ".", "start_date", ",", "table", ".", "end_date", ",", "table", ".", "hours", ",", "cache", "=", "current", ".", "s3db", ".", "cache", ",", "limitby", "=", "(", "0", ",", "1", ")", ")", ".", "first", "(", ")", "try", ":", "form_vars", ".", "course_id", "=", "record", ".", "course_id", "form_vars", ".", "date", "=", "record", ".", "start_date", "form_vars", ".", "end_date", "=", "record", ".", "end_date", "form_vars", ".", "hours", "=", "record", ".", "hours", "except", ":", "return" ]
if the training is created from a training event .
train
false
22,771
def from_module_import_class(modulename, classname): klass = getattr(__import__(modulename, globals(), locals(), [classname], (-1)), classname) globals()[classname] = klass
[ "def", "from_module_import_class", "(", "modulename", ",", "classname", ")", ":", "klass", "=", "getattr", "(", "__import__", "(", "modulename", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "classname", "]", ",", "(", "-", "1", ")", ")", ",", "classname", ")", "globals", "(", ")", "[", "classname", "]", "=", "klass" ]
import a class from a module .
train
false
22,772
def make_friedman1(n_samples=100, n_features=10, noise=0.0, random_state=None): if (n_features < 5): raise ValueError('n_features must be at least five.') generator = check_random_state(random_state) X = generator.rand(n_samples, n_features) y = (((((10 * np.sin(((np.pi * X[:, 0]) * X[:, 1]))) + (20 * ((X[:, 2] - 0.5) ** 2))) + (10 * X[:, 3])) + (5 * X[:, 4])) + (noise * generator.randn(n_samples))) return (X, y)
[ "def", "make_friedman1", "(", "n_samples", "=", "100", ",", "n_features", "=", "10", ",", "noise", "=", "0.0", ",", "random_state", "=", "None", ")", ":", "if", "(", "n_features", "<", "5", ")", ":", "raise", "ValueError", "(", "'n_features must be at least five.'", ")", "generator", "=", "check_random_state", "(", "random_state", ")", "X", "=", "generator", ".", "rand", "(", "n_samples", ",", "n_features", ")", "y", "=", "(", "(", "(", "(", "(", "10", "*", "np", ".", "sin", "(", "(", "(", "np", ".", "pi", "*", "X", "[", ":", ",", "0", "]", ")", "*", "X", "[", ":", ",", "1", "]", ")", ")", ")", "+", "(", "20", "*", "(", "(", "X", "[", ":", ",", "2", "]", "-", "0.5", ")", "**", "2", ")", ")", ")", "+", "(", "10", "*", "X", "[", ":", ",", "3", "]", ")", ")", "+", "(", "5", "*", "X", "[", ":", ",", "4", "]", ")", ")", "+", "(", "noise", "*", "generator", ".", "randn", "(", "n_samples", ")", ")", ")", "return", "(", "X", ",", "y", ")" ]
generate the "friedman #1" regression problem this dataset is described in friedman [1] and breiman [2] .
train
false
22,773
def create_external_account(host='foo.bar.baz', token='doremi-abc-123'): return ExternalAccountFactory(provider='dataverse', provider_name='Dataverse', display_name=host, oauth_key=host, oauth_secret=token)
[ "def", "create_external_account", "(", "host", "=", "'foo.bar.baz'", ",", "token", "=", "'doremi-abc-123'", ")", ":", "return", "ExternalAccountFactory", "(", "provider", "=", "'dataverse'", ",", "provider_name", "=", "'Dataverse'", ",", "display_name", "=", "host", ",", "oauth_key", "=", "host", ",", "oauth_secret", "=", "token", ")" ]
creates external account for dataverse with fields populated the same way as dataverse_add_user_account .
train
false
22,774
def _osx_gpudata(): gpus = [] try: pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') for line in pcictl_out.splitlines(): (fieldname, _, fieldval) = line.partition(': ') if (fieldname.strip() == 'Chipset Model'): (vendor, _, model) = fieldval.partition(' ') vendor = vendor.lower() gpus.append({'vendor': vendor, 'model': model}) except OSError: pass grains = {} grains['num_gpus'] = len(gpus) grains['gpus'] = gpus return grains
[ "def", "_osx_gpudata", "(", ")", ":", "gpus", "=", "[", "]", "try", ":", "pcictl_out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'system_profiler SPDisplaysDataType'", ")", "for", "line", "in", "pcictl_out", ".", "splitlines", "(", ")", ":", "(", "fieldname", ",", "_", ",", "fieldval", ")", "=", "line", ".", "partition", "(", "': '", ")", "if", "(", "fieldname", ".", "strip", "(", ")", "==", "'Chipset Model'", ")", ":", "(", "vendor", ",", "_", ",", "model", ")", "=", "fieldval", ".", "partition", "(", "' '", ")", "vendor", "=", "vendor", ".", "lower", "(", ")", "gpus", ".", "append", "(", "{", "'vendor'", ":", "vendor", ",", "'model'", ":", "model", "}", ")", "except", "OSError", ":", "pass", "grains", "=", "{", "}", "grains", "[", "'num_gpus'", "]", "=", "len", "(", "gpus", ")", "grains", "[", "'gpus'", "]", "=", "gpus", "return", "grains" ]
num_gpus: int gpus: - vendor: nvidia|amd|ati| .
train
true
22,775
@_built_in_directive def module(default=None, api=None, **kwargs): return (api.module if api else default)
[ "@", "_built_in_directive", "def", "module", "(", "default", "=", "None", ",", "api", "=", "None", ",", "**", "kwargs", ")", ":", "return", "(", "api", ".", "module", "if", "api", "else", "default", ")" ]
enable/disable and optionally force a specific version for an selinux module name the name of the module to control module_state should the module be enabled or disabled? version defaults to no preference .
train
false
22,776
def formatFromExtension(fname): (_base, ext) = os.path.splitext(fname) if (not ext): return None try: format = known_extensions[ext.replace('.', '')] except KeyError: format = None return format
[ "def", "formatFromExtension", "(", "fname", ")", ":", "(", "_base", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "if", "(", "not", "ext", ")", ":", "return", "None", "try", ":", "format", "=", "known_extensions", "[", "ext", ".", "replace", "(", "'.'", ",", "''", ")", "]", "except", "KeyError", ":", "format", "=", "None", "return", "format" ]
tries to infer a protocol from the file extension .
train
true
22,777
def SetPeSubsystem(fd, console=True): current_pos = fd.tell() fd.seek(60) header_offset = struct.unpack('<I', fd.read(4))[0] subsystem_offset = (header_offset + 92) fd.seek(subsystem_offset) if console: fd.write('\x03') else: fd.write('\x02') fd.seek(current_pos)
[ "def", "SetPeSubsystem", "(", "fd", ",", "console", "=", "True", ")", ":", "current_pos", "=", "fd", ".", "tell", "(", ")", "fd", ".", "seek", "(", "60", ")", "header_offset", "=", "struct", ".", "unpack", "(", "'<I'", ",", "fd", ".", "read", "(", "4", ")", ")", "[", "0", "]", "subsystem_offset", "=", "(", "header_offset", "+", "92", ")", "fd", ".", "seek", "(", "subsystem_offset", ")", "if", "console", ":", "fd", ".", "write", "(", "'\\x03'", ")", "else", ":", "fd", ".", "write", "(", "'\\x02'", ")", "fd", ".", "seek", "(", "current_pos", ")" ]
takes file like obj and returns for the pe subsystem .
train
true
22,778
def _extract_spreadsheet_key_from_url(url): result = url if ('key=' in url): result = url.split('key=')[(-1)].split('#')[0].split('&')[0] return result
[ "def", "_extract_spreadsheet_key_from_url", "(", "url", ")", ":", "result", "=", "url", "if", "(", "'key='", "in", "url", ")", ":", "result", "=", "url", ".", "split", "(", "'key='", ")", "[", "(", "-", "1", ")", "]", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "split", "(", "'&'", ")", "[", "0", "]", "return", "result" ]
extracts a key from a url in the form .
train
false
22,779
def get_pep_page(pep_number, commit=True): pep_path = os.path.join(settings.PEP_REPO_PATH, 'pep-{}.html'.format(pep_number)) if (not os.path.exists(pep_path)): print "PEP Path '{}' does not exist, skipping".format(pep_path) pep_content = convert_pep_page(pep_number, open(pep_path).read()) (pep_page, _) = Page.objects.get_or_create(path=pep_url(pep_number)) pep_page.title = pep_content['title'] pep_page.content = pep_content['content'] pep_page.content_markup_type = 'html' pep_page.template_name = PEP_TEMPLATE if commit: pep_page.save() return pep_page
[ "def", "get_pep_page", "(", "pep_number", ",", "commit", "=", "True", ")", ":", "pep_path", "=", "os", ".", "path", ".", "join", "(", "settings", ".", "PEP_REPO_PATH", ",", "'pep-{}.html'", ".", "format", "(", "pep_number", ")", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "pep_path", ")", ")", ":", "print", "\"PEP Path '{}' does not exist, skipping\"", ".", "format", "(", "pep_path", ")", "pep_content", "=", "convert_pep_page", "(", "pep_number", ",", "open", "(", "pep_path", ")", ".", "read", "(", ")", ")", "(", "pep_page", ",", "_", ")", "=", "Page", ".", "objects", ".", "get_or_create", "(", "path", "=", "pep_url", "(", "pep_number", ")", ")", "pep_page", ".", "title", "=", "pep_content", "[", "'title'", "]", "pep_page", ".", "content", "=", "pep_content", "[", "'content'", "]", "pep_page", ".", "content_markup_type", "=", "'html'", "pep_page", ".", "template_name", "=", "PEP_TEMPLATE", "if", "commit", ":", "pep_page", ".", "save", "(", ")", "return", "pep_page" ]
given a pep_number retrieve original pep source text .
train
false
22,780
def iterfunc(seqn): for i in seqn: (yield i)
[ "def", "iterfunc", "(", "seqn", ")", ":", "for", "i", "in", "seqn", ":", "(", "yield", "i", ")" ]
regular generator .
train
false
22,781
@require_POST @login_required def unwatch_ready(request, product=None): if (request.LANGUAGE_CODE != settings.WIKI_DEFAULT_LANGUAGE): raise Http404 kwargs = {} if (product is not None): kwargs['product'] = product ReadyRevisionEvent.stop_notifying(request.user, **kwargs) return HttpResponse()
[ "@", "require_POST", "@", "login_required", "def", "unwatch_ready", "(", "request", ",", "product", "=", "None", ")", ":", "if", "(", "request", ".", "LANGUAGE_CODE", "!=", "settings", ".", "WIKI_DEFAULT_LANGUAGE", ")", ":", "raise", "Http404", "kwargs", "=", "{", "}", "if", "(", "product", "is", "not", "None", ")", ":", "kwargs", "[", "'product'", "]", "=", "product", "ReadyRevisionEvent", ".", "stop_notifying", "(", "request", ".", "user", ",", "**", "kwargs", ")", "return", "HttpResponse", "(", ")" ]
stop watching ready-for-l10n revisions for a given product .
train
false
22,782
def get_previous_sle(args, for_update=False): args[u'name'] = (args.get(u'sle', None) or u'') sle = get_stock_ledger_entries(args, u'<=', u'desc', u'limit 1', for_update=for_update) return ((sle and sle[0]) or {})
[ "def", "get_previous_sle", "(", "args", ",", "for_update", "=", "False", ")", ":", "args", "[", "u'name'", "]", "=", "(", "args", ".", "get", "(", "u'sle'", ",", "None", ")", "or", "u''", ")", "sle", "=", "get_stock_ledger_entries", "(", "args", ",", "u'<='", ",", "u'desc'", ",", "u'limit 1'", ",", "for_update", "=", "for_update", ")", "return", "(", "(", "sle", "and", "sle", "[", "0", "]", ")", "or", "{", "}", ")" ]
get the last sle on or before the current time-bucket .
train
false
22,784
def _extract_buffers(commands): data_commands = [command for command in commands if (command[0] == 'DATA')] buffers = [data_command[3] for data_command in data_commands] commands_modified = list(commands) buffer_index = 0 for (i, command) in enumerate(commands_modified): if (command[0] == 'DATA'): commands_modified[i] = (command[:3] + ({'buffer_index': buffer_index},)) buffer_index += 1 return (commands_modified, buffers)
[ "def", "_extract_buffers", "(", "commands", ")", ":", "data_commands", "=", "[", "command", "for", "command", "in", "commands", "if", "(", "command", "[", "0", "]", "==", "'DATA'", ")", "]", "buffers", "=", "[", "data_command", "[", "3", "]", "for", "data_command", "in", "data_commands", "]", "commands_modified", "=", "list", "(", "commands", ")", "buffer_index", "=", "0", "for", "(", "i", ",", "command", ")", "in", "enumerate", "(", "commands_modified", ")", ":", "if", "(", "command", "[", "0", "]", "==", "'DATA'", ")", ":", "commands_modified", "[", "i", "]", "=", "(", "command", "[", ":", "3", "]", "+", "(", "{", "'buffer_index'", ":", "buffer_index", "}", ",", ")", ")", "buffer_index", "+=", "1", "return", "(", "commands_modified", ",", "buffers", ")" ]
extract all data buffers from the list of glir commands .
train
true
22,785
def pdf_mvsk(mvsk): N = len(mvsk) if (N < 4): raise ValueError('Four moments must be given to approximate the pdf.') (mu, mc2, skew, kurt) = mvsk totp = poly1d(1) sig = sqrt(mc2) if (N > 2): Dvals = _hermnorm((N + 1)) C3 = (skew / 6.0) C4 = (kurt / 24.0) totp = ((totp - (C3 * Dvals[3])) + (C4 * Dvals[4])) def pdffunc(x): xn = ((x - mu) / sig) return (((totp(xn) * np.exp((((- xn) * xn) / 2.0))) / np.sqrt((2 * np.pi))) / sig) return pdffunc
[ "def", "pdf_mvsk", "(", "mvsk", ")", ":", "N", "=", "len", "(", "mvsk", ")", "if", "(", "N", "<", "4", ")", ":", "raise", "ValueError", "(", "'Four moments must be given to approximate the pdf.'", ")", "(", "mu", ",", "mc2", ",", "skew", ",", "kurt", ")", "=", "mvsk", "totp", "=", "poly1d", "(", "1", ")", "sig", "=", "sqrt", "(", "mc2", ")", "if", "(", "N", ">", "2", ")", ":", "Dvals", "=", "_hermnorm", "(", "(", "N", "+", "1", ")", ")", "C3", "=", "(", "skew", "/", "6.0", ")", "C4", "=", "(", "kurt", "/", "24.0", ")", "totp", "=", "(", "(", "totp", "-", "(", "C3", "*", "Dvals", "[", "3", "]", ")", ")", "+", "(", "C4", "*", "Dvals", "[", "4", "]", ")", ")", "def", "pdffunc", "(", "x", ")", ":", "xn", "=", "(", "(", "x", "-", "mu", ")", "/", "sig", ")", "return", "(", "(", "(", "totp", "(", "xn", ")", "*", "np", ".", "exp", "(", "(", "(", "(", "-", "xn", ")", "*", "xn", ")", "/", "2.0", ")", ")", ")", "/", "np", ".", "sqrt", "(", "(", "2", "*", "np", ".", "pi", ")", ")", ")", "/", "sig", ")", "return", "pdffunc" ]
return the gaussian expanded pdf function given the list of 1st .
train
false
22,786
def model_name_to_class(model_module, model_name): try: model_class_name = model_name.title() return getattr(model_module, model_class_name) except AttributeError: raise ValidationError(("%s isn't a valid model" % model_class_name))
[ "def", "model_name_to_class", "(", "model_module", ",", "model_name", ")", ":", "try", ":", "model_class_name", "=", "model_name", ".", "title", "(", ")", "return", "getattr", "(", "model_module", ",", "model_class_name", ")", "except", "AttributeError", ":", "raise", "ValidationError", "(", "(", "\"%s isn't a valid model\"", "%", "model_class_name", ")", ")" ]
return the class in model_module that has the same name as the received string .
train
false
22,787
def _add_cdpaths(paths, prefix): env = builtins.__xonsh_env__ csc = env.get('CASE_SENSITIVE_COMPLETIONS') glob_sorted = env.get('GLOB_SORTED') for cdp in env.get('CDPATH'): test_glob = (os.path.join(cdp, prefix) + '*') for s in xt.iglobpath(test_glob, ignore_case=(not csc), sort_result=glob_sorted): if os.path.isdir(s): paths.add(os.path.basename(s))
[ "def", "_add_cdpaths", "(", "paths", ",", "prefix", ")", ":", "env", "=", "builtins", ".", "__xonsh_env__", "csc", "=", "env", ".", "get", "(", "'CASE_SENSITIVE_COMPLETIONS'", ")", "glob_sorted", "=", "env", ".", "get", "(", "'GLOB_SORTED'", ")", "for", "cdp", "in", "env", ".", "get", "(", "'CDPATH'", ")", ":", "test_glob", "=", "(", "os", ".", "path", ".", "join", "(", "cdp", ",", "prefix", ")", "+", "'*'", ")", "for", "s", "in", "xt", ".", "iglobpath", "(", "test_glob", ",", "ignore_case", "=", "(", "not", "csc", ")", ",", "sort_result", "=", "glob_sorted", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "s", ")", ":", "paths", ".", "add", "(", "os", ".", "path", ".", "basename", "(", "s", ")", ")" ]
completes current prefix using cdpath .
train
false
22,788
@nottest def run_tests_if_main(measure_mem=False): local_vars = inspect.currentframe().f_back.f_locals if (not (local_vars.get('__name__', '') == '__main__')): return try: import faulthandler faulthandler.enable() except Exception: pass with warnings.catch_warnings(record=True): mem = (int(round(max(memory_usage((-1))))) if measure_mem else (-1)) if (mem >= 0): print(('Memory consumption after import: %s' % mem)) t0 = time.time() (peak_mem, peak_name) = (mem, 'import') (max_elapsed, elapsed_name) = (0, 'N/A') count = 0 for name in sorted(list(local_vars.keys()), key=(lambda x: x.lower())): val = local_vars[name] if name.startswith('_'): continue elif (callable(val) and name.startswith('test')): count += 1 doc = (val.__doc__.strip() if val.__doc__ else name) sys.stdout.write(('%s ... ' % doc)) sys.stdout.flush() try: t1 = time.time() if measure_mem: with warnings.catch_warnings(record=True): mem = int(round(max(memory_usage((val, (), {}))))) else: val() mem = (-1) if (mem >= peak_mem): (peak_mem, peak_name) = (mem, name) mem = ((', mem: %s MB' % mem) if (mem >= 0) else '') elapsed = int(round((time.time() - t1))) if (elapsed >= max_elapsed): (max_elapsed, elapsed_name) = (elapsed, name) sys.stdout.write(('time: %s sec%s\n' % (elapsed, mem))) sys.stdout.flush() except Exception as err: if ('skiptest' in err.__class__.__name__.lower()): sys.stdout.write(('SKIP (%s)\n' % str(err))) sys.stdout.flush() else: raise elapsed = int(round((time.time() - t0))) sys.stdout.write(('Total: %s tests\n\xe2\x80\xa2 %s sec (%s sec for %s)\n\xe2\x80\xa2 Peak memory %s MB (%s)\n' % (count, elapsed, max_elapsed, elapsed_name, peak_mem, peak_name)))
[ "@", "nottest", "def", "run_tests_if_main", "(", "measure_mem", "=", "False", ")", ":", "local_vars", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", ".", "f_locals", "if", "(", "not", "(", "local_vars", ".", "get", "(", "'__name__'", ",", "''", ")", "==", "'__main__'", ")", ")", ":", "return", "try", ":", "import", "faulthandler", "faulthandler", ".", "enable", "(", ")", "except", "Exception", ":", "pass", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", ":", "mem", "=", "(", "int", "(", "round", "(", "max", "(", "memory_usage", "(", "(", "-", "1", ")", ")", ")", ")", ")", "if", "measure_mem", "else", "(", "-", "1", ")", ")", "if", "(", "mem", ">=", "0", ")", ":", "print", "(", "(", "'Memory consumption after import: %s'", "%", "mem", ")", ")", "t0", "=", "time", ".", "time", "(", ")", "(", "peak_mem", ",", "peak_name", ")", "=", "(", "mem", ",", "'import'", ")", "(", "max_elapsed", ",", "elapsed_name", ")", "=", "(", "0", ",", "'N/A'", ")", "count", "=", "0", "for", "name", "in", "sorted", "(", "list", "(", "local_vars", ".", "keys", "(", ")", ")", ",", "key", "=", "(", "lambda", "x", ":", "x", ".", "lower", "(", ")", ")", ")", ":", "val", "=", "local_vars", "[", "name", "]", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "continue", "elif", "(", "callable", "(", "val", ")", "and", "name", ".", "startswith", "(", "'test'", ")", ")", ":", "count", "+=", "1", "doc", "=", "(", "val", ".", "__doc__", ".", "strip", "(", ")", "if", "val", ".", "__doc__", "else", "name", ")", "sys", ".", "stdout", ".", "write", "(", "(", "'%s ... '", "%", "doc", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "try", ":", "t1", "=", "time", ".", "time", "(", ")", "if", "measure_mem", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", ":", "mem", "=", "int", "(", "round", "(", "max", "(", "memory_usage", "(", "(", "val", ",", "(", ")", ",", "{", "}", ")", ")", ")", ")", ")", "else", ":", "val", "(", ")", "mem", "=", "(", "-", "1", ")", "if", "(", "mem", ">=", "peak_mem", ")", ":", "(", "peak_mem", ",", "peak_name", ")", "=", "(", "mem", ",", "name", ")", "mem", "=", "(", "(", "', mem: %s MB'", "%", "mem", ")", "if", "(", "mem", ">=", "0", ")", "else", "''", ")", "elapsed", "=", "int", "(", "round", "(", "(", "time", ".", "time", "(", ")", "-", "t1", ")", ")", ")", "if", "(", "elapsed", ">=", "max_elapsed", ")", ":", "(", "max_elapsed", ",", "elapsed_name", ")", "=", "(", "elapsed", ",", "name", ")", "sys", ".", "stdout", ".", "write", "(", "(", "'time: %s sec%s\\n'", "%", "(", "elapsed", ",", "mem", ")", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "except", "Exception", "as", "err", ":", "if", "(", "'skiptest'", "in", "err", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ")", ":", "sys", ".", "stdout", ".", "write", "(", "(", "'SKIP (%s)\\n'", "%", "str", "(", "err", ")", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "else", ":", "raise", "elapsed", "=", "int", "(", "round", "(", "(", "time", ".", "time", "(", ")", "-", "t0", ")", ")", ")", "sys", ".", "stdout", ".", "write", "(", "(", "'Total: %s tests\\n\\xe2\\x80\\xa2 %s sec (%s sec for %s)\\n\\xe2\\x80\\xa2 Peak memory %s MB (%s)\\n'", "%", "(", "count", ",", "elapsed", ",", "max_elapsed", ",", "elapsed_name", ",", "peak_mem", ",", "peak_name", ")", ")", ")" ]
run tests in a given file if it is run as a script .
train
false
22,789
def _build_exp_freq_mat(exp_freq_table): exp_freq_mat = ExpectedFrequencyMatrix(alphabet=exp_freq_table.alphabet, build_later=1) for i in exp_freq_mat: if (i[0] == i[1]): exp_freq_mat[i] = (exp_freq_table[i[0]] ** 2) else: exp_freq_mat[i] = ((2.0 * exp_freq_table[i[0]]) * exp_freq_table[i[1]]) return exp_freq_mat
[ "def", "_build_exp_freq_mat", "(", "exp_freq_table", ")", ":", "exp_freq_mat", "=", "ExpectedFrequencyMatrix", "(", "alphabet", "=", "exp_freq_table", ".", "alphabet", ",", "build_later", "=", "1", ")", "for", "i", "in", "exp_freq_mat", ":", "if", "(", "i", "[", "0", "]", "==", "i", "[", "1", "]", ")", ":", "exp_freq_mat", "[", "i", "]", "=", "(", "exp_freq_table", "[", "i", "[", "0", "]", "]", "**", "2", ")", "else", ":", "exp_freq_mat", "[", "i", "]", "=", "(", "(", "2.0", "*", "exp_freq_table", "[", "i", "[", "0", "]", "]", ")", "*", "exp_freq_table", "[", "i", "[", "1", "]", "]", ")", "return", "exp_freq_mat" ]
build an expected frequency matrix exp_freq_table: should be a freqtable instance .
train
false
22,791
def _iterateTests(testSuiteOrCase): try: suite = iter(testSuiteOrCase) except TypeError: (yield testSuiteOrCase) else: for test in suite: for subtest in _iterateTests(test): (yield subtest)
[ "def", "_iterateTests", "(", "testSuiteOrCase", ")", ":", "try", ":", "suite", "=", "iter", "(", "testSuiteOrCase", ")", "except", "TypeError", ":", "(", "yield", "testSuiteOrCase", ")", "else", ":", "for", "test", "in", "suite", ":", "for", "subtest", "in", "_iterateTests", "(", "test", ")", ":", "(", "yield", "subtest", ")" ]
iterate through all of the test cases in c{testsuiteorcase} .
train
false
22,792
def _find_matching_rule(module, secgroup, remotegroup): protocol = module.params['protocol'] remote_ip_prefix = module.params['remote_ip_prefix'] ethertype = module.params['ethertype'] direction = module.params['direction'] remote_group_id = remotegroup['id'] for rule in secgroup['security_group_rules']: if ((protocol == rule['protocol']) and (remote_ip_prefix == rule['remote_ip_prefix']) and (ethertype == rule['ethertype']) and (direction == rule['direction']) and (remote_group_id == rule['remote_group_id']) and _ports_match(protocol, module.params['port_range_min'], module.params['port_range_max'], rule['port_range_min'], rule['port_range_max'])): return rule return None
[ "def", "_find_matching_rule", "(", "module", ",", "secgroup", ",", "remotegroup", ")", ":", "protocol", "=", "module", ".", "params", "[", "'protocol'", "]", "remote_ip_prefix", "=", "module", ".", "params", "[", "'remote_ip_prefix'", "]", "ethertype", "=", "module", ".", "params", "[", "'ethertype'", "]", "direction", "=", "module", ".", "params", "[", "'direction'", "]", "remote_group_id", "=", "remotegroup", "[", "'id'", "]", "for", "rule", "in", "secgroup", "[", "'security_group_rules'", "]", ":", "if", "(", "(", "protocol", "==", "rule", "[", "'protocol'", "]", ")", "and", "(", "remote_ip_prefix", "==", "rule", "[", "'remote_ip_prefix'", "]", ")", "and", "(", "ethertype", "==", "rule", "[", "'ethertype'", "]", ")", "and", "(", "direction", "==", "rule", "[", "'direction'", "]", ")", "and", "(", "remote_group_id", "==", "rule", "[", "'remote_group_id'", "]", ")", "and", "_ports_match", "(", "protocol", ",", "module", ".", "params", "[", "'port_range_min'", "]", ",", "module", ".", "params", "[", "'port_range_max'", "]", ",", "rule", "[", "'port_range_min'", "]", ",", "rule", "[", "'port_range_max'", "]", ")", ")", ":", "return", "rule", "return", "None" ]
find a rule in the group that matches the module parameters .
train
false
22,793
def _checkpointLabelFromCheckpointDir(checkpointDir): assert checkpointDir.endswith(g_defaultCheckpointExtension) lastSegment = os.path.split(checkpointDir)[1] checkpointLabel = lastSegment[0:(- len(g_defaultCheckpointExtension))] return checkpointLabel
[ "def", "_checkpointLabelFromCheckpointDir", "(", "checkpointDir", ")", ":", "assert", "checkpointDir", ".", "endswith", "(", "g_defaultCheckpointExtension", ")", "lastSegment", "=", "os", ".", "path", ".", "split", "(", "checkpointDir", ")", "[", "1", "]", "checkpointLabel", "=", "lastSegment", "[", "0", ":", "(", "-", "len", "(", "g_defaultCheckpointExtension", ")", ")", "]", "return", "checkpointLabel" ]
returns a checkpoint label string for the given model checkpoint directory checkpointdir: relative or absolute model checkpoint directory path .
train
true
22,794
def dependents(tokens, head_index): head_to_deps = {} for (i, token) in enumerate(tokens): head = token['dependencyEdge']['headTokenIndex'] if (i != head): head_to_deps.setdefault(head, []).append(i) return head_to_deps.get(head_index, ())
[ "def", "dependents", "(", "tokens", ",", "head_index", ")", ":", "head_to_deps", "=", "{", "}", "for", "(", "i", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "head", "=", "token", "[", "'dependencyEdge'", "]", "[", "'headTokenIndex'", "]", "if", "(", "i", "!=", "head", ")", ":", "head_to_deps", ".", "setdefault", "(", "head", ",", "[", "]", ")", ".", "append", "(", "i", ")", "return", "head_to_deps", ".", "get", "(", "head_index", ",", "(", ")", ")" ]
returns an ordered list of the token indices of the dependents for the given head .
train
false
22,796
def new(rsa_key): return PKCS115_SigScheme(rsa_key)
[ "def", "new", "(", "rsa_key", ")", ":", "return", "PKCS115_SigScheme", "(", "rsa_key", ")" ]
create a new des cipher .
train
false
22,797
def generate_signed_url(bucket_name, blob_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(blob_name) url = blob.generate_signed_url(expiration=datetime.timedelta(hours=1), method='GET') print 'The signed url for {} is {}'.format(blob.name, url)
[ "def", "generate_signed_url", "(", "bucket_name", ",", "blob_name", ")", ":", "storage_client", "=", "storage", ".", "Client", "(", ")", "bucket", "=", "storage_client", ".", "get_bucket", "(", "bucket_name", ")", "blob", "=", "bucket", ".", "blob", "(", "blob_name", ")", "url", "=", "blob", ".", "generate_signed_url", "(", "expiration", "=", "datetime", ".", "timedelta", "(", "hours", "=", "1", ")", ",", "method", "=", "'GET'", ")", "print", "'The signed url for {} is {}'", ".", "format", "(", "blob", ".", "name", ",", "url", ")" ]
generate signed url to provide query-string authn to a resource .
train
false
22,798
def getWidenedLoop(loop, loopList, outsetLoop, radius): intersectingWithinLoops = getIntersectingWithinLoops(loop, loopList, outsetLoop) if (len(intersectingWithinLoops) < 1): return loop loopsUnified = booleansolid.getLoopsUnified(radius, [[loop], intersectingWithinLoops]) if (len(loopsUnified) < 1): return loop return euclidean.getLargestLoop(loopsUnified)
[ "def", "getWidenedLoop", "(", "loop", ",", "loopList", ",", "outsetLoop", ",", "radius", ")", ":", "intersectingWithinLoops", "=", "getIntersectingWithinLoops", "(", "loop", ",", "loopList", ",", "outsetLoop", ")", "if", "(", "len", "(", "intersectingWithinLoops", ")", "<", "1", ")", ":", "return", "loop", "loopsUnified", "=", "booleansolid", ".", "getLoopsUnified", "(", "radius", ",", "[", "[", "loop", "]", ",", "intersectingWithinLoops", "]", ")", "if", "(", "len", "(", "loopsUnified", ")", "<", "1", ")", ":", "return", "loop", "return", "euclidean", ".", "getLargestLoop", "(", "loopsUnified", ")" ]
get the widened loop .
train
false
22,799
def titleVariations(title, fromPtdf=0): if fromPtdf: title1 = u'' else: title1 = title title2 = title3 = u'' if (fromPtdf or re_year_index.search(title)): titldict = analyze_title(title, canonical=1) title1 = titldict['title'] if (titldict['kind'] != 'episode'): if fromPtdf: title3 = title else: title3 = build_title(titldict, canonical=1, ptdf=1) else: title1 = normalizeTitle(title1) title3 = build_title(titldict, canonical=1, ptdf=1) else: title1 = canonicalTitle(title) title3 = u'' if title1: title2 = title1 t2s = title2.split(u', ') if (t2s[(-1)].lower() in _unicodeArticles): title2 = u', '.join(t2s[:(-1)]) _aux_logger.debug('title variations: 1:[%s] 2:[%s] 3:[%s]', title1, title2, title3) return (title1, title2, title3)
[ "def", "titleVariations", "(", "title", ",", "fromPtdf", "=", "0", ")", ":", "if", "fromPtdf", ":", "title1", "=", "u''", "else", ":", "title1", "=", "title", "title2", "=", "title3", "=", "u''", "if", "(", "fromPtdf", "or", "re_year_index", ".", "search", "(", "title", ")", ")", ":", "titldict", "=", "analyze_title", "(", "title", ",", "canonical", "=", "1", ")", "title1", "=", "titldict", "[", "'title'", "]", "if", "(", "titldict", "[", "'kind'", "]", "!=", "'episode'", ")", ":", "if", "fromPtdf", ":", "title3", "=", "title", "else", ":", "title3", "=", "build_title", "(", "titldict", ",", "canonical", "=", "1", ",", "ptdf", "=", "1", ")", "else", ":", "title1", "=", "normalizeTitle", "(", "title1", ")", "title3", "=", "build_title", "(", "titldict", ",", "canonical", "=", "1", ",", "ptdf", "=", "1", ")", "else", ":", "title1", "=", "canonicalTitle", "(", "title", ")", "title3", "=", "u''", "if", "title1", ":", "title2", "=", "title1", "t2s", "=", "title2", ".", "split", "(", "u', '", ")", "if", "(", "t2s", "[", "(", "-", "1", ")", "]", ".", "lower", "(", ")", "in", "_unicodeArticles", ")", ":", "title2", "=", "u', '", ".", "join", "(", "t2s", "[", ":", "(", "-", "1", ")", "]", ")", "_aux_logger", ".", "debug", "(", "'title variations: 1:[%s] 2:[%s] 3:[%s]'", ",", "title1", ",", "title2", ",", "title3", ")", "return", "(", "title1", ",", "title2", ",", "title3", ")" ]
build title variations useful for searches; if fromptdf is true .
train
false
22,800
def non_reentrant(err_msg=None): def decorator(func): msg = err_msg if (msg is None): msg = ('%s is not re-entrant' % func.__name__) lock = ReentrancyLock(msg) return lock.decorate(func) return decorator
[ "def", "non_reentrant", "(", "err_msg", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "msg", "=", "err_msg", "if", "(", "msg", "is", "None", ")", ":", "msg", "=", "(", "'%s is not re-entrant'", "%", "func", ".", "__name__", ")", "lock", "=", "ReentrancyLock", "(", "msg", ")", "return", "lock", ".", "decorate", "(", "func", ")", "return", "decorator" ]
decorate a function with a threading lock and prevent reentrant calls .
train
false
22,801
def create_python_container(test_case, cluster, parameters, script, cleanup=True, additional_arguments=()): parameters = parameters.copy() parameters[u'image'] = u'python:2.7-slim' parameters[u'command_line'] = ([u'python2.7', u'-c', script.getContent().decode('ascii')] + list(additional_arguments)) if (u'restart_policy' not in parameters): parameters[u'restart_policy'] = {u'name': u'never'} if (u'name' not in parameters): parameters[u'name'] = random_name(test_case) creating = cluster.create_container(parameters) def created(response): if cleanup: test_case.addCleanup(cluster.remove_container, parameters[u'name']) test_case.assertEqual(response, parameters) return response creating.addCallback(created) return creating
[ "def", "create_python_container", "(", "test_case", ",", "cluster", ",", "parameters", ",", "script", ",", "cleanup", "=", "True", ",", "additional_arguments", "=", "(", ")", ")", ":", "parameters", "=", "parameters", ".", "copy", "(", ")", "parameters", "[", "u'image'", "]", "=", "u'python:2.7-slim'", "parameters", "[", "u'command_line'", "]", "=", "(", "[", "u'python2.7'", ",", "u'-c'", ",", "script", ".", "getContent", "(", ")", ".", "decode", "(", "'ascii'", ")", "]", "+", "list", "(", "additional_arguments", ")", ")", "if", "(", "u'restart_policy'", "not", "in", "parameters", ")", ":", "parameters", "[", "u'restart_policy'", "]", "=", "{", "u'name'", ":", "u'never'", "}", "if", "(", "u'name'", "not", "in", "parameters", ")", ":", "parameters", "[", "u'name'", "]", "=", "random_name", "(", "test_case", ")", "creating", "=", "cluster", ".", "create_container", "(", "parameters", ")", "def", "created", "(", "response", ")", ":", "if", "cleanup", ":", "test_case", ".", "addCleanup", "(", "cluster", ".", "remove_container", ",", "parameters", "[", "u'name'", "]", ")", "test_case", ".", "assertEqual", "(", "response", ",", "parameters", ")", "return", "response", "creating", ".", "addCallback", "(", "created", ")", "return", "creating" ]
create a python container that runs a given script .
train
false
22,802
def nic_available(interface): try: subprocess.check_call([settings.ifconfig, interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except subprocess.CalledProcessError: return False
[ "def", "nic_available", "(", "interface", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "settings", ".", "ifconfig", ",", "interface", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "return", "True", "except", "subprocess", ".", "CalledProcessError", ":", "return", "False" ]
check if specified network interface is available .
train
false
22,805
def _general_error_handler(http_error): message = str(http_error) if (http_error.respbody is not None): message += ('\n' + http_error.respbody.decode('utf-8-sig')) raise AzureHttpError(message, http_error.status)
[ "def", "_general_error_handler", "(", "http_error", ")", ":", "message", "=", "str", "(", "http_error", ")", "if", "(", "http_error", ".", "respbody", "is", "not", "None", ")", ":", "message", "+=", "(", "'\\n'", "+", "http_error", ".", "respbody", ".", "decode", "(", "'utf-8-sig'", ")", ")", "raise", "AzureHttpError", "(", "message", ",", "http_error", ".", "status", ")" ]
simple error handler for azure .
train
true
22,806
def _documents_for(locale, topics=None, products=None): documents = cache.get(_documents_for_cache_key(locale, topics, products)) if documents: statsd.incr('wiki.facets.documents_for.cache') return documents try: documents = _es_documents_for(locale, topics, products) cache.add(_documents_for_cache_key(locale, topics, products), documents) statsd.incr('wiki.facets.documents_for.es') except TransportError: documents = _db_documents_for(locale, topics, products) statsd.incr('wiki.facets.documents_for.db') return documents
[ "def", "_documents_for", "(", "locale", ",", "topics", "=", "None", ",", "products", "=", "None", ")", ":", "documents", "=", "cache", ".", "get", "(", "_documents_for_cache_key", "(", "locale", ",", "topics", ",", "products", ")", ")", "if", "documents", ":", "statsd", ".", "incr", "(", "'wiki.facets.documents_for.cache'", ")", "return", "documents", "try", ":", "documents", "=", "_es_documents_for", "(", "locale", ",", "topics", ",", "products", ")", "cache", ".", "add", "(", "_documents_for_cache_key", "(", "locale", ",", "topics", ",", "products", ")", ",", "documents", ")", "statsd", ".", "incr", "(", "'wiki.facets.documents_for.es'", ")", "except", "TransportError", ":", "documents", "=", "_db_documents_for", "(", "locale", ",", "topics", ",", "products", ")", "statsd", ".", "incr", "(", "'wiki.facets.documents_for.db'", ")", "return", "documents" ]
returns a list of articles that apply to passed in topics and products .
train
false
22,807
def test_ast_valid_if(): can_compile(u'(if* foo bar)')
[ "def", "test_ast_valid_if", "(", ")", ":", "can_compile", "(", "u'(if* foo bar)'", ")" ]
make sure ast can compile valid if* .
train
false
22,809
def get_node_value(json_object, parent_node_name, child_node_name=None): if (not json_object): return None if (not parent_node_name): return None detail = json_object[parent_node_name] if (not child_node_name): return detail return_value = None if (child_node_name in detail): return_value = detail[child_node_name] else: return_value = None return return_value
[ "def", "get_node_value", "(", "json_object", ",", "parent_node_name", ",", "child_node_name", "=", "None", ")", ":", "if", "(", "not", "json_object", ")", ":", "return", "None", "if", "(", "not", "parent_node_name", ")", ":", "return", "None", "detail", "=", "json_object", "[", "parent_node_name", "]", "if", "(", "not", "child_node_name", ")", ":", "return", "detail", "return_value", "=", "None", "if", "(", "child_node_name", "in", "detail", ")", ":", "return_value", "=", "detail", "[", "child_node_name", "]", "else", ":", "return_value", "=", "None", "return", "return_value" ]
returns value of given child_node .
train
false
22,810
def getComplex(x=0.0, y=0.0): return complex(x, y)
[ "def", "getComplex", "(", "x", "=", "0.0", ",", "y", "=", "0.0", ")", ":", "return", "complex", "(", "x", ",", "y", ")" ]
get the complex .
train
false
22,811
def load_support_plugin(name): stack = list(filter((lambda f: (f[3] == '<module>')), inspect.stack())) prev_frame = stack[0] path = os.path.dirname(prev_frame[1]) if (not os.path.isabs(path)): prefix = os.path.normpath((__file__ + '../../../../../')) path = os.path.join(prefix, path) if ((sys.version_info[0] == 3) and (sys.version_info[1] >= 3)): import importlib loader = importlib.find_loader(name, [path]) if loader: module = loader.load_module() else: raise ImportError("No module named '{0}'".format(name)) else: import imp (fd, filename, desc) = imp.find_module(name, [path]) try: module = imp.load_module(name, fd, filename, desc) finally: if fd: fd.close() return module
[ "def", "load_support_plugin", "(", "name", ")", ":", "stack", "=", "list", "(", "filter", "(", "(", "lambda", "f", ":", "(", "f", "[", "3", "]", "==", "'<module>'", ")", ")", ",", "inspect", ".", "stack", "(", ")", ")", ")", "prev_frame", "=", "stack", "[", "0", "]", "path", "=", "os", ".", "path", ".", "dirname", "(", "prev_frame", "[", "1", "]", ")", "if", "(", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ")", ":", "prefix", "=", "os", ".", "path", ".", "normpath", "(", "(", "__file__", "+", "'../../../../../'", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "path", ")", "if", "(", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "and", "(", "sys", ".", "version_info", "[", "1", "]", ">=", "3", ")", ")", ":", "import", "importlib", "loader", "=", "importlib", ".", "find_loader", "(", "name", ",", "[", "path", "]", ")", "if", "loader", ":", "module", "=", "loader", ".", "load_module", "(", ")", "else", ":", "raise", "ImportError", "(", "\"No module named '{0}'\"", ".", "format", "(", "name", ")", ")", "else", ":", "import", "imp", "(", "fd", ",", "filename", ",", "desc", ")", "=", "imp", ".", "find_module", "(", "name", ",", "[", "path", "]", ")", "try", ":", "module", "=", "imp", ".", "load_module", "(", "name", ",", "fd", ",", "filename", ",", "desc", ")", "finally", ":", "if", "fd", ":", "fd", ".", "close", "(", ")", "return", "module" ]
loads a plugin from the same directory as the calling plugin .
train
false
22,815
def compute_fill_first_cost_fn(host_state, weight_properties): return (- host_state.free_ram_mb)
[ "def", "compute_fill_first_cost_fn", "(", "host_state", ",", "weight_properties", ")", ":", "return", "(", "-", "host_state", ".", "free_ram_mb", ")" ]
higher weights win .
train
false
22,816
def isCocoaTk(): assert (_tk_type is not None) return (_tk_type == 'cocoa')
[ "def", "isCocoaTk", "(", ")", ":", "assert", "(", "_tk_type", "is", "not", "None", ")", "return", "(", "_tk_type", "==", "'cocoa'", ")" ]
returns true if idle is using a cocoa aqua tk .
train
false
22,817
def _SetWsdlType(ns, wsdlName, typ): return _wsdlTypeMap.setdefault((ns, wsdlName), typ)
[ "def", "_SetWsdlType", "(", "ns", ",", "wsdlName", ",", "typ", ")", ":", "return", "_wsdlTypeMap", ".", "setdefault", "(", "(", "ns", ",", "wsdlName", ")", ",", "typ", ")" ]
set a wsdl type with wsdl namespace and wsdl name .
train
false
22,818
@requires_application() def test_arc_draw1(): with TestingCanvas() as c: ellipse = visuals.Ellipse(center=(50.0, 50.0), radius=(20, 15), start_angle=150.0, span_angle=120.0, color=(0, 0, 1, 1), parent=c.scene) assert_image_approved(c.render(), 'visuals/arc1.png') ellipse.parent = None ellipse = visuals.Ellipse(center=(50.0, 50.0), radius=(20, 15), start_angle=150.0, span_angle=120.0, border_color=(1, 0, 0, 1), parent=c.scene) assert_image_approved(c.render(), 'visuals/arc2.png', min_corr=0.6)
[ "@", "requires_application", "(", ")", "def", "test_arc_draw1", "(", ")", ":", "with", "TestingCanvas", "(", ")", "as", "c", ":", "ellipse", "=", "visuals", ".", "Ellipse", "(", "center", "=", "(", "50.0", ",", "50.0", ")", ",", "radius", "=", "(", "20", ",", "15", ")", ",", "start_angle", "=", "150.0", ",", "span_angle", "=", "120.0", ",", "color", "=", "(", "0", ",", "0", ",", "1", ",", "1", ")", ",", "parent", "=", "c", ".", "scene", ")", "assert_image_approved", "(", "c", ".", "render", "(", ")", ",", "'visuals/arc1.png'", ")", "ellipse", ".", "parent", "=", "None", "ellipse", "=", "visuals", ".", "Ellipse", "(", "center", "=", "(", "50.0", ",", "50.0", ")", ",", "radius", "=", "(", "20", ",", "15", ")", ",", "start_angle", "=", "150.0", ",", "span_angle", "=", "120.0", ",", "border_color", "=", "(", "1", ",", "0", ",", "0", ",", "1", ")", ",", "parent", "=", "c", ".", "scene", ")", "assert_image_approved", "(", "c", ".", "render", "(", ")", ",", "'visuals/arc2.png'", ",", "min_corr", "=", "0.6", ")" ]
test drawing arcs using ellipsevisual .
train
false
22,819
def track_sunrise(offset=None): def track_sunrise_decorator(action): 'Decorator to track sunrise events.' event.track_sunrise(HASS, functools.partial(action, HASS), offset) return action return track_sunrise_decorator
[ "def", "track_sunrise", "(", "offset", "=", "None", ")", ":", "def", "track_sunrise_decorator", "(", "action", ")", ":", "event", ".", "track_sunrise", "(", "HASS", ",", "functools", ".", "partial", "(", "action", ",", "HASS", ")", ",", "offset", ")", "return", "action", "return", "track_sunrise_decorator" ]
decorator factory to track sunrise events .
train
false
22,820
@mock_ec2 def test_dhcp_options_associate_invalid_vpc_id(): conn = boto.connect_vpc(u'the_key', u'the_secret') dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS) with assert_raises(EC2ResponseError) as cm: conn.associate_dhcp_options(dhcp_options.id, u'foo') cm.exception.code.should.equal(u'InvalidVpcID.NotFound') cm.exception.status.should.equal(400) cm.exception.request_id.should_not.be.none
[ "@", "mock_ec2", "def", "test_dhcp_options_associate_invalid_vpc_id", "(", ")", ":", "conn", "=", "boto", ".", "connect_vpc", "(", "u'the_key'", ",", "u'the_secret'", ")", "dhcp_options", "=", "conn", ".", "create_dhcp_options", "(", "SAMPLE_DOMAIN_NAME", ",", "SAMPLE_NAME_SERVERS", ")", "with", "assert_raises", "(", "EC2ResponseError", ")", "as", "cm", ":", "conn", ".", "associate_dhcp_options", "(", "dhcp_options", ".", "id", ",", "u'foo'", ")", "cm", ".", "exception", ".", "code", ".", "should", ".", "equal", "(", "u'InvalidVpcID.NotFound'", ")", "cm", ".", "exception", ".", "status", ".", "should", ".", "equal", "(", "400", ")", "cm", ".", "exception", ".", "request_id", ".", "should_not", ".", "be", ".", "none" ]
associate dhcp option invalid vpc id .
train
false