text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"): r""" Solve for the group index, :math:`n_g`, of a structure at a particular wavelength. Args: structure (Structure): The target structure to solve for modes. wavelength_step (...
[ "def", "solve_ng", "(", "self", ",", "structure", ",", "wavelength_step", "=", "0.01", ",", "filename", "=", "\"ng.dat\"", ")", ":", "wl_nom", "=", "structure", ".", "_wl", "self", ".", "solve", "(", "structure", ")", "n_ctrs", "=", "self", ".", "n_effs"...
35.204545
0.001256
def convert_text_to_CONLL( text, feature_generator ): ''' Converts given estnltk Text object into CONLL format and returns as a string. Uses given *feature_generator* to produce fields ID, FORM, LEMMA, CPOSTAG, POSTAG, FEATS for each token. Fields to predict (HEAD, DEPREL) will be ...
[ "def", "convert_text_to_CONLL", "(", "text", ",", "feature_generator", ")", ":", "from", "estnltk", ".", "text", "import", "Text", "if", "not", "isinstance", "(", "text", ",", "Text", ")", ":", "raise", "Exception", "(", "'(!) Unexpected type of input argument! Ex...
43.769231
0.019768
def loads(s, *args, **kwargs): """Helper function that wraps :func:`json.loads`. Automatically passes the object_hook for BSON type conversion. Raises ``TypeError``, ``ValueError``, ``KeyError``, or :exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON. :Parameters: - `json_options...
[ "def", "loads", "(", "s", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "json_options", "=", "kwargs", ".", "pop", "(", "\"json_options\"", ",", "DEFAULT_JSON_OPTIONS", ")", "kwargs", "[", "\"object_pairs_hook\"", "]", "=", "lambda", "pairs", ":", ...
40.84
0.000957
def lv_load_areas(self): """Returns a generator for iterating over load_areas Yields ------ int generator for iterating over load_areas """ for load_area in sorted(self._lv_load_areas, key=lambda _: repr(_)): yield load_area
[ "def", "lv_load_areas", "(", "self", ")", ":", "for", "load_area", "in", "sorted", "(", "self", ".", "_lv_load_areas", ",", "key", "=", "lambda", "_", ":", "repr", "(", "_", ")", ")", ":", "yield", "load_area" ]
29.6
0.009836
def makedir(self, path, class_id=None): """ Create a storage DirEntry name path """ return self.create_dir_entry(path, dir_type='storage', class_id=class_id)
[ "def", "makedir", "(", "self", ",", "path", ",", "class_id", "=", "None", ")", ":", "return", "self", ".", "create_dir_entry", "(", "path", ",", "dir_type", "=", "'storage'", ",", "class_id", "=", "class_id", ")" ]
37
0.015873
async def get_endpoint_for_did(wallet_handle: int, pool_handle: int, did: str) -> (str, Optional[str]): """ Returns endpoint information for the given DID. :param wallet_handle: Wallet handle (created by open_wallet). :param pool_handle: Poo...
[ "async", "def", "get_endpoint_for_did", "(", "wallet_handle", ":", "int", ",", "pool_handle", ":", "int", ",", "did", ":", "str", ")", "->", "(", "str", ",", "Optional", "[", "str", "]", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__nam...
39.342105
0.001958
def write_omega_scan_config(channellist, fobj, header=True): """Write a `ChannelList` to an Omega-pipeline scan configuration file This method is dumb and assumes the channels are sorted in the right order already """ if isinstance(fobj, FILE_LIKE): close = False else: fobj = op...
[ "def", "write_omega_scan_config", "(", "channellist", ",", "fobj", ",", "header", "=", "True", ")", ":", "if", "isinstance", "(", "fobj", ",", "FILE_LIKE", ")", ":", "close", "=", "False", "else", ":", "fobj", "=", "open", "(", "fobj", ",", "'w'", ")",...
32.037037
0.001122
def handle_args(): """ Default values are defined here. """ default_database_name = dbconfig.testdb_corpus_url.database parser = argparse.ArgumentParser( prog=os.path.basename(__file__), formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('dbname', ...
[ "def", "handle_args", "(", ")", ":", "default_database_name", "=", "dbconfig", ".", "testdb_corpus_url", ".", "database", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "os", ".", "path", ".", "basename", "(", "__file__", ")", ",", "form...
33.133333
0.001957
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: ...
[ "def", "_process_events", "(", "self", ",", "events", ")", ":", "for", "f", ",", "callback", ",", "transferred", ",", "key", ",", "ov", "in", "events", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking event callback {}'", ".", "form...
44.9
0.008734
def _pdf(self, x, dist, cache): """Probability density function.""" return evaluation.evaluate_density( dist, numpy.arctan(x), cache=cache)/(1+x*x)
[ "def", "_pdf", "(", "self", ",", "x", ",", "dist", ",", "cache", ")", ":", "return", "evaluation", ".", "evaluate_density", "(", "dist", ",", "numpy", ".", "arctan", "(", "x", ")", ",", "cache", "=", "cache", ")", "/", "(", "1", "+", "x", "*", ...
43
0.011429
def display_path(path): # type: (Union[str, Text]) -> str """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path...
[ "def", "display_path", "(", "path", ")", ":", "# type: (Union[str, Text]) -> str", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2...
43
0.00207
def _get_all_offsets(self, offset_ns=None): """ returns all token offsets of this document as a generator of (token node ID str, character onset int, character offset int) tuples. Parameters ---------- offset_ns : str or None The namespace from which the offs...
[ "def", "_get_all_offsets", "(", "self", ",", "offset_ns", "=", "None", ")", ":", "for", "token_id", ",", "_token_str", "in", "self", ".", "get_tokens", "(", ")", ":", "onset", "=", "self", ".", "node", "[", "token_id", "]", "[", "'{0}:{1}'", ".", "form...
42.26087
0.002012
def refreshLabels( self ): """ Refreshes the labels to display the proper title and count information. """ itemCount = self.itemCount() title = self.itemsTitle() if ( not itemCount ): self._itemsLabel.setText(' %s per page' % title) e...
[ "def", "refreshLabels", "(", "self", ")", ":", "itemCount", "=", "self", ".", "itemCount", "(", ")", "title", "=", "self", ".", "itemsTitle", "(", ")", "if", "(", "not", "itemCount", ")", ":", "self", ".", "_itemsLabel", ".", "setText", "(", "' %s per ...
35.916667
0.015837
def _verify_names(sampler, var_names, arg_names): """Make sure var_names and arg_names are assigned reasonably. This is meant to run before loading emcee objects into InferenceData. In case var_names or arg_names is None, will provide defaults. If they are not None, it verifies there are the right numb...
[ "def", "_verify_names", "(", "sampler", ",", "var_names", ",", "arg_names", ")", ":", "# There are 3 possible cases: emcee2, emcee3 and sampler read from h5 file (emcee3 only)", "if", "hasattr", "(", "sampler", ",", "\"args\"", ")", ":", "num_vars", "=", "sampler", ".", ...
34.245283
0.002142
def _prepare_ws(self, w0, mmap, n_steps): """ Decide how to make the return array. If mmap is False, this returns a full array of zeros, but with the correct shape as the output. If mmap is True, return a pointer to a memory-mapped array. The latter is particularly useful for int...
[ "def", "_prepare_ws", "(", "self", ",", "w0", ",", "mmap", ",", "n_steps", ")", ":", "from", ".", ".", "dynamics", "import", "PhaseSpacePosition", "if", "not", "isinstance", "(", "w0", ",", "PhaseSpacePosition", ")", ":", "w0", "=", "PhaseSpacePosition", "...
38.714286
0.00144
def pusher(task_queue, event, broker=None): """ Pulls tasks of the broker and puts them in the task queue :type task_queue: multiprocessing.Queue :type event: multiprocessing.Event """ if not broker: broker = get_broker() logger.info(_('{} pushing tasks at {}').format(current_process...
[ "def", "pusher", "(", "task_queue", ",", "event", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "logger", ".", "info", "(", "_", "(", "'{} pushing tasks at {}'", ")", ".", "format", "(", "curre...
37.393939
0.00158
def _send(self, msg, buffers=None): """Sends a message to the model in the front-end.""" if self.comm is not None and self.comm.kernel is not None: self.comm.send(data=msg, buffers=buffers)
[ "def", "_send", "(", "self", ",", "msg", ",", "buffers", "=", "None", ")", ":", "if", "self", ".", "comm", "is", "not", "None", "and", "self", ".", "comm", ".", "kernel", "is", "not", "None", ":", "self", ".", "comm", ".", "send", "(", "data", ...
53.5
0.009217
def _experiments_to_circuits(qobj): """Return a list of QuantumCircuit object(s) from a qobj Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj """ if qobj.experiments: circuits = [] for x i...
[ "def", "_experiments_to_circuits", "(", "qobj", ")", ":", "if", "qobj", ".", "experiments", ":", "circuits", "=", "[", "]", "for", "x", "in", "qobj", ".", "experiments", ":", "quantum_registers", "=", "[", "QuantumRegister", "(", "i", "[", "1", "]", ",",...
39.786885
0.000402
def bring_to_front(self): """adjusts sprite's z-order so that the sprite is on top of it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1
[ "def", "bring_to_front", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "z_order", "=", "self", ".", "parent", ".", "_z_ordered_sprites", "[", "-", "1", "]", ".", "z_order", "+", "1" ]
38.333333
0.008511
def show_nontab_menu(self, event): """Show the context menu assigned to nontabs section.""" menu = self.main.createPopupMenu() menu.exec_(self.dock_tabbar.mapToGlobal(event.pos()))
[ "def", "show_nontab_menu", "(", "self", ",", "event", ")", ":", "menu", "=", "self", ".", "main", ".", "createPopupMenu", "(", ")", "menu", ".", "exec_", "(", "self", ".", "dock_tabbar", ".", "mapToGlobal", "(", "event", ".", "pos", "(", ")", ")", ")...
50.25
0.009804
def indent(self): """ Performs an indentation """ if not self.tab_always_indent: super(PyIndenterMode, self).indent() else: cursor = self.editor.textCursor() assert isinstance(cursor, QtGui.QTextCursor) if cursor.hasSelection(): ...
[ "def", "indent", "(", "self", ")", ":", "if", "not", "self", ".", "tab_always_indent", ":", "super", "(", "PyIndenterMode", ",", "self", ")", ".", "indent", "(", ")", "else", ":", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "as...
37.238095
0.002494
def _DamerauLevenshtein(a, b): """Damerau-Levenshtein edit distance from a to b.""" memo = {} def Distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min(...
[ "def", "_DamerauLevenshtein", "(", "a", ",", "b", ")", ":", "memo", "=", "{", "}", "def", "Distance", "(", "x", ",", "y", ")", ":", "\"\"\"Recursively defined string distance with memoization.\"\"\"", "if", "(", "x", ",", "y", ")", "in", "memo", ":", "retu...
28.384615
0.014417
def get_opt_val(obj_pyxb, attr_str, default_val=None): """Get an optional Simple Content value from a PyXB element. The attributes for elements that are optional according to the schema and not set in the PyXB object are present and set to None. PyXB validation will fail if required elements are missi...
[ "def", "get_opt_val", "(", "obj_pyxb", ",", "attr_str", ",", "default_val", "=", "None", ")", ":", "try", ":", "return", "get_req_val", "(", "getattr", "(", "obj_pyxb", ",", "attr_str", ")", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":"...
29.4
0.001318
def clean(df,error_rate = 0): """ Superficially cleans data, i.e. changing simple things about formatting. Parameters: df - DataFrame DataFrame to clean error_rate - float {0 <= error_rate <= 1}, default 0 Maximum amount of errors/inconsistencies caused explicitly by cleaning, expressed ...
[ "def", "clean", "(", "df", ",", "error_rate", "=", "0", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "# Change colnames", "basics", ".", "clean_colnames", "(", "df", ")", "# Eventually use a more advanced function to clean colnames", "print", "(", "'Changed...
40.581395
0.01455
def execution_time(object): """ | Implements execution timing. | Any method / definition decorated will have it's execution timed through information messages. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) d...
[ "def", "execution_time", "(", "object", ")", ":", "@", "functools", ".", "wraps", "(", "object", ")", "def", "execution_time_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Implements execution timing.\n\n :param \\*args: Argumen...
28.459459
0.012856
def apply(self): """ Make the pending config become the running config for this task by triggering any necessary changes in the running task. Returns True to request a shorter period before the next call, False if nothing special is needed. """ log = self._params.get...
[ "def", "apply", "(", "self", ")", ":", "log", "=", "self", ".", "_params", ".", "get", "(", "'log'", ",", "self", ".", "_discard", ")", "if", "not", "self", ".", "_config_pending", ":", "raise", "TaskError", "(", "self", ".", "_name", ",", "\"No conf...
36.037037
0.002002
def _altair_chart_num_(self, chart_type, xfield, yfield, opts, style2, encode): """ Get a chart + text number chart """ style = {**style2} text_color = "grey" if "text_color" in style: text_color = style["text_color"] del style["text_color"] ...
[ "def", "_altair_chart_num_", "(", "self", ",", "chart_type", ",", "xfield", ",", "yfield", ",", "opts", ",", "style2", ",", "encode", ")", ":", "style", "=", "{", "*", "*", "style2", "}", "text_color", "=", "\"grey\"", "if", "\"text_color\"", "in", "styl...
44.166667
0.008615
def _make_prefixed(self, name, is_element, declared_prefixes, declarations): """Return namespace-prefixed tag or attribute name. Add appropriate declaration to `declarations` when neccessary. If no prefix for an element namespace is defined, make the elements namespace default (no pref...
[ "def", "_make_prefixed", "(", "self", ",", "name", ",", "is_element", ",", "declared_prefixes", ",", "declarations", ")", ":", "namespace", ",", "name", "=", "self", ".", "_split_qname", "(", "name", ",", "is_element", ")", "if", "namespace", "is", "None", ...
39.046512
0.001162
def create(self, **kwargs): """ Create an instance of the Blob Store Service with the typical starting settings. """ self.service.create(**kwargs) predix.config.set_env_value(self.use_class, 'url', self.service.settings.data['url']) predix.config....
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "service", ".", "create", "(", "*", "*", "kwargs", ")", "predix", ".", "config", ".", "set_env_value", "(", "self", ".", "use_class", ",", "'url'", ",", "self", ".", "ser...
46.294118
0.008717
def autogen_argparse_block(extra_args=[]): """ SHOULD TURN ANY REGISTERED ARGS INTO A A NEW PARSING CONFIG FILE FOR BETTER --help COMMANDS import utool as ut __REGISTERED_ARGS__ = ut.util_arg.__REGISTERED_ARGS__ Args: extra_args (list): (default = []) CommandLine: python -...
[ "def", "autogen_argparse_block", "(", "extra_args", "=", "[", "]", ")", ":", "#import utool as ut # NOQA", "#__REGISTERED_ARGS__", "# TODO FINISHME", "grouped_args", "=", "[", "]", "# Group similar a args", "for", "argtup", "in", "__REGISTERED_ARGS__", ":", "argstr_list"...
29.87037
0.001801
def smoothed_state(self,data,beta): """ Creates the negative log marginal likelihood of the model Parameters ---------- data : np.array Data to be smoothed beta : np.array Contains untransformed starting values for latent variables Returns ...
[ "def", "smoothed_state", "(", "self", ",", "data", ",", "beta", ")", ":", "T", ",", "Z", ",", "R", ",", "Q", ",", "H", "=", "self", ".", "_ss_matrices", "(", "beta", ")", "alpha", ",", "V", "=", "univariate_KFS", "(", "data", ",", "Z", ",", "H"...
24.45
0.021654
def make_tstore_conn(params, **kwargs): """ Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager params: The paramaters of the connection kwargs: log_level: logging level to use """ ...
[ "def", "make_tstore_conn", "(", "params", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "params", ".", "get", "(", "'log_level'", ",", "__LOG_LEVEL__", ")", ")", "log", ".", "debug", "(", "\"\\n%s\"", ",", "params", ")", "params", "."...
30.95
0.001567
def Mean(a, axis, keep_dims): """ Mean reduction op. """ return np.mean(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
[ "def", "Mean", "(", "a", ",", "axis", ",", "keep_dims", ")", ":", "return", "np", ".", "mean", "(", "a", ",", "axis", "=", "axis", "if", "not", "isinstance", "(", "axis", ",", "np", ".", "ndarray", ")", "else", "tuple", "(", "axis", ")", ",", "...
31.5
0.010309
def handleCONNACK(self, response): ''' Handles CONNACK packet from the server ''' state = self.__class__.__name__ log.error("Unexpected {packet:7} packet received in {log_source}", packet="CONNACK")
[ "def", "handleCONNACK", "(", "self", ",", "response", ")", ":", "state", "=", "self", ".", "__class__", ".", "__name__", "log", ".", "error", "(", "\"Unexpected {packet:7} packet received in {log_source}\"", ",", "packet", "=", "\"CONNACK\"", ")" ]
38.833333
0.012605
def inspect_image(name): ''' Retrieves image information. Equivalent to running the ``docker inspect`` Docker CLI command, but will only look for image information. .. note:: To inspect an image, it must have been pulled from a registry or built locally. Images on a Docker registry whic...
[ "def", "inspect_image", "(", "name", ")", ":", "ret", "=", "_client_wrapper", "(", "'inspect_image'", ",", "name", ")", "for", "param", "in", "(", "'Size'", ",", "'VirtualSize'", ")", ":", "if", "param", "in", "ret", ":", "ret", "[", "'{0}_Human'", ".", ...
26.5
0.001138
def parse_options(args=None, config=True, rootdir=CURDIR, **overrides): # noqa """ Parse options from command line and configuration files. :return argparse.Namespace: """ args = args or [] # Parse args from command string options = PARSER.parse_args(args) options.file_params = dict() ...
[ "def", "parse_options", "(", "args", "=", "None", ",", "config", "=", "True", ",", "rootdir", "=", "CURDIR", ",", "*", "*", "overrides", ")", ":", "# noqa", "args", "=", "args", "or", "[", "]", "# Parse args from command string", "options", "=", "PARSER", ...
31.696429
0.000546
def get_universe(self, as_str=False): """Returns universe the client is connected to. See ``Universe``. :param bool as_str: Return human-friendly universe name instead of an ID. :rtype: int|str """ result = self._iface.get_connected_universe() if as_str: ret...
[ "def", "get_universe", "(", "self", ",", "as_str", "=", "False", ")", ":", "result", "=", "self", ".", "_iface", ".", "get_connected_universe", "(", ")", "if", "as_str", ":", "return", "Universe", ".", "get_alias", "(", "result", ")", "return", "result" ]
30.166667
0.008043
def startTask(logger=None, action_type=u"", _serializers=None, **fields): """ Like L{action}, but creates a new top-level L{Action} with no parent. @param logger: The L{eliot.ILogger} to which to write messages, or C{None} to use the default one. @param action_type: The type of this action, ...
[ "def", "startTask", "(", "logger", "=", "None", ",", "action_type", "=", "u\"\"", ",", "_serializers", "=", "None", ",", "*", "*", "fields", ")", ":", "action", "=", "Action", "(", "logger", ",", "unicode", "(", "uuid4", "(", ")", ")", ",", "TaskLeve...
32.384615
0.001153
def handle_truncated_response(callback, params, entities): """ Handle truncated responses :param callback: :param params: :param entities: :return: """ results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False ...
[ "def", "handle_truncated_response", "(", "callback", ",", "params", ",", "entities", ")", ":", "results", "=", "{", "}", "for", "entity", "in", "entities", ":", "results", "[", "entity", "]", "=", "[", "]", "while", "True", ":", "try", ":", "marker_found...
29.1875
0.001036
def _decode_num(buf): """ Decodes little-endian integer from buffer Buffer can be of any size """ return functools.reduce(lambda acc, val: acc * 256 + tds_base.my_ord(val), reversed(buf), 0)
[ "def", "_decode_num", "(", "buf", ")", ":", "return", "functools", ".", "reduce", "(", "lambda", "acc", ",", "val", ":", "acc", "*", "256", "+", "tds_base", ".", "my_ord", "(", "val", ")", ",", "reversed", "(", "buf", ")", ",", "0", ")" ]
33.666667
0.009662
def _add_volume(line): ''' Analyse the line of volumes of ``drbdadm status`` ''' section = _analyse_status_type(line) fields = line.strip().split() volume = {} for field in fields: volume[field.split(':')[0]] = field.split(':')[1] if section == 'LOCALDISK': resource['lo...
[ "def", "_add_volume", "(", "line", ")", ":", "section", "=", "_analyse_status_type", "(", "line", ")", "fields", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "volume", "=", "{", "}", "for", "field", "in", "fields", ":", "volume", "[",...
25.25
0.002387
def binarySearchItem(seq, item, cmpfunc=cmp): r""" Search an ordered sequence `seq` for `item`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found instance of `item`, or `None` if item is not in `seq`. The returned item is NOT guaranteed to be the first occurrence of it...
[ "def", "binarySearchItem", "(", "seq", ",", "item", ",", "cmpfunc", "=", "cmp", ")", ":", "pos", "=", "binarySearchPos", "(", "seq", ",", "item", ",", "cmpfunc", ")", "if", "pos", "==", "-", "1", ":", "raise", "KeyError", "(", "\"Item not in seq\"", ")...
57.5
0.008565
def validate_ssl_certificate(self, client): """ Validate that a request to the new SSL certificate is successful :return: null on success, raise TwilioRestException if the request fails """ response = client.request('GET', 'https://api.twilio.com:8443') if response.statu...
[ "def", "validate_ssl_certificate", "(", "self", ",", "client", ")", ":", "response", "=", "client", ".", "request", "(", "'GET'", ",", "'https://api.twilio.com:8443'", ")", "if", "response", ".", "status_code", "<", "200", "or", "response", ".", "status_code", ...
53.888889
0.008114
def supervise(self): """If not in a hot_loop, call supervise() to start the tasks""" self.retval = set([]) stats = TaskMgrStats( worker_count=self.worker_count, log_interval=self.log_interval, hot_loop=self.hot_loop, ) hot_loop = self.hot_loop...
[ "def", "supervise", "(", "self", ")", ":", "self", ".", "retval", "=", "set", "(", "[", "]", ")", "stats", "=", "TaskMgrStats", "(", "worker_count", "=", "self", ".", "worker_count", ",", "log_interval", "=", "self", ".", "log_interval", ",", "hot_loop",...
40.602941
0.002298
def tohdf5(table, source, where=None, name=None, create=False, drop=False, description=None, title='', filters=None, expectedrows=10000, chunkshape=None, byteorder=None, createparents=False, sample=1000): """ Write to an HDF5 table. If `create` is `False`, assumes the table ...
[ "def", "tohdf5", "(", "table", ",", "source", ",", "where", "=", "None", ",", "name", "=", "None", ",", "create", "=", "False", ",", "drop", "=", "False", ",", "description", "=", "None", ",", "title", "=", "''", ",", "filters", "=", "None", ",", ...
34.552239
0.00042
def request(method, uri, *args, **kwargs): """ Handles all the common functionality required for API calls. Returns the resulting response object. Formats the request into a dict representing the headers and body that will be used to make the API call. """ req_method = req_methods[method.up...
[ "def", "request", "(", "method", ",", "uri", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "req_method", "=", "req_methods", "[", "method", ".", "upper", "(", ")", "]", "raise_exception", "=", "kwargs", ".", "pop", "(", "\"raise_exception\"", ",...
34.837838
0.000755
def db_check( block_id, new_ops, op, op_data, txid, vtxindex, checked_ops, db_state=None ): """ (required by virtualchain state engine) Given the block ID and a parsed operation, check to see if this is a *valid* operation. Is this operation consistent with blockstack's rules? checked_ops is...
[ "def", "db_check", "(", "block_id", ",", "new_ops", ",", "op", ",", "op_data", ",", "txid", ",", "vtxindex", ",", "checked_ops", ",", "db_state", "=", "None", ")", ":", "accept", "=", "True", "if", "db_state", "is", "not", "None", ":", "try", ":", "a...
33.907407
0.011146
def bitsBitOp(self, other, op, getVldFn, reduceCheckFn): """ :attention: If other is Bool signal, convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if iamVal and otherIsVal: ...
[ "def", "bitsBitOp", "(", "self", ",", "other", ",", "op", ",", "getVldFn", ",", "reduceCheckFn", ")", ":", "other", "=", "toHVal", "(", "other", ")", "iamVal", "=", "isinstance", "(", "self", ",", "Value", ")", "otherIsVal", "=", "isinstance", "(", "ot...
30.029412
0.000949
def compareSNPs(before, after, outFileName): """Compares two set of SNPs. :param before: the names of the markers in the ``before`` file. :param after: the names of the markers in the ``after`` file. :param outFileName: the name of the output file. :type before: set :type after: set :type ...
[ "def", "compareSNPs", "(", "before", ",", "after", ",", "outFileName", ")", ":", "# First, check that \"before\" is larger than \"after\"", "if", "len", "(", "after", ")", ">", "len", "(", "before", ")", ":", "msg", "=", "\"there are more SNPs after than before\"", ...
32
0.000722
def run(self): '''Run this worker''' self.signals(('TERM', 'INT', 'QUIT')) # Divide up the jobs that we have to divy up between the workers. This # produces evenly-sized groups of jobs resume = self.divide(self.resume, self.count) for index in range(self.count): ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "signals", "(", "(", "'TERM'", ",", "'INT'", ",", "'QUIT'", ")", ")", "# Divide up the jobs that we have to divy up between the workers. This", "# produces evenly-sized groups of jobs", "resume", "=", "self", ".", "div...
42.413043
0.002004
def get_server_public(self, password_verifier, server_private): """B = (k*v + g^b) % N :param int password_verifier: :param int server_private: :rtype: int """ return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime
[ "def", "get_server_public", "(", "self", ",", "password_verifier", ",", "server_private", ")", ":", "return", "(", "(", "self", ".", "_mult", "*", "password_verifier", ")", "+", "pow", "(", "self", ".", "_gen", ",", "server_private", ",", "self", ".", "_pr...
37.875
0.009677
def editItemInfo(self, json_dict): """ Allows for the direct edit of the service's item's information. To get the current item information, pull the data by calling iteminfo property. This will return the default template then pass this object back into the editItemInfo() as a d...
[ "def", "editItemInfo", "(", "self", ",", "json_dict", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/iteminfo/edit\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"serviceItemInfo\"", ":", "json", ".", "dumps", "(", "json_dict", ")", "}", "...
38.409091
0.009238
def run(self, args): """ Setup the environment, and run pylint. @param args: arguments will be passed to pylint @type args: list of string """ # set output stream. if self.outputStream: self.linter.reporter.set_output(self.outputStream) try: ...
[ "def", "run", "(", "self", ",", "args", ")", ":", "# set output stream.", "if", "self", ".", "outputStream", ":", "self", ".", "linter", ".", "reporter", ".", "set_output", "(", "self", ".", "outputStream", ")", "try", ":", "args", "=", "self", ".", "l...
31.977273
0.001379
def get_derived_metric_history(self, id, **kwargs): # noqa: E501 """Get the version history of a specific derived metric definition # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "get_derived_metric_history", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "g...
43.217391
0.001969
def repertoire(self, direction, mechanism, purview): """Return the cause or effect repertoire based on a direction. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism for which to calculate the repertoire. purview ...
[ "def", "repertoire", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ")", ":", "if", "direction", "==", "Direction", ".", "CAUSE", ":", "return", "self", ".", "cause_repertoire", "(", "mechanism", ",", "purview", ")", "elif", "direction", ...
36.304348
0.002334
def parse_fact(text, phase=None, res=None, date=None): """tries to extract fact fields from the string the optional arguments in the syntax makes us actually try parsing values and fallback to next phase start -> [end] -> activity[@category] -> tags Returns dict for the fact and ach...
[ "def", "parse_fact", "(", "text", ",", "phase", "=", "None", ",", "res", "=", "None", ",", "date", "=", "None", ")", ":", "now", "=", "dt", ".", "datetime", ".", "now", "(", ")", "# determine what we can look for", "phases", "=", "[", "\"date\"", ",", ...
35.347458
0.001399
def render(dson_input, saltenv='base', sls='', **kwargs): ''' Accepts DSON data as a string or as a file object and runs it through the JSON parser. :rtype: A Python data structure ''' if not isinstance(dson_input, six.string_types): dson_input = dson_input.read() log.debug('DSON i...
[ "def", "render", "(", "dson_input", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "dson_input", ",", "six", ".", "string_types", ")", ":", "dson_input", "=", "dson_input", ".", ...
29.941176
0.001905
def decr(self, key, value, noreply=False): """ The memcached "decr" command. Args: key: str, see class docs for details. value: int, the amount by which to increment the value. noreply: optional bool, False to wait for the reply (the default). Returns: ...
[ "def", "decr", "(", "self", ",", "key", ",", "value", ",", "noreply", "=", "False", ")", ":", "key", "=", "self", ".", "check_key", "(", "key", ")", "cmd", "=", "b'decr '", "+", "key", "+", "b' '", "+", "six", ".", "text_type", "(", "value", ")",...
34.25
0.002367
def extract_data_from_inspect(network_name, network_data): """ :param network_name: str :param network_data: dict :return: dict: { "ip_address4": "12.34.56.78" "ip_address6": "ff:fa:..." } """ a4 = None if network_name == "host": a4 = "127.0.0....
[ "def", "extract_data_from_inspect", "(", "network_name", ",", "network_data", ")", ":", "a4", "=", "None", "if", "network_name", "==", "\"host\"", ":", "a4", "=", "\"127.0.0.1\"", "n", "=", "{", "}", "a4", "=", "graceful_chain_get", "(", "network_data", ",", ...
25.333333
0.001812
def case_highlight(seq, subseq): """ Highlights all instances of subseq in seq by making them uppercase and everything else lowercase. """ return re.subs(subseq.lower(), subseq.upper(), seq.lower())
[ "def", "case_highlight", "(", "seq", ",", "subseq", ")", ":", "return", "re", ".", "subs", "(", "subseq", ".", "lower", "(", ")", ",", "subseq", ".", "upper", "(", ")", ",", "seq", ".", "lower", "(", ")", ")" ]
35.666667
0.009132
def logical_binary_op(self): """ logical_binary_op ::= and_op | or_op """ return (CaselessKeyword(self.syntax.and_op) | CaselessKeyword(self.syntax.or_op))
[ "def", "logical_binary_op", "(", "self", ")", ":", "return", "(", "CaselessKeyword", "(", "self", ".", "syntax", ".", "and_op", ")", "|", "CaselessKeyword", "(", "self", ".", "syntax", ".", "or_op", ")", ")" ]
33.166667
0.009804
def preds_conf_cred(self, knns_not_in_class): """ Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility. """ nb_data = knns_not_in_class.shape[0] preds_knn = np.zeros(nb_data, dtype=np.int32) confs = np.zeros(...
[ "def", "preds_conf_cred", "(", "self", ",", "knns_not_in_class", ")", ":", "nb_data", "=", "knns_not_in_class", ".", "shape", "[", "0", "]", "preds_knn", "=", "np", ".", "zeros", "(", "nb_data", ",", "dtype", "=", "np", ".", "int32", ")", "confs", "=", ...
43.347826
0.008832
def get_ngrams(inputfile, n=1, use_transcript=False, use_vtt=False): ''' Get ngrams from a text Sourced from: https://gist.github.com/dannguyen/93c2c43f4e65328b85af ''' words = [] if use_transcript: for s in audiogrep.convert_timestamps(inputfile): for w in s['words']: ...
[ "def", "get_ngrams", "(", "inputfile", ",", "n", "=", "1", ",", "use_transcript", "=", "False", ",", "use_vtt", "=", "False", ")", ":", "words", "=", "[", "]", "if", "use_transcript", ":", "for", "s", "in", "audiogrep", ".", "convert_timestamps", "(", ...
30.5
0.000935
def remove_all_events(self, calendar_id): '''Removes all events from a calendar. WARNING: Be very careful using this.''' # todo: incomplete now = datetime.now(tz=self.timezone) # timezone? start_time = datetime(year=now.year - 1, month=now.month, day=now.day, hour=now.hour, minute=now.m...
[ "def", "remove_all_events", "(", "self", ",", "calendar_id", ")", ":", "# todo: incomplete", "now", "=", "datetime", ".", "now", "(", "tz", "=", "self", ".", "timezone", ")", "# timezone?", "start_time", "=", "datetime", "(", "year", "=", "now", ".", "year...
52.208333
0.01489
def generate_cxx(module_name, code, specs=None, optimizations=None, module_dir=None): '''python + pythran spec -> c++ code returns a PythonModule object and an error checker the error checker can be used to print more detailed info on the origin of a compile error (e.g. due to bad typi...
[ "def", "generate_cxx", "(", "module_name", ",", "code", ",", "specs", "=", "None", ",", "optimizations", "=", "None", ",", "module_dir", "=", "None", ")", ":", "pm", ",", "ir", ",", "renamings", ",", "docstrings", "=", "front_middle_end", "(", "module_name...
40.922581
0.000154
def MapEncoder(field_descriptor): """Encoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N; """ # Can't look at field_descriptor.message_type._concrete_class because it may ...
[ "def", "MapEncoder", "(", "field_descriptor", ")", ":", "# Can't look at field_descriptor.message_type._concrete_class because it may", "# not have been initialized yet.", "message_type", "=", "field_descriptor", ".", "message_type", "encode_message", "=", "MessageEncoder", "(", "f...
30.666667
0.01506
def process_input(netIn, allowedformats, outputformat='G'): """ Takes input network and checks what the input is. Parameters ---------- netIn : array, dict, or TemporalNetwork Network (graphlet, contact or object) allowedformats : str Which format of network objects that are al...
[ "def", "process_input", "(", "netIn", ",", "allowedformats", ",", "outputformat", "=", "'G'", ")", ":", "inputtype", "=", "checkInput", "(", "netIn", ")", "# Convert TN to G representation", "if", "inputtype", "==", "'TN'", "and", "'TN'", "in", "allowedformats", ...
31.486111
0.000855
def __rebuild_tree(self, index_point): """! @brief Rebuilt tree in case of maxumum number of entries is exceeded. @param[in] index_point (uint): Index of point that is used as end point of re-building. @return (cftree) Rebuilt tree with encoded points till specifi...
[ "def", "__rebuild_tree", "(", "self", ",", "index_point", ")", ":", "rebuild_result", "=", "False", "increased_diameter", "=", "self", ".", "__tree", ".", "threshold", "*", "self", ".", "__diameter_multiplier", "tree", "=", "None", "while", "(", "rebuild_result"...
38.971429
0.020029
def main(): """ NAME zeq_magic_redo.py DESCRIPTION Calculate principal components through demagnetization data using bounds and calculation type stored in "redo" file SYNTAX zeq_magic_redo.py [command line options] OPTIONS -h prints help message -usr U...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "INCL", "=", "[", "\"LT-NO\"", ",", "\"LT-AF-Z\"", ",", "\"LT-T-Z\"", ",", "\"LT-M-Z\"", "]", "# looking for demag data", "beg", ",", "end", ",", "pole", ",", "geo", ",", "tilt", ",", "askave", ",", ...
49.173432
0.02942
def get_cpds(self, node=None): """ Returns the cpd of the node. If node is not specified returns all the CPDs that have been added till now to the graph Parameter --------- node: any hashable python object (optional) The node whose CPD we want. If node not sp...
[ "def", "get_cpds", "(", "self", ",", "node", "=", "None", ")", ":", "if", "node", "is", "not", "None", ":", "if", "node", "not", "in", "self", ".", "nodes", "(", ")", ":", "raise", "ValueError", "(", "'Node not present in the Directed Graph'", ")", "for"...
34.222222
0.002368
def eval_xof_pattern(node, pattern): """Parse a X of pattern * Set is_of_mul attribute * Set of_values attribute :param node: node to edit :type node: :param pattern: line to match :type pattern: str :return: end of the line (without X of :) :rtyp...
[ "def", "eval_xof_pattern", "(", "node", ",", "pattern", ")", ":", "xof_pattern", "=", "r\"^(-?\\d+%?),*(-?\\d*%?),*(-?\\d*%?) *of: *(.+)\"", "regex", "=", "re", ".", "compile", "(", "xof_pattern", ")", "matches", "=", "regex", ".", "search", "(", "pattern", ")", ...
37.392857
0.001862
def getAdaptiveSVDDims(self, singularValues, fractionOfMax=0.001): """ Compute the number of eigenvectors (singularValues) to keep. :param singularValues: :param fractionOfMax: :return: """ v = singularValues/singularValues[0] idx = numpy.where(v<fractionOfMax)[0] if len(idx): ...
[ "def", "getAdaptiveSVDDims", "(", "self", ",", "singularValues", ",", "fractionOfMax", "=", "0.001", ")", ":", "v", "=", "singularValues", "/", "singularValues", "[", "0", "]", "idx", "=", "numpy", ".", "where", "(", "v", "<", "fractionOfMax", ")", "[", ...
31.4375
0.011583
def eeg_erp(eeg, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, names="ERP", method="mean"): """ DOCS INCOMPLETE :( """ erp = {} data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central) for...
[ "def", "eeg_erp", "(", "eeg", ",", "times", "=", "None", ",", "index", "=", "None", ",", "include", "=", "\"all\"", ",", "exclude", "=", "None", ",", "hemisphere", "=", "\"both\"", ",", "central", "=", "True", ",", "verbose", "=", "True", ",", "names...
35.574468
0.001746
def partial_format(target, **kwargs): """Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute. """ output = target[:] for tag, var in re.findall(r'(\{(.*?)\...
[ "def", "partial_format", "(", "target", ",", "*", "*", "kwargs", ")", ":", "output", "=", "target", "[", ":", "]", "for", "tag", ",", "var", "in", "re", ".", "findall", "(", "r'(\\{(.*?)\\})'", ",", "output", ")", ":", "root", "=", "var", ".", "spl...
34.8
0.011194
def parse_JSON(self, JSON_string): """ Parses a *StationHistory* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_strin...
[ "def", "parse_JSON", "(", "self", ",", "JSON_string", ")", ":", "if", "JSON_string", "is", "None", ":", "raise", "parse_response_error", ".", "ParseResponseError", "(", "'JSON data is None'", ")", "d", "=", "json", ".", "loads", "(", "JSON_string", ")", "# Che...
48.405405
0.001368
def makeevenCIJ(n, k, sz_cl, seed=None): ''' This function generates a random, directed network with a specified number of fully connected modules linked together by evenly distributed remaining random connections. Parameters ---------- N : int number of vertices (must be power of 2...
[ "def", "makeevenCIJ", "(", "n", ",", "k", ",", "sz_cl", ",", "seed", "=", "None", ")", ":", "rng", "=", "get_rng", "(", "seed", ")", "# compute number of hierarchical levels and adjust cluster size", "mx_lvl", "=", "int", "(", "np", ".", "floor", "(", "np", ...
29.671053
0.001288
def exec_command_on_nodes(nodes, cmd, label, conn_params=None): """Execute a command on a node (id or hostname) or on a set of nodes. :param nodes: list of targets of the command cmd. Each must be an execo.Host. :param cmd: string representing the command to run on the...
[ "def", "exec_command_on_nodes", "(", "nodes", ",", "cmd", ",", "label", ",", "conn_params", "=", "None", ")", ":", "if", "isinstance", "(", "nodes", ",", "BASESTRING", ")", ":", "nodes", "=", "[", "nodes", "]", "if", "conn_params", "is", "None", ":", "...
36.541667
0.001111
def describe_handler(h): """Yield one or more lines describing the logging handler `h`.""" t = h.__class__ # using type() breaks in Python <= 2.6 format = handler_formats.get(t) if format is not None: yield format % h.__dict__ else: yield repr(h) level = getattr(h, 'level', logg...
[ "def", "describe_handler", "(", "h", ")", ":", "t", "=", "h", ".", "__class__", "# using type() breaks in Python <= 2.6", "format", "=", "handler_formats", ".", "get", "(", "t", ")", "if", "format", "is", "not", "None", ":", "yield", "format", "%", "h", "....
39.481481
0.000916
def get(cls, context, path, out_fp): """ Streamily download a file from the connection multiplexer process in the controller. :param mitogen.core.Context context: Reference to the context hosting the FileService that will be used to fetch the file. :param...
[ "def", "get", "(", "cls", ",", "context", ",", "path", ",", "out_fp", ")", ":", "LOG", ".", "debug", "(", "'get_file(): fetching %r from %r'", ",", "path", ",", "context", ")", "t0", "=", "time", ".", "time", "(", ")", "recv", "=", "mitogen", ".", "c...
40.964912
0.000836
def can_use_cache(self, target: Target) -> bool: """Return True if should attempt to load `target` from cache. Return False if `target` has to be built, regardless of its cache status (because cache is disabled, or dependencies are dirty). """ # if caching is disabled for t...
[ "def", "can_use_cache", "(", "self", ",", "target", ":", "Target", ")", "->", "bool", ":", "# if caching is disabled for this execution, then all targets are dirty", "if", "self", ".", "conf", ".", "no_build_cache", ":", "return", "False", "# if the target's `cachable` pr...
49.388889
0.002208
def setCookies(browser, domain, cookieJar): """ Writes all given cookies to the given browser Returns: bool - True if successful, false otherwise """ return BrowserCookies.browsers[browser].writeCookies(domain, cookieJar)
[ "def", "setCookies", "(", "browser", ",", "domain", ",", "cookieJar", ")", ":", "return", "BrowserCookies", ".", "browsers", "[", "browser", "]", ".", "writeCookies", "(", "domain", ",", "cookieJar", ")" ]
38.142857
0.010989
def crosscorrfunc(freq, cross): """ Calculate crosscorrelation function(s) for given cross spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. cross : numpy.ndarray 2 dimensional array of cross spectra, 1st axis units, 2nd axis units, ...
[ "def", "crosscorrfunc", "(", "freq", ",", "cross", ")", ":", "tbin", "=", "1.", "/", "(", "2.", "*", "np", ".", "max", "(", "freq", ")", ")", "*", "1e3", "# tbin in ms", "time", "=", "np", ".", "arange", "(", "-", "len", "(", "freq", ")", "/", ...
31.6875
0.001276
def loop_read(self, max_packets=1): """Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application. Use socket() to obtain the client socket to call select() or equivalent on. Do not use if you are using th...
[ "def", "loop_read", "(", "self", ",", "max_packets", "=", "1", ")", ":", "if", "self", ".", "_sock", "is", "None", "and", "self", ".", "_ssl", "is", "None", ":", "return", "MQTT_ERR_NO_CONN", "max_packets", "=", "len", "(", "self", ".", "_out_messages", ...
36.954545
0.002398
def select_icons(xmrs, left=None, relation=None, right=None): """ Return the list of matching ICONS for *xmrs*. :class:`~delphin.mrs.components.IndividualConstraint` objects for *xmrs* match if their `left` matches *left*, `relation` matches *relation*, and `right` matches *right*. The *left*, *rel...
[ "def", "select_icons", "(", "xmrs", ",", "left", "=", "None", ",", "relation", "=", "None", ",", "right", "=", "None", ")", ":", "icmatch", "=", "lambda", "ic", ":", "(", "(", "left", "is", "None", "or", "ic", ".", "left", "==", "left", ")", "and...
39.826087
0.002132
def home(self): """Set cursor to initial position and reset any shifting.""" self.command(c.LCD_RETURNHOME) self._cursor_pos = (0, 0) c.msleep(2)
[ "def", "home", "(", "self", ")", ":", "self", ".", "command", "(", "c", ".", "LCD_RETURNHOME", ")", "self", ".", "_cursor_pos", "=", "(", "0", ",", "0", ")", "c", ".", "msleep", "(", "2", ")" ]
34.6
0.011299
def is_empty(self): """Return whether the block of user data is empty.""" return (not self.breakpoint and not self.code_analysis and not self.todo and not self.bookmarks)
[ "def", "is_empty", "(", "self", ")", ":", "return", "(", "not", "self", ".", "breakpoint", "and", "not", "self", ".", "code_analysis", "and", "not", "self", ".", "todo", "and", "not", "self", ".", "bookmarks", ")" ]
49.75
0.009901
def _choice_format(self, occur): """Return the serialization format for a choice node.""" middle = "%s" if self.rng_children() else "<empty/>%s" fmt = self.start_tag() + middle + self.end_tag() if self.occur != 2: return "<optional>" + fmt + "</optional>" else: ...
[ "def", "_choice_format", "(", "self", ",", "occur", ")", ":", "middle", "=", "\"%s\"", "if", "self", ".", "rng_children", "(", ")", "else", "\"<empty/>%s\"", "fmt", "=", "self", ".", "start_tag", "(", ")", "+", "middle", "+", "self", ".", "end_tag", "(...
41.25
0.008902
def load_ipython_extension(ipython): """ Entry point of the IPython extension Parameters ---------- IPython : IPython interpreter An instance of the IPython interpreter that is handed over to the extension """ import IPython # don't continue if IPython version is < 3.0 ...
[ "def", "load_ipython_extension", "(", "ipython", ")", ":", "import", "IPython", "# don't continue if IPython version is < 3.0", "ipy_version", "=", "LooseVersion", "(", "IPython", ".", "__version__", ")", "if", "ipy_version", "<", "LooseVersion", "(", "\"3.0.0\"", ")", ...
31
0.001422
def navierStokes2d(u, v, p, dt, nt, rho, nu, boundaryConditionUV, boundardConditionP, nit=100): ''' solves the Navier-Stokes equation for incompressible flow one a regular 2d grid u,v,p --> initial velocity(u,v) and pressure(p) maps dt --> time s...
[ "def", "navierStokes2d", "(", "u", ",", "v", ",", "p", ",", "dt", ",", "nt", ",", "rho", ",", "nu", ",", "boundaryConditionUV", ",", "boundardConditionP", ",", "nit", "=", "100", ")", ":", "#next u, v, p maps:\r", "un", "=", "np", ".", "empty_like", "(...
26.452381
0.016493
def get_conversion(scale, limits): """ Get the conversion equations for each axis. limits: dict of min and max values for the axes in the order blr. """ fb = float(scale) / float(limits['b'][1] - limits['b'][0]) fl = float(scale) / float(limits['l'][1] - limits['l'][0]) fr = float(scale) / ...
[ "def", "get_conversion", "(", "scale", ",", "limits", ")", ":", "fb", "=", "float", "(", "scale", ")", "/", "float", "(", "limits", "[", "'b'", "]", "[", "1", "]", "-", "limits", "[", "'b'", "]", "[", "0", "]", ")", "fl", "=", "float", "(", "...
36.533333
0.001779
def search_hits(self, sort_by='CreationTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None): """ Return a page of a Requester's HITs, on behalf of the Requester. The operation returns HITs of any status, except for HITs that have been...
[ "def", "search_hits", "(", "self", ",", "sort_by", "=", "'CreationTime'", ",", "sort_direction", "=", "'Ascending'", ",", "page_size", "=", "10", ",", "page_number", "=", "1", ",", "response_groups", "=", "None", ")", ":", "params", "=", "{", "'SortProperty'...
45.25
0.011905
def as_page(self): """ Wrap this Tag as a self-contained webpage. Create a page with the following structure: .. code-block:: html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/htm...
[ "def", "as_page", "(", "self", ")", ":", "H", "=", "HTML", "(", ")", "utf8", "=", "H", ".", "meta", "(", "{", "'http-equiv'", ":", "'Content-type'", "}", ",", "content", "=", "\"text/html\"", ",", "charset", "=", "\"UTF-8\"", ")", "return", "H", ".",...
29.740741
0.002413
def configure(): """Configure uWSGI. This returns several configuration objects, which will be used to spawn several uWSGI processes. Applications are on 127.0.0.1 on ports starting from 8000. """ import os from uwsgiconf.presets.nice import PythonSection FILE = os.path.abspath(__fil...
[ "def", "configure", "(", ")", ":", "import", "os", "from", "uwsgiconf", ".", "presets", ".", "nice", "import", "PythonSection", "FILE", "=", "os", ".", "path", ".", "abspath", "(", "__file__", ")", "port", "=", "8000", "configurations", "=", "[", "]", ...
24.632653
0.000797
def get_identity(self, processor, user, sp_config): """ Create Identity dict (using SP-specific mapping) """ sp_mapping = sp_config.get('attribute_mapping', {'username': 'username'}) return processor.create_identity(user, sp_mapping, **sp_config.get('extra_config', {}))
[ "def", "get_identity", "(", "self", ",", "processor", ",", "user", ",", "sp_config", ")", ":", "sp_mapping", "=", "sp_config", ".", "get", "(", "'attribute_mapping'", ",", "{", "'username'", ":", "'username'", "}", ")", "return", "processor", ".", "create_id...
59.6
0.013245
def callback(newstate): """Callback from modem, process based on new state""" print('callback: ', newstate) if newstate == modem.STATE_RING: if state == modem.STATE_IDLE: att = {"cid_time": modem.get_cidtime, "cid_number": modem.get_cidnumber, "cid_n...
[ "def", "callback", "(", "newstate", ")", ":", "print", "(", "'callback: '", ",", "newstate", ")", "if", "newstate", "==", "modem", ".", "STATE_RING", ":", "if", "state", "==", "modem", ".", "STATE_IDLE", ":", "att", "=", "{", "\"cid_time\"", ":", "modem"...
38.235294
0.001502
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix where possible. ''' # WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00 # does not define this field so the description is taken from # http://tools.ietf.org/...
[ "def", "sanitize", "(", "self", ")", ":", "# WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00", "# does not define this field so the description is taken from", "# http://tools.ietf.org/html/draft-ietf-lisp-24", "#", "# Record TTL: The time in minutes the recipient of the Map-Reply wi...
49.4
0.000611
def add_source(source, key=None): """Add a package source to this system. @param source: a URL with a rpm package @param key: A key to be added to the system's keyring and used to verify the signatures on packages. Ideally, this should be an ASCII format GPG public key including the block headers....
[ "def", "add_source", "(", "source", ",", "key", "=", "None", ")", ":", "if", "source", "is", "None", ":", "log", "(", "'Source is not present. Skipping'", ")", "return", "if", "source", ".", "startswith", "(", "'http'", ")", ":", "directory", "=", "'/etc/y...
39.512195
0.000602
def pay(self, predecessor): """If the predecessor is not None, gives the appropriate amount of payoff to the predecessor in payment for its contribution to this match set's expected future payoff. The predecessor argument should be either None or a MatchSet instance whose selected action...
[ "def", "pay", "(", "self", ",", "predecessor", ")", ":", "assert", "predecessor", "is", "None", "or", "isinstance", "(", "predecessor", ",", "MatchSet", ")", "if", "predecessor", "is", "not", "None", ":", "expectation", "=", "self", ".", "_algorithm", ".",...
42.913043
0.001982
def getArgumentDescriptions(f): """ Get the arguments, default values, and argument descriptions for a function. Parses the argument descriptions out of the function docstring, using a format something lke this: :: [junk] argument_name: description... description... description... ...
[ "def", "getArgumentDescriptions", "(", "f", ")", ":", "# Get the argument names and default values", "argspec", "=", "inspect", ".", "getargspec", "(", "f", ")", "# Scan through the docstring to extract documentation for each argument as", "# follows:", "# Check the first word of...
33.904255
0.01311
def get_sid(principal): ''' Converts a username to a sid, or verifies a sid. Required for working with the DACL. Args: principal(str): The principal to lookup the sid. Can be a sid or a username. Returns: PySID Object: A sid Usage: .. code-block:: python ...
[ "def", "get_sid", "(", "principal", ")", ":", "# If None is passed, use the Universal Well-known SID \"Null SID\"", "if", "principal", "is", "None", ":", "principal", "=", "'NULL SID'", "# Test if the user passed a sid or a name", "try", ":", "sid", "=", "salt", ".", "uti...
25.477273
0.000859