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
30,145
def get_cluster_ref_by_name(session, cluster_name): all_clusters = get_all_cluster_mors(session) for cluster in all_clusters: if (hasattr(cluster, 'propSet') and (cluster.propSet[0].val == cluster_name)): return cluster.obj
[ "def", "get_cluster_ref_by_name", "(", "session", ",", "cluster_name", ")", ":", "all_clusters", "=", "get_all_cluster_mors", "(", "session", ")", "for", "cluster", "in", "all_clusters", ":", "if", "(", "hasattr", "(", "cluster", ",", "'propSet'", ")", "and", ...
get reference to the vcenter cluster with the specified name .
train
false
30,146
def _get_adjacency_lists(network): ins = defaultdict(list) outs = defaultdict(list) lookup = {repr(layer): index for (index, layer) in enumerate(network)} for current_layer in network: if hasattr(current_layer, 'input_layers'): layer_ins = current_layer.input_layers elif hasattr(current_layer, 'input_layer'): layer_ins = [current_layer.input_layer] else: layer_ins = [] ins[lookup[repr(current_layer)]].extend([lookup[repr(l)] for l in layer_ins]) for l in layer_ins: outs[lookup[repr(l)]].append(lookup[repr(current_layer)]) return (ins, outs)
[ "def", "_get_adjacency_lists", "(", "network", ")", ":", "ins", "=", "defaultdict", "(", "list", ")", "outs", "=", "defaultdict", "(", "list", ")", "lookup", "=", "{", "repr", "(", "layer", ")", ":", "index", "for", "(", "index", ",", "layer", ")", "...
returns adjacency lists for each layer in network .
train
false
30,147
def vcard_from_string(vcard_string): try: vcard = vobject.readOne(vcard_string) except vobject.base.ParseError as error: raise Exception(error) return vcard_from_vobject(vcard)
[ "def", "vcard_from_string", "(", "vcard_string", ")", ":", "try", ":", "vcard", "=", "vobject", ".", "readOne", "(", "vcard_string", ")", "except", "vobject", ".", "base", ".", "ParseError", "as", "error", ":", "raise", "Exception", "(", "error", ")", "ret...
vcard_string: str() or unicode() returns vcard() .
train
false
30,149
def clone_vm_spec(client_factory, location, power_on=False, snapshot=None, template=False, config=None): clone_spec = client_factory.create('ns0:VirtualMachineCloneSpec') clone_spec.location = location clone_spec.powerOn = power_on if snapshot: clone_spec.snapshot = snapshot if (config is not None): clone_spec.config = config clone_spec.template = template return clone_spec
[ "def", "clone_vm_spec", "(", "client_factory", ",", "location", ",", "power_on", "=", "False", ",", "snapshot", "=", "None", ",", "template", "=", "False", ",", "config", "=", "None", ")", ":", "clone_spec", "=", "client_factory", ".", "create", "(", "'ns0...
builds the vm clone spec .
train
false
30,150
def _dump_event(event): dump = {} dump['summary'] = event.title dump['description'] = event.description dump['location'] = event.location dump['transparency'] = ('opaque' if event.busy else 'transparent') if event.all_day: dump['start'] = {'date': event.start.strftime('%Y-%m-%d')} dump['end'] = {'date': event.end.strftime('%Y-%m-%d')} else: dump['start'] = {'dateTime': event.start.isoformat('T'), 'timeZone': 'UTC'} dump['end'] = {'dateTime': event.end.isoformat('T'), 'timeZone': 'UTC'} if event.participants: dump['attendees'] = [] inverse_status_map = {value: key for (key, value) in STATUS_MAP.items()} for participant in event.participants: attendee = {} if ('name' in participant): attendee['displayName'] = participant['name'] if ('status' in participant): attendee['responseStatus'] = inverse_status_map[participant['status']] if ('email' in participant): attendee['email'] = participant['email'] if ('guests' in participant): attendee['additionalGuests'] = participant['guests'] if attendee: dump['attendees'].append(attendee) return dump
[ "def", "_dump_event", "(", "event", ")", ":", "dump", "=", "{", "}", "dump", "[", "'summary'", "]", "=", "event", ".", "title", "dump", "[", "'description'", "]", "=", "event", ".", "description", "dump", "[", "'location'", "]", "=", "event", ".", "l...
convert an event db object to the google api json format .
train
false
30,151
def wait_for_write(socks, timeout=None): return _wait_for_io_events(socks, EVENT_WRITE, timeout)
[ "def", "wait_for_write", "(", "socks", ",", "timeout", "=", "None", ")", ":", "return", "_wait_for_io_events", "(", "socks", ",", "EVENT_WRITE", ",", "timeout", ")" ]
waits for writing to be available from a list of sockets or optionally a single socket if passed in .
train
false
30,152
def a2b_hex(s): return binascii.a2b_hex(strip_whitespace(s))
[ "def", "a2b_hex", "(", "s", ")", ":", "return", "binascii", ".", "a2b_hex", "(", "strip_whitespace", "(", "s", ")", ")" ]
convert hexadecimal to binary .
train
false
30,154
def get_timezone_location(dt_or_tzinfo): return get_i18n().get_timezone_location(dt_or_tzinfo)
[ "def", "get_timezone_location", "(", "dt_or_tzinfo", ")", ":", "return", "get_i18n", "(", ")", ".", "get_timezone_location", "(", "dt_or_tzinfo", ")" ]
see :meth:i18n .
train
false
30,156
def clip_spectrum(s, k, discard=0.001): rel_spectrum = np.abs((1.0 - np.cumsum((s / np.sum(s))))) small = (1 + len(np.where((rel_spectrum > min(discard, (1.0 / k))))[0])) k = min(k, small) logger.info('keeping %i factors (discarding %.3f%% of energy spectrum)', k, (100 * rel_spectrum[(k - 1)])) return k
[ "def", "clip_spectrum", "(", "s", ",", "k", ",", "discard", "=", "0.001", ")", ":", "rel_spectrum", "=", "np", ".", "abs", "(", "(", "1.0", "-", "np", ".", "cumsum", "(", "(", "s", "/", "np", ".", "sum", "(", "s", ")", ")", ")", ")", ")", "...
given eigenvalues s .
train
false
30,158
def find_sr_from_vdi(session, vdi_ref): try: sr_ref = session.call_xenapi('VDI.get_SR', vdi_ref) except session.XenAPI.Failure: LOG.exception(_LE('Unable to find SR from VDI')) raise exception.StorageError(reason=(_('Unable to find SR from VDI %s') % vdi_ref)) return sr_ref
[ "def", "find_sr_from_vdi", "(", "session", ",", "vdi_ref", ")", ":", "try", ":", "sr_ref", "=", "session", ".", "call_xenapi", "(", "'VDI.get_SR'", ",", "vdi_ref", ")", "except", "session", ".", "XenAPI", ".", "Failure", ":", "LOG", ".", "exception", "(", ...
find the sr reference from the vdi reference .
train
false
30,159
def test_vertical_mask_line(): (_, hgrad) = np.mgrid[:1:11j, :1:11j] hgrad[:, 5] = 1 mask = np.ones_like(hgrad) mask[:, 5] = 0 expected = np.zeros_like(hgrad) expected[1:(-1), 1:(-1)] = 0.2 expected[1:(-1), 4:7] = 0 for grad_func in (filters.prewitt_v, filters.sobel_v, filters.scharr_v): result = grad_func(hgrad, mask) (yield (assert_close, result, expected))
[ "def", "test_vertical_mask_line", "(", ")", ":", "(", "_", ",", "hgrad", ")", "=", "np", ".", "mgrid", "[", ":", "1", ":", "11j", ",", ":", "1", ":", "11j", "]", "hgrad", "[", ":", ",", "5", "]", "=", "1", "mask", "=", "np", ".", "ones_like",...
vertical edge filters mask pixels surrounding input mask .
train
false
30,161
def formatRecords(records, heading): (answers, authority, additional) = records lines = [('# ' + heading)] for a in answers: line = [a.name, dns.QUERY_CLASSES.get(a.cls, ('UNKNOWN (%d)' % (a.cls,))), a.payload] lines.append(' '.join((str(word) for word in line))) return '\n'.join((line for line in lines))
[ "def", "formatRecords", "(", "records", ",", "heading", ")", ":", "(", "answers", ",", "authority", ",", "additional", ")", "=", "records", "lines", "=", "[", "(", "'# '", "+", "heading", ")", "]", "for", "a", "in", "answers", ":", "line", "=", "[", ...
extract only the answer records and return them as a neatly formatted string beneath the given heading .
train
false
30,162
def get_total_open_threads(feedback_thread_analytics): return sum((feedback.num_open_threads for feedback in feedback_thread_analytics))
[ "def", "get_total_open_threads", "(", "feedback_thread_analytics", ")", ":", "return", "sum", "(", "(", "feedback", ".", "num_open_threads", "for", "feedback", "in", "feedback_thread_analytics", ")", ")" ]
gets the count of all open threads for the given feedbackthreadanalytics domain object .
train
false
30,163
def _can_update(subnet, module, cloud): network_name = module.params['network_name'] cidr = module.params['cidr'] ip_version = int(module.params['ip_version']) ipv6_ra_mode = module.params['ipv6_ra_mode'] ipv6_a_mode = module.params['ipv6_address_mode'] if network_name: network = cloud.get_network(network_name) if network: netid = network['id'] else: module.fail_json(msg=('No network found for %s' % network_name)) if (netid != subnet['network_id']): module.fail_json(msg='Cannot update network_name in existing subnet') if (ip_version and (subnet['ip_version'] != ip_version)): module.fail_json(msg='Cannot update ip_version in existing subnet') if (ipv6_ra_mode and (subnet.get('ipv6_ra_mode', None) != ipv6_ra_mode)): module.fail_json(msg='Cannot update ipv6_ra_mode in existing subnet') if (ipv6_a_mode and (subnet.get('ipv6_address_mode', None) != ipv6_a_mode)): module.fail_json(msg='Cannot update ipv6_address_mode in existing subnet')
[ "def", "_can_update", "(", "subnet", ",", "module", ",", "cloud", ")", ":", "network_name", "=", "module", ".", "params", "[", "'network_name'", "]", "cidr", "=", "module", ".", "params", "[", "'cidr'", "]", "ip_version", "=", "int", "(", "module", ".", ...
check for differences in non-updatable values .
train
false
30,164
def routingAreaUpdateRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, DrxParameter_presence=0, TmsiStatus_presence=0): a = TpPd(pd=3) b = MessageType(mesType=8) c = UpdateTypeAndCiphKeySeqNr() e = RoutingAreaIdentification() f = MsNetworkCapability() packet = ((((a / b) / c) / e) / f) if (PTmsiSignature_presence is 1): g = PTmsiSignature(ieiPTS=25) packet = (packet / g) if (GprsTimer_presence is 1): h = GprsTimer(ieiGT=23) packet = (packet / h) if (DrxParameter_presence is 1): i = DrxParameter(ieiDP=39) packet = (packet / i) if (TmsiStatus_presence is 1): j = TmsiStatus(ieiTS=9) packet = (packet / j) return packet
[ "def", "routingAreaUpdateRequest", "(", "PTmsiSignature_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "DrxParameter_presence", "=", "0", ",", "TmsiStatus_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "3", ")", "b", "=", ...
routing area update request section 9 .
train
true
30,165
def _CheckIndexName(index_name): _ValidateString(index_name, 'index name', MAXIMUM_INDEX_NAME_LENGTH) return _ValidateVisiblePrintableAsciiNotReserved(index_name, 'index_name')
[ "def", "_CheckIndexName", "(", "index_name", ")", ":", "_ValidateString", "(", "index_name", ",", "'index name'", ",", "MAXIMUM_INDEX_NAME_LENGTH", ")", "return", "_ValidateVisiblePrintableAsciiNotReserved", "(", "index_name", ",", "'index_name'", ")" ]
checks index_name is a string which is not too long .
train
false
30,166
def test_unicode_script(): s = unicode('import datetime; datetime.timedelta') completions = Script(s).completions() assert len(completions) assert (type(completions[0].description) is unicode) s = u("author='\xc3\xb6\xc3\xa4'; author") completions = Script(s).completions() x = completions[0].description assert (type(x) is unicode) s = u("#-*- coding: iso-8859-1 -*-\nauthor='\xc3\xb6\xc3\xa4'; author") s = s.encode('latin-1') completions = Script(s).completions() assert (type(completions[0].description) is unicode)
[ "def", "test_unicode_script", "(", ")", ":", "s", "=", "unicode", "(", "'import datetime; datetime.timedelta'", ")", "completions", "=", "Script", "(", "s", ")", ".", "completions", "(", ")", "assert", "len", "(", "completions", ")", "assert", "(", "type", "...
normally no unicode objects are being used .
train
false
30,167
def getEvaluatedExpressionValueBySplitLine(elementNode, words): evaluators = [] for (wordIndex, word) in enumerate(words): nextWord = '' nextWordIndex = (wordIndex + 1) if (nextWordIndex < len(words)): nextWord = words[nextWordIndex] evaluator = getEvaluator(elementNode, evaluators, nextWord, word) if (evaluator != None): evaluators.append(evaluator) while getBracketsExist(evaluators): pass evaluatedExpressionValueEvaluators = getEvaluatedExpressionValueEvaluators(evaluators) if (len(evaluatedExpressionValueEvaluators) > 0): return evaluatedExpressionValueEvaluators[0].value return None
[ "def", "getEvaluatedExpressionValueBySplitLine", "(", "elementNode", ",", "words", ")", ":", "evaluators", "=", "[", "]", "for", "(", "wordIndex", ",", "word", ")", "in", "enumerate", "(", "words", ")", ":", "nextWord", "=", "''", "nextWordIndex", "=", "(", ...
evaluate the expression value .
train
false
30,168
def add_css_class(css_classes, css_class, prepend=False): classes_list = split_css_classes(css_classes) classes_to_add = [c for c in split_css_classes(css_class) if (c not in classes_list)] if prepend: classes_list = (classes_to_add + classes_list) else: classes_list += classes_to_add return u' '.join(classes_list)
[ "def", "add_css_class", "(", "css_classes", ",", "css_class", ",", "prepend", "=", "False", ")", ":", "classes_list", "=", "split_css_classes", "(", "css_classes", ")", "classes_to_add", "=", "[", "c", "for", "c", "in", "split_css_classes", "(", "css_class", "...
add a css class to a string of css classes .
train
true
30,172
def visit_inheritance_diagram(inner_func): def visitor(self, node): try: content = inner_func(self, node) except DotException as e: warning = self.document.reporter.warning(str(e), line=node.line) warning.parent = node node.children = [warning] else: source = self.document.attributes['source'] self.body.append(content) node.children = [] return visitor
[ "def", "visit_inheritance_diagram", "(", "inner_func", ")", ":", "def", "visitor", "(", "self", ",", "node", ")", ":", "try", ":", "content", "=", "inner_func", "(", "self", ",", "node", ")", "except", "DotException", "as", "e", ":", "warning", "=", "sel...
this is just a wrapper around html/latex_output_graph to make it easier to handle errors and insert warnings .
train
true
30,173
def readXmlFile(xmlFile): checkFile(xmlFile) retVal = minidom.parse(xmlFile).documentElement return retVal
[ "def", "readXmlFile", "(", "xmlFile", ")", ":", "checkFile", "(", "xmlFile", ")", "retVal", "=", "minidom", ".", "parse", "(", "xmlFile", ")", ".", "documentElement", "return", "retVal" ]
reads xml file content and returns its dom representation .
train
false
30,174
def test_ast_bad_cut(): cant_compile(u'(cut)') cant_compile(u'(cut 1 2 3 4 5)')
[ "def", "test_ast_bad_cut", "(", ")", ":", "cant_compile", "(", "u'(cut)'", ")", "cant_compile", "(", "u'(cut 1 2 3 4 5)'", ")" ]
make sure ast cant compile invalid cut .
train
false
30,176
def tuple_factory(colnames, rows): return rows
[ "def", "tuple_factory", "(", "colnames", ",", "rows", ")", ":", "return", "rows" ]
returns each row as a tuple example:: .
train
false
30,177
def osd_activate(**kwargs): return ceph_cfg.osd_activate(**kwargs)
[ "def", "osd_activate", "(", "**", "kwargs", ")", ":", "return", "ceph_cfg", ".", "osd_activate", "(", "**", "kwargs", ")" ]
activate an osd cli example: .
train
false
30,178
@loader_option() def raiseload(loadopt, attr, sql_only=False): return loadopt.set_relationship_strategy(attr, {'lazy': ('raise_on_sql' if sql_only else 'raise')})
[ "@", "loader_option", "(", ")", "def", "raiseload", "(", "loadopt", ",", "attr", ",", "sql_only", "=", "False", ")", ":", "return", "loadopt", ".", "set_relationship_strategy", "(", "attr", ",", "{", "'lazy'", ":", "(", "'raise_on_sql'", "if", "sql_only", ...
indicate that the given relationship attribute should disallow lazy loads .
train
false
30,180
def monkeypatch(klass, methodname=None): def decorator(func): try: name = (methodname or func.__name__) except AttributeError: raise AttributeError(('%s has no __name__ attribute: you should provide an explicit `methodname`' % func)) setattr(klass, name, func) return func return decorator
[ "def", "monkeypatch", "(", "klass", ",", "methodname", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "try", ":", "name", "=", "(", "methodname", "or", "func", ".", "__name__", ")", "except", "AttributeError", ":", "raise", "AttributeE...
the returned monkeypatch fixture provides these helper methods to modify objects .
train
false
30,181
def release_lock(lock_file): os.remove(lock_file)
[ "def", "release_lock", "(", "lock_file", ")", ":", "os", ".", "remove", "(", "lock_file", ")" ]
release a lock represented by a file on the file system .
train
false
30,182
def logo(): return load('logo.png')
[ "def", "logo", "(", ")", ":", "return", "load", "(", "'logo.png'", ")" ]
celery logo image .
train
false
30,183
@task(base=BaseInstructorTask) def course_survey_report_csv(entry_id, xmodule_instance_args): action_name = ugettext_noop('generated') task_fn = partial(upload_course_survey_report, xmodule_instance_args) return run_main_task(entry_id, task_fn, action_name)
[ "@", "task", "(", "base", "=", "BaseInstructorTask", ")", "def", "course_survey_report_csv", "(", "entry_id", ",", "xmodule_instance_args", ")", ":", "action_name", "=", "ugettext_noop", "(", "'generated'", ")", "task_fn", "=", "partial", "(", "upload_course_survey_...
compute the survey report for a course and upload the generated report to an s3 bucket for download .
train
false
30,184
def activatePdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0): a = TpPd(pd=8) b = MessageType(mesType=65) c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = (((((a / b) / c) / d) / e) / f) if (AccessPointName_presence is 1): g = AccessPointName(ieiAPN=40) packet = (packet / g) if (ProtocolConfigurationOptions_presence is 1): h = ProtocolConfigurationOptions(ieiPCO=39) packet = (packet / h) return packet
[ "def", "activatePdpContextRequest", "(", "AccessPointName_presence", "=", "0", ",", "ProtocolConfigurationOptions_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "8", ")", "b", "=", "MessageType", "(", "mesType", "=", "65", ")", "c", "=", ...
activate pdp context request section 9 .
train
true
30,185
def plot_evoked_image(evoked, picks=None, exclude='bads', unit=True, show=True, clim=None, xlim='tight', proj=False, units=None, scalings=None, titles=None, axes=None, cmap='RdBu_r'): return _plot_evoked(evoked=evoked, picks=picks, exclude=exclude, unit=unit, show=show, ylim=clim, proj=proj, xlim=xlim, hline=None, units=units, scalings=scalings, titles=titles, axes=axes, plot_type='image', cmap=cmap)
[ "def", "plot_evoked_image", "(", "evoked", ",", "picks", "=", "None", ",", "exclude", "=", "'bads'", ",", "unit", "=", "True", ",", "show", "=", "True", ",", "clim", "=", "None", ",", "xlim", "=", "'tight'", ",", "proj", "=", "False", ",", "units", ...
plot evoked data as images .
train
false
30,187
def last_modified_time(path): return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')
[ "def", "last_modified_time", "(", "path", ")", ":", "return", "pd", ".", "Timestamp", "(", "os", ".", "path", ".", "getmtime", "(", "path", ")", ",", "unit", "=", "'s'", ",", "tz", "=", "'UTC'", ")" ]
get the last modified time of path as a timestamp .
train
true
30,189
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
initialise module .
train
false
30,190
def token_freqs(doc): freq = defaultdict(int) for tok in tokens(doc): freq[tok] += 1 return freq
[ "def", "token_freqs", "(", "doc", ")", ":", "freq", "=", "defaultdict", "(", "int", ")", "for", "tok", "in", "tokens", "(", "doc", ")", ":", "freq", "[", "tok", "]", "+=", "1", "return", "freq" ]
extract a dict mapping tokens from doc to their frequencies .
train
false
30,191
def __init__(opts): if __virtual__(): os.environ.update(DPKG_ENV_VARS)
[ "def", "__init__", "(", "opts", ")", ":", "if", "__virtual__", "(", ")", ":", "os", ".", "environ", ".", "update", "(", "DPKG_ENV_VARS", ")" ]
for debian and derivative systems .
train
false
30,192
def getBoundedLatitude(latitude): return round(min(179.9, max(0.1, latitude)), 1)
[ "def", "getBoundedLatitude", "(", "latitude", ")", ":", "return", "round", "(", "min", "(", "179.9", ",", "max", "(", "0.1", ",", "latitude", ")", ")", ",", "1", ")" ]
get the bounded latitude .
train
false
30,193
@pytest.mark.django_db def test_format_instance(): ext = FileExtension.objects.create(name='foo') filetype = Format.objects.create(extension=ext, template_extension=ext) assert (str(filetype.template_extension) == str(ext)) assert (str(filetype) == ('%s (%s/%s)' % (filetype.title, ext, ext)))
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_format_instance", "(", ")", ":", "ext", "=", "FileExtension", ".", "objects", ".", "create", "(", "name", "=", "'foo'", ")", "filetype", "=", "Format", ".", "objects", ".", "create", "(", "extens...
tests the creation of a file extension .
train
false
30,194
def find_intersection(x, tr_bounds, lb, ub): lb_centered = (lb - x) ub_centered = (ub - x) lb_total = np.maximum(lb_centered, (- tr_bounds)) ub_total = np.minimum(ub_centered, tr_bounds) orig_l = np.equal(lb_total, lb_centered) orig_u = np.equal(ub_total, ub_centered) tr_l = np.equal(lb_total, (- tr_bounds)) tr_u = np.equal(ub_total, tr_bounds) return (lb_total, ub_total, orig_l, orig_u, tr_l, tr_u)
[ "def", "find_intersection", "(", "x", ",", "tr_bounds", ",", "lb", ",", "ub", ")", ":", "lb_centered", "=", "(", "lb", "-", "x", ")", "ub_centered", "=", "(", "ub", "-", "x", ")", "lb_total", "=", "np", ".", "maximum", "(", "lb_centered", ",", "(",...
find intersection of trust-region bounds and initial bounds .
train
false
30,195
def ignore_comments(lines_enum): for (line_number, line) in lines_enum: line = COMMENT_RE.sub('', line) line = line.strip() if line: (yield (line_number, line))
[ "def", "ignore_comments", "(", "lines_enum", ")", ":", "for", "(", "line_number", ",", "line", ")", "in", "lines_enum", ":", "line", "=", "COMMENT_RE", ".", "sub", "(", "''", ",", "line", ")", "line", "=", "line", ".", "strip", "(", ")", "if", "line"...
strips comments and filter empty lines .
train
true
30,198
def _CheckCursor(cursor): return _ValidateString(cursor, 'cursor', _MAXIMUM_CURSOR_LENGTH, empty_ok=True)
[ "def", "_CheckCursor", "(", "cursor", ")", ":", "return", "_ValidateString", "(", "cursor", ",", "'cursor'", ",", "_MAXIMUM_CURSOR_LENGTH", ",", "empty_ok", "=", "True", ")" ]
checks the cursor if specified is a string which is not too long .
train
false
30,199
@frappe.whitelist() def get_user_roles(arg=None): return frappe.get_roles(frappe.form_dict[u'uid'])
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "get_user_roles", "(", "arg", "=", "None", ")", ":", "return", "frappe", ".", "get_roles", "(", "frappe", ".", "form_dict", "[", "u'uid'", "]", ")" ]
get roles for a user .
train
false
30,202
def _parse_write_concern(options): concern = options.get('w') wtimeout = options.get('wtimeout') j = options.get('j', options.get('journal')) fsync = options.get('fsync') return WriteConcern(concern, wtimeout, j, fsync)
[ "def", "_parse_write_concern", "(", "options", ")", ":", "concern", "=", "options", ".", "get", "(", "'w'", ")", "wtimeout", "=", "options", ".", "get", "(", "'wtimeout'", ")", "j", "=", "options", ".", "get", "(", "'j'", ",", "options", ".", "get", ...
parse write concern options .
train
true
30,203
def _get_failure_view(): return get_callable(settings.CSRF_FAILURE_VIEW)
[ "def", "_get_failure_view", "(", ")", ":", "return", "get_callable", "(", "settings", ".", "CSRF_FAILURE_VIEW", ")" ]
returns the view to be used for csrf rejections .
train
false
30,206
def test_destination(destination, demo=False): if (demo and os.path.exists(destination)): LOGGER.warning(u'The directory {0} already exists, and a new demo site cannot be initialized in an existing directory.'.format(destination)) LOGGER.warning(u'Please remove the directory and try again, or use another directory.') LOGGER.info(u'Hint: If you want to initialize a git repository in this directory, run `git init` in the directory after creating a Nikola site.') return False else: return True
[ "def", "test_destination", "(", "destination", ",", "demo", "=", "False", ")", ":", "if", "(", "demo", "and", "os", ".", "path", ".", "exists", "(", "destination", ")", ")", ":", "LOGGER", ".", "warning", "(", "u'The directory {0} already exists, and a new dem...
check if the destination already exists .
train
false
30,208
@remote_data def test_db_from_registry(): from ...validator import conf db = vos_catalog.VOSDatabase.from_registry(conf.conesearch_master_list, encoding=u'binary', show_progress=False) assert (len(db) > 9000)
[ "@", "remote_data", "def", "test_db_from_registry", "(", ")", ":", "from", "...", "validator", "import", "conf", "db", "=", "vos_catalog", ".", "VOSDatabase", ".", "from_registry", "(", "conf", ".", "conesearch_master_list", ",", "encoding", "=", "u'binary'", ",...
test database created from vo registry .
train
false
30,211
def fileserver(opts, backends): return LazyLoader(_module_dirs(opts, 'fileserver'), opts, tag='fileserver', whitelist=backends, pack={'__utils__': utils(opts)})
[ "def", "fileserver", "(", "opts", ",", "backends", ")", ":", "return", "LazyLoader", "(", "_module_dirs", "(", "opts", ",", "'fileserver'", ")", ",", "opts", ",", "tag", "=", "'fileserver'", ",", "whitelist", "=", "backends", ",", "pack", "=", "{", "'__u...
returns the file server modules .
train
true
30,213
def zdt1(individual): g = (1.0 + ((9.0 * sum(individual[1:])) / (len(individual) - 1))) f1 = individual[0] f2 = (g * (1 - sqrt((f1 / g)))) return (f1, f2)
[ "def", "zdt1", "(", "individual", ")", ":", "g", "=", "(", "1.0", "+", "(", "(", "9.0", "*", "sum", "(", "individual", "[", "1", ":", "]", ")", ")", "/", "(", "len", "(", "individual", ")", "-", "1", ")", ")", ")", "f1", "=", "individual", ...
zdt1 multiobjective function .
train
false
30,214
def to_bag(df, index=False): from ...bag.core import Bag if (not isinstance(df, (DataFrame, Series))): raise TypeError('df must be either DataFrame or Series') name = ('to_bag-' + tokenize(df, index)) dsk = dict((((name, i), (_df_to_bag, block, index)) for (i, block) in enumerate(df._keys()))) dsk.update(df._optimize(df.dask, df._keys())) return Bag(dsk, name, df.npartitions)
[ "def", "to_bag", "(", "df", ",", "index", "=", "False", ")", ":", "from", "...", "bag", ".", "core", "import", "Bag", "if", "(", "not", "isinstance", "(", "df", ",", "(", "DataFrame", ",", "Series", ")", ")", ")", ":", "raise", "TypeError", "(", ...
create dask bag from a dask dataframe parameters index : bool .
train
false
30,215
def as_published(location): return location.replace(revision=MongoRevisionKey.published)
[ "def", "as_published", "(", "location", ")", ":", "return", "location", ".", "replace", "(", "revision", "=", "MongoRevisionKey", ".", "published", ")" ]
returns the location that is the published version for location .
train
false
30,216
def test_end_newlines(): def test(source, end_pos): module = ParserWithRecovery(load_grammar(), u(source)).module assert (module.get_code() == source) assert (module.end_pos == end_pos) test('a', (1, 1)) test('a\n', (2, 0)) test('a\nb', (2, 1)) test('a\n#comment\n', (3, 0)) test('a\n#comment', (2, 8)) test('a#comment', (1, 9)) test('def a():\n pass', (2, 5)) test('def a(', (1, 6))
[ "def", "test_end_newlines", "(", ")", ":", "def", "test", "(", "source", ",", "end_pos", ")", ":", "module", "=", "ParserWithRecovery", "(", "load_grammar", "(", ")", ",", "u", "(", "source", ")", ")", ".", "module", "assert", "(", "module", ".", "get_...
the python grammar explicitly needs a newline at the end .
train
false
30,217
def add_user_with_status_granted(caller, user): if _add_user(user, CourseCreator.GRANTED): update_course_creator_group(caller, user, True)
[ "def", "add_user_with_status_granted", "(", "caller", ",", "user", ")", ":", "if", "_add_user", "(", "user", ",", "CourseCreator", ".", "GRANTED", ")", ":", "update_course_creator_group", "(", "caller", ",", "user", ",", "True", ")" ]
adds a user to the course creator table with status granted .
train
false
30,218
@pytest.mark.cmd @pytest.mark.django_db def test_import_emptyfile(capfd, tmpdir): p = tmpdir.mkdir('sub').join('empty.po') p.write('') with pytest.raises(CommandError) as e: call_command('import', os.path.join(p.dirname, p.basename)) assert ('missing X-Pootle-Path header' in str(e))
[ "@", "pytest", ".", "mark", ".", "cmd", "@", "pytest", ".", "mark", ".", "django_db", "def", "test_import_emptyfile", "(", "capfd", ",", "tmpdir", ")", ":", "p", "=", "tmpdir", ".", "mkdir", "(", "'sub'", ")", ".", "join", "(", "'empty.po'", ")", "p"...
load an empty po file .
train
false
30,219
def get_repository_dependency_types(repository_dependencies): has_repository_dependencies = False for rd_tup in repository_dependencies: (tool_shed, name, owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td) = common_util.parse_repository_dependency_tuple(rd_tup) if (not util.asbool(only_if_compiling_contained_td)): has_repository_dependencies = True break has_repository_dependencies_only_if_compiling_contained_td = False for rd_tup in repository_dependencies: (tool_shed, name, owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td) = common_util.parse_repository_dependency_tuple(rd_tup) if util.asbool(only_if_compiling_contained_td): has_repository_dependencies_only_if_compiling_contained_td = True break return (has_repository_dependencies, has_repository_dependencies_only_if_compiling_contained_td)
[ "def", "get_repository_dependency_types", "(", "repository_dependencies", ")", ":", "has_repository_dependencies", "=", "False", "for", "rd_tup", "in", "repository_dependencies", ":", "(", "tool_shed", ",", "name", ",", "owner", ",", "changeset_revision", ",", "prior_in...
inspect the received list of repository_dependencies tuples and return boolean values for has_repository_dependencies and has_repository_dependencies_only_if_compiling_contained_td .
train
false
30,220
def webpyfunc(inp, fvars=None, autoreload=False): if (not fvars): fvars = upvars() if (not hasattr(inp, '__call__')): if autoreload: mod = __import__(fvars['__file__'].split(os.path.sep).pop().split('.')[0]) name = dictfind(fvars, inp) func = (lambda : handle(getattr(mod, name), mod)) else: func = (lambda : handle(inp, fvars)) else: func = inp return func
[ "def", "webpyfunc", "(", "inp", ",", "fvars", "=", "None", ",", "autoreload", "=", "False", ")", ":", "if", "(", "not", "fvars", ")", ":", "fvars", "=", "upvars", "(", ")", "if", "(", "not", "hasattr", "(", "inp", ",", "'__call__'", ")", ")", ":"...
if inp is a url mapping .
train
false
30,221
def CanonicalPathToLocalPath(path): path = path.replace('/\\', '\\') path = path.replace('/', '\\') m = re.match('\\\\([a-zA-Z]):(.*)$', path) if m: path = ('%s:\\%s' % (m.group(1), m.group(2).lstrip('\\'))) return path
[ "def", "CanonicalPathToLocalPath", "(", "path", ")", ":", "path", "=", "path", ".", "replace", "(", "'/\\\\'", ",", "'\\\\'", ")", "path", "=", "path", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", "m", "=", "re", ".", "match", "(", "'\\\\\\\\([a-zA-...
linux uses a normal path .
train
true
30,222
def byte2int(b): return (ord(b) if PY2 else b)
[ "def", "byte2int", "(", "b", ")", ":", "return", "(", "ord", "(", "b", ")", "if", "PY2", "else", "b", ")" ]
converts a byte to an integer .
train
false
30,224
def _flush_logs_buffer(): logservice.logs_buffer().flush()
[ "def", "_flush_logs_buffer", "(", ")", ":", "logservice", ".", "logs_buffer", "(", ")", ".", "flush", "(", ")" ]
empties all logs stored within the globally-held logs buffer .
train
false
30,225
def _get_graded_from_block(persisted_block, block): if persisted_block: return persisted_block.graded else: return _get_explicit_graded(block)
[ "def", "_get_graded_from_block", "(", "persisted_block", ",", "block", ")", ":", "if", "persisted_block", ":", "return", "persisted_block", ".", "graded", "else", ":", "return", "_get_explicit_graded", "(", "block", ")" ]
returns the graded value from the persisted_block if found .
train
false
30,226
@then('the tag expression selects elements with tags') def step_then_tag_expression_selects_elements_with_tags(context): assert context.tag_expression, 'REQUIRE: context.tag_expression' context.table.require_columns(['tags', 'selected?']) tag_expression = context.tag_expression expected = [] actual = [] for row in context.table.rows: element_tags = convert_model_element_tags(row['tags']) expected_element_selected = convert_yesno(row['selected?']) actual_element_selected = tag_expression.check(element_tags) expected.append((element_tags, expected_element_selected)) actual.append((element_tags, actual_element_selected)) assert_that(actual, equal_to(expected))
[ "@", "then", "(", "'the tag expression selects elements with tags'", ")", "def", "step_then_tag_expression_selects_elements_with_tags", "(", "context", ")", ":", "assert", "context", ".", "tag_expression", ",", "'REQUIRE: context.tag_expression'", "context", ".", "table", "."...
checks if a tag expression selects an element with the given tags .
train
false
30,227
@skipif((not has_qt)) def test_line_profile(): plugin = setup_line_profile(data.camera()) (line_image, scan_data) = plugin.output() for inp in [line_image.nonzero()[0].size, (line_image.sum() / line_image.max()), scan_data.size]: assert_equal(inp, 172) assert_equal(line_image.shape, (512, 512)) assert_allclose(scan_data.max(), 0.9176, rtol=0.001) assert_allclose(scan_data.mean(), 0.2812, rtol=0.001)
[ "@", "skipif", "(", "(", "not", "has_qt", ")", ")", "def", "test_line_profile", "(", ")", ":", "plugin", "=", "setup_line_profile", "(", "data", ".", "camera", "(", ")", ")", "(", "line_image", ",", "scan_data", ")", "=", "plugin", ".", "output", "(", ...
test a line profile using an ndim=2 image .
train
false
30,229
def select_vhost(domain, vhosts): if (not vhosts): return None while True: (code, tag) = _vhost_menu(domain, vhosts) if (code == display_util.HELP): _more_info_vhost(vhosts[tag]) elif (code == display_util.OK): return vhosts[tag] else: return None
[ "def", "select_vhost", "(", "domain", ",", "vhosts", ")", ":", "if", "(", "not", "vhosts", ")", ":", "return", "None", "while", "True", ":", "(", "code", ",", "tag", ")", "=", "_vhost_menu", "(", "domain", ",", "vhosts", ")", "if", "(", "code", "==...
select an appropriate apache vhost .
train
false
30,230
def test_register_filter(): assert_raises(ValueError, register_filter, object) class MyFilter(Filter, ): name = None def output(self, *a, **kw): pass assert_raises(ValueError, register_filter, MyFilter) MyFilter.name = 'foo' register_filter(MyFilter) class OverrideMyFilter(Filter, ): name = 'foo' def output(self, *a, **kw): pass register_filter(OverrideMyFilter) assert_true(isinstance(get_filter('foo'), OverrideMyFilter))
[ "def", "test_register_filter", "(", ")", ":", "assert_raises", "(", "ValueError", ",", "register_filter", ",", "object", ")", "class", "MyFilter", "(", "Filter", ",", ")", ":", "name", "=", "None", "def", "output", "(", "self", ",", "*", "a", ",", "**", ...
test registration of custom filters .
train
false
30,231
def loadAliasFile(domains, filename=None, fp=None): result = {} close = False if (fp is None): fp = open(filename) close = True else: filename = getattr(fp, 'name', '<unknown>') i = 0 prev = '' try: for line in fp: i += 1 line = line.rstrip() if line.lstrip().startswith('#'): continue elif (line.startswith(' ') or line.startswith(' DCTB ')): prev = (prev + line) else: if prev: handle(result, prev, filename, i) prev = line finally: if close: fp.close() if prev: handle(result, prev, filename, i) for (u, a) in result.items(): result[u] = AliasGroup(a, domains, u) return result
[ "def", "loadAliasFile", "(", "domains", ",", "filename", "=", "None", ",", "fp", "=", "None", ")", ":", "result", "=", "{", "}", "close", "=", "False", "if", "(", "fp", "is", "None", ")", ":", "fp", "=", "open", "(", "filename", ")", "close", "="...
load a file containing email aliases .
train
false
30,234
def find_feat_part(artist, albumartist): feat_part = None albumartist_split = artist.split(albumartist, 1) if (len(albumartist_split) <= 1): return feat_part elif (albumartist_split[(-1)] != ''): (_, feat_part) = split_on_feat(albumartist_split[(-1)]) else: (lhs, rhs) = split_on_feat(albumartist_split[0]) if lhs: feat_part = lhs return feat_part
[ "def", "find_feat_part", "(", "artist", ",", "albumartist", ")", ":", "feat_part", "=", "None", "albumartist_split", "=", "artist", ".", "split", "(", "albumartist", ",", "1", ")", "if", "(", "len", "(", "albumartist_split", ")", "<=", "1", ")", ":", "re...
attempt to find featured artists in the items artist fields and return the results .
train
false
30,235
def func_lineno(func): try: return func.compat_co_firstlineno except AttributeError: try: return func.func_code.co_firstlineno except AttributeError: return (-1)
[ "def", "func_lineno", "(", "func", ")", ":", "try", ":", "return", "func", ".", "compat_co_firstlineno", "except", "AttributeError", ":", "try", ":", "return", "func", ".", "func_code", ".", "co_firstlineno", "except", "AttributeError", ":", "return", "(", "-"...
get the line number of a function .
train
false
30,236
def get_backup_drivers(): _ensure_loaded('cinder/backup/drivers') return [DriverInfo(x) for x in interface._backup_register]
[ "def", "get_backup_drivers", "(", ")", ":", "_ensure_loaded", "(", "'cinder/backup/drivers'", ")", "return", "[", "DriverInfo", "(", "x", ")", "for", "x", "in", "interface", ".", "_backup_register", "]" ]
get a list of all backup drivers .
train
false
30,237
def iso8601format(dt): return (dt.strftime('%Y-%m-%dT%H:%M:%SZ') if dt else '')
[ "def", "iso8601format", "(", "dt", ")", ":", "return", "(", "dt", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "if", "dt", "else", "''", ")" ]
given a datetime object .
train
false
30,240
def format_range(value): if (len(value) == 4): result = ('%s %s-%s/%s' % (value[3], value[0], value[1], value[2])) else: result = ('bytes %s-%s/%s' % (value[0], value[1], value[2])) if six.PY2: result = str(result) return result
[ "def", "format_range", "(", "value", ")", ":", "if", "(", "len", "(", "value", ")", "==", "4", ")", ":", "result", "=", "(", "'%s %s-%s/%s'", "%", "(", "value", "[", "3", "]", ",", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "va...
formats a range header tuple per the http spec .
train
false
30,241
def funcs_allclose(f, backends, backend_tensors, rtol=0, atol=1e-07): results = [] for (backend, tensors) in zip(backends, backend_tensors): results.append(call_func(f, backend, tensors)) return tensors_allclose(results, rtol=rtol, atol=atol)
[ "def", "funcs_allclose", "(", "f", ",", "backends", ",", "backend_tensors", ",", "rtol", "=", "0", ",", "atol", "=", "1e-07", ")", ":", "results", "=", "[", "]", "for", "(", "backend", ",", "tensors", ")", "in", "zip", "(", "backends", ",", "backend_...
for each backends .
train
false
30,242
def tracing(): def prep(r): if (r.id and (r.component_name == 'exposure')): ctable = r.component.table case_id = ctable.case_id case_id.default = r.id case_id.readable = case_id.writable = False crud_strings = s3.crud_strings[r.component.tablename] crud_strings['label_create'] = T('Add Contact Person') crud_strings['label_delete_button'] = T('Delete Contact Person') return True s3.prep = prep return s3_rest_controller(rheader=s3db.disease_rheader)
[ "def", "tracing", "(", ")", ":", "def", "prep", "(", "r", ")", ":", "if", "(", "r", ".", "id", "and", "(", "r", ".", "component_name", "==", "'exposure'", ")", ")", ":", "ctable", "=", "r", ".", "component", ".", "table", "case_id", "=", "ctable"...
contact tracing controller .
train
false
30,243
def clip_boxes(boxes, im_shape): boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], (im_shape[1] - 1)), 0) boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], (im_shape[0] - 1)), 0) boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], (im_shape[1] - 1)), 0) boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], (im_shape[0] - 1)), 0) return boxes
[ "def", "clip_boxes", "(", "boxes", ",", "im_shape", ")", ":", "boxes", "[", ":", ",", "0", ":", ":", "4", "]", "=", "np", ".", "maximum", "(", "np", ".", "minimum", "(", "boxes", "[", ":", ",", "0", ":", ":", "4", "]", ",", "(", "im_shape", ...
clip boxes to image boundaries .
train
true
30,244
def p_init_declarator_list_1(t): pass
[ "def", "p_init_declarator_list_1", "(", "t", ")", ":", "pass" ]
init_declarator_list : init_declarator .
train
false
30,246
def p_parameter_list_1(t): pass
[ "def", "p_parameter_list_1", "(", "t", ")", ":", "pass" ]
parameter_list : parameter_declaration .
train
false
30,247
def TruncateValue(value): value = ustr(value) if (len(value) > 32): return (value[:32] + '...') return value
[ "def", "TruncateValue", "(", "value", ")", ":", "value", "=", "ustr", "(", "value", ")", "if", "(", "len", "(", "value", ")", ">", "32", ")", ":", "return", "(", "value", "[", ":", "32", "]", "+", "'...'", ")", "return", "value" ]
truncates potentially very long string to a fixed maximum length .
train
false
30,248
def get_suite(): loader = unittest.TestLoader() tld = __file__.split(os.path.sep) tld.reverse() for (i, x) in enumerate(tld): if (x == 'pyamf'): tld.reverse() tld = os.path.sep.join(tld[:((-1) - i)]) break return loader.discover('pyamf', top_level_dir=tld)
[ "def", "get_suite", "(", ")", ":", "loader", "=", "unittest", ".", "TestLoader", "(", ")", "tld", "=", "__file__", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "tld", ".", "reverse", "(", ")", "for", "(", "i", ",", "x", ")", "in", "en...
discover the entire test suite .
train
false
30,251
def listOfFeatures2Matrix(features): X = numpy.array([]) Y = numpy.array([]) for (i, f) in enumerate(features): if (i == 0): X = f Y = (i * numpy.ones((len(f), 1))) else: X = numpy.vstack((X, f)) Y = numpy.append(Y, (i * numpy.ones((len(f), 1)))) return (X, Y)
[ "def", "listOfFeatures2Matrix", "(", "features", ")", ":", "X", "=", "numpy", ".", "array", "(", "[", "]", ")", "Y", "=", "numpy", ".", "array", "(", "[", "]", ")", "for", "(", "i", ",", "f", ")", "in", "enumerate", "(", "features", ")", ":", "...
listoffeatures2matrix this function takes a list of feature matrices as argument and returns a single concatenated feature matrix and the respective class labels .
train
false
30,252
def getEmptyZLoops(archivableObjects, importRadius, shouldPrintWarning, z, zoneArrangement): emptyZ = zoneArrangement.getEmptyZ(z) visibleObjects = evaluate.getVisibleObjects(archivableObjects) visibleObjectLoopsList = boolean_solid.getVisibleObjectLoopsList(importRadius, visibleObjects, emptyZ) loops = euclidean.getConcatenatedList(visibleObjectLoopsList) if euclidean.isLoopListIntersecting(loops): loops = boolean_solid.getLoopsUnion(importRadius, visibleObjectLoopsList) if shouldPrintWarning: print 'Warning, the triangle mesh slice intersects itself in getExtruderPaths in boolean_geometry.' print 'Something will still be printed, but there is no guarantee that it will be the correct shape.' print 'Once the gcode is saved, you should check over the layer with a z of:' print z return loops
[ "def", "getEmptyZLoops", "(", "archivableObjects", ",", "importRadius", ",", "shouldPrintWarning", ",", "z", ",", "zoneArrangement", ")", ":", "emptyZ", "=", "zoneArrangement", ".", "getEmptyZ", "(", "z", ")", "visibleObjects", "=", "evaluate", ".", "getVisibleObj...
get loops at empty z level .
train
false
30,253
def test_now(): now = datetime.datetime.utcnow() t = Time.now() assert (t.format == 'datetime') assert (t.scale == 'utc') dt = (t.datetime - now) if (sys.version_info[:2] < (2, 7)): total_secs = (lambda td: ((td.microseconds + ((td.seconds + ((td.days * 24) * 3600)) * (10 ** 6))) / (10 ** 6.0))) else: total_secs = (lambda td: td.total_seconds()) assert (total_secs(dt) < 0.1)
[ "def", "test_now", "(", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "t", "=", "Time", ".", "now", "(", ")", "assert", "(", "t", ".", "format", "==", "'datetime'", ")", "assert", "(", "t", ".", "scale", "==", "'utc'...
tests creating a time object with the now class method .
train
false
30,254
def paging(pause=0, marker_property='marker'): def wrapper(f): def page(*args, **kwargs): results = [] marker = None while True: try: new = f(marker=marker, *args, **kwargs) marker = getattr(new, marker_property) results.extend(new) if (not marker): break elif pause: sleep(pause) except TypeError: results = f(*args, **kwargs) break return results return page return wrapper
[ "def", "paging", "(", "pause", "=", "0", ",", "marker_property", "=", "'marker'", ")", ":", "def", "wrapper", "(", "f", ")", ":", "def", "page", "(", "*", "args", ",", "**", "kwargs", ")", ":", "results", "=", "[", "]", "marker", "=", "None", "wh...
adds paging to boto retrieval functions that support a marker this is configurable as not all boto functions seem to use the same name .
train
false
30,255
@decorator def deflate(f, *args, **kwargs): data = f(*args, **kwargs) if isinstance(data, Response): content = data.data else: content = data deflater = zlib.compressobj() deflated_data = deflater.compress(content) deflated_data += deflater.flush() if isinstance(data, Response): data.data = deflated_data data.headers['Content-Encoding'] = 'deflate' data.headers['Content-Length'] = str(len(data.data)) return data return deflated_data
[ "@", "decorator", "def", "deflate", "(", "f", ",", "*", "args", ",", "**", "kwargs", ")", ":", "data", "=", "f", "(", "*", "args", ",", "**", "kwargs", ")", "if", "isinstance", "(", "data", ",", "Response", ")", ":", "content", "=", "data", ".", ...
compress/base64 encode a string .
train
true
30,256
def test_bad_repr(): with nt.assert_raises(ZeroDivisionError): pretty.pretty(BadRepr())
[ "def", "test_bad_repr", "(", ")", ":", "with", "nt", ".", "assert_raises", "(", "ZeroDivisionError", ")", ":", "pretty", ".", "pretty", "(", "BadRepr", "(", ")", ")" ]
dont catch bad repr errors .
train
false
30,257
def configure_network(ip, netmask, gateway): current = network() if ((ip in current['Network Settings']['IP_ADDRESS']['VALUE']) and (netmask in current['Network Settings']['SUBNET_MASK']['VALUE']) and (gateway in current['Network Settings']['GATEWAY_IP_ADDRESS']['VALUE'])): return True _xml = '<RIBCL VERSION="2.0">\n <LOGIN USER_LOGIN="adminname" PASSWORD="password">\n <RIB_INFO MODE="write">\n <MOD_NETWORK_SETTINGS>\n <IP_ADDRESS value="{0}"/>\n <SUBNET_MASK value="{1}"/>\n <GATEWAY_IP_ADDRESS value="{2}"/>\n </MOD_NETWORK_SETTINGS>\n </RIB_INFO>\n </LOGIN>\n </RIBCL> '.format(ip, netmask, gateway) return __execute_cmd('Configure_Network', _xml)
[ "def", "configure_network", "(", "ip", ",", "netmask", ",", "gateway", ")", ":", "current", "=", "network", "(", ")", "if", "(", "(", "ip", "in", "current", "[", "'Network Settings'", "]", "[", "'IP_ADDRESS'", "]", "[", "'VALUE'", "]", ")", "and", "(",...
configure network interface cli example: .
train
true
30,258
def list_environments(): return settings.environments
[ "def", "list_environments", "(", ")", ":", "return", "settings", ".", "environments" ]
returns a list of all defined environments .
train
false
30,259
def get_any_collection(bus): try: return Collection(bus) except ItemNotFoundException: pass try: return Collection(bus, SESSION_COLLECTION) except ItemNotFoundException: pass collections = list(get_all_collections(bus)) if collections: return collections[0] else: raise ItemNotFoundException('No collections found.')
[ "def", "get_any_collection", "(", "bus", ")", ":", "try", ":", "return", "Collection", "(", "bus", ")", "except", "ItemNotFoundException", ":", "pass", "try", ":", "return", "Collection", "(", "bus", ",", "SESSION_COLLECTION", ")", "except", "ItemNotFoundExcepti...
returns any collection .
train
false
30,260
def create_return_url(base, query, **kwargs): part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for (key, values) in parse_qs(query).items(): if (key in kwargs): if isinstance(kwargs[key], basestring): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for (key, values) in parse_qs(part.query).items(): if (key in kwargs): if isinstance(kwargs[key], basestring): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split('?')[0] else: _pre = base logger.debug(('kwargs: %s' % kwargs)) return ('%s?%s' % (_pre, url_encode_params(kwargs)))
[ "def", "create_return_url", "(", "base", ",", "query", ",", "**", "kwargs", ")", ":", "part", "=", "urlsplit", "(", "base", ")", "if", "part", ".", "fragment", ":", "raise", "ValueError", "(", "\"Base URL contained parts it shouldn't\"", ")", "for", "(", "ke...
add a query string plus extra parameters to a base url which may contain a query part already .
train
true
30,262
def get_by_path(obj, path): for key in path: obj = obj[key] return obj
[ "def", "get_by_path", "(", "obj", ",", "path", ")", ":", "for", "key", "in", "path", ":", "obj", "=", "obj", "[", "key", "]", "return", "obj" ]
iteratively get on obj for each key in path .
train
false
30,263
@cli.command() @click.option('--count', default=8000, type=click.IntRange(1, 100000), help='The number of items to process.') def progress(count): items = range_type(count) def process_slowly(item): time.sleep((0.002 * random.random())) def filter(items): for item in items: if (random.random() > 0.3): (yield item) with click.progressbar(items, label='Processing accounts', fill_char=click.style('#', fg='green')) as bar: for item in bar: process_slowly(item) def show_item(item): if (item is not None): return ('Item #%d' % item) with click.progressbar(filter(items), label='Committing transaction', fill_char=click.style('#', fg='yellow'), item_show_func=show_item) as bar: for item in bar: process_slowly(item) with click.progressbar(length=count, label='Counting', bar_template='%(label)s %(bar)s | %(info)s', fill_char=click.style(u'\u2588', fg='cyan'), empty_char=' ') as bar: for item in bar: process_slowly(item) with click.progressbar(length=count, width=0, show_percent=False, show_eta=False, fill_char=click.style('#', fg='magenta')) as bar: for item in bar: process_slowly(item) steps = [(math.exp(((x * 1.0) / 20)) - 1) for x in range(20)] count = int(sum(steps)) with click.progressbar(length=count, show_percent=False, label='Slowing progress bar', fill_char=click.style(u'\u2588', fg='green')) as bar: for item in steps: time.sleep(item) bar.update(item)
[ "@", "cli", ".", "command", "(", ")", "@", "click", ".", "option", "(", "'--count'", ",", "default", "=", "8000", ",", "type", "=", "click", ".", "IntRange", "(", "1", ",", "100000", ")", ",", "help", "=", "'The number of items to process.'", ")", "def...
progress an iterator and updates a pretty status line to the terminal .
train
false
30,265
def start_scan_helper(target_urls, scan_profile, scan_info_setup): scan_info = ScanInfo() SCANS[get_new_scan_id()] = scan_info scan_info.w3af_core = w3af_core = w3afCore() scan_info.target_urls = target_urls scan_info.output = RESTAPIOutput() scan_info_setup.set() (scan_profile_file_name, profile_path) = create_temp_profile(scan_profile) om.manager.set_output_plugins([]) try: w3af_core.profiles.use_profile(scan_profile_file_name, workdir=profile_path) target_options = w3af_core.target.get_options() target_option = target_options['target'] target_option.set_value([URL(u) for u in target_urls]) w3af_core.target.set_options(target_options) w3af_core.plugins.init_plugins() om.manager.set_output_plugin_inst(scan_info.output) w3af_core.verify_environment() w3af_core.start() except Exception as e: scan_info.exception = e try: w3af_core.stop() except AttributeError: pass finally: scan_info.finished = True try: os.unlink(os.path.join(profile_path, scan_profile_file_name)) except (AttributeError, IOError) as _: pass
[ "def", "start_scan_helper", "(", "target_urls", ",", "scan_profile", ",", "scan_info_setup", ")", ":", "scan_info", "=", "ScanInfo", "(", ")", "SCANS", "[", "get_new_scan_id", "(", ")", "]", "=", "scan_info", "scan_info", ".", "w3af_core", "=", "w3af_core", "=...
create a new instance of w3afcore .
train
false
30,266
def _remove_dir(path): try: shutil.rmtree(path.path) except OSError as e: if (e.errno != errno.ENOENT): raise
[ "def", "_remove_dir", "(", "path", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "path", ".", "path", ")", "except", "OSError", "as", "e", ":", "if", "(", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ")", ":", "raise" ]
safely remove the directory path .
train
false
30,267
def name_from_basename(basename): return (u'icons:' + basename)
[ "def", "name_from_basename", "(", "basename", ")", ":", "return", "(", "u'icons:'", "+", "basename", ")" ]
prefix the basename with "icons:" so that git-colas icons are found "icons" is registered with qts resource system during install() .
train
false
30,268
def get_keypair(vm_): keypair = config.get_cloud_config_value('keypair', vm_, __opts__) if keypair: return keypair else: return False
[ "def", "get_keypair", "(", "vm_", ")", ":", "keypair", "=", "config", ".", "get_cloud_config_value", "(", "'keypair'", ",", "vm_", ",", "__opts__", ")", "if", "keypair", ":", "return", "keypair", "else", ":", "return", "False" ]
return the keypair to use .
train
true
30,269
def determine_user_agent(config): if (config.user_agent is None): ua = 'CertbotACMEClient/{0} ({1}) Authenticator/{2} Installer/{3}' ua = ua.format(certbot.__version__, util.get_os_info_ua(), config.authenticator, config.installer) else: ua = config.user_agent return ua
[ "def", "determine_user_agent", "(", "config", ")", ":", "if", "(", "config", ".", "user_agent", "is", "None", ")", ":", "ua", "=", "'CertbotACMEClient/{0} ({1}) Authenticator/{2} Installer/{3}'", "ua", "=", "ua", ".", "format", "(", "certbot", ".", "__version__", ...
set a user_agent string in the config based on the choice of plugins .
train
false
30,270
def gaussian(h, Xi, x): return ((1.0 / np.sqrt((2 * np.pi))) * np.exp(((- ((Xi - x) ** 2)) / ((h ** 2) * 2.0))))
[ "def", "gaussian", "(", "h", ",", "Xi", ",", "x", ")", ":", "return", "(", "(", "1.0", "/", "np", ".", "sqrt", "(", "(", "2", "*", "np", ".", "pi", ")", ")", ")", "*", "np", ".", "exp", "(", "(", "(", "-", "(", "(", "Xi", "-", "x", ")...
gaussian kernel for continuous variables parameters h : 1-d ndarray .
train
true
30,271
def post_call_hook(service, call, request, response, rpc=None, error=None): if recorder_proxy.has_recorder_for_current_request(): if config.DEBUG: logging.debug('post_call_hook: recording %s.%s', service, call) recorder_proxy.record_rpc_response(service, call, request, response, rpc)
[ "def", "post_call_hook", "(", "service", ",", "call", ",", "request", ",", "response", ",", "rpc", "=", "None", ",", "error", "=", "None", ")", ":", "if", "recorder_proxy", ".", "has_recorder_for_current_request", "(", ")", ":", "if", "config", ".", "DEBUG...
post-call hook function for apiproxy_stub_map .
train
false
30,273
def test_pydotprint_cond_highlight(): if (not theano.printing.pydot_imported): raise SkipTest('pydot not available') x = tensor.dvector() f = theano.function([x], (x * 2)) f([1, 2, 3, 4]) s = StringIO() new_handler = logging.StreamHandler(s) new_handler.setLevel(logging.DEBUG) orig_handler = theano.logging_default_handler theano.theano_logger.removeHandler(orig_handler) theano.theano_logger.addHandler(new_handler) try: theano.printing.pydotprint(f, cond_highlight=True, print_output_file=False) finally: theano.theano_logger.addHandler(orig_handler) theano.theano_logger.removeHandler(new_handler) assert (s.getvalue() == 'pydotprint: cond_highlight is set but there is no IfElse node in the graph\n')
[ "def", "test_pydotprint_cond_highlight", "(", ")", ":", "if", "(", "not", "theano", ".", "printing", ".", "pydot_imported", ")", ":", "raise", "SkipTest", "(", "'pydot not available'", ")", "x", "=", "tensor", ".", "dvector", "(", ")", "f", "=", "theano", ...
this is a really partial test .
train
false
30,276
@mock_streams('stdout') def test_puts_with_user_output_off(): output.user = False puts("You aren't reading this.") eq_(sys.stdout.getvalue(), '')
[ "@", "mock_streams", "(", "'stdout'", ")", "def", "test_puts_with_user_output_off", "(", ")", ":", "output", ".", "user", "=", "False", "puts", "(", "\"You aren't reading this.\"", ")", "eq_", "(", "sys", ".", "stdout", ".", "getvalue", "(", ")", ",", "''", ...
puts() shouldnt print input to sys .
train
false
30,278
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "create_customer_gateway", "(", "vpn_connection_type", ",", "ip_address", ",", "bgp_asn", ",", "customer_gateway_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profil...
given a valid vpn connection type .
train
true
30,281
def module_name_from_dir(dirname, err=True, files=None): if (files is None): files = os.listdir(dirname) names = [file for file in files if (file.endswith('.so') or file.endswith('.pyd'))] if ((len(names) == 0) and (not err)): return None elif (len(names) == 1): return os.path.join(dirname, names[0]) else: raise ValueError(('More than 1 compiled module in this directory:' + dirname))
[ "def", "module_name_from_dir", "(", "dirname", ",", "err", "=", "True", ",", "files", "=", "None", ")", ":", "if", "(", "files", "is", "None", ")", ":", "files", "=", "os", ".", "listdir", "(", "dirname", ")", "names", "=", "[", "file", "for", "fil...
scan the contents of a cache directory and return full path of the dynamic lib in it .
train
false
30,284
def triad_graph(triad_name): if (triad_name not in TRIAD_EDGES): raise ValueError('unknown triad name "{}"; use one of the triad names in the TRIAD_NAMES constant'.format(triad_name)) G = DiGraph() G.add_nodes_from('abc') G.add_edges_from(TRIAD_EDGES[triad_name]) return G
[ "def", "triad_graph", "(", "triad_name", ")", ":", "if", "(", "triad_name", "not", "in", "TRIAD_EDGES", ")", ":", "raise", "ValueError", "(", "'unknown triad name \"{}\"; use one of the triad names in the TRIAD_NAMES constant'", ".", "format", "(", "triad_name", ")", ")...
returns the triad graph with the given name .
train
false
30,285
def is_progressive(image): if (not isinstance(image, Image.Image)): return False return (('progressive' in image.info) or ('progression' in image.info))
[ "def", "is_progressive", "(", "image", ")", ":", "if", "(", "not", "isinstance", "(", "image", ",", "Image", ".", "Image", ")", ")", ":", "return", "False", "return", "(", "(", "'progressive'", "in", "image", ".", "info", ")", "or", "(", "'progression'...
check to see if an image is progressive .
train
true