text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _send_raw_command(ipmicmd, raw_bytes): """Use IPMI command object to send raw ipmi command to BMC :param ipmicmd: IPMI command object :param raw_bytes: string of hexadecimal values. This is commonly used for certain vendor specific commands. :returns: dict -- The response from IPMI device ...
[ "def", "_send_raw_command", "(", "ipmicmd", ",", "raw_bytes", ")", ":", "netfn", ",", "command", ",", "data", "=", "_parse_raw_bytes", "(", "raw_bytes", ")", "response", "=", "ipmicmd", ".", "raw_command", "(", "netfn", ",", "command", ",", "data", "=", "d...
34.846154
0.002151
def parse_file(self, sg_file=None, data=None): """Parse a sensor graph file into an AST describing the file. This function builds the statements list for this parser. If you pass ``sg_file``, it will be interpreted as the path to a file to parse. If you pass ``data`` it will be directl...
[ "def", "parse_file", "(", "self", ",", "sg_file", "=", "None", ",", "data", "=", "None", ")", ":", "if", "sg_file", "is", "not", "None", "and", "data", "is", "not", "None", ":", "raise", "ArgumentError", "(", "\"You must pass either a path to an sgf file or th...
40.548387
0.003885
def clear(self): """ Reset the config object to its initial state """ with self._lock: self._config = { CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}}, CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}}, }
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_config", "=", "{", "CacheConfig", ".", "Morlist", ":", "{", "'last'", ":", "defaultdict", "(", "float", ")", ",", "'intl'", ":", "{", "}", "}", ",", "CacheConf...
34.666667
0.00625
def get_source_for(self, asm_offset, runtime=True): """ Solidity source code snippet related to `asm_pos` evm bytecode offset. If runtime is False, initialization bytecode source map is used """ srcmap = self.get_srcmap(runtime) try: beg, size, _, _ = srcmap[asm_...
[ "def", "get_source_for", "(", "self", ",", "asm_offset", ",", "runtime", "=", "True", ")", ":", "srcmap", "=", "self", ".", "get_srcmap", "(", "runtime", ")", "try", ":", "beg", ",", "size", ",", "_", ",", "_", "=", "srcmap", "[", "asm_offset", "]", ...
35.105263
0.007299
def startCollapsedCommissioner(self): """start Collapsed Commissioner Returns: True: successful to start Commissioner False: fail to start Commissioner """ print '%s call startCollapsedCommissioner' % self.port if self.__startOpenThread(): tim...
[ "def", "startCollapsedCommissioner", "(", "self", ")", ":", "print", "'%s call startCollapsedCommissioner'", "%", "self", ".", "port", "if", "self", ".", "__startOpenThread", "(", ")", ":", "time", ".", "sleep", "(", "20", ")", "cmd", "=", "'commissioner start'"...
34.470588
0.004983
def mousePressEvent(self, event): """ Reimplements the :meth:`QLabel.mousePressEvent` method. :param event: QEvent. :type event: QEvent """ self.setPixmap(self.__active_pixmap) self.__menu and self.__menu.exec_(QCursor.pos()) self.pressed.emit()
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "self", ".", "setPixmap", "(", "self", ".", "__active_pixmap", ")", "self", ".", "__menu", "and", "self", ".", "__menu", ".", "exec_", "(", "QCursor", ".", "pos", "(", ")", ")", "self", "...
27.363636
0.006431
def init(base_level=DEFAULT_BASE_LOGGING_LEVEL, verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL, logging_config=None): """initializes a base logger you can use this to init a logger in any of your files. this will use config.py's LOGGER param and logging.dictConfig to configure the logger...
[ "def", "init", "(", "base_level", "=", "DEFAULT_BASE_LOGGING_LEVEL", ",", "verbose_level", "=", "DEFAULT_VERBOSE_LOGGING_LEVEL", ",", "logging_config", "=", "None", ")", ":", "if", "logging_config", "is", "None", ":", "logging_config", "=", "{", "}", "logging_config...
40.589744
0.000617
def write_element(elem_to_parse, file_or_path, encoding=DEFAULT_ENCODING): """ Writes the contents of the parsed element to file_or_path :see: get_element(parent_to_parse, element_path) """ xml_header = '<?xml version="1.0" encoding="{0}"?>'.format(encoding) get_element_tree(elem_to_parse).wri...
[ "def", "write_element", "(", "elem_to_parse", ",", "file_or_path", ",", "encoding", "=", "DEFAULT_ENCODING", ")", ":", "xml_header", "=", "'<?xml version=\"1.0\" encoding=\"{0}\"?>'", ".", "format", "(", "encoding", ")", "get_element_tree", "(", "elem_to_parse", ")", ...
38.888889
0.002793
def export(self): """ Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted. Yields a learner data object for each enrollment, containing: * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object. * ``completed_date``: datetime inst...
[ "def", "export", "(", "self", ")", ":", "# Fetch the consenting enrollment data, including the enterprise_customer_user.", "# Order by the course_id, to avoid fetching course API data more than we have to.", "enrollment_queryset", "=", "EnterpriseCourseEnrollment", ".", "objects", ".", "...
51.861111
0.006045
def generate_enum(self): """ Means that only value specified in the enum is valid. .. code-block:: python { 'enum': ['a', 'b'], } """ enum = self._definition['enum'] if not isinstance(enum, (list, tuple)): raise JsonSc...
[ "def", "generate_enum", "(", "self", ")", ":", "enum", "=", "self", ".", "_definition", "[", "'enum'", "]", "if", "not", "isinstance", "(", "enum", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "JsonSchemaDefinitionException", "(", "'enum must be...
33.5625
0.005435
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker( shell=self.shell, prefilter_manager=self, config=self.config )
[ "def", "init_checkers", "(", "self", ")", ":", "self", ".", "_checkers", "=", "[", "]", "for", "checker", "in", "_default_checkers", ":", "checker", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "config", "=", "self...
34.714286
0.008032
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
[ "def", "runCLI", "(", ")", ":", "args", "=", "docopt", "(", "__doc__", ",", "version", "=", "'0.3.0'", ")", "try", ":", "check_arguments", "(", "args", ")", "command_list", "=", "[", "'genconfig'", ",", "'run'", ",", "'generate'", "]", "select", "=", "...
41.105263
0.005006
def check_encoding_and_env(): """ It brings the environment variables to the screen. The user checks to see if they are using the correct variables. """ import sys import os if sys.getfilesystemencoding() in ['utf-8', 'UTF-8']: print(__(u"{0}File syste...
[ "def", "check_encoding_and_env", "(", ")", ":", "import", "sys", "import", "os", "if", "sys", ".", "getfilesystemencoding", "(", ")", "in", "[", "'utf-8'", ",", "'UTF-8'", "]", ":", "print", "(", "__", "(", "u\"{0}File system encoding correct{1}\"", ")", ".", ...
50.095238
0.007463
def set_hash_key(self, file): """Calculate and store hash key for file.""" filehasher = hashlib.md5() while True: data = file.read(8192) if not data: break filehasher.update(data) file.seek(0) self.hash_key = filehasher.hexdiges...
[ "def", "set_hash_key", "(", "self", ",", "file", ")", ":", "filehasher", "=", "hashlib", ".", "md5", "(", ")", "while", "True", ":", "data", "=", "file", ".", "read", "(", "8192", ")", "if", "not", "data", ":", "break", "filehasher", ".", "update", ...
31.4
0.006192
def get_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """ if isinstance(user_or_username, get_user_model()): user_or_username = get_username(user_or_username) key = six.u('%s_%s_%s') % (prefix, user_or_username, size) return si...
[ "def", "get_cache_key", "(", "user_or_username", ",", "size", ",", "prefix", ")", ":", "if", "isinstance", "(", "user_or_username", ",", "get_user_model", "(", ")", ")", ":", "user_or_username", "=", "get_username", "(", "user_or_username", ")", "key", "=", "s...
46.555556
0.002342
def delete(self, action, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='DELETE', headers=headers)
[ "def", "delete", "(", "self", ",", "action", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "request", "(", "make_url", "(", "self", ".", "endpoint", ",", "action", ")", ",", "method", "=", "'DELETE'", ",", "headers", "=", "headers", "...
40.2
0.009756
def from_composition_and_entries(comp, entries_in_chemsys, working_ion_symbol="Li"): """ Convenience constructor to make a ConversionElectrode from a composition and all entries in a chemical system. Args: comp: Starting composition for C...
[ "def", "from_composition_and_entries", "(", "comp", ",", "entries_in_chemsys", ",", "working_ion_symbol", "=", "\"Li\"", ")", ":", "pd", "=", "PhaseDiagram", "(", "entries_in_chemsys", ")", "return", "ConversionElectrode", ".", "from_composition_and_pd", "(", "comp", ...
49.375
0.003727
def mutagen_call(action, path, func, *args, **kwargs): """Call a Mutagen function with appropriate error handling. `action` is a string describing what the function is trying to do, and `path` is the relevant filename. The rest of the arguments describe the callable to invoke. We require at least ...
[ "def", "mutagen_call", "(", "action", ",", "path", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "mutagen", ".", "MutagenError", "as", "exc"...
46.565217
0.000915
def CopyFromDict(self, attributes): """Copies the attribute container from a dictionary. Args: attributes (dict[str, object]): attribute values per name. """ for attribute_name, attribute_value in attributes.items(): # Not using startswith to improve performance. if attribute_name[0] ...
[ "def", "CopyFromDict", "(", "self", ",", "attributes", ")", ":", "for", "attribute_name", ",", "attribute_value", "in", "attributes", ".", "items", "(", ")", ":", "# Not using startswith to improve performance.", "if", "attribute_name", "[", "0", "]", "==", "'_'",...
35.181818
0.010076
def _retransmit(self, transaction, message, future_time, retransmit_count): """ Thread function to retransmit the message in the future :param transaction: the transaction that owns the message that needs retransmission :param message: the message that needs the retransmission task ...
[ "def", "_retransmit", "(", "self", ",", "transaction", ",", "message", ",", "future_time", ",", "retransmit_count", ")", ":", "with", "transaction", ":", "while", "retransmit_count", "<", "defines", ".", "MAX_RETRANSMIT", "and", "(", "not", "message", ".", "ac...
47.90625
0.003836
def get_uint_info(self, field): """Get unsigned integer property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ ...
[ "def", "get_uint_info", "(", "self", ",", "field", ")", ":", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "ret", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_uint", ")", "(", ")", "_check_call", "(", "_LIB", ".", "XGDMatrixGetUIntInfo", ...
34.55
0.002817
def calc_wtd_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16): """Calculate the effective exposure. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` nbin : int Number of points per decade with w...
[ "def", "calc_wtd_exp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy_bins", ",", "cth_bins", ",", "fn", ",", "nbin", "=", "16", ")", ":", "cnts", "=", "calc_counts_edisp", "(", "skydir", ",", "ltc", ",", "event_class", ",",...
30.611111
0.003521
def get_time_as_string(self): """stub""" if self.has_time(): return (str(self.time['hours']).zfill(2) + ':' + str(self.time['minutes']).zfill(2) + ':' + str(self.time['seconds']).zfill(2)) raise IllegalState()
[ "def", "get_time_as_string", "(", "self", ")", ":", "if", "self", ".", "has_time", "(", ")", ":", "return", "(", "str", "(", "self", ".", "time", "[", "'hours'", "]", ")", ".", "zfill", "(", "2", ")", "+", "':'", "+", "str", "(", "self", ".", "...
39.857143
0.007018
def set_exception(self, exception): ''' set the exception message and set the status to failed ''' logger.error("%s : %s" % (exception.__class__.__name__, str(exception))) self._set_status(enumAsperaControllerStatus.FAILED, exception)
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "logger", ".", "error", "(", "\"%s : %s\"", "%", "(", "exception", ".", "__class__", ".", "__name__", ",", "str", "(", "exception", ")", ")", ")", "self", ".", "_set_status", "(", "enumAspe...
63.75
0.011628
def ensure_dir(directory: str) -> None: """Create a directory if it doesn't exist.""" if not os.path.isdir(directory): LOG.debug(f"Directory {directory} does not exist, creating it.") os.makedirs(directory)
[ "def", "ensure_dir", "(", "directory", ":", "str", ")", "->", "None", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "LOG", ".", "debug", "(", "f\"Directory {directory} does not exist, creating it.\"", ")", "os", ".", "makedir...
45.2
0.004348
def MI_associators(self, env, objectName, assocClassName, resultClassName, role, resultRole, propertyList): # pylint: disable=invalid-name """R...
[ "def", "MI_associators", "(", "self", ",", "env", ",", "objectName", ",", "assocClassName", ",", "resultClassName", ",", "role", ",", "resultRole", ",", "propertyList", ")", ":", "# pylint: disable=invalid-name", "# NOTE: This should honor the parameters resultClassName, ro...
42.426471
0.004404
def instantiate_inline_workflow_template( self, parent, template, instance_id=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Instantiates a te...
[ "def", "instantiate_inline_workflow_template", "(", "self", ",", "parent", ",", "template", ",", "instance_id", "=", "None", ",", "request_id", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "t...
44.333333
0.003771
def format(self, indent_level, indent_size=4): """Format this verifier Returns: string: A formatted string """ name = self.format_name('Boolean', indent_size) if self._require_value is not None: if self.long_desc is not None: name += '\n...
[ "def", "format", "(", "self", ",", "indent_level", ",", "indent_size", "=", "4", ")", ":", "name", "=", "self", ".", "format_name", "(", "'Boolean'", ",", "indent_size", ")", "if", "self", ".", "_require_value", "is", "not", "None", ":", "if", "self", ...
29.6875
0.006122
def run_optimization(self): """Run the optimization, call run_one_step with suitable placeholders. Returns: True if certificate is found False otherwise """ penalty_val = self.params['init_penalty'] # Don't use smoothing initially - very inaccurate for large dimension self.smooth_on...
[ "def", "run_optimization", "(", "self", ")", ":", "penalty_val", "=", "self", ".", "params", "[", "'init_penalty'", "]", "# Don't use smoothing initially - very inaccurate for large dimension", "self", ".", "smooth_on", "=", "False", "smooth_val", "=", "0", "learning_ra...
44.6
0.008776
def intranges_from_list(list_): """Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i. Ranges are encoded as single integers (start << 32 | end), not as tuples. ...
[ "def", "intranges_from_list", "(", "list_", ")", ":", "sorted_list", "=", "sorted", "(", "list_", ")", "ranges", "=", "[", "]", "last_write", "=", "-", "1", "for", "i", "in", "range", "(", "len", "(", "sorted_list", ")", ")", ":", "if", "i", "+", "...
35.35
0.001377
def _set_view(self): """Assign a view to current graph""" view_class = ReverseView if self.inverse_y_axis else View self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
[ "def", "_set_view", "(", "self", ")", ":", "view_class", "=", "ReverseView", "if", "self", ".", "inverse_y_axis", "else", "View", "self", ".", "view", "=", "view_class", "(", "self", ".", "width", "-", "self", ".", "margin_box", ".", "x", ",", "self", ...
33.25
0.007326
def bulkDetails(self, packageNames): """Get several apps details from a list of package names. This is much more efficient than calling N times details() since it requires only one request. If an item is not found it returns an empty object instead of throwing a RequestError('Item not f...
[ "def", "bulkDetails", "(", "self", ",", "packageNames", ")", ":", "params", "=", "{", "'au'", ":", "'1'", "}", "req", "=", "googleplay_pb2", ".", "BulkDetailsRequest", "(", ")", "req", ".", "docid", ".", "extend", "(", "packageNames", ")", "data", "=", ...
45
0.004184
def do_history(self, args: argparse.Namespace) -> None: """View, run, edit, save, or clear previously entered commands""" # -v must be used alone with no other options if args.verbose: if args.clear or args.edit or args.output_file or args.run or args.transcript \ ...
[ "def", "do_history", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# -v must be used alone with no other options", "if", "args", ".", "verbose", ":", "if", "args", ".", "clear", "or", "args", ".", "edit", "or", "args",...
43.34
0.003158
def get_address_by_id(cls, address_id, **kwargs): """Find Address Return single instance of Address by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_address_by_id(address_id, asy...
[ "def", "get_address_by_id", "(", "cls", ",", "address_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_get_address_by_id_with_ht...
40.571429
0.00344
def _svd_sym_koopman(K, C00_train, Ctt_train): """ Computes the SVD of the symmetrized Koopman operator in the empirical distribution. """ from pyemma._ext.variational.solvers.direct import spd_inv_sqrt # reweight operator to empirical distribution C0t_re = mdot(C00_train, K) # symmetrized opera...
[ "def", "_svd_sym_koopman", "(", "K", ",", "C00_train", ",", "Ctt_train", ")", ":", "from", "pyemma", ".", "_ext", ".", "variational", ".", "solvers", ".", "direct", "import", "spd_inv_sqrt", "# reweight operator to empirical distribution", "C0t_re", "=", "mdot", "...
47.692308
0.004747
def printfile(aFileName): """ Print a mission file to demonstrate "round trip" """ print("\nMission file: %s" % aFileName) with open(aFileName) as f: for line in f: print(' %s' % line.strip())
[ "def", "printfile", "(", "aFileName", ")", ":", "print", "(", "\"\\nMission file: %s\"", "%", "aFileName", ")", "with", "open", "(", "aFileName", ")", "as", "f", ":", "for", "line", "in", "f", ":", "print", "(", "' %s'", "%", "line", ".", "strip", "(",...
28.125
0.00431
def register_error_handler(app, handler=None): """ Register error handler Registers an exception handler on the app instance for every type of exception code werkzeug is aware about. :param app: flask.Flask - flask application instance :param handler: function - the handler :return: None ...
[ "def", "register_error_handler", "(", "app", ",", "handler", "=", "None", ")", ":", "if", "not", "handler", ":", "handler", "=", "default_error_handler", "for", "code", "in", "exceptions", ".", "default_exceptions", ".", "keys", "(", ")", ":", "app", ".", ...
31.733333
0.002041
def run_initialization_experiment(seed, num_neurons = 50, dim = 40, num_bins = 10, num_samples = 50*600, neuron_size = 10000, ...
[ "def", "run_initialization_experiment", "(", "seed", ",", "num_neurons", "=", "50", ",", "dim", "=", "40", ",", "num_bins", "=", "10", ",", "num_samples", "=", "50", "*", "600", ",", "neuron_size", "=", "10000", ",", "num_dendrites", "=", "400", ",", "de...
51.195122
0.020332
def upcoming(cls, api_key=None, stripe_account=None, **params): """Return a deferred.""" url = cls.class_url() + '/upcoming' return cls.request('get', url, params)
[ "def", "upcoming", "(", "cls", ",", "api_key", "=", "None", ",", "stripe_account", "=", "None", ",", "*", "*", "params", ")", ":", "url", "=", "cls", ".", "class_url", "(", ")", "+", "'/upcoming'", "return", "cls", ".", "request", "(", "'get'", ",", ...
46
0.010695
def reward_pool_balances(self): ''' Fetches and returns the 3 values needed to calculate the reward pool and other associated values such as rshares. Returns the reward balance, all recent claims and the current price of steem. ''' if self.reward_balance > 0: ...
[ "def", "reward_pool_balances", "(", "self", ")", ":", "if", "self", ".", "reward_balance", ">", "0", ":", "return", "self", ".", "reward_balance", "else", ":", "reward_fund", "=", "self", ".", "steem_instance", "(", ")", ".", "get_reward_fund", "(", ")", "...
42.315789
0.002433
def perturb(model, verbose=False, steady_state=None, eigmax=1.0-1e-6, solve_steady_state=False, order=1, details=True): """Compute first order approximation of optimal controls Parameters: ----------- model: NumericModel Model to be solved verbose: boolean ...
[ "def", "perturb", "(", "model", ",", "verbose", "=", "False", ",", "steady_state", "=", "None", ",", "eigmax", "=", "1.0", "-", "1e-6", ",", "solve_steady_state", "=", "False", ",", "order", "=", "1", ",", "details", "=", "True", ")", ":", "if", "ord...
27.850746
0.005694
def create_account(self, **kwargs): """ Create a new root account. :calls: `POST /api/v1/accounts \ <https://canvas.instructure.com/doc/api/accounts.html#method.accounts.create>`_ :rtype: :class:`canvasapi.account.Account` """ response = self.__requester.request...
[ "def", "create_account", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "__requester", ".", "request", "(", "'POST'", ",", "'accounts'", ",", "_kwargs", "=", "combine_kwargs", "(", "*", "*", "kwargs", ")", ")", "return", ...
30.933333
0.004184
def Deserialize(self, reader): """ Read serialized data from byte stream Args: reader (neocore.IO.BinaryReader): reader to read byte data from """ self.name = reader.ReadVarString().decode('utf-8') self.symbol = reader.ReadVarString().decode('utf-8') s...
[ "def", "Deserialize", "(", "self", ",", "reader", ")", ":", "self", ".", "name", "=", "reader", ".", "ReadVarString", "(", ")", ".", "decode", "(", "'utf-8'", ")", "self", ".", "symbol", "=", "reader", ".", "ReadVarString", "(", ")", ".", "decode", "...
38.333333
0.005666
def runcmds_plus_hooks(self, cmds: List[str]) -> bool: """Convenience method to run multiple commands by onecmd_plus_hooks. This method adds the given cmds to the command queue and processes the queue until completion or an error causes it to abort. Scripts that are loaded will have the...
[ "def", "runcmds_plus_hooks", "(", "self", ",", "cmds", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "stop", "=", "False", "self", ".", "cmdqueue", "=", "list", "(", "cmds", ")", "+", "self", ".", "cmdqueue", "try", ":", "while", "self", "....
49.195122
0.001945
def _text_image(page): """ returns text image URL """ img = None alt = page.data.get('label') or page.data.get('title') source = _image(page) if source: img = "![%s](%s)" % (alt, source) return img
[ "def", "_text_image", "(", "page", ")", ":", "img", "=", "None", "alt", "=", "page", ".", "data", ".", "get", "(", "'label'", ")", "or", "page", ".", "data", ".", "get", "(", "'title'", ")", "source", "=", "_image", "(", "page", ")", "if", "sourc...
22.8
0.004219
def qos_queue_scheduler_strict_priority_dwrr_traffic_class2(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") queue = ET.SubElement(qos, "queue") scheduler = ET.SubElement...
[ "def", "qos_queue_scheduler_strict_priority_dwrr_traffic_class2", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "qos", "=", "ET", ".", "SubElement", "(", "config", ",", "\"qos\"", ",", "xmlns", "...
49.384615
0.006116
def to_mllp(self, encoding_chars=None, trailing_children=False): """ Returns the er7 representation of the message wrapped with mllp encoding characters :type encoding_chars: ``dict`` :param encoding_chars: a dictionary containing the encoding chars or None to use the default ...
[ "def", "to_mllp", "(", "self", ",", "encoding_chars", "=", "None", ",", "trailing_children", "=", "False", ")", ":", "if", "encoding_chars", "is", "None", ":", "encoding_chars", "=", "self", ".", "encoding_chars", "return", "\"{0}{1}{2}{3}{2}\"", ".", "format", ...
49.65
0.007905
def get_json(self, path, watch=None): """Reads the data of the specified node and converts it to json.""" data, _ = self.get(path, watch) return load_json(data) if data else None
[ "def", "get_json", "(", "self", ",", "path", ",", "watch", "=", "None", ")", ":", "data", ",", "_", "=", "self", ".", "get", "(", "path", ",", "watch", ")", "return", "load_json", "(", "data", ")", "if", "data", "else", "None" ]
49.75
0.009901
def create_bandwidth_limit_rule(self, policy, body=None): """Creates a new bandwidth limit rule.""" return self.post(self.qos_bandwidth_limit_rules_path % policy, body=body)
[ "def", "create_bandwidth_limit_rule", "(", "self", ",", "policy", ",", "body", "=", "None", ")", ":", "return", "self", ".", "post", "(", "self", ".", "qos_bandwidth_limit_rules_path", "%", "policy", ",", "body", "=", "body", ")" ]
52.75
0.009346
def anomalyRemoveLabels(self, start, end, labelFilter): """ Remove labels from the anomaly classifier within this model. Removes all records if ``labelFilter==None``, otherwise only removes the labels equal to ``labelFilter``. :param start: (int) index to start removing labels :param end: (int)...
[ "def", "anomalyRemoveLabels", "(", "self", ",", "start", ",", "end", ",", "labelFilter", ")", ":", "self", ".", "_getAnomalyClassifier", "(", ")", ".", "getSelf", "(", ")", ".", "removeLabels", "(", "start", ",", "end", ",", "labelFilter", ")" ]
46.090909
0.005803
def unlock_kinetis_swd(jlink): """Unlocks a Kinetis device over SWD. Steps Involved in Unlocking: 1. Verify that the device is configured to read/write from the CoreSight registers; this is done by reading the Identification Code Register and checking its validity. This register is ...
[ "def", "unlock_kinetis_swd", "(", "jlink", ")", ":", "SWDIdentity", "=", "Identity", "(", "0x2", ",", "0xBA01", ")", "jlink", ".", "power_on", "(", ")", "jlink", ".", "coresight_configure", "(", ")", "# 1. Verify that the device is configured properly.", "flags", ...
40.512397
0.000597
def update_metadata(self, loadbalancer, metadata, node=None): """ Updates the existing metadata with the supplied dictionary. If 'node' is supplied, the metadata for that node is updated instead of for the load balancer. """ # Get the existing metadata md = self.g...
[ "def", "update_metadata", "(", "self", ",", "loadbalancer", ",", "metadata", ",", "node", "=", "None", ")", ":", "# Get the existing metadata", "md", "=", "self", ".", "get_metadata", "(", "loadbalancer", ",", "raw", "=", "True", ")", "id_lookup", "=", "dict...
46.529412
0.001858
def __get_xml_text(root): """ Return the text for the given root node (xml.dom.minidom). """ txt = "" for e in root.childNodes: if (e.nodeType == e.TEXT_NODE): txt += e.data return txt
[ "def", "__get_xml_text", "(", "root", ")", ":", "txt", "=", "\"\"", "for", "e", "in", "root", ".", "childNodes", ":", "if", "(", "e", ".", "nodeType", "==", "e", ".", "TEXT_NODE", ")", ":", "txt", "+=", "e", ".", "data", "return", "txt" ]
30.571429
0.004545
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string_ptr = CoreFoundation.CFStringGetCStringPtr( value, ...
[ "def", "cf_string_to_unicode", "(", "value", ")", ":", "string_ptr", "=", "CoreFoundation", ".", "CFStringGetCStringPtr", "(", "value", ",", "kCFStringEncodingUTF8", ")", "string", "=", "None", "if", "is_null", "(", "string_ptr", ")", "else", "ffi", ".", "string...
29.933333
0.002157
def clean_corpus_serial(corpus, lemmatizing="wordnet"): """ Extracts a bag-of-words from each document in a corpus serially. Inputs: - corpus: A python list of python strings. Each string is a document. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". ...
[ "def", "clean_corpus_serial", "(", "corpus", ",", "lemmatizing", "=", "\"wordnet\"", ")", ":", "list_of_bags_of_words", "=", "list", "(", ")", "append_bag_of_words", "=", "list_of_bags_of_words", ".", "append", "lemma_to_keywordbag_total", "=", "defaultdict", "(", "la...
47.36
0.004967
def tokenize(s): # type: (str) -> List[Token] """Translate a type comment into a list of tokens.""" original = s tokens = [] # type: List[Token] while True: if not s: tokens.append(End()) return tokens elif s[0] == ' ': s = s[1:] elif s[0]...
[ "def", "tokenize", "(", "s", ")", ":", "# type: (str) -> List[Token]", "original", "=", "s", "tokens", "=", "[", "]", "# type: List[Token]", "while", "True", ":", "if", "not", "s", ":", "tokens", ".", "append", "(", "End", "(", ")", ")", "return", "token...
40.894737
0.000629
def dynamic_message_event(self, sender, message): """Dynamic event handler - set message state based on event. Dynamic messages don't clear the message buffer. :param sender: Unused - the object that sent the message. :type sender: Object, None :param message: A message to sho...
[ "def", "dynamic_message_event", "(", "self", ",", "sender", ",", "message", ")", ":", "# LOGGER.debug('Dynamic message event')", "_", "=", "sender", "# NOQA", "self", ".", "dynamic_messages", ".", "append", "(", "message", ")", "self", ".", "dynamic_messages_log", ...
35.944444
0.003012
def set_parent(self, parent): """Set the parent reftrack object If a parent gets deleted, the children will be deleted too. .. Note:: Once the parent is set, it cannot be set again! :param parent: the parent reftrack object :type parent: :class:`Reftrack` | None :retur...
[ "def", "set_parent", "(", "self", ",", "parent", ")", ":", "assert", "self", ".", "_parent", "is", "None", "or", "self", ".", "_parent", "is", "parent", ",", "\"Cannot change the parent. Can only set from None.\"", "if", "parent", "and", "self", ".", "_parent", ...
37.727273
0.002349
def percussive(y, **kwargs): '''Extract percussive elements from an audio time-series. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series kwargs : additional keyword arguments. See `librosa.decompose.hpss` for details. Returns ------- y_percussive : np....
[ "def", "percussive", "(", "y", ",", "*", "*", "kwargs", ")", ":", "# Compute the STFT matrix", "stft", "=", "core", ".", "stft", "(", "y", ")", "# Remove harmonics", "stft_perc", "=", "decompose", ".", "hpss", "(", "stft", ",", "*", "*", "kwargs", ")", ...
26.357143
0.000871
def sflow_collector_use_vrf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow") collector = ET.SubElement(sflow, "collector") collector_ip_address_key = ET.SubElement(...
[ "def", "sflow_collector_use_vrf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "sflow", "=", "ET", ".", "SubElement", "(", "config", ",", "\"sflow\"", ",", "xmlns", "=", "\"urn:brocade.com:mgm...
51.2
0.006394
def validate(self): """ Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. """ validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt validation_scope = {} exec(val...
[ "def", "validate", "(", "self", ")", ":", "validation_code", "=", "self", ".", "setup_src", "+", "'\\nvalidation_result = '", "+", "self", ".", "stmt", "validation_scope", "=", "{", "}", "exec", "(", "validation_code", ",", "validation_scope", ")", "# Store the ...
60.068966
0.007345
def get_parent_gradebook_ids(self, gradebook_id): """Gets the parent ``Ids`` of the given gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook return: (osid.id.IdList) - the parent ``Ids`` of the gradebook raise: NotFound - ``gradebook_id`` is not found raise...
[ "def", "get_parent_gradebook_ids", "(", "self", ",", "gradebook_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.get_parent_bin_ids", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_sess...
50.352941
0.00344
def get_direct_derivatives(self, address): """Get all targets derived directly from the specified target. Note that the specified target itself is not returned. :API: public """ derivative_addrs = self._derivatives_by_derived_from.get(address, []) return [self.get_target(addr) for addr in deri...
[ "def", "get_direct_derivatives", "(", "self", ",", "address", ")", ":", "derivative_addrs", "=", "self", ".", "_derivatives_by_derived_from", ".", "get", "(", "address", ",", "[", "]", ")", "return", "[", "self", ".", "get_target", "(", "addr", ")", "for", ...
36.111111
0.003003
def start_blocking(self): """ Start the advertiser in the background, but wait until it is ready """ self._cav_started.clear() self.start() self._cav_started.wait()
[ "def", "start_blocking", "(", "self", ")", ":", "self", ".", "_cav_started", ".", "clear", "(", ")", "self", ".", "start", "(", ")", "self", ".", "_cav_started", ".", "wait", "(", ")" ]
32
0.015228
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def source_registered(source): self.__source = source def source_unregistered(source=None): pass def reference_registered(pr...
[ "def", "persistent_object_context_changed", "(", "self", ")", ":", "super", "(", ")", ".", "persistent_object_context_changed", "(", ")", "def", "source_registered", "(", "source", ")", ":", "self", ".", "__source", "=", "source", "def", "source_unregistered", "("...
49.321429
0.004261
def _parse_config(config_file_path): """ Parse Config File from yaml file. """ config_file = open(config_file_path, 'r') config = yaml.load(config_file) config_file.close() return config
[ "def", "_parse_config", "(", "config_file_path", ")", ":", "config_file", "=", "open", "(", "config_file_path", ",", "'r'", ")", "config", "=", "yaml", ".", "load", "(", "config_file", ")", "config_file", ".", "close", "(", ")", "return", "config" ]
33.5
0.004854
def match_attribute_name(self, el, attr, prefix): """Match attribute name and return value if it exists.""" value = None if self.supports_namespaces(): value = None # If we have not defined namespaces, we can't very well find them, so don't bother trying. if ...
[ "def", "match_attribute_name", "(", "self", ",", "el", ",", "attr", ",", "prefix", ")", ":", "value", "=", "None", "if", "self", ".", "supports_namespaces", "(", ")", ":", "value", "=", "None", "# If we have not defined namespaces, we can't very well find them, so d...
41.297872
0.004529
def economic_svd(G, epsilon=sqrt(finfo(float).eps)): r"""Economic Singular Value Decomposition. Args: G (array_like): Matrix to be factorized. epsilon (float): Threshold on the square root of the eigen values. Default is ``sqrt(finfo(float).eps)``. Returns: ...
[ "def", "economic_svd", "(", "G", ",", "epsilon", "=", "sqrt", "(", "finfo", "(", "float", ")", ".", "eps", ")", ")", ":", "from", "scipy", ".", "linalg", "import", "svd", "G", "=", "asarray", "(", "G", ",", "float", ")", "(", "U", ",", "S", ","...
28.703704
0.001248
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
[ "def", "generate_algebra_simplify_sample", "(", "vlist", ",", "ops", ",", "min_depth", ",", "max_depth", ")", ":", "depth", "=", "random", ".", "randrange", "(", "min_depth", ",", "max_depth", "+", "1", ")", "expr", "=", "random_expr", "(", "depth", ",", "...
40.913043
0.008307
def write_png(matrix, version, out, scale=1, border=None, color='#000', background='#fff', compresslevel=9, dpi=None, addad=True): """\ Serializes the QR Code as PNG image. By default, the generated PNG will be a greyscale image with a bitdepth of 1. If different colors are provided, an i...
[ "def", "write_png", "(", "matrix", ",", "version", ",", "out", ",", "scale", "=", "1", ",", "border", "=", "None", ",", "color", "=", "'#000'", ",", "background", "=", "'#fff'", ",", "compresslevel", "=", "9", ",", "dpi", "=", "None", ",", "addad", ...
45.089385
0.001697
def get_value(self, label): """ Get value from a single fully-qualified name """ for (key, value) in self.items: if key == label: return value
[ "def", "get_value", "(", "self", ",", "label", ")", ":", "for", "(", "key", ",", "value", ")", "in", "self", ".", "items", ":", "if", "key", "==", "label", ":", "return", "value" ]
32.2
0.018182
def use_theme(theme, directory=None): """Switches to the specified theme. This returns False if switching to the already active theme.""" repo = require_repo(directory) if theme not in list_themes(directory): raise ThemeNotFoundError(theme) old_theme = set_value(repo, 'theme', theme) return...
[ "def", "use_theme", "(", "theme", ",", "directory", "=", "None", ")", ":", "repo", "=", "require_repo", "(", "directory", ")", "if", "theme", "not", "in", "list_themes", "(", "directory", ")", ":", "raise", "ThemeNotFoundError", "(", "theme", ")", "old_the...
41.5
0.0059
def filter(self, entries): """Filter a set of declarations: keep only those related to this object. This will keep: - Declarations that 'override' the current ones - Declarations that are parameters to current ones """ return [ entry for entry in entries ...
[ "def", "filter", "(", "self", ",", "entries", ")", ":", "return", "[", "entry", "for", "entry", "in", "entries", "if", "self", ".", "split", "(", "entry", ")", "[", "0", "]", "in", "self", ".", "declarations", "]" ]
33.818182
0.007853
def modify_placeholder(request, page_id): """Modify the content of a page.""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) perm = request.user.has_perm('pages.change_page') if perm and request.method == 'PO...
[ "def", "modify_placeholder", "(", "request", ",", "page_id", ")", ":", "content_type", "=", "request", ".", "GET", ".", "get", "(", "'content_type'", ")", "language_id", "=", "request", ".", "GET", ".", "get", "(", "'language_id'", ")", "page", "=", "get_o...
39.461538
0.000634
def copyVarStatesFrom(self, particleState, varNames): """Copy specific variables from particleState into this particle. Parameters: -------------------------------------------------------------- particleState: dict produced by a particle's getState() method varNames: which variab...
[ "def", "copyVarStatesFrom", "(", "self", ",", "particleState", ",", "varNames", ")", ":", "# Set this to false if you don't want the variable to move anymore", "# after we set the state", "allowedToMove", "=", "True", "for", "varName", "in", "particleState", "[", "'varStates...
36.771429
0.006056
def cash_table(self): '现金的table' _cash = pd.DataFrame( data=[self.cash[1::], self.time_index_max], index=['cash', 'datetime'] ).T _cash = _cash.assign( date=_cash.datetime.apply(lambda x: pd.to_datetime(str(x)[0:10]...
[ "def", "cash_table", "(", "self", ")", ":", "_cash", "=", "pd", ".", "DataFrame", "(", "data", "=", "[", "self", ".", "cash", "[", "1", ":", ":", "]", ",", "self", ".", "time_index_max", "]", ",", "index", "=", "[", "'cash'", ",", "'datetime'", "...
27.921053
0.003643
def get_role_members(self, role): """get permissions of a user""" targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleDb).only('user') return json.loads(members.to_json())
[ "def", "get_role_members", "(", "self", ",", "role", ")", ":", "targetRoleDb", "=", "AuthGroup", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "role", "=", "role", ")", "members", "=", "AuthMembership", ".", "objects", "(", "groups__in",...
53.2
0.007407
def correspondence(soup): """ Find the corresp tags included in author-notes for primary correspondence """ correspondence = [] author_notes_nodes = raw_parser.author_notes(soup) if author_notes_nodes: corresp_nodes = raw_parser.corresp(author_notes_nodes) for tag in corres...
[ "def", "correspondence", "(", "soup", ")", ":", "correspondence", "=", "[", "]", "author_notes_nodes", "=", "raw_parser", ".", "author_notes", "(", "soup", ")", "if", "author_notes_nodes", ":", "corresp_nodes", "=", "raw_parser", ".", "corresp", "(", "author_not...
25.666667
0.002506
def start(self, service): """ Start the service, catching and logging exceptions """ try: map(self.start_class, service.depends) if service.is_running(): return if service in self.failed: log.warning("%s previously faile...
[ "def", "start", "(", "self", ",", "service", ")", ":", "try", ":", "map", "(", "self", ".", "start_class", ",", "service", ".", "depends", ")", "if", "service", ".", "is_running", "(", ")", ":", "return", "if", "service", "in", "self", ".", "failed",...
33.733333
0.003846
def index(self, item): """Finds the child index of a given item, searchs in added order.""" index_at = None for (i, child) in enumerate(self._children): if child.item == item: index_at = i break if index_at is None: raise ValueError...
[ "def", "index", "(", "self", ",", "item", ")", ":", "index_at", "=", "None", "for", "(", "i", ",", "child", ")", "in", "enumerate", "(", "self", ".", "_children", ")", ":", "if", "child", ".", "item", "==", "item", ":", "index_at", "=", "i", "bre...
38
0.005141
def run(self, positions, pixel_scale, results=None): """ Run this phase. Parameters ---------- pixel_scale positions results: autofit.tools.pipeline.ResultsCollection An object describing the results of the last phase or None if no phase has been exec...
[ "def", "run", "(", "self", ",", "positions", ",", "pixel_scale", ",", "results", "=", "None", ")", ":", "analysis", "=", "self", ".", "make_analysis", "(", "positions", "=", "positions", ",", "pixel_scale", "=", "pixel_scale", ",", "results", "=", "results...
34.684211
0.005908
def _u0Eq(logu,delta,pot,E,Lz22): """The equation that needs to be minimized to find u0""" u= numpy.exp(logu) sinh2u= numpy.sinh(u)**2. cosh2u= numpy.cosh(u)**2. dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta) return -(E*sinh2u-dU-Lz22/delta**2./sinh2u)
[ "def", "_u0Eq", "(", "logu", ",", "delta", ",", "pot", ",", "E", ",", "Lz22", ")", ":", "u", "=", "numpy", ".", "exp", "(", "logu", ")", "sinh2u", "=", "numpy", ".", "sinh", "(", "u", ")", "**", "2.", "cosh2u", "=", "numpy", ".", "cosh", "(",...
42.428571
0.039604
def _get_client_by_hostname(self, hostname): """Search GRR by hostname and get the latest active client. Args: hostname: hostname to search for. Returns: GRR API Client object Raises: DFTimewolfError: if no client ID found for hostname. """ # Search for the hostname in GRR ...
[ "def", "_get_client_by_hostname", "(", "self", ",", "hostname", ")", ":", "# Search for the hostname in GRR", "print", "(", "'Searching for client: {0:s}'", ".", "format", "(", "hostname", ")", ")", "try", ":", "search_result", "=", "self", ".", "grr_api", ".", "S...
35.244898
0.003944
def child_element(self, by=By.ID, value=None, el_class=None): """ Doesn't rise NoSuchElementException in case if there are no element with the selector. In this case ``exists()`` and ``is_displayed()`` methods of the element will return *False*. Attempt to call any other method supposed ...
[ "def", "child_element", "(", "self", ",", "by", "=", "By", ".", "ID", ",", "value", "=", "None", ",", "el_class", "=", "None", ")", ":", "el", ",", "selector", "=", "define_selector", "(", "by", ",", "value", ",", "el_class", ")", "return", "self", ...
41.8
0.004677
def answer(self) -> str: """Get a random answer in current language. :return: An answer. :Example: No """ answers = self._data['answers'] return self.random.choice(answers)
[ "def", "answer", "(", "self", ")", "->", "str", ":", "answers", "=", "self", ".", "_data", "[", "'answers'", "]", "return", "self", ".", "random", ".", "choice", "(", "answers", ")" ]
22.5
0.008547
def to_one_dim_array(values, as_type=None): """ Converts list or flattens n-dim array to 1-dim array if possible """ if isinstance(values, (list, tuple)): values = np.array(values, dtype=np.float32) elif isinstance(values, pd.Series): values = values.values values = values.flatten() ...
[ "def", "to_one_dim_array", "(", "values", ",", "as_type", "=", "None", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "np", ".", "floa...
37.25
0.002183
def post_log_artifacts(job_log): """Post a list of artifacts to a job.""" logger.debug("Downloading/parsing log for log %s", job_log.id) try: artifact_list = extract_text_log_artifacts(job_log) except LogSizeException as e: job_log.update_status(JobLog.SKIPPED_SIZE) logger.warni...
[ "def", "post_log_artifacts", "(", "job_log", ")", ":", "logger", ".", "debug", "(", "\"Downloading/parsing log for log %s\"", ",", "job_log", ".", "id", ")", "try", ":", "artifact_list", "=", "extract_text_log_artifacts", "(", "job_log", ")", "except", "LogSizeExcep...
42.030303
0.001409
def get_pdf_response(self, context, **response_kwargs): """ Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`django.http.HttpResponse` """ return render_to_pdf_response( request=self.request, template=self...
[ "def", "get_pdf_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "return", "render_to_pdf_response", "(", "request", "=", "self", ".", "request", ",", "template", "=", "self", ".", "get_template_names", "(", ")", ",", "cont...
32.6
0.003976
def create_session( self, kind: SessionKind, proxy_user: str = None, jars: List[str] = None, py_files: List[str] = None, files: List[str] = None, driver_memory: str = None, driver_cores: int = None, executor_memory: str = None, executor_cor...
[ "def", "create_session", "(", "self", ",", "kind", ":", "SessionKind", ",", "proxy_user", ":", "str", "=", "None", ",", "jars", ":", "List", "[", "str", "]", "=", "None", ",", "py_files", ":", "List", "[", "str", "]", "=", "None", ",", "files", ":"...
41.185567
0.000733
def iter(self, keyed=False, extended=False): '''Iterate over the rows. Each row is returned in a format that depends on the arguments `keyed` and `extended`. By default, each row is returned as list of their values. Args: keyed (bool, optional): When True, each retu...
[ "def", "iter", "(", "self", ",", "keyed", "=", "False", ",", "extended", "=", "False", ")", ":", "# Error if closed", "if", "self", ".", "closed", ":", "message", "=", "'Stream is closed. Please call \"stream.open()\" first.'", "raise", "exceptions", ".", "Tabulat...
39.829787
0.002086
def lag_calc(detections, detect_data, template_names, templates, shift_len=0.2, min_cc=0.4, horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'], cores=1, interpolate=False, plot=False, parallel=True, debug=0): """ Main lag-calculation function for detections of spe...
[ "def", "lag_calc", "(", "detections", ",", "detect_data", ",", "template_names", ",", "templates", ",", "shift_len", "=", "0.2", ",", "min_cc", "=", "0.4", ",", "horizontal_chans", "=", "[", "'E'", ",", "'N'", ",", "'1'", ",", "'2'", "]", ",", "vertical_...
46.079812
0.0001
def download_binaries(package_dir=False): """Download all binaries for the current platform Parameters ---------- package_dir: bool If set to `True`, the binaries will be downloaded to the `resources` directory of the qpsphere package instead of to the users application data dir...
[ "def", "download_binaries", "(", "package_dir", "=", "False", ")", ":", "# bhfield", "# make sure the binary is available on the system", "paths", "=", "_bhfield", ".", "fetch", ".", "get_binaries", "(", ")", "if", "package_dir", ":", "# Copy the binaries to the `resource...
31.72973
0.000826
def _create_datadict(cls, internal_name): """Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object """ if internal_name == "LOCATION": ...
[ "def", "_create_datadict", "(", "cls", ",", "internal_name", ")", ":", "if", "internal_name", "==", "\"LOCATION\"", ":", "return", "Location", "(", ")", "if", "internal_name", "==", "\"DESIGN CONDITIONS\"", ":", "return", "DesignConditions", "(", ")", "if", "int...
36.321429
0.002874
def write_tree_file(tree, hostname, buf): ''' write something into treedir/hostname ''' # TODO: might be nice to append playbook runs per host in a similar way # in which case, we'd want append mode. path = os.path.join(tree, hostname) fd = open(path, "w+") fd.write(buf) fd.close()
[ "def", "write_tree_file", "(", "tree", ",", "hostname", ",", "buf", ")", ":", "# TODO: might be nice to append playbook runs per host in a similar way", "# in which case, we'd want append mode.", "path", "=", "os", ".", "path", ".", "join", "(", "tree", ",", "hostname", ...
33.666667
0.003215
def norm_coefs(self): """Multiply all coefficients by the same factor, so that their sum becomes one.""" sum_coefs = self.sum_coefs self.ar_coefs /= sum_coefs self.ma_coefs /= sum_coefs
[ "def", "norm_coefs", "(", "self", ")", ":", "sum_coefs", "=", "self", ".", "sum_coefs", "self", ".", "ar_coefs", "/=", "sum_coefs", "self", ".", "ma_coefs", "/=", "sum_coefs" ]
36.666667
0.008889
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/ef...
[ "def", "transaction_effects", "(", "self", ",", "tx_hash", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/transactions/{tx_hash}/effects'", ".", "format", "(", "tx_hash", "=", "tx_hash", ")", ...
50.611111
0.003233
def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009): """ Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 :...
[ "def", "great_circle_vec", "(", "lat1", ",", "lng1", ",", "lat2", ",", "lng2", ",", "earth_radius", "=", "6371009", ")", ":", "phi1", "=", "np", ".", "deg2rad", "(", "lat1", ")", "phi2", "=", "np", ".", "deg2rad", "(", "lat2", ")", "d_phi", "=", "p...
29.315789
0.003475
def get_user_by_key(app, key): """ This method is only an example! Replace it with a real user database. :param str key: the public key the user belongs to """ if not hasattr(app, 'example_user_db'): app.example_user_db = {} if key in app.example_user_db: return app.example_use...
[ "def", "get_user_by_key", "(", "app", ",", "key", ")", ":", "if", "not", "hasattr", "(", "app", ",", "'example_user_db'", ")", ":", "app", ".", "example_user_db", "=", "{", "}", "if", "key", "in", "app", ".", "example_user_db", ":", "return", "app", "....
27.833333
0.002899
def creditusage(cls): """Get credit usage per hour""" rating = cls.call('hosting.rating.list') if not rating: return 0 rating = rating.pop() usage = [sum(resource.values()) for resource in rating.values() if isinstance(resource, dict...
[ "def", "creditusage", "(", "cls", ")", ":", "rating", "=", "cls", ".", "call", "(", "'hosting.rating.list'", ")", "if", "not", "rating", ":", "return", "0", "rating", "=", "rating", ".", "pop", "(", ")", "usage", "=", "[", "sum", "(", "resource", "."...
30.727273
0.005747
def read(self, n): '''Reads n bytes into the internal buffer''' bytes_wanted = n - self.buffer_length + self.pos + 1 if bytes_wanted > 0: self._buffer_bytes(bytes_wanted) end_pos = self.pos + n ret = self.buffer[self.pos + 1:end_pos + 1] self.pos = end_pos ...
[ "def", "read", "(", "self", ",", "n", ")", ":", "bytes_wanted", "=", "n", "-", "self", ".", "buffer_length", "+", "self", ".", "pos", "+", "1", "if", "bytes_wanted", ">", "0", ":", "self", ".", "_buffer_bytes", "(", "bytes_wanted", ")", "end_pos", "=...
32.7
0.005952