text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def experiment(qnum, repetitions=100): """Execute the phase estimator cirquit with multiple settings and show results. """ def example_gate(phi): """An example unitary 1-qubit gate U with an eigen vector |0> and an eigen value exp(2*Pi*i*phi) """ gate = cirq.SingleQubit...
[ "def", "experiment", "(", "qnum", ",", "repetitions", "=", "100", ")", ":", "def", "example_gate", "(", "phi", ")", ":", "\"\"\"An example unitary 1-qubit gate U with an eigen vector |0> and an\n eigen value exp(2*Pi*i*phi)\n \"\"\"", "gate", "=", "cirq", ".", ...
41.185185
0.001757
def _update_rs_with_primary_from_member( sds, replica_set_name, server_description): """RS with known primary. Process a response from a non-primary. Pass in a dict of ServerDescriptions, current replica set name, and the ServerDescription we are processing. Returns new topolog...
[ "def", "_update_rs_with_primary_from_member", "(", "sds", ",", "replica_set_name", ",", "server_description", ")", ":", "assert", "replica_set_name", "is", "not", "None", "if", "replica_set_name", "!=", "server_description", ".", "replica_set_name", ":", "sds", ".", "...
32.571429
0.00142
def set_widgets(self): """Set widgets on the Unit tab.""" self.clear_further_steps() # Set widgets purpose = self.parent.step_kw_purpose.selected_purpose() subcategory = self.parent.step_kw_subcategory.selected_subcategory() self.lblSelectUnit.setText( unit_qu...
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", ".", "selected_purpose", "(", ")", "subcategory", "=", "self", ".", "parent", ".", "ste...
43.305556
0.001255
def close(self): """Add docstring!""" # Seek to the start of the buffer self.seek(0) while True: # Copy bytes from the buffer until we reach the end of the JSON brace_count = 0 quoted = False json_string = '' while True: ...
[ "def", "close", "(", "self", ")", ":", "# Seek to the start of the buffer", "self", ".", "seek", "(", "0", ")", "while", "True", ":", "# Copy bytes from the buffer until we reach the end of the JSON", "brace_count", "=", "0", "quoted", "=", "False", "json_string", "="...
31.185714
0.000888
def connect_patch_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_patch_namespaced_pod_proxy_with_path # noqa: E501 connect PATCH requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an a...
[ "def", "connect_patch_namespaced_pod_proxy_with_path", "(", "self", ",", "name", ",", "namespace", ",", "path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'a...
56.541667
0.001449
def _create_latent_variables(self): """ Creates the model's latent variables Returns ---------- None (changes model attributes) """ # Input layer for unit in range(self.units): self.latent_variables.add_z('Constant | Layer ' + str(1) + ' | Unit ' + s...
[ "def", "_create_latent_variables", "(", "self", ")", ":", "# Input layer", "for", "unit", "in", "range", "(", "self", ".", "units", ")", ":", "self", ".", "latent_variables", ".", "add_z", "(", "'Constant | Layer '", "+", "str", "(", "1", ")", "+", "' | Un...
47.037037
0.011574
def byaxis_out(self): """Object to index along output dimensions. This is only valid for non-trivial `out_shape`. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd(0, 1) >>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2...
[ "def", "byaxis_out", "(", "self", ")", ":", "space", "=", "self", "class", "FspaceByaxisOut", "(", "object", ")", ":", "\"\"\"Helper class for indexing by output axes.\"\"\"", "def", "__getitem__", "(", "self", ",", "indices", ")", ":", "\"\"\"Return ``self[indices]``...
33.047619
0.000933
def get_item_bank_id_metadata(self): """get the metadata for item bank""" metadata = dict(self._item_bank_id_metadata) metadata.update({'existing_id_values': self.my_osid_object_form._my_map['itemBankId']}) return Metadata(**metadata)
[ "def", "get_item_bank_id_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_item_bank_id_metadata", ")", "metadata", ".", "update", "(", "{", "'existing_id_values'", ":", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'item...
52.4
0.011278
def concat_sheets(xl_path: str, sheetnames=None, add_tab_names=False): """ Return a pandas DataFrame with the concat'ed content of the `sheetnames` from the Excel file in `xl_path`. Parameters ---------- xl_path: str Path to the Excel file sheetnames: list of str List of ex...
[ "def", "concat_sheets", "(", "xl_path", ":", "str", ",", "sheetnames", "=", "None", ",", "add_tab_names", "=", "False", ")", ":", "xl_path", ",", "choice", "=", "_check_xl_path", "(", "xl_path", ")", "if", "sheetnames", "is", "None", ":", "sheetnames", "="...
26.176471
0.001083
def update_bgp_speaker(self, bgp_speaker_id, body=None): """Update a BGP speaker.""" return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body)
[ "def", "update_bgp_speaker", "(", "self", ",", "bgp_speaker_id", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "bgp_speaker_path", "%", "bgp_speaker_id", ",", "body", "=", "body", ")" ]
55
0.011976
def getCollectionClass(cls, name) : """Return the class object of a collection given its 'name'""" try : return cls.collectionClasses[name] except KeyError : raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(...
[ "def", "getCollectionClass", "(", "cls", ",", "name", ")", ":", "try", ":", "return", "cls", ".", "collectionClasses", "[", "name", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "\"There is no Collection Class of type: '%s'; currently supported values: [%s]\...
58
0.022663
def from_tuples_dict(pair_dict): '''pair_dict should be a dict mapping tuple (HET code, residue ID) -> (HET code, residue ID) e.g. {('MG ', 'A 204 ') : ('MG ', 'C 221 '), ...}. HET codes and residue IDs should respectively correspond to columns 17:20 and 21:27 of the PDB file. ''' lm ...
[ "def", "from_tuples_dict", "(", "pair_dict", ")", ":", "lm", "=", "LigandMap", "(", ")", "for", "k", ",", "v", "in", "pair_dict", ".", "iteritems", "(", ")", ":", "lm", ".", "add", "(", "k", "[", "0", "]", ",", "k", "[", "1", "]", ",", "v", "...
53.75
0.009153
def _generate_route_signature( self, route, namespace, # pylint: disable=unused-argument route_args, extra_args, doc_list, task_type_name, func_suffix): """Generates route method signature for the given route.""" ...
[ "def", "_generate_route_signature", "(", "self", ",", "route", ",", "namespace", ",", "# pylint: disable=unused-argument", "route_args", ",", "extra_args", ",", "doc_list", ",", "task_type_name", ",", "func_suffix", ")", ":", "for", "name", ",", "_", ",", "typ", ...
39.803571
0.000876
def latlng(arg): """Converts a lat/lon pair to a comma-separated string. For example: sydney = { "lat" : -33.8674869, "lng" : 151.2069902 } convert.latlng(sydney) # '-33.8674869,151.2069902' For convenience, also accepts lat/lon pair as a string, in which case it's re...
[ "def", "latlng", "(", "arg", ")", ":", "if", "is_string", "(", "arg", ")", ":", "return", "arg", "normalized", "=", "normalize_lat_lng", "(", "arg", ")", "return", "\"%s,%s\"", "%", "(", "format_float", "(", "normalized", "[", "0", "]", ")", ",", "form...
23.625
0.001695
def is_identifier_position(rootpath): """Return whether the cursor is in identifier-position in a member declaration.""" if len(rootpath) >= 2 and is_tuple_member_node(rootpath[-2]) and is_identifier(rootpath[-1]): return True if len(rootpath) >= 1 and is_tuple_node(rootpath[-1]): # No deeper node than tu...
[ "def", "is_identifier_position", "(", "rootpath", ")", ":", "if", "len", "(", "rootpath", ")", ">=", "2", "and", "is_tuple_member_node", "(", "rootpath", "[", "-", "2", "]", ")", "and", "is_identifier", "(", "rootpath", "[", "-", "1", "]", ")", ":", "r...
52
0.018913
def dict_diff(dicts): """ Subset dictionaries to keys which map to multiple values """ diff_keys = set() for k in union(set(d.keys()) for d in dicts): values = [] for d in dicts: if k not in d: diff_keys.add(k) break else: ...
[ "def", "dict_diff", "(", "dicts", ")", ":", "diff_keys", "=", "set", "(", ")", "for", "k", "in", "union", "(", "set", "(", "d", ".", "keys", "(", ")", ")", "for", "d", "in", "dicts", ")", ":", "values", "=", "[", "]", "for", "d", "in", "dicts...
25.842105
0.001965
def from_devanagari(self, data): """A convenience method""" from indic_transliteration import sanscript return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name)
[ "def", "from_devanagari", "(", "self", ",", "data", ")", ":", "from", "indic_transliteration", "import", "sanscript", "return", "sanscript", ".", "transliterate", "(", "data", "=", "data", ",", "_from", "=", "sanscript", ".", "DEVANAGARI", ",", "_to", "=", "...
52.25
0.014151
def pw( ctx, key_pattern, user_pattern, mode, strict_flag, user_flag, file, edit_subcommand, gen_subcommand, ): """Search for USER and KEY in GPG-encrypted password file.""" # install silent Ctrl-C handler def handle_sigint(*_): click.echo() ctx.exit(1) ...
[ "def", "pw", "(", "ctx", ",", "key_pattern", ",", "user_pattern", ",", "mode", ",", "strict_flag", ",", "user_flag", ",", "file", ",", "edit_subcommand", ",", "gen_subcommand", ",", ")", ":", "# install silent Ctrl-C handler", "def", "handle_sigint", "(", "*", ...
30.163043
0.001745
def sigma_clipped_stats(data, mask=None, mask_value=None, sigma=3.0, sigma_lower=None, sigma_upper=None, maxiters=5, cenfunc='median', stdfunc='std', std_ddof=0, axis=None): """ Calculate sigma-clipped statistics on the provided data. ...
[ "def", "sigma_clipped_stats", "(", "data", ",", "mask", "=", "None", ",", "mask_value", "=", "None", ",", "sigma", "=", "3.0", ",", "sigma_lower", "=", "None", ",", "sigma_upper", "=", "None", ",", "maxiters", "=", "5", ",", "cenfunc", "=", "'median'", ...
42.627273
0.000208
def unbind(self, callback, event_name = None): """Unbind a callback from an event Params: callback (callable): Callback to unbind event_name (string): If None (default) this callback is removed from every event to which it's bound. If a name is given then it is only removed from tha...
[ "def", "unbind", "(", "self", ",", "callback", ",", "event_name", "=", "None", ")", ":", "if", "event_name", "is", "None", ":", "for", "name", "in", "self", ".", "handlers", ".", "keys", "(", ")", ":", "self", ".", "unbind", "(", "callback", ",", "...
30.555556
0.03351
def apply_default_prefetch(input_source_or_dataflow, trainer): """ Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource """ if not isinstance(input_source_or_dat...
[ "def", "apply_default_prefetch", "(", "input_source_or_dataflow", ",", "trainer", ")", ":", "if", "not", "isinstance", "(", "input_source_or_dataflow", ",", "InputSource", ")", ":", "# to mimic same behavior of the old trainer interface", "if", "type", "(", "trainer", ")"...
36.967742
0.001701
def _symbols(): """(Lazy)load list of all supported symbols (sorted) Look into `_data()` for all currency symbols, then sort by length and unicode-ord (A-Z is not as relevant as ֏). Returns: List[unicode]: Sorted list of possible currency symbols. """ global _SYMBOLS if _SYMBOLS is...
[ "def", "_symbols", "(", ")", ":", "global", "_SYMBOLS", "if", "_SYMBOLS", "is", "None", ":", "tmp", "=", "[", "(", "s", ",", "'symbol'", ")", "for", "s", "in", "_data", "(", ")", "[", "'symbol'", "]", ".", "keys", "(", ")", "]", "tmp", "+=", "[...
32.5
0.001495
def serial_udb_extra_f8_send(self, sue_HEIGHT_TARGET_MAX, sue_HEIGHT_TARGET_MIN, sue_ALT_HOLD_THROTTLE_MIN, sue_ALT_HOLD_THROTTLE_MAX, sue_ALT_HOLD_PITCH_MIN, sue_ALT_HOLD_PITCH_MAX, sue_ALT_HOLD_PITCH_HIGH, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F8: ...
[ "def", "serial_udb_extra_f8_send", "(", "self", ",", "sue_HEIGHT_TARGET_MAX", ",", "sue_HEIGHT_TARGET_MIN", ",", "sue_ALT_HOLD_THROTTLE_MIN", ",", "sue_ALT_HOLD_THROTTLE_MAX", ",", "sue_ALT_HOLD_PITCH_MIN", ",", "sue_ALT_HOLD_PITCH_MAX", ",", "sue_ALT_HOLD_PITCH_HIGH", ",", "fo...
89.928571
0.008648
def sparse_angular_random_projection_split(inds, indptr, data, indices, rng_state): """Given a set of ``indices`` for data points from a sparse data set presented in csr sparse format as inds, indptr and data, create a random hyperplane to split the data, returning two arrays indices that fall on either...
[ "def", "sparse_angular_random_projection_split", "(", "inds", ",", "indptr", ",", "data", ",", "indices", ",", "rng_state", ")", ":", "# Select two random points, set the hyperplane between them", "left_index", "=", "tau_rand_int", "(", "rng_state", ")", "%", "indices", ...
35.582609
0.001902
def localize(self, mode="r", perm=None, parent_perm=None, **kwargs): """ localize(mode="r", perm=None, parent_perm=None, skip_copy=False, is_tmp=None, **kwargs) """ if mode not in ("r", "w"): raise Exception("unknown mode '{}', use r or w".format(mode)) # get additional argu...
[ "def", "localize", "(", "self", ",", "mode", "=", "\"r\"", ",", "perm", "=", "None", ",", "parent_perm", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "not", "in", "(", "\"r\"", ",", "\"w\"", ")", ":", "raise", "Exception", "(", "...
31.87931
0.002099
def _redis_notifier(state): """Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config # Notify timestamp r = re...
[ "def", "_redis_notifier", "(", "state", ")", ":", "tstamp", "=", "time", ".", "time", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "conf", "=", "state", ".", "app", ".", "config", "# Notify timestamp", "r", "=", "redis", ".", "client", ".", "Stric...
28.642857
0.002415
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None): """Start the stream.""" listener...
[ "def", "start", "(", "track_file", ",", "twitter_api_key", ",", "twitter_api_secret", ",", "twitter_access_token", ",", "twitter_access_token_secret", ",", "poll_interval", "=", "15", ",", "unfiltered", "=", "False", ",", "languages", "=", "None", ",", "debug", "=...
31.346154
0.002381
def hash_from_file(filename): """ Compute the fuzzy hash of a file. Opens, reads, and hashes the contents of the file 'filename' :param String|Bytes filename: The name of the file to be hashed :return: The fuzzy hash of the file :rtype: String :raises IOError: If Python is unable to read t...
[ "def", "hash_from_file", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOError", "(", "\"Path not found\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", ...
33.653846
0.001111
def _iana_unassigned_port_ranges(): """ Returns unassigned port ranges according to IANA. """ page = urllib2.urlopen(IANA_DOWNLOAD_URL).read() xml = ElementTree.fromstring(page) records = xml.findall('{%s}record' % IANA_NS) for record in records: description = record.find('{%s}descri...
[ "def", "_iana_unassigned_port_ranges", "(", ")", ":", "page", "=", "urllib2", ".", "urlopen", "(", "IANA_DOWNLOAD_URL", ")", ".", "read", "(", ")", "xml", "=", "ElementTree", ".", "fromstring", "(", "page", ")", "records", "=", "xml", ".", "findall", "(", ...
38.333333
0.002123
def random_shift(image, wsr=0.1, hsr=0.1): """Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction o...
[ "def", "random_shift", "(", "image", ",", "wsr", "=", "0.1", ",", "hsr", "=", "0.1", ")", ":", "height", ",", "width", ",", "_", "=", "common_layers", ".", "shape_list", "(", "image", ")", "width_range", ",", "height_range", "=", "wsr", "*", "width", ...
44.166667
0.009852
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_...
[ "def", "preprocess_input", "(", "features", ",", "target", ",", "train_config", ",", "preprocess_output_dir", ",", "model_type", ")", ":", "target_name", "=", "train_config", "[", "'target_column'", "]", "key_name", "=", "train_config", "[", "'key_column'", "]", "...
40.094737
0.009736
def query_all(self): """ Query all records without limit and offset. """ return self.query_model(self.model, self.condition, order_by=self.order_by, group_by=self.group_by, having=self.having)
[ "def", "query_all", "(", "self", ")", ":", "return", "self", ".", "query_model", "(", "self", ".", "model", ",", "self", ".", "condition", ",", "order_by", "=", "self", ".", "order_by", ",", "group_by", "=", "self", ".", "group_by", ",", "having", "=",...
42.666667
0.011494
def validate_is_document_type(option, value): """Validate the type of method arguments that expect a MongoDB document.""" if not isinstance(value, (collections.MutableMapping, RawBSONDocument)): raise TypeError("%s must be an instance of dict, bson.son.SON, " "bson.raw_bson.RawBS...
[ "def", "validate_is_document_type", "(", "option", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "collections", ".", "MutableMapping", ",", "RawBSONDocument", ")", ")", ":", "raise", "TypeError", "(", "\"%s must be an instance of dict,...
64.142857
0.002198
def set_setpoint(self, setpointvalue): """Set the setpoint. Args: setpointvalue (float): Setpoint [most often in degrees] """ _checkSetpointValue( setpointvalue, self.setpoint_max ) self.write_register( 4097, setpointvalue, 1)
[ "def", "set_setpoint", "(", "self", ",", "setpointvalue", ")", ":", "_checkSetpointValue", "(", "setpointvalue", ",", "self", ".", "setpoint_max", ")", "self", ".", "write_register", "(", "4097", ",", "setpointvalue", ",", "1", ")" ]
32.444444
0.023333
def _infer_decorator_callchain(node): """Detect decorator call chaining and see if the end result is a static or a classmethod. """ if not isinstance(node, FunctionDef): return None if not node.parent: return None try: result = next(node.infer_call_result(node.parent)) ...
[ "def", "_infer_decorator_callchain", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "FunctionDef", ")", ":", "return", "None", "if", "not", "node", ".", "parent", ":", "return", "None", "try", ":", "result", "=", "next", "(", "node",...
33.85
0.001437
def parse_extension_item_param( header: str, pos: int, header_name: str ) -> Tuple[ExtensionParameter, int]: """ Parse a single extension parameter from ``header`` at the given position. Return a ``(name, value)`` pair and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` o...
[ "def", "parse_extension_item_param", "(", "header", ":", "str", ",", "pos", ":", "int", ",", "header_name", ":", "str", ")", "->", "Tuple", "[", "ExtensionParameter", ",", "int", "]", ":", "# Extract parameter name.", "name", ",", "pos", "=", "parse_token", ...
39.6875
0.001537
def pipe(self, f, *args, **kwargs): """Generic composition function to enable expression pipelining. Parameters ---------- f : function or (function, arg_name) tuple If the expression needs to be passed as anything other than the first argument to the function, pass ...
[ "def", "pipe", "(", "self", ",", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "f", ",", "tuple", ")", ":", "f", ",", "data_keyword", "=", "f", "kwargs", "=", "kwargs", ".", "copy", "(", ")", "kwargs", "[", ...
30.566038
0.001196
def get_sphinx_autodoc( self, depth=None, exclude=None, width=72, error=False, raised=False, no_comment=False, ): r""" Return exception list in `reStructuredText`_ auto-determining callable name. :param depth: Hierarchy levels to inclu...
[ "def", "get_sphinx_autodoc", "(", "self", ",", "depth", "=", "None", ",", "exclude", "=", "None", ",", "width", "=", "72", ",", "error", "=", "False", ",", "raised", "=", "False", ",", "no_comment", "=", "False", ",", ")", ":", "# This code is cog-specif...
39.574713
0.001417
def UpdateUserCredentials(client_id, client_secret, refresh_token, adwords_manager_cid, developer_token): """Update the credentials associated with application user. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved f...
[ "def", "UpdateUserCredentials", "(", "client_id", ",", "client_secret", ",", "refresh_token", ",", "adwords_manager_cid", ",", "developer_token", ")", ":", "app_user", "=", "AppUser", ".", "query", "(", "AppUser", ".", "user", "==", "users", ".", "get_current_user...
43.35
0.010158
def relate_obs_ids_to_chosen_alts(obs_id_array, alt_id_array, choice_array): """ Creates a dictionary that relates each unique alternative id to the set of observations ids that chose the given alternative. Parameters ---------- ...
[ "def", "relate_obs_ids_to_chosen_alts", "(", "obs_id_array", ",", "alt_id_array", ",", "choice_array", ")", ":", "# Figure out which units of observation chose each alternative.", "chosen_alts_to_obs_ids", "=", "{", "}", "for", "alt_id", "in", "np", ".", "sort", "(", "np"...
44.651163
0.00051
def extract_mfd_params(src): """ Extracts the MFD parameters from an object """ tags = get_taglist(src) if "incrementalMFD" in tags: mfd_node = src.nodes[tags.index("incrementalMFD")] elif "truncGutenbergRichterMFD" in tags: mfd_node = src.nodes[tags.index("truncGutenbergRichterM...
[ "def", "extract_mfd_params", "(", "src", ")", ":", "tags", "=", "get_taglist", "(", "src", ")", "if", "\"incrementalMFD\"", "in", "tags", ":", "mfd_node", "=", "src", ".", "nodes", "[", "tags", ".", "index", "(", "\"incrementalMFD\"", ")", "]", "elif", "...
42.473684
0.000606
def infer(args: argparse.Namespace) -> None: """ :args: An argparse.Namespace object. This is the function called when the 'infer' sub-command is passed as an argument to the CLI. """ try: last_tag = last_git_release_tag(git_tags()) except NoGitTagsException: print(SemVer(0,...
[ "def", "infer", "(", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "try", ":", "last_tag", "=", "last_git_release_tag", "(", "git_tags", "(", ")", ")", "except", "NoGitTagsException", ":", "print", "(", "SemVer", "(", "0", ",", "1", ...
25.384615
0.00146
def delete(gandi, webacc, vhost, backend, port): """ Delete a webaccelerator, a vhost or a backend """ result = [] if webacc: result = gandi.webacc.delete(webacc) if backend: backends = backend for backend in backends: if 'port' not in backend: if not...
[ "def", "delete", "(", "gandi", ",", "webacc", ",", "vhost", ",", "backend", ",", "port", ")", ":", "result", "=", "[", "]", "if", "webacc", ":", "result", "=", "gandi", ".", "webacc", ".", "delete", "(", "webacc", ")", "if", "backend", ":", "backen...
36.230769
0.001034
def threshold_gradients(self, grad_thresh): """Creates a new DepthImage by zeroing out all depths where the magnitude of the gradient at that point is greater than grad_thresh. Parameters ---------- grad_thresh : float A threshold for the gradient magnitude. ...
[ "def", "threshold_gradients", "(", "self", ",", "grad_thresh", ")", ":", "data", "=", "np", ".", "copy", "(", "self", ".", "_data", ")", "gx", ",", "gy", "=", "self", ".", "gradients", "(", ")", "gradients", "=", "np", ".", "zeros", "(", "[", "gx",...
34.166667
0.002372
def boards(self, startAt=0, maxResults=50, type=None, name=None, projectKeyOrID=None): """Get a list of board resources. :param startAt: The starting index of the returned boards. Base index: 0. :param maxResults: The maximum number of boards to return per page. Default: 50 :param type:...
[ "def", "boards", "(", "self", ",", "startAt", "=", "0", ",", "maxResults", "=", "50", ",", "type", "=", "None", ",", "name", "=", "None", ",", "projectKeyOrID", "=", "None", ")", ":", "params", "=", "{", "}", "if", "type", ":", "params", "[", "'t...
55.451613
0.008576
def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : n...
[ "def", "onepara", "(", "R", ")", ":", "import", "numpy", "as", "np", "import", "warnings", "d", "=", "R", ".", "shape", "[", "0", "]", "if", "d", "<", "2", ":", "raise", "Exception", "(", "(", "\"More than one variable is required.\"", "\"Supply at least a...
23.631579
0.00107
def _update_views_binary(self, result, other, binop): ''' @result: weldarray that is being updated @other: weldarray or scalar. (result binop other) @binop: str, operation to perform. FIXME: the common indexing pattern for parent/child in _update_view might be too expensive ...
[ "def", "_update_views_binary", "(", "self", ",", "result", ",", "other", ",", "binop", ")", ":", "update_str_template", "=", "'{e2}{binop}e'", "v", "=", "result", ".", "_weldarray_view", "if", "isinstance", "(", "other", ",", "weldarray", ")", ":", "lookup_ind...
47.173913
0.009937
def get_suffixes(): """Get a list of all the filename suffixes supported by libvips. Returns: [string] """ names = [] if at_least_libvips(8, 8): array = vips_lib.vips_foreign_get_suffixes() i = 0 while array[i] != ffi.NULL: name = _to_string(array[i]) ...
[ "def", "get_suffixes", "(", ")", ":", "names", "=", "[", "]", "if", "at_least_libvips", "(", "8", ",", "8", ")", ":", "array", "=", "vips_lib", ".", "vips_foreign_get_suffixes", "(", ")", "i", "=", "0", "while", "array", "[", "i", "]", "!=", "ffi", ...
21.5
0.002024
def cookieDomainForRequest(self, request): """ Pick a domain to use when setting cookies. @type request: L{nevow.inevow.IRequest} @param request: Request to determine cookie domain for @rtype: C{str} or C{None} @return: Domain name to use when setting cookies, or C{None...
[ "def", "cookieDomainForRequest", "(", "self", ",", "request", ")", ":", "host", "=", "request", ".", "getHeader", "(", "'host'", ")", "if", "host", "is", "None", ":", "# This is a malformed request that we cannot possibly handle", "# safely, fall back to the default behav...
43.98
0.00089
def _write_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param ...
[ "def", "_write_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "try", ":", "self", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "not", "self", ":", "socket", "=", "_socket_refs", ".", "get", ...
30.037736
0.000608
def plot_multitrack(multitrack, filename=None, mode='separate', track_label='name', preset='default', cmaps=None, xtick='auto', ytick='octave', xticklabel=True, yticklabel='auto', tick_loc=None, tick_direction='in', label='both', grid='both...
[ "def", "plot_multitrack", "(", "multitrack", ",", "filename", "=", "None", ",", "mode", "=", "'separate'", ",", "track_label", "=", "'name'", ",", "preset", "=", "'default'", ",", "cmaps", "=", "None", ",", "xtick", "=", "'auto'", ",", "ytick", "=", "'oc...
43.419643
0.000402
def set_bool_param(params, name, value): """ Set a boolean parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The name of the parameter to set. :param bool value: The value of the parameter. If ``None``, the field will not be set. If ...
[ "def", "set_bool_param", "(", "params", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "if", "value", "is", "True", ":", "params", "[", "name", "]", "=", "'true'", "elif", "value", "is", "False", ":", "params", "[", ...
29.6
0.001309
def find_event(name): """Actually import the event represented by name Raises the `EventNotFoundError` if it's not possible to find the event class refered by `name`. """ try: module, klass = parse_event_name(name) return getattr(import_module(module), klass) except (ImportError...
[ "def", "find_event", "(", "name", ")", ":", "try", ":", "module", ",", "klass", "=", "parse_event_name", "(", "name", ")", "return", "getattr", "(", "import_module", "(", "module", ")", ",", "klass", ")", "except", "(", "ImportError", ",", "AttributeError"...
37.214286
0.001873
def buff(self, target, buff, **kwargs): """ Summon \a buff and apply it to \a target If keyword arguments are given, attempt to set the given values to the buff. Example: player.buff(target, health=random.randint(1, 5)) NOTE: Any Card can buff any other Card. The controller of the Card that buffs the targ...
[ "def", "buff", "(", "self", ",", "target", ",", "buff", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "self", ".", "controller", ".", "card", "(", "buff", ",", "self", ")", "ret", ".", "source", "=", "self", "ret", ".", "apply", "(", "target", ...
33.066667
0.031373
def _get_marX(self, attr_name, default): """ Generalized method to get margin values. """ if self.tcPr is None: return Emu(default) return Emu(int(self.tcPr.get(attr_name, default)))
[ "def", "_get_marX", "(", "self", ",", "attr_name", ",", "default", ")", ":", "if", "self", ".", "tcPr", "is", "None", ":", "return", "Emu", "(", "default", ")", "return", "Emu", "(", "int", "(", "self", ".", "tcPr", ".", "get", "(", "attr_name", ",...
32.571429
0.008547
def create_index(self,*fields): """Create an index on the specified field names An index on a field is a mapping between the values taken by the field and the sorted list of the ids of the records whose field is equal to this value For each indexed field...
[ "def", "create_index", "(", "self", ",", "*", "fields", ")", ":", "reset", "=", "False", "for", "f", "in", "fields", ":", "if", "not", "f", "in", "self", ".", "fields", ":", "raise", "NameError", ",", "\"%s is not a field name %s\"", "%", "(", "f", ","...
42.655172
0.014229
def infer(query, replacements=None, root_type=None, libs=("stdcore", "stdmath")): """Determine the type of the query's output without actually running it. Arguments: query: A query object or string with the query. replacements: Built-time parameters to the query, either as dict or as ...
[ "def", "infer", "(", "query", ",", "replacements", "=", "None", ",", "root_type", "=", "None", ",", "libs", "=", "(", "\"stdcore\"", ",", "\"stdmath\"", ")", ")", ":", "# Always make the scope stack start with stdcore.", "if", "root_type", ":", "type_scope", "="...
37.596154
0.001994
def next_frame_sv2p(): """SV2P model hparams.""" hparams = basic_stochastic.next_frame_basic_stochastic() hparams.optimizer = "true_adam" hparams.learning_rate_schedule = "constant" hparams.learning_rate_constant = 1e-3 hparams.video_num_input_frames = 1 hparams.video_num_target_frames = 3 hparams.batch...
[ "def", "next_frame_sv2p", "(", ")", ":", "hparams", "=", "basic_stochastic", ".", "next_frame_basic_stochastic", "(", ")", "hparams", ".", "optimizer", "=", "\"true_adam\"", "hparams", ".", "learning_rate_schedule", "=", "\"constant\"", "hparams", ".", "learning_rate_...
36.558824
0.02116
def dump_pmean(self, filename): """ Dump parameter means (``fit.pmean``) into file ``filename``. ``fit.dump_pmean(filename)`` saves the means of the best-fit parameter values (``fit.pmean``) from a ``nonlinear_fit`` called ``fit``. These values are recovered using ``p0 = nonline...
[ "def", "dump_pmean", "(", "self", ",", "filename", ")", ":", "warnings", ".", "warn", "(", "\"nonlinear_fit.dump_pmean deprecated; use pickle.dump instead\"", ",", "DeprecationWarning", ",", ")", "with", "open", "(", "filename", ",", "\"wb\"", ")", "as", "f", ":",...
44.25
0.002212
def _update_cov_model(self, strata_to_update='all'): """ strata_to_update : array-like or 'all' array containing stratum indices to update """ if strata_to_update == 'all': strata_to_update = self.strata.indices_ #: Otherwise assume strata_to_update is val...
[ "def", "_update_cov_model", "(", "self", ",", "strata_to_update", "=", "'all'", ")", ":", "if", "strata_to_update", "==", "'all'", ":", "strata_to_update", "=", "self", ".", "strata", ".", "indices_", "#: Otherwise assume strata_to_update is valid (no duplicates etc.)", ...
47.148148
0.021555
def run(self, lines): """Filter method""" ret = [] for line in lines: ret.append(re.sub(r'^#', '#' + ('#' * self.offset), line)) return ret
[ "def", "run", "(", "self", ",", "lines", ")", ":", "ret", "=", "[", "]", "for", "line", "in", "lines", ":", "ret", ".", "append", "(", "re", ".", "sub", "(", "r'^#'", ",", "'#'", "+", "(", "'#'", "*", "self", ".", "offset", ")", ",", "line", ...
25.428571
0.01087
def copy(self, items=None): """Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. >>> from ngram import NGram >>> from ...
[ "def", "copy", "(", "self", ",", "items", "=", "None", ")", ":", "return", "NGram", "(", "items", "if", "items", "is", "not", "None", "else", "self", ",", "self", ".", "threshold", ",", "self", ".", "warp", ",", "self", ".", "_key", ",", "self", ...
36.454545
0.00243
def push(self: BoardT, move: Move) -> None: """ Updates the position with the given move and puts it onto the move stack. >>> import chess >>> >>> board = chess.Board() >>> >>> Nf3 = chess.Move.from_uci("g1f3") >>> board.push(Nf3) # Make the move...
[ "def", "push", "(", "self", ":", "BoardT", ",", "move", ":", "Move", ")", "->", "None", ":", "# Push move and remember board state.", "move", "=", "self", ".", "_to_chess960", "(", "move", ")", "self", ".", "move_stack", ".", "append", "(", "self", ".", ...
37.86087
0.002462
def parse_JSON(self, JSON_string): """ Parses an *NO2Index* instance out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: st...
[ "def", "parse_JSON", "(", "self", ",", "JSON_string", ")", ":", "if", "JSON_string", "is", "None", ":", "raise", "parse_response_error", ".", "ParseResponseError", "(", "'JSON data is None'", ")", "d", "=", "json", ".", "loads", "(", "JSON_string", ")", "try",...
42.243902
0.001693
def write_report(storage_dic, output_file, sample_id): """ Writes a report from multiple samples. Parameters ---------- storage_dic : dict or :py:class:`OrderedDict` Storage containing the trimming statistics. See :py:func:`parse_log` for its generation. output_file : str Pa...
[ "def", "write_report", "(", "storage_dic", ",", "output_file", ",", "sample_id", ")", ":", "with", "open", "(", "output_file", ",", "\"w\"", ")", "as", "fh", ",", "open", "(", "\".report.json\"", ",", "\"w\"", ")", "as", "json_rep", ":", "# Write header", ...
33.545455
0.000658
def init_app(self, app, storage=None, cache=None, file_upload=None): """ Initialize the engine. :param app: The app to use :type app: Object :param storage: The blog storage instance that implements the :type storage: Object :param cache: (Optional) A Flask-Cache...
[ "def", "init_app", "(", "self", ",", "app", ",", "storage", "=", "None", ",", "cache", "=", "None", ",", "file_upload", "=", "None", ")", ":", "self", ".", "app", "=", "app", "self", ".", "config", "=", "self", ".", "app", ".", "config", "self", ...
38.441176
0.001493
def conjugate(self): """Return the conjugate of the operator.""" return Operator( np.conj(self.data), self.input_dims(), self.output_dims())
[ "def", "conjugate", "(", "self", ")", ":", "return", "Operator", "(", "np", ".", "conj", "(", "self", ".", "data", ")", ",", "self", ".", "input_dims", "(", ")", ",", "self", ".", "output_dims", "(", ")", ")" ]
41.25
0.011905
def get(self): """Return current profiler statistics.""" sort = self.get_argument('sort', 'cum_time') count = self.get_argument('count', 20) strip_dirs = self.get_argument('strip_dirs', True) error = '' sorts = ('num_calls', 'cum_time', 'total_time', 'cu...
[ "def", "get", "(", "self", ")", ":", "sort", "=", "self", ".", "get_argument", "(", "'sort'", ",", "'cum_time'", ")", "count", "=", "self", ".", "get_argument", "(", "'count'", ",", "20", ")", "strip_dirs", "=", "self", ".", "get_argument", "(", "'stri...
38.742857
0.002158
def match(license): '''Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.''' if license not in VALID_LICENSES: for l1 in _split_license(license): if l1 in VALID_LICENSES: continue for l2 in _s...
[ "def", "match", "(", "license", ")", ":", "if", "license", "not", "in", "VALID_LICENSES", ":", "for", "l1", "in", "_split_license", "(", "license", ")", ":", "if", "l1", "in", "VALID_LICENSES", ":", "continue", "for", "l2", "in", "_split_license", "(", "...
32.857143
0.002114
def ShowMessage(self, title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000): ''' Shows a balloon above icon in system tray :param title: Title shown in balloon :param message: Message to be displayed :param filename: Optional icon filename ...
[ "def", "ShowMessage", "(", "self", ",", "title", ",", "message", ",", "filename", "=", "None", ",", "data", "=", "None", ",", "data_base64", "=", "None", ",", "messageicon", "=", "None", ",", "time", "=", "10000", ")", ":", "qicon", "=", "None", "if"...
38.028571
0.002198
def get_parameter(self, parameter): "Return a dict for given parameter" parameter = self._get_parameter_name(parameter) return self._parameters[parameter]
[ "def", "get_parameter", "(", "self", ",", "parameter", ")", ":", "parameter", "=", "self", ".", "_get_parameter_name", "(", "parameter", ")", "return", "self", ".", "_parameters", "[", "parameter", "]" ]
43.75
0.011236
def issue(self, issue_instance_id): """Select an issue. Parameters: issue_instance_id: int id of the issue instance to select Note: We are selecting issue instances, even though the command is called issue. """ with self.db.make_session() as session: ...
[ "def", "issue", "(", "self", ",", "issue_instance_id", ")", ":", "with", "self", ".", "db", ".", "make_session", "(", ")", "as", "session", ":", "selected_issue", "=", "(", "session", ".", "query", "(", "IssueInstance", ")", ".", "filter", "(", "IssueIns...
33.674419
0.002013
def get_all(self, cat): """ if data can't found in cache then it will be fetched from db, parsed and stored to cache for each lang_code. :param cat: cat of catalog data :return: """ return self._get_from_local_cache(cat) or self._get_from_cache(cat) or self._get...
[ "def", "get_all", "(", "self", ",", "cat", ")", ":", "return", "self", ".", "_get_from_local_cache", "(", "cat", ")", "or", "self", ".", "_get_from_cache", "(", "cat", ")", "or", "self", ".", "_get_from_db", "(", "cat", ")" ]
36.111111
0.009009
def read_interactions(path, comments="#", directed=False, delimiter=None, nodetype=None, timestamptype=None, encoding='utf-8', keys=False): """Read a DyNetx graph from interaction list format. Parameters ---------- path : basestring The desired output filenam...
[ "def", "read_interactions", "(", "path", ",", "comments", "=", "\"#\"", ",", "directed", "=", "False", ",", "delimiter", "=", "None", ",", "nodetype", "=", "None", ",", "timestamptype", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "keys", "=", "Fal...
34.190476
0.00813
def create_framework( bundles, properties=None, auto_start=False, wait_for_stop=False, auto_delete=False, ): # type: (Union[list, tuple], dict, bool, bool, bool) -> Framework """ Creates a Pelix framework, installs the given bundles and returns its instance reference. If *auto_st...
[ "def", "create_framework", "(", "bundles", ",", "properties", "=", "None", ",", "auto_start", "=", "False", ",", "wait_for_stop", "=", "False", ",", "auto_delete", "=", "False", ",", ")", ":", "# type: (Union[list, tuple], dict, bool, bool, bool) -> Framework", "# Tes...
36.35
0.000446
def _find_detections(cum_net_resp, nodes, threshold, thresh_type, samp_rate, realstations, length): """ Find detections within the cumulative network response. :type cum_net_resp: numpy.ndarray :param cum_net_resp: Array of cumulative network response for nodes :type nodes: lis...
[ "def", "_find_detections", "(", "cum_net_resp", ",", "nodes", ",", "threshold", ",", "thresh_type", ",", "samp_rate", ",", "realstations", ",", "length", ")", ":", "cum_net_resp", "=", "np", ".", "nan_to_num", "(", "cum_net_resp", ")", "# Force no NaNs", "if", ...
43.253968
0.000359
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) ...
[ "def", "send_keys", "(", "self", ",", "keys", ")", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "settimeout", "(", "self", ".", "_timeout", ")", "sock", "."...
38.391304
0.00221
def _ta_plot(self,study,periods=14,column=None,include=True,str='{name}({period})',detail=False, theme=None,sharing=None,filename='',asFigure=False,**iplot_kwargs): """ Generates a Technical Study Chart Parameters: ----------- study : string Technical Study to be charted sma - 'Simple Moving Averag...
[ "def", "_ta_plot", "(", "self", ",", "study", ",", "periods", "=", "14", ",", "column", "=", "None", ",", "include", "=", "True", ",", "str", "=", "'{name}({period})'", ",", "detail", "=", "False", ",", "theme", "=", "None", ",", "sharing", "=", "Non...
29.772727
0.055771
def framers(self, value): """ Set the framers in use for the connection. The framer states will be reset next time their respective framer is used. """ # Handle sequence values if isinstance(value, collections.Sequence): if len(value) != 2: r...
[ "def", "framers", "(", "self", ",", "value", ")", ":", "# Handle sequence values", "if", "isinstance", "(", "value", ",", "collections", ".", "Sequence", ")", ":", "if", "len", "(", "value", ")", "!=", "2", ":", "raise", "ValueError", "(", "'need exactly 2...
38.6
0.002022
def urljoin_safe(base_url, url, allow_fragments=True): '''urljoin with warning log on error. Returns: str, None''' try: return wpull.url.urljoin( base_url, url, allow_fragments=allow_fragments ) except ValueError as error: _logger.warning(__( _('U...
[ "def", "urljoin_safe", "(", "base_url", ",", "url", ",", "allow_fragments", "=", "True", ")", ":", "try", ":", "return", "wpull", ".", "url", ".", "urljoin", "(", "base_url", ",", "url", ",", "allow_fragments", "=", "allow_fragments", ")", "except", "Value...
27.857143
0.002481
def t_EQUAL(self, t): r"\=" t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_EQUAL", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
23.75
0.020408
def exec_command(command, **kwargs): """ Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- * `stderr` (``*`` = None) -- ...
[ "def", "exec_command", "(", "command", ",", "*", "*", "kwargs", ")", ":", "shell", "=", "kwargs", ".", "get", "(", "'shell'", ",", "False", ")", "stdin", "=", "kwargs", ".", "get", "(", "'stdin'", ",", "None", ")", "stdout", "=", "kwargs", ".", "ge...
27.558824
0.001031
def _should_skip_travis_event(on_travis_push, on_travis_pr, on_travis_api, on_travis_cron): """Detect if the upload should be skipped based on the ``TRAVIS_EVENT_TYPE`` environment variable. Returns ------- should_skip : `bool` True if the upload should be skip...
[ "def", "_should_skip_travis_event", "(", "on_travis_push", ",", "on_travis_pr", ",", "on_travis_api", ",", "on_travis_cron", ")", ":", "travis_event", "=", "os", ".", "getenv", "(", "'TRAVIS_EVENT_TYPE'", ")", "if", "travis_event", "is", "None", ":", "raise", "cli...
39.096774
0.000805
def pack_own(self, serializer): """ Same as pack but uses a user-defined serializer function to convert items into longstr. """ return Zframe(lib.zhashx_pack_own(self._as_parameter_, serializer), True)
[ "def", "pack_own", "(", "self", ",", "serializer", ")", ":", "return", "Zframe", "(", "lib", ".", "zhashx_pack_own", "(", "self", ".", "_as_parameter_", ",", "serializer", ")", ",", "True", ")" ]
38
0.017167
def _gauc(ref_lca, est_lca, transitive, window): '''Generalized area under the curve (GAUC) This function computes the normalized recall score for correctly ordering triples ``(q, i, j)`` where frames ``(q, i)`` are closer than ``(q, j)`` in the reference annotation. Parameters ---------- ...
[ "def", "_gauc", "(", "ref_lca", ",", "est_lca", ",", "transitive", ",", "window", ")", ":", "# Make sure we have the right number of frames", "if", "ref_lca", ".", "shape", "!=", "est_lca", ".", "shape", ":", "raise", "ValueError", "(", "'Estimated and reference hie...
30.659341
0.000347
def _match(self, **kwargs): """Method which indicates if the object matches specified criteria. Match accepts criteria as kwargs and looks them up on attributes. Actual matching is performed with fnmatch, so shell-like wildcards work within match strings. Examples: obj._match(A...
[ "def", "_match", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "try", ":", "val", "=", "getattr", "(", "self", ",", "k", ")", "except", "_a11y", ".", "Error", ":", "return", "False", "# ...
39.421053
0.001303
def set_charset(self, charset): """Changes the <meta> charset tag (default charset in init is UTF-8).""" self.head.charset.attr(charset=charset) return self
[ "def", "set_charset", "(", "self", ",", "charset", ")", ":", "self", ".", "head", ".", "charset", ".", "attr", "(", "charset", "=", "charset", ")", "return", "self" ]
44.25
0.016667
def main(): """ Run the CLI. """ parser = argparse.ArgumentParser( description='Search artists, lyrics, and songs!' ) parser.add_argument( 'artist', help='Specify an artist name (Default: Taylor Swift)', default='Taylor Swift', nargs='?', ) parser....
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Search artists, lyrics, and songs!'", ")", "parser", ".", "add_argument", "(", "'artist'", ",", "help", "=", "'Specify an artist name (Default: Taylor Swift)'", ...
24.930233
0.000898
def normalize(self): """ Sum the values in a Counter, then create a new Counter where each new value (while keeping the original key) is equal to the original value divided by sum of all the original values (this is sometimes referred to as the normalization constant). https://en.wikipedia.org/wiki/No...
[ "def", "normalize", "(", "self", ")", ":", "total", "=", "sum", "(", "self", ".", "values", "(", ")", ")", "stats", "=", "{", "k", ":", "(", "v", "/", "float", "(", "total", ")", ")", "for", "k", ",", "v", "in", "self", ".", "items", "(", "...
38
0.036403
def KeyPress(self, key, n=1, delay=0): """Press key for n times. :param key: :param n: press key for n times """ self._delay(delay) cmd = Command("KeyPress", 'KeyPress "%s", %s' % (key, n)) self.add(cmd)
[ "def", "KeyPress", "(", "self", ",", "key", ",", "n", "=", "1", ",", "delay", "=", "0", ")", ":", "self", ".", "_delay", "(", "delay", ")", "cmd", "=", "Command", "(", "\"KeyPress\"", ",", "'KeyPress \"%s\", %s'", "%", "(", "key", ",", "n", ")", ...
28.888889
0.011194
def preprocess(net, image): ''' convert to Caffe input image layout ''' return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
[ "def", "preprocess", "(", "net", ",", "image", ")", ":", "return", "np", ".", "float32", "(", "np", ".", "rollaxis", "(", "image", ",", "2", ")", "[", ":", ":", "-", "1", "]", ")", "-", "net", ".", "transformer", ".", "mean", "[", "\"data\"", "...
32.2
0.012121
def comments_2(self, value=None): """Corresponds to IDD Field `comments_2` Args: value (str): value for IDD Field `comments_2` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
[ "def", "comments_2", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '...
34.826087
0.00243
def set_device_name(self, newname): """ Sets internal device name. (not announced bluetooth name). requires utf-8 encoded string. """ return self.write(request.SetDeviceName(self.seq, *self.prep_str(newname)))
[ "def", "set_device_name", "(", "self", ",", "newname", ")", ":", "return", "self", ".", "write", "(", "request", ".", "SetDeviceName", "(", "self", ".", "seq", ",", "*", "self", ".", "prep_str", "(", "newname", ")", ")", ")" ]
57.5
0.012876
def get_id(opts, cache_minion_id=False): ''' Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ...
[ "def", "get_id", "(", "opts", ",", "cache_minion_id", "=", "False", ")", ":", "if", "opts", "[", "'root_dir'", "]", "is", "None", ":", "root_dir", "=", "salt", ".", "syspaths", ".", "ROOT_DIR", "else", ":", "root_dir", "=", "opts", "[", "'root_dir'", "...
38.294118
0.001123
def PHASE(angle, qubit): """Produces the PHASE gate:: PHASE(phi) = [[1, 0], [0, exp(1j * phi)]] This is the same as the RZ gate. :param angle: The angle to rotate around the z-axis on the bloch sphere. :param qubit: The qubit apply the gate to. :returns: A Gate objec...
[ "def", "PHASE", "(", "angle", ",", "qubit", ")", ":", "return", "Gate", "(", "name", "=", "\"PHASE\"", ",", "params", "=", "[", "angle", "]", ",", "qubits", "=", "[", "unpack_qubit", "(", "qubit", ")", "]", ")" ]
30.307692
0.002463
def follow(self, something, follow=True): """关注用户、问题、话题或收藏夹 :param Author/Question/Topic something: 需要关注的对象 :param bool follow: True-->关注,False-->取消关注 :return: 成功返回True,失败返回False :rtype: bool """ from .question import Question from .topic import Topic ...
[ "def", "follow", "(", "self", ",", "something", ",", "follow", "=", "True", ")", ":", "from", ".", "question", "import", "Question", "from", ".", "topic", "import", "Topic", "from", ".", "collection", "import", "Collection", "if", "isinstance", "(", "somet...
41.26
0.000947
def name(dtype): """Returns the string name for this `dtype`.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'name'): return dtype.name if hasattr(dtype, '__name__'): return dtype.__name__ return str(dtype)
[ "def", "name", "(", "dtype", ")", ":", "dtype", "=", "tf", ".", "as_dtype", "(", "dtype", ")", "if", "hasattr", "(", "dtype", ",", "'name'", ")", ":", "return", "dtype", ".", "name", "if", "hasattr", "(", "dtype", ",", "'__name__'", ")", ":", "retu...
27.25
0.026667
def forwards(apps, schema_editor): """ Change all Movie objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the Movie. """ Movie = apps.get_model('spectator_events', 'Movie') Work = apps.get_model('spectator_events', 'Work') WorkRole = app...
[ "def", "forwards", "(", "apps", ",", "schema_editor", ")", ":", "Movie", "=", "apps", ".", "get_model", "(", "'spectator_events'", ",", "'Movie'", ")", "Work", "=", "apps", ".", "get_model", "(", "'spectator_events'", ",", "'Work'", ")", "WorkRole", "=", "...
30.166667
0.000892
def hook(self, name): """ Return a decorator that attaches a callback to a hook. """ def wrapper(func): self.hooks.add(name, func) return func return wrapper
[ "def", "hook", "(", "self", ",", "name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "self", ".", "hooks", ".", "add", "(", "name", ",", "func", ")", "return", "func", "return", "wrapper" ]
33.333333
0.009756
def INT(cpu, op0): """ Calls to interrupt procedure. The INT n instruction generates a call to the interrupt or exception handler specified with the destination operand. The INT n instruction is the general mnemonic for executing a software-generated call to an interrupt handle...
[ "def", "INT", "(", "cpu", ",", "op0", ")", ":", "if", "op0", ".", "read", "(", ")", "!=", "0x80", ":", "logger", ".", "warning", "(", "\"Unsupported interrupt\"", ")", "raise", "Interruption", "(", "op0", ".", "read", "(", ")", ")" ]
45.941176
0.008783