text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def not_present(subset=None, show_ip=False, show_ipv4=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up accor...
[ "def", "not_present", "(", "subset", "=", "None", ",", "show_ip", "=", "False", ",", "show_ipv4", "=", "None", ")", ":", "show_ip", "=", "_show_ip_migration", "(", "show_ip", ",", "show_ipv4", ")", "return", "list_not_state", "(", "subset", "=", "subset", ...
30.333333
0.001332
def deriv(self, n=1): """ Compute *n*-th derivative of ``self``. :param n: Number of derivatives. :type n: positive integer :returns: *n*-th derivative of ``self``. """ if n==1: if self.order > 0: return PowerSeries(self.c[1:]*range(1,len(self...
[ "def", "deriv", "(", "self", ",", "n", "=", "1", ")", ":", "if", "n", "==", "1", ":", "if", "self", ".", "order", ">", "0", ":", "return", "PowerSeries", "(", "self", ".", "c", "[", "1", ":", "]", "*", "range", "(", "1", ",", "len", "(", ...
30.3125
0.012
def encodeSemiOctets(number): """ Semi-octet encoding algorithm (e.g. for phone numbers) :return: bytearray containing the encoded octets :rtype: bytearray """ if len(number) % 2 == 1: number = number + 'F' # append the "end" indicator octets = [int(number[i+1] + number[i], 16) ...
[ "def", "encodeSemiOctets", "(", "number", ")", ":", "if", "len", "(", "number", ")", "%", "2", "==", "1", ":", "number", "=", "number", "+", "'F'", "# append the \"end\" indicator", "octets", "=", "[", "int", "(", "number", "[", "i", "+", "1", "]", "...
37.5
0.010417
def _margtime_loglr(self, mf_snr, opt_snr): """Returns the log likelihood ratio marginalized over time. """ return special.logsumexp(mf_snr, b=self._deltat) - 0.5*opt_snr
[ "def", "_margtime_loglr", "(", "self", ",", "mf_snr", ",", "opt_snr", ")", ":", "return", "special", ".", "logsumexp", "(", "mf_snr", ",", "b", "=", "self", ".", "_deltat", ")", "-", "0.5", "*", "opt_snr" ]
47.75
0.010309
def set_rate_limiting(rate_limit, min_wait=timedelta(milliseconds=50)): ''' Enable or disable rate limiting on requests to the Mediawiki servers. If rate limiting is not enabled, under some circumstances (depending on load on Wikipedia, the number of requests you and other `wikipedia` users are making, and ot...
[ "def", "set_rate_limiting", "(", "rate_limit", ",", "min_wait", "=", "timedelta", "(", "milliseconds", "=", "50", ")", ")", ":", "global", "RATE_LIMIT", "global", "RATE_LIMIT_MIN_WAIT", "global", "RATE_LIMIT_LAST_CALL", "RATE_LIMIT", "=", "rate_limit", "if", "not", ...
32.7
0.009901
def bind_and_listen_on_socket(socket_name, accept_callback): """ Return socket name. :param accept_callback: Callback is called with a `PipeConnection` as argument. """ if is_windows(): from .win32_server import bind_and_listen_on_win32_socket return bind_and_listen_on_win32...
[ "def", "bind_and_listen_on_socket", "(", "socket_name", ",", "accept_callback", ")", ":", "if", "is_windows", "(", ")", ":", "from", ".", "win32_server", "import", "bind_and_listen_on_win32_socket", "return", "bind_and_listen_on_win32_socket", "(", "socket_name", ",", "...
37.769231
0.001988
def clearFindAndRebuild(self): """Empties catalog, then finds all contentish objects (i.e. objects with an indexObject method), and reindexes them. This may take a long time. """ def indexObject(obj, path): self.reindexObject(obj) self.counter += 1 ...
[ "def", "clearFindAndRebuild", "(", "self", ")", ":", "def", "indexObject", "(", "obj", ",", "path", ")", ":", "self", ".", "reindexObject", "(", "obj", ")", "self", ".", "counter", "+=", "1", "if", "self", ".", "counter", "%", "100", "==", "0", ":", ...
43.5
0.002249
def execute(cls, search, search_terms="", user=None, reference=None, save=True): """Create a new SearchQuery instance and execute a search against ES.""" warnings.warn( "Pending deprecation - please use `execute_search` function instead.", PendingDeprecationWarning, ) ...
[ "def", "execute", "(", "cls", ",", "search", ",", "search_terms", "=", "\"\"", ",", "user", "=", "None", ",", "reference", "=", "None", ",", "save", "=", "True", ")", ":", "warnings", ".", "warn", "(", "\"Pending deprecation - please use `execute_search` funct...
48.666667
0.013453
def touch_member(config, dcs): ''' Rip-off of the ha.touch_member without inter-class dependencies ''' p = Postgresql(config['postgresql']) p.set_state('running') p.set_role('master') def restapi_connection_string(config): protocol = 'https' if config.get('certfile') else 'http' con...
[ "def", "touch_member", "(", "config", ",", "dcs", ")", ":", "p", "=", "Postgresql", "(", "config", "[", "'postgresql'", "]", ")", "p", ".", "set_state", "(", "'running'", ")", "p", ".", "set_role", "(", "'master'", ")", "def", "restapi_connection_string", ...
34.2
0.001422
def dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fid
[ "def", "dangling_files", "(", "self", ")", ":", "for", "fid", "in", "self", ".", "_fsdb", ":", "if", "not", "self", ".", "_db", ".", "file_is_attached", "(", "'fsdb:///'", "+", "fid", ")", ":", "yield", "fid" ]
42.2
0.009302
def select_db(self, db): '''Set current db''' yield self._execute_command(COMMAND.COM_INIT_DB, db) yield self._read_ok_packet()
[ "def", "select_db", "(", "self", ",", "db", ")", ":", "yield", "self", ".", "_execute_command", "(", "COMMAND", ".", "COM_INIT_DB", ",", "db", ")", "yield", "self", ".", "_read_ok_packet", "(", ")" ]
37
0.013245
def px_to_pt(self, px): """Convert a size in pxel to a size in points.""" if px < 200: pt = self.PX_TO_PT[px] else: pt = int(floor((px - 1.21) / 1.332)) return pt
[ "def", "px_to_pt", "(", "self", ",", "px", ")", ":", "if", "px", "<", "200", ":", "pt", "=", "self", ".", "PX_TO_PT", "[", "px", "]", "else", ":", "pt", "=", "int", "(", "floor", "(", "(", "px", "-", "1.21", ")", "/", "1.332", ")", ")", "re...
26.5
0.009132
def validate(self): """Validate that the UnaryTransformation is correctly representable.""" _validate_operator_name(self.operator, UnaryTransformation.SUPPORTED_OPERATORS) if not isinstance(self.inner_expression, Expression): raise TypeError(u'Expected Expression inner_expression, g...
[ "def", "validate", "(", "self", ")", ":", "_validate_operator_name", "(", "self", ".", "operator", ",", "UnaryTransformation", ".", "SUPPORTED_OPERATORS", ")", "if", "not", "isinstance", "(", "self", ".", "inner_expression", ",", "Expression", ")", ":", "raise",...
58.428571
0.009639
def _systemd_notify_once(): """Send notification once to Systemd that service is ready. Systemd sets NOTIFY_SOCKET environment variable with the name of the socket listening for notifications from services. This method removes the NOTIFY_SOCKET environment variable to ensure not...
[ "def", "_systemd_notify_once", "(", ")", ":", "notify_socket", "=", "os", ".", "getenv", "(", "'NOTIFY_SOCKET'", ")", "if", "notify_socket", ":", "if", "notify_socket", ".", "startswith", "(", "'@'", ")", ":", "# abstract namespace socket", "notify_socket", "=", ...
43.636364
0.002039
def start(self): """Spawn the task. Throws RuntimeError if the task was already started.""" if not self.pipe is None: raise RuntimeError("Cannot start task twice") self.ioloop = tornado.ioloop.IOLoop.instance() if self.timeout > 0: self.expiration = self...
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "pipe", "is", "None", ":", "raise", "RuntimeError", "(", "\"Cannot start task twice\"", ")", "self", ".", "ioloop", "=", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ...
42.35
0.013857
def encode(self, word): """Return the Kölner Phonetik (numeric output) code for a word. While the output code is numeric, it is still a str because 0s can lead the code. Parameters ---------- word : str The word to transform Returns ------- ...
[ "def", "encode", "(", "self", ",", "word", ")", ":", "def", "_after", "(", "word", ",", "pos", ",", "letters", ")", ":", "\"\"\"Return True if word[pos] follows one of the supplied letters.\n\n Parameters\n ----------\n word : str\n ...
27.574468
0.000497
def _gcp_client(project, mod_name, pkg_name, key_file=None, http_auth=None, user_agent=None): """ Private GCP client builder. :param project: Google Cloud project string. :type project: ``str`` :param mod_name: Module name to load. Should be found in sys.path. :type mod_name: ...
[ "def", "_gcp_client", "(", "project", ",", "mod_name", ",", "pkg_name", ",", "key_file", "=", "None", ",", "http_auth", "=", "None", ",", "user_agent", "=", "None", ")", ":", "client", "=", "None", "if", "http_auth", "is", "None", ":", "http_auth", "=", ...
35.818182
0.001235
def ask(question, default_answer=False, default_answer_str="no"): """ Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The...
[ "def", "ask", "(", "question", ",", "default_answer", "=", "False", ",", "default_answer_str", "=", "\"no\"", ")", ":", "response", "=", "default_answer", "def", "should_ignore_tty", "(", ")", ":", "\"\"\"\n Check, if we want to ignore an opened tty result.\n ...
32.410256
0.000768
def eval(self, script, keys=[], args=[]): """Execute a Lua script server side.""" return self.execute(b'EVAL', script, len(keys), *(keys + args))
[ "def", "eval", "(", "self", ",", "script", ",", "keys", "=", "[", "]", ",", "args", "=", "[", "]", ")", ":", "return", "self", ".", "execute", "(", "b'EVAL'", ",", "script", ",", "len", "(", "keys", ")", ",", "*", "(", "keys", "+", "args", ")...
53
0.012422
def volume_shell(f_dist, m_dist): """ Compute the sensitive volume using sum over spherical shells. Parameters ----------- f_dist: numpy.ndarray The distances of found injections m_dist: numpy.ndarray The distances of missed injections Returns -------- volume: float ...
[ "def", "volume_shell", "(", "f_dist", ",", "m_dist", ")", ":", "f_dist", ".", "sort", "(", ")", "m_dist", ".", "sort", "(", ")", "distances", "=", "numpy", ".", "concatenate", "(", "[", "f_dist", ",", "m_dist", "]", ")", "dist_sorting", "=", "distances...
25.897436
0.000954
def args(self): """Parsed command-line arguments.""" if self._args is None: parser = self._build_parser() self._args = parser.parse_args() return self._args
[ "def", "args", "(", "self", ")", ":", "if", "self", ".", "_args", "is", "None", ":", "parser", "=", "self", ".", "_build_parser", "(", ")", "self", ".", "_args", "=", "parser", ".", "parse_args", "(", ")", "return", "self", ".", "_args" ]
33.166667
0.009804
def get_diffs(history): """ Look at files and compute the diffs intelligently """ # First get all possible representations mgr = plugins_get_mgr() keys = mgr.search('representation')['representation'] representations = [mgr.get_by_key('representation', k) for k in keys] for i in range...
[ "def", "get_diffs", "(", "history", ")", ":", "# First get all possible representations", "mgr", "=", "plugins_get_mgr", "(", ")", "keys", "=", "mgr", ".", "search", "(", "'representation'", ")", "[", "'representation'", "]", "representations", "=", "[", "mgr", ...
33.578313
0.013594
def toBytes(self, value): ''' toBytes - Convert a value to bytes using the encoding specified on this field @param value <str> - The field to convert to bytes @return <bytes> - The object encoded using the codec specified on this field. NOTE: This method may go away. ''' if type(value) == bytes: ...
[ "def", "toBytes", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "==", "bytes", ":", "return", "value", "return", "value", ".", "encode", "(", "self", ".", "getEncoding", "(", ")", ")" ]
27.923077
0.034667
def convertToPDF(self, from_page=0, to_page=-1, rotate=0): """Convert document to PDF selecting page range and optional rotation. Output bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_conv...
[ "def", "convertToPDF", "(", "self", ",", "from_page", "=", "0", ",", "to_page", "=", "-", "1", ",", "rotate", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for c...
59.5
0.008287
def check_n_eff(fit, pars=None, verbose=True): """Checks the effective sample size per iteration Parameters ---------- fit : StanFit4Model object pars : {str, sequence of str}, optional Parameter (or quantile) name(s). Test only specific parameters. Raises an exception if parameter ...
[ "def", "check_n_eff", "(", "fit", ",", "pars", "=", "None", ",", "verbose", "=", "True", ")", ":", "verbosity", "=", "int", "(", "verbose", ")", "n_iter", "=", "sum", "(", "fit", ".", "sim", "[", "'n_save'", "]", ")", "-", "sum", "(", "fit", ".",...
34.511905
0.001006
def is_capable(cls, requested_capability): """Returns true if the requested capability is supported by this plugin """ for c in requested_capability: if not c in cls.capability: return False return True
[ "def", "is_capable", "(", "cls", ",", "requested_capability", ")", ":", "for", "c", "in", "requested_capability", ":", "if", "not", "c", "in", "cls", ".", "capability", ":", "return", "False", "return", "True" ]
36.571429
0.01145
def save(self, *args, **kwargs): """Saves changes made on model instance if ``request`` or ``track_token`` keyword are provided. """ from tracked_model.models import History, RequestInfo if self.pk: action = ActionType.UPDATE changes = None else: ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "tracked_model", ".", "models", "import", "History", ",", "RequestInfo", "if", "self", ".", "pk", ":", "action", "=", "ActionType", ".", "UPDATE", "changes", "=", ...
36.717949
0.001361
def fix_spelling(self, words, join=True, joinstring=' '): """Simple function for quickly correcting misspelled words. Parameters ---------- words: list of str or str Either a list of pretokenized words or a string. In case of a string, it will be splitted using d...
[ "def", "fix_spelling", "(", "self", ",", "words", ",", "join", "=", "True", ",", "joinstring", "=", "' '", ")", ":", "fixed_words", "=", "[", "]", "for", "word", "in", "self", ".", "spellcheck", "(", "words", ",", "suggestions", "=", "True", ")", ":"...
34.657143
0.002406
def intensity_to_rgb(intensity, cmap='cubehelix', normalize=False): """ Convert a 1-channel matrix of intensities to an RGB image employing a colormap. This function requires matplotlib. See `matplotlib colormaps <http://matplotlib.org/examples/color/colormaps_reference.html>`_ for a list of availab...
[ "def", "intensity_to_rgb", "(", "intensity", ",", "cmap", "=", "'cubehelix'", ",", "normalize", "=", "False", ")", ":", "assert", "intensity", ".", "ndim", "==", "2", ",", "intensity", ".", "shape", "intensity", "=", "intensity", ".", "astype", "(", "\"flo...
36.807692
0.002037
def parse_table_data(lines): """"Parse list of lines from SOFT file into DataFrame. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Table data. """ # filter lines that do not start with symbols data = "\n".join([i.rstrip() for i in lin...
[ "def", "parse_table_data", "(", "lines", ")", ":", "# filter lines that do not start with symbols", "data", "=", "\"\\n\"", ".", "join", "(", "[", "i", ".", "rstrip", "(", ")", "for", "i", "in", "lines", "if", "not", "i", ".", "startswith", "(", "(", "\"^\...
29.294118
0.001946
def main(): '''Example code, showing the instantiation of a ChebiEntity, a call to get_name(), get_outgoings() and the calling of a number of methods of the returned Relation objects.''' chebi_entity = ChebiEntity(15903) print(chebi_entity.get_name()) for outgoing in chebi_entity.get_outgoings...
[ "def", "main", "(", ")", ":", "chebi_entity", "=", "ChebiEntity", "(", "15903", ")", "print", "(", "chebi_entity", ".", "get_name", "(", ")", ")", "for", "outgoing", "in", "chebi_entity", ".", "get_outgoings", "(", ")", ":", "target_chebi_entity", "=", "Ch...
42
0.002119
def bin(args): """ %prog bin filename filename.bin Serialize counts to bitarrays. """ from bitarray import bitarray p = OptionParser(bin.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) inp, outp = args fp = must_open(inp) fw...
[ "def", "bin", "(", "args", ")", ":", "from", "bitarray", "import", "bitarray", "p", "=", "OptionParser", "(", "bin", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ...
20.227273
0.002146
def focused_on_tweet(request): """ Return index if focused on tweet False if couldn't """ slots = request.get_slot_map() if "Index" in slots and slots["Index"]: index = int(slots['Index']) elif "Ordinal" in slots and slots["Index"]: parse_ordinal = lambda inp : int("".join([l fo...
[ "def", "focused_on_tweet", "(", "request", ")", ":", "slots", "=", "request", ".", "get_slot_map", "(", ")", "if", "\"Index\"", "in", "slots", "and", "slots", "[", "\"Index\"", "]", ":", "index", "=", "int", "(", "slots", "[", "'Index'", "]", ")", "eli...
35.958333
0.009029
def flip_coords(X,loop): """ Align circulation with z-axis """ if(loop[0]==1): return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X)) else: return X
[ "def", "flip_coords", "(", "X", ",", "loop", ")", ":", "if", "(", "loop", "[", "0", "]", "==", "1", ")", ":", "return", "np", ".", "array", "(", "map", "(", "lambda", "i", ":", "np", ".", "array", "(", "[", "i", "[", "2", "]", ",", "i", "...
32
0.050761
def get(self, request, bot_id, id, format=None): """ Get KikBot by id --- serializer: KikBotSerializer responseMessages: - code: 401 message: Not authenticated """ return super(KikBotDetail, self).get(request, bot_id, id, format)
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "KikBotDetail", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
31
0.009404
def check_solver(self, image_x, image_y, kwargs_lens): """ returns the precision of the solver to match the image position :param kwargs_lens: full lens model (including solved parameters) :param image_x: point source in image :param image_y: point source in image :retur...
[ "def", "check_solver", "(", "self", ",", "image_x", ",", "image_y", ",", "kwargs_lens", ")", ":", "source_x", ",", "source_y", "=", "self", ".", "_lensModel", ".", "ray_shooting", "(", "image_x", ",", "image_y", ",", "kwargs_lens", ")", "dist", "=", "np", ...
50.833333
0.008052
def _rows_event_to_dict(e, stream): """ Convert RowsEvent to a dict Args: e (pymysqlreplication.row_event.RowsEvent): the event stream (pymysqlreplication.BinLogStreamReader): the stream that yields event Returns: dict: event's data as a dict """ pk_cols = e.pri...
[ "def", "_rows_event_to_dict", "(", "e", ",", "stream", ")", ":", "pk_cols", "=", "e", ".", "primary_key", "if", "isinstance", "(", "e", ".", "primary_key", ",", "(", "list", ",", "tuple", ")", ")", "else", "(", "e", ".", "primary_key", ",", ")", "if"...
30.097561
0.000785
def make_placeholders(seq, start=1): """ Generate placeholders for the given sequence. """ if len(seq) == 0: raise ValueError('Sequence must have at least one element.') param_style = Context.current().param_style placeholders = None if isinstance(seq, dict): if param_style i...
[ "def", "make_placeholders", "(", "seq", ",", "start", "=", "1", ")", ":", "if", "len", "(", "seq", ")", "==", "0", ":", "raise", "ValueError", "(", "'Sequence must have at least one element.'", ")", "param_style", "=", "Context", ".", "current", "(", ")", ...
41.615385
0.000903
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None, other=None): """ Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will ...
[ "def", "cov_params", "(", "self", ",", "r_matrix", "=", "None", ",", "column", "=", "None", ",", "scale", "=", "None", ",", "cov_p", "=", "None", ",", "other", "=", "None", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'mle_settings'", ")", "a...
42.17284
0.000858
def add_ip(self,oid,value,label=None): """Short helper to add an IP address value to the MIB subtree.""" self.add_oid_entry(oid,'IPADDRESS',value,label=label)
[ "def", "add_ip", "(", "self", ",", "oid", ",", "value", ",", "label", "=", "None", ")", ":", "self", ".", "add_oid_entry", "(", "oid", ",", "'IPADDRESS'", ",", "value", ",", "label", "=", "label", ")" ]
53.333333
0.061728
def main(arguments=None): """ The main function used when ``yaml_to_database.py`` when installed as a cl tool """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", options_first=False, projectName=F...
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "# setup the command-line util settings", "su", "=", "tools", "(", "arguments", "=", "arguments", ",", "docString", "=", "__doc__", ",", "logLevel", "=", "\"WARNING\"", ",", "options_first", "=", "False", ...
30.775862
0.001629
def remove(self, key): ''' remove key from the namespace. it is fine to remove a key multiple times. ''' encodedKey = json.dumps(key) sql = 'DELETE FROM ' + self.table + ' WHERE name = %s' with self.connect() as conn: with doTransaction(conn): ...
[ "def", "remove", "(", "self", ",", "key", ")", ":", "encodedKey", "=", "json", ".", "dumps", "(", "key", ")", "sql", "=", "'DELETE FROM '", "+", "self", ".", "table", "+", "' WHERE name = %s'", "with", "self", ".", "connect", "(", ")", "as", "conn", ...
40
0.008152
def get_requirements(lookup=None): '''get_requirements reads in requirements and versions from the lookup obtained with get_lookup''' if lookup == None: lookup = get_lookup() install_requires = [] for module in lookup['INSTALL_REQUIRES']: module_name = module[0] module_meta...
[ "def", "get_requirements", "(", "lookup", "=", "None", ")", ":", "if", "lookup", "==", "None", ":", "lookup", "=", "get_lookup", "(", ")", "install_requires", "=", "[", "]", "for", "module", "in", "lookup", "[", "'INSTALL_REQUIRES'", "]", ":", "module_name...
36.95
0.009235
def concat(self, other, inplace=False): '''Concatenate two ChemicalEntity of the same kind''' # Create new entity if inplace: obj = self else: obj = self.copy() # Stitch every attribute for name, attr in obj.__attributes__.items()...
[ "def", "concat", "(", "self", ",", "other", ",", "inplace", "=", "False", ")", ":", "# Create new entity", "if", "inplace", ":", "obj", "=", "self", "else", ":", "obj", "=", "self", ".", "copy", "(", ")", "# Stitch every attribute", "for", "name", ",", ...
31.233333
0.008282
def parse_datetime(value): """Attempts to parse `value` into an instance of ``datetime.datetime``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string or datetime.datetime value. """ if not value: return None elif isinstanc...
[ "def", "parse_datetime", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "elif", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", "return", "dateutil", ".", "parser", ".", "parse", "(", "valu...
30.538462
0.002445
def new_schedule(self, program, station, time, duration, new, stereo, subtitled, hdtv, closeCaptioned, ei, tvRating, dolby, partNumber, partTotal): """Callback run for each new schedule entry""" if self.__v_schedule: # [Schedule: EP012964250031, 70387...
[ "def", "new_schedule", "(", "self", ",", "program", ",", "station", ",", "time", ",", "duration", ",", "new", ",", "stereo", ",", "subtitled", ",", "hdtv", ",", "closeCaptioned", ",", "ei", ",", "tvRating", ",", "dolby", ",", "partNumber", ",", "partTota...
56.75
0.014451
def write(self): """Return a string encoding of the page header and data. A ValueError is raised if the data is too big to fit in a single page. """ data = [ struct.pack("<4sBBqIIi", b"OggS", self.version, self.__type_flags, self.position, se...
[ "def", "write", "(", "self", ")", ":", "data", "=", "[", "struct", ".", "pack", "(", "\"<4sBBqIIi\"", ",", "b\"OggS\"", ",", "self", ".", "version", ",", "self", ".", "__type_flags", ",", "self", ".", "position", ",", "self", ".", "serial", ",", "sel...
39.40625
0.001548
def _is_defaultable(i, entry, table, check_for_aliases=True): """Determine if an entry may be removed from a routing table and be replaced by a default route. Parameters ---------- i : int Position of the entry in the table entry : RoutingTableEntry The entry itself table : ...
[ "def", "_is_defaultable", "(", "i", ",", "entry", ",", "table", ",", "check_for_aliases", "=", "True", ")", ":", "# May only have one source and sink (which may not be None)", "if", "(", "len", "(", "entry", ".", "sources", ")", "==", "1", "and", "len", "(", "...
38.029412
0.000754
def on_window_width_value_changed(self, wscale): """Changes the value of window_width in dconf """ val = wscale.get_value() self.settings.general.set_int('window-width', int(val))
[ "def", "on_window_width_value_changed", "(", "self", ",", "wscale", ")", ":", "val", "=", "wscale", ".", "get_value", "(", ")", "self", ".", "settings", ".", "general", ".", "set_int", "(", "'window-width'", ",", "int", "(", "val", ")", ")" ]
41.4
0.009479
def getViews(self, networkId, viewId, objectType, visualProperty, verbose=None): """ Returns a list of all Visual Property values for the Visual Property specified by the `visualProperty` and `objectType` parameters, in the Network View specified by the `viewId` and `networkId` parameters. ...
[ "def", "getViews", "(", "self", ",", "networkId", ",", "viewId", ",", "objectType", ",", "visualProperty", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'networks/'", "+", "str", "(", "netw...
62.470588
0.009276
def createResetLink(network, sensorRegionName, regionName): """Create a reset link from a sensor region: sensorRegionName -> regionName""" network.link(sensorRegionName, regionName, "UniformLink", "", srcOutput="resetOut", destInput="resetIn")
[ "def", "createResetLink", "(", "network", ",", "sensorRegionName", ",", "regionName", ")", ":", "network", ".", "link", "(", "sensorRegionName", ",", "regionName", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"resetOut\"", ",", "destInput", "=",...
64.75
0.015267
def start_service(addr, n, authenticator): """ Start a service """ s = Subscriber(addr, authenticator=authenticator) def do_something(line): pass s.subscribe('test', do_something) started = time.time() for _ in range(n): s.process() s.socket.close() duration = time.ti...
[ "def", "start_service", "(", "addr", ",", "n", ",", "authenticator", ")", ":", "s", "=", "Subscriber", "(", "addr", ",", "authenticator", "=", "authenticator", ")", "def", "do_something", "(", "line", ")", ":", "pass", "s", ".", "subscribe", "(", "'test'...
21.105263
0.002387
def auto_retry(fun): """Decorator for retrying method calls, based on instance parameters.""" @functools.wraps(fun) def decorated(instance, *args, **kwargs): """Wrapper around a decorated function.""" cfg = instance._retry_config remaining_tries = cfg.retry_attempts current_...
[ "def", "auto_retry", "(", "fun", ")", ":", "@", "functools", ".", "wraps", "(", "fun", ")", "def", "decorated", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper around a decorated function.\"\"\"", "cfg", "=", "instance", ...
30.1875
0.001003
async def acquire_async(self): """Acquire the :attr:`lock` asynchronously """ r = self.acquire(blocking=False) while not r: await asyncio.sleep(.01) r = self.acquire(blocking=False)
[ "async", "def", "acquire_async", "(", "self", ")", ":", "r", "=", "self", ".", "acquire", "(", "blocking", "=", "False", ")", "while", "not", "r", ":", "await", "asyncio", ".", "sleep", "(", ".01", ")", "r", "=", "self", ".", "acquire", "(", "block...
28.875
0.008403
def calibrate_plunger( self, top=None, bottom=None, blow_out=None, drop_tip=None): """Set calibration values for the pipette plunger. This can be called multiple times as the user sets each value, or you can set them all at once. ...
[ "def", "calibrate_plunger", "(", "self", ",", "top", "=", "None", ",", "bottom", "=", "None", ",", "blow_out", "=", "None", ",", "drop_tip", "=", "None", ")", ":", "if", "top", "is", "not", "None", ":", "self", ".", "plunger_positions", "[", "'top'", ...
28.487179
0.001741
def decode_solution(self, encoded_solution): """Return solution from an encoded representation.""" return self._decode_function(encoded_solution, *self._decode_args, **self._decode_kwargs)
[ "def", "decode_solution", "(", "self", ",", "encoded_solution", ")", ":", "return", "self", ".", "_decode_function", "(", "encoded_solution", ",", "*", "self", ".", "_decode_args", ",", "*", "*", "self", ".", "_decode_kwargs", ")" ]
59.5
0.008299
def _get_object_from_python_path(python_path): """Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: ...
[ "def", "_get_object_from_python_path", "(", "python_path", ")", ":", "# Dissect the path", "python_path", "=", "python_path", ".", "split", "(", "'.'", ")", "module_path", "=", "python_path", "[", ":", "-", "1", "]", "object_class", "=", "python_path", "[", "-",...
29.172414
0.002288
def commentify(value): """ Builds a comment. """ value = comment_links(value) if value is None: return if len(value.split('\n')) == 1: return "* " + value else: return '\n'.join([' * ' + l for l in value.split('\n')[:-1]])
[ "def", "commentify", "(", "value", ")", ":", "value", "=", "comment_links", "(", "value", ")", "if", "value", "is", "None", ":", "return", "if", "len", "(", "value", ".", "split", "(", "'\\n'", ")", ")", "==", "1", ":", "return", "\"* \"", "+", "va...
21.636364
0.028226
def loadFile(self, fileName): """ Load and display the PDF file specified by ``fileName``. """ # Test if the file exists. if not QtCore.QFile(fileName).exists(): msg = "File <b>{}</b> does not exist".format(self.qteAppletID()) self.qteLogger.info(msg) ...
[ "def", "loadFile", "(", "self", ",", "fileName", ")", ":", "# Test if the file exists.", "if", "not", "QtCore", ".", "QFile", "(", "fileName", ")", ".", "exists", "(", ")", ":", "msg", "=", "\"File <b>{}</b> does not exist\"", ".", "format", "(", "self", "."...
40.526316
0.001268
def argmin(indexable, key=None): """ Returns index / key of the item with the smallest value. This is similar to `numpy.argmin`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by key (Callable, op...
[ "def", "argmin", "(", "indexable", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", "and", "isinstance", "(", "indexable", ",", "collections_abc", ".", "Mapping", ")", ":", "return", "min", "(", "indexable", ".", "items", "(", ")", ",", ...
38.241379
0.00088
def data(self, index, role): """Return role specific data for the item referred by index.column().""" if not index.isValid(): return item = self.item(index) column = index.column() value = item.getItemData(column) if role == Qt.DisplayRole: ...
[ "def", "data", "(", "self", ",", "index", ",", "role", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "item", "=", "self", ".", "item", "(", "index", ")", "column", "=", "index", ".", "column", "(", ")", "value", "=", ...
36.054054
0.00146
def canonical_averages(ps, microcanonical_averages_arrays): """ Compute the canonical cluster statistics from microcanonical statistics This is according to Newman and Ziff, Equation (2). Note that we also simply average the bounds of the confidence intervals according to this formula. Paramet...
[ "def", "canonical_averages", "(", "ps", ",", "microcanonical_averages_arrays", ")", ":", "num_sites", "=", "microcanonical_averages_arrays", "[", "'N'", "]", "num_edges", "=", "microcanonical_averages_arrays", "[", "'M'", "]", "spanning_cluster", "=", "(", "'spanning_cl...
31.928571
0.000542
def newReference(self, name): """Creation of a new reference node. """ ret = libxml2mod.xmlNewReference(self._o, name) if ret is None:raise treeError('xmlNewReference() failed') __tmp = xmlNode(_obj=ret) return __tmp
[ "def", "newReference", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewReference", "(", "self", ".", "_o", ",", "name", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewReference() failed'", ")", "__tmp", ...
41.833333
0.015625
def create_secret(self, name, data, labels=None, driver=None): """ Create a secret Args: name (string): Name of the secret data (bytes): Secret data to be stored labels (dict): A mapping of labels to assign to the secret dr...
[ "def", "create_secret", "(", "self", ",", "name", ",", "data", ",", "labels", "=", "None", ",", "driver", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "bytes", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")"...
31.702703
0.001654
def show_summaries(cls, keys=None, indent=0, *args, **kwargs): """ Classmethod to print the summaries of the formatoptions Parameters ---------- %(Plotter.show_keys.parameters)s Other Parameters ---------------- %(Plotter.show_keys.other_parameters)s ...
[ "def", "show_summaries", "(", "cls", ",", "keys", "=", "None", ",", "indent", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "find_summary", "(", "key", ",", "key_txt", ",", "doc", ")", ":", "return", "'\\n'", ".", "join", ...
32.192308
0.00232
def can_execute(self): """True if we can execute the callback.""" return not self._disabled and all(dep.status == dep.node.S_OK for dep in self.deps)
[ "def", "can_execute", "(", "self", ")", ":", "return", "not", "self", ".", "_disabled", "and", "all", "(", "dep", ".", "status", "==", "dep", ".", "node", ".", "S_OK", "for", "dep", "in", "self", ".", "deps", ")" ]
54.333333
0.018182
def construct(self, streams, lowcut, highcut, filt_order, sampling_rate, multiplex, name, align, shift_len=0, reject=0.3, no_missed=True, plot=False): """ Construct a subspace detector from a list of streams, full rank. Subspace detector will be full-rank, fu...
[ "def", "construct", "(", "self", ",", "streams", ",", "lowcut", ",", "highcut", ",", "filt_order", ",", "sampling_rate", ",", "multiplex", ",", "name", ",", "align", ",", "shift_len", "=", "0", ",", "reject", "=", "0.3", ",", "no_missed", "=", "True", ...
45
0.001087
def tocimxml(self, ignore_host=False, ignore_namespace=False): """ Return the CIM-XML representation of this CIM class path, as an object of an appropriate subclass of :term:`Element`. If the class path has no namespace specified or if `ignore_namespace` is `True`, the returned ...
[ "def", "tocimxml", "(", "self", ",", "ignore_host", "=", "False", ",", "ignore_namespace", "=", "False", ")", ":", "classname_xml", "=", "cim_xml", ".", "CLASSNAME", "(", "self", ".", "classname", ")", "if", "self", ".", "namespace", "is", "None", "or", ...
37
0.00117
def scan_django_settings(values, imports): '''Recursively scans Django settings for values that appear to be imported modules. ''' if isinstance(values, (str, bytes)): if utils.is_import_str(values): imports.add(values) elif isinstance(values, dict): for k, v in values.it...
[ "def", "scan_django_settings", "(", "values", ",", "imports", ")", ":", "if", "isinstance", "(", "values", ",", "(", "str", ",", "bytes", ")", ")", ":", "if", "utils", ".", "is_import_str", "(", "values", ")", ":", "imports", ".", "add", "(", "values",...
40.176471
0.001431
def load_json(json_data, decoder=None): """ Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict ...
[ "def", "load_json", "(", "json_data", ",", "decoder", "=", "None", ")", ":", "if", "decoder", "is", "None", ":", "decoder", "=", "DateTimeDecoder", "return", "json", ".", "loads", "(", "json_data", ",", "object_hook", "=", "decoder", ".", "decode", ")" ]
30.857143
0.002247
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, s...
[ "def", "predict_proba", "(", "self", ",", "time", ")", ":", "check_is_fitted", "(", "self", ",", "\"unique_time_\"", ")", "time", "=", "check_array", "(", "time", ",", "ensure_2d", "=", "False", ")", "# K-M is undefined if estimate at last time point is non-zero", "...
33.842105
0.002268
def mode(ctx, mode, touch_eject, autoeject_timeout, chalresp_timeout, force): """ Manage connection modes (USB Interfaces). Get the current connection mode of the YubiKey, or set it to MODE. MODE can be a string, such as "OTP+FIDO+CCID", or a shortened form: "o+f+c". It can also be a mode number. ...
[ "def", "mode", "(", "ctx", ",", "mode", ",", "touch_eject", ",", "autoeject_timeout", ",", "chalresp_timeout", ",", "force", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "if", "autoeject_timeout", ":", "touch_eject", "=", "True", "autoeject"...
37.310345
0.0009
def groups_set_description(self, room_id, description, **kwargs): """Sets the description for the private group.""" return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs)
[ "def", "groups_set_description", "(", "self", ",", "room_id", ",", "description", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'groups.setDescription'", ",", "roomId", "=", "room_id", ",", "description", "=", "description", ...
79.333333
0.0125
def getdebug(environ=os.environ, true_values=TRUE_VALUES): ''' Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwis...
[ "def", "getdebug", "(", "environ", "=", "os", ".", "environ", ",", "true_values", "=", "TRUE_VALUES", ")", ":", "return", "environ", ".", "get", "(", "'DEBUG'", ",", "''", ")", ".", "lower", "(", ")", "in", "true_values" ]
35.909091
0.002469
def convert2hdf5(ClassIn, platform_name, bandnames, scale=1e-06): """Retrieve original RSR data and convert to internal hdf5 format. *scale* is the number which has to be multiplied to the wavelength data in order to get it in the SI unit meter """ import h5py instr = ClassIn(bandnames[0], pl...
[ "def", "convert2hdf5", "(", "ClassIn", ",", "platform_name", ",", "bandnames", ",", "scale", "=", "1e-06", ")", ":", "import", "h5py", "instr", "=", "ClassIn", "(", "bandnames", "[", "0", "]", ",", "platform_name", ")", "instr_name", "=", "instr", ".", "...
43.514286
0.000642
def _write_error_batch(batch, database, measurements): """Invoked when a batch submission fails, this method will submit one measurement to InfluxDB. It then adds a timeout to the IOLoop which will invoke :meth:`_write_error_batch_wait` which will evaluate the result and then determine what to do next. ...
[ "def", "_write_error_batch", "(", "batch", ",", "database", ",", "measurements", ")", ":", "if", "not", "measurements", ":", "LOGGER", ".", "info", "(", "'All %s measurements from batch %s processed'", ",", "database", ",", "batch", ")", "return", "LOGGER", ".", ...
38.21875
0.000797
def get_as_nullable_parameters(self, key): """ Converts map element into an Parameters or returns null if conversion is not possible. :param key: a key of element to get. :return: Parameters value of the element or null if conversion is not supported. """ value = self.g...
[ "def", "get_as_nullable_parameters", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get_as_nullable_map", "(", "key", ")", "return", "Parameters", "(", "value", ")", "if", "value", "!=", "None", "else", "None" ]
39.4
0.012407
def log_this(cls, f): """Decorator to log user actions""" @functools.wraps(f) def wrapper(*args, **kwargs): user_id = None if g.user: user_id = g.user.get_id() d = request.form.to_dict() or {} # request parameters can overwrite pos...
[ "def", "log_this", "(", "cls", ",", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "None", "if", "g", ".", "user", ":", "user_id", "=", "g", ...
32.12069
0.001042
def _print_beam(self, sequences: mx.nd.NDArray, accumulated_scores: mx.nd.NDArray, finished: mx.nd.NDArray, inactive: mx.nd.NDArray, constraints: List[Optional[constrained.ConstrainedHypothesis]], tim...
[ "def", "_print_beam", "(", "self", ",", "sequences", ":", "mx", ".", "nd", ".", "NDArray", ",", "accumulated_scores", ":", "mx", ".", "nd", ".", "NDArray", ",", "finished", ":", "mx", ".", "nd", ".", "NDArray", ",", "inactive", ":", "mx", ".", "nd", ...
55.5
0.009488
def split_label_fuzzy(self, label): """ Splits a label entered as user input. It's more flexible in it's syntax parsing than the L{split_label_strict} method, as it allows the exclamation mark (B{C{!}}) to be omitted. The ambiguity is resolved by searching the modules in the sna...
[ "def", "split_label_fuzzy", "(", "self", ",", "label", ")", ":", "module", "=", "function", "=", "None", "offset", "=", "0", "# Special case: None", "if", "not", "label", ":", "label", "=", "compat", ".", "b", "(", "\"0x0\"", ")", "else", ":", "# Remove ...
35.156716
0.001858
def client_list(self, *args): """Display a list of connected clients""" if len(self._clients) == 0: self.log('No clients connected') else: self.log(self._clients, pretty=True)
[ "def", "client_list", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "self", ".", "_clients", ")", "==", "0", ":", "self", ".", "log", "(", "'No clients connected'", ")", "else", ":", "self", ".", "log", "(", "self", ".", "_clients", ",...
36.333333
0.008969
def _draw(self): """ Interal draw method, simply prints to screen """ if self.display: print(self._formatstr.format(**self.__dict__), end='') sys.stdout.flush()
[ "def", "_draw", "(", "self", ")", ":", "if", "self", ".", "display", ":", "print", "(", "self", ".", "_formatstr", ".", "format", "(", "*", "*", "self", ".", "__dict__", ")", ",", "end", "=", "''", ")", "sys", ".", "stdout", ".", "flush", "(", ...
39.2
0.01
def shuffle_dataset(filenames, extra_fn=None): """Shuffles the dataset. Args: filenames: a list of strings extra_fn: an optional function from list of records to list of records to be called after shuffling a file. """ if outputs_exist(filenames): tf.logging.info("Skipping shuffle because out...
[ "def", "shuffle_dataset", "(", "filenames", ",", "extra_fn", "=", "None", ")", ":", "if", "outputs_exist", "(", "filenames", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Skipping shuffle because output files exist\"", ")", "return", "tf", ".", "logging",...
32.466667
0.011976
def __publish(topic, message, subject=None): """ Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :ret...
[ "def", "__publish", "(", "topic", ",", "message", ",", "subject", "=", "None", ")", ":", "try", ":", "SNS_CONNECTION", ".", "publish", "(", "topic", "=", "topic", ",", "message", "=", "message", ",", "subject", "=", "subject", ")", "logger", ".", "info...
32.578947
0.00157
def _init(self): """Initialize layer structure.""" group_stack = [self] clip_stack = [] last_layer = None for record, channels in self._record._iter_layers(): current_group = group_stack[-1] blocks = record.tagged_blocks end_of_group = False ...
[ "def", "_init", "(", "self", ")", ":", "group_stack", "=", "[", "self", "]", "clip_stack", "=", "[", "]", "last_layer", "=", "None", "for", "record", ",", "channels", "in", "self", ".", "_record", ".", "_iter_layers", "(", ")", ":", "current_group", "=...
40.7
0.0006
def acquisition_source(self, key, value): """Populate the ``acquisition_source`` key.""" def _get_datetime(value): d_value = force_single_element(value.get('d', '')) if d_value: try: date = PartialDate.loads(d_value) except ValueError: retu...
[ "def", "acquisition_source", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_get_datetime", "(", "value", ")", ":", "d_value", "=", "force_single_element", "(", "value", ".", "get", "(", "'d'", ",", "''", ")", ")", "if", "d_value", ":", "try"...
31.020408
0.001276
def _populate_header(self, root): """Populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part.""" # If this gets more complicated, it should be handled via an XSLT. title_stmt = root.xpath( 'tei:teiHeader/tei:fileDesc/tei:titleS...
[ "def", "_populate_header", "(", "self", ",", "root", ")", ":", "# If this gets more complicated, it should be handled via an XSLT.", "title_stmt", "=", "root", ".", "xpath", "(", "'tei:teiHeader/tei:fileDesc/tei:titleStmt'", ",", "namespaces", "=", "constants", ".", "NAMESP...
43.818182
0.00203
def given_lc_get_out_of_transit_points( time, flux, err_flux, blsfit_savpath=None, trapfit_savpath=None, in_out_transit_savpath=None, sigclip=None, magsarefluxes=True, nworkers=1, extra_maskfrac=0.03 ): '''This gets the out-of-transit light curve point...
[ "def", "given_lc_get_out_of_transit_points", "(", "time", ",", "flux", ",", "err_flux", ",", "blsfit_savpath", "=", "None", ",", "trapfit_savpath", "=", "None", ",", "in_out_transit_savpath", "=", "None", ",", "sigclip", "=", "None", ",", "magsarefluxes", "=", "...
36.23301
0.002087
def lstm_with_zoneout(hidden_size, keep_prob_c=0.5, keep_prob_h=0.95, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob_c: the probability to use the new value of the cell state rather than freezing it. keep_prob_h: the probability to use the new value ...
[ "def", "lstm_with_zoneout", "(", "hidden_size", ",", "keep_prob_c", "=", "0.5", ",", "keep_prob_h", "=", "0.95", ",", "*", "*", "kwargs", ")", ":", "lstm", "=", "LSTM", "(", "hidden_size", ",", "*", "*", "kwargs", ")", "keep_probs", "=", "LSTMState", "("...
38.772727
0.009153
def simple_highlight(img1, img2, opts): """Try to align the two images to minimize pixel differences. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, finding the aligment that minimzes the differences, and then smoothing it a bit to re...
[ "def", "simple_highlight", "(", "img1", ",", "img2", ",", "opts", ")", ":", "try", ":", "diff", ",", "(", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", ")", "=", "best_diff", "(", "img1", ",", "img2", ",", "opts", ")", "except", ...
39.846154
0.000943
def get_template_path(self, content=None): """ Find template. :return string: remplate path """ if isinstance(content, Paginator): return op.join('api', 'paginator.%s' % self.format) if isinstance(content, UpdatedList): return op.join('api', 'updated.%s...
[ "def", "get_template_path", "(", "self", ",", "content", "=", "None", ")", ":", "if", "isinstance", "(", "content", ",", "Paginator", ")", ":", "return", "op", ".", "join", "(", "'api'", ",", "'paginator.%s'", "%", "self", ".", "format", ")", "if", "is...
27.7
0.002326
def compute_mask_offsets(shard_id2num_examples): """Return the list of offsets associated with each shards. Args: shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples Returns: mask_offsets: `list[int]`, offset to skip for each of the shard """ total_num_examples = sum(shard_id2num_exam...
[ "def", "compute_mask_offsets", "(", "shard_id2num_examples", ")", ":", "total_num_examples", "=", "sum", "(", "shard_id2num_examples", ")", "mask_offsets", "=", "[", "]", "total_num_examples", "=", "0", "for", "num_examples_in_shard", "in", "shard_id2num_examples", ":",...
33.05
0.010294
def get_packages(directory, prefix): """return a list of subpackages for the given directory""" result = [] for package in os.listdir(directory): absfile = join(directory, package) if isdir(absfile): if exists(join(absfile, "__init__.py")): if prefix: ...
[ "def", "get_packages", "(", "directory", ",", "prefix", ")", ":", "result", "=", "[", "]", "for", "package", "in", "os", ".", "listdir", "(", "directory", ")", ":", "absfile", "=", "join", "(", "directory", ",", "package", ")", "if", "isdir", "(", "a...
38.538462
0.001949
def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
[ "def", "num_devices", "(", "self", ")", ":", "c_count", "=", "c_uint", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetCount_v2\"", ")", "(", "byref", "(", "c_count", ")", ")", ")", "return", "c_count", ".", "value" ]
34.333333
0.009479
def assignUserCredits(self, usernames, credits): """ assigns credit to a user. Inputs: usernames - list of users credits - number of credits to assign to the users Ouput: dictionary """ userAssignments = [] for name in usernames: ...
[ "def", "assignUserCredits", "(", "self", ",", "usernames", ",", "credits", ")", ":", "userAssignments", "=", "[", "]", "for", "name", "in", "usernames", ":", "userAssignments", ".", "append", "(", "{", "\"username\"", ":", "name", ",", "\"credits\"", ":", ...
32.296296
0.011136
def _draw_placeholder(self): """To be used in QTreeView""" if self.model().rowCount() == 0: painter = QPainter(self.viewport()) painter.setFont(_custom_font(is_italic=True)) painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt.TextWordWrap, ...
[ "def", "_draw_placeholder", "(", "self", ")", ":", "if", "self", ".", "model", "(", ")", ".", "rowCount", "(", ")", "==", "0", ":", "painter", "=", "QPainter", "(", "self", ".", "viewport", "(", ")", ")", "painter", ".", "setFont", "(", "_custom_font...
50.428571
0.008357
def unisim_csv_formatting(path, fname): """ Remove some useless stuff from the head of a csv file generated by unisim and returns a pandas dataframe """ with open(path+fname, 'r') as fobj: data = fobj.readlines() header = data[9].split(",")[:-1] unit_of_measures = data[10].sp...
[ "def", "unisim_csv_formatting", "(", "path", ",", "fname", ")", ":", "with", "open", "(", "path", "+", "fname", ",", "'r'", ")", "as", "fobj", ":", "data", "=", "fobj", ".", "readlines", "(", ")", "header", "=", "data", "[", "9", "]", ".", "split",...
37.833333
0.001433
def _call_single(self, client, command, *args): """ Call single """ try: return client.call(command, *args) except Exception as e: return None, str(e)
[ "def", "_call_single", "(", "self", ",", "client", ",", "command", ",", "*", "args", ")", ":", "try", ":", "return", "client", ".", "call", "(", "command", ",", "*", "args", ")", "except", "Exception", "as", "e", ":", "return", "None", ",", "str", ...
32.166667
0.010101
def generate_sphinx_all(): """Generate sphinx documentation. This generates a .rst file for all auto-generated image methods. Use it to regenerate the docs with something like:: $ python -c \ "import pyvips; pyvips.Operation.generate_sphinx_all()" > x And copy-paste the fi...
[ "def", "generate_sphinx_all", "(", ")", ":", "# generate list of all nicknames we can generate docstrings for", "all_nicknames", "=", "[", "]", "def", "add_nickname", "(", "gtype", ",", "a", ",", "b", ")", ":", "nickname", "=", "nickname_find", "(", "gtype", ")", ...
29.111111
0.001231
def sitesMatching(self, targets, matchCase, any_): """ Find sites (i.e., sequence indices) that match a given set of target sequence bases. @param targets: A C{set} of sequence bases to look for. @param matchCase: If C{True}, case will be considered in matching. @param a...
[ "def", "sitesMatching", "(", "self", ",", "targets", ",", "matchCase", ",", "any_", ")", ":", "# If case is unimportant, we convert everything (target bases and", "# sequences, as we read them) to lower case.", "if", "not", "matchCase", ":", "targets", "=", "set", "(", "m...
41.583333
0.001305