text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def gps_rtcm_data_send(self, flags, len, data, force_mavlink1=False): ''' WORK IN PROGRESS! RTCM message for injecting into the onboard GPS (used for DGPS) flags : LSB: 1 means message is fragmented (uint8_t) len ...
[ "def", "gps_rtcm_data_send", "(", "self", ",", "flags", ",", "len", ",", "data", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "gps_rtcm_data_encode", "(", "flags", ",", "len", ",", "data", ")", ",", "f...
51.454545
0.010417
def _enable_thread_pool(func): """ Use thread pool for executing a task if self.enable_thread_pool is True. Return an instance of future when flag is_async is True otherwise will to block waiting for the result until timeout then returns the result. """ @functools.wraps(func) def wrapper(*...
[ "def", "_enable_thread_pool", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "if", "self", ".", "enable_thread_pool",...
34.896552
0.000962
def _cursor_down(self, count=1): """ Moves cursor down count lines in same column. Cursor stops at bottom margin. """ self.y = min(self.size[0] - 1, self.y + count)
[ "def", "_cursor_down", "(", "self", ",", "count", "=", "1", ")", ":", "self", ".", "y", "=", "min", "(", "self", ".", "size", "[", "0", "]", "-", "1", ",", "self", ".", "y", "+", "count", ")" ]
33.333333
0.014634
def logout(self): """Explicit Abode logout.""" if self._token: header_data = { 'ABODE-API-KEY': self._token } self._session = requests.session() self._token = None self._panel = None self._user = None se...
[ "def", "logout", "(", "self", ")", ":", "if", "self", ".", "_token", ":", "header_data", "=", "{", "'ABODE-API-KEY'", ":", "self", ".", "_token", "}", "self", ".", "_session", "=", "requests", ".", "session", "(", ")", "self", ".", "_token", "=", "No...
31.451613
0.00199
def find_gene(self, name: str): """Find gene(s) by name.""" result = [ExpGene.from_series(s) for i, s in self.loc[self['name'] == name].iterrows()] return result
[ "def", "find_gene", "(", "self", ",", "name", ":", "str", ")", ":", "result", "=", "[", "ExpGene", ".", "from_series", "(", "s", ")", "for", "i", ",", "s", "in", "self", ".", "loc", "[", "self", "[", "'name'", "]", "==", "name", "]", ".", "iter...
39.8
0.009852
def copy(self): """ Get a copy of this item but with a new id :return: copy of this object with a new id :rtype: object """ # New dummy item with it's own running properties copied_item = self.__class__({}) # Now, copy the properties for prop in s...
[ "def", "copy", "(", "self", ")", ":", "# New dummy item with it's own running properties", "copied_item", "=", "self", ".", "__class__", "(", "{", "}", ")", "# Now, copy the properties", "for", "prop", "in", "self", ".", "__class__", ".", "properties", ":", "if", ...
32.142857
0.002157
def remove_reactions(self, reactions, remove_orphans=False): """Remove reactions from the model. The change is reverted upon exit when using the model as a context. Parameters ---------- reactions : list A list with reactions (`cobra.Reaction`), or their id's, to re...
[ "def", "remove_reactions", "(", "self", ",", "reactions", ",", "remove_orphans", "=", "False", ")", ":", "if", "isinstance", "(", "reactions", ",", "string_types", ")", "or", "hasattr", "(", "reactions", ",", "\"id\"", ")", ":", "warn", "(", "\"need to pass ...
38.333333
0.000706
async def session_bus_async(loop = None, **kwargs) : "returns a Connection object for the current D-Bus session bus." return \ Connection \ ( await dbus.Connection.bus_get_async(DBUS.BUS_SESSION, private = False, loop = loop) ) \ .register_additional_standard(**kw...
[ "async", "def", "session_bus_async", "(", "loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Connection", "(", "await", "dbus", ".", "Connection", ".", "bus_get_async", "(", "DBUS", ".", "BUS_SESSION", ",", "private", "=", "False", ",", "...
39.75
0.033846
def lnlike(self, theta): """ Logarithm of the likelihood """ params,loglike = self.params,self.loglike kwargs = dict(list(zip(params,theta))) try: lnlike = loglike.value(**kwargs) except ValueError as AssertionError: lnlike = -np.inf return lnlike
[ "def", "lnlike", "(", "self", ",", "theta", ")", ":", "params", ",", "loglike", "=", "self", ".", "params", ",", "self", ".", "loglike", "kwargs", "=", "dict", "(", "list", "(", "zip", "(", "params", ",", "theta", ")", ")", ")", "try", ":", "lnli...
34.555556
0.015674
def bootstrap_pex_env(entry_point): """Bootstrap the current runtime environment using a given pex.""" pex_info = _bootstrap(entry_point) from .environment import PEXEnvironment PEXEnvironment(entry_point, pex_info).activate()
[ "def", "bootstrap_pex_env", "(", "entry_point", ")", ":", "pex_info", "=", "_bootstrap", "(", "entry_point", ")", "from", ".", "environment", "import", "PEXEnvironment", "PEXEnvironment", "(", "entry_point", ",", "pex_info", ")", ".", "activate", "(", ")" ]
38.333333
0.021277
def check_dependee_build(self, depender, dependee, dependee_id): """Checks whether a depended on module is configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # If depender is installed or will be installed, so must the dependee if not (cfg[dependee.module_id]['shut...
[ "def", "check_dependee_build", "(", "self", ",", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# If depender is installed or will be installed, ...
60.4
0.021207
def balance(self): """ Access the balance :returns: twilio.rest.api.v2010.account.balance.BalanceList :rtype: twilio.rest.api.v2010.account.balance.BalanceList """ if self._balance is None: self._balance = BalanceList(self._version, account_sid=self._solution...
[ "def", "balance", "(", "self", ")", ":", "if", "self", ".", "_balance", "is", "None", ":", "self", ".", "_balance", "=", "BalanceList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "ret...
35
0.008357
def _update(dict1,dict2,**kwargs): ''' dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} _update(dict1,dict2) pobj(dict1) pobj(dict2) ''' if('deepcopy' in kwargs): deepcopy = kwargs['deepcopy'] else: deepcopy = 1 if(deep...
[ "def", "_update", "(", "dict1", ",", "dict2", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'deepcopy'", "in", "kwargs", ")", ":", "deepcopy", "=", "kwargs", "[", "'deepcopy'", "]", "else", ":", "deepcopy", "=", "1", "if", "(", "deepcopy", "==", "...
25.444444
0.012632
def set_menu(self, menu): '''set a MPTopMenu on the frame''' self.menu = menu self.in_queue.put(MPImageMenu(menu))
[ "def", "set_menu", "(", "self", ",", "menu", ")", ":", "self", ".", "menu", "=", "menu", "self", ".", "in_queue", ".", "put", "(", "MPImageMenu", "(", "menu", ")", ")" ]
33.75
0.014493
def plot_diodespec(ON_obs,OFF_obs,calflux,calfreq,spec_in,units='mJy',**kwargs): ''' Plots the full-band Stokes I spectrum of the noise diode (ON-OFF) ''' dspec = diode_spec(ON_obs,OFF_obs,calflux,calfreq,spec_in,**kwargs) obs = Waterfall(ON_obs,max_load=150) freqs = obs.populate_freqs() ch...
[ "def", "plot_diodespec", "(", "ON_obs", ",", "OFF_obs", ",", "calflux", ",", "calfreq", ",", "spec_in", ",", "units", "=", "'mJy'", ",", "*", "*", "kwargs", ")", ":", "dspec", "=", "diode_spec", "(", "ON_obs", ",", "OFF_obs", ",", "calflux", ",", "calf...
37.8125
0.025806
async def send_script(self, conn_id, data): """Send a a script to a device. See :meth:`AbstractDeviceAdapter.send_script`. """ progress_callback = functools.partial(_on_progress, self, 'script', conn_id) resp = await self._execute(self._adapter.send_script_sync, conn_id, data,...
[ "async", "def", "send_script", "(", "self", ",", "conn_id", ",", "data", ")", ":", "progress_callback", "=", "functools", ".", "partial", "(", "_on_progress", ",", "self", ",", "'script'", ",", "conn_id", ")", "resp", "=", "await", "self", ".", "_execute",...
37.8
0.010336
def applymap(self, func): """ Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame. Parameters ---------- func : callable Python function, returns a single value...
[ "def", "applymap", "(", "self", ",", "func", ")", ":", "# if we have a dtype == 'M8[ns]', provide boxed values", "def", "infer", "(", "x", ")", ":", "if", "x", ".", "empty", ":", "return", "lib", ".", "map_infer", "(", "x", ",", "func", ")", "return", "lib...
27.630769
0.001075
def register_listener(self, listener, reading=False): """Add a callback function that is called when sensor value is updated. The callback footprint is received_timestamp, timestamp, status, value. Parameters ---------- listener : function Callback signature: if read...
[ "def", "register_listener", "(", "self", ",", "listener", ",", "reading", "=", "False", ")", ":", "listener_id", "=", "hashable_identity", "(", "listener", ")", "self", ".", "_listeners", "[", "listener_id", "]", "=", "(", "listener", ",", "reading", ")", ...
44.421053
0.00232
def filter_pypi(self, entry): """Show only usefull packages""" for package in self.packages: if entry.title.lower().startswith(package): return entry
[ "def", "filter_pypi", "(", "self", ",", "entry", ")", ":", "for", "package", "in", "self", ".", "packages", ":", "if", "entry", ".", "title", ".", "lower", "(", ")", ".", "startswith", "(", "package", ")", ":", "return", "entry" ]
37.8
0.010363
def npm_install(package, flags=None): """Install a package from NPM.""" command = u'install %s %s' % (package, flags or u'') npm_command(command.strip())
[ "def", "npm_install", "(", "package", ",", "flags", "=", "None", ")", ":", "command", "=", "u'install %s %s'", "%", "(", "package", ",", "flags", "or", "u''", ")", "npm_command", "(", "command", ".", "strip", "(", ")", ")" ]
32.6
0.011976
def zero_fill(self, corpus): """Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results ...
[ "def", "zero_fill", "(", "self", ",", "corpus", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Zero-filling results'", ")", "zero_rows", "=", "[", "]", "work_sigla", "=", "{", "}", "grouping_cols", "=", "[", "constants", ".", "LABEL_FIELDNAME", ",",...
47.40625
0.001292
def getsatstars(self, verbose = None): """ Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use. """ if verbose == None: verbose = self.verbose if not self.satlevel > 0: raise RuntimeError, "Canno...
[ "def", "getsatstars", "(", "self", ",", "verbose", "=", "None", ")", ":", "if", "verbose", "==", "None", ":", "verbose", "=", "self", ".", "verbose", "if", "not", "self", ".", "satlevel", ">", "0", ":", "raise", "RuntimeError", ",", "\"Cannot determine s...
39.166667
0.022869
def perlin(self, stat='perlin'): """Apply Perlin noise to my nodes, and return myself. I'll try to use the name of the node as its spatial position for this purpose, or use its stats 'x', 'y', and 'z', or skip the node if neither are available. z is assumed 0 if not provided for...
[ "def", "perlin", "(", "self", ",", "stat", "=", "'perlin'", ")", ":", "from", "math", "import", "floor", "p", "=", "self", ".", "engine", ".", "shuffle", "(", "[", "151", ",", "160", ",", "137", ",", "91", ",", "90", ",", "15", ",", "131", ",",...
38.146552
0.000441
def success(headers = None, data = ''): """ Generate success JSON to send to client """ passed_headers = {} if headers is None else headers if isinstance(data, dict): data = json.dumps(data) ret_headers = {'status' : 'ok'} ret_headers.update(passed_headers) return server_responce(ret_headers, da...
[ "def", "success", "(", "headers", "=", "None", ",", "data", "=", "''", ")", ":", "passed_headers", "=", "{", "}", "if", "headers", "is", "None", "else", "headers", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "json", ".", "d...
45.285714
0.021672
def _hash_comparison(self): """ Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefb...
[ "def", "_hash_comparison", "(", "self", ")", ":", "def", "hash_then_or", "(", "hash_name", ")", ":", "# For now, all the decent hashes have 6-char names, so we can get", "# away with hard-coding space literals.", "return", "chain", "(", "[", "hash_name", "]", ",", "repeat",...
39.52
0.001976
def abs_paths(self): """ :API: public """ for root, products in self._rooted_products_by_root.items(): yield root, products.abs_paths()
[ "def", "abs_paths", "(", "self", ")", ":", "for", "root", ",", "products", "in", "self", ".", "_rooted_products_by_root", ".", "items", "(", ")", ":", "yield", "root", ",", "products", ".", "abs_paths", "(", ")" ]
25.333333
0.012739
def _decode_response(self, ip_address): """Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError """ # Reverse the IP, reassign the octets to...
[ "def", "_decode_response", "(", "self", ",", "ip_address", ")", ":", "# Reverse the IP, reassign the octets to integers", "vt", ",", "ts", ",", "days", ",", "rc", "=", "[", "int", "(", "o", ")", "for", "o", "in", "ip_address", ".", "split", "(", "'.'", ")"...
36.870968
0.001705
def add_data(self): """This function properly constructs a QR code's data string. It takes into account the interleaving pattern required by the standard. """ #Encode the data into a QR code self.buffer.write(self.binary_string(self.mode, 4)) self.buffer.write(self.get_da...
[ "def", "add_data", "(", "self", ")", ":", "#Encode the data into a QR code", "self", ".", "buffer", ".", "write", "(", "self", ".", "binary_string", "(", "self", ".", "mode", ",", "4", ")", ")", "self", ".", "buffer", ".", "write", "(", "self", ".", "g...
40.009901
0.011591
def _parse_status(bug_el): """Return a bugreport object from a given status xml element""" bug = Bugreport() # plain fields for field in ('originator', 'subject', 'msgid', 'package', 'severity', 'owner', 'summary', 'location', 'source', 'pending', 'forwarded'): ...
[ "def", "_parse_status", "(", "bug_el", ")", ":", "bug", "=", "Bugreport", "(", ")", "# plain fields", "for", "field", "in", "(", "'originator'", ",", "'subject'", ",", "'msgid'", ",", "'package'", ",", "'severity'", ",", "'owner'", ",", "'summary'", ",", "...
47.486486
0.000558
def indicate_fulfillment_ficon(self, control_unit, unit_address): """ TODO: Add ControlUnit objects etc for FICON support. Indicate completion of :term:`fulfillment` for this ECKD (=FICON) storage volume and provide identifying information (control unit and unit address) about t...
[ "def", "indicate_fulfillment_ficon", "(", "self", ",", "control_unit", ",", "unit_address", ")", ":", "# The operation requires exactly 2 characters in lower case", "unit_address_2", "=", "format", "(", "int", "(", "unit_address", ",", "16", ")", ",", "'02x'", ")", "b...
37.220339
0.000887
def generic_type_args(type_: Type) -> List[Type]: """Gets the type argument list for the given generic type. If you give this function List[int], it will return [int], and if you give it Union[int, str] it will give you [int, str]. Note that on Python < 3.7, Union[int, bool] collapses to Union[int] and...
[ "def", "generic_type_args", "(", "type_", ":", "Type", ")", "->", "List", "[", "Type", "]", ":", "if", "hasattr", "(", "type_", ",", "'__union_params__'", ")", ":", "# 3.5 Union", "return", "list", "(", "type_", ".", "__union_params__", ")", "return", "lis...
35.263158
0.001453
def list_actions(self): """ Returns the registered actions. :return: Actions list. :rtype: list """ actions = [] for path, actionName, action in self: actions.append(self.__namespace_splitter.join(itertools.chain(path, (actionName,)))) return...
[ "def", "list_actions", "(", "self", ")", ":", "actions", "=", "[", "]", "for", "path", ",", "actionName", ",", "action", "in", "self", ":", "actions", ".", "append", "(", "self", ".", "__namespace_splitter", ".", "join", "(", "itertools", ".", "chain", ...
27.083333
0.008929
def encrypt(self, message, public_key): """Encrypts a string using a given rsa.PublicKey object. If the message is larger than the key, it will split it up into a list and encrypt each line in the list. Args: message (string): The string to encrypt. public_key (rsa.P...
[ "def", "encrypt", "(", "self", ",", "message", ",", "public_key", ")", ":", "# Get the maximum message length based on the key", "max_str_len", "=", "rsa", ".", "common", ".", "byte_size", "(", "public_key", ".", "n", ")", "-", "11", "# If the message is longer than...
34.866667
0.00124
def start_notifications(self): """Start the notifications thread. If an external callback is not set up (using `update_webhook`) then calling this function is mandatory to get or set resource. .. code-block:: python >>> api.start_notifications() >>> print(api.g...
[ "def", "start_notifications", "(", "self", ")", ":", "with", "self", ".", "_notifications_lock", ":", "if", "self", ".", "has_active_notification_thread", ":", "return", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "NotificationsApi", ")", "self", "."...
34.25
0.002028
def compare_timestamp(src, dst): """ Compares the timestamps of file *src* and *dst*, returning #True if the *dst* is out of date or does not exist. Raises an #OSError if the *src* file does not exist. """ try: dst_time = os.path.getmtime(dst) except OSError as exc: if exc.errno == errno.ENOENT: ...
[ "def", "compare_timestamp", "(", "src", ",", "dst", ")", ":", "try", ":", "dst_time", "=", "os", ".", "path", ".", "getmtime", "(", "dst", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "ENOENT", ":", "re...
27.333333
0.016509
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ if __debug__: verbose.report('backend_agg.new_figure_manager', 'debug-annoying') FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) ...
[ "def", "new_figure_manager", "(", "num", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "__debug__", ":", "verbose", ".", "report", "(", "'backend_agg.new_figure_manager'", ",", "'debug-annoying'", ")", "FigureClass", "=", "kwargs", ".", "pop", "...
33.090909
0.008021
def apply_delta(self, delta): """Apply delta to our state and return a copy of the affected object as it was before and after the update, e.g.: old_obj, new_obj = self.apply_delta(delta) old_obj may be None if the delta is for the creation of a new object, e.g. a new applic...
[ "def", "apply_delta", "(", "self", ",", "delta", ")", ":", "history", "=", "(", "self", ".", "state", ".", "setdefault", "(", "delta", ".", "entity", ",", "{", "}", ")", ".", "setdefault", "(", "delta", ".", "get_id", "(", ")", ",", "collections", ...
34
0.002288
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to...
[ "def", "shapesides", "(", "inputtocheck", ",", "inputtype", "=", "'shape'", ")", ":", "# Define the array of sides to a shape", "shapestosides", "=", "{", "'triangle'", ":", "3", ",", "'square'", ":", "4", ",", "'pentagon'", ":", "5", ",", "'hexagon'", ":", "6...
27.375
0.00049
def find_data_files(source,target,patterns,isiter=False): """Locates the specified data-files and returns the matches; filesystem tree for setup's data_files in setup.py Usage: data_files = find_data_files(r"C:\Python27\Lib\site-packages\numpy\core","numpy/core",["*....
[ "def", "find_data_files", "(", "source", ",", "target", ",", "patterns", ",", "isiter", "=", "False", ")", ":", "if", "glob", ".", "has_magic", "(", "source", ")", "or", "glob", ".", "has_magic", "(", "target", ")", ":", "raise", "ValueError", "(", "\"...
61.107143
0.016686
def avl_join(t1, t2, node): """ Joins two trees `t1` and `t1` with an intermediate key-value pair CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_join Example: >>> # DISABLE_DOCTEST >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> s...
[ "def", "avl_join", "(", "t1", ",", "t2", ",", "node", ")", ":", "if", "DEBUG_JOIN", ":", "print", "(", "'-- JOIN node=%r'", "%", "(", "node", ",", ")", ")", "if", "t1", "is", "None", "and", "t2", "is", "None", ":", "if", "DEBUG_JOIN", ":", "print",...
31.3375
0.000387
def near(self, center, sphere=False, min=None, max=None): """Order results by their distance from the given point, optionally with range limits in meters. Geospatial operator: {$near: {...}} Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near { $near: { $geom...
[ "def", "near", "(", "self", ",", "center", ",", "sphere", "=", "False", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "from", "marrow", ".", "mongo", ".", "geo", "import", "Point", "near", "=", "{", "'$geometry'", ":", "Point", "(", ...
27.486486
0.047483
def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle): """ Based on the C{style} and C{currentDayStyle} determine what day-of-week value is to be returned. @type wd: integer @param wd: day-of-week value for the current day @typ...
[ "def", "_CalculateDOWDelta", "(", "self", ",", "wd", ",", "wkdy", ",", "offset", ",", "style", ",", "currentDayStyle", ")", ":", "diffBase", "=", "wkdy", "-", "wd", "origOffset", "=", "offset", "if", "offset", "==", "2", ":", "# no modifier is present.", "...
37.307692
0.001005
def delete(self) : "deletes the document from the database" if self.URL is None : raise DeletionError("Can't delete a document that was not saved") r = self.connection.session.delete(self.URL) data = r.json() if (r.status_code != 200 and r.status_code != 202) or 'err...
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "URL", "is", "None", ":", "raise", "DeletionError", "(", "\"Can't delete a document that was not saved\"", ")", "r", "=", "self", ".", "connection", ".", "session", ".", "delete", "(", "self", ".", ...
37.333333
0.010893
def draw(self): """ Draws a popup rectangle with a rotating text queue. """ if len(self.q) > 0: self.update() if self.delay == 0: # Rounded rectangle in the given background color. p,...
[ "def", "draw", "(", "self", ")", ":", "if", "len", "(", "self", ".", "q", ")", ">", "0", ":", "self", ".", "update", "(", ")", "if", "self", ".", "delay", "==", "0", ":", "# Rounded rectangle in the given background color.", "p", ",", "h", "=", "self...
32.675676
0.012851
def _dump_multipolygon(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`. """ coords = obj['coordinates'] vertex = coords[0][0][0] num_dims = len(vertex) wkb_string, byte_fmt, byte_order ...
[ "def", "_dump_multipolygon", "(", "obj", ",", "big_endian", ",", "meta", ")", ":", "coords", "=", "obj", "[", "'coordinates'", "]", "vertex", "=", "coords", "[", "0", "]", "[", "0", "]", "[", "0", "]", "num_dims", "=", "len", "(", "vertex", ")", "w...
32.685714
0.000849
def _shift_field_positions_global(record, start, delta=1): """ Shift all global field positions. Shift all global field positions with global field positions higher or equal to 'start' from the value 'delta'. """ if not delta: return for tag, fields in record.items(): newfi...
[ "def", "_shift_field_positions_global", "(", "record", ",", "start", ",", "delta", "=", "1", ")", ":", "if", "not", "delta", ":", "return", "for", "tag", ",", "fields", "in", "record", ".", "items", "(", ")", ":", "newfields", "=", "[", "]", "for", "...
31.842105
0.001605
def find_ledger_file(ledgerrcpath=None): """Returns main ledger file path or raise exception if it cannot be \ found.""" if ledgerrcpath is None: ledgerrcpath = os.path.abspath(os.path.expanduser("~/.ledgerrc")) if "LEDGER_FILE" in os.environ: return os.path.abspath(os.path.expanduser(os.env...
[ "def", "find_ledger_file", "(", "ledgerrcpath", "=", "None", ")", ":", "if", "ledgerrcpath", "is", "None", ":", "ledgerrcpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "\"~/.ledgerrc\"", ")", ")", "if", "\"...
40.625
0.001504
def convert(*args, **kargs): """ Wrapper around CountryConverter.convert() Uses the same parameters. This function has the same performance as CountryConverter.convert for one call; for multiple calls it is better to instantiate a common CountryConverter (this avoid loading the source data file mul...
[ "def", "convert", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "init", "=", "{", "'country_data'", ":", "COUNTRY_DATA_FILE", ",", "'additional_data'", ":", "None", ",", "'only_UNmember'", ":", "False", ",", "'include_obsolete'", ":", "False", "}", "...
37.177419
0.000423
def auth_user_remote_user(self, username): """ REMOTE_USER user Authentication :param username: user's username for remote auth :type self: User model """ user = self.find_user(username=username) # User does not exist, create one if auto user registr...
[ "def", "auth_user_remote_user", "(", "self", ",", "username", ")", ":", "user", "=", "self", ".", "find_user", "(", "username", "=", "username", ")", "# User does not exist, create one if auto user registration.", "if", "user", "is", "None", "and", "self", ".", "a...
35.344828
0.001899
def parse(self, data=b''): """ Parses the wire protocol from NATS for the client and dispatches the subscription callbacks. """ self.buf.extend(data) while self.buf: if self.state == AWAITING_CONTROL_LINE: msg = MSG_RE.match(self.buf) ...
[ "def", "parse", "(", "self", ",", "data", "=", "b''", ")", ":", "self", ".", "buf", ".", "extend", "(", "data", ")", "while", "self", ".", "buf", ":", "if", "self", ".", "state", "==", "AWAITING_CONTROL_LINE", ":", "msg", "=", "MSG_RE", ".", "match...
39.518519
0.001219
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
[ "def", "grow", "(", "self", ")", ":", "t", "=", "self", ".", "worker_factory", "(", "self", ")", "t", ".", "start", "(", ")", "self", ".", "_size", "+=", "1" ]
26.6
0.014599
def transpose(self): """ Returns a copy of this databox with the columns as rows. Currently requires that the databox has equal-length columns. """ # Create an empty databox with the same headers and delimiter. d = databox(delimter=self.delimiter) self.co...
[ "def", "transpose", "(", "self", ")", ":", "# Create an empty databox with the same headers and delimiter.", "d", "=", "databox", "(", "delimter", "=", "self", ".", "delimiter", ")", "self", ".", "copy_headers", "(", "d", ")", "# Get the transpose", "z", "=", "_n"...
31.235294
0.012797
def lines2less(lines): """ input: lines = list / iterator of strings eg: lines = ["This is the first line", "This is the second line"] output: print those lines to stdout if the output is short + narrow otherwise print the lines to less """ lines = iter(lines) #cast list to iterator...
[ "def", "lines2less", "(", "lines", ")", ":", "lines", "=", "iter", "(", "lines", ")", "#cast list to iterator", "#print output to stdout if small, otherwise to less", "has_term", "=", "True", "terminal_cols", "=", "100", "try", ":", "terminal_cols", "=", "terminal_siz...
29.567568
0.010619
def readline(self, size=None): """Read a single line from rfile buffer and return it. Args: size (int): minimum amount of data to read Returns: bytes: One line from rfile. """ data = EMPTY if size == 0: return data while Tr...
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "data", "=", "EMPTY", "if", "size", "==", "0", ":", "return", "data", "while", "True", ":", "if", "size", "and", "len", "(", "data", ")", ">=", "size", ":", "return", "data", "if...
29.690476
0.001553
def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whet...
[ "def", "_modifyInternal", "(", "self", ",", "*", ",", "sort", "=", "None", ",", "purge", "=", "False", ",", "done", "=", "None", ")", ":", "sortAll", ",", "sortLevels", "=", "sort", "is", "not", "None", "and", "sort", "or", "(", "[", "]", ",", "{...
39.772727
0.000743
def is_finite(self): """ Whether or not the domain contains a finite number of points. :type: `bool` """ return not np.isinf(self.min) and not np.isinf(self.max)
[ "def", "is_finite", "(", "self", ")", ":", "return", "not", "np", ".", "isinf", "(", "self", ".", "min", ")", "and", "not", "np", ".", "isinf", "(", "self", ".", "max", ")" ]
28
0.009901
def AgregarBonificacion(self, porcentaje, importe): "Agrega la información referente a las bonificaciones de la liquidación (opcional)" bonif = dict(porcentaje=porcentaje, importe=importe) self.solicitud['bonificacion'] = bonif return True
[ "def", "AgregarBonificacion", "(", "self", ",", "porcentaje", ",", "importe", ")", ":", "bonif", "=", "dict", "(", "porcentaje", "=", "porcentaje", ",", "importe", "=", "importe", ")", "self", ".", "solicitud", "[", "'bonificacion'", "]", "=", "bonif", "re...
53.4
0.01107
def exch_info(ticker: str) -> pd.Series: """ Exchange info for given ticker Args: ticker: ticker or exchange Returns: pd.Series Examples: >>> exch_info('SPY US Equity') tz America/New_York allday [04:00, 20:00] day [09:30, 16:00]...
[ "def", "exch_info", "(", "ticker", ":", "str", ")", "->", "pd", ".", "Series", ":", "logger", "=", "logs", ".", "get_logger", "(", "exch_info", ",", "level", "=", "'debug'", ")", "if", "' '", "not", "in", "ticker", ".", "strip", "(", ")", ":", "tic...
29.071429
0.001188
def merge_config(cfg_chunks): """Merge a set of fetched Route 53 config Etrees into a canonical form. Args: cfg_chunks: [ lxml.etree.ETree ] Returns: lxml.etree.Element""" root = lxml.etree.XML('<ResourceRecordSets xmlns="%s"></ResourceRecordSets>' % R53_XMLNS, parser=XML_PARSER) for chunk in cfg_chunks: ...
[ "def", "merge_config", "(", "cfg_chunks", ")", ":", "root", "=", "lxml", ".", "etree", ".", "XML", "(", "'<ResourceRecordSets xmlns=\"%s\"></ResourceRecordSets>'", "%", "R53_XMLNS", ",", "parser", "=", "XML_PARSER", ")", "for", "chunk", "in", "cfg_chunks", ":", ...
41.9
0.016355
def extract_aws_metadata(wrapped, instance, args, kwargs, return_value): """Provide AWS metadata for improved visualization. See documentation for this data structure: http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-aws """ response = return_value...
[ "def", "extract_aws_metadata", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ",", "return_value", ")", ":", "response", "=", "return_value", "LOGGER", ".", "debug", "(", "'Extracting AWS metadata'", ",", "args", "=", "args", ",", "kwargs", "=", ...
29.893617
0.000689
def get_score(self): """ 获得成绩列表 :return: json array """ html = self.__get_score_html() soup = BeautifulSoup(html) div = soup.find_all('div', class_='Section1')[0] tag_ps = div.find_all('p') del tag_ps[0] result = [] ''' #one...
[ "def", "get_score", "(", "self", ")", ":", "html", "=", "self", ".", "__get_score_html", "(", ")", "soup", "=", "BeautifulSoup", "(", "html", ")", "div", "=", "soup", ".", "find_all", "(", "'div'", ",", "class_", "=", "'Section1'", ")", "[", "0", "]"...
30.366667
0.001595
def present(name, service_name, auth=None, **kwargs): ''' Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to cont...
[ "def", "present", "(", "name", ",", "service_name", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "...
27.328125
0.000552
def copy(self, file_id, title=None, copy_permissions=False): """Copies a spreadsheet. :param file_id: A key of a spreadsheet to copy. :type title: str :param title: (optional) A title for the new spreadsheet. :type title: str :param copy_permissions: (optional) If True...
[ "def", "copy", "(", "self", ",", "file_id", ",", "title", "=", "None", ",", "copy_permissions", "=", "False", ")", ":", "url", "=", "'{0}/{1}/copy'", ".", "format", "(", "DRIVE_FILES_API_V2_URL", ",", "file_id", ")", "payload", "=", "{", "'title'", ":", ...
27.7
0.000996
def _create_connection(self): """.. :py:method:: If we hava several hosts, we can random choice one to connect """ db = psycopg2.connect(database=self.dbname, user=self.user, password=self.password, host=self.host, po...
[ "def", "_create_connection", "(", "self", ")", ":", "db", "=", "psycopg2", ".", "connect", "(", "database", "=", "self", ".", "dbname", ",", "user", "=", "self", ".", "user", ",", "password", "=", "self", ".", "password", ",", "host", "=", "self", "....
39.454545
0.009009
def cmd_tcpflags(ip, port, flags, rflags, verbose): """Send TCP packets with different flags and tell what responses receives. It can be used to analyze how the different TCP/IP stack implementations and configurations responds to packet with various flag combinations. Example: \b # habu.tcpf...
[ "def", "cmd_tcpflags", "(", "ip", ",", "port", ",", "flags", ",", "rflags", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "pkts", "=", "IP", "(", "dst", "=", "ip", ")", "/", "TCP", "(", "flags", "=", "(", "0", ",", "255", ")", ...
28.857143
0.002052
def collectInterest(self): """ Collects user's daily interest, returns result Returns bool - True if successful, False otherwise """ if self.collectedInterest: return False pg = self.usr.getPage("http://www.neopets.com/bank.phtml") ...
[ "def", "collectInterest", "(", "self", ")", ":", "if", "self", ".", "collectedInterest", ":", "return", "False", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/bank.phtml\"", ")", "form", "=", "pg", ".", "form", "(", "action", ...
33.727273
0.009174
def find_path(name, config, wsonly=False): """Find path for given workspace and|or repository.""" workspace = Workspace(config) config = config["workspaces"] path_list = {} if name.find('/') != -1: wsonly = False try: ws, repo = name.split('/') except ValueError...
[ "def", "find_path", "(", "name", ",", "config", ",", "wsonly", "=", "False", ")", ":", "workspace", "=", "Workspace", "(", "config", ")", "config", "=", "config", "[", "\"workspaces\"", "]", "path_list", "=", "{", "}", "if", "name", ".", "find", "(", ...
36.212121
0.000815
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) Loggi...
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "...
32.240506
0.000381
def competitions_data_list_files(self, id, **kwargs): # noqa: E501 """List competition data files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_list_files(id, as...
[ "def", "competitions_data_list_files", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", ...
44.2
0.002215
def convert_header(cls, old_header, new_version): """ Converts a header to a another version Parameters ---------- old_header: the old header instance new_version: float or str Returns ------- The converted header >>> old_header = HeaderFactory...
[ "def", "convert_header", "(", "cls", ",", "old_header", ",", "new_version", ")", ":", "new_header_class", "=", "cls", ".", "header_class_for_version", "(", "new_version", ")", "b", "=", "bytearray", "(", "old_header", ")", "b", "+=", "b\"\\x00\"", "*", "(", ...
27.6
0.002334
def nextSolarReturn(chart, date): """ Returns the solar return of a Chart after a specific date. """ sun = chart.getObject(const.SUN) srDate = ephem.nextSolarReturn(date, sun.lon) return _computeChart(chart, srDate)
[ "def", "nextSolarReturn", "(", "chart", ",", "date", ")", ":", "sun", "=", "chart", ".", "getObject", "(", "const", ".", "SUN", ")", "srDate", "=", "ephem", ".", "nextSolarReturn", "(", "date", ",", "sun", ".", "lon", ")", "return", "_computeChart", "(...
29.625
0.008197
def get_k8s_metadata(): """Get kubernetes container metadata, as on GCP GKE.""" k8s_metadata = {} gcp_cluster = (gcp_metadata_config.GcpMetadataConfig .get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY)) if gcp_cluster is not None: k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluste...
[ "def", "get_k8s_metadata", "(", ")", ":", "k8s_metadata", "=", "{", "}", "gcp_cluster", "=", "(", "gcp_metadata_config", ".", "GcpMetadataConfig", ".", "get_attribute", "(", "gcp_metadata_config", ".", "CLUSTER_NAME_KEY", ")", ")", "if", "gcp_cluster", "is", "not"...
37.066667
0.001754
def get_validation_data(doc): """ Validate the docstring. Parameters ---------- doc : Docstring A Docstring object with the given function name. Returns ------- tuple errors : list of tuple Errors occurred during validation. warnings : list of tuple ...
[ "def", "get_validation_data", "(", "doc", ")", ":", "errs", "=", "[", "]", "wrns", "=", "[", "]", "if", "not", "doc", ".", "raw_doc", ":", "errs", ".", "append", "(", "error", "(", "'GL08'", ")", ")", "return", "errs", ",", "wrns", ",", "''", "if...
37.609626
0.000139
def attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, key, cum_att): """ It is a implementation one step of block of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax). Based on the papers: https://arxiv.org/abs/1508.04025 "Effective...
[ "def", "attention_gen_step", "(", "hidden_for_sketch", ",", "hidden_for_attn_alignment", ",", "sketch", ",", "key", ",", "cum_att", ")", ":", "with", "tf", ".", "name_scope", "(", "'attention_step'", ")", ":", "sketch_dims", "=", "hidden_for_sketch", ".", "get_sha...
61
0.010299
def body_block_content_render(tag, recursive=False, base_url=None): """ Render the tag as body content and call recursively if the tag has child tags """ block_content_list = [] tag_content = OrderedDict() if tag.name == "p": for block_content in body_block_paragraph_render(tag, bas...
[ "def", "body_block_content_render", "(", "tag", ",", "recursive", "=", "False", ",", "base_url", "=", "None", ")", ":", "block_content_list", "=", "[", "]", "tag_content", "=", "OrderedDict", "(", ")", "if", "tag", ".", "name", "==", "\"p\"", ":", "for", ...
40.482759
0.002495
def resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs): """Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] ...
[ "def", "resample", "(", "y", ",", "orig_sr", ",", "target_sr", ",", "res_type", "=", "'kaiser_best'", ",", "fix", "=", "True", ",", "scale", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# First, validate the audio buffer", "util", ".", "valid_audio", ...
29.103774
0.002194
def callback_datadirs(attr, old, new): '''Update source and controls with data loaded from selected directory''' import os global data try: # Load data from new data directory path_dir = os.path.join(parent_input.value, new) data, params_tag, params_data = load_data(path_dir) ...
[ "def", "callback_datadirs", "(", "attr", ",", "old", ",", "new", ")", ":", "import", "os", "global", "data", "try", ":", "# Load data from new data directory", "path_dir", "=", "os", ".", "path", ".", "join", "(", "parent_input", ".", "value", ",", "new", ...
34.777778
0.011809
def DeleteInstance(self, InstanceName, **extra): # pylint: disable=invalid-name """ Delete an instance. This method performs the DeleteInstance operation (see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all methods performing such operations. If t...
[ "def", "DeleteInstance", "(", "self", ",", "InstanceName", ",", "*", "*", "extra", ")", ":", "# pylint: disable=invalid-name", "exc", "=", "None", "method_name", "=", "'DeleteInstance'", "if", "self", ".", "_operation_recorders", ":", "self", ".", "operation_recor...
33.6
0.001239
def plugin_request(plugin_str): ''' Extract plugin name and version specifiers from plugin descriptor string. .. versionchanged:: 0.25.2 Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_. .. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5 ''' from pip_hel...
[ "def", "plugin_request", "(", "plugin_str", ")", ":", "from", "pip_helpers", "import", "CRE_PACKAGE", "match", "=", "CRE_PACKAGE", ".", "match", "(", "plugin_str", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'Invalid plugin descriptor. Must be like ...
34.375
0.00177
def _new_packet_cb(self, packet): """Callback for newly arrived packets with TOC information""" chan = packet.channel cmd = packet.data[0] payload = packet.data[1:] if (chan == CHAN_SETTINGS): id = payload[0] error_status = payload[1] block = ...
[ "def", "_new_packet_cb", "(", "self", ",", "packet", ")", ":", "chan", "=", "packet", ".", "channel", "cmd", "=", "packet", ".", "data", "[", "0", "]", "payload", "=", "packet", ".", "data", "[", "1", ":", "]", "if", "(", "chan", "==", "CHAN_SETTIN...
45.88172
0.000459
def create_personal(cls, name, user_id, scopes=None, is_internal=False): """Create a personal access token. A token that is bound to a specific user and which doesn't expire, i.e. similar to the concept of an API key. :param name: Client name. :param user_id: User ID. :...
[ "def", "create_personal", "(", "cls", ",", "name", ",", "user_id", ",", "scopes", "=", "None", ",", "is_internal", "=", "False", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "scopes", "=", "\" \"", ".", "join", "(", "sc...
31.428571
0.00147
def common_directory(paths): """Find the deepest common directory of a list of paths. :return: if no paths are provided, None is returned; if there is no common directory, '' is returned; otherwise the common directory with a trailing / is returned. """ import posixpath def get_dir_with...
[ "def", "common_directory", "(", "paths", ")", ":", "import", "posixpath", "def", "get_dir_with_slash", "(", "path", ")", ":", "if", "path", "==", "b''", "or", "path", ".", "endswith", "(", "b'/'", ")", ":", "return", "path", "else", ":", "dirname", ",", ...
31.555556
0.002278
def _write_private_key_file(self, filename, key, format, password=None): """ Write an SSH2-format private key file in a form that can be read by paramiko or openssh. If no password is given, the key is written in a trivially-encoded format (base64) which is completely insecure. If ...
[ "def", "_write_private_key_file", "(", "self", ",", "filename", ",", "key", ",", "format", ",", "password", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "f", ":", "os", ".", "chmod", "(", "filename", ",", "o600", "...
48.611111
0.002242
def get_data_table(filename): """Returns a DataTable instance built from either the filename, or STDIN if filename is None.""" with get_file_object(filename, "r") as rf: return DataTable(list(csv.reader(rf)))
[ "def", "get_data_table", "(", "filename", ")", ":", "with", "get_file_object", "(", "filename", ",", "\"r\"", ")", "as", "rf", ":", "return", "DataTable", "(", "list", "(", "csv", ".", "reader", "(", "rf", ")", ")", ")" ]
53.25
0.018519
def init_logging(logfile=DEFAULT_LOGNAME, default=None, level=logging.INFO): """ Set up logger for capturing stdout/stderr messages. Must be called prior to writing any messages that you want to log. """ if logfile == "INDEF": if not is_blank(default): logname = fileutil.buildN...
[ "def", "init_logging", "(", "logfile", "=", "DEFAULT_LOGNAME", ",", "default", "=", "None", ",", "level", "=", "logging", ".", "INFO", ")", ":", "if", "logfile", "==", "\"INDEF\"", ":", "if", "not", "is_blank", "(", "default", ")", ":", "logname", "=", ...
37
0.002241
def embed(self, title=''): """Start an IPython embed Calling embed won't do anything in a multithread context The stack_depth will be found automatically """ if self.embed_disabled: self.warning_log("Embed is disabled when runned from the grid runner because of the ...
[ "def", "embed", "(", "self", ",", "title", "=", "''", ")", ":", "if", "self", ".", "embed_disabled", ":", "self", ".", "warning_log", "(", "\"Embed is disabled when runned from the grid runner because of the multithreading\"", ")", "# noqa", "return", "False", "from",...
32.3
0.002004
def _dir_size(directory): """Returns total size (in bytes) of the given 'directory'.""" size = 0 for elem in tf_v1.gfile.ListDirectory(directory): elem_full_path = os.path.join(directory, elem) stat = tf_v1.gfile.Stat(elem_full_path) size += _dir_size(elem_full_path) if stat.is_directory else stat.len...
[ "def", "_dir_size", "(", "directory", ")", ":", "size", "=", "0", "for", "elem", "in", "tf_v1", ".", "gfile", ".", "ListDirectory", "(", "directory", ")", ":", "elem_full_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "elem", ")", ...
41.25
0.014837
def process_module(self, node): ''' process a module the module's content is accessible via node.file_stream object ''' pep263 = re.compile(six.b(self.RE_PEP263)) try: file_stream = node.file_stream except AttributeError: # Pylint >= 1.8....
[ "def", "process_module", "(", "self", ",", "node", ")", ":", "pep263", "=", "re", ".", "compile", "(", "six", ".", "b", "(", "self", ".", "RE_PEP263", ")", ")", "try", ":", "file_stream", "=", "node", ".", "file_stream", "except", "AttributeError", ":"...
37.407407
0.00193
def set_sim_params(self, nparams, attr_params): """Store parameters in `params` in `h5file.root.parameters`. `nparams` (dict) A dict as returned by `get_params()` in `ParticlesSimulation()` The format is: keys: used as parameter name value...
[ "def", "set_sim_params", "(", "self", ",", "nparams", ",", "attr_params", ")", ":", "for", "name", ",", "value", "in", "nparams", ".", "items", "(", ")", ":", "val", "=", "value", "[", "0", "]", "if", "value", "[", "0", "]", "is", "not", "None", ...
45.15
0.002169
def _build_editable_options(req): """ This method generates a dictionary of the query string parameters contained in a given editable URL. """ regexp = re.compile(r"[\?#&](?P<name>[^&=]+)=(?P<value>[^&=]+)") matched = regexp.findall(req) if matched: ret = dict() for...
[ "def", "_build_editable_options", "(", "req", ")", ":", "regexp", "=", "re", ".", "compile", "(", "r\"[\\?#&](?P<name>[^&=]+)=(?P<value>[^&=]+)\"", ")", "matched", "=", "regexp", ".", "findall", "(", "req", ")", "if", "matched", ":", "ret", "=", "dict", "(", ...
28.777778
0.001869
def send(self, msg): """Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Arg...
[ "def", "send", "(", "self", ",", "msg", ")", ":", "# Create a sliplib Driver", "slipDriver", "=", "sliplib", ".", "Driver", "(", ")", "# Package data in slip format", "slipData", "=", "slipDriver", ".", "send", "(", "msg", ")", "# Send data over serial port", "res...
31.44
0.002469
def load_spitzer_image(show_progress=False): # pragma: no cover """ Load a 4.5 micron Spitzer image. The catalog for this image is returned by :func:`load_spitzer_catalog`. Parameters ---------- show_progress : bool, optional Whether to display a progress bar during the download...
[ "def", "load_spitzer_image", "(", "show_progress", "=", "False", ")", ":", "# pragma: no cover", "path", "=", "get_path", "(", "'spitzer_example_image.fits'", ",", "location", "=", "'remote'", ",", "show_progress", "=", "show_progress", ")", "hdu", "=", "fits", "....
23.324324
0.001112
def render_pipeline(self): """Write pipeline attributes to json This function writes the pipeline and their attributes to a json file, that is intended to be read by resources/pipeline_graph.html to render a graphical output showing the DAG. """ dict_viz = { ...
[ "def", "render_pipeline", "(", "self", ")", ":", "dict_viz", "=", "{", "\"name\"", ":", "\"root\"", ",", "\"children\"", ":", "[", "]", "}", "last_of_us", "=", "{", "}", "f_tree", "=", "self", ".", "_fork_tree", "if", "self", ".", "_fork_tree", "else", ...
33.287671
0.001199
def ExportingCursorWrapper(cursor_class, alias, vendor): """Returns a CursorWrapper class that knows its database's alias and vendor name. """ class CursorWrapper(cursor_class): """Extends the base CursorWrapper to count events.""" def execute(self, *args, **kwargs): execut...
[ "def", "ExportingCursorWrapper", "(", "cursor_class", ",", "alias", ",", "vendor", ")", ":", "class", "CursorWrapper", "(", "cursor_class", ")", ":", "\"\"\"Extends the base CursorWrapper to count events.\"\"\"", "def", "execute", "(", "self", ",", "*", "args", ",", ...
46.090909
0.000966
def resizeEvent( self, event ): """ Overloads the resize event to handle updating of buttons. :param event | <QResizeEvent> """ super(XLineEdit, self).resizeEvent(event) self.adjustButtons()
[ "def", "resizeEvent", "(", "self", ",", "event", ")", ":", "super", "(", "XLineEdit", ",", "self", ")", ".", "resizeEvent", "(", "event", ")", "self", ".", "adjustButtons", "(", ")" ]
30.625
0.019841
def cross(triangles): """ Returns the cross product of two edges from input triangles Parameters -------------- triangles: (n, 3, 3) float Vertices of triangles Returns -------------- crosses : (n, 3) float Cross product of two edge vectors """ vectors = np.diff(tri...
[ "def", "cross", "(", "triangles", ")", ":", "vectors", "=", "np", ".", "diff", "(", "triangles", ",", "axis", "=", "1", ")", "crosses", "=", "np", ".", "cross", "(", "vectors", "[", ":", ",", "0", "]", ",", "vectors", "[", ":", ",", "1", "]", ...
23
0.002457
def _needs_download(self, f): ''' Decorator used to make sure that the downloading happens prior to running the task. ''' @wraps(f) def wrapper(self, *args, **kwargs): if not self.isdownloaded(): self.download() return f(self, *args, **kwargs) return wrapper
[ "def", "_needs_download", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "isdownloaded", "(", ")", ":", "self", ".", "d...
29.888889
0.036101
def output(self, to=None, *args, **kwargs): '''Outputs to a stream (like a file or request)''' to.write(self.start_tag) if not self.tag_self_closes: to.write(self.end_tag)
[ "def", "output", "(", "self", ",", "to", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "to", ".", "write", "(", "self", ".", "start_tag", ")", "if", "not", "self", ".", "tag_self_closes", ":", "to", ".", "write", "(", "self", ...
40.6
0.009662
def parse_listen_addr(listen_addr): """ Parse an address of the form [ipaddress]:port into a tcp or tcp6 Twisted endpoint description string for use with ``twisted.internet.endpoints.serverFromString``. """ if ':' not in listen_addr: raise ValueError( "'%s' does not have the ...
[ "def", "parse_listen_addr", "(", "listen_addr", ")", ":", "if", "':'", "not", "in", "listen_addr", ":", "raise", "ValueError", "(", "\"'%s' does not have the correct form for a listen address: \"", "'[ipaddress]:port'", "%", "(", "listen_addr", ",", ")", ")", "host", ...
35.40625
0.000859
def active_brokers(self): """Set of brokers that are not inactive or decommissioned.""" return { broker for broker in six.itervalues(self.brokers) if not broker.inactive and not broker.decommissioned }
[ "def", "active_brokers", "(", "self", ")", ":", "return", "{", "broker", "for", "broker", "in", "six", ".", "itervalues", "(", "self", ".", "brokers", ")", "if", "not", "broker", ".", "inactive", "and", "not", "broker", ".", "decommissioned", "}" ]
40.666667
0.008032