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
33,096
def vgdisplay(vgname=''): ret = {} cmd = ['vgdisplay', '-c'] if vgname: cmd.append(vgname) cmd_ret = __salt__['cmd.run_all'](cmd, python_shell=False) if (cmd_ret['retcode'] != 0): return {} out = cmd_ret['stdout'].splitlines() for line in out: comps = line.strip().split(':') ret[comps[0]] = {'Volume Group Name': comps[0], 'Volume Group Access': comps[1], 'Volume Group Status': comps[2], 'Internal Volume Group Number': comps[3], 'Maximum Logical Volumes': comps[4], 'Current Logical Volumes': comps[5], 'Open Logical Volumes': comps[6], 'Maximum Logical Volume Size': comps[7], 'Maximum Physical Volumes': comps[8], 'Current Physical Volumes': comps[9], 'Actual Physical Volumes': comps[10], 'Volume Group Size (kB)': comps[11], 'Physical Extent Size (kB)': comps[12], 'Total Physical Extents': comps[13], 'Allocated Physical Extents': comps[14], 'Free Physical Extents': comps[15], 'UUID': comps[16]} return ret
[ "def", "vgdisplay", "(", "vgname", "=", "''", ")", ":", "ret", "=", "{", "}", "cmd", "=", "[", "'vgdisplay'", ",", "'-c'", "]", "if", "vgname", ":", "cmd", ".", "append", "(", "vgname", ")", "cmd_ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(...
return information about the volume group(s) cli examples: .
train
true
33,097
@login_required @ensure_csrf_cookie def view_tracking_log(request, args=''): if (not request.user.is_staff): return redirect('/') nlen = 100 username = '' if args: for arg in args.split('/'): if arg.isdigit(): nlen = int(arg) if arg.startswith('username='): username = arg[9:] record_instances = TrackingLog.objects.all().order_by('-time') if username: record_instances = record_instances.filter(username=username) record_instances = record_instances[0:nlen] fmt = '%a %d-%b-%y %H:%M:%S' for rinst in record_instances: rinst.dtstr = rinst.time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern')).strftime(fmt) return render_to_response('tracking_log.html', {'records': record_instances})
[ "@", "login_required", "@", "ensure_csrf_cookie", "def", "view_tracking_log", "(", "request", ",", "args", "=", "''", ")", ":", "if", "(", "not", "request", ".", "user", ".", "is_staff", ")", ":", "return", "redirect", "(", "'/'", ")", "nlen", "=", "100"...
view to output contents of trackinglog model .
train
false
33,098
def group_content(generator, content_type): category_filter = generator.settings.get('CATEGORIES_TO_COLLATE', None) filtering_active = (type(category_filter) in (list, tuple, set)) collations = generator.context.get('collations', defaultdict(list)) for content in generator.context[content_type]: category_list = [c.strip() for c in content.category.name.split(',')] for category in category_list: if (filtering_active and (category not in category_filter)): continue category = substitute_category_name(category) collations[('%s_%s' % (category, content_type))].append(content) generator.context['collations'] = collations
[ "def", "group_content", "(", "generator", ",", "content_type", ")", ":", "category_filter", "=", "generator", ".", "settings", ".", "get", "(", "'CATEGORIES_TO_COLLATE'", ",", "None", ")", "filtering_active", "=", "(", "type", "(", "category_filter", ")", "in", ...
assembles articles and pages into lists based on each article or pages content .
train
true
33,099
@login_required def delete_revision(request, document_slug, revision_id): revision = get_object_or_404(Revision, pk=revision_id, document__slug=document_slug) document = revision.document if (not document.allows(request.user, 'delete_revision')): raise PermissionDenied only_revision = (document.revisions.count() == 1) helpful_votes = HelpfulVote.objects.filter(revision=revision.id) has_votes = helpful_votes.exists() if (request.method == 'GET'): return render(request, 'wiki/confirm_revision_delete.html', {'revision': revision, 'document': document, 'only_revision': only_revision, 'has_votes': has_votes}) if only_revision: return HttpResponseBadRequest() log.warning(('User %s is deleting revision with id=%s' % (request.user, revision.id))) revision.delete() return HttpResponseRedirect(reverse('wiki.document_revisions', args=[document.slug]))
[ "@", "login_required", "def", "delete_revision", "(", "request", ",", "document_slug", ",", "revision_id", ")", ":", "revision", "=", "get_object_or_404", "(", "Revision", ",", "pk", "=", "revision_id", ",", "document__slug", "=", "document_slug", ")", "document",...
delete a revision .
train
false
33,101
def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10, _recursive_depth=0): new_terms = [] for term in expr.args: if isinstance(term, Mul): new_term = _normal_ordered_form_factor(term, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth, independent=independent) new_terms.append(new_term) else: new_terms.append(term) return Add(*new_terms)
[ "def", "_normal_ordered_form_terms", "(", "expr", ",", "independent", "=", "False", ",", "recursive_limit", "=", "10", ",", "_recursive_depth", "=", "0", ")", ":", "new_terms", "=", "[", "]", "for", "term", "in", "expr", ".", "args", ":", "if", "isinstance...
helper function for normal_ordered_form: loop through each term in an addition expression and call _normal_ordered_form_factor to perform the factor to an normally ordered expression .
train
false
33,102
def bit_size(num): if (num == 0): return 0 if (num < 0): num = (- num) (num & 1) hex_num = ('%x' % num) return (((len(hex_num) - 1) * 4) + {'0': 0, '1': 1, '2': 2, '3': 2, '4': 3, '5': 3, '6': 3, '7': 3, '8': 4, '9': 4, 'a': 4, 'b': 4, 'c': 4, 'd': 4, 'e': 4, 'f': 4}[hex_num[0]])
[ "def", "bit_size", "(", "num", ")", ":", "if", "(", "num", "==", "0", ")", ":", "return", "0", "if", "(", "num", "<", "0", ")", ":", "num", "=", "(", "-", "num", ")", "(", "num", "&", "1", ")", "hex_num", "=", "(", "'%x'", "%", "num", ")"...
number of bits needed to represent a integer excluding any prefix 0 bits .
train
false
33,103
def get_alarm_refs(entity=None): alarm_states = entity.triggeredAlarmState ret = [] for alarm_state in alarm_states: tdict = {'alarm': alarm_state.key.split('.')[0], 'status': alarm_state.overallStatus} ret.append(tdict) return ret
[ "def", "get_alarm_refs", "(", "entity", "=", "None", ")", ":", "alarm_states", "=", "entity", ".", "triggeredAlarmState", "ret", "=", "[", "]", "for", "alarm_state", "in", "alarm_states", ":", "tdict", "=", "{", "'alarm'", ":", "alarm_state", ".", "key", "...
useful method that will return a list of dict with the moref and alarm status for all triggered alarms on a given entity .
train
false
33,104
def get_err_response(code): error_table = {'AccessDenied': (HTTP_FORBIDDEN, 'Access denied'), 'BucketAlreadyExists': (HTTP_CONFLICT, 'The requested bucket name is not available'), 'BucketNotEmpty': (HTTP_CONFLICT, 'The bucket you tried to delete is not empty'), 'InvalidArgument': (HTTP_BAD_REQUEST, 'Invalid Argument'), 'InvalidBucketName': (HTTP_BAD_REQUEST, 'The specified bucket is not valid'), 'InvalidURI': (HTTP_BAD_REQUEST, 'Could not parse the specified URI'), 'InvalidDigest': (HTTP_BAD_REQUEST, 'The Content-MD5 you specified was invalid'), 'BadDigest': (HTTP_BAD_REQUEST, 'The Content-Length you specified was invalid'), 'NoSuchBucket': (HTTP_NOT_FOUND, 'The specified bucket does not exist'), 'SignatureDoesNotMatch': (HTTP_FORBIDDEN, 'The calculated request signature does not match your provided one'), 'RequestTimeTooSkewed': (HTTP_FORBIDDEN, 'The difference between the request time and the current time is too large'), 'NoSuchKey': (HTTP_NOT_FOUND, 'The resource you requested does not exist'), 'Unsupported': (HTTP_NOT_IMPLEMENTED, 'The feature you requested is not yet implemented'), 'MissingContentLength': (HTTP_LENGTH_REQUIRED, 'Length Required'), 'ServiceUnavailable': (HTTP_SERVICE_UNAVAILABLE, 'Please reduce your request rate')} resp = Response(content_type='text/xml') resp.status = error_table[code][0] resp.body = ('<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n <Code>%s</Code>\r\n <Message>%s</Message>\r\n</Error>\r\n' % (code, error_table[code][1])) return resp
[ "def", "get_err_response", "(", "code", ")", ":", "error_table", "=", "{", "'AccessDenied'", ":", "(", "HTTP_FORBIDDEN", ",", "'Access denied'", ")", ",", "'BucketAlreadyExists'", ":", "(", "HTTP_CONFLICT", ",", "'The requested bucket name is not available'", ")", ","...
given an http response code .
train
false
33,106
def validate_non_negative_integer_or_none(option, value): if (value is None): return value return validate_non_negative_integer(option, value)
[ "def", "validate_non_negative_integer_or_none", "(", "option", ",", "value", ")", ":", "if", "(", "value", "is", "None", ")", ":", "return", "value", "return", "validate_non_negative_integer", "(", "option", ",", "value", ")" ]
validate that value is a positive integer or 0 or none .
train
false
33,107
@register_uncanonicalize @gof.local_optimizer([T.Alloc]) def local_alloc_dimshuffle(node): if isinstance(node.op, T.Alloc): input_ = node.inputs[0] if (input_.owner and isinstance(input_.owner.op, DimShuffle)): new_order = input_.owner.op.new_order expected_new_order = ((('x',) * (input_.ndim - input_.owner.inputs[0].ndim)) + tuple(range(input_.owner.inputs[0].ndim))) if (new_order != expected_new_order): return False return [T.alloc(input_.owner.inputs[0], *node.inputs[1:])] return False
[ "@", "register_uncanonicalize", "@", "gof", ".", "local_optimizer", "(", "[", "T", ".", "Alloc", "]", ")", "def", "local_alloc_dimshuffle", "(", "node", ")", ":", "if", "isinstance", "(", "node", ".", "op", ",", "T", ".", "Alloc", ")", ":", "input_", "...
if a dimshuffle is inside an alloc and only adds dimension to the left .
train
false
33,108
@receiver(thread_voted) @receiver(thread_created) @receiver(comment_voted) @receiver(comment_created) def post_create_vote_handler(sender, **kwargs): handle_activity(kwargs['user'], kwargs['post'])
[ "@", "receiver", "(", "thread_voted", ")", "@", "receiver", "(", "thread_created", ")", "@", "receiver", "(", "comment_voted", ")", "@", "receiver", "(", "comment_created", ")", "def", "post_create_vote_handler", "(", "sender", ",", "**", "kwargs", ")", ":", ...
update the users last activity date upon creating or voting for a post .
train
false
33,109
def unpack_nullterm_array(array): addrs = cast(array, POINTER(ctypes.c_void_p)) l = [] i = 0 value = array[i] while value: l.append(value) free(addrs[i]) i += 1 value = array[i] free(addrs) return l
[ "def", "unpack_nullterm_array", "(", "array", ")", ":", "addrs", "=", "cast", "(", "array", ",", "POINTER", "(", "ctypes", ".", "c_void_p", ")", ")", "l", "=", "[", "]", "i", "=", "0", "value", "=", "array", "[", "i", "]", "while", "value", ":", ...
takes a null terminated array .
train
true
33,110
def __apf_cmd(cmd): apf_cmd = '{0} {1}'.format(salt.utils.which('apf'), cmd) out = __salt__['cmd.run_all'](apf_cmd) if (out['retcode'] != 0): if (not out['stderr']): msg = out['stdout'] else: msg = out['stderr'] raise CommandExecutionError('apf failed: {0}'.format(msg)) return out['stdout']
[ "def", "__apf_cmd", "(", "cmd", ")", ":", "apf_cmd", "=", "'{0} {1}'", ".", "format", "(", "salt", ".", "utils", ".", "which", "(", "'apf'", ")", ",", "cmd", ")", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "apf_cmd", ")", "if", "(", "o...
return the apf location .
train
true
33,111
def test_callable_filter(): def my_filter(_in, out): assert (_in.read() == 'initial value') out.write('filter was here') with TempEnvironmentHelper() as helper: helper.create_files({'in': 'initial value'}) b = helper.mkbundle('in', filters=my_filter, output='out') b.build() assert (helper.get('out') == 'filter was here')
[ "def", "test_callable_filter", "(", ")", ":", "def", "my_filter", "(", "_in", ",", "out", ")", ":", "assert", "(", "_in", ".", "read", "(", ")", "==", "'initial value'", ")", "out", ".", "write", "(", "'filter was here'", ")", "with", "TempEnvironmentHelpe...
simple callables can be used as filters .
train
false
33,112
def _comp_intron_lens(seq_type, inter_blocks, raw_inter_lens): opp_type = ('hit' if (seq_type == 'query') else 'query') has_intron_after = [('Intron' in x[seq_type]) for x in inter_blocks] assert (len(has_intron_after) == len(raw_inter_lens)) inter_lens = [] for (flag, parsed_len) in zip(has_intron_after, raw_inter_lens): if flag: if all(parsed_len[:2]): intron_len = (int(parsed_len[0]) if (opp_type == 'query') else int(parsed_len[1])) elif parsed_len[2]: intron_len = int(parsed_len[2]) else: raise ValueError(('Unexpected intron parsing result: %r' % parsed_len)) else: intron_len = 0 inter_lens.append(intron_len) return inter_lens
[ "def", "_comp_intron_lens", "(", "seq_type", ",", "inter_blocks", ",", "raw_inter_lens", ")", ":", "opp_type", "=", "(", "'hit'", "if", "(", "seq_type", "==", "'query'", ")", "else", "'query'", ")", "has_intron_after", "=", "[", "(", "'Intron'", "in", "x", ...
returns the length of introns between fragments .
train
false
33,113
def by_name(backend=None, loader=None, extension_namespace=u'celery.result_backends'): backend = (backend or u'disabled') loader = (loader or current_app.loader) aliases = dict(BACKEND_ALIASES, **loader.override_backends) aliases.update((load_extension_class_names(extension_namespace) or {})) try: cls = symbol_by_name(backend, aliases) except ValueError as exc: reraise(ImproperlyConfigured, ImproperlyConfigured(UNKNOWN_BACKEND.strip().format(backend, exc)), sys.exc_info()[2]) if isinstance(cls, types.ModuleType): raise ImproperlyConfigured(UNKNOWN_BACKEND.strip().format(backend, u'is a Python module, not a backend class.')) return cls
[ "def", "by_name", "(", "backend", "=", "None", ",", "loader", "=", "None", ",", "extension_namespace", "=", "u'celery.result_backends'", ")", ":", "backend", "=", "(", "backend", "or", "u'disabled'", ")", "loader", "=", "(", "loader", "or", "current_app", "....
get backend class by name/alias .
train
false
33,115
def test_nextitem_previtem_chain(hist): assert (hist.start('f') == 'fifth') assert (hist.previtem() == 'fourth') assert (hist.previtem() == 'first') assert (hist.nextitem() == 'fourth')
[ "def", "test_nextitem_previtem_chain", "(", "hist", ")", ":", "assert", "(", "hist", ".", "start", "(", "'f'", ")", "==", "'fifth'", ")", "assert", "(", "hist", ".", "previtem", "(", ")", "==", "'fourth'", ")", "assert", "(", "hist", ".", "previtem", "...
test a combination of nextitem and previtem statements .
train
false
33,116
def get_balances(): opts = salt.utils.namecheap.get_opts('namecheap.users.getBalances') response_xml = salt.utils.namecheap.get_request(opts) if (response_xml is None): return {} balance_response = response_xml.getElementsByTagName('UserGetBalancesResult')[0] return salt.utils.namecheap.atts_to_dict(balance_response)
[ "def", "get_balances", "(", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.users.getBalances'", ")", "response_xml", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_request", "(", "opts", ")", "if", ...
gets information about fund in the users account .
train
true
33,117
@with_setup(step_runner_environ) def test_undefined_behave_as_step_fails(): runnable_step = Step.from_string('Given I have a step which calls the "undefined step" step with behave_as') assert_raises(AssertionError, runnable_step.run, True) assert runnable_step.failed
[ "@", "with_setup", "(", "step_runner_environ", ")", "def", "test_undefined_behave_as_step_fails", "(", ")", ":", "runnable_step", "=", "Step", ".", "from_string", "(", "'Given I have a step which calls the \"undefined step\" step with behave_as'", ")", "assert_raises", "(", "...
when a step definition calls an undefined step definition with behave_as .
train
false
33,118
def get_model_url(object, kind=u'detail', user=None, required_permissions=None): for module in get_modules(): url = module.get_model_url(object, kind) if (not url): continue if (user is None): return url else: permissions = () if (required_permissions is not None): permissions = required_permissions else: permissions = get_default_model_permissions(object) if (not get_missing_permissions(user, permissions)): return url raise NoModelUrl((u"Can't get object URL of kind %s: %r" % (kind, force_text(object))))
[ "def", "get_model_url", "(", "object", ",", "kind", "=", "u'detail'", ",", "user", "=", "None", ",", "required_permissions", "=", "None", ")", ":", "for", "module", "in", "get_modules", "(", ")", ":", "url", "=", "module", ".", "get_model_url", "(", "obj...
get a an admin object url for the given object or object class by interrogating each admin module .
train
false
33,119
def lagrange_inversion(a): n = len(a) f = sum(((a[i] * (x ** i)) for i in range(len(a)))) h = (x / f).series(x, 0, n).removeO() hpower = [(h ** 0)] for k in range(n): hpower.append((hpower[(-1)] * h).expand()) b = [mp.mpf(0)] for k in range(1, n): b.append((hpower[k].coeff(x, (k - 1)) / k)) b = map((lambda x: mp.mpf(x)), b) return b
[ "def", "lagrange_inversion", "(", "a", ")", ":", "n", "=", "len", "(", "a", ")", "f", "=", "sum", "(", "(", "(", "a", "[", "i", "]", "*", "(", "x", "**", "i", ")", ")", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", ")", ")"...
given a series f(x) = a[1]*x + a[2]*x**2 + .
train
false
33,120
def _check_newline(prefix, file_name, keep_newline): if isinstance(keep_newline, bool): return (not keep_newline) full_path = os.path.join(prefix, file_name) for pattern in keep_newline: try: if fnmatch.fnmatch(full_path, pattern): return False except TypeError: if fnmatch.fnmatch(full_path, str(pattern)): return False return True
[ "def", "_check_newline", "(", "prefix", ",", "file_name", ",", "keep_newline", ")", ":", "if", "isinstance", "(", "keep_newline", ",", "bool", ")", ":", "return", "(", "not", "keep_newline", ")", "full_path", "=", "os", ".", "path", ".", "join", "(", "pr...
return a boolean stating whether or not a files trailing newline should be removed .
train
true
33,121
def test_resize_icon_enlarge(): resize_size = [1000] final_size = [(339, 128)] _uploader(resize_size, final_size)
[ "def", "test_resize_icon_enlarge", "(", ")", ":", "resize_size", "=", "[", "1000", "]", "final_size", "=", "[", "(", "339", ",", "128", ")", "]", "_uploader", "(", "resize_size", ",", "final_size", ")" ]
image stays the same .
train
false
33,122
def test_bare_started_state(name, path=None): try: ret = (run_all(name, 'ls', path=path, ignore_retcode=True)['retcode'] == 0) except (CommandExecutionError,): ret = None return ret
[ "def", "test_bare_started_state", "(", "name", ",", "path", "=", "None", ")", ":", "try", ":", "ret", "=", "(", "run_all", "(", "name", ",", "'ls'", ",", "path", "=", "path", ",", "ignore_retcode", "=", "True", ")", "[", "'retcode'", "]", "==", "0", ...
test if a non systemd container is fully started for now .
train
true
33,123
def get_all_theme_template_dirs(): themes = get_themes() template_paths = list() for theme in themes: template_paths.extend(theme.template_dirs) return template_paths
[ "def", "get_all_theme_template_dirs", "(", ")", ":", "themes", "=", "get_themes", "(", ")", "template_paths", "=", "list", "(", ")", "for", "theme", "in", "themes", ":", "template_paths", ".", "extend", "(", "theme", ".", "template_dirs", ")", "return", "tem...
returns template directories for all the themes .
train
false
33,124
def _diff_conditional(expr, base_scalar): new_expr = express(expr, base_scalar.system, variables=True) if (base_scalar in new_expr.atoms(BaseScalar)): return Derivative(new_expr, base_scalar) return S(0)
[ "def", "_diff_conditional", "(", "expr", ",", "base_scalar", ")", ":", "new_expr", "=", "express", "(", "expr", ",", "base_scalar", ".", "system", ",", "variables", "=", "True", ")", "if", "(", "base_scalar", "in", "new_expr", ".", "atoms", "(", "BaseScala...
first re-expresses expr in the system that base_scalar belongs to .
train
false
33,126
def substitute_keywords_with_data(string, context): user_id = context.get('user_id') course_title = context.get('course_title') if ((user_id is None) or (course_title is None)): return string return substitute_keywords(string, user_id, context)
[ "def", "substitute_keywords_with_data", "(", "string", ",", "context", ")", ":", "user_id", "=", "context", ".", "get", "(", "'user_id'", ")", "course_title", "=", "context", ".", "get", "(", "'course_title'", ")", "if", "(", "(", "user_id", "is", "None", ...
given an email context .
train
false
33,127
def _generate_mne_locs_file(output_fname): logger.info('Converting Tristan coil file to mne loc file...') resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources') chan_fname = op.join(resource_dir, 'Artemis123_ChannelMap.csv') chans = _load_tristan_coil_locs(chan_fname) locs = {n: _compute_mne_loc(cinfo) for (n, cinfo) in chans.items()} with open(output_fname, 'w') as fid: for n in sorted(locs.keys()): fid.write(('%s,' % n)) fid.write(','.join(locs[n].astype(str))) fid.write('\n')
[ "def", "_generate_mne_locs_file", "(", "output_fname", ")", ":", "logger", ".", "info", "(", "'Converting Tristan coil file to mne loc file...'", ")", "resource_dir", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "op", ".", "abspath", "(", "__file__", ...
generate mne coil locs and save to supplied file .
train
false
33,128
def _KindKeyToString(key): key_path = key.to_path() if ((len(key_path) == 2) and (key_path[0] == '__kind__') and isinstance(key_path[1], basestring)): return key_path[1] raise BadRequestError('invalid Key for __kind__ table')
[ "def", "_KindKeyToString", "(", "key", ")", ":", "key_path", "=", "key", ".", "to_path", "(", ")", "if", "(", "(", "len", "(", "key_path", ")", "==", "2", ")", "and", "(", "key_path", "[", "0", "]", "==", "'__kind__'", ")", "and", "isinstance", "("...
extract kind name from __kind__ key .
train
false
33,131
def quota_class_update(context, class_name, resource, limit): return IMPL.quota_class_update(context, class_name, resource, limit)
[ "def", "quota_class_update", "(", "context", ",", "class_name", ",", "resource", ",", "limit", ")", ":", "return", "IMPL", ".", "quota_class_update", "(", "context", ",", "class_name", ",", "resource", ",", "limit", ")" ]
update a quota class or raise if it does not exist .
train
false
33,132
def __named_property_def(DOMname): CSSname = _toCSSname(DOMname) def _get(self): return self._getP(CSSname) def _set(self, value): self._setP(CSSname, value) def _del(self): self._delP(CSSname) return (_get, _set, _del)
[ "def", "__named_property_def", "(", "DOMname", ")", ":", "CSSname", "=", "_toCSSname", "(", "DOMname", ")", "def", "_get", "(", "self", ")", ":", "return", "self", ".", "_getP", "(", "CSSname", ")", "def", "_set", "(", "self", ",", "value", ")", ":", ...
closure to keep name known in each properties accessor function domname is converted to cssname here .
train
false
33,135
def generate_sentences(amount, start_with_lorem=False): return _GENERATOR.generate_sentences(amount, start_with_lorem)
[ "def", "generate_sentences", "(", "amount", ",", "start_with_lorem", "=", "False", ")", ":", "return", "_GENERATOR", ".", "generate_sentences", "(", "amount", ",", "start_with_lorem", ")" ]
generator function that yields specified amount of random sentences with stats .
train
false
33,136
def is_youtube_available(): return False
[ "def", "is_youtube_available", "(", ")", ":", "return", "False" ]
check if the required youtube urls are available .
train
false
33,137
def get_rollbacks(): return _get_client().get_rollbacks()
[ "def", "get_rollbacks", "(", ")", ":", "return", "_get_client", "(", ")", ".", "get_rollbacks", "(", ")" ]
get a list of stored configuration rollbacks .
train
false
33,138
def _require_store(tp, po_dir, name): from pootle_store.constants import PARSED from pootle_store.models import Store parent_dir = tp.directory pootle_path = (tp.pootle_path + name) file_path = (tp.real_path and os.path.join(po_dir, tp.real_path, name)) try: store = Store.objects.get(pootle_path=pootle_path, translation_project=tp) except Store.DoesNotExist: store = Store.objects.create_by_path(file=file_path, create_tp=False, create_directory=False, pootle_path=('%s%s' % (parent_dir.pootle_path, name))) if store.file.exists(): if (store.state < PARSED): store.update(store.file.store) return store
[ "def", "_require_store", "(", "tp", ",", "po_dir", ",", "name", ")", ":", "from", "pootle_store", ".", "constants", "import", "PARSED", "from", "pootle_store", ".", "models", "import", "Store", "parent_dir", "=", "tp", ".", "directory", "pootle_path", "=", "...
helper to get/create a new store .
train
false
33,139
def object_copy(self, CopySource, ExtraArgs=None, Callback=None, SourceClient=None, Config=None): return self.meta.client.copy(CopySource=CopySource, Bucket=self.bucket_name, Key=self.key, ExtraArgs=ExtraArgs, Callback=Callback, SourceClient=SourceClient, Config=Config)
[ "def", "object_copy", "(", "self", ",", "CopySource", ",", "ExtraArgs", "=", "None", ",", "Callback", "=", "None", ",", "SourceClient", "=", "None", ",", "Config", "=", "None", ")", ":", "return", "self", ".", "meta", ".", "client", ".", "copy", "(", ...
copy an object from one s3 location to this object .
train
false
33,140
def extract_from_file(method, filename, keywords=DEFAULT_KEYWORDS, comment_tags=(), options=None, strip_comment_tags=False): with open(filename, 'rb') as fileobj: return list(extract(method, fileobj, keywords, comment_tags, options, strip_comment_tags))
[ "def", "extract_from_file", "(", "method", ",", "filename", ",", "keywords", "=", "DEFAULT_KEYWORDS", ",", "comment_tags", "=", "(", ")", ",", "options", "=", "None", ",", "strip_comment_tags", "=", "False", ")", ":", "with", "open", "(", "filename", ",", ...
extract messages from a specific file .
train
false
33,142
def rows_from_range(range_string): (min_col, min_row, max_col, max_row) = range_boundaries(range_string) for row in range(min_row, (max_row + 1)): (yield tuple((('%s%d' % (get_column_letter(col), row)) for col in range(min_col, (max_col + 1)))))
[ "def", "rows_from_range", "(", "range_string", ")", ":", "(", "min_col", ",", "min_row", ",", "max_col", ",", "max_row", ")", "=", "range_boundaries", "(", "range_string", ")", "for", "row", "in", "range", "(", "min_row", ",", "(", "max_row", "+", "1", "...
get individual addresses for every cell in a range .
train
false
33,143
def check_sole_error(response, status, strings): if isinstance(strings, str): strings = [strings] assert (response.status_code == status) document = loads(response.data) errors = document['errors'] assert (len(errors) == 1) error = errors[0] assert (error['status'] == status) assert all(((s in error['detail']) for s in strings))
[ "def", "check_sole_error", "(", "response", ",", "status", ",", "strings", ")", ":", "if", "isinstance", "(", "strings", ",", "str", ")", ":", "strings", "=", "[", "strings", "]", "assert", "(", "response", ".", "status_code", "==", "status", ")", "docum...
asserts that the response is an errors response with a single error object whose detail message contains all of the given strings .
train
false
33,144
def commit(): connection._commit() set_clean()
[ "def", "commit", "(", ")", ":", "connection", ".", "_commit", "(", ")", "set_clean", "(", ")" ]
commits a transaction .
train
false
33,147
def _refine_mode(mode): mode = str(mode).lower() if any([mode.startswith('e'), (mode == '1'), (mode == 'on')]): return 'Enforcing' if any([mode.startswith('p'), (mode == '0'), (mode == 'off')]): return 'Permissive' if any([mode.startswith('d')]): return 'Disabled' return 'unknown'
[ "def", "_refine_mode", "(", "mode", ")", ":", "mode", "=", "str", "(", "mode", ")", ".", "lower", "(", ")", "if", "any", "(", "[", "mode", ".", "startswith", "(", "'e'", ")", ",", "(", "mode", "==", "'1'", ")", ",", "(", "mode", "==", "'on'", ...
return a mode value that is predictable .
train
false
33,148
def PolygonCollection(mode='raw', *args, **kwargs): return RawPolygonCollection(*args, **kwargs)
[ "def", "PolygonCollection", "(", "mode", "=", "'raw'", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "RawPolygonCollection", "(", "*", "args", ",", "**", "kwargs", ")" ]
mode: string - "raw" - "agg" - "agg+" .
train
false
33,149
def muse(field): out = sh('muse') for line in out.split('\n'): if line.startswith(field): break else: raise ValueError('line not found') return int(line.split()[1])
[ "def", "muse", "(", "field", ")", ":", "out", "=", "sh", "(", "'muse'", ")", "for", "line", "in", "out", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "field", ")", ":", "break", "else", ":", "raise", "ValueError", "...
thin wrapper around muse cmdline utility .
train
false
33,150
def marker_comparator(matches, markers): def comparator(marker1, marker2): '\n The actual comparator function.\n ' matches_count = (marker_weight(matches, marker2) - marker_weight(matches, marker1)) if matches_count: return matches_count len_diff = (len(marker2) - len(marker1)) if len_diff: return len_diff return (markers.index(marker2) - markers.index(marker1)) return comparator
[ "def", "marker_comparator", "(", "matches", ",", "markers", ")", ":", "def", "comparator", "(", "marker1", ",", "marker2", ")", ":", "matches_count", "=", "(", "marker_weight", "(", "matches", ",", "marker2", ")", "-", "marker_weight", "(", "matches", ",", ...
builds a comparator that returns markers sorted from the most valuable to the less .
train
false
33,151
def test_inequality(): lu1 = u.mag(u.Jy) lu2 = u.dex(u.Jy) lu3 = u.mag((u.Jy ** 2)) lu4 = (lu3 - lu1) assert (lu1 != lu2) assert (lu1 != lu3) assert (lu1 == lu4)
[ "def", "test_inequality", "(", ")", ":", "lu1", "=", "u", ".", "mag", "(", "u", ".", "Jy", ")", "lu2", "=", "u", ".", "dex", "(", "u", ".", "Jy", ")", "lu3", "=", "u", ".", "mag", "(", "(", "u", ".", "Jy", "**", "2", ")", ")", "lu4", "=...
check __ne__ works .
train
false
33,152
def unique_svr_name(server): num = 0 svr = 1 new_name = server while svr: if num: new_name = ('%s@%d' % (server, num)) else: new_name = ('%s' % server) svr = config.get_config('servers', new_name) num += 1 return new_name
[ "def", "unique_svr_name", "(", "server", ")", ":", "num", "=", "0", "svr", "=", "1", "new_name", "=", "server", "while", "svr", ":", "if", "num", ":", "new_name", "=", "(", "'%s@%d'", "%", "(", "server", ",", "num", ")", ")", "else", ":", "new_name...
return a unique variant on given server name .
train
false
33,154
def set_remote_events(enable): state = salt.utils.mac_utils.validate_enabled(enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) salt.utils.mac_utils.execute_return_success(cmd) return salt.utils.mac_utils.confirm_updated(state, get_remote_events, normalize_ret=True)
[ "def", "set_remote_events", "(", "enable", ")", ":", "state", "=", "salt", ".", "utils", ".", "mac_utils", ".", "validate_enabled", "(", "enable", ")", "cmd", "=", "'systemsetup -setremoteappleevents {0}'", ".", "format", "(", "state", ")", "salt", ".", "utils...
set whether the server responds to events sent by other computers .
train
false
33,156
def check_minc(): return (Info.version() is not None)
[ "def", "check_minc", "(", ")", ":", "return", "(", "Info", ".", "version", "(", ")", "is", "not", "None", ")" ]
returns true if and only if minc is installed .
train
false
33,157
@LocalContext def scramble(raw_bytes, *a, **kw): return encode(raw_bytes, force=1, *a, **kw)
[ "@", "LocalContext", "def", "scramble", "(", "raw_bytes", ",", "*", "a", ",", "**", "kw", ")", ":", "return", "encode", "(", "raw_bytes", ",", "force", "=", "1", ",", "*", "a", ",", "**", "kw", ")" ]
scramble -> str encodes the input data with a random encoder .
train
false
33,158
def get_fontext_synonyms(fontext): return {'ttf': ('ttf', 'otf'), 'otf': ('ttf', 'otf'), 'afm': ('afm',)}[fontext]
[ "def", "get_fontext_synonyms", "(", "fontext", ")", ":", "return", "{", "'ttf'", ":", "(", "'ttf'", ",", "'otf'", ")", ",", "'otf'", ":", "(", "'ttf'", ",", "'otf'", ")", ",", "'afm'", ":", "(", "'afm'", ",", ")", "}", "[", "fontext", "]" ]
return a list of file extensions extensions that are synonyms for the given file extension *fileext* .
train
false
33,159
def revert_strip_none(data): if (isinstance(data, str) and (data.strip() == '~')): return None if isinstance(data, list): data2 = [] for x in data: data2.append(revert_strip_none(x)) return data2 if isinstance(data, dict): data2 = {} for key in data.keys(): data2[key] = revert_strip_none(data[key]) return data2 return data
[ "def", "revert_strip_none", "(", "data", ")", ":", "if", "(", "isinstance", "(", "data", ",", "str", ")", "and", "(", "data", ".", "strip", "(", ")", "==", "'~'", ")", ")", ":", "return", "None", "if", "isinstance", "(", "data", ",", "list", ")", ...
does the opposite to strip_none .
train
false
33,160
def to_binary_string(obj, encoding=None): if PY2: if (encoding is None): return str(obj) else: return obj.encode(encoding) else: return bytes(obj, ('utf-8' if (encoding is None) else encoding))
[ "def", "to_binary_string", "(", "obj", ",", "encoding", "=", "None", ")", ":", "if", "PY2", ":", "if", "(", "encoding", "is", "None", ")", ":", "return", "str", "(", "obj", ")", "else", ":", "return", "obj", ".", "encode", "(", "encoding", ")", "el...
convert obj to binary string .
train
true
33,161
def _mult_cal_one(data_view, one, idx, cals, mult): one = np.asarray(one, dtype=data_view.dtype) assert (data_view.shape[1] == one.shape[1]) if (mult is not None): data_view[:] = np.dot(mult, one) else: if isinstance(idx, slice): data_view[:] = one[idx] else: np.take(one, idx, axis=0, out=data_view) if (cals is not None): data_view *= cals
[ "def", "_mult_cal_one", "(", "data_view", ",", "one", ",", "idx", ",", "cals", ",", "mult", ")", ":", "one", "=", "np", ".", "asarray", "(", "one", ",", "dtype", "=", "data_view", ".", "dtype", ")", "assert", "(", "data_view", ".", "shape", "[", "1...
take a chunk of raw data .
train
false
33,163
@when(u'we create table') def step_create_table(context): context.cli.sendline(u'create table a(x text);')
[ "@", "when", "(", "u'we create table'", ")", "def", "step_create_table", "(", "context", ")", ":", "context", ".", "cli", ".", "sendline", "(", "u'create table a(x text);'", ")" ]
send create table .
train
false
33,164
@world.absorb def css_has_value(css_selector, value, index=0): if value: wait_for((lambda _: css_value(css_selector, index=index))) return (css_value(css_selector, index=index) == value)
[ "@", "world", ".", "absorb", "def", "css_has_value", "(", "css_selector", ",", "value", ",", "index", "=", "0", ")", ":", "if", "value", ":", "wait_for", "(", "(", "lambda", "_", ":", "css_value", "(", "css_selector", ",", "index", "=", "index", ")", ...
return a boolean indicating whether the element with css_selector has the specified value .
train
false
33,165
def relu(x, use_cudnn=True): return ReLU(use_cudnn)(x)
[ "def", "relu", "(", "x", ",", "use_cudnn", "=", "True", ")", ":", "return", "ReLU", "(", "use_cudnn", ")", "(", "x", ")" ]
relu implementation with t .
train
false
33,166
def _net_read(sock, count, expiration): s = '' while (count > 0): _wait_for_readable(sock, expiration) n = sock.recv(count) if (n == ''): raise EOFError count = (count - len(n)) s = (s + n) return s
[ "def", "_net_read", "(", "sock", ",", "count", ",", "expiration", ")", ":", "s", "=", "''", "while", "(", "count", ">", "0", ")", ":", "_wait_for_readable", "(", "sock", ",", "expiration", ")", "n", "=", "sock", ".", "recv", "(", "count", ")", "if"...
read the specified number of bytes from sock .
train
true
33,168
def testing_engine(url=None, options=None): from sqlalchemy import create_engine from sqlalchemy.engine.url import make_url if (not options): use_reaper = True else: use_reaper = options.pop('use_reaper', True) url = (url or config.db.url) url = make_url(url) if (options is None): if ((config.db is None) or (url.drivername == config.db.url.drivername)): options = config.db_opts else: options = {} engine = create_engine(url, **options) engine._has_events = True if isinstance(engine.pool, pool.QueuePool): engine.pool._timeout = 0 engine.pool._max_overflow = 0 if use_reaper: event.listen(engine.pool, 'connect', testing_reaper.connect) event.listen(engine.pool, 'checkout', testing_reaper.checkout) event.listen(engine.pool, 'invalidate', testing_reaper.invalidate) testing_reaper.add_engine(engine) return engine
[ "def", "testing_engine", "(", "url", "=", "None", ",", "options", "=", "None", ")", ":", "from", "sqlalchemy", "import", "create_engine", "from", "sqlalchemy", ".", "engine", ".", "url", "import", "make_url", "if", "(", "not", "options", ")", ":", "use_rea...
produce an engine configured by --options with optional overrides .
train
false
33,170
def group_significance_row_generator(bt, cat_sam_indices): data = array([i for i in bt.iter_data(axis='observation')]) indices = cat_sam_indices.values() return izip(*[data.take(i, axis=1) for i in indices])
[ "def", "group_significance_row_generator", "(", "bt", ",", "cat_sam_indices", ")", ":", "data", "=", "array", "(", "[", "i", "for", "i", "in", "bt", ".", "iter_data", "(", "axis", "=", "'observation'", ")", "]", ")", "indices", "=", "cat_sam_indices", ".",...
produce generator that feeds lists of arrays to group significance tests .
train
false
33,171
def module_name_split(name): if ('.' in name): (package_name, module) = name.rsplit('.', 1) else: (package_name, module) = ('', name) return (package_name, module)
[ "def", "module_name_split", "(", "name", ")", ":", "if", "(", "'.'", "in", "name", ")", ":", "(", "package_name", ",", "module", ")", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "else", ":", "(", "package_name", ",", "module", ")", "=", ...
split the module name into package name and module name .
train
false
33,172
def test_column_named_items(): class ItemsTable(tables.Table, ): items = tables.Column() table = ItemsTable([{u'items': 123}, {u'items': 2345}]) html = table.as_html(request) assert (u'123' in html) assert (u'2345' in html)
[ "def", "test_column_named_items", "(", ")", ":", "class", "ItemsTable", "(", "tables", ".", "Table", ",", ")", ":", "items", "=", "tables", ".", "Column", "(", ")", "table", "=", "ItemsTable", "(", "[", "{", "u'items'", ":", "123", "}", ",", "{", "u'...
a column named items must not make the table fail URL .
train
false
33,173
def getHitmask(image): mask = [] for x in range(image.get_width()): mask.append([]) for y in range(image.get_height()): mask[x].append(bool(image.get_at((x, y))[3])) return mask
[ "def", "getHitmask", "(", "image", ")", ":", "mask", "=", "[", "]", "for", "x", "in", "range", "(", "image", ".", "get_width", "(", ")", ")", ":", "mask", ".", "append", "(", "[", "]", ")", "for", "y", "in", "range", "(", "image", ".", "get_hei...
returns a hitmask using an images alpha .
train
false
33,174
def eq_(result, expected, msg=None): params = {'expected': expected, 'result': result} aka = ('\n\n--------------------------------- aka -----------------------------------------\n\nExpected:\n%(expected)r\n\nGot:\n%(result)r\n' % params) default_msg = ('\nExpected:\n%(expected)s\n\nGot:\n%(result)s\n' % params) if ((repr(result) != str(result)) or (repr(expected) != str(expected))): default_msg += aka assert (result == expected), (msg or default_msg)
[ "def", "eq_", "(", "result", ",", "expected", ",", "msg", "=", "None", ")", ":", "params", "=", "{", "'expected'", ":", "expected", ",", "'result'", ":", "result", "}", "aka", "=", "(", "'\\n\\n--------------------------------- aka --------------------------------...
shorthand for assert a == b .
train
false
33,175
def bz2_encode(input, errors='strict'): assert (errors == 'strict') output = bz2.compress(input) return (output, len(input))
[ "def", "bz2_encode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "assert", "(", "errors", "==", "'strict'", ")", "output", "=", "bz2", ".", "compress", "(", "input", ")", "return", "(", "output", ",", "len", "(", "input", ")", ")" ]
encodes the object input and returns a tuple .
train
false
33,176
def upgrade_to_access_token(request_token, server_response_body): (token, token_secret) = oauth_token_info_from_body(server_response_body) request_token.token = token request_token.token_secret = token_secret request_token.auth_state = ACCESS_TOKEN request_token.next = None request_token.verifier = None return request_token
[ "def", "upgrade_to_access_token", "(", "request_token", ",", "server_response_body", ")", ":", "(", "token", ",", "token_secret", ")", "=", "oauth_token_info_from_body", "(", "server_response_body", ")", "request_token", ".", "token", "=", "token", "request_token", "....
extracts access token information from response to an upgrade request .
train
false
33,177
def get_lb_conn(dd_driver=None): vm_ = get_configured_provider() region = config.get_cloud_config_value('region', vm_, __opts__) user_id = config.get_cloud_config_value('user_id', vm_, __opts__) key = config.get_cloud_config_value('key', vm_, __opts__) if (not dd_driver): raise SaltCloudSystemExit('Missing dimensiondata_driver for get_lb_conn method.') return get_driver_lb(Provider_lb.DIMENSIONDATA)(user_id, key, region=region)
[ "def", "get_lb_conn", "(", "dd_driver", "=", "None", ")", ":", "vm_", "=", "get_configured_provider", "(", ")", "region", "=", "config", ".", "get_cloud_config_value", "(", "'region'", ",", "vm_", ",", "__opts__", ")", "user_id", "=", "config", ".", "get_clo...
return a load-balancer conn object .
train
true
33,180
def sigma_skip(p): return C_skip
[ "def", "sigma_skip", "(", "p", ")", ":", "return", "C_skip" ]
returns score of an indel of p .
train
false
33,182
def gammaln(x): x = (x - 1.0) y = (x + 5.5) y = (((x + 0.5) * log(y)) - y) n = 1.0 for i in xrange(6): x += 1 n += ((76.18009173, (-86.50532033), 24.01409822, (-1.231739516), 0.00120858003, (-5.36382e-06))[i] / x) return (y + log((2.50662827465 * n)))
[ "def", "gammaln", "(", "x", ")", ":", "x", "=", "(", "x", "-", "1.0", ")", "y", "=", "(", "x", "+", "5.5", ")", "y", "=", "(", "(", "(", "x", "+", "0.5", ")", "*", "log", "(", "y", ")", ")", "-", "y", ")", "n", "=", "1.0", "for", "i...
returns the natural logarithm of the gamma function at x .
train
false
33,183
def lang_map(): iso639 = _load_iso639() translate = _ global _lang_map if (_lang_map is None): _lang_map = {k: translate(v) for (k, v) in iso639['by_3t'].iteritems()} return _lang_map
[ "def", "lang_map", "(", ")", ":", "iso639", "=", "_load_iso639", "(", ")", "translate", "=", "_", "global", "_lang_map", "if", "(", "_lang_map", "is", "None", ")", ":", "_lang_map", "=", "{", "k", ":", "translate", "(", "v", ")", "for", "(", "k", "...
return mapping of iso 639 3 letter codes to localized language names .
train
false
33,185
def get_fczm_drivers(): _ensure_loaded('cinder/zonemanager/drivers') return [DriverInfo(x) for x in interface._fczm_register]
[ "def", "get_fczm_drivers", "(", ")", ":", "_ensure_loaded", "(", "'cinder/zonemanager/drivers'", ")", "return", "[", "DriverInfo", "(", "x", ")", "for", "x", "in", "interface", ".", "_fczm_register", "]" ]
get a list of all fczm drivers .
train
false
33,186
def _query_for_diff(review_request, user, revision, draft): if revision: revision = int(revision) if (draft and draft.diffset_id and ((revision is None) or (draft.diffset.revision == revision))): return draft.diffset query = Q(history=review_request.diffset_history_id) if (revision is not None): query = (query & Q(revision=revision)) try: return DiffSet.objects.filter(query).latest() except DiffSet.DoesNotExist: raise Http404
[ "def", "_query_for_diff", "(", "review_request", ",", "user", ",", "revision", ",", "draft", ")", ":", "if", "revision", ":", "revision", "=", "int", "(", "revision", ")", "if", "(", "draft", "and", "draft", ".", "diffset_id", "and", "(", "(", "revision"...
queries for a diff based on several parameters .
train
false
33,187
def contenttype(): return random.choice(('image/jpeg', 'text/html', 'audio/aiff', 'video/avi', 'text/plain', 'application/msword', 'application/x-gzip', 'application/javascript'))
[ "def", "contenttype", "(", ")", ":", "return", "random", ".", "choice", "(", "(", "'image/jpeg'", ",", "'text/html'", ",", "'audio/aiff'", ",", "'video/avi'", ",", "'text/plain'", ",", "'application/msword'", ",", "'application/x-gzip'", ",", "'application/javascrip...
random mime type .
train
false
33,188
def notify_user(user, msg, **kwargs): Notification.objects.create(recipient=user, subject=msg, **kwargs)
[ "def", "notify_user", "(", "user", ",", "msg", ",", "**", "kwargs", ")", ":", "Notification", ".", "objects", ".", "create", "(", "recipient", "=", "user", ",", "subject", "=", "msg", ",", "**", "kwargs", ")" ]
send a simple notification to a user .
train
false
33,190
def find_subcircuit(circuit, subcircuit, start=0, end=0): if isinstance(circuit, Mul): circuit = circuit.args if isinstance(subcircuit, Mul): subcircuit = subcircuit.args if ((len(subcircuit) == 0) or (len(subcircuit) > len(circuit))): return (-1) if (end < 1): end = len(circuit) pos = start index = 0 table = kmp_table(subcircuit) while ((pos + index) < end): if (subcircuit[index] == circuit[(pos + index)]): index = (index + 1) else: pos = ((pos + index) - table[index]) index = (table[index] if (table[index] > (-1)) else 0) if (index == len(subcircuit)): return pos return (-1)
[ "def", "find_subcircuit", "(", "circuit", ",", "subcircuit", ",", "start", "=", "0", ",", "end", "=", "0", ")", ":", "if", "isinstance", "(", "circuit", ",", "Mul", ")", ":", "circuit", "=", "circuit", ".", "args", "if", "isinstance", "(", "subcircuit"...
finds the subcircuit in circuit .
train
false
33,192
def unregister_security_check(name): _populate_security_checks() try: del _security_checks[name] except KeyError: logging.error((u'Failed to unregister unknown security check "%s"' % name)) raise KeyError((u'"%s" is not a registered security check' % name))
[ "def", "unregister_security_check", "(", "name", ")", ":", "_populate_security_checks", "(", ")", "try", ":", "del", "_security_checks", "[", "name", "]", "except", "KeyError", ":", "logging", ".", "error", "(", "(", "u'Failed to unregister unknown security check \"%s...
unregister a previously registered security check .
train
false
33,194
def fetch_page(base_url, page, session): return session.get((base_url + '?page={}'.format(page))).json()
[ "def", "fetch_page", "(", "base_url", ",", "page", ",", "session", ")", ":", "return", "session", ".", "get", "(", "(", "base_url", "+", "'?page={}'", ".", "format", "(", "page", ")", ")", ")", ".", "json", "(", ")" ]
fetch a particular page number for a github api resource .
train
false
33,196
@ffi.callback('int(void* handle, int revents)') def _python_callback(handle, revents): try: the_watcher = ffi.from_handle(handle) args = the_watcher.args if (args is None): args = _NOARGS if ((len(args) > 0) and (args[0] == GEVENT_CORE_EVENTS)): args = ((revents,) + args[1:]) the_watcher.callback(*args) except: the_watcher._exc_info = sys.exc_info() the_watcher.loop._keepaliveset.add(the_watcher) return (-1) else: if (the_watcher in the_watcher.loop._keepaliveset): return 0 return 1
[ "@", "ffi", ".", "callback", "(", "'int(void* handle, int revents)'", ")", "def", "_python_callback", "(", "handle", ",", "revents", ")", ":", "try", ":", "the_watcher", "=", "ffi", ".", "from_handle", "(", "handle", ")", "args", "=", "the_watcher", ".", "ar...
returns an integer having one of three values: - -1 an exception occurred during the callback and you must call :func:_python_handle_error to deal with it .
train
false
33,198
def replace_jump_to_id_urls(text, course_id, jump_to_id_base_url): def replace_jump_to_id_url(match): quote = match.group('quote') rest = match.group('rest') return ''.join([quote, (jump_to_id_base_url + rest), quote]) return re.sub(_url_replace_regex('/jump_to_id/'), replace_jump_to_id_url, text)
[ "def", "replace_jump_to_id_urls", "(", "text", ",", "course_id", ",", "jump_to_id_base_url", ")", ":", "def", "replace_jump_to_id_url", "(", "match", ")", ":", "quote", "=", "match", ".", "group", "(", "'quote'", ")", "rest", "=", "match", ".", "group", "(",...
this will replace a link between courseware in the format /jump_to_id/<id> with a url for a page that will correctly redirect this is similar to replace_course_urls .
train
false
33,199
def write_latest_release_file(): filename = '_latest_release.rst' template = ":orphan:\n\n.. Some common reStructuredText substitutions.\n\n **This file is autogenerated!** So don't edit it by hand.\n\n You can include this file at the top of your ``*.rst`` file with a line\n like::\n\n .. include:: {filename}\n\n Then use the substitutions in this file, e.g.::\n\n |latest_release_version|\n\n.. |latest_release_tag| replace:: {latest_tag}\n.. |latest_release_version| replace:: {latest_version}\n.. |latest_package_name_precise| replace:: {package_name_precise}\n.. |latest_package_name_trusty| replace:: {package_name_trusty}\n\n" open(filename, 'w').write(template.format(filename=filename, latest_tag=latest_release_tag(), latest_version=latest_release_version(), package_name_precise=latest_package_name('precise'), package_name_trusty=latest_package_name('trusty')))
[ "def", "write_latest_release_file", "(", ")", ":", "filename", "=", "'_latest_release.rst'", "template", "=", "\":orphan:\\n\\n.. Some common reStructuredText substitutions.\\n\\n **This file is autogenerated!** So don't edit it by hand.\\n\\n You can include this file at the top of your ``*...
write a file in the doc/ dir containing restructuredtext substitutions for the latest release tag name and version number .
train
false
33,200
def connectWS(factory, contextFactory=None, timeout=30, bindAddress=None): if hasattr(factory, 'reactor'): reactor = factory.reactor else: from twisted.internet import reactor if factory.isSecure: if (contextFactory is None): from twisted.internet import ssl contextFactory = ssl.ClientContextFactory() if (factory.proxy is not None): factory.contextFactory = contextFactory conn = reactor.connectTCP(factory.proxy[u'host'], factory.proxy[u'port'], factory, timeout, bindAddress) elif factory.isSecure: conn = reactor.connectSSL(factory.host, factory.port, factory, contextFactory, timeout, bindAddress) else: conn = reactor.connectTCP(factory.host, factory.port, factory, timeout, bindAddress) return conn
[ "def", "connectWS", "(", "factory", ",", "contextFactory", "=", "None", ",", "timeout", "=", "30", ",", "bindAddress", "=", "None", ")", ":", "if", "hasattr", "(", "factory", ",", "'reactor'", ")", ":", "reactor", "=", "factory", ".", "reactor", "else", ...
establish websocket connection to a server .
train
false
33,201
def clean_raw_line(raw_line, blacklist=DEFAULT_BLACKLIST): return re.sub('|'.join(blacklist), '', raw_line)
[ "def", "clean_raw_line", "(", "raw_line", ",", "blacklist", "=", "DEFAULT_BLACKLIST", ")", ":", "return", "re", ".", "sub", "(", "'|'", ".", "join", "(", "blacklist", ")", ",", "''", ",", "raw_line", ")" ]
strip blacklisted characters from raw_line .
train
false
33,204
def dmp_div(f, g, u, K): if K.has_Field: return dmp_ff_div(f, g, u, K) else: return dmp_rr_div(f, g, u, K)
[ "def", "dmp_div", "(", "f", ",", "g", ",", "u", ",", "K", ")", ":", "if", "K", ".", "has_Field", ":", "return", "dmp_ff_div", "(", "f", ",", "g", ",", "u", ",", "K", ")", "else", ":", "return", "dmp_rr_div", "(", "f", ",", "g", ",", "u", ",...
polynomial division with remainder in k[x] .
train
false
33,205
def dynamic_choice_scriptler_param(registry, xml_parent, data): dynamic_scriptler_param_common(registry, xml_parent, data, 'ScriptlerChoiceParameterDefinition')
[ "def", "dynamic_choice_scriptler_param", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "dynamic_scriptler_param_common", "(", "registry", ",", "xml_parent", ",", "data", ",", "'ScriptlerChoiceParameterDefinition'", ")" ]
yaml: dynamic-choice-scriptler dynamic choice parameter requires the jenkins :jenkins-wiki:jenkins dynamic parameter plug-in <dynamic+parameter+plug-in> .
train
false
33,206
def _generate_cache_header_key(key_prefix, request): path = md5_constructor(iri_to_uri(request.path)) cache_key = ('views.decorators.cache.cache_header.%s.%s' % (key_prefix, path.hexdigest())) return _i18n_cache_key_suffix(request, cache_key)
[ "def", "_generate_cache_header_key", "(", "key_prefix", ",", "request", ")", ":", "path", "=", "md5_constructor", "(", "iri_to_uri", "(", "request", ".", "path", ")", ")", "cache_key", "=", "(", "'views.decorators.cache.cache_header.%s.%s'", "%", "(", "key_prefix", ...
returns a cache key for the header cache .
train
false
33,207
def _netbios_getnode(): import win32wnet, netbios ncb = netbios.NCB() ncb.Command = netbios.NCBENUM ncb.Buffer = adapters = netbios.LANA_ENUM() adapters._pack() if (win32wnet.Netbios(ncb) != 0): return adapters._unpack() for i in range(adapters.length): ncb.Reset() ncb.Command = netbios.NCBRESET ncb.Lana_num = ord(adapters.lana[i]) if (win32wnet.Netbios(ncb) != 0): continue ncb.Reset() ncb.Command = netbios.NCBASTAT ncb.Lana_num = ord(adapters.lana[i]) ncb.Callname = '*'.ljust(16) ncb.Buffer = status = netbios.ADAPTER_STATUS() if (win32wnet.Netbios(ncb) != 0): continue status._unpack() bytes = status.adapter_address return ((((((bytes[0] << 40) + (bytes[1] << 32)) + (bytes[2] << 24)) + (bytes[3] << 16)) + (bytes[4] << 8)) + bytes[5])
[ "def", "_netbios_getnode", "(", ")", ":", "import", "win32wnet", ",", "netbios", "ncb", "=", "netbios", ".", "NCB", "(", ")", "ncb", ".", "Command", "=", "netbios", ".", "NCBENUM", "ncb", ".", "Buffer", "=", "adapters", "=", "netbios", ".", "LANA_ENUM", ...
get the hardware address on windows using netbios calls .
train
true
33,209
def fixkey(ip): print 'My idea of what the remote hostkey should be is wrong.' while True: ret = raw_input('Would you like me to fix this? (y/n): ') if (ret.lower() == 'y'): rep = os.popen(('ssh-keyscan %s 2> /dev/null' % ip)).read() return (rep or False) elif (ret.lower() == 'n'): return False else: print 'Please choose either y or n.' continue
[ "def", "fixkey", "(", "ip", ")", ":", "print", "'My idea of what the remote hostkey should be is wrong.'", "while", "True", ":", "ret", "=", "raw_input", "(", "'Would you like me to fix this? (y/n): '", ")", "if", "(", "ret", ".", "lower", "(", ")", "==", "'y'", "...
return a host key or false .
train
false
33,210
def inputhook(context): NSApp = _NSApp() _stop_on_read(context.fileno()) msg(NSApp, n('run')) if (not _triggered.is_set()): CoreFoundation.CFRunLoopRun()
[ "def", "inputhook", "(", "context", ")", ":", "NSApp", "=", "_NSApp", "(", ")", "_stop_on_read", "(", "context", ".", "fileno", "(", ")", ")", "msg", "(", "NSApp", ",", "n", "(", "'run'", ")", ")", "if", "(", "not", "_triggered", ".", "is_set", "("...
run the pyglet event loop by processing pending events only .
train
false
33,211
def openshift_svc_verify(registry, xml_parent, data): osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.OpenShiftServiceVerifier') mapping = [('api-url', 'apiURL', 'https://openshift.default.svc.cluster.local'), ('svc-name', 'svcName', 'frontend'), ('namespace', 'namespace', 'test'), ('auth-token', 'authToken', ''), ('verbose', 'verbose', False)] convert_mapping_to_xml(osb, data, mapping, fail_required=True)
[ "def", "openshift_svc_verify", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "osb", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'com.openshift.jenkins.plugins.pipeline.OpenShiftServiceVerifier'", ")", "mapping", "=", "[", "(", "'api-url'", "...
yaml: openshift-svc-verify verify a service is up in openshift for the job .
train
false
33,212
def _exception_traceback(exc_info): excout = StringIO() (exc_type, exc_val, exc_tb) = exc_info traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) return excout.getvalue()
[ "def", "_exception_traceback", "(", "exc_info", ")", ":", "excout", "=", "StringIO", "(", ")", "(", "exc_type", ",", "exc_val", ",", "exc_tb", ")", "=", "exc_info", "traceback", ".", "print_exception", "(", "exc_type", ",", "exc_val", ",", "exc_tb", ",", "...
return a string containing a traceback message for the given exc_info tuple (as returned by sys .
train
true
33,213
def fmt_diff(value, diff, idx): if (diff is None): return value diffvalue = escape(force_text(diff[idx])) return html_diff(diffvalue, value)
[ "def", "fmt_diff", "(", "value", ",", "diff", ",", "idx", ")", ":", "if", "(", "diff", "is", "None", ")", ":", "return", "value", "diffvalue", "=", "escape", "(", "force_text", "(", "diff", "[", "idx", "]", ")", ")", "return", "html_diff", "(", "di...
format diff if there is any .
train
false
33,216
@constructor def largest(*args): if (len(args) == 2): (a, b) = args return switch((a > b), a, b) else: return max(stack(args), axis=0)
[ "@", "constructor", "def", "largest", "(", "*", "args", ")", ":", "if", "(", "len", "(", "args", ")", "==", "2", ")", ":", "(", "a", ",", "b", ")", "=", "args", "return", "switch", "(", "(", "a", ">", "b", ")", ",", "a", ",", "b", ")", "e...
create a proxy for an instance which makes it sort larger than anything it is compared to .
train
false
33,217
def init_func_generator(cls, spec): if (not spec): def __init__(self): pass return __init__ (varnames, defaults) = zip(*spec) args = ', '.join(map('{0[0]}={0[1]!r}'.format, spec)) init = 'def __init__(self, {0}):\n'.format(args) init += '\n'.join(map(' self.{0} = {0}'.format, varnames)) name = '<generated {0}.__init__>'.format(cls.__name__) code = compile(init, name, 'exec') func = next((c for c in code.co_consts if isinstance(c, types.CodeType))) linecache.cache[name] = (len(init), None, init.splitlines(True), name) return types.FunctionType(func, {}, argdefs=defaults)
[ "def", "init_func_generator", "(", "cls", ",", "spec", ")", ":", "if", "(", "not", "spec", ")", ":", "def", "__init__", "(", "self", ")", ":", "pass", "return", "__init__", "(", "varnames", ",", "defaults", ")", "=", "zip", "(", "*", "spec", ")", "...
generate __init__ function based on tpayload .
train
false
33,218
@validator def iban(value): return (pattern.match(value) and modcheck(value))
[ "@", "validator", "def", "iban", "(", "value", ")", ":", "return", "(", "pattern", ".", "match", "(", "value", ")", "and", "modcheck", "(", "value", ")", ")" ]
return whether or not given value is a valid iban code .
train
false
33,219
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
33,220
def _IsSudsIterable(obj): return (obj and (not isinstance(obj, basestring)) and hasattr(obj, '__iter__'))
[ "def", "_IsSudsIterable", "(", "obj", ")", ":", "return", "(", "obj", "and", "(", "not", "isinstance", "(", "obj", ",", "basestring", ")", ")", "and", "hasattr", "(", "obj", ",", "'__iter__'", ")", ")" ]
a short helper method to determine if a field is iterable for suds .
train
false
33,221
def cyclic_find(subseq, alphabet=string.ascii_lowercase, n=None): if isinstance(subseq, (int, long)): width = ('all' if (n is None) else (n * 8)) subseq = packing.pack(subseq, width, 'little', False) if ((n is None) and (len(subseq) != 4)): log.warn_once(((('cyclic_find() expects 4-byte subsequences by default, you gave %r\n' % subseq) + ('Unless you specified cyclic(..., n=%i), you probably just want the first 4 bytes.\n' % len(subseq))) + ('Truncating the data at 4 bytes. Specify cyclic_find(..., n=%i) to override this.' % len(subseq)))) subseq = subseq[:4] if any(((c not in alphabet) for c in subseq)): return (-1) n = (n or len(subseq)) return _gen_find(subseq, de_bruijn(alphabet, n))
[ "def", "cyclic_find", "(", "subseq", ",", "alphabet", "=", "string", ".", "ascii_lowercase", ",", "n", "=", "None", ")", ":", "if", "isinstance", "(", "subseq", ",", "(", "int", ",", "long", ")", ")", ":", "width", "=", "(", "'all'", "if", "(", "n"...
cyclic_find -> int calculates the position of a substring into a de bruijn sequence .
train
false
33,222
def table_dict_save(table_dict, ModelClass, context): model = context['model'] session = context['session'] table = class_mapper(ModelClass).mapped_table obj = None unique_constraints = get_unique_constraints(table, context) id = table_dict.get('id') if id: obj = session.query(ModelClass).get(id) if (not obj): unique_constraints = get_unique_constraints(table, context) for constraint in unique_constraints: params = dict(((key, table_dict.get(key)) for key in constraint)) obj = session.query(ModelClass).filter_by(**params).first() if obj: break if (not obj): obj = ModelClass() for (key, value) in table_dict.iteritems(): if isinstance(value, list): continue setattr(obj, key, value) session.add(obj) return obj
[ "def", "table_dict_save", "(", "table_dict", ",", "ModelClass", ",", "context", ")", ":", "model", "=", "context", "[", "'model'", "]", "session", "=", "context", "[", "'session'", "]", "table", "=", "class_mapper", "(", "ModelClass", ")", ".", "mapped_table...
given a dict and a model class .
train
false
33,224
def gca(**kwargs): return gcf().gca(**kwargs)
[ "def", "gca", "(", "**", "kwargs", ")", ":", "return", "gcf", "(", ")", ".", "gca", "(", "**", "kwargs", ")" ]
return the current axis instance .
train
false
33,225
def whereis(program): for path in os.environ.get('PATH', '').split(':'): if (os.path.exists(os.path.join(path, program)) and (not os.path.isdir(os.path.join(path, program)))): return os.path.join(path, program) return None
[ "def", "whereis", "(", "program", ")", ":", "for", "path", "in", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", ".", "split", "(", "':'", ")", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "j...
search path for executable .
train
false
33,226
def write_lastlines_file(lastlines_dirpath, path, data): underscored = path.replace('/', '_') dest_path = os.path.join(lastlines_dirpath, underscored) open(dest_path, 'w').write(data) return dest_path
[ "def", "write_lastlines_file", "(", "lastlines_dirpath", ",", "path", ",", "data", ")", ":", "underscored", "=", "path", ".", "replace", "(", "'/'", ",", "'_'", ")", "dest_path", "=", "os", ".", "path", ".", "join", "(", "lastlines_dirpath", ",", "undersco...
write data to lastlines file for path .
train
false