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 |
|---|---|---|---|---|---|
27,859 | def _getAvatar(acc):
pimg = (('avatars/' + acc) + '.jpeg')
return ((pimg, None) if os.path.exists(pimg) else ('/Applications/Skype.app', 'fileicon'))
| [
"def",
"_getAvatar",
"(",
"acc",
")",
":",
"pimg",
"=",
"(",
"(",
"'avatars/'",
"+",
"acc",
")",
"+",
"'.jpeg'",
")",
"return",
"(",
"(",
"pimg",
",",
"None",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pimg",
")",
"else",
"(",
"'/Applicat... | get the path for the avatar image of a user . | train | false |
27,860 | def get_request_ip_resolver():
(module, attribute) = get_cms_setting('REQUEST_IP_RESOLVER').rsplit('.', 1)
try:
ip_resolver_module = importlib.import_module(module)
ip_resolver = getattr(ip_resolver_module, attribute)
except ImportError:
raise ImproperlyConfigured(_('Unable to find the specified CMS_REQUEST_IP_RESOLVER module: "{0}".').format(module))
except AttributeError:
raise ImproperlyConfigured(_('Unable to find the specified CMS_REQUEST_IP_RESOLVER function: "{0}" in module "{1}".').format(attribute, module))
return ip_resolver
| [
"def",
"get_request_ip_resolver",
"(",
")",
":",
"(",
"module",
",",
"attribute",
")",
"=",
"get_cms_setting",
"(",
"'REQUEST_IP_RESOLVER'",
")",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"ip_resolver_module",
"=",
"importlib",
".",
"import_module"... | this is the recommended method for obtaining the specified cms_request_ip_resolver as it also does some basic import validation . | train | false |
27,861 | def plugin_pack(app, plugin_name, request):
try:
filename = apath(('../deposit/web2py.plugin.%s.w2p' % plugin_name), request)
w2p_pack_plugin(filename, apath(app, request), plugin_name)
return filename
except Exception:
return False
| [
"def",
"plugin_pack",
"(",
"app",
",",
"plugin_name",
",",
"request",
")",
":",
"try",
":",
"filename",
"=",
"apath",
"(",
"(",
"'../deposit/web2py.plugin.%s.w2p'",
"%",
"plugin_name",
")",
",",
"request",
")",
"w2p_pack_plugin",
"(",
"filename",
",",
"apath",... | builds a w2p package for the plugin args: app: application name plugin_name: the name of the plugin without plugin_ prefix request: the current request app returns: filename of the w2p file or false on error . | train | false |
27,863 | def _unwindk(z):
return int(np.ceil(((z.imag - np.pi) / (2 * np.pi))))
| [
"def",
"_unwindk",
"(",
"z",
")",
":",
"return",
"int",
"(",
"np",
".",
"ceil",
"(",
"(",
"(",
"z",
".",
"imag",
"-",
"np",
".",
"pi",
")",
"/",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
")",
")"
] | compute the scalar unwinding number . | train | false |
27,864 | def construct_superclient(conf):
(service, protocol, transport) = connect_to_thrift(conf)
return SuperClient(service, transport, timeout_seconds=conf.timeout_seconds)
| [
"def",
"construct_superclient",
"(",
"conf",
")",
":",
"(",
"service",
",",
"protocol",
",",
"transport",
")",
"=",
"connect_to_thrift",
"(",
"conf",
")",
"return",
"SuperClient",
"(",
"service",
",",
"transport",
",",
"timeout_seconds",
"=",
"conf",
".",
"t... | constructs a thrift client . | train | false |
27,865 | def channel_session_user(func):
@channel_session
@functools.wraps(func)
def inner(message, *args, **kwargs):
if (not hasattr(message, 'channel_session')):
raise ValueError('Did not see a channel session to get auth from')
if (message.channel_session is None):
from django.contrib.auth.models import AnonymousUser
message.user = AnonymousUser()
else:
fake_request = type('FakeRequest', (object,), {'session': message.channel_session})
message.user = auth.get_user(fake_request)
return func(message, *args, **kwargs)
return inner
| [
"def",
"channel_session_user",
"(",
"func",
")",
":",
"@",
"channel_session",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"message",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"message"... | presents a message . | train | false |
27,866 | def clearCache(indexerid=0):
cache_db_con = db.DBConnection('cache.db')
cache_db_con.action('DELETE FROM scene_names WHERE indexer_id = ? OR indexer_id = ?', (indexerid, 0))
toRemove = [key for (key, value) in nameCache.iteritems() if (value in (0, indexerid))]
for key in toRemove:
del nameCache[key]
| [
"def",
"clearCache",
"(",
"indexerid",
"=",
"0",
")",
":",
"cache_db_con",
"=",
"db",
".",
"DBConnection",
"(",
"'cache.db'",
")",
"cache_db_con",
".",
"action",
"(",
"'DELETE FROM scene_names WHERE indexer_id = ? OR indexer_id = ?'",
",",
"(",
"indexerid",
",",
"0"... | deletes all "unknown" entries from the cache . | train | false |
27,867 | def dictlike_iteritems(dictlike):
if compat.py3k:
if hasattr(dictlike, 'items'):
return list(dictlike.items())
elif hasattr(dictlike, 'iteritems'):
return dictlike.iteritems()
elif hasattr(dictlike, 'items'):
return iter(dictlike.items())
getter = getattr(dictlike, '__getitem__', getattr(dictlike, 'get', None))
if (getter is None):
raise TypeError(("Object '%r' is not dict-like" % dictlike))
if hasattr(dictlike, 'iterkeys'):
def iterator():
for key in dictlike.iterkeys():
(yield (key, getter(key)))
return iterator()
elif hasattr(dictlike, 'keys'):
return iter(((key, getter(key)) for key in dictlike.keys()))
else:
raise TypeError(("Object '%r' is not dict-like" % dictlike))
| [
"def",
"dictlike_iteritems",
"(",
"dictlike",
")",
":",
"if",
"compat",
".",
"py3k",
":",
"if",
"hasattr",
"(",
"dictlike",
",",
"'items'",
")",
":",
"return",
"list",
"(",
"dictlike",
".",
"items",
"(",
")",
")",
"elif",
"hasattr",
"(",
"dictlike",
",... | return a iterator for almost any dict-like object . | train | false |
27,868 | def h2_safe_headers(headers):
stripped = {i.lower().strip() for (k, v) in headers if (k == 'connection') for i in v.split(',')}
stripped.add('connection')
return [header for header in headers if (header[0] not in stripped)]
| [
"def",
"h2_safe_headers",
"(",
"headers",
")",
":",
"stripped",
"=",
"{",
"i",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"headers",
"if",
"(",
"k",
"==",
"'connection'",
")",
"for",
"i",
"in",
"v",
".... | this method takes a set of headers that are provided by the user and transforms them into a form that is safe for emitting over http/2 . | train | false |
27,870 | def _regexSearchRegPolData(search_string, policy_data):
if policy_data:
if search_string:
match = re.search(search_string, policy_data, re.IGNORECASE)
if match:
return True
return False
| [
"def",
"_regexSearchRegPolData",
"(",
"search_string",
",",
"policy_data",
")",
":",
"if",
"policy_data",
":",
"if",
"search_string",
":",
"match",
"=",
"re",
".",
"search",
"(",
"search_string",
",",
"policy_data",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"... | helper function to do a search of policy data from a registry . | train | true |
27,871 | def getarray_nofancy(a, b, lock=None):
return getarray(a, b, lock=lock)
| [
"def",
"getarray_nofancy",
"(",
"a",
",",
"b",
",",
"lock",
"=",
"None",
")",
":",
"return",
"getarray",
"(",
"a",
",",
"b",
",",
"lock",
"=",
"lock",
")"
] | a simple wrapper around getarray . | train | false |
27,872 | def _color_text(text, color):
color_mapping = {u'black': u'0;30', u'red': u'0;31', u'green': u'0;32', u'brown': u'0;33', u'blue': u'0;34', u'magenta': u'0;35', u'cyan': u'0;36', u'lightgrey': u'0;37', u'default': u'0;39', u'darkgrey': u'1;30', u'lightred': u'1;31', u'lightgreen': u'1;32', u'yellow': u'1;33', u'lightblue': u'1;34', u'lightmagenta': u'1;35', u'lightcyan': u'1;36', u'white': u'1;37'}
if ((sys.platform == u'win32') and (OutStream is None)):
return text
color_code = color_mapping.get(color, u'0;39')
return u'\x1b[{0}m{1}\x1b[0m'.format(color_code, text)
| [
"def",
"_color_text",
"(",
"text",
",",
"color",
")",
":",
"color_mapping",
"=",
"{",
"u'black'",
":",
"u'0;30'",
",",
"u'red'",
":",
"u'0;31'",
",",
"u'green'",
":",
"u'0;32'",
",",
"u'brown'",
":",
"u'0;33'",
",",
"u'blue'",
":",
"u'0;34'",
",",
"u'mag... | returns a string wrapped in ansi color codes for coloring the text in a terminal:: colored_text = color_text this wont actually effect the text until it is printed to the terminal . | train | false |
27,873 | def get_url_prefixer():
return getattr(_locals, 'prefixer', None)
| [
"def",
"get_url_prefixer",
"(",
")",
":",
"return",
"getattr",
"(",
"_locals",
",",
"'prefixer'",
",",
"None",
")"
] | get the prefixer for the current thread . | train | false |
27,874 | def ReportTestResult(name, metadata):
now = time.time()
colorizer = Colorizer()
if (metadata['exit_code'] == 0):
result = colorizer.Render('GREEN', 'PASSED')
else:
result = colorizer.Render('RED', 'FAILED')
result += open(metadata['output_path'], 'rb').read()
print ' DCTB {0: <40} {1} in {2: >6.2f}s'.format(name, result, (now - metadata['start']))
| [
"def",
"ReportTestResult",
"(",
"name",
",",
"metadata",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"colorizer",
"=",
"Colorizer",
"(",
")",
"if",
"(",
"metadata",
"[",
"'exit_code'",
"]",
"==",
"0",
")",
":",
"result",
"=",
"colorizer",
".... | print statistics about the outcome of a test run . | train | false |
27,875 | def demographic_data():
return s3_rest_controller()
| [
"def",
"demographic_data",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | restful crud controller . | train | false |
27,876 | def unicode_to_str(s, encoding=None):
if (not (type(s) == unicode)):
return s
if (not encoding):
encoding = ENCODING
for c in [encoding, 'utf-8', 'latin-1']:
try:
return s.encode(c)
except UnicodeDecodeError:
pass
return s.encode(encoding, 'replace')
| [
"def",
"unicode_to_str",
"(",
"s",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"(",
"not",
"(",
"type",
"(",
"s",
")",
"==",
"unicode",
")",
")",
":",
"return",
"s",
"if",
"(",
"not",
"encoding",
")",
":",
"encoding",
"=",
"ENCODING",
"for",
"c... | return the str representation of text in the given encoding . | train | false |
27,877 | def _apply_if_callable(maybe_callable, obj, **kwargs):
if callable(maybe_callable):
return maybe_callable(obj, **kwargs)
return maybe_callable
| [
"def",
"_apply_if_callable",
"(",
"maybe_callable",
",",
"obj",
",",
"**",
"kwargs",
")",
":",
"if",
"callable",
"(",
"maybe_callable",
")",
":",
"return",
"maybe_callable",
"(",
"obj",
",",
"**",
"kwargs",
")",
"return",
"maybe_callable"
] | evaluate possibly callable input using obj and kwargs if it is callable . | train | false |
27,878 | @app.route('/call/receive', methods=['POST'])
def receive_call():
response = twiml.Response()
response.say('Hello from Twilio!')
return (str(response), 200, {'Content-Type': 'application/xml'})
| [
"@",
"app",
".",
"route",
"(",
"'/call/receive'",
",",
"methods",
"=",
"[",
"'POST'",
"]",
")",
"def",
"receive_call",
"(",
")",
":",
"response",
"=",
"twiml",
".",
"Response",
"(",
")",
"response",
".",
"say",
"(",
"'Hello from Twilio!'",
")",
"return",... | answers a call and replies with a simple greeting . | train | false |
27,880 | def course_wiki_slug(course):
slug = course.wiki_slug
if slug_is_numerical(slug):
slug = (slug + '_')
return slug
| [
"def",
"course_wiki_slug",
"(",
"course",
")",
":",
"slug",
"=",
"course",
".",
"wiki_slug",
"if",
"slug_is_numerical",
"(",
"slug",
")",
":",
"slug",
"=",
"(",
"slug",
"+",
"'_'",
")",
"return",
"slug"
] | returns the slug for the course wiki root . | train | false |
27,882 | def simple_hash(text, key='', salt='', digest_alg='md5'):
text = to_bytes(text)
key = to_bytes(key)
salt = to_bytes(salt)
if (not digest_alg):
raise RuntimeError('simple_hash with digest_alg=None')
elif (not isinstance(digest_alg, str)):
h = digest_alg(((text + key) + salt))
elif digest_alg.startswith('pbkdf2'):
(iterations, keylen, alg) = digest_alg[7:(-1)].split(',')
return to_native(pbkdf2_hex(text, salt, int(iterations), int(keylen), get_digest(alg)))
elif key:
digest_alg = get_digest(digest_alg)
h = hmac.new((key + salt), text, digest_alg)
else:
h = get_digest(digest_alg)()
h.update((text + salt))
return h.hexdigest()
| [
"def",
"simple_hash",
"(",
"text",
",",
"key",
"=",
"''",
",",
"salt",
"=",
"''",
",",
"digest_alg",
"=",
"'md5'",
")",
":",
"text",
"=",
"to_bytes",
"(",
"text",
")",
"key",
"=",
"to_bytes",
"(",
"key",
")",
"salt",
"=",
"to_bytes",
"(",
"salt",
... | generate hash with the given text using the specified digest algorithm . | train | false |
27,884 | def getAKAsInLanguage(movie, lang, _searchedTitle=None):
akas = []
for (language, aka) in akasLanguages(movie):
if (lang == language):
akas.append(aka)
if _searchedTitle:
scores = []
if isinstance(_searchedTitle, unicode):
_searchedTitle = _searchedTitle.encode('utf8')
for aka in akas:
m_aka = aka
if isinstance(m_aka):
m_aka = m_aka.encode('utf8')
scores.append(difflib.SequenceMatcher(None, m_aka.lower(), _searchedTitle.lower()), aka)
scores.sort(reverse=True)
akas = [x[1] for x in scores]
return akas
| [
"def",
"getAKAsInLanguage",
"(",
"movie",
",",
"lang",
",",
"_searchedTitle",
"=",
"None",
")",
":",
"akas",
"=",
"[",
"]",
"for",
"(",
"language",
",",
"aka",
")",
"in",
"akasLanguages",
"(",
"movie",
")",
":",
"if",
"(",
"lang",
"==",
"language",
"... | return a list of akas of a movie . | train | false |
27,885 | def _execute_array_values(evaluator, array):
if isinstance(array, Array):
values = []
for types in array.py__iter__():
objects = set(chain.from_iterable((_execute_array_values(evaluator, typ) for typ in types)))
values.append(AlreadyEvaluated(objects))
return [FakeSequence(evaluator, values, array.type)]
else:
return evaluator.execute(array)
| [
"def",
"_execute_array_values",
"(",
"evaluator",
",",
"array",
")",
":",
"if",
"isinstance",
"(",
"array",
",",
"Array",
")",
":",
"values",
"=",
"[",
"]",
"for",
"types",
"in",
"array",
".",
"py__iter__",
"(",
")",
":",
"objects",
"=",
"set",
"(",
... | tuples indicate that theres not just one return value . | train | false |
27,886 | def priority_sorter(registry, xml_parent, data):
priority_sorter_tag = XML.SubElement(xml_parent, 'hudson.queueSorter.PrioritySorterJobProperty')
try:
XML.SubElement(priority_sorter_tag, 'priority').text = str(data['priority'])
except KeyError as e:
raise MissingAttributeError(e)
| [
"def",
"priority_sorter",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"priority_sorter_tag",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.queueSorter.PrioritySorterJobProperty'",
")",
"try",
":",
"XML",
".",
"SubElement",
"(",
"pr... | yaml: priority-sorter allows simple ordering of builds . | train | false |
27,887 | @api_view(['GET'])
@mobile_view()
def my_user_info(request):
return redirect('user-detail', username=request.user.username)
| [
"@",
"api_view",
"(",
"[",
"'GET'",
"]",
")",
"@",
"mobile_view",
"(",
")",
"def",
"my_user_info",
"(",
"request",
")",
":",
"return",
"redirect",
"(",
"'user-detail'",
",",
"username",
"=",
"request",
".",
"user",
".",
"username",
")"
] | redirect to the currently-logged-in users info page . | train | false |
27,888 | def _get_split_size(split_size):
if isinstance(split_size, string_types):
exp = dict(MB=20, GB=30).get(split_size[(-2):], None)
if (exp is None):
raise ValueError('split_size has to end with either"MB" or "GB"')
split_size = int((float(split_size[:(-2)]) * (2 ** exp)))
if (split_size > 2147483648):
raise ValueError('split_size cannot be larger than 2GB')
return split_size
| [
"def",
"_get_split_size",
"(",
"split_size",
")",
":",
"if",
"isinstance",
"(",
"split_size",
",",
"string_types",
")",
":",
"exp",
"=",
"dict",
"(",
"MB",
"=",
"20",
",",
"GB",
"=",
"30",
")",
".",
"get",
"(",
"split_size",
"[",
"(",
"-",
"2",
")"... | convert human-readable bytes to machine-readable bytes . | train | false |
27,889 | def regionprops(label_image, intensity_image=None, cache=True):
label_image = np.squeeze(label_image)
if (label_image.ndim not in (2, 3)):
raise TypeError('Only 2-D and 3-D images supported.')
if (not np.issubdtype(label_image.dtype, np.integer)):
raise TypeError('Label image must be of integral type.')
regions = []
objects = ndi.find_objects(label_image)
for (i, sl) in enumerate(objects):
if (sl is None):
continue
label = (i + 1)
props = _RegionProperties(sl, label, label_image, intensity_image, cache)
regions.append(props)
return regions
| [
"def",
"regionprops",
"(",
"label_image",
",",
"intensity_image",
"=",
"None",
",",
"cache",
"=",
"True",
")",
":",
"label_image",
"=",
"np",
".",
"squeeze",
"(",
"label_image",
")",
"if",
"(",
"label_image",
".",
"ndim",
"not",
"in",
"(",
"2",
",",
"3... | measure properties of labeled image regions . | train | false |
27,890 | def _positional(max_pos_args):
def positional_decorator(wrapped):
@functools.wraps(wrapped)
def positional_wrapper(*args, **kwds):
if (len(args) > max_pos_args):
plural_s = ''
if (max_pos_args != 1):
plural_s = 's'
raise TypeError(('%s() takes at most %d positional argument%s (%d given)' % (wrapped.__name__, max_pos_args, plural_s, len(args))))
return wrapped(*args, **kwds)
return positional_wrapper
return positional_decorator
| [
"def",
"_positional",
"(",
"max_pos_args",
")",
":",
"def",
"positional_decorator",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"positional_wrapper",
"(",
"*",
"args",
",",
"**",
"kwds",
")",
":",
"if",
"(",
"len... | a decorator to declare that only the first n arguments may be positional . | train | false |
27,891 | def Merge(text, message):
_ParseOrMerge(text, message, True)
| [
"def",
"Merge",
"(",
"text",
",",
"message",
")",
":",
"_ParseOrMerge",
"(",
"text",
",",
"message",
",",
"True",
")"
] | parses an ascii representation of a protocol message into a message . | train | false |
27,892 | def patch_socket(dns=True, aggressive=True):
from gevent import socket
if dns:
items = socket.__implements__
else:
items = (set(socket.__implements__) - set(socket.__dns__))
patch_module('socket', items=items)
if aggressive:
if ('ssl' not in socket.__implements__):
remove_item(socket, 'ssl')
| [
"def",
"patch_socket",
"(",
"dns",
"=",
"True",
",",
"aggressive",
"=",
"True",
")",
":",
"from",
"gevent",
"import",
"socket",
"if",
"dns",
":",
"items",
"=",
"socket",
".",
"__implements__",
"else",
":",
"items",
"=",
"(",
"set",
"(",
"socket",
".",
... | replace the standard socket object with gevents cooperative sockets . | train | false |
27,893 | def dsu(list, key):
warnings.warn('dsu is deprecated since Twisted 10.1. Use the built-in sorted() instead.', DeprecationWarning, stacklevel=2)
L2 = [(key(e), i, e) for (i, e) in zip(range(len(list)), list)]
L2.sort()
return [e[2] for e in L2]
| [
"def",
"dsu",
"(",
"list",
",",
"key",
")",
":",
"warnings",
".",
"warn",
"(",
"'dsu is deprecated since Twisted 10.1. Use the built-in sorted() instead.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"L2",
"=",
"[",
"(",
"key",
"(",
"e",
")",
... | decorate-sort-undecorate deprecated . | train | false |
27,894 | def mark(obj, map_class=Map, sequence_class=Sequence):
if isinstance(obj, Aggregate):
return obj
if isinstance(obj, dict):
return map_class(obj)
if isinstance(obj, (list, tuple, set)):
return sequence_class(obj)
else:
return sequence_class([obj])
| [
"def",
"mark",
"(",
"obj",
",",
"map_class",
"=",
"Map",
",",
"sequence_class",
"=",
"Sequence",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Aggregate",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"... | convert obj into an aggregate instance . | train | true |
27,896 | def send_broadcast(namespace, type, payload):
frame = {'type': type, 'payload': payload}
amqp.add_item(routing_key=namespace, body=json.dumps(frame), exchange=_WEBSOCKET_EXCHANGE)
| [
"def",
"send_broadcast",
"(",
"namespace",
",",
"type",
",",
"payload",
")",
":",
"frame",
"=",
"{",
"'type'",
":",
"type",
",",
"'payload'",
":",
"payload",
"}",
"amqp",
".",
"add_item",
"(",
"routing_key",
"=",
"namespace",
",",
"body",
"=",
"json",
... | broadcast an object to all websocket listeners in a namespace . | train | false |
27,897 | def count_contributors_in_range(queryset, users, date_range):
(start, end) = date_range
users = set((o.creator for o in queryset.filter(creator__in=users, created__gte=start, created__lt=end)))
return len(users)
| [
"def",
"count_contributors_in_range",
"(",
"queryset",
",",
"users",
",",
"date_range",
")",
":",
"(",
"start",
",",
"end",
")",
"=",
"date_range",
"users",
"=",
"set",
"(",
"(",
"o",
".",
"creator",
"for",
"o",
"in",
"queryset",
".",
"filter",
"(",
"c... | of the group users . | train | false |
27,898 | def _has_unexpected_italian_leading_zero(numobj):
return (numobj.italian_leading_zero and (not _is_leading_zero_possible(numobj.country_code)))
| [
"def",
"_has_unexpected_italian_leading_zero",
"(",
"numobj",
")",
":",
"return",
"(",
"numobj",
".",
"italian_leading_zero",
"and",
"(",
"not",
"_is_leading_zero_possible",
"(",
"numobj",
".",
"country_code",
")",
")",
")"
] | returns true if a number is from a region whose national significant number couldnt contain a leading zero . | train | false |
27,900 | def column_group_by(column, keys):
from .table import Table
if isinstance(keys, Table):
keys = keys.as_array()
if (not isinstance(keys, np.ndarray)):
raise TypeError(u'Keys input must be numpy array, but got {0}'.format(type(keys)))
if (len(keys) != len(column)):
raise ValueError(u'Input keys array length {0} does not match column length {1}'.format(len(keys), len(column)))
index = None
if isinstance(keys, Table):
index = get_index(keys)
elif (hasattr(keys, u'indices') and keys.indices):
index = keys.indices[0]
if (index is not None):
idx_sort = index.sorted_data()
else:
idx_sort = keys.argsort()
keys = keys[idx_sort]
diffs = np.concatenate(([True], (keys[1:] != keys[:(-1)]), [True]))
indices = np.flatnonzero(diffs)
out = column.__class__(column[idx_sort])
out._groups = ColumnGroups(out, indices=indices, keys=keys[indices[:(-1)]])
return out
| [
"def",
"column_group_by",
"(",
"column",
",",
"keys",
")",
":",
"from",
".",
"table",
"import",
"Table",
"if",
"isinstance",
"(",
"keys",
",",
"Table",
")",
":",
"keys",
"=",
"keys",
".",
"as_array",
"(",
")",
"if",
"(",
"not",
"isinstance",
"(",
"ke... | get groups for column on specified keys parameters column : column object column to group keys : table or numpy array of same length as col grouping key specifier returns grouped_column : column object with groups attr set accordingly . | train | false |
27,901 | def constant(value):
return TT.constant(numpy.asarray(value, dtype=theano.config.floatX))
| [
"def",
"constant",
"(",
"value",
")",
":",
"return",
"TT",
".",
"constant",
"(",
"numpy",
".",
"asarray",
"(",
"value",
",",
"dtype",
"=",
"theano",
".",
"config",
".",
"floatX",
")",
")"
] | zero order polynomial regression model . | train | false |
27,902 | def RegisterShellInfo(searchPaths):
import regutil, win32con
suffix = IsDebug()
exePath = FindRegisterPythonExe(('Python%s.exe' % suffix), searchPaths)
regutil.SetRegistryDefaultValue('.py', 'Python.File', win32con.HKEY_CLASSES_ROOT)
regutil.RegisterShellCommand('Open', (QuotedFileName(exePath) + ' "%1" %*'), '&Run')
regutil.SetRegistryDefaultValue('Python.File\\DefaultIcon', ('%s,0' % exePath), win32con.HKEY_CLASSES_ROOT)
FindRegisterHelpFile('Python.hlp', searchPaths, 'Main Python Documentation')
FindRegisterHelpFile('ActivePython.chm', searchPaths, 'Main Python Documentation')
| [
"def",
"RegisterShellInfo",
"(",
"searchPaths",
")",
":",
"import",
"regutil",
",",
"win32con",
"suffix",
"=",
"IsDebug",
"(",
")",
"exePath",
"=",
"FindRegisterPythonExe",
"(",
"(",
"'Python%s.exe'",
"%",
"suffix",
")",
",",
"searchPaths",
")",
"regutil",
"."... | registers key parts of the python installation with the windows shell . | train | false |
27,903 | def test_all_sparktext():
chart = Line()
chart.add('_', range(8))
assert (chart.render_sparktext() == u('\xe2\x96\x81\xe2\x96\x82\xe2\x96\x83\xe2\x96\x84\xe2\x96\x85\xe2\x96\x86\xe2\x96\x87\xe2\x96\x88'))
| [
"def",
"test_all_sparktext",
"(",
")",
":",
"chart",
"=",
"Line",
"(",
")",
"chart",
".",
"add",
"(",
"'_'",
",",
"range",
"(",
"8",
")",
")",
"assert",
"(",
"chart",
".",
"render_sparktext",
"(",
")",
"==",
"u",
"(",
"'\\xe2\\x96\\x81\\xe2\\x96\\x82\\xe... | test all character sparktext . | train | false |
27,904 | def fix_osmesa_gl_lib():
if ('VISPY_GL_LIB' in os.environ):
logger.warning('VISPY_GL_LIB is ignored when using OSMesa. Use OSMESA_LIBRARY instead.')
os.environ['VISPY_GL_LIB'] = os.getenv('OSMESA_LIBRARY', 'libOSMesa.so')
| [
"def",
"fix_osmesa_gl_lib",
"(",
")",
":",
"if",
"(",
"'VISPY_GL_LIB'",
"in",
"os",
".",
"environ",
")",
":",
"logger",
".",
"warning",
"(",
"'VISPY_GL_LIB is ignored when using OSMesa. Use OSMESA_LIBRARY instead.'",
")",
"os",
".",
"environ",
"[",
"'VISPY_GL_LIB'",
... | when using osmesa . | train | false |
27,906 | def _get_aspect(evoked, allow_maxshield):
is_maxshield = False
aspect = dir_tree_find(evoked, FIFF.FIFFB_ASPECT)
if (len(aspect) == 0):
_check_maxshield(allow_maxshield)
aspect = dir_tree_find(evoked, FIFF.FIFFB_SMSH_ASPECT)
is_maxshield = True
if (len(aspect) > 1):
logger.info('Multiple data aspects found. Taking first one.')
return (aspect[0], is_maxshield)
| [
"def",
"_get_aspect",
"(",
"evoked",
",",
"allow_maxshield",
")",
":",
"is_maxshield",
"=",
"False",
"aspect",
"=",
"dir_tree_find",
"(",
"evoked",
",",
"FIFF",
".",
"FIFFB_ASPECT",
")",
"if",
"(",
"len",
"(",
"aspect",
")",
"==",
"0",
")",
":",
"_check_... | get evoked data aspect . | train | false |
27,907 | def upgradeDatabase(connection, schema):
logger.log((u'Checking database structure...' + connection.filename), logger.DEBUG)
_processUpgrade(connection, schema)
| [
"def",
"upgradeDatabase",
"(",
"connection",
",",
"schema",
")",
":",
"logger",
".",
"log",
"(",
"(",
"u'Checking database structure...'",
"+",
"connection",
".",
"filename",
")",
",",
"logger",
".",
"DEBUG",
")",
"_processUpgrade",
"(",
"connection",
",",
"sc... | perform database upgrade and provide logging . | train | false |
27,908 | def sdecode(string_):
encodings = get_encodings()
for encoding in encodings:
try:
decoded = salt.utils.to_unicode(string_, encoding)
(u' ' + decoded)
return decoded
except UnicodeDecodeError:
continue
return string_
| [
"def",
"sdecode",
"(",
"string_",
")",
":",
"encodings",
"=",
"get_encodings",
"(",
")",
"for",
"encoding",
"in",
"encodings",
":",
"try",
":",
"decoded",
"=",
"salt",
".",
"utils",
".",
"to_unicode",
"(",
"string_",
",",
"encoding",
")",
"(",
"u' '",
... | since we dont know where a string is coming from and that string will need to be safely decoded . | train | false |
27,909 | def unlink(f):
try:
os.unlink(f)
except OSError as e:
if (e.errno != errno.ENOENT):
raise
| [
"def",
"unlink",
"(",
"f",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"f",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
")",
":",
"raise"
] | unlinks a file or directory on the target device . | train | false |
27,910 | def _validated_param(obj, name, base_class, default, base_class_name=None):
base_class_name = (base_class_name if base_class_name else base_class.__name__)
if ((obj is not None) and (not isinstance(obj, base_class))):
raise ValueError(u'{name} must be an instance of {cls}'.format(name=name, cls=base_class_name))
return (obj or default)
| [
"def",
"_validated_param",
"(",
"obj",
",",
"name",
",",
"base_class",
",",
"default",
",",
"base_class_name",
"=",
"None",
")",
":",
"base_class_name",
"=",
"(",
"base_class_name",
"if",
"base_class_name",
"else",
"base_class",
".",
"__name__",
")",
"if",
"("... | validates a parameter passed to __init__ . | train | false |
27,911 | def zshift(s):
s = s.lstrip()
i = 0
while s.startswith((ZERO, '0')):
s = re.sub(('^(0|%s)\\s*' % ZERO), '', s, 1)
i = (i + 1)
return (s, i)
| [
"def",
"zshift",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"lstrip",
"(",
")",
"i",
"=",
"0",
"while",
"s",
".",
"startswith",
"(",
"(",
"ZERO",
",",
"'0'",
")",
")",
":",
"s",
"=",
"re",
".",
"sub",
"(",
"(",
"'^(0|%s)\\\\s*'",
"%",
"ZERO",
... | returns a -tuple . | train | false |
27,912 | def validate_format(tformat):
try:
time = datetime.datetime.utcnow()
time.strftime(tformat)
except:
raise ValueError(u'Invalid time format')
return tformat
| [
"def",
"validate_format",
"(",
"tformat",
")",
":",
"try",
":",
"time",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"time",
".",
"strftime",
"(",
"tformat",
")",
"except",
":",
"raise",
"ValueError",
"(",
"u'Invalid time format'",
")",
"retu... | returns the format . | train | false |
27,913 | def _array_of_arrays(list_of_arrays):
out = np.empty(len(list_of_arrays), dtype=object)
out[:] = list_of_arrays
return out
| [
"def",
"_array_of_arrays",
"(",
"list_of_arrays",
")",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"list_of_arrays",
")",
",",
"dtype",
"=",
"object",
")",
"out",
"[",
":",
"]",
"=",
"list_of_arrays",
"return",
"out"
] | creates an array of array from list of arrays . | train | false |
27,914 | def rsa_verify(xml, signature, key, c14n_exc=True):
if key.startswith('-----BEGIN PUBLIC KEY-----'):
bio = BIO.MemoryBuffer(key)
rsa = RSA.load_pub_key_bio(bio)
else:
rsa = RSA.load_pub_key(certificate)
pubkey = EVP.PKey()
pubkey.assign_rsa(rsa)
pubkey.reset_context(md='sha1')
pubkey.verify_init()
pubkey.verify_update(canonicalize(xml, c14n_exc))
ret = pubkey.verify_final(base64.b64decode(signature))
return (ret == 1)
| [
"def",
"rsa_verify",
"(",
"xml",
",",
"signature",
",",
"key",
",",
"c14n_exc",
"=",
"True",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'-----BEGIN PUBLIC KEY-----'",
")",
":",
"bio",
"=",
"BIO",
".",
"MemoryBuffer",
"(",
"key",
")",
"rsa",
"=",
"... | verify a xml document signature usign rsa-sha1 . | train | false |
27,915 | def prep_data(raw_input, input_type, max_len, vocab, dtype='int32', index_from=2, oov=1):
dtype = np.dtype(dtype)
if (input_type == 'text'):
in_shape = (max_len, 1)
tokens = tokenize(raw_input)
sent_inp = np.array([(oov if (t not in vocab) else (vocab[t] + index_from)) for t in tokens])
l = min(len(sent_inp), max_len)
xbuf = np.zeros(in_shape, dtype=dtype)
xbuf[(- l):] = sent_inp[(- l):].reshape((-1), 1)
return xbuf
else:
raise ValueError(('Unsupported data type: %s' % input_type))
| [
"def",
"prep_data",
"(",
"raw_input",
",",
"input_type",
",",
"max_len",
",",
"vocab",
",",
"dtype",
"=",
"'int32'",
",",
"index_from",
"=",
"2",
",",
"oov",
"=",
"1",
")",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"if",
"(",
"input... | transforms the raw received input data to put it in the required format for running through neon . | train | false |
27,916 | def generate_thumbnail_download_link_youtube(video_id_from_shortcode):
thumbnail_download_link = (('https://img.youtube.com/vi/' + video_id_from_shortcode) + '/0.jpg')
return thumbnail_download_link
| [
"def",
"generate_thumbnail_download_link_youtube",
"(",
"video_id_from_shortcode",
")",
":",
"thumbnail_download_link",
"=",
"(",
"(",
"'https://img.youtube.com/vi/'",
"+",
"video_id_from_shortcode",
")",
"+",
"'/0.jpg'",
")",
"return",
"thumbnail_download_link"
] | thumbnail url generator for youtube videos . | train | false |
27,917 | def string_from_geom(func):
func.argtypes = [GEOM_PTR]
func.restype = geos_char_p
func.errcheck = check_string
return func
| [
"def",
"string_from_geom",
"(",
"func",
")",
":",
"func",
".",
"argtypes",
"=",
"[",
"GEOM_PTR",
"]",
"func",
".",
"restype",
"=",
"geos_char_p",
"func",
".",
"errcheck",
"=",
"check_string",
"return",
"func"
] | argument is a geometry . | train | false |
27,918 | def permutation(random_state, size=None, n=1, ndim=None, dtype='int64'):
if ((size is None) or (size == ())):
if (not ((ndim is None) or (ndim == 1))):
raise TypeError('You asked for just one permutation but asked for more then 1 dimensions.')
ndim = 1
size = ()
bcast = ()
else:
(ndim, size, bcast) = _infer_ndim_bcast(ndim, size)
op = RandomFunction(permutation_helper, tensor.TensorType(dtype=dtype, broadcastable=(bcast + (False,))), ndim_added=1)
return op(random_state, size, n)
| [
"def",
"permutation",
"(",
"random_state",
",",
"size",
"=",
"None",
",",
"n",
"=",
"1",
",",
"ndim",
"=",
"None",
",",
"dtype",
"=",
"'int64'",
")",
":",
"if",
"(",
"(",
"size",
"is",
"None",
")",
"or",
"(",
"size",
"==",
"(",
")",
")",
")",
... | return permutations of the integers between 0 and n-1 . | train | false |
27,919 | def get_user_name_id(user):
if re.match('\\d+', str(user)):
pass_info = pwd.getpwuid(user)
else:
pass_info = pwd.getpwnam(user)
return (pass_info[0], pass_info[2])
| [
"def",
"get_user_name_id",
"(",
"user",
")",
":",
"if",
"re",
".",
"match",
"(",
"'\\\\d+'",
",",
"str",
"(",
"user",
")",
")",
":",
"pass_info",
"=",
"pwd",
".",
"getpwuid",
"(",
"user",
")",
"else",
":",
"pass_info",
"=",
"pwd",
".",
"getpwnam",
... | get the user id # and name . | train | false |
27,920 | def _squeeze_output(out):
out = out.squeeze()
if (out.ndim == 0):
out = out[()]
return out
| [
"def",
"_squeeze_output",
"(",
"out",
")",
":",
"out",
"=",
"out",
".",
"squeeze",
"(",
")",
"if",
"(",
"out",
".",
"ndim",
"==",
"0",
")",
":",
"out",
"=",
"out",
"[",
"(",
")",
"]",
"return",
"out"
] | remove single-dimensional entries from array and convert to scalar . | train | false |
27,921 | def not_all_have_id(files):
id_reg_exp = re.compile(FILE_PATTERN)
for file in files:
ids = id_reg_exp.findall(file)
if (ids is None):
return True
return False
| [
"def",
"not_all_have_id",
"(",
"files",
")",
":",
"id_reg_exp",
"=",
"re",
".",
"compile",
"(",
"FILE_PATTERN",
")",
"for",
"file",
"in",
"files",
":",
"ids",
"=",
"id_reg_exp",
".",
"findall",
"(",
"file",
")",
"if",
"(",
"ids",
"is",
"None",
")",
"... | return true iff any of the filenames does not conform to the pattern we require for determining the category id . | train | false |
27,922 | def exponential(M, center=None, tau=1.0, sym=True):
if (sym and (center is not None)):
raise ValueError('If sym==True, center must be None.')
if _len_guards(M):
return np.ones(M)
(M, needs_trunc) = _extend(M, sym)
if (center is None):
center = ((M - 1) / 2)
n = np.arange(0, M)
w = np.exp(((- np.abs((n - center))) / tau))
return _truncate(w, needs_trunc)
| [
"def",
"exponential",
"(",
"M",
",",
"center",
"=",
"None",
",",
"tau",
"=",
"1.0",
",",
"sym",
"=",
"True",
")",
":",
"if",
"(",
"sym",
"and",
"(",
"center",
"is",
"not",
"None",
")",
")",
":",
"raise",
"ValueError",
"(",
"'If sym==True, center must... | return an exponential window . | train | false |
27,924 | def valid_id(opts, id_):
try:
return bool(clean_path(opts['pki_dir'], id_))
except (AttributeError, KeyError) as e:
return False
| [
"def",
"valid_id",
"(",
"opts",
",",
"id_",
")",
":",
"try",
":",
"return",
"bool",
"(",
"clean_path",
"(",
"opts",
"[",
"'pki_dir'",
"]",
",",
"id_",
")",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
"as",
"e",
":",
"return",
"False"
... | returns if the passed id is valid . | train | false |
27,926 | def _parse_www_authenticate(headers, headername='www-authenticate'):
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = ((USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT) or WWW_AUTH_RELAXED)
while authenticate:
if (headername == 'authentication-info'):
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(' ', 1)
match = www_auth.search(the_rest)
auth_params = {}
while match:
if (match and (len(match.groups()) == 3)):
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub('\\1', value)
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader('WWW-Authenticate')
return retval
| [
"def",
"_parse_www_authenticate",
"(",
"headers",
",",
"headername",
"=",
"'www-authenticate'",
")",
":",
"retval",
"=",
"{",
"}",
"if",
"headers",
".",
"has_key",
"(",
"headername",
")",
":",
"try",
":",
"authenticate",
"=",
"headers",
"[",
"headername",
"]... | returns a dictionary of dictionaries . | train | false |
27,927 | def get_unique_items(sequence, reference):
return tuple([item for item in sequence if (item not in reference)])
| [
"def",
"get_unique_items",
"(",
"sequence",
",",
"reference",
")",
":",
"return",
"tuple",
"(",
"[",
"item",
"for",
"item",
"in",
"sequence",
"if",
"(",
"item",
"not",
"in",
"reference",
")",
"]",
")"
] | return items in sequence that cant be found in reference . | train | false |
27,928 | def test_scenario_tables_are_solved_against_outlines():
expected_hashes_per_step = [[{'Parameter': 'a', 'Value': '1'}, {'Parameter': 'b', 'Value': '2'}], [], [], [{'Parameter': 'a', 'Value': '2'}, {'Parameter': 'b', 'Value': '4'}], [], []]
scenario = Scenario.from_string(OUTLINED_SCENARIO_WITH_SUBSTITUTIONS_IN_TABLE)
for (step, expected_hashes) in zip(scenario.solved_steps, expected_hashes_per_step):
assert_equals(type(step), Step)
assert_equals(step.hashes, expected_hashes)
| [
"def",
"test_scenario_tables_are_solved_against_outlines",
"(",
")",
":",
"expected_hashes_per_step",
"=",
"[",
"[",
"{",
"'Parameter'",
":",
"'a'",
",",
"'Value'",
":",
"'1'",
"}",
",",
"{",
"'Parameter'",
":",
"'b'",
",",
"'Value'",
":",
"'2'",
"}",
"]",
"... | outline substitution should apply to tables within a scenario . | train | false |
27,929 | def _maybe_to_dense(obj):
if hasattr(obj, 'to_dense'):
return obj.to_dense()
return obj
| [
"def",
"_maybe_to_dense",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'to_dense'",
")",
":",
"return",
"obj",
".",
"to_dense",
"(",
")",
"return",
"obj"
] | try to convert to dense . | train | false |
27,931 | def combine_plays(games):
chain = itertools.chain(*[g.drives.plays() for g in games])
return nflgame.seq.GenPlays(chain)
| [
"def",
"combine_plays",
"(",
"games",
")",
":",
"chain",
"=",
"itertools",
".",
"chain",
"(",
"*",
"[",
"g",
".",
"drives",
".",
"plays",
"(",
")",
"for",
"g",
"in",
"games",
"]",
")",
"return",
"nflgame",
".",
"seq",
".",
"GenPlays",
"(",
"chain",... | combines a list of games into one big play generator that can be searched as if it were a single game . | train | false |
27,934 | def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None):
tablespaces = tablespace_list(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas)
return (name in tablespaces)
| [
"def",
"tablespace_exists",
"(",
"name",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"tablespaces",
"=",
"tablespac... | checks if a tablespace exists on the postgres server . | train | true |
27,935 | def WriteGraph(edges):
files = collections.defaultdict(list)
for (src, dst) in edges.items():
(build_file, target_name, toolset) = ParseTarget(src)
files[build_file].append(src)
print 'digraph D {'
print ' fontsize=8'
print ' node [fontsize=8]'
for (filename, targets) in files.items():
if (len(targets) == 1):
target = targets[0]
(build_file, target_name, toolset) = ParseTarget(target)
print (' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name))
else:
print (' subgraph "cluster_%s" {' % filename)
print (' label = "%s"' % filename)
for target in targets:
(build_file, target_name, toolset) = ParseTarget(target)
print (' "%s" [label="%s"]' % (target, target_name))
print ' }'
for (src, dsts) in edges.items():
for dst in dsts:
print (' "%s" -> "%s"' % (src, dst))
print '}'
| [
"def",
"WriteGraph",
"(",
"edges",
")",
":",
"files",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"(",
"src",
",",
"dst",
")",
"in",
"edges",
".",
"items",
"(",
")",
":",
"(",
"build_file",
",",
"target_name",
",",
"toolset",
")"... | print a graphviz graph to stdout . | train | false |
27,936 | def get_course_content_milestones(course_id, content_id, relationship, user_id=None):
if (not settings.FEATURES.get('MILESTONES_APP')):
return []
if (user_id is None):
return milestones_api.get_course_content_milestones(course_id, content_id, relationship)
request_cache_dict = request_cache.get_cache(REQUEST_CACHE_NAME)
if (user_id not in request_cache_dict):
request_cache_dict[user_id] = {}
if (relationship not in request_cache_dict[user_id]):
request_cache_dict[user_id][relationship] = milestones_api.get_course_content_milestones(course_key=course_id, relationship=relationship, user={'id': user_id})
return [m for m in request_cache_dict[user_id][relationship] if (m['content_id'] == unicode(content_id))]
| [
"def",
"get_course_content_milestones",
"(",
"course_id",
",",
"content_id",
",",
"relationship",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"(",
"not",
"settings",
".",
"FEATURES",
".",
"get",
"(",
"'MILESTONES_APP'",
")",
")",
":",
"return",
"[",
"]",
... | client api operation adapter/wrapper uses the request cache to store all of a users milestones . | train | false |
27,937 | def _set_output(groups, which):
previous = {}
try:
for group in output.expand_aliases(groups):
previous[group] = output[group]
output[group] = which
(yield)
finally:
output.update(previous)
| [
"def",
"_set_output",
"(",
"groups",
",",
"which",
")",
":",
"previous",
"=",
"{",
"}",
"try",
":",
"for",
"group",
"in",
"output",
".",
"expand_aliases",
"(",
"groups",
")",
":",
"previous",
"[",
"group",
"]",
"=",
"output",
"[",
"group",
"]",
"outp... | refactored subroutine used by hide and show . | train | false |
27,938 | def getsignaturefromtext(text, objname):
if isinstance(text, dict):
text = text.get('docstring', '')
oneline_re = (objname + '\\([^\\)].+?(?<=[\\w\\]\\}\\\'"])\\)(?!,)')
multiline_re = (objname + '\\([^\\)]+(?<=[\\w\\]\\}\\\'"])\\)(?!,)')
multiline_end_parenleft_re = '(%s\\([^\\)]+(\\),\\n.+)+(?<=[\\w\\]\\}\\\'"])\\))'
if (not text):
text = ''
sigs_1 = re.findall(((oneline_re + '|') + multiline_re), text)
sigs_2 = [g[0] for g in re.findall((multiline_end_parenleft_re % objname), text)]
all_sigs = (sigs_1 + sigs_2)
if all_sigs:
return all_sigs[0]
else:
return ''
| [
"def",
"getsignaturefromtext",
"(",
"text",
",",
"objname",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"dict",
")",
":",
"text",
"=",
"text",
".",
"get",
"(",
"'docstring'",
",",
"''",
")",
"oneline_re",
"=",
"(",
"objname",
"+",
"'\\\\([^\\\\)].+?(... | get object signatures from text return a list containing a single string in most cases example of multiple signatures: pyqt4 objects . | train | true |
27,940 | def _ConvertToolsToExpectedForm(tools):
tool_list = []
for (tool, settings) in tools.iteritems():
settings_fixed = {}
for (setting, value) in settings.iteritems():
if (type(value) == list):
if (((tool == 'VCLinkerTool') and (setting == 'AdditionalDependencies')) or (setting == 'AdditionalOptions')):
settings_fixed[setting] = ' '.join(value)
else:
settings_fixed[setting] = ';'.join(value)
else:
settings_fixed[setting] = value
tool_list.append(MSVSProject.Tool(tool, settings_fixed))
return tool_list
| [
"def",
"_ConvertToolsToExpectedForm",
"(",
"tools",
")",
":",
"tool_list",
"=",
"[",
"]",
"for",
"(",
"tool",
",",
"settings",
")",
"in",
"tools",
".",
"iteritems",
"(",
")",
":",
"settings_fixed",
"=",
"{",
"}",
"for",
"(",
"setting",
",",
"value",
")... | convert tools to a form expected by visual studio . | train | false |
27,941 | def test_enn_init():
enn = EditedNearestNeighbours(random_state=RND_SEED)
assert_equal(enn.n_neighbors, 3)
assert_equal(enn.kind_sel, 'all')
assert_equal(enn.n_jobs, 1)
assert_equal(enn.random_state, RND_SEED)
| [
"def",
"test_enn_init",
"(",
")",
":",
"enn",
"=",
"EditedNearestNeighbours",
"(",
"random_state",
"=",
"RND_SEED",
")",
"assert_equal",
"(",
"enn",
".",
"n_neighbors",
",",
"3",
")",
"assert_equal",
"(",
"enn",
".",
"kind_sel",
",",
"'all'",
")",
"assert_eq... | test the initialisation of the object . | train | false |
27,942 | def _decision_relationships(workflow, parent, child_el):
for switch in child_el:
if (not isinstance(switch.tag, basestring)):
continue
for case in switch:
if (not isinstance(case.tag, basestring)):
continue
if ('to' not in case.attrib):
raise RuntimeError((_("Node %s has a link that is missing 'to' attribute.") % parent.name))
to = case.attrib['to']
try:
child = Node.objects.get(workflow=workflow, name=to)
except Node.DoesNotExist as e:
raise RuntimeError((_('Node %s has not been defined.') % to))
if (etree.QName(case).localname == 'default'):
name = 'default'
obj = Link.objects.create(name=name, parent=parent, child=child)
else:
name = 'start'
comment = case.text.strip()
obj = Link.objects.create(name=name, parent=parent, child=child, comment=comment)
obj.save()
| [
"def",
"_decision_relationships",
"(",
"workflow",
",",
"parent",
",",
"child_el",
")",
":",
"for",
"switch",
"in",
"child_el",
":",
"if",
"(",
"not",
"isinstance",
"(",
"switch",
".",
"tag",
",",
"basestring",
")",
")",
":",
"continue",
"for",
"case",
"... | resolves the switch statement like nature of decision nodes . | train | false |
27,943 | def _not_null(value, field):
return ((value is not None) or (field.mode != 'NULLABLE'))
| [
"def",
"_not_null",
"(",
"value",
",",
"field",
")",
":",
"return",
"(",
"(",
"value",
"is",
"not",
"None",
")",
"or",
"(",
"field",
".",
"mode",
"!=",
"'NULLABLE'",
")",
")"
] | check whether value should be coerced to field type . | train | false |
27,945 | def _get_file(src):
try:
if (('://' in src) or (src[0:2] == '//')):
response = urllib2.urlopen(src)
return response.read()
else:
with open(src, 'rb') as fh:
return fh.read()
except Exception as e:
raise RuntimeError('Error generating base64image: {}'.format(e))
| [
"def",
"_get_file",
"(",
"src",
")",
":",
"try",
":",
"if",
"(",
"(",
"'://'",
"in",
"src",
")",
"or",
"(",
"src",
"[",
"0",
":",
"2",
"]",
"==",
"'//'",
")",
")",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"src",
")",
"return",
"r... | return content from local or remote file . | train | true |
27,946 | def point_inside_polygon(x, y, poly):
n = len(poly)
inside = False
p1x = poly[0]
p1y = poly[1]
for i in range(0, (n + 2), 2):
p2x = poly[(i % n)]
p2y = poly[((i + 1) % n)]
if (y > min(p1y, p2y)):
if (y <= max(p1y, p2y)):
if (x <= max(p1x, p2x)):
if (p1y != p2y):
xinters = ((((y - p1y) * (p2x - p1x)) / (p2y - p1y)) + p1x)
if ((p1x == p2x) or (x <= xinters)):
inside = (not inside)
(p1x, p1y) = (p2x, p2y)
return inside
| [
"def",
"point_inside_polygon",
"(",
"x",
",",
"y",
",",
"poly",
")",
":",
"n",
"=",
"len",
"(",
"poly",
")",
"inside",
"=",
"False",
"p1x",
"=",
"poly",
"[",
"0",
"]",
"p1y",
"=",
"poly",
"[",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",... | taken from URL . | train | true |
27,947 | def persistent(cls):
cls._instance_hardref = True
return cls
| [
"def",
"persistent",
"(",
"cls",
")",
":",
"cls",
".",
"_instance_hardref",
"=",
"True",
"return",
"cls"
] | makes this plugin non-gcable :type cls: class :rtype: class . | train | false |
27,948 | @hook.command('note', 'notes', 'todo')
def note(text, conn, nick, db, notice):
parts = text.split()
if ((len(parts) == 1) and text.isdigit()):
cmd = 'get'
args = parts
else:
cmd = parts[0].lower()
args = parts[1:]
if (cmd in ['add', 'new']):
if (not len(args)):
return 'No text provided!'
note_text = ' '.join(args)
add_note(db, conn.name, nick, note_text)
notice('Note added!')
return
elif (cmd in ['del', 'delete', 'remove']):
if (not len(args)):
return 'No note ID provided!'
note_id = args[0]
n = read_note(db, conn.name, nick, note_id)
if (not n):
notice('#{} is not a valid note ID.'.format(note_id))
return
delete_note(db, conn.name, nick, note_id)
notice('Note #{} deleted!'.format(note_id))
return
elif (cmd == 'clear'):
delete_all_notes(db, conn.name, nick)
notice('All notes deleted!')
return
elif (cmd == 'get'):
if (not len(args)):
return 'No note ID provided!'
note_id = args[0]
n = read_note(db, conn.name, nick, note_id)
if (not n):
notice('{} is not a valid note ID.'.format(nick))
return
text = format_note(n)
notice(text)
return
elif (cmd in ['share', 'show']):
if (not len(args)):
return 'No note ID provided!'
note_id = args[0]
n = read_note(db, conn.name, nick, note_id)
if (not n):
notice('{} is not a valid note ID.'.format(nick))
return
text = format_note(n)
return text
elif (cmd == 'list'):
notes = read_all_notes(db, conn.name, nick)
if (not notes):
notice('You have no notes.'.format(nick))
return
notice('All notes for {}:'.format(nick))
for n in notes:
text = format_note(n)
notice(text)
elif (cmd == 'listall'):
notes = read_all_notes(db, conn.name, nick, show_deleted=True)
if (not notes):
notice('You have no notes.'.format(nick))
return
notice('All notes for {}:'.format(nick))
for n in notes:
text = format_note(n)
notice(text)
else:
notice('Unknown command: {}'.format(cmd))
| [
"@",
"hook",
".",
"command",
"(",
"'note'",
",",
"'notes'",
",",
"'todo'",
")",
"def",
"note",
"(",
"text",
",",
"conn",
",",
"nick",
",",
"db",
",",
"notice",
")",
":",
"parts",
"=",
"text",
".",
"split",
"(",
")",
"if",
"(",
"(",
"len",
"(",
... | notes: restful crud controller . | train | false |
27,949 | def net2range(network):
(addr, mask) = network.split('/')
addr = ip2int(addr)
if ('.' in mask):
mask = ip2int(mask)
else:
mask = int2mask(int(mask))
start = (addr & mask)
stop = int2ip(((start + 4294967295) - mask))
start = int2ip(start)
return (start, stop)
| [
"def",
"net2range",
"(",
"network",
")",
":",
"(",
"addr",
",",
"mask",
")",
"=",
"network",
".",
"split",
"(",
"'/'",
")",
"addr",
"=",
"ip2int",
"(",
"addr",
")",
"if",
"(",
"'.'",
"in",
"mask",
")",
":",
"mask",
"=",
"ip2int",
"(",
"mask",
"... | converts a network to a tuple . | train | false |
27,950 | def CreateStartInterval(index, total):
part = int((constants.MAX_RANGE / float(total)))
start = (part * index)
if (total == (index - 1)):
end = constants.MAX_RANGE
else:
end = (part * (index + 1))
ret = rdf_data_server.DataServerInterval(start=start, end=end)
return ret
| [
"def",
"CreateStartInterval",
"(",
"index",
",",
"total",
")",
":",
"part",
"=",
"int",
"(",
"(",
"constants",
".",
"MAX_RANGE",
"/",
"float",
"(",
"total",
")",
")",
")",
"start",
"=",
"(",
"part",
"*",
"index",
")",
"if",
"(",
"total",
"==",
"(",... | create initial range given index of server and number of servers . | train | false |
27,952 | def decompose_to_known_units(unit, func):
from .. import core
if isinstance(unit, core.CompositeUnit):
new_unit = core.Unit(unit.scale)
for (base, power) in zip(unit.bases, unit.powers):
new_unit = (new_unit * (decompose_to_known_units(base, func) ** power))
return new_unit
elif isinstance(unit, core.NamedUnit):
try:
func(unit)
except ValueError:
if isinstance(unit, core.Unit):
return decompose_to_known_units(unit._represents, func)
raise
return unit
| [
"def",
"decompose_to_known_units",
"(",
"unit",
",",
"func",
")",
":",
"from",
".",
".",
"import",
"core",
"if",
"isinstance",
"(",
"unit",
",",
"core",
".",
"CompositeUnit",
")",
":",
"new_unit",
"=",
"core",
".",
"Unit",
"(",
"unit",
".",
"scale",
")... | partially decomposes a unit so it is only composed of units that are "known" to a given format . | train | false |
27,953 | def failure_code_init(sub):
return ('{\n if (!PyErr_Occurred()) {\n PyErr_SetString(PyExc_RuntimeError,\n "Unexpected error in an Op\'s C code. "\n "No Python exception was set.");\n }\n return %(id)d;\n}' % sub)
| [
"def",
"failure_code_init",
"(",
"sub",
")",
":",
"return",
"(",
"'{\\n if (!PyErr_Occurred()) {\\n PyErr_SetString(PyExc_RuntimeError,\\n \"Unexpected error in an Op\\'s C code. \"\\n \"No Python exception was set.\");\\n }\\n return... | code for failure in the struct init . | train | false |
27,954 | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('--port-id', metavar='<port_id>', help=_('Port ID.'), dest='port_id')
@utils.arg('--net-id', metavar='<net_id>', help=_('Network ID'), default=None, dest='net_id')
@utils.arg('--fixed-ip', metavar='<fixed_ip>', help=_('Requested fixed IP.'), default=None, dest='fixed_ip')
def do_interface_attach(cs, args):
server = _find_server(cs, args.server)
res = server.interface_attach(args.port_id, args.net_id, args.fixed_ip)
if isinstance(res, dict):
utils.print_dict(res)
| [
"@",
"utils",
".",
"arg",
"(",
"'server'",
",",
"metavar",
"=",
"'<server>'",
",",
"help",
"=",
"_",
"(",
"'Name or ID of server.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'--port-id'",
",",
"metavar",
"=",
"'<port_id>'",
",",
"help",
"=",
"_",
"(",... | attach a network interface to a server . | train | false |
27,956 | def add_tmpl_to_pot(prefix, dst):
src = open((EMAIL_DIR + ('/%s-en.tmpl' % prefix)), 'r')
dst.write(('#: email/%s.tmpl:1\n' % prefix))
dst.write('msgid ""\n')
for line in src:
dst.write(('"%s"\n' % line.replace('\n', '\\n').replace('"', '\\"')))
dst.write('msgstr ""\n\n')
src.close()
| [
"def",
"add_tmpl_to_pot",
"(",
"prefix",
",",
"dst",
")",
":",
"src",
"=",
"open",
"(",
"(",
"EMAIL_DIR",
"+",
"(",
"'/%s-en.tmpl'",
"%",
"prefix",
")",
")",
",",
"'r'",
")",
"dst",
".",
"write",
"(",
"(",
"'#: email/%s.tmpl:1\\n'",
"%",
"prefix",
")",... | append english template to open pot file dst . | train | false |
27,958 | def ensure_correct_host(session):
this_vm_uuid = get_this_vm_uuid()
try:
session.call_xenapi('VM.get_by_uuid', this_vm_uuid)
except session.XenAPI.Failure as exc:
if (exc.details[0] != 'UUID_INVALID'):
raise
raise Exception(_('This domU must be running on the host specified by xenapi_connection_url'))
| [
"def",
"ensure_correct_host",
"(",
"session",
")",
":",
"this_vm_uuid",
"=",
"get_this_vm_uuid",
"(",
")",
"try",
":",
"session",
".",
"call_xenapi",
"(",
"'VM.get_by_uuid'",
",",
"this_vm_uuid",
")",
"except",
"session",
".",
"XenAPI",
".",
"Failure",
"as",
"... | ensure were connected to the host were running on . | train | false |
27,959 | def generate_next_dates(start_date, offset=0):
start = (offset * 7)
for i in itertools.count(start):
(yield (start_date + timedelta(i)))
| [
"def",
"generate_next_dates",
"(",
"start_date",
",",
"offset",
"=",
"0",
")",
":",
"start",
"=",
"(",
"offset",
"*",
"7",
")",
"for",
"i",
"in",
"itertools",
".",
"count",
"(",
"start",
")",
":",
"(",
"yield",
"(",
"start_date",
"+",
"timedelta",
"(... | generator that returns the next date . | train | false |
27,960 | def natural_ipv4_netmask(ip, fmt='prefixlen'):
bits = _ipv4_to_bits(ip)
if bits.startswith('11'):
mask = '24'
elif bits.startswith('1'):
mask = '16'
else:
mask = '8'
if (fmt == 'netmask'):
return cidr_to_ipv4_netmask(mask)
else:
return ('/' + mask)
| [
"def",
"natural_ipv4_netmask",
"(",
"ip",
",",
"fmt",
"=",
"'prefixlen'",
")",
":",
"bits",
"=",
"_ipv4_to_bits",
"(",
"ip",
")",
"if",
"bits",
".",
"startswith",
"(",
"'11'",
")",
":",
"mask",
"=",
"'24'",
"elif",
"bits",
".",
"startswith",
"(",
"'1'"... | returns the "natural" mask of an ipv4 address . | train | true |
27,961 | @evalcontextfilter
def do_tojson(eval_ctx, value, indent=None):
policies = eval_ctx.environment.policies
dumper = policies['json.dumps_function']
options = policies['json.dumps_kwargs']
if (indent is not None):
options = dict(options)
options['indent'] = indent
return htmlsafe_json_dumps(value, dumper=dumper, **options)
| [
"@",
"evalcontextfilter",
"def",
"do_tojson",
"(",
"eval_ctx",
",",
"value",
",",
"indent",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"dumper",
"=",
"policies",
"[",
"'json.dumps_function'",
"]",
"options",
"=",
... | dumps a structure to json so that its safe to use in <script> tags . | train | true |
27,962 | def selEpsilonLexicase(individuals, k, epsilon):
selected_individuals = []
for i in range(k):
fit_weights = individuals[0].fitness.weights
candidates = individuals
cases = list(range(len(individuals[0].fitness.values)))
random.shuffle(cases)
while ((len(cases) > 0) and (len(candidates) > 1)):
if (fit_weights[cases[0]] > 0):
best_val_for_case = max(map((lambda x: x.fitness.values[cases[0]]), candidates))
min_val_to_survive_case = (best_val_for_case - epsilon)
candidates = list(filter((lambda x: (x.fitness.values[cases[0]] >= min_val_to_survive_case)), candidates))
else:
best_val_for_case = min(map((lambda x: x.fitness.values[cases[0]]), candidates))
max_val_to_survive_case = (best_val_for_case + epsilon)
candidates = list(filter((lambda x: (x.fitness.values[cases[0]] <= max_val_to_survive_case)), candidates))
cases.pop(0)
selected_individuals.append(random.choice(candidates))
return selected_individuals
| [
"def",
"selEpsilonLexicase",
"(",
"individuals",
",",
"k",
",",
"epsilon",
")",
":",
"selected_individuals",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"fit_weights",
"=",
"individuals",
"[",
"0",
"]",
".",
"fitness",
".",
"weights",
... | returns an individual that does the best on the fitness cases when considered one at a time in random order . | train | false |
27,963 | def install_templates_translations(generator):
if ('JINJA_ENVIRONMENT' in generator.settings):
jinja_extensions = generator.settings['JINJA_ENVIRONMENT'].get('extensions', [])
else:
jinja_extensions = generator.settings['JINJA_EXTENSIONS']
if ('jinja2.ext.i18n' in jinja_extensions):
domain = generator.settings.get('I18N_GETTEXT_DOMAIN', 'messages')
localedir = generator.settings.get('I18N_GETTEXT_LOCALEDIR')
if (localedir is None):
localedir = os.path.join(generator.theme, 'translations')
current_lang = generator.settings['DEFAULT_LANG']
if (current_lang == generator.settings.get('I18N_TEMPLATES_LANG', _MAIN_LANG)):
translations = gettext.NullTranslations()
else:
langs = [current_lang]
try:
translations = gettext.translation(domain, localedir, langs)
except (IOError, OSError):
_LOGGER.error("Cannot find translations for language '{}' in '{}' with domain '{}'. Installing NullTranslations.".format(langs[0], localedir, domain))
translations = gettext.NullTranslations()
newstyle = generator.settings.get('I18N_GETTEXT_NEWSTYLE', True)
generator.env.install_gettext_translations(translations, newstyle)
| [
"def",
"install_templates_translations",
"(",
"generator",
")",
":",
"if",
"(",
"'JINJA_ENVIRONMENT'",
"in",
"generator",
".",
"settings",
")",
":",
"jinja_extensions",
"=",
"generator",
".",
"settings",
"[",
"'JINJA_ENVIRONMENT'",
"]",
".",
"get",
"(",
"'extensio... | install gettext translations in the jinja2 . | train | true |
27,964 | def libvlc_media_player_get_rate(p_mi):
f = (_Cfunctions.get('libvlc_media_player_get_rate', None) or _Cfunction('libvlc_media_player_get_rate', ((1,),), None, ctypes.c_float, MediaPlayer))
return f(p_mi)
| [
"def",
"libvlc_media_player_get_rate",
"(",
"p_mi",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_player_get_rate'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_player_get_rate'",
",",
"(",
"(",
"1",
",",
")",
",",
")",
... | get the requested movie play rate . | train | true |
27,965 | def publicize_exploration(committer_id, exploration_id):
_publicize_activity(committer_id, exploration_id, feconf.ACTIVITY_TYPE_EXPLORATION)
| [
"def",
"publicize_exploration",
"(",
"committer_id",
",",
"exploration_id",
")",
":",
"_publicize_activity",
"(",
"committer_id",
",",
"exploration_id",
",",
"feconf",
".",
"ACTIVITY_TYPE_EXPLORATION",
")"
] | publicizes an exploration . | train | false |
27,967 | @require_admin_context
def volume_type_qos_specs_get(context, type_id):
session = get_session()
with session.begin():
_volume_type_get(context, type_id, session)
row = session.query(models.VolumeTypes).options(joinedload('qos_specs')).filter_by(id=type_id).first()
specs = _dict_with_qos_specs(row.qos_specs)
if (not specs):
specs = None
else:
specs = specs[0]
return {'qos_specs': specs}
| [
"@",
"require_admin_context",
"def",
"volume_type_qos_specs_get",
"(",
"context",
",",
"type_id",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"_volume_type_get",
"(",
"context",
",",
"type_id",
",",
"sessi... | get all qos specs for given volume type . | train | false |
27,968 | def assert_link(test, expected_link, actual_link):
test.assertEqual(expected_link['href'], actual_link.get_attribute('href'))
test.assertEqual(expected_link['text'], actual_link.text)
| [
"def",
"assert_link",
"(",
"test",
",",
"expected_link",
",",
"actual_link",
")",
":",
"test",
".",
"assertEqual",
"(",
"expected_link",
"[",
"'href'",
"]",
",",
"actual_link",
".",
"get_attribute",
"(",
"'href'",
")",
")",
"test",
".",
"assertEqual",
"(",
... | assert that href and text inside help dom element are correct . | train | false |
27,969 | def create_callback_server(session):
class CallbackHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, ):
def do_GET(self):
params = cgi.parse_qs(self.path.split('?', 1)[1], keep_blank_values=False)
session.REQUEST_TOKEN = OAuthToken(params['oauth_token'][0], params['oauth_token_secret'][0])
session.REQUEST_TOKEN.set_verifier(params['oauth_verifier'][0])
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write('OAuth request token fetched; you can close this window.')
def log_request(self, code='-', size='-'):
pass
server = SocketServer.TCPServer(('127.0.0.1', 0), CallbackHandler)
return server
| [
"def",
"create_callback_server",
"(",
"session",
")",
":",
"class",
"CallbackHandler",
"(",
"SimpleHTTPServer",
".",
"SimpleHTTPRequestHandler",
",",
")",
":",
"def",
"do_GET",
"(",
"self",
")",
":",
"params",
"=",
"cgi",
".",
"parse_qs",
"(",
"self",
".",
"... | adapted from URL simple server to handle callbacks from oauth request to browser . | train | false |
27,970 | def permute_dimensions(x, pattern):
pattern = tuple(pattern)
return x.dimshuffle(pattern)
| [
"def",
"permute_dimensions",
"(",
"x",
",",
"pattern",
")",
":",
"pattern",
"=",
"tuple",
"(",
"pattern",
")",
"return",
"x",
".",
"dimshuffle",
"(",
"pattern",
")"
] | permutes axes in a tensor . | train | false |
27,971 | def get_function_argspec(func):
if (not callable(func)):
raise TypeError('{0} is not a callable'.format(func))
if six.PY2:
if inspect.isfunction(func):
aspec = inspect.getargspec(func)
elif inspect.ismethod(func):
aspec = inspect.getargspec(func)
del aspec.args[0]
elif isinstance(func, object):
aspec = inspect.getargspec(func.__call__)
del aspec.args[0]
else:
raise TypeError("Cannot inspect argument list for '{0}'".format(func))
elif inspect.isfunction(func):
aspec = _getargspec(func)
elif inspect.ismethod(func):
aspec = _getargspec(func)
del aspec.args[0]
elif isinstance(func, object):
aspec = _getargspec(func.__call__)
del aspec.args[0]
else:
raise TypeError("Cannot inspect argument list for '{0}'".format(func))
return aspec
| [
"def",
"get_function_argspec",
"(",
"func",
")",
":",
"if",
"(",
"not",
"callable",
"(",
"func",
")",
")",
":",
"raise",
"TypeError",
"(",
"'{0} is not a callable'",
".",
"format",
"(",
"func",
")",
")",
"if",
"six",
".",
"PY2",
":",
"if",
"inspect",
"... | a small wrapper around getargspec that also supports callable classes . | train | true |
27,972 | def screen():
_lib.RAND_screen()
| [
"def",
"screen",
"(",
")",
":",
"_lib",
".",
"RAND_screen",
"(",
")"
] | add the current contents of the screen to the prng state . | train | false |
27,975 | def apply_change(targetState, name):
if (targetState == 'present'):
set_locale(name, enabled=True)
else:
set_locale(name, enabled=False)
localeGenExitValue = call('locale-gen')
if (localeGenExitValue != 0):
raise EnvironmentError(localeGenExitValue, ('locale.gen failed to execute, it returned ' + str(localeGenExitValue)))
| [
"def",
"apply_change",
"(",
"targetState",
",",
"name",
")",
":",
"if",
"(",
"targetState",
"==",
"'present'",
")",
":",
"set_locale",
"(",
"name",
",",
"enabled",
"=",
"True",
")",
"else",
":",
"set_locale",
"(",
"name",
",",
"enabled",
"=",
"False",
... | create or remove locale . | train | false |
27,976 | def match_album(artist, album, tracks=None, limit=SEARCH_LIMIT):
criteria = {'release': album.lower().strip()}
if (artist is not None):
criteria['artist'] = artist.lower().strip()
else:
criteria['arid'] = VARIOUS_ARTISTS_ID
if (tracks is not None):
criteria['tracks'] = str(tracks)
if (not any(criteria.itervalues())):
return
try:
res = musicbrainzngs.search_releases(limit=limit, **criteria)
except musicbrainzngs.MusicBrainzError as exc:
raise MusicBrainzAPIError(exc, 'release search', criteria, traceback.format_exc())
for release in res['release-list']:
albuminfo = album_for_id(release['id'])
if (albuminfo is not None):
(yield albuminfo)
| [
"def",
"match_album",
"(",
"artist",
",",
"album",
",",
"tracks",
"=",
"None",
",",
"limit",
"=",
"SEARCH_LIMIT",
")",
":",
"criteria",
"=",
"{",
"'release'",
":",
"album",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"}",
"if",
"(",
"artist",
"... | searches for a single album and returns an iterator over albuminfo objects . | train | false |
27,977 | def resolve_embedded_fields(resource, req):
embedded_fields = []
non_embedded_fields = []
if req.embedded:
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description='Unable to parse `embedded` clause')
try:
embedded_fields = [k for (k, v) in client_embedding.items() if (v == 1)]
non_embedded_fields = [k for (k, v) in client_embedding.items() if (v == 0)]
except AttributeError:
abort(400, description='Unable to parse `embedded` clause')
embedded_fields = list(((set(config.DOMAIN[resource]['embedded_fields']) | set(embedded_fields)) - set(non_embedded_fields)))
enabled_embedded_fields = []
for field in sorted(embedded_fields, key=(lambda a: a.count('.'))):
field_def = field_definition(resource, field)
if field_def:
if (field_def.get('type') == 'list'):
field_def = field_def['schema']
if (('data_relation' in field_def) and field_def['data_relation'].get('embeddable')):
enabled_embedded_fields.append(field)
return enabled_embedded_fields
| [
"def",
"resolve_embedded_fields",
"(",
"resource",
",",
"req",
")",
":",
"embedded_fields",
"=",
"[",
"]",
"non_embedded_fields",
"=",
"[",
"]",
"if",
"req",
".",
"embedded",
":",
"try",
":",
"client_embedding",
"=",
"json",
".",
"loads",
"(",
"req",
".",
... | returns a list of validated embedded fields from the incoming request or from the resource definition is the request does not specify . | train | false |
27,979 | def http_content_security_policy(http_server):
return "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:"
| [
"def",
"http_content_security_policy",
"(",
"http_server",
")",
":",
"return",
"\"default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:\""
] | calculate the default content security policy string . | train | false |
27,980 | def check_config(request):
if (not request.user.is_superuser):
return HttpResponse(_('You must be a superuser.'))
context = {'conf_dir': os.path.realpath(os.getenv('HUE_CONF_DIR', get_desktop_root('conf'))), 'error_list': _get_config_errors(request, cache=False)}
if (request.GET.get('format') == 'json'):
return JsonResponse(context)
else:
return render('check_config.mako', request, context, force_template=True)
| [
"def",
"check_config",
"(",
"request",
")",
":",
"if",
"(",
"not",
"request",
".",
"user",
".",
"is_superuser",
")",
":",
"return",
"HttpResponse",
"(",
"_",
"(",
"'You must be a superuser.'",
")",
")",
"context",
"=",
"{",
"'conf_dir'",
":",
"os",
".",
... | check if config is changed . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.