text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def read_data_from_bytes(fileContent): """ Takes the binary data stored in the binary string provided and extracts the data for each channel that was saved, along with the sample rate and length of the data array. Parameters ---------- fileContent : bytes bytes object containing t...
[ "def", "read_data_from_bytes", "(", "fileContent", ")", ":", "TotalDataLen", "=", "struct", ".", "unpack", "(", "'Q'", ",", "fileContent", "[", ":", "8", "]", ")", "[", "0", "]", "# Unsigned long long ", "NumOfChannels", "=", "struct", ".", "unpack", "(", ...
37.578947
25.105263
def convert_fig_elements(self): """ Responsible for the correct conversion of JPTS 3.0 <fig> elements to EPUB xhtml. Aside from translating <fig> to <img>, the content model must be edited. """ for fig in self.main.getroot().findall('.//fig'): if fig.getparent...
[ "def", "convert_fig_elements", "(", "self", ")", ":", "for", "fig", "in", "self", ".", "main", ".", "getroot", "(", ")", ".", "findall", "(", "'.//fig'", ")", ":", "if", "fig", ".", "getparent", "(", ")", ".", "tag", "==", "'p'", ":", "elevate_elemen...
49.142857
17.755102
def _load_machines_cache(self): """This method should fill up `_machines_cache` from scratch. It could happen only in two cases: 1. During class initialization 2. When all etcd members failed""" self._update_machines_cache = True if 'srv' not in self._config and 'host' ...
[ "def", "_load_machines_cache", "(", "self", ")", ":", "self", ".", "_update_machines_cache", "=", "True", "if", "'srv'", "not", "in", "self", ".", "_config", "and", "'host'", "not", "in", "self", ".", "_config", "and", "'hosts'", "not", "in", "self", ".", ...
41.304348
22.652174
def count_countries(publishingCountry, **kwargs): ''' Lists occurrence counts for all countries covered by the data published by the given country :param publishingCountry: [str] A two letter country code :return: dict Usage:: from pygbif import occurrences occurrences.co...
[ "def", "count_countries", "(", "publishingCountry", ",", "*", "*", "kwargs", ")", ":", "url", "=", "gbif_baseurl", "+", "'occurrence/counts/countries'", "out", "=", "gbif_GET", "(", "url", ",", "{", "'publishingCountry'", ":", "publishingCountry", "}", ",", "*",...
31.125
29.125
def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None): """Generate a sample sheet in tab-separated text format. The columns contain the following sample attributes: 1) accession 2) name 3) CEL file name 4) CEL file URL Parameters ---------- output_file: str...
[ "def", "write_sample_sheet", "(", "output_file", ",", "accessions", ",", "names", ",", "celfile_urls", ",", "sel", "=", "None", ")", ":", "assert", "isinstance", "(", "output_file", ",", "str", ")", "assert", "isinstance", "(", "accessions", ",", "(", "list"...
32.127273
17.490909
def httpResponse_bodyParse(self, **kwargs): """ Returns the *body* from a http response. :param kwargs: response = <string> :return: the <body> from the http <string> """ str_response = '' for k,v in kwargs.items(): if k == 'response': str_respons...
[ "def", "httpResponse_bodyParse", "(", "self", ",", "*", "*", "kwargs", ")", ":", "str_response", "=", "''", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'response'", ":", "str_response", "=", "v", "try", ":", ...
31.666667
13.555556
def run_main(): """Initializes flags and calls main().""" program.setup_environment() if getattr(tf, '__version__', 'stub') == 'stub': print("TensorFlow installation not found - running with reduced feature set.", file=sys.stderr) tensorboard = program.TensorBoard(default.get_plugins(), ...
[ "def", "run_main", "(", ")", ":", "program", ".", "setup_environment", "(", ")", "if", "getattr", "(", "tf", ",", "'__version__'", ",", "'stub'", ")", "==", "'stub'", ":", "print", "(", "\"TensorFlow installation not found - running with reduced feature set.\"", ","...
35.125
21.333333
def parse_runtime_limit(value, now=None): """Parsing CLI option for runtime limit, supplied as VALUE. Value could be something like: Sunday 23:00-05:00, the format being [Wee[kday]] [hh[:mm][-hh[:mm]]]. The function will return two valid time ranges. The first could be in the past, containing the p...
[ "def", "parse_runtime_limit", "(", "value", ",", "now", "=", "None", ")", ":", "def", "extract_time", "(", "value", ")", ":", "value", "=", "_RE_RUNTIMELIMIT_HOUR", ".", "search", "(", "value", ")", ".", "groupdict", "(", ")", "return", "timedelta", "(", ...
34.336842
19.515789
def fill_opacity(self, opacity): """ :param opacity: 0.0 ~ 1.0 """ opacity = pgmagick.DrawableFillOpacity(float(opacity)) self.drawer.append(opacity)
[ "def", "fill_opacity", "(", "self", ",", "opacity", ")", ":", "opacity", "=", "pgmagick", ".", "DrawableFillOpacity", "(", "float", "(", "opacity", ")", ")", "self", ".", "drawer", ".", "append", "(", "opacity", ")" ]
30.666667
7
def remove(self, w): '''remove a waypoint''' self.wpoints.remove(w) self.last_change = time.time() self.reindex()
[ "def", "remove", "(", "self", ",", "w", ")", ":", "self", ".", "wpoints", ".", "remove", "(", "w", ")", "self", ".", "last_change", "=", "time", ".", "time", "(", ")", "self", ".", "reindex", "(", ")" ]
28.2
11.8
def findNextItem(self, item): """ Returns the next item in the tree. :param item | <QtGui.QTreeWidgetItem> :return <QtGui.QTreeWidgetItem> """ if not item: return None if item.childCount(): re...
[ "def", "findNextItem", "(", "self", ",", "item", ")", ":", "if", "not", "item", ":", "return", "None", "if", "item", ".", "childCount", "(", ")", ":", "return", "item", ".", "child", "(", "0", ")", "while", "item", ".", "parent", "(", ")", ":", "...
27.541667
14.125
def instantiate(args): """ %prog instantiate tagged.bed blacklist.ids big_gaps.bed instantiate NEW genes tagged by renumber. """ p = OptionParser(instantiate.__doc__) p.set_annot_reformat_opts() p.add_option("--extended_stride", default=False, action="store_true", help="Tog...
[ "def", "instantiate", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "instantiate", ".", "__doc__", ")", "p", ".", "set_annot_reformat_opts", "(", ")", "p", ".", "add_option", "(", "\"--extended_stride\"", ",", "default", "=", "False", ",", "action", ...
31.531646
18.746835
def crc_update(crc, data): """Update CRC-32C checksum with data. Args: crc: 32-bit checksum to update as long. data: byte array, string or iterable over bytes. Returns: 32-bit updated CRC-32C as long. """ if type(data) != array.array or data.itemsize != 1: buf = array...
[ "def", "crc_update", "(", "crc", ",", "data", ")", ":", "if", "type", "(", "data", ")", "!=", "array", ".", "array", "or", "data", ".", "itemsize", "!=", "1", ":", "buf", "=", "array", ".", "array", "(", "\"B\"", ",", "data", ")", "else", ":", ...
30.117647
14.705882
def _get_parameters(link, encoding): """ Generates Swagger Parameter Item object. """ parameters = [] properties = {} required = [] for field in link.fields: parser = OpenApiFieldParser(link, field) if parser.location == 'form': if encoding in ('multipart/form-da...
[ "def", "_get_parameters", "(", "link", ",", "encoding", ")", ":", "parameters", "=", "[", "]", "properties", "=", "{", "}", "required", "=", "[", "]", "for", "field", "in", "link", ".", "fields", ":", "parser", "=", "OpenApiFieldParser", "(", "link", "...
33.615385
18.589744
def get_session(*args, **kwargs): """ Pass session configuration options """ if 'config' not in kwargs: kwargs['config'] = tf.ConfigProto(**settings.session) if settings.profiling.dump_timeline: def fill_kwargs(key, value): """ Internal function for filling de...
[ "def", "get_session", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'config'", "not", "in", "kwargs", ":", "kwargs", "[", "'config'", "]", "=", "tf", ".", "ConfigProto", "(", "*", "*", "settings", ".", "session", ")", "if", "settings", ...
40.136364
8.863636
def nslookup(cls): """ Implementation of UNIX nslookup. """ try: # We try to get the addresse information of the given domain or IP. if "current_test_data" in PyFunceble.INTERN: # pragma: no cover # The end-user want more information whith his t...
[ "def", "nslookup", "(", "cls", ")", ":", "try", ":", "# We try to get the addresse information of the given domain or IP.", "if", "\"current_test_data\"", "in", "PyFunceble", ".", "INTERN", ":", "# pragma: no cover", "# The end-user want more information whith his test.", "if", ...
38.84507
22.112676
def from_points(cls, point1, point2): """Return a Vector instance from two given points.""" if isinstance(point1, Point) and isinstance(point2, Point): displacement = point1.substract(point2) return cls(displacement.x, displacement.y, displacement.z) raise TypeError
[ "def", "from_points", "(", "cls", ",", "point1", ",", "point2", ")", ":", "if", "isinstance", "(", "point1", ",", "Point", ")", "and", "isinstance", "(", "point2", ",", "Point", ")", ":", "displacement", "=", "point1", ".", "substract", "(", "point2", ...
51.5
14.666667
def register_context_middleware(self, *middleware): """ :param middleware: Middleware in order of execution """ for m in middleware: if not is_generator(m): raise Exception('Middleware {} must be a Python generator callable.'.format(m)) self._middlewa...
[ "def", "register_context_middleware", "(", "self", ",", "*", "middleware", ")", ":", "for", "m", "in", "middleware", ":", "if", "not", "is_generator", "(", "m", ")", ":", "raise", "Exception", "(", "'Middleware {} must be a Python generator callable.'", ".", "form...
37
16.111111
def topoplot(values, locations, axes=None, offset=(0, 0), plot_locations=True, plot_head=True, **kwargs): """Wrapper function for :class:`Topoplot. """ topo = Topoplot(**kwargs) topo.set_locations(locations) topo.set_values(values) topo.create_map() topo.plot_map(axes=axes, offs...
[ "def", "topoplot", "(", "values", ",", "locations", ",", "axes", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "plot_locations", "=", "True", ",", "plot_head", "=", "True", ",", "*", "*", "kwargs", ")", ":", "topo", "=", "Topoplot"...
34.071429
12.785714
def deepupdate( mapping: abc.MutableMapping, other: abc.Mapping, listextend=False ): """update one dictionary from another recursively. Only individual values will be overwritten--not entire branches of nested dictionaries. """ def inner(other, previouskeys): """previouskeys is a tuple ...
[ "def", "deepupdate", "(", "mapping", ":", "abc", ".", "MutableMapping", ",", "other", ":", "abc", ".", "Mapping", ",", "listextend", "=", "False", ")", ":", "def", "inner", "(", "other", ",", "previouskeys", ")", ":", "\"\"\"previouskeys is a tuple that stores...
35.125
16.5
def pack(self, value=None): """Pack the value as a binary representation. If the passed value (or the self._value) is zero (int), then the pack will assume that the value to be packed is '00:00:00:00:00:00'. Returns bytes: The binary representation. Raises: ...
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "if", "value", "is", "None", ":", "value", "=", "self", ".", "...
30.387097
21.806452
def get_pretrained_file_names(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `mxnet.contrib.text.embedding.create(...
[ "def", "get_pretrained_file_names", "(", "embedding_name", "=", "None", ")", ":", "text_embedding_reg", "=", "registry", ".", "get_registry", "(", "_TokenEmbedding", ")", "if", "embedding_name", "is", "not", "None", ":", "if", "embedding_name", "not", "in", "text_...
46.731707
31.097561
def config_from_file(filename, config=None): ''' Small configuration file management function''' if config: # We're writing configuration try: with open(filename, 'w') as fdesc: fdesc.write(json.dumps(config)) except IOError as error: logger.except...
[ "def", "config_from_file", "(", "filename", ",", "config", "=", "None", ")", ":", "if", "config", ":", "# We're writing configuration", "try", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fdesc", ":", "fdesc", ".", "write", "(", "json", ...
31.190476
13.857143
def woodbury_inv(self): """ The inverse of the woodbury matrix, in the gaussian likelihood case it is defined as $$ (K_{xx} + \Sigma_{xx})^{-1} \Sigma_{xx} := \texttt{Likelihood.variance / Approximate likelihood covariance} $$ """ if self._woodbury_inv is ...
[ "def", "woodbury_inv", "(", "self", ")", ":", "if", "self", ".", "_woodbury_inv", "is", "None", ":", "if", "self", ".", "_woodbury_chol", "is", "not", "None", ":", "self", ".", "_woodbury_inv", ",", "_", "=", "dpotri", "(", "self", ".", "_woodbury_chol",...
49.55
21.55
def udiv(self, o): """ Binary operation: unsigned division :param o: The divisor :return: (self / o) in unsigned arithmetic """ #FIXME: copy the code fromm wrapped interval splitted_dividends = self._ssplit() splitted_divisors = o._ssplit() resul...
[ "def", "udiv", "(", "self", ",", "o", ")", ":", "#FIXME: copy the code fromm wrapped interval", "splitted_dividends", "=", "self", ".", "_ssplit", "(", ")", "splitted_divisors", "=", "o", ".", "_ssplit", "(", ")", "resulting_intervals", "=", "set", "(", ")", "...
34
14.888889
def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if the asset is in the restricted_list. """ if self.restrictions.is_restricted(asset, algo_datetime): ...
[ "def", "validate", "(", "self", ",", "asset", ",", "amount", ",", "portfolio", ",", "algo_datetime", ",", "algo_current_data", ")", ":", "if", "self", ".", "restrictions", ".", "is_restricted", "(", "asset", ",", "algo_datetime", ")", ":", "self", ".", "ha...
32.818182
12.818182
def set_module_log_level(modules=None, log_level=logging.WARNING): """ This will raise the log level for the given modules in general this is used to silence them :param modules: list of str of module names ex. ['requests'] :param log_level: str of the new log level :return: ...
[ "def", "set_module_log_level", "(", "modules", "=", "None", ",", "log_level", "=", "logging", ".", "WARNING", ")", ":", "modules", "=", "modules", "or", "[", "]", "if", "not", "isinstance", "(", "modules", ",", "list", ")", ":", "modules", "=", "[", "m...
38.923077
12.461538
def get_lockfile_filename(impl, working_dir): """ Get the absolute path to the chain's indexing lockfile """ lockfile_name = impl.get_virtual_chain_name() + ".lock" return os.path.join(working_dir, lockfile_name)
[ "def", "get_lockfile_filename", "(", "impl", ",", "working_dir", ")", ":", "lockfile_name", "=", "impl", ".", "get_virtual_chain_name", "(", ")", "+", "\".lock\"", "return", "os", ".", "path", ".", "join", "(", "working_dir", ",", "lockfile_name", ")" ]
37.833333
8.833333
def _defgate(self, program, gate_name, gate_matrix): """Defines a gate named gate_name with matrix gate_matrix in program. In addition, updates self.defined_gates to track what has been defined. :param Program program: Pyquil Program to add the defgate and gate to. :param str gate_name...
[ "def", "_defgate", "(", "self", ",", "program", ",", "gate_name", ",", "gate_matrix", ")", ":", "new_program", "=", "pq", ".", "Program", "(", ")", "new_program", "+=", "program", "if", "gate_name", "not", "in", "self", ".", "defined_gates", ":", "new_prog...
47.125
16.3125
def setup_smtp(self, host, port, user, passwd, recipients, **kwargs): """ Set up the crash reporter to send reports via email using SMTP :param host: SMTP host :param port: SMTP port :param user: sender email address :param passwd: sender email password :param re...
[ "def", "setup_smtp", "(", "self", ",", "host", ",", "port", ",", "user", ",", "passwd", ",", "recipients", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_smtp", "=", "kwargs", "self", ".", "_smtp", ".", "update", "(", "{", "'host'", ":", "host",...
42.444444
19.333333
def e(self,analytic=False,pot=None,**kwargs): """ NAME: e PURPOSE: calculate the eccentricity, either numerically from the numerical orbit integration or using analytical means INPUT: analytic(= False) compute this analytically pot - pote...
[ "def", "e", "(", "self", ",", "analytic", "=", "False", ",", "pot", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "pot", "is", "None", ":", "pot", "=", "flatten_potential", "(", "pot", ")", "_check_consistent_units", "(", "self", ",", ...
32.488372
35.837209
def read_until(self, delimiter): """Reads until the delimiter is found.""" if delimiter in self._buffer: data, delimiter, self._buffer = self._buffer.partition(delimiter) return data else: self._buffer += self.__read__(self._max_bytes) return self....
[ "def", "read_until", "(", "self", ",", "delimiter", ")", ":", "if", "delimiter", "in", "self", ".", "_buffer", ":", "data", ",", "delimiter", ",", "self", ".", "_buffer", "=", "self", ".", "_buffer", ".", "partition", "(", "delimiter", ")", "return", "...
41.75
14.375
def site_analysis(self, folder_name, site_install_mapping, end_date): """ Summarize site data into a single table. folder_name : str Folder where all site data resides. site_event_mapping : dic Dictionary of site name to date of installation. end_date ...
[ "def", "site_analysis", "(", "self", ",", "folder_name", ",", "site_install_mapping", ",", "end_date", ")", ":", "def", "count_number_of_days", "(", "site", ",", "end_date", ")", ":", "\"\"\" Counts the number of days between two dates.\n\n Parameters\n ...
41.686047
24.197674
def combine_HSPs(a): """ Combine HSPs into a single BlastLine. """ m = a[0] if len(a) == 1: return m for b in a[1:]: assert m.query == b.query assert m.subject == b.subject m.hitlen += b.hitlen m.nmismatch += b.nmismatch m.ngaps += b.ngaps ...
[ "def", "combine_HSPs", "(", "a", ")", ":", "m", "=", "a", "[", "0", "]", "if", "len", "(", "a", ")", "==", "1", ":", "return", "m", "for", "b", "in", "a", "[", "1", ":", "]", ":", "assert", "m", ".", "query", "==", "b", ".", "query", "ass...
25.521739
13.869565
def print_todo(self, p_todo): """ Given a todo item, pretty print it. """ todo_str = p_todo.source() for ppf in self.filters: todo_str = ppf.filter(todo_str, p_todo) return TopydoString(todo_str)
[ "def", "print_todo", "(", "self", ",", "p_todo", ")", ":", "todo_str", "=", "p_todo", ".", "source", "(", ")", "for", "ppf", "in", "self", ".", "filters", ":", "todo_str", "=", "ppf", ".", "filter", "(", "todo_str", ",", "p_todo", ")", "return", "Top...
29.25
14.875
def wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt', spoken: bool = False) -> str: """ Translate wind shear into a readable string Ex: Wind shear 2000ft from 140 at 30kt """ if not shear or 'WS' not in shear or '/' not in shear: return '' shear = shear[2:].rstrip(unit...
[ "def", "wind_shear", "(", "shear", ":", "str", ",", "unit_alt", ":", "str", "=", "'ft'", ",", "unit_wind", ":", "str", "=", "'kt'", ",", "spoken", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "not", "shear", "or", "'WS'", "not", "in", ...
47.181818
24.636364
def equals(self, other, timestamp_delta=1.0e-6): """ Compares a given message with this one. :param can.Message other: the message to compare with :type timestamp_delta: float or int or None :param timestamp_delta: the maximum difference at which two timestamps are ...
[ "def", "equals", "(", "self", ",", "other", ",", "timestamp_delta", "=", "1.0e-6", ")", ":", "# see https://github.com/hardbyte/python-can/pull/413 for a discussion", "# on why a delta of 1.0e-6 was chosen", "return", "(", "# check for identity first and finish fast", "self", "is...
41.888889
20.333333
def generate_vector_color_map(self): """Generate color stops array for use with match expression in mapbox template""" vector_stops = [] # if join data specified as filename or URL, parse JSON to list of Python dicts if type(self.data) == str: self.data = geojson_to_dict_lis...
[ "def", "generate_vector_color_map", "(", "self", ")", ":", "vector_stops", "=", "[", "]", "# if join data specified as filename or URL, parse JSON to list of Python dicts", "if", "type", "(", "self", ".", "data", ")", "==", "str", ":", "self", ".", "data", "=", "geo...
42.5
26.111111
def compare_datetimes(d1, d2): """ Compares two datetimes safely, whether they are timezone-naive or timezone-aware. If either datetime is naive it is converted to an aware datetime assuming UTC. Args: d1: first datetime. d2: second datetime. Returns: -1 if d1 < d2, 0 if they are the same, or +1 ...
[ "def", "compare_datetimes", "(", "d1", ",", "d2", ")", ":", "if", "d1", ".", "tzinfo", "is", "None", "or", "d1", ".", "tzinfo", ".", "utcoffset", "(", "d1", ")", "is", "None", ":", "d1", "=", "d1", ".", "replace", "(", "tzinfo", "=", "pytz", ".",...
27.47619
22.238095
def SetAttribute(self, attribute): """Checks that attribute is a valid Attribute() instance.""" # Grab the attribute registered for this name self.attribute = attribute self.attribute_obj = Attribute.GetAttributeByName(attribute) if self.attribute_obj is None: raise lexer.ParseError("Attribute...
[ "def", "SetAttribute", "(", "self", ",", "attribute", ")", ":", "# Grab the attribute registered for this name", "self", ".", "attribute", "=", "attribute", "self", ".", "attribute_obj", "=", "Attribute", ".", "GetAttributeByName", "(", "attribute", ")", "if", "self...
49
11.857143
def _label(self, line): '''_label will parse a Dockerfile label Parameters ========== line: the line from the recipe file to parse for CMD ''' label = self._setup('LABEL', line) self.labels += [ label ]
[ "def", "_label", "(", "self", ",", "line", ")", ":", "label", "=", "self", ".", "_setup", "(", "'LABEL'", ",", "line", ")", "self", ".", "labels", "+=", "[", "label", "]" ]
27.1
19.3
def _initialize(self, chain, length): """Create an SQL table. """ if self._getfunc is None: self._getfunc = self.db.model._funs_to_tally[self.name] # Determine size try: self._shape = np.shape(self._getfunc()) except TypeError: self._...
[ "def", "_initialize", "(", "self", ",", "chain", ",", "length", ")", ":", "if", "self", ".", "_getfunc", "is", "None", ":", "self", ".", "_getfunc", "=", "self", ".", "db", ".", "model", ".", "_funs_to_tally", "[", "self", ".", "name", "]", "# Determ...
31.6
17.8
def setup(self, settings): ''' Setup the handler @param settings: The loaded settings file ''' self.producer = self._create_producer(settings) self.topic_prefix = settings['KAFKA_TOPIC_PREFIX'] self.use_appid_topics = settings['KAFKA_APPID_TOPICS'] self...
[ "def", "setup", "(", "self", ",", "settings", ")", ":", "self", ".", "producer", "=", "self", ".", "_create_producer", "(", "settings", ")", "self", ".", "topic_prefix", "=", "settings", "[", "'KAFKA_TOPIC_PREFIX'", "]", "self", ".", "use_appid_topics", "=",...
33.384615
25.230769
def select_attribute(source, name, val=None): ''' Yields elements from the source having the given attrivute, optionally with the given attribute value source - if an element, starts with all child elements in order; can also be any other iterator name - attribute name to check val - if None check o...
[ "def", "select_attribute", "(", "source", ",", "name", ",", "val", "=", "None", ")", ":", "def", "check", "(", "x", ")", ":", "if", "val", "is", "None", ":", "return", "name", "in", "x", ".", "xml_attributes", "else", ":", "return", "name", "in", "...
48.076923
29.461538
def check(self): """Check if a file is changed """ for (path, handler) in self.handlers.items(): current_signature = self.signatures[path] new_signature = self.get_path_signature(path) if new_signature != current_signature: self.signatures[path...
[ "def", "check", "(", "self", ")", ":", "for", "(", "path", ",", "handler", ")", "in", "self", ".", "handlers", ".", "items", "(", ")", ":", "current_signature", "=", "self", ".", "signatures", "[", "path", "]", "new_signature", "=", "self", ".", "get...
41.777778
10.666667
def do_local_server_auth_flow(session_params=None, force_new_client=False): """ Starts a local http server, opens a browser to have the user authenticate, and gets the code redirected to the server (no copy and pasting required) """ session_params = session_params or {} # start local server and...
[ "def", "do_local_server_auth_flow", "(", "session_params", "=", "None", ",", "force_new_client", "=", "False", ")", ":", "session_params", "=", "session_params", "or", "{", "}", "# start local server and create matching redirect_uri", "with", "start_local_server", "(", "l...
41.3
20.75
def set_exit_callback(self, callback: Callable[[int], None]) -> None: """Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libr...
[ "def", "set_exit_callback", "(", "self", ",", "callback", ":", "Callable", "[", "[", "int", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_exit_callback", "=", "callback", "Subprocess", ".", "initialize", "(", ")", "Subprocess", ".", "_wai...
43.238095
21.619048
async def _reset_vector(self): """Background task to initialize this system in the event loop.""" self._logger.debug("sensor_graph subsystem task starting") # If there is a persistent sgf loaded, send reset information. self.initialized.set() while True: stream, r...
[ "async", "def", "_reset_vector", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"sensor_graph subsystem task starting\"", ")", "# If there is a persistent sgf loaded, send reset information.", "self", ".", "initialized", ".", "set", "(", ")", "while...
40.578947
28.789474
def _get_path(entity_id): '''Get the entity_id as a string if it is a Reference. @param entity_id The ID either a reference or a string of the entity to get. @return entity_id as a string ''' try: path = entity_id.path() except AttributeError: path = entity_id if p...
[ "def", "_get_path", "(", "entity_id", ")", ":", "try", ":", "path", "=", "entity_id", ".", "path", "(", ")", "except", "AttributeError", ":", "path", "=", "entity_id", "if", "path", ".", "startswith", "(", "'cs:'", ")", ":", "path", "=", "path", "[", ...
26.357143
20.785714
def reindex_variables( variables: Mapping[Any, Variable], sizes: Mapping[Any, int], indexes: Mapping[Any, pd.Index], indexers: Mapping, method: Optional[str] = None, tolerance: Any = None, copy: bool = True, ) -> 'Tuple[OrderedDict[Any, Variable], OrderedDict[Any, pd.Index]]': """Conform...
[ "def", "reindex_variables", "(", "variables", ":", "Mapping", "[", "Any", ",", "Variable", "]", ",", "sizes", ":", "Mapping", "[", "Any", ",", "int", "]", ",", "indexes", ":", "Mapping", "[", "Any", ",", "pd", ".", "Index", "]", ",", "indexers", ":",...
38.815385
19.953846
def filter2(resources, query, open_resource): """Filter a list of resources according to a query expression. It accepts the optional part of the expression. .. warning: This function is experimental and unsafe as it uses eval, It also might require to open the resource. :param resourc...
[ "def", "filter2", "(", "resources", ",", "query", ",", "open_resource", ")", ":", "if", "'{'", "in", "query", ":", "try", ":", "query", ",", "optional", "=", "query", ".", "split", "(", "'{'", ")", "optional", ",", "_", "=", "optional", ".", "split",...
36
16.426829
def from_xml(cls, child, result=None): """ Create new way element from XML data :param child: XML node to be parsed :type child: xml.etree.ElementTree.Element :param result: The result this node belongs to :type result: overpy.Result :return: New Way oject ...
[ "def", "from_xml", "(", "cls", ",", "child", ",", "result", "=", "None", ")", ":", "if", "child", ".", "tag", ".", "lower", "(", ")", "!=", "cls", ".", "_type_value", ":", "raise", "exception", ".", "ElementDataWrongType", "(", "type_expected", "=", "c...
33.914894
15.148936
def result_key_for(self, op_name): """ Checks for the presence of a ``result_key``, which defines what data should make up an instance. Returns ``None`` if there is no ``result_key``. :param op_name: The operation name to look for the ``result_key`` in. :type op_name: s...
[ "def", "result_key_for", "(", "self", ",", "op_name", ")", ":", "ops", "=", "self", ".", "resource_data", ".", "get", "(", "'operations'", ",", "{", "}", ")", "op", "=", "ops", ".", "get", "(", "op_name", ",", "{", "}", ")", "key", "=", "op", "."...
33
17.705882
def convert_mrf_to_syntax_mrf( mrf_lines, conversion_rules ): ''' Converts given lines from Filosoft's mrf format to syntactic analyzer's format, using the morph-category conversion rules from conversion_rules, and punctuation via method _convert_punctuation(); As a result of conversion, th...
[ "def", "convert_mrf_to_syntax_mrf", "(", "mrf_lines", ",", "conversion_rules", ")", ":", "i", "=", "0", "while", "(", "i", "<", "len", "(", "mrf_lines", ")", ")", ":", "line", "=", "mrf_lines", "[", "i", "]", "if", "line", ".", "startswith", "(", "' '...
48.140625
18.109375
def comet_view(self, request): """ This is dumb function, it just passes everything it gets into the message stream. Something else in the stream should be responsible for asynchronously figuring out what to do with all these messages. """ request_id = self.id_for_reques...
[ "def", "comet_view", "(", "self", ",", "request", ")", ":", "request_id", "=", "self", ".", "id_for_request", "(", "request", ")", "if", "not", "request_id", ":", "request", ".", "write", "(", "HttpResponse", "(", "403", ")", ".", "as_bytes", "(", ")", ...
39
16
def summary_data_from_transaction_data( transactions, customer_id_col, datetime_col, monetary_value_col=None, datetime_format=None, observation_period_end=None, freq="D", freq_multiplier=1, ): """ Return summary data from transactions. This transforms a DataFrame of transact...
[ "def", "summary_data_from_transaction_data", "(", "transactions", ",", "customer_id_col", ",", "datetime_col", ",", "monetary_value_col", "=", "None", ",", "datetime_format", "=", "None", ",", "observation_period_end", "=", "None", ",", "freq", "=", "\"D\"", ",", "f...
43.544444
27.633333
def relation_(self, table, origin_field, search_field, destination_field=None, id_field="id"): """ Returns a DataSwim instance with a column filled from a relation foreign key """ df = self._relation(table, origin_field, search_field, destin...
[ "def", "relation_", "(", "self", ",", "table", ",", "origin_field", ",", "search_field", ",", "destination_field", "=", "None", ",", "id_field", "=", "\"id\"", ")", ":", "df", "=", "self", ".", "_relation", "(", "table", ",", "origin_field", ",", "search_f...
46.375
16.625
def default_icon_path(self): """Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") ...
[ "def", "default_icon_path", "(", "self", ")", ":", "supported_exts", "=", "[", "'.png'", ",", "'.svg'", "]", "stripped", "=", "self", ".", "path", ".", "replace", "(", "os", ".", "path", ".", "join", "(", "self", ".", "load_path", ",", "'assistants'", ...
47.863636
16.181818
def noise_uniform(self, lower_bound, upper_bound): """Create a uniform noise variable""" assert upper_bound > lower_bound nu = self.sym.sym('nu_{:d}'.format(len(self.scope['nu']))) self.scope['nu'].append(nu) return lower_bound + nu*(upper_bound - lower_bound)
[ "def", "noise_uniform", "(", "self", ",", "lower_bound", ",", "upper_bound", ")", ":", "assert", "upper_bound", ">", "lower_bound", "nu", "=", "self", ".", "sym", ".", "sym", "(", "'nu_{:d}'", ".", "format", "(", "len", "(", "self", ".", "scope", "[", ...
49.166667
10
def define_cyclic_can_msg(self, channel, can_msg=None): """ Defines a list of CAN messages for automatic transmission. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param list(CanMsg) can_msg: List of CAN messages ...
[ "def", "define_cyclic_can_msg", "(", "self", ",", "channel", ",", "can_msg", "=", "None", ")", ":", "if", "can_msg", "is", "not", "None", ":", "c_can_msg", "=", "(", "CanMsg", "*", "len", "(", "can_msg", ")", ")", "(", "*", "can_msg", ")", "c_count", ...
44.666667
22.533333
def children(self, table_name, primary=None): """ :param table_name: `schema`.`table` :param primary: if None, then all children are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one no...
[ "def", "children", "(", "self", ",", "table_name", ",", "primary", "=", "None", ")", ":", "return", "dict", "(", "p", "[", "1", ":", "3", "]", "for", "p", "in", "self", ".", "out_edges", "(", "table_name", ",", "data", "=", "True", ")", "if", "pr...
58.9
25.3
def create(cls, name, servers, backup_log_data=False, encrypt_password=None, comment=None): """ Create a new server backup task. This task provides the ability to backup individual or all management and log servers under SMC management. :param str name: na...
[ "def", "create", "(", "cls", ",", "name", ",", "servers", ",", "backup_log_data", "=", "False", ",", "encrypt_password", "=", "None", ",", "comment", "=", "None", ")", ":", "if", "not", "servers", ":", "servers", "=", "[", "svr", ".", "href", "for", ...
43.916667
18.861111
def read(self, timeout=None): ''' Read from the transport. If no data is available, should return None. The timeout is ignored as this returns only data that has already been buffered locally. ''' # NOTE: copying over this comment from Connection, because there is ...
[ "def", "read", "(", "self", ",", "timeout", "=", "None", ")", ":", "# NOTE: copying over this comment from Connection, because there is", "# knowledge captured here, even if the details are stale", "# Because of the timer callback to dataRead when we re-buffered,", "# there's a chance that...
47.933333
22.066667
def dumps(obj, *args, **kwargs): """Serialize a object to string Basic Usage: >>> import simplekit.objson >>> obj = {'name':'wendy'} >>> print simplekit.objson.dumps(obj) :param obj: a object which need to dump :param args: Optional arguments that :func:`json.dumps` takes. :param kwa...
[ "def", "dumps", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'default'", "]", "=", "object2dict", "return", "json", ".", "dumps", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
25.833333
18.722222
def _method_(name): """ getter factory """ def _getter_(self): return getattr(self, self.get_private_name(name)) return _getter_
[ "def", "_method_", "(", "name", ")", ":", "def", "_getter_", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "get_private_name", "(", "name", ")", ")", "return", "_getter_" ]
28.8
15.2
def geo_context_from_ref(self, ref): """Return a ref context object given a location reference entry.""" value = ref.get('value') if value: # Here we get the RefContext from the stashed geoloc dictionary rc = self.doc.geolocs.get(value['@id']) return rc ...
[ "def", "geo_context_from_ref", "(", "self", ",", "ref", ")", ":", "value", "=", "ref", ".", "get", "(", "'value'", ")", "if", "value", ":", "# Here we get the RefContext from the stashed geoloc dictionary", "rc", "=", "self", ".", "doc", ".", "geolocs", ".", "...
40.75
15.125
def mark_as_done(self, **kwargs): """Mark the todo as done. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabTodoError: If the server failed to perform the request ...
[ "def", "mark_as_done", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'%s/%s/mark_as_done'", "%", "(", "self", ".", "manager", ".", "path", ",", "self", ".", "id", ")", "server_data", "=", "self", ".", "manager", ".", "gitlab", ".", "h...
37.615385
21.923077
def reference(self): """The Didl object this favorite refers to.""" # Import from_didl_string if it isn't present already. The import # happens here because it would cause cyclic import errors if the # import happened at load time. global _FROM_DIDL_STRING_FUNCTION # pylint: di...
[ "def", "reference", "(", "self", ")", ":", "# Import from_didl_string if it isn't present already. The import", "# happens here because it would cause cyclic import errors if the", "# import happened at load time.", "global", "_FROM_DIDL_STRING_FUNCTION", "# pylint: disable=global-statement", ...
45.882353
19.764706
def address(self, s): """ Parse an address, any of p2pkh, p2sh, p2pkh_segwit, or p2sh_segwit. Return a :class:`Contract <Contract>`, or None. """ s = parseable_str(s) return self.p2pkh(s) or self.p2sh(s) or self.p2pkh_segwit(s) or self.p2sh_segwit(s)
[ "def", "address", "(", "self", ",", "s", ")", ":", "s", "=", "parseable_str", "(", "s", ")", "return", "self", ".", "p2pkh", "(", "s", ")", "or", "self", ".", "p2sh", "(", "s", ")", "or", "self", ".", "p2pkh_segwit", "(", "s", ")", "or", "self"...
41.714286
18.857143
def get_available_parameters(self): """ Return a list of the parameters made available by the script. """ # At the moment, we rely on regex to extract the list of available # parameters. This solution will break if the format of the output # changes, but this is the best...
[ "def", "get_available_parameters", "(", "self", ")", ":", "# At the moment, we rely on regex to extract the list of available", "# parameters. This solution will break if the format of the output", "# changes, but this is the best option that is currently available.", "result", "=", "subproces...
47.393939
25.272727
def walk(self, listener): """Walk the parse tree, using the given listener. The listener should be a stix2patterns.grammars.STIXPatternListener.STIXPatternListener (or subclass) instance.""" antlr4.ParseTreeWalker.DEFAULT.walk(listener, self.__parse_tree)
[ "def", "walk", "(", "self", ",", "listener", ")", ":", "antlr4", ".", "ParseTreeWalker", ".", "DEFAULT", ".", "walk", "(", "listener", ",", "self", ".", "__parse_tree", ")" ]
48.5
17
def findConfigFile(cls, filename): """ Search the configuration path (specified via the NTA_CONF_PATH environment variable) for the given filename. If found, return the complete path to the file. :param filename: (string) name of file to locate """ paths = cls.getConfigPaths() for p in pat...
[ "def", "findConfigFile", "(", "cls", ",", "filename", ")", ":", "paths", "=", "cls", ".", "getConfigPaths", "(", ")", "for", "p", "in", "paths", ":", "testPath", "=", "os", ".", "path", ".", "join", "(", "p", ",", "filename", ")", "if", "os", ".", ...
33.076923
14.846154
def filter(self, local_name=None, name=None, ns_uri=None, node_type=None, filter_fn=None, first_only=False): """ Apply filters to the set of nodes in this list. :param local_name: a local name used to filter the nodes. :type local_name: string or None :param name: a ...
[ "def", "filter", "(", "self", ",", "local_name", "=", "None", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "node_type", "=", "None", ",", "filter_fn", "=", "None", ",", "first_only", "=", "False", ")", ":", "# Build our own filter function un...
47.016949
19.389831
def lookup_defs(self, variable, size_threshold=32): """ Find all definitions of the varaible :param SimVariable variable: The variable to lookup for. :param int size_threshold: The maximum bytes to consider for the variable. For example, if the variable is 100 ...
[ "def", "lookup_defs", "(", "self", ",", "variable", ",", "size_threshold", "=", "32", ")", ":", "live_def_locs", "=", "set", "(", ")", "if", "isinstance", "(", "variable", ",", "SimRegisterVariable", ")", ":", "if", "variable", ".", "reg", "is", "None", ...
38.076923
22.025641
def is_russian(self): """Checks if file path is russian :return: True iff document has a russian name """ russian_chars = 0 for char in RUSSIAN_CHARS: if char in self.name: russian_chars += 1 # found a russian char return russian_chars > len...
[ "def", "is_russian", "(", "self", ")", ":", "russian_chars", "=", "0", "for", "char", "in", "RUSSIAN_CHARS", ":", "if", "char", "in", "self", ".", "name", ":", "russian_chars", "+=", "1", "# found a russian char", "return", "russian_chars", ">", "len", "(", ...
30.090909
15.727273
def notifications(self): """ Access the notifications :returns: twilio.rest.api.v2010.account.notification.NotificationList :rtype: twilio.rest.api.v2010.account.notification.NotificationList """ if self._notifications is None: self._notifications = Notificat...
[ "def", "notifications", "(", "self", ")", ":", "if", "self", ".", "_notifications", "is", "None", ":", "self", ".", "_notifications", "=", "NotificationList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'sid'", "]...
40.5
20.5
def updateDeviceStatus(self, deviceName, state, reason=None): """ Updates the current device status. :param deviceName: the device name. :param state: the state. :param reason: the reason for the change. :return: """ logger.info('Updating recording device ...
[ "def", "updateDeviceStatus", "(", "self", ",", "deviceName", ",", "state", ",", "reason", "=", "None", ")", ":", "logger", ".", "info", "(", "'Updating recording device state for '", "+", "deviceName", "+", "' to '", "+", "state", ".", "name", "+", "(", "''"...
41.904762
16.380952
def split_data(self, train_images, train_labels): """ :param train_images: numpy array (image_dim, image_dim, num_images) :param train_labels: numpy array (labels) :return: train_images, train_labels, valid_images, valid_labels """ valid_images = train_images[:self.num_va...
[ "def", "split_data", "(", "self", ",", "train_images", ",", "train_labels", ")", ":", "valid_images", "=", "train_images", "[", ":", "self", ".", "num_valid_images", "]", "valid_labels", "=", "train_labels", "[", ":", "self", ".", "num_valid_images", "]", "tra...
51.909091
17.181818
def get_google_songs(self, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from user's Google Music library. Parameters: include_filters (list): A list of ``(field, pattern)`` tuples. Fields are any valid Google Music metadata field available to the M...
[ "def", "get_google_songs", "(", "self", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "logger", ".", "info", "(", "\"Loading Google Music songs...\"", ")"...
44.166667
32.388889
def drop_indexes(quiet=True, stdout=None): """ Discover and drop all indexes. :type: bool :return: None """ results, meta = db.cypher_query("CALL db.indexes()") pattern = re.compile(':(.*)\((.*)\)') for index in results: db.cypher_query('DROP ' + index[0]) match = patte...
[ "def", "drop_indexes", "(", "quiet", "=", "True", ",", "stdout", "=", "None", ")", ":", "results", ",", "meta", "=", "db", ".", "cypher_query", "(", "\"CALL db.indexes()\"", ")", "pattern", "=", "re", ".", "compile", "(", "':(.*)\\((.*)\\)'", ")", "for", ...
29.6875
14.6875
def acceptable(value, capitalize=False): """Convert a string into something that can be used as a valid python variable name""" name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value)) # Clean up irregularities in underscores. name = regexes['repeated_underscore'].sub("_", name.strip('_')...
[ "def", "acceptable", "(", "value", ",", "capitalize", "=", "False", ")", ":", "name", "=", "regexes", "[", "'punctuation'", "]", ".", "sub", "(", "\"\"", ",", "regexes", "[", "'joins'", "]", ".", "sub", "(", "\"_\"", ",", "value", ")", ")", "# Clean ...
48.375
15.875
def apply_binding(self, binding, msg_str, destination="", relay_state="", response=False, sign=False, **kwargs): """ Construct the necessary HTTP arguments dependent on Binding :param binding: Which binding to use :param msg_str: The return message as a string (XML...
[ "def", "apply_binding", "(", "self", ",", "binding", ",", "msg_str", ",", "destination", "=", "\"\"", ",", "relay_state", "=", "\"\"", ",", "response", "=", "False", ",", "sign", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# unless if BINDING_HTTP_AR...
42.517241
16.413793
def datapt_to_system(self, datapt, system=None, coords='data', naxispath=None): """ Map points to given coordinate system. Parameters ---------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0, ...], [x1, y1, ......
[ "def", "datapt_to_system", "(", "self", ",", "datapt", ",", "system", "=", "None", ",", "coords", "=", "'data'", ",", "naxispath", "=", "None", ")", ":", "if", "self", ".", "coordsys", "==", "'raw'", ":", "raise", "common", ".", "WCSError", "(", "\"No ...
32.456522
21.413043
def default_type_resolver( value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType ) -> AwaitableOrValue[Optional[Union[GraphQLObjectType, str]]]: """Default type resolver function. If a resolve_type function is not given, then a default resolve behavior is used which attempts two stra...
[ "def", "default_type_resolver", "(", "value", ":", "Any", ",", "info", ":", "GraphQLResolveInfo", ",", "abstract_type", ":", "GraphQLAbstractType", ")", "->", "AwaitableOrValue", "[", "Optional", "[", "Union", "[", "GraphQLObjectType", ",", "str", "]", "]", "]",...
38.288462
21.461538
def assign_asset_to_repository(self, asset_id, repository_id): """Adds an existing ``Asset`` to a ``Repository``. arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` arg: repository_id (osid.id.Id): the ``Id`` of the ``Repository`` raise: AlreadyExists - ``ass...
[ "def", "assign_asset_to_repository", "(", "self", ",", "asset_id", ",", "repository_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'REPOSITORY'", ",...
51
21.863636
def inline(self) -> str: """ Return inline string format of the Membership instance :return: """ return "{0}:{1}:{2}:{3}:{4}".format(self.issuer, self.signatures[0], self.membership_ts, ...
[ "def", "inline", "(", "self", ")", "->", "str", ":", "return", "\"{0}:{1}:{2}:{3}:{4}\"", ".", "format", "(", "self", ".", "issuer", ",", "self", ".", "signatures", "[", "0", "]", ",", "self", ".", "membership_ts", ",", "self", ".", "identity_ts", ",", ...
42
15.8
def get_branding_ids(self): """Gets the branding asset ``Ids``. return: (osid.id.IdList) - a list of asset ``Ids`` *compliance: mandatory -- This method must be implemented.* """ from ..id.objects import IdList if 'brandingIds' not in self._my_map: return Id...
[ "def", "get_branding_ids", "(", "self", ")", ":", "from", ".", ".", "id", ".", "objects", "import", "IdList", "if", "'brandingIds'", "not", "in", "self", ".", "_my_map", ":", "return", "IdList", "(", "[", "]", ")", "id_list", "=", "[", "]", "for", "i...
32.5
14.071429
def _add_post_data(self, request: Request): '''Add data to the payload.''' if self._item_session.url_record.post_data: data = wpull.string.to_bytes(self._item_session.url_record.post_data) else: data = wpull.string.to_bytes( self._processor.fetch_params.po...
[ "def", "_add_post_data", "(", "self", ",", "request", ":", "Request", ")", ":", "if", "self", ".", "_item_session", ".", "url_record", ".", "post_data", ":", "data", "=", "wpull", ".", "string", ".", "to_bytes", "(", "self", ".", "_item_session", ".", "u...
35.8
19.9
def selectImpl(self, cond, multiple, root, maxDepth, onlyVisibleNode, includeRoot): """ Selector internal implementation. TODO: add later. .. note:: This doc shows only the outline of the algorithm. Do not call this method in your code as this is an internal method. A...
[ "def", "selectImpl", "(", "self", ",", "cond", ",", "multiple", ",", "root", ",", "maxDepth", ",", "onlyVisibleNode", ",", "includeRoot", ")", ":", "result", "=", "[", "]", "if", "not", "root", ":", "return", "result", "op", ",", "args", "=", "cond", ...
44.337838
26.905405
def _variance_scale_term(self): """Helper to `_covariance` and `_variance` which computes a shared scale.""" # Expand back the last dim so the shape of _variance_scale_term matches the # shape of self.concentration. c0 = self.total_concentration[..., tf.newaxis] return tf.sqrt((1. + c0 / self.total_...
[ "def", "_variance_scale_term", "(", "self", ")", ":", "# Expand back the last dim so the shape of _variance_scale_term matches the", "# shape of self.concentration.", "c0", "=", "self", ".", "total_concentration", "[", "...", ",", "tf", ".", "newaxis", "]", "return", "tf", ...
58.5
16.833333
def from_string(string, conv, bound=r'.+?', disj=r' ?\| ?', sep=r', ?', left_open=r'\(', left_closed=r'\[', right_open=r'\)', right_closed=r'\]', pinf=r'\+inf', ninf=r'-inf'): """ Parse given string and create an Interval instance. A converter function has to be provided to convert a bound (...
[ "def", "from_string", "(", "string", ",", "conv", ",", "bound", "=", "r'.+?'", ",", "disj", "=", "r' ?\\| ?'", ",", "sep", "=", "r', ?'", ",", "left_open", "=", "r'\\('", ",", "left_closed", "=", "r'\\['", ",", "right_open", "=", "r'\\)'", ",", "right_cl...
44.714286
27.357143
def load(self, rule_type, quiet = False): """ Open a JSON file definiting a ruleset and load it into a Ruleset object :param quiet: :return: """ if self.filename and os.path.exists(self.filename): try: with open(self.filename, 'rt') as f: ...
[ "def", "load", "(", "self", ",", "rule_type", ",", "quiet", "=", "False", ")", ":", "if", "self", ".", "filename", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "filename", ")", ":", "try", ":", "with", "open", "(", "self", ".", "fil...
41.307692
18.769231
def is_updated_after(self, bucket_name, object_name, ts): """ Checks if an blob_name is updated in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the object is. :type bucket_name: str :param object_name: The name of the object to check in the Goo...
[ "def", "is_updated_after", "(", "self", ",", "bucket_name", ",", "object_name", ",", "ts", ")", ":", "client", "=", "self", ".", "get_conn", "(", ")", "bucket", "=", "storage", ".", "Bucket", "(", "client", "=", "client", ",", "name", "=", "bucket_name",...
32.419355
20.290323
def get_key_for(self, address): """ Generates the key associated with the specified address. Note that this method will generate the wrong key if the input address was generated from a different key! """ return self.get_key( index=address.key_index, ...
[ "def", "get_key_for", "(", "self", ",", "address", ")", ":", "return", "self", ".", "get_key", "(", "index", "=", "address", ".", "key_index", ",", "iterations", "=", "address", ".", "security_level", ",", ")" ]
32.454545
15.181818
def get_name_DID(name, proxy=None, hostport=None): """ Get the DID for a name or subdomain Return the DID string on success Return None if not found """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: proxy = connect_hostport(hostport) did_schema = { ...
[ "def", "get_name_DID", "(", "name", ",", "proxy", "=", "None", ",", "hostport", "=", "None", ")", ":", "assert", "proxy", "or", "hostport", ",", "'Need proxy or hostport'", "if", "proxy", "is", "None", ":", "proxy", "=", "connect_hostport", "(", "hostport", ...
28.921875
22.390625
def _combined_asides(cls): # pylint: disable=no-self-argument """ A dictionary mapping XBlock view names to the aside method that decorates them (or None, if there is no decorator for the specified view). """ # The method declares what views it decorates. We rely on `dir` ...
[ "def", "_combined_asides", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "# The method declares what views it decorates. We rely on `dir`", "# to handle subclasses and overrides.", "combined_asides", "=", "defaultdict", "(", "None", ")", "for", "_view_name", ",", "v...
52.384615
19.307692
def getUTC(self, utcoffset): """ Returns a new Time object set to UTC given an offset Time object. """ newTime = (self.value - utcoffset.value) % 24 return Time(newTime)
[ "def", "getUTC", "(", "self", ",", "utcoffset", ")", ":", "newTime", "=", "(", "self", ".", "value", "-", "utcoffset", ".", "value", ")", "%", "24", "return", "Time", "(", "newTime", ")" ]
30.428571
11.285714
def upload_document_fileobj(file_obj, file_name, session, documents_resource, log=None): """Uploads a single file-like object to the One Codex server directly to S3. Parameters ---------- file_obj : `FilePassthru`, or a file-like object If a file-like object is given, its mime-type will be sent...
[ "def", "upload_document_fileobj", "(", "file_obj", ",", "file_name", ",", "session", ",", "documents_resource", ",", "log", "=", "None", ")", ":", "try", ":", "fields", "=", "documents_resource", ".", "init_multipart_upload", "(", ")", "except", "requests", ".",...
36.82
27.12
def jsonify_assert(asserted, message, status_code=400): """Asserts something is true, aborts the request if not.""" if asserted: return try: raise AssertionError(message) except AssertionError, e: stack = traceback.extract_stack() stack.pop() logging.error('Assert...
[ "def", "jsonify_assert", "(", "asserted", ",", "message", ",", "status_code", "=", "400", ")", ":", "if", "asserted", ":", "return", "try", ":", "raise", "AssertionError", "(", "message", ")", "except", "AssertionError", ",", "e", ":", "stack", "=", "trace...
37.916667
15.5
def miscs_update_idxs_vals(self, miscs, idxs, vals, assert_all_vals_used=True, idxs_map=None): """ Unpack the idxs-vals format into the list of dictionaries that is `misc`. Parameters ---------- idxs_map : dic...
[ "def", "miscs_update_idxs_vals", "(", "self", ",", "miscs", ",", "idxs", ",", "vals", ",", "assert_all_vals_used", "=", "True", ",", "idxs_map", "=", "None", ")", ":", "if", "idxs_map", "is", "None", ":", "idxs_map", "=", "{", "}", "assert", "set", "(", ...
36.666667
19