text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_levels(version=None): '''get_levels returns a dictionary of levels (key) and values (dictionaries with descriptions and regular expressions for files) for the user. :param version: the version of singularity to use (default is 2.2) :param include_files: files to add to the level, only relvant i...
[ "def", "get_levels", "(", "version", "=", "None", ")", ":", "valid_versions", "=", "[", "'2.3'", ",", "'2.2'", "]", "if", "version", "is", "None", ":", "version", "=", "\"2.3\"", "version", "=", "str", "(", "version", ")", "if", "version", "not", "in",...
40.344828
25.37931
def __get_oauth_url(self, url, method, **kwargs): """ Generate oAuth1.0a URL """ oauth = OAuth( url=url, consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, version=self.version, method=method, oauth_timestamp=kwar...
[ "def", "__get_oauth_url", "(", "self", ",", "url", ",", "method", ",", "*", "*", "kwargs", ")", ":", "oauth", "=", "OAuth", "(", "url", "=", "url", ",", "consumer_key", "=", "self", ".", "consumer_key", ",", "consumer_secret", "=", "self", ".", "consum...
32.916667
15.416667
def properties(self, value): """The properties property. Args: value (hash). the property value. """ if value == self._defaults['properties'] and 'properties' in self._values: del self._values['properties'] else: self._values['properti...
[ "def", "properties", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'properties'", "]", "and", "'properties'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'properties'", "]", "else", ...
32.3
15.3
def _create_worker(self, worker): """Common worker setup.""" worker.sig_started.connect(self._start) self._workers.append(worker)
[ "def", "_create_worker", "(", "self", ",", "worker", ")", ":", "worker", ".", "sig_started", ".", "connect", "(", "self", ".", "_start", ")", "self", ".", "_workers", ".", "append", "(", "worker", ")" ]
37.5
4.5
def version(command='dmenu'): '''The dmenu command's version message. Raises: DmenuCommandError Example: >>> import dmenu >>> dmenu.version() 'dmenu-4.5, \xc2\xa9 2006-2012 dmenu engineers, see LICENSE for details' ''' args = [command, '-v'] try: # st...
[ "def", "version", "(", "command", "=", "'dmenu'", ")", ":", "args", "=", "[", "command", ",", "'-v'", "]", "try", ":", "# start the dmenu process", "proc", "=", "subprocess", ".", "Popen", "(", "args", ",", "universal_newlines", "=", "True", ",", "stdout",...
24.6875
20.375
def clear_caches(): """Jinja2 keeps internal caches for environments and lexers. These are used so that Jinja2 doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. """...
[ "def", "clear_caches", "(", ")", ":", "from", "jinja2", ".", "environment", "import", "_spontaneous_environments", "from", "jinja2", ".", "lexer", "import", "_lexer_cache", "_spontaneous_environments", ".", "clear", "(", ")", "_lexer_cache", ".", "clear", "(", ")"...
47.7
15.5
def _update_partition_in_create(self, tenant_id, tenant_name): """Function to update a partition. """ in_subnet_dict = self.get_in_ip_addr(tenant_id) # self._update_partition(tenant_name, in_ip) # Need more generic thinking on this one TODO(padkrish) next_hop = str(netaddr.IPAdd...
[ "def", "_update_partition_in_create", "(", "self", ",", "tenant_id", ",", "tenant_name", ")", ":", "in_subnet_dict", "=", "self", ".", "get_in_ip_addr", "(", "tenant_id", ")", "# self._update_partition(tenant_name, in_ip)", "# Need more generic thinking on this one TODO(padkris...
60
19
def arg_to_array(func): """ Decorator to convert argument to array. Parameters ---------- func : function The function to decorate. Returns ------- func : function The decorated function. """ def fn(self, arg, *args, **kwargs): """Function Param...
[ "def", "arg_to_array", "(", "func", ")", ":", "def", "fn", "(", "self", ",", "arg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Function\n\n Parameters\n ----------\n arg : array-like\n Argument to convert.\n *args : tu...
19.878788
18.121212
def nvrtcGetPTX(self, prog): """ Returns the compiled PTX for the NVRTC program object. """ size = c_size_t() code = self._lib.nvrtcGetPTXSize(prog, byref(size)) self._throw_on_error(code) buf = create_string_buffer(size.value) code = self._lib.nvrtcGetPT...
[ "def", "nvrtcGetPTX", "(", "self", ",", "prog", ")", ":", "size", "=", "c_size_t", "(", ")", "code", "=", "self", ".", "_lib", ".", "nvrtcGetPTXSize", "(", "prog", ",", "byref", "(", "size", ")", ")", "self", ".", "_throw_on_error", "(", "code", ")",...
30.538462
13.307692
def set_historylog(self, historylog): """Bind historylog instance to this console Not used anymore since v2.0""" historylog.add_history(self.shell.history_filename) self.shell.append_to_history.connect(historylog.append_to_history)
[ "def", "set_historylog", "(", "self", ",", "historylog", ")", ":", "historylog", ".", "add_history", "(", "self", ".", "shell", ".", "history_filename", ")", "self", ".", "shell", ".", "append_to_history", ".", "connect", "(", "historylog", ".", "append_to_his...
52.6
11.2
def read(self, filepath): """Read the metadata values from a file path.""" fp = codecs.open(filepath, 'r', encoding='utf-8') try: self.read_file(fp) finally: fp.close()
[ "def", "read", "(", "self", ",", "filepath", ")", ":", "fp", "=", "codecs", ".", "open", "(", "filepath", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "self", ".", "read_file", "(", "fp", ")", "finally", ":", "fp", ".", "close", ...
31.142857
16
def _set_mip_policy(self, v, load=False): """ Setter method for mip_policy, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mip_policy (mip-policy-type) If this variable is read-only (config: false) in the source YANG file, then _set_mip_policy is considered as a private ...
[ "def", "_set_mip_policy", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "bas...
98
47.272727
def getScalarNames(self, parentFieldName=''): """ Return the field names for each of the scalar values returned by getScalars. :param parentFieldName: The name of the encoder which is our parent. This name is prefixed to each of the field names within this encoder to form the keys of th...
[ "def", "getScalarNames", "(", "self", ",", "parentFieldName", "=", "''", ")", ":", "names", "=", "[", "]", "if", "self", ".", "encoders", "is", "not", "None", ":", "for", "(", "name", ",", "encoder", ",", "offset", ")", "in", "self", ".", "encoders",...
31.230769
20.461538
def health(self, **kwargs): ''' Support `node`, `service`, `check`, `state` ''' if not len(kwargs): raise ValueError('no resource provided') for resource, name in kwargs.iteritems(): endpoint = 'health/{}/{}'.format(resource, name) return self._get...
[ "def", "health", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "len", "(", "kwargs", ")", ":", "raise", "ValueError", "(", "'no resource provided'", ")", "for", "resource", ",", "name", "in", "kwargs", ".", "iteritems", "(", ")", ":", ...
35.777778
15.777778
def set_credentials(self, client_id=None, client_secret=None): """ set given credentials and reset the session """ self._client_id = client_id self._client_secret = client_secret # make sure to reset session due to credential change self._session = None
[ "def", "set_credentials", "(", "self", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ")", ":", "self", ".", "_client_id", "=", "client_id", "self", ".", "_client_secret", "=", "client_secret", "# make sure to reset session due to credential change"...
33.555556
12.666667
def hash_data(salt, value): """ Hashes a value together with a salt. :type salt: str :type value: str :param salt: hash salt :param value: value to hash together with the salt :return: hash value (SHA512) """ msg = "UserIdHasher is deprecated; use ...
[ "def", "hash_data", "(", "salt", ",", "value", ")", ":", "msg", "=", "\"UserIdHasher is deprecated; use satosa.util.hash_data instead.\"", "_warnings", ".", "warn", "(", "msg", ",", "DeprecationWarning", ")", "return", "util", ".", "hash_data", "(", "salt", ",", "...
35.916667
10.75
def _set_distance(self, v, load=False): """ Setter method for distance, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/qsfpp/distance (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_distance is considered as a private...
[ "def", "_set_distance", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base"...
94.454545
45.909091
def set_language(self, request, org): """Set the current language from the org configuration.""" if org: lang = org.language or settings.DEFAULT_LANGUAGE translation.activate(lang)
[ "def", "set_language", "(", "self", ",", "request", ",", "org", ")", ":", "if", "org", ":", "lang", "=", "org", ".", "language", "or", "settings", ".", "DEFAULT_LANGUAGE", "translation", ".", "activate", "(", "lang", ")" ]
43.2
10
def _find_by_id(self, resource, _id, parent=None): """Find the document by Id. If parent is not provided then on routing exception try to find using search. """ def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('fou...
[ "def", "_find_by_id", "(", "self", ",", "resource", ",", "_id", ",", "parent", "=", "None", ")", ":", "def", "is_found", "(", "hit", ")", ":", "if", "'exists'", "in", "hit", ":", "hit", "[", "'found'", "]", "=", "hit", "[", "'exists'", "]", "return...
37.108108
17.108108
def list_snapshots(config='root'): ''' List available snapshots CLI example: .. code-block:: bash salt '*' snapper.list_snapshots config=myconfig ''' try: snapshots = snapper.ListSnapshots(config) return [_snapshot_to_data(s) for s in snapshots] except dbus.DBusExc...
[ "def", "list_snapshots", "(", "config", "=", "'root'", ")", ":", "try", ":", "snapshots", "=", "snapper", ".", "ListSnapshots", "(", "config", ")", "return", "[", "_snapshot_to_data", "(", "s", ")", "for", "s", "in", "snapshots", "]", "except", "dbus", "...
27.055556
21.944444
def should_log(self, request, response): """ Method that should return a value that evaluated to True if the request should be logged. By default, check if the request method is in logging_methods. """ return self.logging_methods == '__all__' or request.method in self.logging_met...
[ "def", "should_log", "(", "self", ",", "request", ",", "response", ")", ":", "return", "self", ".", "logging_methods", "==", "'__all__'", "or", "request", ".", "method", "in", "self", ".", "logging_methods" ]
53.166667
22.833333
def close(self): """ Terminate the agent, clean the files, close connections Should be called manually """ os.remove(self._file) os.rmdir(self._dir) self.thread._exit = True self.thread.join(1000) self._close()
[ "def", "close", "(", "self", ")", ":", "os", ".", "remove", "(", "self", ".", "_file", ")", "os", ".", "rmdir", "(", "self", ".", "_dir", ")", "self", ".", "thread", ".", "_exit", "=", "True", "self", ".", "thread", ".", "join", "(", "1000", ")...
27.3
11.5
def Winterfeld_Scriven_Davis(xs, sigmas, rhoms): r'''Calculates surface tension of a liquid mixture according to mixing rules in [1]_ and also in [2]_. .. math:: \sigma_M = \sum_i \sum_j \frac{1}{V_L^{L2}}\left(x_i V_i \right) \left( x_jV_j\right)\sqrt{\sigma_i\cdot \sigma_j} Parameter...
[ "def", "Winterfeld_Scriven_Davis", "(", "xs", ",", "sigmas", ",", "rhoms", ")", ":", "if", "not", "none_and_length_check", "(", "[", "xs", ",", "sigmas", ",", "rhoms", "]", ")", ":", "raise", "Exception", "(", "'Function inputs are incorrect format'", ")", "rh...
36.762712
25.745763
def deprecated(instructions): """ Flags a method as deprecated. :param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.' :return: DeprecatedWarning """ def decorator(func): """This is a decorator which can be used to mark functions as ...
[ "def", "deprecated", "(", "instructions", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"This is a decorator which can be used to mark functions as deprecated.\n\n It will result in a warning being emitted when the function is used.\n \"\"\"", "@", "functools",...
41.791667
18.625
def createNew(cls, store, pathSegments): """ Create a new SubStore, allocating a new file space for it. """ if isinstance(pathSegments, basestring): raise ValueError( 'Received %r instead of a sequence' % (pathSegments,)) if store.dbdir is None: ...
[ "def", "createNew", "(", "cls", ",", "store", ",", "pathSegments", ")", ":", "if", "isinstance", "(", "pathSegments", ",", "basestring", ")", ":", "raise", "ValueError", "(", "'Received %r instead of a sequence'", "%", "(", "pathSegments", ",", ")", ")", "if",...
36.066667
14.466667
def stop_instances(self, instance_ids=None, force=False): """ Stop the instances specified :type instance_ids: list :param instance_ids: A list of strings of the Instance IDs to stop :type force: bool :param force: Forces the instance to stop :rtype: list ...
[ "def", "stop_instances", "(", "self", ",", "instance_ids", "=", "None", ",", "force", "=", "False", ")", ":", "params", "=", "{", "}", "if", "force", ":", "params", "[", "'Force'", "]", "=", "'true'", "if", "instance_ids", ":", "self", ".", "build_list...
32.25
18.25
def open_interface_async(self, conn_id, interface, callback, connection_string=None): """Asynchronously connect to a device.""" future = self._loop.launch_coroutine(self._adapter.open_interface(conn_id, interface)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
[ "def", "open_interface_async", "(", "self", ",", "conn_id", ",", "interface", ",", "callback", ",", "connection_string", "=", "None", ")", ":", "future", "=", "self", ".", "_loop", ".", "launch_coroutine", "(", "self", ".", "_adapter", ".", "open_interface", ...
63
37.2
def angular_distance(km, lat, lat2=None): """ Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179' """ if lat2 is not None: # use the largest latitude to compute the...
[ "def", "angular_distance", "(", "km", ",", "lat", ",", "lat2", "=", "None", ")", ":", "if", "lat2", "is", "not", "None", ":", "# use the largest latitude to compute the angular distance", "lat", "=", "max", "(", "abs", "(", "lat", ")", ",", "abs", "(", "la...
32.846154
15.769231
def _loc_to_file_path(self, path, environ=None): """Convert resource path to a unicode absolute file path. Optional environ argument may be useful e.g. in relation to per-user sub-folder chrooting inside root_folder_path. """ root_path = self.root_folder_path assert root_...
[ "def", "_loc_to_file_path", "(", "self", ",", "path", ",", "environ", "=", "None", ")", ":", "root_path", "=", "self", ".", "root_folder_path", "assert", "root_path", "is", "not", "None", "assert", "compat", ".", "is_native", "(", "root_path", ")", "assert",...
38.727273
15.727273
def V_multiple_hole_cylinder(Do, L, holes): r'''Returns the solid volume of a cylinder with multiple cylindrical holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. .. math:: V = \frac{\pi D_o^2}{4}L - L\f...
[ "def", "V_multiple_hole_cylinder", "(", "Do", ",", "L", ",", "holes", ")", ":", "V", "=", "pi", "*", "Do", "**", "2", "/", "4", "*", "L", "for", "Di", ",", "n", "in", "holes", ":", "V", "-=", "pi", "*", "Di", "**", "2", "/", "4", "*", "L", ...
26.53125
25.03125
def handle(cls, vm, args): """ Setup forwarding connection to given VM and pipe docker cmds over SSH. """ docker = Iaas.info(vm) if not docker: raise Exception('docker vm %s not found' % vm) if docker['state'] != 'running': Iaas.start(vm) ...
[ "def", "handle", "(", "cls", ",", "vm", ",", "args", ")", ":", "docker", "=", "Iaas", ".", "info", "(", "vm", ")", "if", "not", "docker", ":", "raise", "Exception", "(", "'docker vm %s not found'", "%", "vm", ")", "if", "docker", "[", "'state'", "]",...
31.25
22.45
def slow_augmenting_row_reduction(n, ii, jj, idx, count, x, y, u, v, c): '''Perform the augmenting row reduction step from the Jonker-Volgenaut algorithm n - the number of i and j in the linear assignment problem ii - the unassigned i jj - the j-index of every entry in c idx - the index of the ...
[ "def", "slow_augmenting_row_reduction", "(", "n", ",", "ii", ",", "jj", ",", "idx", ",", "count", ",", "x", ",", "y", ",", "u", ",", "v", ",", "c", ")", ":", "#######################################", "#", "# From Jonker:", "#", "# procedure AUGMENTING ROW RED...
31.5
18.375
def list_repos(self, envs=[], query='/repositories/'): """ List repositories in specified environments """ juicer.utils.Log.log_debug( "List Repos In: %s", ", ".join(envs)) repo_lists = {} for env in envs: repo_lists[env] = [] for env...
[ "def", "list_repos", "(", "self", ",", "envs", "=", "[", "]", ",", "query", "=", "'/repositories/'", ")", ":", "juicer", ".", "utils", ".", "Log", ".", "log_debug", "(", "\"List Repos In: %s\"", ",", "\", \"", ".", "join", "(", "envs", ")", ")", "repo_...
35.1
16.3
def request(self, request): """ Sets the request of this V1beta1CertificateSigningRequestSpec. Base64-encoded PKCS#10 CSR data :param request: The request of this V1beta1CertificateSigningRequestSpec. :type: str """ if request is None: raise ValueErro...
[ "def", "request", "(", "self", ",", "request", ")", ":", "if", "request", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `request`, must not be `None`\"", ")", "if", "request", "is", "not", "None", "and", "not", "re", ".", "search", "(", ...
49.428571
33.285714
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
[ "def", "_bucket_boundaries", "(", "max_length", ",", "min_length", "=", "8", ",", "length_bucket_step", "=", "1.1", ")", ":", "assert", "length_bucket_step", ">", "1.0", "x", "=", "min_length", "boundaries", "=", "[", "]", "while", "x", "<", "max_length", ":...
33.555556
16.444444
def is_at_exit(): """ Some heuristics to figure out whether this is called at a stage where the Python interpreter is shutting down. :return: whether the Python interpreter is currently in the process of shutting down :rtype: bool """ if _threading_main_thread is not None: if not hasatt...
[ "def", "is_at_exit", "(", ")", ":", "if", "_threading_main_thread", "is", "not", "None", ":", "if", "not", "hasattr", "(", "threading", ",", "\"main_thread\"", ")", ":", "return", "True", "if", "threading", ".", "main_thread", "(", ")", "!=", "_threading_mai...
35.666667
21.666667
def from_object(cls, o, base_uri=None, parent_curies=None, draft=AUTO): """Returns a new ``Document`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON for the new ``Document``, or a ``list`` of such documents. - ``base_u...
[ "def", "from_object", "(", "cls", ",", "o", ",", "base_uri", "=", "None", ",", "parent_curies", "=", "None", ",", "draft", "=", "AUTO", ")", ":", "if", "isinstance", "(", "o", ",", "list", ")", ":", "return", "[", "cls", ".", "from_object", "(", "x...
45.791667
26
def uri(self, value): """Attempt to validate URI and split into individual values""" if value == self.__uri: return match = URI_REGEX.match(value) if match is None: raise ValueError('Unable to match URI from `{}`'.format(value)) for key, value in match.g...
[ "def", "uri", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "__uri", ":", "return", "match", "=", "URI_REGEX", ".", "match", "(", "value", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "'Unable to match URI...
33.363636
17.909091
def build_iters(data_dir, max_records, q, horizon, splits, batch_size): """ Load & generate training examples from multivariate time series data :return: data iters & variables required to define network architecture """ # Read in data as numpy array df = pd.read_csv(os.path.join(data_dir, "elec...
[ "def", "build_iters", "(", "data_dir", ",", "max_records", ",", "q", ",", "horizon", ",", "splits", ",", "batch_size", ")", ":", "# Read in data as numpy array", "df", "=", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", ...
42.913043
16.173913
def _run(self, keep_successfull): """Interpret the parsed 010 AST :returns: PfpDom """ # example self._ast.show(): # FileAST: # Decl: data, [], [], [] # TypeDecl: data, [] # Struct: DATA # Decl: a, [], [], [] ...
[ "def", "_run", "(", "self", ",", "keep_successfull", ")", ":", "# example self._ast.show():", "# FileAST:", "# Decl: data, [], [], []", "# TypeDecl: data, []", "# Struct: DATA", "# Decl: a, [], [], []", "# TypeDecl: a, []", "# ...
34.508197
15.196721
def from_api_repr(cls, api_repr): """Return a :class:`TimePartitioning` object deserialized from a dict. This method creates a new ``TimePartitioning`` instance that points to the ``api_repr`` parameter as its internal properties dict. This means that when a ``TimePartitioning`` instanc...
[ "def", "from_api_repr", "(", "cls", ",", "api_repr", ")", ":", "instance", "=", "cls", "(", "api_repr", "[", "\"type\"", "]", ")", "instance", ".", "_properties", "=", "api_repr", "return", "instance" ]
40.37037
20.703704
def installFunc(target, source, env): """Install a source file into a target using the function specified as the INSTALL construction variable.""" try: install = env['INSTALL'] except KeyError: raise SCons.Errors.UserError('Missing INSTALL construction variable.') assert len(target)...
[ "def", "installFunc", "(", "target", ",", "source", ",", "env", ")", ":", "try", ":", "install", "=", "env", "[", "'INSTALL'", "]", "except", "KeyError", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Missing INSTALL construction variable.'", ...
39.266667
23.466667
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archi...
[ "def", "create_archive", "(", "source", ":", "Path", ",", "target", ":", "Path", ",", "interpreter", ":", "str", ",", "main", ":", "str", ",", "compressed", ":", "bool", "=", "True", ")", "->", "None", ":", "# Check that main has the right format.", "mod", ...
32.043478
21.043478
def update_group(self, group_id, new_name): """ Update the name of a group :type group_id: int :param group_id: group ID number :type new_name: str :param new_name: New name for the group :rtype: dict :return: a dictionary containing group information ...
[ "def", "update_group", "(", "self", ",", "group_id", ",", "new_name", ")", ":", "data", "=", "{", "'id'", ":", "group_id", ",", "'name'", ":", "new_name", ",", "}", "try", ":", "response", "=", "self", ".", "post", "(", "'updateGroup'", ",", "data", ...
27.423077
18.423077
def paginate(self, request, offset=0, limit=None): """Paginate queryset.""" return self.collection.offset(offset).limit(limit), self.collection.count()
[ "def", "paginate", "(", "self", ",", "request", ",", "offset", "=", "0", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "collection", ".", "offset", "(", "offset", ")", ".", "limit", "(", "limit", ")", ",", "self", ".", "collection", "...
55
17.666667
def run_command( host, command, username=None, key_path=None, noisy=True ): """ Run a command via SSH, proxied through the mesos master :param host: host or IP of the machine to execute the command on :type host: str :param command: the command to exe...
[ "def", "run_command", "(", "host", ",", "command", ",", "username", "=", "None", ",", "key_path", "=", "None", ",", "noisy", "=", "True", ")", ":", "with", "HostSession", "(", "host", ",", "username", ",", "key_path", ",", "noisy", ")", "as", "s", ":...
29.6
20
def set(self, uuid, content, encoding="utf-8"): # type: (UUID, Any, Optional[Text]) -> None """Store binary content with uuid as key. :param:uuid: :class:`UUID` instance :param:content: string, bytes, or any object with a `read()` method :param:encoding: encoding to use when con...
[ "def", "set", "(", "self", ",", "uuid", ",", "content", ",", "encoding", "=", "\"utf-8\"", ")", ":", "# type: (UUID, Any, Optional[Text]) -> None", "dest", "=", "self", ".", "abs_path", "(", "uuid", ")", "if", "not", "dest", ".", "parent", ".", "exists", "...
32.818182
15.636364
def cast_to_swimlane(self, value): """Restore swimlane format, attempting to keep initial IDs for any previously existing values""" value = super(ListField, self).cast_to_swimlane(value) if not value: return None # Copy initial values to pop IDs out as each value is hydrate...
[ "def", "cast_to_swimlane", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "ListField", ",", "self", ")", ".", "cast_to_swimlane", "(", "value", ")", "if", "not", "value", ":", "return", "None", "# Copy initial values to pop IDs out as each valu...
48.25
29.916667
def parse_args(self, args=None): """Parse the given arguments All commands should support executing a function, so you can use the arg Namespace like this:: launcher = Launcher() args, unknown = launcher.parse_args() args.func(args, unknown) # execute the command ...
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "return", "self", ".", "parser", ".", "parse_known_args", "(", "args", ")" ]
31.631579
15.578947
def copy_endpoint_with_new_service_name(endpoint, service_name): """Copies a copy of a given endpoint with a new service name. This should be very fast, on the order of several microseconds. :param endpoint: existing zipkin_core.Endpoint object :param service_name: str of new service name :returns:...
[ "def", "copy_endpoint_with_new_service_name", "(", "endpoint", ",", "service_name", ")", ":", "return", "zipkin_core", ".", "Endpoint", "(", "ipv4", "=", "endpoint", ".", "ipv4", ",", "port", "=", "endpoint", ".", "port", ",", "service_name", "=", "service_name"...
36.076923
15
def copy_style(shapefile_path): """Copy style from the OSM resource directory to the output path. .. versionadded: 3.3 :param shapefile_path: Path to the shapefile that should get the path added. :type shapefile_path: basestring """ source_qml_path = resourc...
[ "def", "copy_style", "(", "shapefile_path", ")", ":", "source_qml_path", "=", "resources_path", "(", "'petabencana'", ",", "'flood-style.qml'", ")", "output_qml_path", "=", "shapefile_path", ".", "replace", "(", "'shp'", ",", "'qml'", ")", "LOGGER", ".", "info", ...
39.923077
18.538462
def from_output_script(output_script, cashaddr=True): ''' bytes -> str Convert output script (the on-chain format) to an address There's probably a better way to do this ''' try: if (len(output_script) == len(riemann.network.P2WSH_PREFIX) + 32 and output_script.find(riema...
[ "def", "from_output_script", "(", "output_script", ",", "cashaddr", "=", "True", ")", ":", "try", ":", "if", "(", "len", "(", "output_script", ")", "==", "len", "(", "riemann", ".", "network", ".", "P2WSH_PREFIX", ")", "+", "32", "and", "output_script", ...
39.78125
23.90625
def mousePressEvent(self, event): """saves the drag position, so we know when a drag should be initiated""" super(AbstractDragView, self).mousePressEvent(event) self.dragStartPosition = event.pos()
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "super", "(", "AbstractDragView", ",", "self", ")", ".", "mousePressEvent", "(", "event", ")", "self", ".", "dragStartPosition", "=", "event", ".", "pos", "(", ")" ]
54.5
7.75
def require(packages): """Ensures that a pypi package has been installed into the App's python environment. If not, the package will be installed and your env will be rebooted. Example: :: lore.env.require('pandas') # -> pandas is required. Dependencies added to requirement...
[ "def", "require", "(", "packages", ")", ":", "global", "INSTALLED_PACKAGES", ",", "_new_requirements", "if", "_new_requirements", ":", "INSTALLED_PACKAGES", "=", "None", "set_installed_packages", "(", ")", "if", "not", "INSTALLED_PACKAGES", ":", "return", "if", "not...
31.190476
20.833333
def predict_next_action(self, state_key, next_action_list): ''' Predict next action by Q-Learning. Args: state_key: The key of state in `self.t+1`. next_action_list: The possible action in `self.t+1`. Returns: The key of action. '...
[ "def", "predict_next_action", "(", "self", ",", "state_key", ",", "next_action_list", ")", ":", "if", "self", ".", "q_df", "is", "not", "None", ":", "next_action_q_df", "=", "self", ".", "q_df", "[", "self", ".", "q_df", ".", "state_key", "==", "state_key"...
40.538462
25.153846
def get_image_id(kwargs=None, call=None): ''' Returns an image's ID from the given image name. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f get_image_id opennebula name=my-image-name ''' if call == 'action': raise SaltCloudSystemExit( ...
[ "def", "get_image_id", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The get_image_id function must be called with -f or --function.'", ")", "if", "kwargs", "is", "None", ...
22.588235
24.058824
def _default_make_pool(http, proxy_info): """Creates a urllib3.PoolManager object that has SSL verification enabled and uses the certifi certificates.""" if not http.ca_certs: http.ca_certs = _certifi_where_for_ssl_version() ssl_disabled = http.disable_ssl_certificate_validation cert_reqs...
[ "def", "_default_make_pool", "(", "http", ",", "proxy_info", ")", ":", "if", "not", "http", ".", "ca_certs", ":", "http", ".", "ca_certs", "=", "_certifi_where_for_ssl_version", "(", ")", "ssl_disabled", "=", "http", ".", "disable_ssl_certificate_validation", "cer...
34.375
18.725
def daily(self, symbol=None): ''' 获取日线数据 :param symbol: :return: pd.dataFrame or None ''' reader = TdxDailyBarReader() vipdoc = self.find_path(symbol=symbol, subdir='lday', ext='day') if vipdoc is not None: return reader.get_df(vipdoc) ...
[ "def", "daily", "(", "self", ",", "symbol", "=", "None", ")", ":", "reader", "=", "TdxDailyBarReader", "(", ")", "vipdoc", "=", "self", ".", "find_path", "(", "symbol", "=", "symbol", ",", "subdir", "=", "'lday'", ",", "ext", "=", "'day'", ")", "if",...
22.928571
21.642857
def restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None): """Restore descriptor from SQL """ # Fields fields = [] for column in columns: if column.name == autoincrement_column: continue field_type = self.re...
[ "def", "restore_descriptor", "(", "self", ",", "table_name", ",", "columns", ",", "constraints", ",", "autoincrement_column", "=", "None", ")", ":", "# Fields", "fields", "=", "[", "]", "for", "column", "in", "columns", ":", "if", "column", ".", "name", "=...
38.017857
17.464286
def trace(): """ trace finds the line, the filename and error message and returns it to the user """ import traceback import sys tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # script name + line number line = tbinfo.split(", ")[1] # Get Python sy...
[ "def", "trace", "(", ")", ":", "import", "traceback", "import", "sys", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "tbinfo", "=", "traceback", ".", "format_tb", "(", "tb", ")", "[", "0", "]", "# script name + line number", "line", "=", ...
25.75
12.125
def f_ratios(calON_obs,calOFF_obs,chan_per_coarse,**kwargs): ''' Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3 Parameters ---------- calON_obs : str Path to filterbank file (any format) for observation ON the calibrator source calOFF_obs : str ...
[ "def", "f_ratios", "(", "calON_obs", ",", "calOFF_obs", ",", "chan_per_coarse", ",", "*", "*", "kwargs", ")", ":", "#Calculate noise diode ON and noise diode OFF spectra (H and L) for both observations", "L_ON", ",", "H_ON", "=", "integrate_calib", "(", "calON_obs", ",", ...
36.421053
31.157895
def writetofastq(data, dsort, read): """ Writes sorted data 'dsort dict' to a tmp files """ if read == 1: rrr = "R1" else: rrr = "R2" for sname in dsort: ## skip writing if empty. Write to tmpname handle = os.path.join(data.dirs.fastqs, "{}_{}_....
[ "def", "writetofastq", "(", "data", ",", "dsort", ",", "read", ")", ":", "if", "read", "==", "1", ":", "rrr", "=", "\"R1\"", "else", ":", "rrr", "=", "\"R2\"", "for", "sname", "in", "dsort", ":", "## skip writing if empty. Write to tmpname", "handle", "=",...
27.733333
13.533333
def _login(self, username, password, client_id, client_secret): """Performs login with the provided credentials""" url = self.api_url + self.auth_token_url auth_string = '%s:%s' % (client_id, client_secret) authorization = base64.b64encode(auth_string.encode()).decode() headers =...
[ "def", "_login", "(", "self", ",", "username", ",", "password", ",", "client_id", ",", "client_secret", ")", ":", "url", "=", "self", ".", "api_url", "+", "self", ".", "auth_token_url", "auth_string", "=", "'%s:%s'", "%", "(", "client_id", ",", "client_sec...
42.647059
15.588235
def extcodehash(computation: BaseComputation) -> None: """ Return the code hash for a given address. EIP: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1052.md """ account = force_bytes_to_address(computation.stack_pop(type_hint=constants.BYTES)) state = computation.state if state.a...
[ "def", "extcodehash", "(", "computation", ":", "BaseComputation", ")", "->", "None", ":", "account", "=", "force_bytes_to_address", "(", "computation", ".", "stack_pop", "(", "type_hint", "=", "constants", ".", "BYTES", ")", ")", "state", "=", "computation", "...
38.083333
17.416667
def generate_doc(self, language_predicate, create_jvmdoc_command): """ Generate an execute method given a language predicate and command to create documentation language_predicate: a function that accepts a target and returns True if the target is of that language create_jvmdoc_...
[ "def", "generate_doc", "(", "self", ",", "language_predicate", ",", "create_jvmdoc_command", ")", ":", "catalog", "=", "self", ".", "context", ".", "products", ".", "isrequired", "(", "self", ".", "jvmdoc", "(", ")", ".", "product_type", ")", "if", "catalog"...
42.338983
25.898305
def default(self, line): ''' Implement short-cut commands: any unique command prefix should work.''' cmdargs = line.split() remain = ' '.join(cmdargs[1:]) if 'show'.startswith(cmdargs[0]): self.do_show(remain) elif 'set'.startswith(cmdargs[0]): ...
[ "def", "default", "(", "self", ",", "line", ")", ":", "cmdargs", "=", "line", ".", "split", "(", ")", "remain", "=", "' '", ".", "join", "(", "cmdargs", "[", "1", ":", "]", ")", "if", "'show'", ".", "startswith", "(", "cmdargs", "[", "0", "]", ...
37.033333
9.233333
def is_acceptable(self, response, request_params): """ Override this method to create a different definition of what kind of response is acceptable. If `bool(the_return_value) is False` then an `HTTPServiceError` will be raised. For example, you might want to assert that...
[ "def", "is_acceptable", "(", "self", ",", "response", ",", "request_params", ")", ":", "expected_codes", "=", "request_params", ".", "get", "(", "'expected_response_codes'", ",", "[", "]", ")", "return", "response", ".", "is_ok", "or", "response", ".", "status...
46.529412
21.352941
def make_pkgng_aware(jname): ''' Make jail ``jname`` pkgng aware CLI Example: .. code-block:: bash salt '*' poudriere.make_pkgng_aware <jail name> ''' ret = {'changes': {}} cdir = _config_dir() # ensure cdir is there if not os.path.isdir(cdir): os.makedirs(cdir) ...
[ "def", "make_pkgng_aware", "(", "jname", ")", ":", "ret", "=", "{", "'changes'", ":", "{", "}", "}", "cdir", "=", "_config_dir", "(", ")", "# ensure cdir is there", "if", "not", "os", ".", "path", ".", "isdir", "(", "cdir", ")", ":", "os", ".", "make...
30.393939
24.212121
def user_remove(name, user=None, password=None, host=None, port=None, database='admin', authdb=None): ''' Remove a MongoDB user CLI Example: .. code-block:: bash salt '*' mongodb.user_remove <name> <user> <password> <host> <port> <database> ''' conn = _connect(user, pa...
[ "def", "user_remove", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "database", "=", "'admin'", ",", "authdb", "=", "None", ")", ":", "conn", "=", "_connect", "(", "use...
29.083333
24.083333
def to_bytes(x, blocksize=0): """ Converts input to a byte string. Typically used in PyCrypto as an argument (e.g., key, iv) :param x: string (does nothing), bytearray, array with numbers :return: """ if isinstance(x, bytearray): return left_zero_pad(bytes(x), blocksize) elif is...
[ "def", "to_bytes", "(", "x", ",", "blocksize", "=", "0", ")", ":", "if", "isinstance", "(", "x", ",", "bytearray", ")", ":", "return", "left_zero_pad", "(", "bytes", "(", "x", ")", ",", "blocksize", ")", "elif", "isinstance", "(", "x", ",", "basestri...
34.222222
12.666667
def speech_recognition_bottom(x, model_hparams, vocab_size): """Use batchnorm instead of CMVN and shorten the stft with strided convs. Args: x: float32 tensor with shape [batch_size, len, 1, freqs * channels] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: ...
[ "def", "speech_recognition_bottom", "(", "x", ",", "model_hparams", ",", "vocab_size", ")", ":", "del", "vocab_size", "# unused arg", "inputs", "=", "x", "p", "=", "model_hparams", "num_mel_bins", "=", "p", ".", "audio_num_mel_bins", "num_channels", "=", "3", "i...
39.0125
18.6875
def browse(request, classifiers): """ Retrieve a list of (name, version) pairs of all releases classified with all of the given classifiers. 'classifiers' must be a list of Trove classifier strings. changelog(since) Retrieve a list of four-tuples (name, version, timestamp, action) since the...
[ "def", "browse", "(", "request", ",", "classifiers", ")", ":", "session", "=", "DBSession", "(", ")", "release", "=", "Release", ".", "by_classifiers", "(", "session", ",", "classifiers", ")", "rv", "=", "[", "(", "r", ".", "package", ".", "name", ",",...
38.4
18.8
def _get_licences(): """ Lists all the licenses on command line """ licenses = _LICENSES for license in licenses: print("{license_name} [{license_code}]".format( license_name=licenses[license], license_code=license))
[ "def", "_get_licences", "(", ")", ":", "licenses", "=", "_LICENSES", "for", "license", "in", "licenses", ":", "print", "(", "\"{license_name} [{license_code}]\"", ".", "format", "(", "license_name", "=", "licenses", "[", "license", "]", ",", "license_code", "=",...
33
18.142857
def list_vms(search=None, sort=None, order='uuid,type,ram,state,alias', keyed=True): ''' Return a list of VMs search : string vmadm filter property sort : string vmadm sort (-s) property order : string vmadm order (-o) property -- Default: uuid,type,ram,state,alias keyed...
[ "def", "list_vms", "(", "search", "=", "None", ",", "sort", "=", "None", ",", "order", "=", "'uuid,type,ram,state,alias'", ",", "keyed", "=", "True", ")", ":", "ret", "=", "{", "}", "# vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...]", "cmd", "...
32.821429
20.964286
def convert_to_theano_var(obj): """ Convert neural vars to theano vars. :param obj: NeuralVariable or list or dict or tuple :return: theano var, test var, tensor found, neural var found """ from deepy.core.neural_var import NeuralVariable if type(obj) == tuple: return tuple(convert_t...
[ "def", "convert_to_theano_var", "(", "obj", ")", ":", "from", "deepy", ".", "core", ".", "neural_var", "import", "NeuralVariable", "if", "type", "(", "obj", ")", "==", "tuple", ":", "return", "tuple", "(", "convert_to_theano_var", "(", "list", "(", "obj", ...
41.293103
13.327586
def body(circuit, settings): """ Return the body of the Latex document, including the entire circuit in TikZ format. :param Program circuit: The circuit to be drawn, represented as a pyquil program. :param dict settings: :return: Latex string to draw the entire circuit. :rtype: string ...
[ "def", "body", "(", "circuit", ",", "settings", ")", ":", "qubit_instruction_mapping", "=", "{", "}", "# Allocate each qubit.", "for", "inst", "in", "circuit", ":", "if", "isinstance", "(", "inst", ",", "Measurement", ")", ":", "inst", ".", "qubits", "=", ...
44.236842
21.710526
def _jcols(self, *cols): """Return a JVM Seq of Columns from a list of Column or column names If `cols` has only one list in it, cols[0] will be used as the list. """ if len(cols) == 1 and isinstance(cols[0], list): cols = cols[0] return self._jseq(cols, _to_java_col...
[ "def", "_jcols", "(", "self", ",", "*", "cols", ")", ":", "if", "len", "(", "cols", ")", "==", "1", "and", "isinstance", "(", "cols", "[", "0", "]", ",", "list", ")", ":", "cols", "=", "cols", "[", "0", "]", "return", "self", ".", "_jseq", "(...
39.625
16.25
def master_send_callback(self, m, master): '''called on sending a message''' if self.status.watch is not None: for msg_type in self.status.watch: if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()): self.mpstate.console.writeln('> '+ str(m)) ...
[ "def", "master_send_callback", "(", "self", ",", "m", ",", "master", ")", ":", "if", "self", ".", "status", ".", "watch", "is", "not", "None", ":", "for", "msg_type", "in", "self", ".", "status", ".", "watch", ":", "if", "fnmatch", ".", "fnmatch", "(...
45.153846
16.384615
async def activate_scene(self, scene_id: int): """Activate a scene :param scene_id: Scene id. :return: """ _scene = await self.get_scene(scene_id) await _scene.activate()
[ "async", "def", "activate_scene", "(", "self", ",", "scene_id", ":", "int", ")", ":", "_scene", "=", "await", "self", ".", "get_scene", "(", "scene_id", ")", "await", "_scene", ".", "activate", "(", ")" ]
23.555556
14.666667
def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names): """ prepare kernel string for compilation Prepends the kernel with a series of C preprocessor defines specific to this kernel instance: * the thread block dimensions * the grid dimensions * tunab...
[ "def", "prepare_kernel_string", "(", "kernel_name", ",", "kernel_string", ",", "params", ",", "grid", ",", "threads", ",", "block_size_names", ")", ":", "logging", ".", "debug", "(", "'prepare_kernel_string called for %s'", ",", "kernel_name", ")", "grid_dim_names", ...
42.981132
28.45283
def enable_tracing(self, thread_trace_func=None): ''' Enables tracing. If in regular mode (tracing), will set the tracing function to the tracing function for this thread -- by default it's `PyDB.trace_dispatch`, but after `PyDB.enable_tracing` is called with a `thread_trace_fun...
[ "def", "enable_tracing", "(", "self", ",", "thread_trace_func", "=", "None", ")", ":", "if", "self", ".", "frame_eval_func", "is", "not", "None", ":", "self", ".", "frame_eval_func", "(", ")", "pydevd_tracing", ".", "SetTrace", "(", "self", ".", "dummy_trace...
39.95
25.15
def line(self, text, style=None, verbosity=None): """ Write a string as information output. """ if style: styled = "<%s>%s</>" % (style, text) else: styled = text self._io.write_line(styled, verbosity)
[ "def", "line", "(", "self", ",", "text", ",", "style", "=", "None", ",", "verbosity", "=", "None", ")", ":", "if", "style", ":", "styled", "=", "\"<%s>%s</>\"", "%", "(", "style", ",", "text", ")", "else", ":", "styled", "=", "text", "self", ".", ...
26.5
13.3
def _dispatch(self, operation, request, path_args): """ Wrapped dispatch method, prepare request and generate a HTTP Response. """ # Determine the request and response types. Ensure API supports the requested types request_type = resolve_content_type(self.request_type_resolvers, ...
[ "def", "_dispatch", "(", "self", ",", "operation", ",", "request", ",", "path_args", ")", ":", "# Determine the request and response types. Ensure API supports the requested types", "request_type", "=", "resolve_content_type", "(", "self", ".", "request_type_resolvers", ",", ...
42.184211
24.868421
def fromtimestamp(cls, timestamp, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) converter = _time.localtime if tz is None else _time.gmtime self = cls._from_timestam...
[ "def", "fromtimestamp", "(", "cls", ",", "timestamp", ",", "tz", "=", "None", ")", ":", "_check_tzinfo_arg", "(", "tz", ")", "converter", "=", "_time", ".", "localtime", "if", "tz", "is", "None", "else", "_time", ".", "gmtime", "self", "=", "cls", ".",...
38.181818
14.272727
def clear(self): """Clear all work items from the session. This removes any associated results as well. """ with self._conn: self._conn.execute('DELETE FROM results') self._conn.execute('DELETE FROM work_items')
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "_conn", ":", "self", ".", "_conn", ".", "execute", "(", "'DELETE FROM results'", ")", "self", ".", "_conn", ".", "execute", "(", "'DELETE FROM work_items'", ")" ]
32.625
15.125
def resume(vm_): ''' Resume the named vm CLI Example: .. code-block:: bash salt '*' virt.resume <vm name> ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if vm_uuid is False: return False try: xapi.VM.unp...
[ "def", "resume", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try", ":", "xapi", ...
20.526316
20.526316
def render_to(self, path, template, **data): """Render data with template and then write to path""" html = self.render(template, **data) with open(path, 'w') as f: f.write(html.encode(charset))
[ "def", "render_to", "(", "self", ",", "path", ",", "template", ",", "*", "*", "data", ")", ":", "html", "=", "self", ".", "render", "(", "template", ",", "*", "*", "data", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ...
45
3
def add_residue_mindist(self, residue_pairs='all', scheme='closest-heavy', ignore_nonprotein=True, threshold=None, periodic=True): r""" Adds the minimum distance be...
[ "def", "add_residue_mindist", "(", "self", ",", "residue_pairs", "=", "'all'", ",", "scheme", "=", "'closest-heavy'", ",", "ignore_nonprotein", "=", "True", ",", "threshold", "=", "None", ",", "periodic", "=", "True", ")", ":", "from", ".", "distances", "imp...
48.944444
32.037037
def to_json(self, data): """ Converts the given object to a pretty-formatted JSON string :param data: the object to convert to JSON :return: A pretty-formatted JSON string """ # Don't forget the empty line at the end of the file return ( json.dumps( ...
[ "def", "to_json", "(", "self", ",", "data", ")", ":", "# Don't forget the empty line at the end of the file", "return", "(", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",",...
28.277778
16.055556
def fullmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.""" # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly rep...
[ "def", "fullmatch", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "# Build a version of the pattern with a non-capturing group around it.", "# This is needed to get m.end() to correctly report the size of the", "# matched expression (as per the final doctest above).", ...
54.846154
15.769231
def register(self, plugin=None, plugin_file=None, directory=None, skip_types=None, override=False, activate=True): """ Register a plugin, or plugins to be managed and recognized by the plugin manager. Will take a plugin instance, file where a plugin / plugin(s) reside, parent directory t...
[ "def", "register", "(", "self", ",", "plugin", "=", "None", ",", "plugin_file", "=", "None", ",", "directory", "=", "None", ",", "skip_types", "=", "None", ",", "override", "=", "False", ",", "activate", "=", "True", ")", ":", "# Double verify that there's...
55.626016
31.284553
def pgettext(self, context, string, domain=None, **variables): """Like :meth:`gettext` but with a context.""" t = self.get_translations(domain) return t.upgettext(context, string) % variables
[ "def", "pgettext", "(", "self", ",", "context", ",", "string", ",", "domain", "=", "None", ",", "*", "*", "variables", ")", ":", "t", "=", "self", ".", "get_translations", "(", "domain", ")", "return", "t", ".", "upgettext", "(", "context", ",", "str...
53
9.5
def api_version(created_ver, last_changed_ver, return_value_ver): """Version check decorator. Currently only checks Bigger Than.""" def api_min_version_decorator(function): def wrapper(function, self, *args, **kwargs): if not self.version_check_mode == "none": if self.v...
[ "def", "api_version", "(", "created_ver", ",", "last_changed_ver", ",", "return_value_ver", ")", ":", "def", "api_min_version_decorator", "(", "function", ")", ":", "def", "wrapper", "(", "function", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")...
69.857143
30.666667
def _tr_system(line_info): "Translate lines escaped with: !" cmd = line_info.line.lstrip().lstrip(ESC_SHELL) return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
[ "def", "_tr_system", "(", "line_info", ")", ":", "cmd", "=", "line_info", ".", "line", ".", "lstrip", "(", ")", ".", "lstrip", "(", "ESC_SHELL", ")", "return", "'%sget_ipython().system(%r)'", "%", "(", "line_info", ".", "pre", ",", "cmd", ")" ]
47
14
def _add_comments( self, comments: Optional[Sequence[str]], original_string: str = "" ) -> str: """ Returns a string with comments added if ignore_comments is not set. """ if self.config['ignore_comments']: return self._strip_comments(original_...
[ "def", "_add_comments", "(", "self", ",", "comments", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", ",", "original_string", ":", "str", "=", "\"\"", ")", "->", "str", ":", "if", "self", ".", "config", "[", "'ignore_comments'", "]", ":", "retu...
35.294118
18.941176
def update(self, friendly_name=values.unset, unique_name=values.unset, email=values.unset, cc_emails=values.unset, status=values.unset, verification_code=values.unset, verification_type=values.unset, verification_document_sid=values.unset, extension=values.unset, ...
[ "def", "update", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ",", "email", "=", "values", ".", "unset", ",", "cc_emails", "=", "values", ".", "unset", ",", "status", "=", "values", "....
52.647059
24.764706
def _make_static_dir_path(cwd, static_dir): """ This method returns the path to the directory where static files are to be served from. If static_dir is a relative path, then it is resolved to be relative to the current working directory. If no static directory is provided, or if the res...
[ "def", "_make_static_dir_path", "(", "cwd", ",", "static_dir", ")", ":", "if", "not", "static_dir", ":", "return", "None", "static_dir_path", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "static_dir", ")", "if", "os", ".", "path", ".", "exists",...
52.647059
29.823529
def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None): """ Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID...
[ "def", "logout", "(", "self", ",", "return_to", "=", "None", ",", "name_id", "=", "None", ",", "session_index", "=", "None", ",", "nq", "=", "None", ",", "name_id_format", "=", "None", ")", ":", "slo_url", "=", "self", ".", "get_slo_url", "(", ")", "...
39.309091
23.636364
def generate_pymol_session(self, pymol_executable = 'pymol', settings = {}): ''' Generates the PyMOL session for the scaffold, model, and design structures. Returns this session and the script which generated it.''' if not self.fixed: self.fix() b = BatchBuilder(pymol_e...
[ "def", "generate_pymol_session", "(", "self", ",", "pymol_executable", "=", "'pymol'", ",", "settings", "=", "{", "}", ")", ":", "if", "not", "self", ".", "fixed", ":", "self", ".", "fix", "(", ")", "b", "=", "BatchBuilder", "(", "pymol_executable", "=",...
40.066667
31.933333
def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs): """List subtitles. The `videos` must pass the `languages` check of :func:`check_video`. :param videos: videos to list subtitles for. :type videos: set of :class:`~subliminal.video.Video` :param languages: languages to search...
[ "def", "list_subtitles", "(", "videos", ",", "languages", ",", "pool_class", "=", "ProviderPool", ",", "*", "*", "kwargs", ")", ":", "listed_subtitles", "=", "defaultdict", "(", "list", ")", "# check videos", "checked_videos", "=", "[", "]", "for", "video", ...
38.820513
21.769231