text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def rotation(ATTITUDE): '''return the current DCM rotation matrix''' r = Matrix3() r.from_euler(ATTITUDE.roll, ATTITUDE.pitch, ATTITUDE.yaw) return r
[ "def", "rotation", "(", "ATTITUDE", ")", ":", "r", "=", "Matrix3", "(", ")", "r", ".", "from_euler", "(", "ATTITUDE", ".", "roll", ",", "ATTITUDE", ".", "pitch", ",", "ATTITUDE", ".", "yaw", ")", "return", "r" ]
32.2
0.006061
def t(self): """:obj:`numpy.ndarray` : The 3x1 translation matrix for this projection """ t = np.array([self._plane_width / 2, self._plane_height / 2, self._depth_scale / 2]) return t
[ "def", "t", "(", "self", ")", ":", "t", "=", "np", ".", "array", "(", "[", "self", ".", "_plane_width", "/", "2", ",", "self", ".", "_plane_height", "/", "2", ",", "self", ".", "_depth_scale", "/", "2", "]", ")", "return", "t" ]
36.142857
0.011583
def items(self): """ ITERATE THROUGH ALL coord, value PAIRS """ for c in self._all_combos(): _, value = _getitem(self.cube, c) yield c, value
[ "def", "items", "(", "self", ")", ":", "for", "c", "in", "self", ".", "_all_combos", "(", ")", ":", "_", ",", "value", "=", "_getitem", "(", "self", ".", "cube", ",", "c", ")", "yield", "c", ",", "value" ]
27.285714
0.010152
def get_monitoring_problems(self): """Get the current scheduler livesynthesis :return: live synthesis and problems dictionary :rtype: dict """ res = {} if not self.sched: return res # Get statistics from the scheduler scheduler_stats = self.s...
[ "def", "get_monitoring_problems", "(", "self", ")", ":", "res", "=", "{", "}", "if", "not", "self", ".", "sched", ":", "return", "res", "# Get statistics from the scheduler", "scheduler_stats", "=", "self", ".", "sched", ".", "get_scheduler_stats", "(", "details...
32
0.003373
def add_labels(self, objects, count=1): """Add multiple labels to the sheet. Parameters ---------- objects: iterable An iterable of the objects to add. Each of these will be passed to the add_label method. Note that if this is a generator it will be c...
[ "def", "add_labels", "(", "self", ",", "objects", ",", "count", "=", "1", ")", ":", "# If we can convert it to an int, do so and use the itertools.repeat()", "# method to create an infinite iterator from it. Otherwise, assume it", "# is an iterable or sequence.", "try", ":", "count...
41.28
0.000947
def snap(self, path=None): """Get a snapshot and save it to disk.""" if path is None: path = "/tmp" else: path = path.rstrip("/") day_dir = datetime.datetime.now().strftime("%d%m%Y") hour_dir = datetime.datetime.now().strftime("%H%M") ensure_snapsh...
[ "def", "snap", "(", "self", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "\"/tmp\"", "else", ":", "path", "=", "path", ".", "rstrip", "(", "\"/\"", ")", "day_dir", "=", "datetime", ".", "datetime", ".", "now", ...
35
0.004449
def _GetAPFSVolumeIdentifiers(self, scan_node): """Determines the APFS volume identifiers. Args: scan_node (dfvfs.SourceScanNode): scan node. Returns: list[str]: APFS volume identifiers. Raises: SourceScannerError: if the format of or within the source is not supported or ...
[ "def", "_GetAPFSVolumeIdentifiers", "(", "self", ",", "scan_node", ")", ":", "if", "not", "scan_node", "or", "not", "scan_node", ".", "path_spec", ":", "raise", "errors", ".", "SourceScannerError", "(", "'Invalid scan node.'", ")", "volume_system", "=", "apfs_volu...
32.702128
0.005685
def make_url(invocation, args=[], kwargs={}): """ >>> make_url('some/path/program', ['arg1', 'arg2'], {'arg3': 4}) '/some/path/program/arg1/arg2?arg3=4' """ if not invocation.endswith('/'): invocation += '/' if not invocation.startswith('/'): invocation = '/' + invocation ur...
[ "def", "make_url", "(", "invocation", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ")", ":", "if", "not", "invocation", ".", "endswith", "(", "'/'", ")", ":", "invocation", "+=", "'/'", "if", "not", "invocation", ".", "startswith", "(", ...
23.25
0.004132
def read_tex_file(root_filepath, root_dir=None): r"""Read a TeX file, automatically processing and normalizing it (including other input files, removing comments, and deleting trailing whitespace). Parameters ---------- root_filepath : `str` Filepath to a TeX file. root_dir : `str` ...
[ "def", "read_tex_file", "(", "root_filepath", ",", "root_dir", "=", "None", ")", ":", "with", "open", "(", "root_filepath", ",", "'r'", ")", "as", "f", ":", "tex_source", "=", "f", ".", "read", "(", ")", "if", "root_dir", "is", "None", ":", "root_dir",...
28.966667
0.001114
def execute(self, expr, params=None, limit='default', **kwargs): """ Compile and execute Ibis expression using this backend client interface, returning results in-memory in the appropriate object type Parameters ---------- expr : Expr limit : int, default None ...
[ "def", "execute", "(", "self", ",", "expr", ",", "params", "=", "None", ",", "limit", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "query_ast", "=", "self", ".", "_build_ast_ensure_limit", "(", "expr", ",", "limit", ",", "params", "=", "params"...
37.608696
0.002255
def _subscribe(self, sub_id, channel, callback, **kwargs): """Listen to a queue, notify via callback function. :param sub_id: ID for this subscription in the transport layer :param channel: Queue name to subscribe to :param callback: Function to be called when messages are received ...
[ "def", "_subscribe", "(", "self", ",", "sub_id", ",", "channel", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "{", "}", "if", "kwargs", ".", "get", "(", "\"exclusive\"", ")", ":", "headers", "[", "\"activemq.exclusive\"", "]", "=...
51.47619
0.00227
def process_error_labels(value): """ Process the error labels of a dependent variable 'value' to ensure uniqueness. """ observed_error_labels = {} for error in value.get('errors', []): label = error.get('label', 'error') if label not in observed_error_labels: ...
[ "def", "process_error_labels", "(", "value", ")", ":", "observed_error_labels", "=", "{", "}", "for", "error", "in", "value", ".", "get", "(", "'errors'", ",", "[", "]", ")", ":", "label", "=", "error", ".", "get", "(", "'label'", ",", "'error'", ")", ...
42.095238
0.004425
def calc_prediction(registered_map, preregistration_mesh, native_mesh, model): ''' calc_registration_prediction is a pimms calculator that creates the both the prediction and the registration_prediction, both of which are pimms itables including the fields 'polar_angle', 'eccentricity', and 'visual_area...
[ "def", "calc_prediction", "(", "registered_map", ",", "preregistration_mesh", ",", "native_mesh", ",", "model", ")", ":", "# invert the map projection to make the registration map into a mesh", "coords3d", "=", "np", ".", "array", "(", "preregistration_mesh", ".", "coordina...
55.650794
0.01009
def detectMeegoPhone(self): """Return detection of a Meego phone Detects a phone running the Meego OS. """ return UAgentInfo.deviceMeego in self.__userAgent \ and UAgentInfo.mobi in self.__userAgent
[ "def", "detectMeegoPhone", "(", "self", ")", ":", "return", "UAgentInfo", ".", "deviceMeego", "in", "self", ".", "__userAgent", "and", "UAgentInfo", ".", "mobi", "in", "self", ".", "__userAgent" ]
33.857143
0.00823
def init_config(cls): """ Initialize Gandi CLI configuration. Create global configuration directory with API credentials """ try: # first load current conf and only overwrite needed params # we don't want to reset everything config_file = os.path.exp...
[ "def", "init_config", "(", "cls", ")", ":", "try", ":", "# first load current conf and only overwrite needed params", "# we don't want to reset everything", "config_file", "=", "os", ".", "path", ".", "expanduser", "(", "cls", ".", "home_config", ")", "config", "=", "...
40.913793
0.000823
def setChecked(self, column, state): """ Sets the check state of the inputed column based on the given bool state. This is a convenience method on top of the setCheckState method. :param column | <int> state | <bool> """ ...
[ "def", "setChecked", "(", "self", ",", "column", ",", "state", ")", ":", "self", ".", "setCheckState", "(", "column", ",", "QtCore", ".", "Qt", ".", "Checked", "if", "state", "else", "QtCore", ".", "Qt", ".", "Unchecked", ")" ]
39.2
0.009975
def _run_command_in_extended_path(syslog_ng_sbin_dir, command, params): ''' Runs the specified command with the syslog_ng_sbin_dir in the PATH ''' orig_path = os.environ.get('PATH', '') env = None if syslog_ng_sbin_dir: # Custom environment variables should be str types. This code ...
[ "def", "_run_command_in_extended_path", "(", "syslog_ng_sbin_dir", ",", "command", ",", "params", ")", ":", "orig_path", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", "env", "=", "None", "if", "syslog_ng_sbin_dir", ":", "# Custom enviro...
38.95
0.002506
def fit(self, X, y=None, **fit_params): """Fits the inverse covariance model according to the given training data and parameters. Parameters ----------- X : 2D ndarray, shape (n_features, n_features) Input data. Returns ------- self "...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "# quic-specific outputs", "self", ".", "opt_", "=", "None", "self", ".", "cputime_", "=", "None", "self", ".", "iters_", "=", "None", "self", ".", "...
29.269231
0.001907
def query_all(**kwargs): ''' query all the posts. ''' kind = kwargs.get('kind', '1') limit = kwargs.get('limit', 10) return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_update.d...
[ "def", "query_all", "(", "*", "*", "kwargs", ")", ":", "kind", "=", "kwargs", ".", "get", "(", "'kind'", ",", "'1'", ")", "limit", "=", "kwargs", ".", "get", "(", "'limit'", ",", "10", ")", "return", "TabPost", ".", "select", "(", ")", ".", "wher...
25.846154
0.005747
def get_option(self, key): """Return the current value of the option `key` (string). Instance method, only refers to current instance.""" return self._options.get(key, self._default_options[key])
[ "def", "get_option", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_options", ".", "get", "(", "key", ",", "self", ".", "_default_options", "[", "key", "]", ")" ]
43.2
0.009091
def transform_image(self, content_metadata_item): """ Return the image URI of the content item. """ image_url = '' if content_metadata_item['content_type'] in ['course', 'program']: image_url = content_metadata_item.get('card_image_url') elif content_metadata_...
[ "def", "transform_image", "(", "self", ",", "content_metadata_item", ")", ":", "image_url", "=", "''", "if", "content_metadata_item", "[", "'content_type'", "]", "in", "[", "'course'", ",", "'program'", "]", ":", "image_url", "=", "content_metadata_item", ".", "...
39.545455
0.004494
def refresh(self): """! \~english Update current view content to display Supported: JMRPiDisplay_SSD1306 and Adafruit SSD1306 driver \~chinese 更新当前视图内容到显示屏 支持: JMRPiDisplay_SSD1306 和 Adafruit SSD1306 driver """ try: # suport for RPiDis...
[ "def", "refresh", "(", "self", ")", ":", "try", ":", "# suport for RPiDisplay SSD1306 driver", "self", ".", "Display", ".", "setImage", "(", "self", ".", "_catchCurrentViewContent", "(", ")", ")", "except", ":", "try", ":", "# suport for Adafruit SSD1306 driver", ...
31.047619
0.014881
def _prepare_deprecation_data(self): """ Cycles through the list of AppSettingDeprecation instances set on ``self.deprecations`` and prepulates two new dictionary attributes: ``self._deprecated_settings``: Uses the deprecated setting names themselves as the keys. Used to ...
[ "def", "_prepare_deprecation_data", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "deprecations", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "IncorrectDeprecationsValueType", "(", "\"'deprecations' must be a list or tuple, not a {}.\...
45.552239
0.000962
def warnpy3k(message, category=None, stacklevel=1): """Issue a deprecation warning for Python 3.x related changes. Warnings are omitted unless Python is started with the -3 option. """ if sys.py3kwarning: if category is None: category = DeprecationWarning warn(message, categ...
[ "def", "warnpy3k", "(", "message", ",", "category", "=", "None", ",", "stacklevel", "=", "1", ")", ":", "if", "sys", ".", "py3kwarning", ":", "if", "category", "is", "None", ":", "category", "=", "DeprecationWarning", "warn", "(", "message", ",", "catego...
36.666667
0.002959
def stop_service(conn, service='ceph'): """ Stop a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): # Without the check, an error is rai...
[ "def", "stop_service", "(", "conn", ",", "service", "=", "'ceph'", ")", ":", "if", "is_systemd", "(", "conn", ")", ":", "# Without the check, an error is raised trying to stop an", "# already stopped service", "if", "is_systemd_service_active", "(", "conn", ",", "servic...
33.263158
0.001538
def _read_gtf(gtf): """ Load GTF file with precursor positions on genome """ if not gtf: return gtf db = defaultdict(list) with open(gtf) as in_handle: for line in in_handle: if line.startswith("#"): continue cols = line.strip().split("\t")...
[ "def", "_read_gtf", "(", "gtf", ")", ":", "if", "not", "gtf", ":", "return", "gtf", "db", "=", "defaultdict", "(", "list", ")", "with", "open", "(", "gtf", ")", "as", "in_handle", ":", "for", "line", "in", "in_handle", ":", "if", "line", ".", "star...
35.941176
0.00319
def bind(self, handler, argspec): """ :param handler: a function with :param argspec: :return: """ self.handlers[argspec.key].append((handler, argspec))
[ "def", "bind", "(", "self", ",", "handler", ",", "argspec", ")", ":", "self", ".", "handlers", "[", "argspec", ".", "key", "]", ".", "append", "(", "(", "handler", ",", "argspec", ")", ")" ]
27.714286
0.01
def __CheckAndUnifyQueryFormat(self, query_body): """Checks and unifies the format of the query body. :raises TypeError: If query_body is not of expected type (depending on the query compatibility mode). :raises ValueError: If query_body is a dict but doesn\'t have valid query text. :ra...
[ "def", "__CheckAndUnifyQueryFormat", "(", "self", ",", "query_body", ")", ":", "if", "(", "self", ".", "_query_compatibility_mode", "==", "CosmosClient", ".", "_QueryCompatibilityMode", ".", "Default", "or", "self", ".", "_query_compatibility_mode", "==", "CosmosClien...
50.586207
0.006689
def match(self, expression=None, xpath=None, namespaces=None): """decorator that allows us to match by expression or by xpath for each transformation method""" class MatchObject(Dict): pass def _match(function): self.matches.append( MatchObject(expression...
[ "def", "match", "(", "self", ",", "expression", "=", "None", ",", "xpath", "=", "None", ",", "namespaces", "=", "None", ")", ":", "class", "MatchObject", "(", "Dict", ")", ":", "pass", "def", "_match", "(", "function", ")", ":", "self", ".", "matches...
48.181818
0.012963
def find_window_for_buffer_name(cli, buffer_name): """ Look for a :class:`~prompt_toolkit.layout.containers.Window` in the Layout that contains the :class:`~prompt_toolkit.layout.controls.BufferControl` for the given buffer and return it. If no such Window is found, return None. """ from prompt_...
[ "def", "find_window_for_buffer_name", "(", "cli", ",", "buffer_name", ")", ":", "from", "prompt_toolkit", ".", "interface", "import", "CommandLineInterface", "assert", "isinstance", "(", "cli", ",", "CommandLineInterface", ")", "from", ".", "containers", "import", "...
41.5
0.004418
def deserialize(stream_or_string, **options): ''' Deserialize any string or stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower configparser module. ''' if six.PY3: cp = configparser.ConfigPar...
[ "def", "deserialize", "(", "stream_or_string", ",", "*", "*", "options", ")", ":", "if", "six", ".", "PY3", ":", "cp", "=", "configparser", ".", "ConfigParser", "(", "*", "*", "options", ")", "else", ":", "cp", "=", "configparser", ".", "SafeConfigParser...
33.617647
0.00085
def parse_event(data, attendees=None, photos=None): """ Parse a ``MeetupEvent`` from the given response data. Returns ------- A ``pythonkc_meetups.types.MeetupEvent``. """ return MeetupEvent( id=data.get('id', None), name=data.get('name', None), description=data.get...
[ "def", "parse_event", "(", "data", ",", "attendees", "=", "None", ",", "photos", "=", "None", ")", ":", "return", "MeetupEvent", "(", "id", "=", "data", ".", "get", "(", "'id'", ",", "None", ")", ",", "name", "=", "data", ".", "get", "(", "'name'",...
33.791667
0.001199
def plotIndividual(self): ''' Plot the individual ''' pl.plot(self.x_int, self.y_int) pl.grid(True) pl.show()
[ "def", "plotIndividual", "(", "self", ")", ":", "pl", ".", "plot", "(", "self", ".", "x_int", ",", "self", ".", "y_int", ")", "pl", ".", "grid", "(", "True", ")", "pl", ".", "show", "(", ")" ]
16.428571
0.066116
def __shxRecords(self): """Writes the shx records.""" f = self.__getFileObj(self.shx) f.seek(100) for i in range(len(self._shapes)): f.write(pack(">i", self._offsets[i] // 2)) f.write(pack(">i", self._lengths[i]))
[ "def", "__shxRecords", "(", "self", ")", ":", "f", "=", "self", ".", "__getFileObj", "(", "self", ".", "shx", ")", "f", ".", "seek", "(", "100", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_shapes", ")", ")", ":", "f", ".", ...
38.428571
0.007273
def encrypt(self, sa, esp, key): """ Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: the secret key used for encryption @return: a valid ESP packet...
[ "def", "encrypt", "(", "self", ",", "sa", ",", "esp", ",", "key", ")", ":", "data", "=", "esp", ".", "data_for_encryption", "(", ")", "if", "self", ".", "cipher", ":", "mode_iv", "=", "self", ".", "_format_mode_iv", "(", "algo", "=", "self", ",", "...
38.230769
0.001963
def make_dynamic_fields(pattern_module, dynamic_field_patterns, attrs): """Add some Salesforce fields from a pattern_module models.py Parameters: pattern_module: Module where to search additional fields settings. It is an imported module created by introspection (inspectdb), usua...
[ "def", "make_dynamic_fields", "(", "pattern_module", ",", "dynamic_field_patterns", ",", "attrs", ")", ":", "# pylint:disable=invalid-name,too-many-branches,too-many-locals", "import", "re", "attr_meta", "=", "attrs", "[", "'Meta'", "]", "db_table", "=", "getattr", "(", ...
45.010309
0.002017
def exchange_code(self, code): """Exchange one-use code for an access_token and request_token.""" params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'authorization_code', 'code': code} result = self._sen...
[ "def", "exchange_code", "(", "self", ",", "code", ")", ":", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'grant_type'", ":", "'authorization_code'", ",", "'code'", ":", "co...
52.583333
0.003115
async def close(self): """Close this SAConnection. This results in a release of the underlying database resources, that is, the underlying connection referenced internally. The underlying connection is typically restored back to the connection-holding Pool referenced by the Engi...
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_connection", "is", "None", ":", "return", "if", "self", ".", "_transaction", "is", "not", "None", ":", "await", "self", ".", "_transaction", ".", "rollback", "(", ")", "self", ".", ...
40.28
0.00194
def _parse_global_section(self, cfg_handler): """Parse global ([versionner]) section :param cfg_handler: :return: """ # global configuration if 'versionner' in cfg_handler: cfg = cfg_handler['versionner'] if 'file' in cfg: self.ver...
[ "def", "_parse_global_section", "(", "self", ",", "cfg_handler", ")", ":", "# global configuration", "if", "'versionner'", "in", "cfg_handler", ":", "cfg", "=", "cfg_handler", "[", "'versionner'", "]", "if", "'file'", "in", "cfg", ":", "self", ".", "version_file...
39.157895
0.003937
def print_all(self, out=sys.stdout): """ Prints all of the thread profiler results to a given file. (stdout by default) """ THREAD_FUNC_NAME_LEN = 25 THREAD_NAME_LEN = 13 THREAD_ID_LEN = 15 THREAD_SCHED_CNT_LEN = 10 out.write(CRLF) out.write("name...
[ "def", "print_all", "(", "self", ",", "out", "=", "sys", ".", "stdout", ")", ":", "THREAD_FUNC_NAME_LEN", "=", "25", "THREAD_NAME_LEN", "=", "13", "THREAD_ID_LEN", "=", "15", "THREAD_SCHED_CNT_LEN", "=", "10", "out", ".", "write", "(", "CRLF", ")", "out", ...
40
0.004651
def item_link(self, item): """ Generates a link for a specific item of the feed. """ return reverse_lazy( 'forum_conversation:topic', kwargs={ 'forum_slug': item.forum.slug, 'forum_pk': item.forum.pk, 'slug': item.slug, ...
[ "def", "item_link", "(", "self", ",", "item", ")", ":", "return", "reverse_lazy", "(", "'forum_conversation:topic'", ",", "kwargs", "=", "{", "'forum_slug'", ":", "item", ".", "forum", ".", "slug", ",", "'forum_pk'", ":", "item", ".", "forum", ".", "pk", ...
32.090909
0.00551
def apply_boundary_conditions(self, **kwargs): """Applies any boundary conditions to the given values (e.g., applying cyclic conditions, and/or reflecting values off of boundaries). This is done by running `apply_conditions` of each bounds in self on the corresponding value. See `boundar...
[ "def", "apply_boundary_conditions", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "[", "[", "p", ",", "self", ".", "_bounds", "[", "p", "]", ".", "apply_conditions", "(", "val", ")", "]", "for", "p", ",", "val", "in", "kwar...
42.045455
0.004228
def received_message(self, m): """Push upstream messages to downstream.""" # TODO: No support for binary messages m = str(m) logger.debug("Incoming upstream WS: %s", m) uwsgi.websocket_send(m) logger.debug("Send ok")
[ "def", "received_message", "(", "self", ",", "m", ")", ":", "# TODO: No support for binary messages", "m", "=", "str", "(", "m", ")", "logger", ".", "debug", "(", "\"Incoming upstream WS: %s\"", ",", "m", ")", "uwsgi", ".", "websocket_send", "(", "m", ")", "...
32.25
0.007547
def join_conn_groups( conns, descs, mat_ids, concat = False ): """Join groups of the same element type.""" el = dict_from_keys_init( descs, list ) for ig, desc in enumerate( descs ): el[desc].append( ig ) groups = [ii for ii in el.values() if ii] ## print el, groups descs_out, conns_ou...
[ "def", "join_conn_groups", "(", "conns", ",", "descs", ",", "mat_ids", ",", "concat", "=", "False", ")", ":", "el", "=", "dict_from_keys_init", "(", "descs", ",", "list", ")", "for", "ig", ",", "desc", "in", "enumerate", "(", "descs", ")", ":", "el", ...
31.6
0.029683
def get_instruction(self, idx, off=None): """ Get a particular instruction by using (default) the index of the address if specified :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of the instruction :t...
[ "def", "get_instruction", "(", "self", ",", "idx", ",", "off", "=", "None", ")", ":", "if", "self", ".", "code", "is", "not", "None", ":", "return", "self", ".", "code", ".", "get_bc", "(", ")", ".", "get_instruction", "(", "idx", ",", "off", ")", ...
35.5
0.007843
def calc_changes(db, ignore_tables=None): migrator = None # expose eventually? if migrator is None: migrator = auto_detect_migrator(db) existing_tables = [unicode(t) for t in db.get_tables()] existing_indexes = {table:get_indexes_by_table(db, table) for table in existing_tables} existing_columns_by_table...
[ "def", "calc_changes", "(", "db", ",", "ignore_tables", "=", "None", ")", ":", "migrator", "=", "None", "# expose eventually?", "if", "migrator", "is", "None", ":", "migrator", "=", "auto_detect_migrator", "(", "db", ")", "existing_tables", "=", "[", "unicode"...
43.849315
0.015582
def create_disk(kwargs=None, call=None): ''' Create a new persistent disk. Must specify `disk_name` and `location`, and optionally can specify 'disk_type' as pd-standard or pd-ssd, which defaults to pd-standard. Can also specify an `image` or `snapshot` but if neither of those are specified, a `siz...
[ "def", "create_disk", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_disk function must be called with -f or --function.'", ")", "if", "kwargs", "is", "None", ...
26.571429
0.000864
def _migrate_ledger(data_directory, old_ledger_file, new_ledger_file, serializer: MappingSerializer = None): """ Test for the directory, open old and new ledger, migrate data, rename directories """ # we should have ChunkedFileStorage implementation of the Ledger...
[ "def", "_migrate_ledger", "(", "data_directory", ",", "old_ledger_file", ",", "new_ledger_file", ",", "serializer", ":", "MappingSerializer", "=", "None", ")", ":", "# we should have ChunkedFileStorage implementation of the Ledger", "if", "not", "os", ".", "path", ".", ...
40.34
0.000968
def add_peer(self, peer_addr): "Build a connection to the Hub at a given ``(host, port)`` address" peer = connection.Peer( self._ident, self._dispatcher, peer_addr, backend.Socket()) peer.start() self._started_peers[peer_addr] = peer
[ "def", "add_peer", "(", "self", ",", "peer_addr", ")", ":", "peer", "=", "connection", ".", "Peer", "(", "self", ".", "_ident", ",", "self", ".", "_dispatcher", ",", "peer_addr", ",", "backend", ".", "Socket", "(", ")", ")", "peer", ".", "start", "("...
46
0.007117
def check_owners(self, request, **resources): """ Check parents of current resource. Recursive scanning of the fact that the child has FK to the parent and in resources we have right objects. We check that in request like /author/1/book/2/page/3 Page object with pk=3 has Forei...
[ "def", "check_owners", "(", "self", ",", "request", ",", "*", "*", "resources", ")", ":", "if", "self", ".", "_meta", ".", "allow_public_access", "or", "not", "self", ".", "_meta", ".", "parent", ":", "return", "True", "self", ".", "parent", ".", "chec...
35.4
0.001571
async def write_registers(self, address, values, skip_encode=False): """Write modbus registers. The Modbus protocol doesn't allow requests longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ while len(v...
[ "async", "def", "write_registers", "(", "self", ",", "address", ",", "values", ",", "skip_encode", "=", "False", ")", ":", "while", "len", "(", "values", ")", ">", "62", ":", "await", "self", ".", "_request", "(", "'write_registers'", ",", "address", ","...
47.615385
0.00317
def index(value, array): """ Array search that behaves like I want it to. Totally dumb, I know. """ i = array.searchsorted(value) if i == len(array): return -1 else: return i
[ "def", "index", "(", "value", ",", "array", ")", ":", "i", "=", "array", ".", "searchsorted", "(", "value", ")", "if", "i", "==", "len", "(", "array", ")", ":", "return", "-", "1", "else", ":", "return", "i" ]
29.428571
0.018868
def _addProteinIdsToGroupMapping(self, proteinIds, groupId): """Add a groupId to one or multiple entries of the internal proteinToGroupId mapping. :param proteinIds: a proteinId or a list of proteinIds, a proteinId must be a string. :param groupId: str, a groupId """...
[ "def", "_addProteinIdsToGroupMapping", "(", "self", ",", "proteinIds", ",", "groupId", ")", ":", "for", "proteinId", "in", "AUX", ".", "toList", "(", "proteinIds", ")", ":", "self", ".", "_proteinToGroupIds", "[", "proteinId", "]", ".", "add", "(", "groupId"...
42
0.004662
def _assemble_autophosphorylation(self, stmt): """Example: complex(p(HGNC:MAPK14), p(HGNC:TAB1)) => p(HGNC:MAPK14, pmod(Ph, Tyr, 100))""" sub_agent = deepcopy(stmt.enz) mc = stmt._get_mod_condition() sub_agent.mods.append(mc) # FIXME Ignore...
[ "def", "_assemble_autophosphorylation", "(", "self", ",", "stmt", ")", ":", "sub_agent", "=", "deepcopy", "(", "stmt", ".", "enz", ")", "mc", "=", "stmt", ".", "_get_mod_condition", "(", ")", "sub_agent", ".", "mods", ".", "append", "(", "mc", ")", "# FI...
49.714286
0.004231
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
[ "def", "is_zombie", "(", "self", ",", "path", ")", ":", "node", "=", "self", ".", "get_node", "(", "path", ")", "if", "not", "node", ":", "return", "False", "return", "node", ".", "is_zombie" ]
33.166667
0.009804
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via pairwise atom-atom distances Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.n...
[ "def", "partial_transform", "(", "self", ",", "traj", ")", ":", "d", "=", "md", ".", "geometry", ".", "compute_distances", "(", "traj", ",", "self", ".", "pair_indices", ",", "periodic", "=", "self", ".", "periodic", ")", "return", "d", "**", "self", "...
37.541667
0.002165
def lookup_reverse(ip_address): """Perform a reverse lookup of IP address.""" try: type(ipaddress.ip_address(ip_address)) except ValueError: return {} record = reversename.from_address(ip_address) hostname = str(resolver.query(record, "PTR")[0])[:-1] return {'hostname': hostname...
[ "def", "lookup_reverse", "(", "ip_address", ")", ":", "try", ":", "type", "(", "ipaddress", ".", "ip_address", "(", "ip_address", ")", ")", "except", "ValueError", ":", "return", "{", "}", "record", "=", "reversename", ".", "from_address", "(", "ip_address",...
31.2
0.003115
def get_dataset(self, key, info): """Load a dataset.""" logger.debug('Reading in get_dataset %s.', key.name) var_name = info.get('file_key', self.filetype_info.get('file_key')) if var_name: data = self[var_name] elif 'Sectorized_CMI' in self.nc: data = sel...
[ "def", "get_dataset", "(", "self", ",", "key", ",", "info", ")", ":", "logger", ".", "debug", "(", "'Reading in get_dataset %s.'", ",", "key", ".", "name", ")", "var_name", "=", "info", ".", "get", "(", "'file_key'", ",", "self", ".", "filetype_info", "....
45.586957
0.002334
def return_data(self, data, format=None): """Format and return data appropriate to the requested API format. data: The data retured by the api request """ if format is None: format = self.format if format == "json": formatted_data = json.loads(data) ...
[ "def", "return_data", "(", "self", ",", "data", ",", "format", "=", "None", ")", ":", "if", "format", "is", "None", ":", "format", "=", "self", ".", "format", "if", "format", "==", "\"json\"", ":", "formatted_data", "=", "json", ".", "loads", "(", "d...
29.307692
0.005089
def negotiate_sasl(transport, xmlstream, sasl_providers, negotiation_timeout, jid, features): """ Perform SASL authentication on the given :class:`.protocol.XMLStream` `stream`. `transport` must be the :class:`asyncio.Transport` over which the `st...
[ "def", "negotiate_sasl", "(", "transport", ",", "xmlstream", ",", "sasl_providers", ",", "negotiation_timeout", ",", "jid", ",", "features", ")", ":", "if", "not", "transport", ".", "get_extra_info", "(", "\"sslcontext\"", ")", ":", "transport", "=", "None", "...
36.761905
0.000421
def install_brew(target_path): """ Install brew to the target path """ if not os.path.exists(target_path): try: os.makedirs(target_path) except OSError: logger.warn("Unable to create directory %s for brew." % target_path) logger.warn("Skipping...") ...
[ "def", "install_brew", "(", "target_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "target_path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "target_path", ")", "except", "OSError", ":", "logger", ".", "warn", "(", "\"Unabl...
39
0.005013
def new(): """Create new group.""" form = GroupForm(request.form) if form.validate_on_submit(): try: group = Group.create(admins=[current_user], **form.data) flash(_('Group "%(name)s" created', name=group.name), 'success') return redirect(url_for(".index")) ...
[ "def", "new", "(", ")", ":", "form", "=", "GroupForm", "(", "request", ".", "form", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "try", ":", "group", "=", "Group", ".", "create", "(", "admins", "=", "[", "current_user", "]", ",", "*...
27.941176
0.002037
def create_transfer_config( self, parent, transfer_config, authorization_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new data transfer configuration....
[ "def", "create_transfer_config", "(", "self", ",", "parent", ",", "transfer_config", ",", "authorization_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "ap...
48.04902
0.007197
def import_object(object_name): """Import an object from its Fully Qualified Name.""" package, name = object_name.rsplit('.', 1) return getattr(importlib.import_module(package), name)
[ "def", "import_object", "(", "object_name", ")", ":", "package", ",", "name", "=", "object_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "return", "getattr", "(", "importlib", ".", "import_module", "(", "package", ")", ",", "name", ")" ]
48
0.005128
def get_calltip(project, source_code, offset, resource=None, maxfixes=1, ignore_unknown=False, remove_self=False): """Get the calltip of a function The format of the returned string is ``module_name.holding_scope_names.function_name(arguments)``. For classes `__init__()` and for normal...
[ "def", "get_calltip", "(", "project", ",", "source_code", ",", "offset", ",", "resource", "=", "None", ",", "maxfixes", "=", "1", ",", "ignore_unknown", "=", "False", ",", "remove_self", "=", "False", ")", ":", "fixer", "=", "fixsyntax", ".", "FixSyntax", ...
40.903226
0.00077
def to_dict(self, model): """Create a dictionary serialization for a model. Parameters ---------- model : ModelHandle Returns ------- dict Dictionary serialization for a model """ # Get the basic Json object from the super class ...
[ "def", "to_dict", "(", "self", ",", "model", ")", ":", "# Get the basic Json object from the super class", "obj", "=", "super", "(", "ModelRegistry", ",", "self", ")", ".", "to_dict", "(", "model", ")", "# Add model parameter", "obj", "[", "'parameters'", "]", "...
27.952381
0.003295
def invert_dict(dict_, unique_vals=True): """ Reverses the keys and values in a dictionary. Set unique_vals to False if the values in the dict are not unique. Args: dict_ (dict_): dictionary unique_vals (bool): if False, inverted keys are returned in a list. Returns: dict: ...
[ "def", "invert_dict", "(", "dict_", ",", "unique_vals", "=", "True", ")", ":", "if", "unique_vals", ":", "inverted_items", "=", "[", "(", "val", ",", "key", ")", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "dict_", ")", "]", "invert...
34.384615
0.000544
def split(self, only_watertight=True, adjacency=None, **kwargs): """ Returns a list of Trimesh objects, based on face connectivity. Splits into individual components, sometimes referred to as 'bodies' Parameters --------- only_watertight : bool Only return wate...
[ "def", "split", "(", "self", ",", "only_watertight", "=", "True", ",", "adjacency", "=", "None", ",", "*", "*", "kwargs", ")", ":", "meshes", "=", "graph", ".", "split", "(", "self", ",", "only_watertight", "=", "only_watertight", ",", "adjacency", "=", ...
34.727273
0.002548
async def preProcessForComparison(results, target_size, size_tolerance_prct): """ Process results to prepare them for future comparison and sorting. """ # find reference (=image most likely to match target cover ignoring factors like size and format) reference = None for result in results: if resu...
[ "async", "def", "preProcessForComparison", "(", "results", ",", "target_size", ",", "size_tolerance_prct", ")", ":", "# find reference (=image most likely to match target cover ignoring factors like size and format)", "reference", "=", "None", "for", "result", "in", "results", ...
41.253521
0.01067
def set_course_timetable(self, course_id, timetables_course_section_id=None, timetables_course_section_id_end_time=None, timetables_course_section_id_location_name=None, timetables_course_section_id_start_time=None, timetables_course_section_id_weekdays=None): """ Set a course timetable. Cr...
[ "def", "set_course_timetable", "(", "self", ",", "course_id", ",", "timetables_course_section_id", "=", "None", ",", "timetables_course_section_id_end_time", "=", "None", ",", "timetables_course_section_id_location_name", "=", "None", ",", "timetables_course_section_id_start_ti...
57.469388
0.005237
def fpost(self, url, form_data): """ To make a form-data POST request to Falkonry API server :param url: string :param form_data: form-data """ response = None if 'files' in form_data: response = requests.post( self.host + url, ...
[ "def", "fpost", "(", "self", ",", "url", ",", "form_data", ")", ":", "response", "=", "None", "if", "'files'", "in", "form_data", ":", "response", "=", "requests", ".", "post", "(", "self", ".", "host", "+", "url", ",", "data", "=", "form_data", "[",...
37.897436
0.003958
def load_deposit(data): """Load the raw JSON dump of the Deposition. Uses Record API in order to bypass all Deposit-specific initialization, which are to be done after the final stage of deposit migration. :param data: Dictionary containing deposition data. :type data: dict """ from inveni...
[ "def", "load_deposit", "(", "data", ")", ":", "from", "invenio_db", "import", "db", "deposit", ",", "dep_pid", "=", "create_record_and_pid", "(", "data", ")", "deposit", "=", "create_files_and_sip", "(", "deposit", ",", "dep_pid", ")", "db", ".", "session", ...
34.615385
0.002165
def get_object(model, cid, engine_name=None, connection=None): """ Get cached object from redis if id is None then return None: """ from uliweb import settings if not id: return if not check_enable(): return redis = get_redis() if not redis: retur...
[ "def", "get_object", "(", "model", ",", "cid", ",", "engine_name", "=", "None", ",", "connection", "=", "None", ")", ":", "from", "uliweb", "import", "settings", "if", "not", "id", ":", "return", "if", "not", "check_enable", "(", ")", ":", "return", "r...
25.028571
0.010989
def log_predictive_density_sampling(self, y_test, mu_star, var_star, Y_metadata=None, num_samples=1000): """ Calculation of the log predictive density via sampling .. math: log p(y_{*}|D) = log 1/num_samples prod^{S}_{s=1} p(y_{*}|f_{*s}) f_{*s} ~ p(f_{*}|\mu_{*}\\sigma^...
[ "def", "log_predictive_density_sampling", "(", "self", ",", "y_test", ",", "mu_star", ",", "var_star", ",", "Y_metadata", "=", "None", ",", "num_samples", "=", "1000", ")", ":", "assert", "y_test", ".", "shape", "==", "mu_star", ".", "shape", "assert", "y_te...
45.793103
0.008112
def post(url, var): """Post data to an url.""" data = {b[0]: b[1] for b in [a.split("=") for a in var]} writeln("Sending data to url", url) response = requests.post(url, data=data) if response.status_code == 200: writeln(response.text) else: writeln(str(response.status_code), res...
[ "def", "post", "(", "url", ",", "var", ")", ":", "data", "=", "{", "b", "[", "0", "]", ":", "b", "[", "1", "]", "for", "b", "in", "[", "a", ".", "split", "(", "\"=\"", ")", "for", "a", "in", "var", "]", "}", "writeln", "(", "\"Sending data ...
36.111111
0.003003
def _camel_case(cls, text, first_upper=False): """ Transform text to camelCase or CamelCase :param text: :param first_upper: first symbol must be upper? :return: """ result = '' need_upper = False for pos, symbol in enumerate(text): if...
[ "def", "_camel_case", "(", "cls", ",", "text", ",", "first_upper", "=", "False", ")", ":", "result", "=", "''", "need_upper", "=", "False", "for", "pos", ",", "symbol", "in", "enumerate", "(", "text", ")", ":", "if", "symbol", "==", "'_'", "and", "po...
29.727273
0.002963
def perform(self, cfg): """ Performs transformation according to configuration :param cfg: transformation configuration """ self.__src = self._load(cfg[Transformation.__CFG_KEY_LOAD]) self.__transform(cfg[Transformation.__CFG_KEY_TRANSFORM]) self.__cleanup(cfg[Tra...
[ "def", "perform", "(", "self", ",", "cfg", ")", ":", "self", ".", "__src", "=", "self", ".", "_load", "(", "cfg", "[", "Transformation", ".", "__CFG_KEY_LOAD", "]", ")", "self", ".", "__transform", "(", "cfg", "[", "Transformation", ".", "__CFG_KEY_TRANS...
44.333333
0.004914
def fetch_job(self, job_id, checkout=False): """ Fetch the current job reference (refs/aetros/job/<id>) from origin and (when checkout=True)read its tree to the current git index and checkout into working director. """ self.job_id = job_id self.logger.debug("Git fetch jo...
[ "def", "fetch_job", "(", "self", ",", "job_id", ",", "checkout", "=", "False", ")", ":", "self", ".", "job_id", "=", "job_id", "self", ".", "logger", ".", "debug", "(", "\"Git fetch job reference %s\"", "%", "(", "self", ".", "ref_head", ",", ")", ")", ...
43.666667
0.007471
def set_objective(self, expression): """Set objective of problem.""" if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression(offset=expression) # Clear previous objectiv...
[ "def", "set_objective", "(", "self", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "numbers", ".", "Number", ")", ":", "# Allow expressions with no variables as objective,", "# represented as a number", "expression", "=", "Expression", "(", ...
39.176471
0.002933
def merged(*dicts, **kwargs): """ Merge dictionaries. Later keys overwrite. .. code-block:: python merged(dict(a=1), dict(b=2), c=3, d=1) """ if not dicts: return Struct() result = dict() for d in dicts: result.update(d) result.update(kwargs) struct_type = ...
[ "def", "merged", "(", "*", "dicts", ",", "*", "*", "kwargs", ")", ":", "if", "not", "dicts", ":", "return", "Struct", "(", ")", "result", "=", "dict", "(", ")", "for", "d", "in", "dicts", ":", "result", ".", "update", "(", "d", ")", "result", "...
20.647059
0.002725
def validate_config(data: dict) -> dict: """Convert to MIP config format.""" errors = ConfigSchema().validate(data) if errors: for field, messages in errors.items(): if isinstance(messages, dict): for level, sample_errors in messages.items(): ...
[ "def", "validate_config", "(", "data", ":", "dict", ")", "->", "dict", ":", "errors", "=", "ConfigSchema", "(", ")", ".", "validate", "(", "data", ")", "if", "errors", ":", "for", "field", ",", "messages", "in", "errors", ".", "items", "(", ")", ":",...
54.153846
0.00419
def collect_sound_streams(self): """ Return a list of sound streams in this timeline and its children. The streams are returned in order with respect to the timeline. A stream is returned as a list: the first element is the tag which introduced that stream; other elements are th...
[ "def", "collect_sound_streams", "(", "self", ")", ":", "rc", "=", "[", "]", "current_stream", "=", "None", "# looking in all containers for frames", "for", "tag", "in", "self", ".", "all_tags_of_type", "(", "(", "TagSoundStreamHead", ",", "TagSoundStreamBlock", ")",...
42.333333
0.005501
def get(self, name=""): """Get the address(es). """ addrs = [] with self._address_lock: for metadata in self._addresses.values(): if (name == "" or (name and name in metadata["service"])): mda = copy.copy(metadata) ...
[ "def", "get", "(", "self", ",", "name", "=", "\"\"", ")", ":", "addrs", "=", "[", "]", "with", "self", ".", "_address_lock", ":", "for", "metadata", "in", "self", ".", "_addresses", ".", "values", "(", ")", ":", "if", "(", "name", "==", "\"\"", "...
35.214286
0.003953
def calculate_subscription_lifecycle(subscription_id): """ Calculates the expected lifecycle position the subscription in subscription_ids, and creates a BehindSubscription entry for them. Args: subscription_id (str): ID of subscription to calculate lifecycle for """ subscription = Subs...
[ "def", "calculate_subscription_lifecycle", "(", "subscription_id", ")", ":", "subscription", "=", "Subscription", ".", "objects", ".", "select_related", "(", "\"messageset\"", ",", "\"schedule\"", ")", ".", "get", "(", "id", "=", "subscription_id", ")", "behind", ...
39.115385
0.002879
def pred_from_structures(self, target_species, structures_list, remove_duplicates=True, remove_existing=False): """ performs a structure prediction targeting compounds containing all of the target_species, based on a list of structure (those structures can fo...
[ "def", "pred_from_structures", "(", "self", ",", "target_species", ",", "structures_list", ",", "remove_duplicates", "=", "True", ",", "remove_existing", "=", "False", ")", ":", "target_species", "=", "get_el_sp", "(", "target_species", ")", "result", "=", "[", ...
46.204301
0.001823
def leb128_decode(data): """ Decodes a LEB128-encoded unsigned integer. :param BufferedIOBase data: The buffer containing the LEB128-encoded integer to decode. :return: The decoded integer. :rtype: int """ result = 0 shift = 0 while True: ...
[ "def", "leb128_decode", "(", "data", ")", ":", "result", "=", "0", "shift", "=", "0", "while", "True", ":", "character", "=", "data", ".", "read", "(", "1", ")", "if", "len", "(", "character", ")", "==", "0", ":", "raise", "bitcoin", ".", "core", ...
28.409091
0.006192
def permute(self, qubits: Qubits) -> 'Channel': """Return a copy of this channel with qubits in new order""" vec = self.vec.permute(qubits) return Channel(vec.tensor, qubits=vec.qubits)
[ "def", "permute", "(", "self", ",", "qubits", ":", "Qubits", ")", "->", "'Channel'", ":", "vec", "=", "self", ".", "vec", ".", "permute", "(", "qubits", ")", "return", "Channel", "(", "vec", ".", "tensor", ",", "qubits", "=", "vec", ".", "qubits", ...
51.5
0.009569
def auth(self): """ Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList """ if self._auth is None: self._auth = AuthTypesList( se...
[ "def", "auth", "(", "self", ")", ":", "if", "self", ".", "_auth", "is", "None", ":", "self", ".", "_auth", "=", "AuthTypesList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "domain_si...
33.428571
0.008316
def _to_ufo_features(self, master, ufo): """Write an UFO's OpenType feature file.""" # Recover the original feature code if it was stored in the user data original = master.userData[ORIGINAL_FEATURE_CODE_KEY] if original is not None: ufo.features.text = original return prefixes = [...
[ "def", "_to_ufo_features", "(", "self", ",", "master", ",", "ufo", ")", ":", "# Recover the original feature code if it was stored in the user data", "original", "=", "master", ".", "userData", "[", "ORIGINAL_FEATURE_CODE_KEY", "]", "if", "original", "is", "not", "None"...
37.19697
0.001984
def nacm_rule_list_cmdrule_log_if_permit(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm") rule_list = ET.SubElement(nacm, "rule-list") name_key = ET.SubElem...
[ "def", "nacm_rule_list_cmdrule_log_if_permit", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "nacm", "=", "ET", ".", "SubElement", "(", "config", ",", "\"nacm\"", ",", "xmlns", "=", "\"urn:ietf...
47.266667
0.005533
def fold(self): """Folds the region.""" start, end = self.get_range() TextBlockHelper.set_collapsed(self._trigger, True) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): block.setVisible(False) block = block.next()
[ "def", "fold", "(", "self", ")", ":", "start", ",", "end", "=", "self", ".", "get_range", "(", ")", "TextBlockHelper", ".", "set_collapsed", "(", "self", ".", "_trigger", ",", "True", ")", "block", "=", "self", ".", "_trigger", ".", "next", "(", ")",...
38.125
0.00641
def plural(formatter, value, name, option, format): """Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.form...
[ "def", "plural", "(", "formatter", ",", "value", ",", "name", ",", "option", ",", "format", ")", ":", "# Extract the plural words from the format string.", "words", "=", "format", ".", "split", "(", "'|'", ")", "# This extension requires at least two plural words.", "...
34.535714
0.001006
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. """ for d in dict_list: ...
[ "def", "dictlist_convert_to_string", "(", "dict_list", ":", "Iterable", "[", "Dict", "]", ",", "key", ":", "str", ")", "->", "None", ":", "for", "d", "in", "dict_list", ":", "d", "[", "key", "]", "=", "str", "(", "d", "[", "key", "]", ")", "if", ...
38.5
0.002538
def coerce_nc3_dtype(arr): """Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keywo...
[ "def", "coerce_nc3_dtype", "(", "arr", ")", ":", "dtype", "=", "str", "(", "arr", ".", "dtype", ")", "if", "dtype", "in", "_nc3_dtype_coercions", ":", "new_dtype", "=", "_nc3_dtype_coercions", "[", "dtype", "]", "# TODO: raise a warning whenever casting the data-typ...
37.8
0.00129
def requests_url(self, ptype, **data): """ 这里包装了一个函数,发送post_data :param ptype: n 列表无歌曲,返回新列表 e 发送歌曲完毕 b 不再播放,返回新列表 s 下一首,返回新的列表 r 标记喜欢 u 取消标记喜欢 """ options = { ...
[ "def", "requests_url", "(", "self", ",", "ptype", ",", "*", "*", "data", ")", ":", "options", "=", "{", "'type'", ":", "ptype", ",", "'pt'", ":", "'3.1'", ",", "'channel'", ":", "self", ".", "_channel_id", ",", "'pb'", ":", "'320'", ",", "'from'", ...
31.815789
0.001605
def set(self, item, value): """ Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items """ # FIXME: refactor, clearly separate broadcasting & zip-like assignment # can prob also fix the various if tests for sparse/c...
[ "def", "set", "(", "self", ",", "item", ",", "value", ")", ":", "# FIXME: refactor, clearly separate broadcasting & zip-like assignment", "# can prob also fix the various if tests for sparse/categorical", "# TODO(EA): Remove an is_extension_ when all extension types satisfy", "# the...
39.868421
0.000429
def fqn(o): """Returns the fully qualified class name of an object or a class :param o: object or class :return: class name >>> import concurrency.fields >>> fqn('str') Traceback (most recent call last): ... ValueError: Invalid argument `str` >>> class A(object): ... def me...
[ "def", "fqn", "(", "o", ")", ":", "parts", "=", "[", "]", "# if inspect.ismethod(o):", "# try:", "# cls = o.im_class", "# except AttributeError:", "# # Python 3 eliminates im_class, substitutes __module__ and", "# # __qualname__ to provide similar inform...
25.021277
0.000818
def make_poll(self, options, expires_in, multiple=False, hide_totals=False): """ Generate a poll object that can be passed as the `poll` option when posting a status. options is an array of strings with the poll options (Maximum, by default: 4), expires_in is the time in seconds...
[ "def", "make_poll", "(", "self", ",", "options", ",", "expires_in", ",", "multiple", "=", "False", ",", "hide_totals", "=", "False", ")", ":", "poll_params", "=", "locals", "(", ")", "del", "poll_params", "[", "\"self\"", "]", "return", "poll_params" ]
51.75
0.012658
def solve_apply(expr, vars): """Returns the result of applying function (lhs) to its arguments (rest). We use IApplicative to apply the function, because that gives the host application an opportunity to compare the function being called against a whitelist. EFILTER will never directly call a function ...
[ "def", "solve_apply", "(", "expr", ",", "vars", ")", ":", "func", "=", "__solve_for_scalar", "(", "expr", ".", "func", ",", "vars", ")", "args", "=", "[", "]", "kwargs", "=", "{", "}", "for", "arg", "in", "expr", ".", "args", ":", "if", "isinstance...
35.8
0.001088
def setup_tables(create=True, drop=False): """ Binds the model classes to registered metadata and engine and (potentially) creates the db tables. This function expects that you have bound the L{meta.metadata} and L{meta.engine}. @param create: Whether to create the tables (if they do not exist). ...
[ "def", "setup_tables", "(", "create", "=", "True", ",", "drop", "=", "False", ")", ":", "global", "frames_table", "frames_table", "=", "Table", "(", "'frames'", ",", "meta", ".", "metadata", ",", "Column", "(", "'message_id'", ",", "String", "(", "255", ...
37
0.002927