text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def running(name, cpu=None, mem=None, image=None, vm_type=None, disk_profile=None, disks=None, nic_profile=None, interfaces=None, graphics=None, loader=None, seed=True, install...
[ "def", "running", "(", "name", ",", "cpu", "=", "None", ",", "mem", "=", "None", ",", "image", "=", "None", ",", "vm_type", "=", "None", ",", "disk_profile", "=", "None", ",", "disks", "=", "None", ",", "nic_profile", "=", "None", ",", "interfaces", ...
39.967078
22.757202
def handle(self): """ Reimplements the :meth:`SocketServer.BaseRequestHandler.handle` method. :return: Method success. :rtype: bool """ while True: data = self.request.recv(1024) if not data: break self.request.send(d...
[ "def", "handle", "(", "self", ")", ":", "while", "True", ":", "data", "=", "self", ".", "request", ".", "recv", "(", "1024", ")", "if", "not", "data", ":", "break", "self", ".", "request", ".", "send", "(", "data", ")", "return", "True" ]
22
19.6
def aliases_of(self, name): """ Returns other names for given real key or alias ``name``. If given a real key, returns its aliases. If given an alias, returns the real key it points to, plus any other aliases of that real key. (The given alias itself is not included in ...
[ "def", "aliases_of", "(", "self", ",", "name", ")", ":", "names", "=", "[", "]", "key", "=", "name", "# self.aliases keys are aliases, not realkeys. Easy test to see if we", "# should flip around to the POV of a realkey when given an alias.", "if", "name", "in", "self", "."...
36.846154
19.307692
def get_list(file,fmt): '''makes a list out of the fmt from the LspOutput f using the format i for int f for float d for double s for string''' out=[] for i in fmt: if i == 'i': out.append(get_int(file)); elif i == 'f' or i == 'd': out.appe...
[ "def", "get_list", "(", "file", ",", "fmt", ")", ":", "out", "=", "[", "]", "for", "i", "in", "fmt", ":", "if", "i", "==", "'i'", ":", "out", ".", "append", "(", "get_int", "(", "file", ")", ")", "elif", "i", "==", "'f'", "or", "i", "==", "...
28.235294
18.235294
def _parse(self, command): """ Parse a single command. """ cmd, id_, args = command[0], command[1], command[2:] if cmd == 'CURRENT': # This context is made current self.env.clear() self._gl_initialize() self.env['fbo'] = args[0] ...
[ "def", "_parse", "(", "self", ",", "command", ")", ":", "cmd", ",", "id_", ",", "args", "=", "command", "[", "0", "]", ",", "command", "[", "1", "]", ",", "command", "[", "2", ":", "]", "if", "cmd", "==", "'CURRENT'", ":", "# This context is made c...
40.328358
12.029851
def import_rsa_privatekey_from_file(filepath, password=None, scheme='rsassa-pss-sha256', prompt=False): """ <Purpose> Import the PEM file in 'filepath' containing the private key. If password is passed use passed password for decryption. If prompt is True use entered password for decryption. If...
[ "def", "import_rsa_privatekey_from_file", "(", "filepath", ",", "password", "=", "None", ",", "scheme", "=", "'rsassa-pss-sha256'", ",", "prompt", "=", "False", ")", ":", "# Does 'filepath' have the correct format?", "# Ensure the arguments have the appropriate number of object...
39.307018
27.903509
def good_surts_from_default(default_surt): ''' Takes a standard surt without scheme and without trailing comma, and returns a list of "good" surts that together match the same set of urls. For example: good_surts_from_default('com,example)/path') returns ...
[ "def", "good_surts_from_default", "(", "default_surt", ")", ":", "if", "default_surt", "==", "''", ":", "return", "[", "''", "]", "parts", "=", "default_surt", ".", "split", "(", "')'", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "2", ":", "...
33.285714
19.228571
def as_dict(self): """ Json-serializable dict representation. """ structure = self.final_structure d = {"has_gaussian_completed": self.properly_terminated, "nsites": len(structure)} comp = structure.composition d["unit_cell_formula"] = comp.as_dict() ...
[ "def", "as_dict", "(", "self", ")", ":", "structure", "=", "self", ".", "final_structure", "d", "=", "{", "\"has_gaussian_completed\"", ":", "self", ".", "properly_terminated", ",", "\"nsites\"", ":", "len", "(", "structure", ")", "}", "comp", "=", "structur...
34.681818
16.090909
def interface_type(self): """ Get the CoRE Link Format if attribute of the resource. :return: the CoRE Link Format if attribute """ value = "if=" lst = self._attributes.get("if") if lst is None: value = "" else: value += "\"" + str...
[ "def", "interface_type", "(", "self", ")", ":", "value", "=", "\"if=\"", "lst", "=", "self", ".", "_attributes", ".", "get", "(", "\"if\"", ")", "if", "lst", "is", "None", ":", "value", "=", "\"\"", "else", ":", "value", "+=", "\"\\\"\"", "+", "str",...
26.230769
14.692308
def names(self): """Names, by which the instance can be retrieved.""" if getattr(self, 'key', None) is None: result = [] else: result = [self.key] if hasattr(self, 'aliases'): result.extend(self.aliases) return result
[ "def", "names", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'key'", ",", "None", ")", "is", "None", ":", "result", "=", "[", "]", "else", ":", "result", "=", "[", "self", ".", "key", "]", "if", "hasattr", "(", "self", ",", "'alia...
31.666667
11.888889
def _build_attribute_modifiers(var, attribute_mapping, ignore=None): """ Handles adding schema modifiers for a given config var and some mapping. :param attr._make.Attribute var: The config var to build modifiers for :param Dict[str, str] attribute_mapping: A mapping of attribute to jsonschema modi...
[ "def", "_build_attribute_modifiers", "(", "var", ",", "attribute_mapping", ",", "ignore", "=", "None", ")", ":", "if", "not", "isinstance", "(", "ignore", ",", "list", ")", ":", "ignore", "=", "[", "\"type\"", ",", "\"name\"", ",", "\"required\"", ",", "\"...
44.411765
24.235294
def next_frame_base_range(rhp): """Basic tuning grid.""" rhp.set_float("dropout", 0.2, 0.6) rhp.set_discrete("hidden_size", [64, 128, 256]) rhp.set_int("num_compress_steps", 5, 8) rhp.set_discrete("batch_size", [4, 8, 16, 32]) rhp.set_int("num_hidden_layers", 1, 3) rhp.set_int("filter_double_steps", 1, 6)...
[ "def", "next_frame_base_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.2", ",", "0.6", ")", "rhp", ".", "set_discrete", "(", "\"hidden_size\"", ",", "[", "64", ",", "128", ",", "256", "]", ")", "rhp", ".", "set_int",...
41.909091
5.545455
def log_config(self, value): """ { "Type": "<driver_name>", "Config": {"key1": "val1"}} """ if not isinstance(value, dict): raise TypeError("log_config must be a dict. {0} was passed".format(value)) config = value.get('config') driver_type = value.get('t...
[ "def", "log_config", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"log_config must be a dict. {0} was passed\"", ".", "format", "(", "value", ")", ")", "config", "=", "value...
40.043478
25.521739
def run_job(self, job_spec, wait_until_done=True): """ Runs a job defined by jobspec, optionally non-blocking. Takes a GPJobSpec object that defines a request to run a job, and makes the request to the server. By default blocks until the job is finished by polling the server, b...
[ "def", "run_job", "(", "self", ",", "job_spec", ",", "wait_until_done", "=", "True", ")", ":", "# names should be a list of names,", "# values should be a list of **lists** of values", "json_string", "=", "json", ".", "dumps", "(", "{", "'lsid'", ":", "job_spec", ".",...
49.5
26.5
def showMessageDialog(title, text): ''' Show a dialog containing a given text, with a given title. The text accepts HTML syntax ''' dlg = QgsMessageOutput.createMessageOutput() dlg.setTitle(title) dlg.setMessage(text, QgsMessageOutput.MessageHtml) dlg.showMessage()
[ "def", "showMessageDialog", "(", "title", ",", "text", ")", ":", "dlg", "=", "QgsMessageOutput", ".", "createMessageOutput", "(", ")", "dlg", ".", "setTitle", "(", "title", ")", "dlg", ".", "setMessage", "(", "text", ",", "QgsMessageOutput", ".", "MessageHtm...
28.9
19.9
def eval_function(value): """ Evaluate a timestamp function """ name, args = value[0], value[1:] if name == "NOW": return datetime.utcnow().replace(tzinfo=tzutc()) elif name in ["TIMESTAMP", "TS"]: return parse(unwrap(args[0])).replace(tzinfo=tzlocal()) elif name in ["UTCTIMESTAMP", ...
[ "def", "eval_function", "(", "value", ")", ":", "name", ",", "args", "=", "value", "[", "0", "]", ",", "value", "[", "1", ":", "]", "if", "name", "==", "\"NOW\"", ":", "return", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", ...
39.384615
13.461538
def get_symm_bands(self, structure, efermi, kpt_line=None, labels_dict=None): """ Function useful to read bands from Boltztrap output and get a BandStructureSymmLine object comparable with that one from a DFT calculation (if the same kpt_line is provide...
[ "def", "get_symm_bands", "(", "self", ",", "structure", ",", "efermi", ",", "kpt_line", "=", "None", ",", "labels_dict", "=", "None", ")", ":", "try", ":", "if", "kpt_line", "is", "None", ":", "kpath", "=", "HighSymmKpath", "(", "structure", ")", "kpt_li...
43.907692
20.769231
def create_title(article, language, title, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, creation_date=None, image=None): """ Create an article title. """ # validate article assert isinstance(article, Article) # validate ...
[ "def", "create_title", "(", "article", ",", "language", ",", "title", ",", "slug", "=", "None", ",", "description", "=", "None", ",", "page_title", "=", "None", ",", "menu_title", "=", "None", ",", "meta_description", "=", "None", ",", "creation_date", "="...
27.304348
19.73913
def explain_unicode(text): """ A utility method that's useful for debugging mysterious Unicode. It breaks down a string, showing you for each codepoint its number in hexadecimal, its glyph, its category in the Unicode standard, and its name in the Unicode standard. >>> explain_unicode('(╯°...
[ "def", "explain_unicode", "(", "text", ")", ":", "for", "char", "in", "text", ":", "if", "char", ".", "isprintable", "(", ")", ":", "display", "=", "char", "else", ":", "display", "=", "char", ".", "encode", "(", "'unicode-escape'", ")", ".", "decode",...
41.575758
17.212121
def on_source_directory_chooser_clicked(self): """Autoconnect slot activated when tbSourceDir is clicked.""" title = self.tr('Set the source directory for script and scenario') self.choose_directory(self.source_directory, title)
[ "def", "on_source_directory_chooser_clicked", "(", "self", ")", ":", "title", "=", "self", ".", "tr", "(", "'Set the source directory for script and scenario'", ")", "self", ".", "choose_directory", "(", "self", ".", "source_directory", ",", "title", ")" ]
49.8
20
def _is_compressed(dicom_file, force=False): """ Check if dicoms are compressed or not """ header = pydicom.read_file(dicom_file, defer_size="1 KB", stop_before_pixels=True, force=force) uncompressed_types ...
[ "def", "_is_compressed", "(", "dicom_file", ",", "force", "=", "False", ")", ":", "header", "=", "pydicom", ".", "read_file", "(", "dicom_file", ",", "defer_size", "=", "\"1 KB\"", ",", "stop_before_pixels", "=", "True", ",", "force", "=", "force", ")", "u...
36.705882
15.294118
def word_counts(self): """Dictionary of word frequencies in this text.""" counts = defaultdict(int) stripped_words = [lowerstrip(word) for word in self.words] for word in stripped_words: counts[word] += 1 return counts
[ "def", "word_counts", "(", "self", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "stripped_words", "=", "[", "lowerstrip", "(", "word", ")", "for", "word", "in", "self", ".", "words", "]", "for", "word", "in", "stripped_words", ":", "counts", ...
37.714286
12.285714
def change_text(self, text, fname, pattern=None, before=False, force=False, delete=False, note=None, replace=False, line_oriented=True, create=True, ...
[ "def", "change_text", "(", "self", ",", "text", ",", "fname", ",", "pattern", "=", "None", ",", "before", "=", "False", ",", "force", "=", "False", ",", "delete", "=", "False", ",", "note", "=", "None", ",", "replace", "=", "False", ",", "line_orient...
44.486607
23.986607
def _astype(self, dtype, copy=False, errors='raise', values=None, **kwargs): """Coerce to the new type Parameters ---------- dtype : str, dtype convertible copy : boolean, default False copy if indicated errors : str, {'raise', 'ignore'}, defa...
[ "def", "_astype", "(", "self", ",", "dtype", ",", "copy", "=", "False", ",", "errors", "=", "'raise'", ",", "values", "=", "None", ",", "*", "*", "kwargs", ")", ":", "errors_legal_values", "=", "(", "'raise'", ",", "'ignore'", ")", "if", "errors", "n...
38.168142
20.327434
def empty_channel(self, topic, channel): """Empty all the queued messages for an existing channel.""" nsq.assert_valid_topic_name(topic) nsq.assert_valid_channel_name(channel) return self._request('POST', '/channel/empty', fields={'topic': topic, 'channel': c...
[ "def", "empty_channel", "(", "self", ",", "topic", ",", "channel", ")", ":", "nsq", ".", "assert_valid_topic_name", "(", "topic", ")", "nsq", ".", "assert_valid_channel_name", "(", "channel", ")", "return", "self", ".", "_request", "(", "'POST'", ",", "'/cha...
53.833333
9.166667
def as_pyemu_matrix(self,typ=Matrix): """ Create a pyemu.Matrix from the Ensemble. Parameters ---------- typ : pyemu.Matrix or derived type the type of matrix to return Returns ------- pyemu.Matrix : pyemu.Matrix """ ...
[ "def", "as_pyemu_matrix", "(", "self", ",", "typ", "=", "Matrix", ")", ":", "x", "=", "self", ".", "values", ".", "copy", "(", ")", ".", "astype", "(", "np", ".", "float", ")", "return", "typ", "(", "x", "=", "x", ",", "row_names", "=", "list", ...
26.235294
15.764706
def set_global_tracer(value): """Sets the global tracer. It is an error to pass ``None``. :param value: the :class:`Tracer` used as global instance. :type value: :class:`Tracer` """ if value is None: raise ValueError('The global Tracer tracer cannot be None') global tracer, is_trac...
[ "def", "set_global_tracer", "(", "value", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "'The global Tracer tracer cannot be None'", ")", "global", "tracer", ",", "is_tracer_registered", "tracer", "=", "value", "is_tracer_registered", "=", ...
28.615385
15.615385
def asbaseline(self, pos): """Convert a position measure into a baseline measure. No actual baseline is calculated, since operations can be done on positions, with subtractions to obtain baselines at a later stage. :param pos: a position measure :returns: a baseline measure ...
[ "def", "asbaseline", "(", "self", ",", "pos", ")", ":", "if", "not", "is_measure", "(", "pos", ")", "or", "pos", "[", "'type'", "]", "not", "in", "[", "'position'", ",", "'baseline'", "]", ":", "raise", "TypeError", "(", "'Argument is not a position/baseli...
40.6875
16.625
def driver(self): """Returns a Selenium WebDriver instance of the type requested in the configuration.""" from dallinger.config import get_config config = get_config() if not config.ready: config.load() driver_url = config.get("webdriver_url", None) d...
[ "def", "driver", "(", "self", ")", ":", "from", "dallinger", ".", "config", "import", "get_config", "config", "=", "get_config", "(", ")", "if", "not", "config", ".", "ready", ":", "config", ".", "load", "(", ")", "driver_url", "=", "config", ".", "get...
35.71875
18.90625
def getdef(self, defname, tag='*'): """Return definition element with name *defname*""" if defname.startswith('a:'): defname = defname[2:] for xsd in self.__xsd_trees: xpath = "./%s[@name='%s']" % (tag, defname) elements = xsd.xpath(xpath) if eleme...
[ "def", "getdef", "(", "self", ",", "defname", ",", "tag", "=", "'*'", ")", ":", "if", "defname", ".", "startswith", "(", "'a:'", ")", ":", "defname", "=", "defname", "[", "2", ":", "]", "for", "xsd", "in", "self", ".", "__xsd_trees", ":", "xpath", ...
41.7
8.4
def _load_fits(self, h5file): """ Loads fits from h5file and returns a dictionary of fits. """ fits = {} for key in ['mf']: fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file) for key in ['chif', 'vf']: fits[key] = self._load_vector_fit(key, h5file) ...
[ "def", "_load_fits", "(", "self", ",", "h5file", ")", ":", "fits", "=", "{", "}", "for", "key", "in", "[", "'mf'", "]", ":", "fits", "[", "key", "]", "=", "self", ".", "_load_scalar_fit", "(", "fit_key", "=", "key", ",", "h5file", "=", "h5file", ...
41
15.75
def _apply_local_transforms(p, ts): """ Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits) and a list of assignment probability matrices (one for each bit in the readout, ordered like the inner axis of results) apply local 2x2 matrices to each bit index. ...
[ "def", "_apply_local_transforms", "(", "p", ",", "ts", ")", ":", "p_corrected", "=", "_bitstring_probs_by_qubit", "(", "p", ")", "nq", "=", "p_corrected", ".", "ndim", "for", "idx", ",", "trafo_idx", "in", "enumerate", "(", "ts", ")", ":", "# this contractio...
44.516129
30.193548
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout): """Submit all the jobs in job_dict """ if link is None: return JobStatus.no_job if job_dict is None: job_keys = link.jobs.keys() else: job_keys = sorted(job_dict.keys()) ...
[ "def", "submit_jobs", "(", "self", ",", "link", ",", "job_dict", "=", "None", ",", "job_archive", "=", "None", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "if", "link", "is", "None", ":", "return", "JobStatus", ".", "no_job", "if", "job_dict", ...
38.171875
17.609375
def batch_snapshot(self, read_timestamp=None, exact_staleness=None): """Return an object which wraps a batch read / query. :type read_timestamp: :class:`datetime.datetime` :param read_timestamp: Execute all reads at the given timestamp. :type exact_staleness: :class:`datetime.timedelta...
[ "def", "batch_snapshot", "(", "self", ",", "read_timestamp", "=", "None", ",", "exact_staleness", "=", "None", ")", ":", "return", "BatchSnapshot", "(", "self", ",", "read_timestamp", "=", "read_timestamp", ",", "exact_staleness", "=", "exact_staleness", ")" ]
42.0625
24.1875
def get_bgp_config(self, group="", neighbor=""): """ Parse BGP config params into a dict :param group='': :param neighbor='': """ bgp_config = {} def build_prefix_limit(af_table, limit, prefix_percent, prefix_timeout): prefix_limit = {} ...
[ "def", "get_bgp_config", "(", "self", ",", "group", "=", "\"\"", ",", "neighbor", "=", "\"\"", ")", ":", "bgp_config", "=", "{", "}", "def", "build_prefix_limit", "(", "af_table", ",", "limit", ",", "prefix_percent", ",", "prefix_timeout", ")", ":", "prefi...
41.293878
18.004082
def _maybe_validate_shape_override(self, override_shape, base_is_scalar, validate_args, name): """Helper to __init__ which ensures override batch/event_shape are valid.""" if override_shape is None: override_shape = [] override_shape = tf.convert_to_tensor( ...
[ "def", "_maybe_validate_shape_override", "(", "self", ",", "override_shape", ",", "base_is_scalar", ",", "validate_args", ",", "name", ")", ":", "if", "override_shape", "is", "None", ":", "override_shape", "=", "[", "]", "override_shape", "=", "tf", ".", "conver...
38.150943
20.113208
def encodeIntoArray(self, input, output,learn=None): """ [overrides nupic.encoders.scalar.ScalarEncoder.encodeIntoArray] """ self.recordNum +=1 if learn is None: learn = self._learningEnabled if input == SENTINEL_VALUE_FOR_MISSING_DATA: output[0:self.n] = 0 elif not math.isnan...
[ "def", "encodeIntoArray", "(", "self", ",", "input", ",", "output", ",", "learn", "=", "None", ")", ":", "self", ".", "recordNum", "+=", "1", "if", "learn", "is", "None", ":", "learn", "=", "self", ".", "_learningEnabled", "if", "input", "==", "SENTINE...
30.357143
15.785714
def position_from_bundle(self, bundle): """[DEPRECATED] Return position, given the `coefficient_bundle()` return value.""" coefficients, days_per_set, T, twot1 = bundle return (T.T * coefficients).sum(axis=2)
[ "def", "position_from_bundle", "(", "self", ",", "bundle", ")", ":", "coefficients", ",", "days_per_set", ",", "T", ",", "twot1", "=", "bundle", "return", "(", "T", ".", "T", "*", "coefficients", ")", ".", "sum", "(", "axis", "=", "2", ")" ]
45.8
12.2
def value_for_key(membersuite_object_data, key): """Return the value for `key` of membersuite_object_data. """ key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
[ "def", "value_for_key", "(", "membersuite_object_data", ",", "key", ")", ":", "key_value_dicts", "=", "{", "d", "[", "'Key'", "]", ":", "d", "[", "'Value'", "]", "for", "d", "in", "membersuite_object_data", "[", "\"Fields\"", "]", "[", "\"KeyValueOfstringanyTy...
39.428571
10.285714
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
[ "def", "encipher_shift", "(", "plaintext", ",", "plain_vocab", ",", "shift", ")", ":", "ciphertext", "=", "[", "]", "cipher", "=", "ShiftEncryptionLayer", "(", "plain_vocab", ",", "shift", ")", "for", "_", ",", "sentence", "in", "enumerate", "(", "plaintext"...
34.809524
19.333333
def ok(self, data, schema=None, envelope=None): """ Gets a 200 response with the specified data. :param data: The content value. :param schema: The schema to serialize the data. :param envelope: The key used to envelope the data. :return: A Flask response object. ...
[ "def", "ok", "(", "self", ",", "data", ",", "schema", "=", "None", ",", "envelope", "=", "None", ")", ":", "data", "=", "marshal", "(", "data", ",", "schema", ",", "envelope", ")", "return", "self", ".", "__make_response", "(", "data", ")" ]
33.583333
11.916667
def is_powered_on(self): """ Get power status of device. The set-top box can't explicitly powered on or powered off the device. The power can only be toggled. To find out the power status of the device a little trick is used. When the set-top box is powered a web server is runn...
[ "def", "is_powered_on", "(", "self", ")", ":", "host", "=", "'{0}:62137'", ".", "format", "(", "self", ".", "ip", ")", "try", ":", "HTTPConnection", "(", "host", ",", "timeout", "=", "2", ")", ".", "request", "(", "'GET'", ",", "'/DeviceDescription.xml'"...
39.12
22.96
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'id'", ")", "and", "self", ".", "id", "is", "not", "None", ":", "_dict", "[", "'id'", "]", "=", "self", ".", "id", "return", "_dict" ]
34.666667
14.166667
def _addDataFile(self, filename): """ Given a filename, add it to the graph """ if filename.endswith('.ttl'): self._rdfGraph.parse(filename, format='n3') else: self._rdfGraph.parse(filename, format='xml')
[ "def", "_addDataFile", "(", "self", ",", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "'.ttl'", ")", ":", "self", ".", "_rdfGraph", ".", "parse", "(", "filename", ",", "format", "=", "'n3'", ")", "else", ":", "self", ".", "_rdfGraph", ...
32.625
9.125
def get_custom_query(self): """Extracts custom query keys from the index. Parameters which get extracted from the request: `q`: Passes the value to the `SearchableText` `path`: Creates a path query `recent_created`: Creates a date query `recent_modified`...
[ "def", "get_custom_query", "(", "self", ")", ":", "query", "=", "{", "}", "# searchable text queries", "q", "=", "req", ".", "get_query", "(", ")", "if", "q", ":", "query", "[", "\"SearchableText\"", "]", "=", "q", "# physical path queries", "path", "=", "...
31.564103
19.25641
def parse_name_and_version(p): """ A utility method used to get name and version from a string. From e.g. a Provides-Dist value. :param p: A value in a form 'foo (1.0)' :return: The name and version as a tuple. """ m = NAME_VERSION_RE.match(p) if not m: raise DistlibException('...
[ "def", "parse_name_and_version", "(", "p", ")", ":", "m", "=", "NAME_VERSION_RE", ".", "match", "(", "p", ")", "if", "not", "m", ":", "raise", "DistlibException", "(", "'Ill-formed name/version string: \\'%s\\''", "%", "p", ")", "d", "=", "m", ".", "groupdic...
30
15.857143
def prep_folder(self, seq): """Take in a sequence string and prepares the folder for the I-TASSER run.""" itasser_dir = op.join(self.root_dir, self.id) if not op.exists(itasser_dir): os.makedirs(itasser_dir) tmp = {self.id: seq} fasta.write_fasta_file_from_dict(ind...
[ "def", "prep_folder", "(", "self", ",", "seq", ")", ":", "itasser_dir", "=", "op", ".", "join", "(", "self", ".", "root_dir", ",", "self", ".", "id", ")", "if", "not", "op", ".", "exists", "(", "itasser_dir", ")", ":", "os", ".", "makedirs", "(", ...
36.928571
17.285714
def index(self, item): """Finds the child index of a given item, searchs in added order.""" index_at = None for (i, child) in enumerate(self._children): if child.item == item: index_at = i break if index_at is None: raise ValueError...
[ "def", "index", "(", "self", ",", "item", ")", ":", "index_at", "=", "None", "for", "(", "i", ",", "child", ")", "in", "enumerate", "(", "self", ".", "_children", ")", ":", "if", "child", ".", "item", "==", "item", ":", "index_at", "=", "i", "bre...
38
14.6
def get_keys_from_class(cc): """Return list of the key property names for a class """ return [prop.name for prop in cc.properties.values() \ if 'key' in prop.qualifiers]
[ "def", "get_keys_from_class", "(", "cc", ")", ":", "return", "[", "prop", ".", "name", "for", "prop", "in", "cc", ".", "properties", ".", "values", "(", ")", "if", "'key'", "in", "prop", ".", "qualifiers", "]" ]
46.5
7.5
def createSessionForKey(self, key, user): """ Create a persistent session in the database. @type key: L{bytes} @param key: The persistent session identifier. @type user: L{bytes} @param user: The username the session will belong to. """ PersistentSession...
[ "def", "createSessionForKey", "(", "self", ",", "key", ",", "user", ")", ":", "PersistentSession", "(", "store", "=", "self", ".", "store", ",", "sessionKey", "=", "key", ",", "authenticatedAs", "=", "user", ")" ]
28.571429
14.142857
def cancel(self): """Return a deferred.""" d = self.request('post', self.instance_url() + '/cancel') return d.addCallback(self.refresh_from)
[ "def", "cancel", "(", "self", ")", ":", "d", "=", "self", ".", "request", "(", "'post'", ",", "self", ".", "instance_url", "(", ")", "+", "'/cancel'", ")", "return", "d", ".", "addCallback", "(", "self", ".", "refresh_from", ")" ]
40.25
13.75
def measure_states(states, measurement_matrix, measurement_covariance): """ Measure a list of states with a measurement matrix in the presence of measurement noise. Args: states (array): states to measure. Shape is NxSTATE_DIM. measurement_matrix (array): Each state in *states* is measu...
[ "def", "measure_states", "(", "states", ",", "measurement_matrix", ",", "measurement_covariance", ")", ":", "# Sanitise input", "measurement_matrix", "=", "np", ".", "atleast_2d", "(", "measurement_matrix", ")", "measurement_covariance", "=", "np", ".", "atleast_2d", ...
39.157895
24.210526
def __calculate_cluster_difference(self, index_cluster, difference): """! @brief Calculates distance from each object in specified cluster to specified object. @param[in] index_point (uint): Index point for which difference is calculated. @return (list) Distance from specified ob...
[ "def", "__calculate_cluster_difference", "(", "self", ",", "index_cluster", ",", "difference", ")", ":", "cluster_difference", "=", "0.0", "for", "index_point", "in", "self", ".", "__clusters", "[", "index_cluster", "]", ":", "cluster_difference", "+=", "difference"...
40.642857
28.857143
def _find_navigation_coefs(self): """Find navigation coefficients for the current time The navigation Chebyshev coefficients are only valid for a certain time interval. The header entry SatelliteStatus/Orbit/OrbitPolynomial contains multiple coefficients for multiple time intervals. Find the ...
[ "def", "_find_navigation_coefs", "(", "self", ")", ":", "# Find index of interval enclosing the nominal timestamp of the scan", "time", "=", "np", ".", "datetime64", "(", "self", ".", "prologue", "[", "'ImageAcquisition'", "]", "[", "'PlannedAcquisitionTime'", "]", "[", ...
61.526316
37.894737
def estimateNormal(sampleData, performLowerBoundCheck=True): """ :param sampleData: :type sampleData: Numpy array. :param performLowerBoundCheck: :type performLowerBoundCheck: bool :returns: A dict containing the parameters of a normal distribution based on the ``sampleData``. """ params = { "...
[ "def", "estimateNormal", "(", "sampleData", ",", "performLowerBoundCheck", "=", "True", ")", ":", "params", "=", "{", "\"name\"", ":", "\"normal\"", ",", "\"mean\"", ":", "numpy", ".", "mean", "(", "sampleData", ")", ",", "\"variance\"", ":", "numpy", ".", ...
30.484848
19.939394
def get_all_images(self, image_ids=None, owners=None, executable_by=None, filters=None): """ Retrieve all the EC2 images available on your account. :type image_ids: list :param image_ids: A list of strings with the image IDs wanted :type owners: list ...
[ "def", "get_all_images", "(", "self", ",", "image_ids", "=", "None", ",", "owners", "=", "None", ",", "executable_by", "=", "None", ",", "filters", "=", "None", ")", ":", "params", "=", "{", "}", "if", "image_ids", ":", "self", ".", "build_list_params", ...
40.769231
21.076923
def _get_template(settings): """ Prompt user to pick template from a list. """ puts("\nPick a template\n") template = None while not template: _list_templates(settings) index = raw_input("\nWhich template would you like to use? [1] ") if not index: index = "1"...
[ "def", "_get_template", "(", "settings", ")", ":", "puts", "(", "\"\\nPick a template\\n\"", ")", "template", "=", "None", "while", "not", "template", ":", "_list_templates", "(", "settings", ")", "index", "=", "raw_input", "(", "\"\\nWhich template would you like t...
31.705882
17.352941
def private_key_to_address(private_key: Union[str, bytes]) -> ChecksumAddress: """ Converts a private key to an Ethereum address. """ if isinstance(private_key, str): private_key_bytes = to_bytes(hexstr=private_key) else: private_key_bytes = private_key pk = PrivateKey(private_key_bytes)...
[ "def", "private_key_to_address", "(", "private_key", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "ChecksumAddress", ":", "if", "isinstance", "(", "private_key", ",", "str", ")", ":", "private_key_bytes", "=", "to_bytes", "(", "hexstr", "=", "priv...
45.125
12.375
def print_table(self, stream=sys.stdout, filter_function=None): """ A pretty ASCII printer for the periodic table, based on some filter_function. Args: stream: file-like object filter_function: A filtering function that take a Pseudo as input and returns ...
[ "def", "print_table", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ",", "filter_function", "=", "None", ")", ":", "print", "(", "self", ".", "to_table", "(", "filter_function", "=", "filter_function", ")", ",", "file", "=", "stream", ")" ]
47.25
25.916667
def build_reduce(function: Callable[[Any, Any], Any] = None, *, init: Any = NONE): """ Decorator to wrap a function to return a Reduce operator. :param function: function to be wrapped :param init: optional initialization for state """ _init = init def _build_reduce(function: ...
[ "def", "build_reduce", "(", "function", ":", "Callable", "[", "[", "Any", ",", "Any", "]", ",", "Any", "]", "=", "None", ",", "*", ",", "init", ":", "Any", "=", "NONE", ")", ":", "_init", "=", "init", "def", "_build_reduce", "(", "function", ":", ...
31.590909
17.045455
def new_deploy(py_ver: PyVer, release_target: ReleaseTarget): """Job for deploying package to pypi""" cache_file = f'app_{py_ver.name}.tar' template = yaml.safe_load(f""" machine: image: circleci/classic:201710-02 steps: - attach_workspace: at: {cache_dir} - checkout ...
[ "def", "new_deploy", "(", "py_ver", ":", "PyVer", ",", "release_target", ":", "ReleaseTarget", ")", ":", "cache_file", "=", "f'app_{py_ver.name}.tar'", "template", "=", "yaml", ".", "safe_load", "(", "f\"\"\"\n machine:\n image: circleci/classic:201710-02\n steps...
36.547619
16.952381
def merge_dictionary(dst, src, extend_lists=False): """Recursively merge two dicts. Hashes at the root level are NOT overwritten. This can be used to merge two dicts using deep key evaluation (with support for merging lists as well). There is also logic to handle placeholders (`None`) in lists as docu...
[ "def", "merge_dictionary", "(", "dst", ",", "src", ",", "extend_lists", "=", "False", ")", ":", "stack", "=", "[", "(", "dst", ",", "src", ")", "]", "while", "stack", ":", "current_dst", ",", "current_src", "=", "stack", ".", "pop", "(", ")", "for", ...
37.413793
20.586207
def _query_nsot(url, headers, device=None): ''' if a device is given, query nsot for that specific device, otherwise return all devices :param url: str :param headers: dict :param device: None or str :return: ''' url = urlparse.urljoin(url, 'devices') ret = {} if not device:...
[ "def", "_query_nsot", "(", "url", ",", "headers", ",", "device", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "url", ",", "'devices'", ")", "ret", "=", "{", "}", "if", "not", "device", ":", "query", "=", "salt", ".", "utils",...
28.48
23.2
def failure_format_traceback(self, fail): """ :param fail: must be an IFailedFuture returns a string """ try: f = six.StringIO() traceback.print_exception( fail._type, fail.value, fail._traceback, ...
[ "def", "failure_format_traceback", "(", "self", ",", "fail", ")", ":", "try", ":", "f", "=", "six", ".", "StringIO", "(", ")", "traceback", ".", "print_exception", "(", "fail", ".", "_type", ",", "fail", ".", "value", ",", "fail", ".", "_traceback", ",...
29.3125
12.6875
def threshold_absolute(W, thr, copy=True): ''' This function thresholds the connectivity matrix by absolute weight magnitude. All weights below the given threshold, and all weights on the main diagonal (self-self connections) are set to 0. If copy is not set, this function will *modify W in place.*...
[ "def", "threshold_absolute", "(", "W", ",", "thr", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "W", "=", "W", ".", "copy", "(", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0", ")", "# clear diagonal", "W", "[", "W", "<", "thr", ...
28
22.571429
def set_header_info(self, r_free, r_work, resolution, title, deposition_date, release_date, experimental_methods): """Sets the header information. :param r_free: the measured R-Free for the structure :param r_work: the measure R-Work for the structure :param resol...
[ "def", "set_header_info", "(", "self", ",", "r_free", ",", "r_work", ",", "resolution", ",", "title", ",", "deposition_date", ",", "release_date", ",", "experimental_methods", ")", ":", "self", ".", "r_free", "=", "r_free", "self", ".", "r_work", "=", "r_wor...
49.333333
15.666667
def parse_script_interpreter(source): """ Parse the script interpreter portion of a UNIX hashbang using the rules Linux uses. :param str source: String like "/usr/bin/env python". :returns: Tuple of `(interpreter, arg)`, where `intepreter` is the script interpreter and `arg` is its...
[ "def", "parse_script_interpreter", "(", "source", ")", ":", "# Find terminating newline. Assume last byte of binprm_buf if absent.", "nl", "=", "source", ".", "find", "(", "b'\\n'", ",", "0", ",", "128", ")", "if", "nl", "==", "-", "1", ":", "nl", "=", "min", ...
36.869565
20.956522
def run_nupack(kwargs): '''Run picklable Nupack command. :param kwargs: keyword arguments to pass to Nupack as well as 'cmd'. :returns: Variable - whatever `cmd` returns. ''' run = NUPACK(kwargs['seq']) output = getattr(run, kwargs['cmd'])(**kwargs['arguments']) return output
[ "def", "run_nupack", "(", "kwargs", ")", ":", "run", "=", "NUPACK", "(", "kwargs", "[", "'seq'", "]", ")", "output", "=", "getattr", "(", "run", ",", "kwargs", "[", "'cmd'", "]", ")", "(", "*", "*", "kwargs", "[", "'arguments'", "]", ")", "return",...
29.7
22.9
def _async_raise(tid, exctype): """ raises the exception, performs cleanup if needed 参考: https://www.oschina.net/question/172446_2159505 """ tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes....
[ "def", "_async_raise", "(", "tid", ",", "exctype", ")", ":", "tid", "=", "ctypes", ".", "c_long", "(", "tid", ")", "if", "not", "inspect", ".", "isclass", "(", "exctype", ")", ":", "exctype", "=", "type", "(", "exctype", ")", "res", "=", "ctypes", ...
45.764706
15.058824
def process_data(self, stream, metadata): """ Extract the tabulated data from the input file. Parameters ---------- stream : Streamlike object A Streamlike object (nominally StringIO) containing the table to be extracted metadata : dict ...
[ "def", "process_data", "(", "self", ",", "stream", ",", "metadata", ")", ":", "ch", ",", "metadata", "=", "self", ".", "_get_column_headers_and_update_metadata", "(", "stream", ",", "metadata", ")", "df", "=", "self", ".", "_convert_data_block_and_headers_to_df", ...
35
20.478261
async def StatusHistory(self, requests): ''' requests : typing.Sequence[~StatusHistoryRequest] Returns -> typing.Sequence[~StatusHistoryResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='StatusHistory', ...
[ "async", "def", "StatusHistory", "(", "self", ",", "requests", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Client'", ",", "request", "=", "'StatusHistory'", ",", "version", "=", "2", "...
33.357143
11.785714
def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces()
[ "def", "interfaces", "(", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "return", "win_interfaces", "(", ")", "elif", "salt", ".", "utils", ".", "platform", ".", "is_netbsd", "(", ")", ":", "return", "netbsd_i...
29.6
18
def write_output(self): """ Write the Playbook output variables. """ # output self.tcex.log.debug('output_strings: {}'.format(self.output_strings)) self.tcex.playbook.create_output('string.operation', self.args.tc_action) self.tcex.playbook.create_output('string.outputs', self.o...
[ "def", "write_output", "(", "self", ")", ":", "# output", "self", ".", "tcex", ".", "log", ".", "debug", "(", "'output_strings: {}'", ".", "format", "(", "self", ".", "output_strings", ")", ")", "self", ".", "tcex", ".", "playbook", ".", "create_output", ...
53.7
30.5
def clear_boxes(self): """ Clear all boxes """ self.tmin_box.Clear() self.tmin_box.SetItems(self.T_list) self.tmin_box.SetSelection(-1) self.tmax_box.Clear() self.tmax_box.SetItems(self.T_list) self.tmax_box.SetSelection(-1) self.Blab_win...
[ "def", "clear_boxes", "(", "self", ")", ":", "self", ".", "tmin_box", ".", "Clear", "(", ")", "self", ".", "tmin_box", ".", "SetItems", "(", "self", ".", "T_list", ")", "self", ".", "tmin_box", ".", "SetSelection", "(", "-", "1", ")", "self", ".", ...
44.282051
19.769231
def jsonarrlen(self, name, path=Path.rootPath()): """ Returns the length of the array JSON value under ``path`` at key ``name`` """ return self.execute_command('JSON.ARRLEN', name, str_path(path))
[ "def", "jsonarrlen", "(", "self", ",", "name", ",", "path", "=", "Path", ".", "rootPath", "(", ")", ")", ":", "return", "self", ".", "execute_command", "(", "'JSON.ARRLEN'", ",", "name", ",", "str_path", "(", "path", ")", ")" ]
38.5
16.166667
def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False): """ Lists containers on the Docker remote host, similar to ``docker ps``. :param list_all: Shows all containers. Default is ``False``, which omits exited containers. :type list_all: bool :param short_image: Hides ...
[ "def", "list_containers", "(", "list_all", "=", "True", ",", "short_image", "=", "True", ",", "full_ids", "=", "False", ",", "full_cmd", "=", "False", ")", ":", "containers", "=", "docker_fabric", "(", ")", ".", "containers", "(", "all", "=", "list_all", ...
55.133333
33
def save(self, filename=None, clean_data=False, raw=False, trash=False): """ This will save the data to a filename :param clean_data: func call that will clean the data before saving it :param raw: obj of the return object from request :param trash: bool if true puts ...
[ "def", "save", "(", "self", ",", "filename", "=", "None", ",", "clean_data", "=", "False", ",", "raw", "=", "False", ",", "trash", "=", "False", ")", ":", "full_path", "=", "get_filename", "(", "filename", "or", "self", ".", "filename", "or", "self", ...
42
18.181818
def get_failed_enrollment_message(cls, users, enrolled_in): """ Create message for the users who were not able to be enrolled in a course or program. Args: users: An iterable of users who were not successfully enrolled enrolled_in (str): A string identifier for the cours...
[ "def", "get_failed_enrollment_message", "(", "cls", ",", "users", ",", "enrolled_in", ")", ":", "failed_emails", "=", "[", "user", ".", "email", "for", "user", "in", "users", "]", "return", "(", "'error'", ",", "_", "(", "'The following learners could not be enr...
37.428571
26.666667
def mimebundle_to_html(bundle): """ Converts a MIME bundle into HTML. """ if isinstance(bundle, tuple): data, metadata = bundle else: data = bundle html = data.get('text/html', '') if 'application/javascript' in data: js = data['application/javascript'] html +...
[ "def", "mimebundle_to_html", "(", "bundle", ")", ":", "if", "isinstance", "(", "bundle", ",", "tuple", ")", ":", "data", ",", "metadata", "=", "bundle", "else", ":", "data", "=", "bundle", "html", "=", "data", ".", "get", "(", "'text/html'", ",", "''",...
30.384615
11.923077
def gen_to_dev(self, address): """Generic address to device address""" cmd = ["nvm_addr gen2dev", self.envs["DEV_PATH"], "0x{:x}".format(address)] status, stdout, _ = cij.ssh.command(cmd, shell=True) if status: raise RuntimeError("cij.liblight.gen_to_dev: cmd fail") ...
[ "def", "gen_to_dev", "(", "self", ",", "address", ")", ":", "cmd", "=", "[", "\"nvm_addr gen2dev\"", ",", "self", ".", "envs", "[", "\"DEV_PATH\"", "]", ",", "\"0x{:x}\"", ".", "format", "(", "address", ")", "]", "status", ",", "stdout", ",", "_", "=",...
46.5
23.625
def parse_type(source: SourceType, **options: dict) -> TypeNode: """Parse the AST for a given string containing a GraphQL Type. Throws GraphQLError if a syntax error is encountered. This is useful within tools that operate upon GraphQL Types directly and in isolation of complete GraphQL documents. ...
[ "def", "parse_type", "(", "source", ":", "SourceType", ",", "*", "*", "options", ":", "dict", ")", "->", "TypeNode", ":", "if", "isinstance", "(", "source", ",", "str", ")", ":", "source", "=", "Source", "(", "source", ")", "lexer", "=", "Lexer", "("...
36.705882
17.235294
def jtype(c): """ Return the a string with the data type of a value, for JSON data """ ct = c['type'] return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))
[ "def", "jtype", "(", "c", ")", ":", "ct", "=", "c", "[", "'type'", "]", "return", "ct", "if", "ct", "!=", "'literal'", "else", "'{}, {}'", ".", "format", "(", "ct", ",", "c", ".", "get", "(", "'xml:lang'", ")", ")" ]
31.5
18.833333
def connect(self, servers=["nats://127.0.0.1:4222"], loop=None, # 'io_loop' and 'loop' are the same, but we have # both params to be consistent with asyncio client. io_loop=None, # Event Callbacks error_cb=N...
[ "def", "connect", "(", "self", ",", "servers", "=", "[", "\"nats://127.0.0.1:4222\"", "]", ",", "loop", "=", "None", ",", "# 'io_loop' and 'loop' are the same, but we have", "# both params to be consistent with asyncio client.", "io_loop", "=", "None", ",", "# Event Callbac...
38.79021
17.20979
def surf_z(data, name): """Surface plot of the quasiparticle weight as fuction of U/D and dop""" from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter fig = plt.figure() ax = fig.gca(projection='3d') dop, u_int = n...
[ "def", "surf_z", "(", "data", ",", "name", ")", ":", "from", "mpl_toolkits", ".", "mplot3d", "import", "Axes3D", "from", "matplotlib", "import", "cm", "from", "matplotlib", ".", "ticker", "import", "LinearLocator", ",", "FormatStrFormatter", "fig", "=", "plt",...
34.928571
20.5
def cli(env, identifier, price=False, guests=False): """Get details for a virtual server.""" dhost = SoftLayer.DedicatedHostManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' result = dhost.get_host(identifier) resul...
[ "def", "cli", "(", "env", ",", "identifier", ",", "price", "=", "False", ",", "guests", "=", "False", ")", ":", "dhost", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "KeyValueTable", "(",...
42.955556
20.533333
def _create(cls, repo, path, resolve, reference, force, logmsg=None): """internal method used to create a new symbolic reference. If resolve is False, the reference will be taken as is, creating a proper symbolic reference. Otherwise it will be resolved to the corresponding object and a ...
[ "def", "_create", "(", "cls", ",", "repo", ",", "path", ",", "resolve", ",", "reference", ",", "force", ",", "logmsg", "=", "None", ")", ":", "git_dir", "=", "_git_dir", "(", "repo", ",", "path", ")", "full_ref_path", "=", "cls", ".", "to_full_path", ...
43.967742
17.612903
def get_config_variable(self, config_id, offset): """Get a chunk of a config variable's value.""" config = self._config_variables.get(config_id) if config is None: return [b""] return [bytes(config.current_value[offset:offset + 20])]
[ "def", "get_config_variable", "(", "self", ",", "config_id", ",", "offset", ")", ":", "config", "=", "self", ".", "_config_variables", ".", "get", "(", "config_id", ")", "if", "config", "is", "None", ":", "return", "[", "b\"\"", "]", "return", "[", "byte...
34
19.625
def windowed_tajima_d(pos, ac, size=None, start=None, stop=None, step=None, windows=None, min_sites=3): """Calculate the value of Tajima's D in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int, shape (n_items,) Variant positions, usi...
[ "def", "windowed_tajima_d", "(", "pos", ",", "ac", ",", "size", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", "windows", "=", "None", ",", "min_sites", "=", "3", ")", ":", "# check inputs", "if", "...
35.336449
18.831776
def code_almost_equal(a, b): """Return True if code is similar. Ignore whitespace when comparing specific line. """ split_a = split_and_strip_non_empty_lines(a) split_b = split_and_strip_non_empty_lines(b) if len(split_a) != len(split_b): return False for (index, _) in enumerate(...
[ "def", "code_almost_equal", "(", "a", ",", "b", ")", ":", "split_a", "=", "split_and_strip_non_empty_lines", "(", "a", ")", "split_b", "=", "split_and_strip_non_empty_lines", "(", "b", ")", "if", "len", "(", "split_a", ")", "!=", "len", "(", "split_b", ")", ...
25.529412
20.176471
def get_sound(self, title, group): ''' Retrieve sound @title from group @group. ''' return self.sounds[group.lower()][title.lower()]
[ "def", "get_sound", "(", "self", ",", "title", ",", "group", ")", ":", "return", "self", ".", "sounds", "[", "group", ".", "lower", "(", ")", "]", "[", "title", ".", "lower", "(", ")", "]" ]
32
17.6
def extract_facts(rule): """Given a rule, return a set containing all rule LHS facts.""" def _extract_facts(ce): if isinstance(ce, Fact): yield ce elif isinstance(ce, TEST): pass else: for e in ce: yield from _extract_facts(e) retu...
[ "def", "extract_facts", "(", "rule", ")", ":", "def", "_extract_facts", "(", "ce", ")", ":", "if", "isinstance", "(", "ce", ",", "Fact", ")", ":", "yield", "ce", "elif", "isinstance", "(", "ce", ",", "TEST", ")", ":", "pass", "else", ":", "for", "e...
28.083333
14.833333
def quoter(obj): """Return a Quoted URL. The quote function will return a URL encoded string. If there is an exception in the job which results in a "KeyError" the original string will be returned as it will be assumed to already be URL encoded. :param obj: ``basestring`` :return: ``str``...
[ "def", "quoter", "(", "obj", ")", ":", "try", ":", "try", ":", "return", "urllib", ".", "quote", "(", "obj", ")", "except", "AttributeError", ":", "return", "urllib", ".", "parse", ".", "quote", "(", "obj", ")", "except", "KeyError", ":", "return", "...
25.473684
21.368421
def parse_args(arguments, wrapper_kwargs={}): """ MMI Runner """ # make a socket that replies to message with the grid # if we are running mpi we want to know the rank args = {} positional = [ 'engine', 'configfile', ] for key in positional: args[key] = argum...
[ "def", "parse_args", "(", "arguments", ",", "wrapper_kwargs", "=", "{", "}", ")", ":", "# make a socket that replies to message with the grid", "# if we are running mpi we want to know the rank", "args", "=", "{", "}", "positional", "=", "[", "'engine'", ",", "'configfile...
26.482759
17.448276
def from_auto_dict(values, source='auto'): ''' Pass an entire dictionary to from_auto .. note:: The key will be passed as the name ''' for name, value in values.items(): values[name] = from_auto(name, value, source) return values
[ "def", "from_auto_dict", "(", "values", ",", "source", "=", "'auto'", ")", ":", "for", "name", ",", "value", "in", "values", ".", "items", "(", ")", ":", "values", "[", "name", "]", "=", "from_auto", "(", "name", ",", "value", ",", "source", ")", "...
21.75
21.416667
def make_ica_funs(observed_dimension, latent_dimension): """These functions implement independent component analysis. The model is: latents are drawn i.i.d. for each data point from a product of student-ts. weights are the same across all datapoints. each data = latents * weghts + noise.""" de...
[ "def", "make_ica_funs", "(", "observed_dimension", ",", "latent_dimension", ")", ":", "def", "sample", "(", "weights", ",", "n_samples", ",", "noise_std", ",", "rs", ")", ":", "latents", "=", "rs", ".", "randn", "(", "latent_dimension", ",", "n_samples", ")"...
38.517241
21.206897
def replace_country_by_id(cls, country_id, country, **kwargs): """Replace Country Replace all attributes of Country This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_country_by_id(countr...
[ "def", "replace_country_by_id", "(", "cls", ",", "country_id", ",", "country", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_r...
44.181818
21.681818
def _get_relative_base_path(filename, path_to_check): """Extracts the relative mod path of the file to import from Check if a file is within the passed in path and if so, returns the relative mod path from the one passed in. If the filename is no in path_to_check, returns None Note this function ...
[ "def", "_get_relative_base_path", "(", "filename", ",", "path_to_check", ")", ":", "importable_path", "=", "None", "path_to_check", "=", "os", ".", "path", ".", "normcase", "(", "path_to_check", ")", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(",...
38.125
21.28125
def backward(self, out_grads=None): """Backward computation.""" assert self.binded and self.params_initialized self._curr_module.backward(out_grads=out_grads)
[ "def", "backward", "(", "self", ",", "out_grads", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "self", ".", "_curr_module", ".", "backward", "(", "out_grads", "=", "out_grads", ")" ]
44.75
8.5
def sync(self): """ Send and fetch all outstanding messages. :return: 2-tuple of number of detail messages and number of summary messages fetched """ self.send() detail_count = summary_count = 0 while self.responses: response = self.responses[0] w...
[ "def", "sync", "(", "self", ")", ":", "self", ".", "send", "(", ")", "detail_count", "=", "summary_count", "=", "0", "while", "self", ".", "responses", ":", "response", "=", "self", ".", "responses", "[", "0", "]", "while", "not", "response", ".", "c...
37.714286
12.785714
def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
[ "def", "index_iterator", "(", "self", ")", ":", "idx", "=", "0", "# index", "while", "idx", "<", "self", ".", "number_intervals", ":", "new_idx", "=", "yield", "idx", "idx", "+=", "1", "if", "new_idx", ":", "idx", "=", "new_idx", "-", "1" ]
29.6
12.2