text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
async def game( self, short_name, *, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates a new inline result of game type. Args: short_name (`str`): T...
[ "async", "def", "game", "(", "self", ",", "short_name", ",", "*", ",", "id", "=", "None", ",", "text", "=", "None", ",", "parse_mode", "=", "(", ")", ",", "link_preview", "=", "True", ",", "geo", "=", "None", ",", "period", "=", "60", ",", "conta...
31.074074
17.222222
def payments(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start retu...
[ "def", "payments", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_payments", "(", "address", "=", "self", ".", "address...
53.466667
31.8
def output(data, **kwargs): # pylint: disable=unused-argument ''' Read in the dict structure generated by the salt key API methods and print the structure. ''' color = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) strip_colors = __opts_...
[ "def", "output", "(", "data", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "color", "=", "salt", ".", "utils", ".", "color", ".", "get_colors", "(", "__opts__", ".", "get", "(", "'color'", ")", ",", "__opts__", ".", "get", "(",...
39.978261
13.934783
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, ...
[ "def", "get_conn", "(", "cls", ")", ":", "conn", "=", "cls", ".", "_conn", "if", "conn", "is", "None", "or", "conn", ".", "closed", ":", "conn", "=", "ldap3", ".", "Connection", "(", "settings", ".", "CAS_LDAP_SERVER", ",", "settings", ".", "CAS_LDAP_U...
33.615385
9.538462
def sortable_title(instance): """Uses the default Plone sortable_text index lower-case """ title = plone_sortable_title(instance) if safe_callable(title): title = title() return title.lower()
[ "def", "sortable_title", "(", "instance", ")", ":", "title", "=", "plone_sortable_title", "(", "instance", ")", "if", "safe_callable", "(", "title", ")", ":", "title", "=", "title", "(", ")", "return", "title", ".", "lower", "(", ")" ]
30.428571
8.285714
def _lookup(self, p, directory, fsclass, create=1): """ The generic entry point for Node lookup with user-supplied data. This translates arbitrary input into a canonical Node.FS object of the specified fsclass. The general approach for strings is to turn it into a fully normali...
[ "def", "_lookup", "(", "self", ",", "p", ",", "directory", ",", "fsclass", ",", "create", "=", "1", ")", ":", "if", "isinstance", "(", "p", ",", "Base", ")", ":", "# It's already a Node.FS object. Make sure it's the right", "# class and return.", "p", ".", "m...
38.6
19.459259
def _set_meta(self): """ set the meta fields of the ParameterSet as those that are shared by ALL parameters in the ParameterSet. For any fields that are not """ # we want to set meta-fields that are shared by ALL params in the PS for field in _meta_fields_twig: ...
[ "def", "_set_meta", "(", "self", ")", ":", "# we want to set meta-fields that are shared by ALL params in the PS", "for", "field", "in", "_meta_fields_twig", ":", "keys_for_this_field", "=", "set", "(", "[", "getattr", "(", "p", ",", "field", ")", "for", "p", "in", ...
45.2
18.8
def dropEvent( self, event ): """ Processes the drag drop event using the filter set by the \ setDragDropFilter :param event | <QDropEvent> """ filt = self.dragDropFilter() if not filt: super(XTreeWidget, self).dropEvent(event) ...
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "filt", "=", "self", ".", "dragDropFilter", "(", ")", "if", "not", "filt", ":", "super", "(", "XTreeWidget", ",", "self", ")", ".", "dropEvent", "(", "event", ")", "return", "filt", "(", "self"...
27.923077
14.384615
def add(x1, x2, output_shape=None, name=None): """Binary addition with broadcsting. Args: x1: a Tensor x2: a Tensor output_shape: an optional Shape name: an optional string Returns: a Tensor """ output_shape = convert_to_shape(output_shape) if not isinstance(x2, Tensor): return Scal...
[ "def", "add", "(", "x1", ",", "x2", ",", "output_shape", "=", "None", ",", "name", "=", "None", ")", ":", "output_shape", "=", "convert_to_shape", "(", "output_shape", ")", "if", "not", "isinstance", "(", "x2", ",", "Tensor", ")", ":", "return", "Scala...
30.263158
15.368421
def set(self, handler, attr, name, path, cfg): """ Obtain value for config variable, by prompting the user for input and substituting a default value if needed. Also does validation on user input """ full_name = ("%s.%s" % (path, name)).strip(".") # obtain def...
[ "def", "set", "(", "self", ",", "handler", ",", "attr", ",", "name", ",", "path", ",", "cfg", ")", ":", "full_name", "=", "(", "\"%s.%s\"", "%", "(", "path", ",", "name", ")", ")", ".", "strip", "(", "\".\"", ")", "# obtain default value", "if", "a...
33.3
19.9
def search_certificate(self, hash): """ Searches for a specific certificate using its hash :param hash: certificate hash :type hash: str :return: dict """ c = CensysCertificates(api_id=self.__uid, api_secret=self.__api_key) return c.view(hash)
[ "def", "search_certificate", "(", "self", ",", "hash", ")", ":", "c", "=", "CensysCertificates", "(", "api_id", "=", "self", ".", "__uid", ",", "api_secret", "=", "self", ".", "__api_key", ")", "return", "c", ".", "view", "(", "hash", ")" ]
29.9
15.1
def _checkRelatesTo(self, value): '''WS-Address From value -- From server returned. ''' if value != self._messageID: raise WSActionException, 'wrong WS-Address RelatesTo(%s), expecting %s'%(value,self._messageID)
[ "def", "_checkRelatesTo", "(", "self", ",", "value", ")", ":", "if", "value", "!=", "self", ".", "_messageID", ":", "raise", "WSActionException", ",", "'wrong WS-Address RelatesTo(%s), expecting %s'", "%", "(", "value", ",", "self", ".", "_messageID", ")" ]
42
20.333333
def p_namedblock(self, p): 'namedblock : BEGIN COLON ID namedblock_statements END' p[0] = Block(p[4], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_namedblock", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Block", "(", "p", "[", "4", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",",...
44.25
13.25
def get_topic_keyword_dictionary(): """ Opens the topic-keyword map resource file and returns the corresponding python dictionary. - Input: - file_path: The path pointing to the topic-keyword map resource file. - Output: - topic_set: A topic to keyword python dictionary. """ topic_keyword_dic...
[ "def", "get_topic_keyword_dictionary", "(", ")", ":", "topic_keyword_dictionary", "=", "dict", "(", ")", "file_row_gen", "=", "get_file_row_generator", "(", "get_package_path", "(", ")", "+", "\"/twitter/res/topics/topic_keyword_mapping\"", "+", "\".txt\"", ",", "\",\"", ...
43.625
25.25
def create(self, name, incident_preference): """ This API endpoint allows you to create an alert policy :type name: str :param name: The name of the policy :type incident_preference: str :param incident_preference: Can be PER_POLICY, PER_CONDITION or PER_CON...
[ "def", "create", "(", "self", ",", "name", ",", "incident_preference", ")", ":", "data", "=", "{", "\"policy\"", ":", "{", "\"name\"", ":", "name", ",", "\"incident_preference\"", ":", "incident_preference", "}", "}", "return", "self", ".", "_post", "(", "...
24.65
19.65
def qnormal(mu, sigma, q, random_state): ''' mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(normal(mu, sigma, random_state) / q) * q
[ "def", "qnormal", "(", "mu", ",", "sigma", ",", "q", ",", "random_state", ")", ":", "return", "np", ".", "round", "(", "normal", "(", "mu", ",", "sigma", ",", "random_state", ")", "/", "q", ")", "*", "q" ]
33
15.75
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `MojAnonymousUser` is returned. """ user = None try: user_id = request.session[SESSION_KEY] token = request.session[AUTH_TOKEN_SESSION_KEY]...
[ "def", "get_user", "(", "request", ")", ":", "user", "=", "None", "try", ":", "user_id", "=", "request", ".", "session", "[", "SESSION_KEY", "]", "token", "=", "request", ".", "session", "[", "AUTH_TOKEN_SESSION_KEY", "]", "user_data", "=", "request", ".",...
38.862069
17.965517
async def send_packed_command(self, command): "Send an already packed command to the Redis server" if not self._writer: await self.connect() try: if isinstance(command, str): command = [command] self._writer.writelines(command) except a...
[ "async", "def", "send_packed_command", "(", "self", ",", "command", ")", ":", "if", "not", "self", ".", "_writer", ":", "await", "self", ".", "connect", "(", ")", "try", ":", "if", "isinstance", "(", "command", ",", "str", ")", ":", "command", "=", "...
36.208333
12.875
def keys(request): """Lists API keys. Compatible with jQuery DataTables.""" iDisplayStart = parse_int_param(request, 'iDisplayStart') iDisplayLength = parse_int_param(request, 'iDisplayLength') sEcho = parse_int_param(request, 'sEcho') iSortCol_0 = parse_int_param(request, 'iSortCol_0') sSortDir...
[ "def", "keys", "(", "request", ")", ":", "iDisplayStart", "=", "parse_int_param", "(", "request", ",", "'iDisplayStart'", ")", "iDisplayLength", "=", "parse_int_param", "(", "request", ",", "'iDisplayLength'", ")", "sEcho", "=", "parse_int_param", "(", "request", ...
47.725
19.275
def natsort(string): '''按照语言里的意义对字符串进行排序. 这个方法用于替换按照字符编码顺序对字符串进行排序. 相关链接: http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-a-list-using-a-natural-order-algorithm http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html ''' return [...
[ "def", "natsort", "(", "string", ")", ":", "return", "[", "int", "(", "s", ")", "if", "s", ".", "isdigit", "(", ")", "else", "s", "for", "s", "in", "re", ".", "split", "(", "'(\\d+)'", ",", "string", ")", "]" ]
41.777778
35.333333
def load_pem_private_key(data, password): """Load RSA PEM certificate.""" key = _serialization.load_pem_private_key( data, password, _backends.default_backend()) return key
[ "def", "load_pem_private_key", "(", "data", ",", "password", ")", ":", "key", "=", "_serialization", ".", "load_pem_private_key", "(", "data", ",", "password", ",", "_backends", ".", "default_backend", "(", ")", ")", "return", "key" ]
37.6
9
def get_ccle_mrna(gene_list, cell_lines): """Return a dict of mRNA amounts in given genes and cell lines from CCLE. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mRNA amounts for. cell_lines : list[str] A list of CCLE cell line names to get mRNA amou...
[ "def", "get_ccle_mrna", "(", "gene_list", ",", "cell_lines", ")", ":", "gene_list_str", "=", "','", ".", "join", "(", "gene_list", ")", "data", "=", "{", "'cmd'", ":", "'getProfileData'", ",", "'case_set_id'", ":", "ccle_study", "+", "'_mrna'", ",", "'geneti...
36.710526
15.289474
def _init(self): """ initialize all values based on provided input :return: None """ self.col_count = len(self.col_list) # list of lengths of longest entries in columns self.col_longest = self.get_all_longest_col_lengths() self.data_length = sum(self.col_...
[ "def", "_init", "(", "self", ")", ":", "self", ".", "col_count", "=", "len", "(", "self", ".", "col_list", ")", "# list of lengths of longest entries in columns", "self", ".", "col_longest", "=", "self", ".", "get_all_longest_col_lengths", "(", ")", "self", ".",...
51.071429
25.857143
def _init_tools(self, element, callbacks=[]): """ Processes the list of tools to be supplied to the plot. """ tooltips, hover_opts = self._hover_opts(element) tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name)) if isinstance(ttp, Dimen...
[ "def", "_init_tools", "(", "self", ",", "element", ",", "callbacks", "=", "[", "]", ")", ":", "tooltips", ",", "hover_opts", "=", "self", ".", "_hover_opts", "(", "element", ")", "tooltips", "=", "[", "(", "ttp", ".", "pprint_label", ",", "'@{%s}'", "%...
40.521739
15.782609
def get_current_traceback(ignore_system_exceptions=False): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the function as first pa...
[ "def", "get_current_traceback", "(", "ignore_system_exceptions", "=", "False", ")", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "if", "ignore_system_exceptions", "and", "exc_type", "in", "system_exceptions", ":", "raise", ...
49.9
15.5
def location(self): """ Returns a ``string`` constant to indicate whether the game was played at home, away, or in a neutral location. """ if self._location.lower() == 'n': return NEUTRAL if self._location.lower() == '@': return AWAY return...
[ "def", "location", "(", "self", ")", ":", "if", "self", ".", "_location", ".", "lower", "(", ")", "==", "'n'", ":", "return", "NEUTRAL", "if", "self", ".", "_location", ".", "lower", "(", ")", "==", "'@'", ":", "return", "AWAY", "return", "HOME" ]
31.6
12
def send(self, message) : "puts a message in the outgoing queue." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if serial = ct.c_uint() if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) : ...
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "serial", "=", "ct", ".", "c_uint", "(", ")", "if", "no...
37.454545
18.727273
def register_error_handler( self, error: Union[Type[Exception], int], func: Callable, name: AppOrBlueprintKey=None, ) -> None: """Register a function as an error handler. This is designed to be used on the application directly. An example usage, .. code-block:: python ...
[ "def", "register_error_handler", "(", "self", ",", "error", ":", "Union", "[", "Type", "[", "Exception", "]", ",", "int", "]", ",", "func", ":", "Callable", ",", "name", ":", "AppOrBlueprintKey", "=", "None", ",", ")", "->", "None", ":", "handler", "="...
33
19.416667
def load_dump(self, name=None): """ Загружает базу с жёсткого диска. Текущая база заменяется. :name: Имя файла, без расширения. """ name = name or "vocabularDump" dump_file = os_join( self.temp_folder, "{0}.json".format(name) ) ...
[ "def", "load_dump", "(", "self", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "\"vocabularDump\"", "dump_file", "=", "os_join", "(", "self", ".", "temp_folder", ",", "\"{0}.json\"", ".", "format", "(", "name", ")", ")", "if", "not", "...
34
10
def grant_bonus(self, worker_id, assignment_id, bonus_price, reason): """ Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or rejected. This payme...
[ "def", "grant_bonus", "(", "self", ",", "worker_id", ",", "assignment_id", ",", "bonus_price", ",", "reason", ")", ":", "params", "=", "bonus_price", ".", "get_as_params", "(", "'BonusAmount'", ",", "1", ")", "params", "[", "'WorkerId'", "]", "=", "worker_id...
46.75
18.875
def _ep_pairwise( n_items, comparisons, alpha, match_moments, max_iter, initial_state): """Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ # Static variable that a...
[ "def", "_ep_pairwise", "(", "n_items", ",", "comparisons", ",", "alpha", ",", "match_moments", ",", "max_iter", ",", "initial_state", ")", ":", "# Static variable that allows to check the # of iterations after the call.", "_ep_pairwise", ".", "iterations", "=", "0", "m", ...
41.594203
13.73913
def draw_legend(data, obj): """Adds legend code. """ texts = [] children_alignment = [] for text in obj.texts: texts.append("{}".format(text.get_text())) children_alignment.append("{}".format(text.get_horizontalalignment())) # Get the location. # http://matplotlib.org/api/le...
[ "def", "draw_legend", "(", "data", ",", "obj", ")", ":", "texts", "=", "[", "]", "children_alignment", "=", "[", "]", "for", "text", "in", "obj", ".", "texts", ":", "texts", ".", "append", "(", "\"{}\"", ".", "format", "(", "text", ".", "get_text", ...
34.670732
20.268293
def get_market_deep(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_deep """ import warnings warnings.warn(WNG_MSG % ("get_market_deep", "iexdata.get_deep")) return DEEP(symbols, **kwargs).fetch()
[ "def", "get_market_deep", "(", "symbols", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_market_deep\"", ",", "\"iexdata.get_deep\"", ")", ")", "return", "DEEP", "(", "symbols",...
33.285714
8.142857
def _AssertIsLocal(path): ''' Checks if a given path is local, raise an exception if not. This is used in filesystem functions that do not support remote operations yet. :param unicode path: :raises NotImplementedForRemotePathError: If the given path is not local ''' from six.move...
[ "def", "_AssertIsLocal", "(", "path", ")", ":", "from", "six", ".", "moves", ".", "urllib", ".", "parse", "import", "urlparse", "if", "not", "_UrlIsLocal", "(", "urlparse", "(", "path", ")", ")", ":", "from", ".", "_exceptions", "import", "NotImplementedFo...
32.6
21.933333
def time(self, intervals=1, *args, _show_progress=True, _print=True, _collect_garbage=True, _quiet=True, **kwargs): """ Measures the execution time of :prop:_callable for @intervals @intervals: #int number of intervals to measure the execution time of the function for ...
[ "def", "time", "(", "self", ",", "intervals", "=", "1", ",", "*", "args", ",", "_show_progress", "=", "True", ",", "_print", "=", "True", ",", "_collect_garbage", "=", "True", ",", "_quiet", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", "...
43.790698
16.534884
def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]: """Get a guild member by their id Args: guild_id: snowflake id of the guild member_id: snowflake id of the member Returns: Dictionary data for the guild member. E...
[ "def", "get_guild_member_by_id", "(", "self", ",", "guild_id", ":", "int", ",", "member_id", ":", "int", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "_query", "(", "f'guilds/{guild_id}/members/{member_id}'", ",", "'GET'", ")" ...
37.382353
14.558824
def merge_lists(dest, source, extend_lists=False): """Recursively merge two lists. :keyword extend_lists: if true, just extends lists instead of merging them. This applies merge_dictionary if any of the entries are dicts. Note: This updates dest and returns it. """ if not source: retur...
[ "def", "merge_lists", "(", "dest", ",", "source", ",", "extend_lists", "=", "False", ")", ":", "if", "not", "source", ":", "return", "if", "not", "extend_lists", ":", "# Make them the same size", "left", "=", "dest", "right", "=", "source", "[", ":", "]", ...
38.25
16.3125
def recv_multipart(self, *args, **kwargs): """wrap recv_multipart to prevent state_changed on each partial recv""" self.__in_recv_multipart = True try: msg = super(GreenSocket, self).recv_multipart(*args, **kwargs) finally: self.__in_recv_multipart = False ...
[ "def", "recv_multipart", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__in_recv_multipart", "=", "True", "try", ":", "msg", "=", "super", "(", "GreenSocket", ",", "self", ")", ".", "recv_multipart", "(", "*", "args", ...
39.777778
13.444444
def get_parentparser(parser, description=None, help=True): """ :param parser: :class:`argparse.ArgumentParser` instance or None :param description: string used to build a new parser if parser is None :param help: flag used to build a new parser if parser is None :returns: if parser is None the new p...
[ "def", "get_parentparser", "(", "parser", ",", "description", "=", "None", ",", "help", "=", "True", ")", ":", "if", "parser", "is", "None", ":", "return", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ",", "add_help", "=", "he...
42.733333
17.133333
def to_python(self, value): """ Convert our string value to JSON after we load it from the DB """ if not value: return {} elif isinstance(value, six.string_types): res = loads(value) assert isinstance(res, dict) return JSONDict(**res) else:...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "return", "{", "}", "elif", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "res", "=", "loads", "(", "value", ")", "assert", "isinstance", "("...
33.6
11.9
def tomorrow(hour=None, minute=None): """ Gives the ``datetime.datetime`` object corresponding to tomorrow. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = now ...
[ "def", "tomorrow", "(", "hour", "=", "None", ",", "minute", "=", "None", ")", ":", "if", "hour", "is", "None", ":", "hour", "=", "datetime", ".", "now", "(", ")", ".", "hour", "if", "minute", "is", "None", ":", "minute", "=", "datetime", ".", "no...
41.538462
20.923077
def get_array(self, variable_name, period): """ Return the value of ``variable_name`` for ``period``, if this value is alreay in the cache (if it has been set as an input or previously calculated). Unlike :any:`calculate`, this method *does not* trigger calculations and *does not* use a...
[ "def", "get_array", "(", "self", ",", "variable_name", ",", "period", ")", ":", "if", "period", "is", "not", "None", "and", "not", "isinstance", "(", "period", ",", "periods", ".", "Period", ")", ":", "period", "=", "periods", ".", "period", "(", "peri...
57.444444
32.777778
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click....
[ "def", "package", "(", "files", ",", "tag", ",", "metadata", ",", "extra_options", ",", "branch", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "install", ",", "spatialite", ",", "version_note", ",", "*", "*", "extra_metadata", ")", ":", "if...
20.977273
22.613636
def trunc(self, model, prompt, **fields): """ Truncates fields values for the given model. Prompts for a new value if truncation occurs. """ for field_name, value in fields.items(): field = model._meta.get_field(field_name) max_length = getattr(field, "max...
[ "def", "trunc", "(", "self", ",", "model", ",", "prompt", ",", "*", "*", "fields", ")", ":", "for", "field_name", ",", "value", "in", "fields", ".", "items", "(", ")", ":", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "field_name", "...
45.954545
15.863636
def get_current_block_hash(self, is_full: bool = False) -> str: """ This interface is used to get the hexadecimal hash value of the highest block in current network. Return: the hexadecimal hash value of the highest block in current network. """ payload = self.genera...
[ "def", "get_current_block_hash", "(", "self", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_CURRENT_BLOCK_HASH", ")", "response", "=", "self", ".", "__pos...
41.333333
23.833333
def publish_workflow_submission(self, user_id, workflow_id_or_name, parameters): """Publish workflow submission parameters.""" msg = { "user": user_id, "workflow_id_or_name...
[ "def", "publish_workflow_submission", "(", "self", ",", "user_id", ",", "workflow_id_or_name", ",", "parameters", ")", ":", "msg", "=", "{", "\"user\"", ":", "user_id", ",", "\"workflow_id_or_name\"", ":", "workflow_id_or_name", ",", "\"parameters\"", ":", "paramete...
37
12
def make_request_fn(): """Returns a request function.""" if FLAGS.cloud_mlengine_model_name: request_fn = serving_utils.make_cloud_mlengine_request_fn( credentials=GoogleCredentials.get_application_default(), model_name=FLAGS.cloud_mlengine_model_name, version=FLAGS.cloud_mlengine_model_...
[ "def", "make_request_fn", "(", ")", ":", "if", "FLAGS", ".", "cloud_mlengine_model_name", ":", "request_fn", "=", "serving_utils", ".", "make_cloud_mlengine_request_fn", "(", "credentials", "=", "GoogleCredentials", ".", "get_application_default", "(", ")", ",", "mode...
36.428571
14.928571
def format(self, formatter, subset=None): """ Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements...
[ "def", "format", "(", "self", ",", "formatter", ",", "subset", "=", "None", ")", ":", "if", "subset", "is", "None", ":", "row_locs", "=", "range", "(", "len", "(", "self", ".", "data", ")", ")", "col_locs", "=", "range", "(", "len", "(", "self", ...
33.890625
21.328125
def stop(self): """Stop this gateway agent.""" if self._disconnector: self._disconnector.stop() self.client.disconnect()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_disconnector", ":", "self", ".", "_disconnector", ".", "stop", "(", ")", "self", ".", "client", ".", "disconnect", "(", ")" ]
21.714286
18
def _make_parser(**kwargs): """ :return: (keyword args to be used, parser object) """ # Optional arguements for configparser.SafeConfigParser{,readfp} kwargs_0 = filter_options(("defaults", "dict_type", "allow_no_value"), kwargs) kwargs_1 = filter_options(("filename...
[ "def", "_make_parser", "(", "*", "*", "kwargs", ")", ":", "# Optional arguements for configparser.SafeConfigParser{,readfp}", "kwargs_0", "=", "filter_options", "(", "(", "\"defaults\"", ",", "\"dict_type\"", ",", "\"allow_no_value\"", ")", ",", "kwargs", ")", "kwargs_1...
39.105263
21.421053
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as ul """ return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
[ "def", "as_ul", "(", "self", ",", "show_leaf", "=", "True", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_ul\"", ",", "show_leaf", ",", "current_linkable", ",", "...
44.8
18.4
def expected_error_messages(*error_messages): """ Decorator expecting defined error messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperErrorMixin.get_error_messages` returns. .. versionadded:: 2.0 Before this decorator was called ``ShouldBeError``. """...
[ "def", "expected_error_messages", "(", "*", "error_messages", ")", ":", "def", "wrapper", "(", "func", ")", ":", "setattr", "(", "func", ",", "EXPECTED_ERROR_MESSAGES", ",", "error_messages", ")", "return", "func", "return", "wrapper" ]
30.857143
19.285714
def calculate_diagram_ranges(data): """ Given a numpy array calculate what the ranges of the H-R diagram should be. """ data = round_arr_teff_luminosity(data) temps = data['temp'] x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)] lums = data['lum'] y_range = [.50 * np.amin(lums...
[ "def", "calculate_diagram_ranges", "(", "data", ")", ":", "data", "=", "round_arr_teff_luminosity", "(", "data", ")", "temps", "=", "data", "[", "'temp'", "]", "x_range", "=", "[", "1.05", "*", "np", ".", "amax", "(", "temps", ")", ",", ".95", "*", "np...
32.818182
11.181818
def all_api_methods(cls): """ Return a list of all the TradingAlgorithm API methods. """ return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
[ "def", "all_api_methods", "(", "cls", ")", ":", "return", "[", "fn", "for", "fn", "in", "itervalues", "(", "vars", "(", "cls", ")", ")", "if", "getattr", "(", "fn", ",", "'is_api_method'", ",", "False", ")", "]" ]
28.75
13.5
def list_product_versions_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all ProductVersions associated with a BuildConfiguration """ data = list_product_versions_for_build_configuration_raw(id, name, page_size, page_index, sort, q) if data: ...
[ "def", "list_product_versions_for_build_configuration", "(", "id", "=", "None", ",", "name", "=", "None", ",", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "sort", "=", "\"\"", ",", "q", "=", "\"\"", ")", ":", "data", "=", "list_product_versi...
50
27.428571
def create(cls, messageType, extended, hopsleft=3, hopsmax=3): """Create message flags. messageType: integter 0 to 7: MESSAGE_TYPE_DIRECT_MESSAGE = 0 MESSAGE_TYPE_DIRECT_MESSAGE_ACK = 1 MESSAGE_TYPE_ALL_LINK_CLEANUP = 2 MESSAGE_TYPE_ALL_LINK_CLEANUP_ACK =...
[ "def", "create", "(", "cls", ",", "messageType", ",", "extended", ",", "hopsleft", "=", "3", ",", "hopsmax", "=", "3", ")", ":", "flags", "=", "MessageFlags", "(", "None", ")", "if", "messageType", "<", "8", ":", "flags", ".", "_messageType", "=", "m...
34.903226
10.483871
def react(self, **kwargs): """ Bounce off of a shoreline feature = Linestring of two points, being the line segment the particle hit. angle = decimal degrees from 0 (x-axis), couter-clockwise (math style) """ if self._type == "bounce": print "This ...
[ "def", "react", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_type", "==", "\"bounce\"", ":", "print", "\"This shoreline type is NOT SUPPORTED and is broken\"", "return", "self", ".", "__bounce", "(", "*", "*", "kwargs", ")", "elif", "...
44.214286
15.928571
def get_sftp_conn(config): """Make a SFTP connection, returns sftp client and connection objects""" remote = config.get('remote_location') parts = urlparse(remote) if ':' in parts.netloc: hostname, port = parts.netloc.split(':') else: hostname = parts.netloc port = 22 po...
[ "def", "get_sftp_conn", "(", "config", ")", ":", "remote", "=", "config", ".", "get", "(", "'remote_location'", ")", "parts", "=", "urlparse", "(", "remote", ")", "if", "':'", "in", "parts", ".", "netloc", ":", "hostname", ",", "port", "=", "parts", "....
33.052632
15.263158
def is_python3_identifier(possible_identifier): """ Returns `True` if the given `possible_identifier` can be used as an identifier in Python 3. """ possible_identifier = unicodedata.normalize('NFKC', possible_identifier) return ( bool(possible_identifier) and _is_in_id_start(poss...
[ "def", "is_python3_identifier", "(", "possible_identifier", ")", ":", "possible_identifier", "=", "unicodedata", ".", "normalize", "(", "'NFKC'", ",", "possible_identifier", ")", "return", "(", "bool", "(", "possible_identifier", ")", "and", "_is_in_id_start", "(", ...
40
14
def auto_delete_files_on_instance_delete(instance: Any, fieldnames: Iterable[str]) -> None: """ Deletes files from filesystem when object is deleted. """ for fieldname in fieldnames: filefield = getattr(instance, fieldname, None) if filefield: ...
[ "def", "auto_delete_files_on_instance_delete", "(", "instance", ":", "Any", ",", "fieldnames", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "fieldname", "in", "fieldnames", ":", "filefield", "=", "getattr", "(", "instance", ",", "fieldname"...
39.6
11.6
def get_ipv4(hostname): """Get list of ipv4 addresses for hostname """ addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET, socket.SOCK_STREAM) return [addrinfo[x][4][0] for x in range(len(addrinfo))]
[ "def", "get_ipv4", "(", "hostname", ")", ":", "addrinfo", "=", "socket", ".", "getaddrinfo", "(", "hostname", ",", "None", ",", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "return", "[", "addrinfo", "[", "x", "]", "[", "4", "]", ...
36.285714
16.428571
def is_seq_of(seq, expected_type, seq_type=None): """Check whether it is a sequence of some type. Args: seq (Sequence): The sequence to be checked. expected_type (type): Expected type of sequence items. seq_type (type, optional): Expected sequence type. Returns: bool: Wheth...
[ "def", "is_seq_of", "(", "seq", ",", "expected_type", ",", "seq_type", "=", "None", ")", ":", "if", "seq_type", "is", "None", ":", "exp_seq_type", "=", "collections_abc", ".", "Sequence", "else", ":", "assert", "isinstance", "(", "seq_type", ",", "type", "...
30.090909
16.181818
def vqa_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-8 ...
[ "def", "vqa_attention_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "use_fixed_batch_size", "=", "True", ",", "hparams", ".", "optimizer", "=", "\"adam\"", "hpa...
31.75
11.588235
def MultiAppend(self, value_timestamp_pairs): """Adds multiple value<->timestamp pairs. Args: value_timestamp_pairs: Tuples of (value, timestamp). """ for value, timestamp in value_timestamp_pairs: self.Append(value, timestamp)
[ "def", "MultiAppend", "(", "self", ",", "value_timestamp_pairs", ")", ":", "for", "value", ",", "timestamp", "in", "value_timestamp_pairs", ":", "self", ".", "Append", "(", "value", ",", "timestamp", ")" ]
31.125
13.625
def action(self, column=None, value=None, **kwargs): """ The underlying GICS table provides codes and descriptions identifying the current status or disposition of a grant project. >>> GICS().action('action_code', 'A') """ return self._resolve_call('GIC_ACTION', column, ...
[ "def", "action", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'GIC_ACTION'", ",", "column", ",", "value", ",", "*", "*", "kwargs", ")" ]
41.125
18.375
def create_or_update(cls, course_video, file_name=None, image_data=None, generated_images=None): """ Create a VideoImage object for a CourseVideo. NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise a new file name is constructed based on uuid and exten...
[ "def", "create_or_update", "(", "cls", ",", "course_video", ",", "file_name", "=", "None", ",", "image_data", "=", "None", ",", "generated_images", "=", "None", ")", ":", "video_image", ",", "created", "=", "cls", ".", "objects", ".", "get_or_create", "(", ...
50.938776
29.061224
def concatenate_fastas(output_fna_clustered, output_fna_failures, output_concat_filepath): """ Concatenates two input fastas, writes to output_concat_filepath output_fna_clustered: fasta of successful ref clusters output_fna_failures: de novo fasta of cluster f...
[ "def", "concatenate_fastas", "(", "output_fna_clustered", ",", "output_fna_failures", ",", "output_concat_filepath", ")", ":", "output_fp", "=", "open", "(", "output_concat_filepath", ",", "\"w\"", ")", "for", "label", ",", "seq", "in", "parse_fasta", "(", "open", ...
39.166667
17.833333
def set_roi(location): """ Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a specified region of interest (LocationGlobal). The vehicle may also turn to face the ROI. For more information see: http://copter.ardupilot.com/common-mavlink-mission-command-messages-mav_cmd/#mav_cmd_do_se...
[ "def", "set_roi", "(", "location", ")", ":", "# create the MAV_CMD_DO_SET_ROI command", "msg", "=", "vehicle", ".", "message_factory", ".", "command_long_encode", "(", "0", ",", "0", ",", "# target system, target component", "mavutil", ".", "mavlink", ".", "MAV_CMD_DO...
33.714286
16.285714
def setmonitor(self, enable=True): """Alias for setmode('monitor') or setmode('managed') Only available with Npcap""" # We must reset the monitor cache if enable: res = self.setmode('monitor') else: res = self.setmode('managed') if not res: ...
[ "def", "setmonitor", "(", "self", ",", "enable", "=", "True", ")", ":", "# We must reset the monitor cache", "if", "enable", ":", "res", "=", "self", ".", "setmode", "(", "'monitor'", ")", "else", ":", "res", "=", "self", ".", "setmode", "(", "'managed'", ...
38.769231
10.692308
def missing_values(self): ''' Computes the values that must be missing from each player's hand, based on when they have passed. :return: a list of sets, each one containing the values that must be missing from the corresponding player's hand '''...
[ "def", "missing_values", "(", "self", ")", ":", "missing", "=", "[", "set", "(", ")", "for", "_", "in", "self", ".", "hands", "]", "# replay the game from the beginning", "board", "=", "dominoes", ".", "SkinnyBoard", "(", ")", "player", "=", "self", ".", ...
33.076923
16.769231
def load(items, default_section=_DEFAULT_SECTION): """ 从混合类型组中读取配置 :param default_section: :param items: :return: """ settings = [] assert isinstance(items, list), 'items必须为list' logger.debug(items) for item in items: if _is_conf(item): settings.append(load_...
[ "def", "load", "(", "items", ",", "default_section", "=", "_DEFAULT_SECTION", ")", ":", "settings", "=", "[", "]", "assert", "isinstance", "(", "items", ",", "list", ")", ",", "'items必须为list'", "logger", ".", "debug", "(", "items", ")", "for", "item", "i...
23.789474
18.421053
def should_run(self): """ Returns true if the feature should run """ should_run = True config = self.target or self.source if config.has('systems'): should_run = False valid_systems = [s.lower() for s in config.get('systems').split(",")] for system_typ...
[ "def", "should_run", "(", "self", ")", ":", "should_run", "=", "True", "config", "=", "self", ".", "target", "or", "self", ".", "source", "if", "config", ".", "has", "(", "'systems'", ")", ":", "should_run", "=", "False", "valid_systems", "=", "[", "s"...
45.583333
15.916667
def stringify(metrics_headers=()): """Convert the provided metrics headers to a string. Iterate over the metrics headers (a dictionary, usually ordered) and return a properly-formatted space-separated string (e.g. foo/1.2.3 bar/3.14.159). """ metrics_headers = collections.OrderedDict(metrics_he...
[ "def", "stringify", "(", "metrics_headers", "=", "(", ")", ")", ":", "metrics_headers", "=", "collections", ".", "OrderedDict", "(", "metrics_headers", ")", "return", "' '", ".", "join", "(", "[", "'%s/%s'", "%", "(", "k", ",", "v", ")", "for", "k", ",...
43.777778
17.222222
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2): """ Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion pow...
[ "def", "prop_power", "(", "self", ",", "propulsion_eff", "=", "0.7", ",", "sea_margin", "=", "0.2", ")", ":", "PP", "=", "(", "1", "+", "sea_margin", ")", "*", "self", ".", "resistance", "(", ")", "*", "self", ".", "speed", "/", "propulsion_eff", "re...
43.3
21.7
def firmware_manifest_retrieve(self, manifest_id, **kwargs): # noqa: E501 """Get a manifest # noqa: E501 Retrieve a firmware manifest. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>>...
[ "def", "firmware_manifest_retrieve", "(", "self", ",", "manifest_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self",...
47.095238
22.619048
def value(self, extra=None): """The value used for processing. Can be a tuple. with optional extra bits """ if isinstance(self.code, WithExtra): if not 0<=extra<1<<self.extraBits(): raise ValueError("value: extra value doesn't fit in extraBits") re...
[ "def", "value", "(", "self", ",", "extra", "=", "None", ")", ":", "if", "isinstance", "(", "self", ".", "code", ",", "WithExtra", ")", ":", "if", "not", "0", "<=", "extra", "<", "1", "<<", "self", ".", "extraBits", "(", ")", ":", "raise", "ValueE...
44.454545
11.181818
def create(logger_name, logfile='gromacs.log'): """Create a top level logger. - The file logger logs everything (including DEBUG). - The console logger only logs INFO and above. Logging to a file and the console. See http://docs.python.org/library/logging.html?#logging-to-multiple-destination...
[ "def", "create", "(", "logger_name", ",", "logfile", "=", "'gromacs.log'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logfile", "=", "logging", ".", "FileHan...
34.916667
22.194444
def reset_syslog_config(host, username, password, protocol=None, port=None, syslog_config=None, esxi_hosts=None, credstore=None): ''' Reset the ...
[ "def", "reset_syslog_config", "(", "host", ",", "username", ",", "password", ",", "protocol", "=", "None", ",", "port", "=", "None", ",", "syslog_config", "=", "None", ",", "esxi_hosts", "=", "None", ",", "credstore", "=", "None", ")", ":", "if", "not", ...
38.673684
26.8
def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds): # instantiating string the main string block for the javascript block of html code string = '' ''' # logic for instantiating variable colorkey input if not colorkeyfields == False: colorkey = 'selectedText' ''' # iteratin...
[ "def", "make_bindings_type", "(", "filenames", ",", "color_input", ",", "colorkey", ",", "file_dictionary", ",", "sidebar", ",", "bounds", ")", ":", "# instantiating string the main string block for the javascript block of html code", "string", "=", "''", "# iterating through...
31.538462
21.650888
def make_us_postal_code(s, allowed_lengths=(), allowed_digits=()): """ >>> make_us_postal_code(1234) '01234' >>> make_us_postal_code(507.6009) '507' >>> make_us_postal_code(90210.0) '90210' >>> make_us_postal_code(39567.7226) '39567-7226' >>> make_us_postal_code(39567.7226) '...
[ "def", "make_us_postal_code", "(", "s", ",", "allowed_lengths", "=", "(", ")", ",", "allowed_digits", "=", "(", ")", ")", ":", "allowed_lengths", "=", "allowed_lengths", "or", "tuple", "(", "N", "if", "N", "<", "6", "else", "N", "+", "1", "for", "N", ...
30.52
16.04
def on_make_toast(self, ref): """ Using Toast.makeToast returns async so we have to initialize it later. """ d = self.declaration self.toast = Toast(__id__=ref) self.init_widget()
[ "def", "on_make_toast", "(", "self", ",", "ref", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "toast", "=", "Toast", "(", "__id__", "=", "ref", ")", "self", ".", "init_widget", "(", ")" ]
28.875
12
def convert_args(test_fcn, *test_args): """ Decorator to be using in formulas to convert ``test_args`` depending on the ``test_fcn``. :param test_fcn: A test function that converts arguments. :type test_fcn: function :param test_args: Names of args to convert using ``test_fcn``. :type test_...
[ "def", "convert_args", "(", "test_fcn", ",", "*", "test_args", ")", ":", "def", "wrapper", "(", "origfcn", ")", ":", "@", "functools", ".", "wraps", "(", "origfcn", ")", "def", "newfcn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "argspec",...
38.277778
17.5
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
[ "def", "get_synset_1000", "(", "self", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "'synsets.txt'", ")", "assert", "os", ".", "path", ".", "isfile", "(", "fname", ")", "lines", "=", "[", "x", ".", "strip", ...
32.333333
8.777778
def create_table_from_json( self, json_source, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a JSON file/text. :param str json_source: Path to the JSON file or JSON text. :p...
[ "def", "create_table_from_json", "(", "self", ",", "json_source", ",", "table_name", "=", "\"\"", ",", "primary_key", "=", "None", ",", "add_primary_key_column", "=", "False", ",", "index_attrs", "=", "None", ",", ")", ":", "import", "pytablereader", "as", "pt...
32.4375
18.9375
def clean_dataframe(df, is_slugify=True, threshold=50, rename_cols=None): """ This method is used to: - slugify the column names (if slugify is set to True) - convert columns to 'category' (if len(unique) < threshold) or 'int' - clean the dataframe and rename if necessary """ if is_slugify: ...
[ "def", "clean_dataframe", "(", "df", ",", "is_slugify", "=", "True", ",", "threshold", "=", "50", ",", "rename_cols", "=", "None", ")", ":", "if", "is_slugify", ":", "df", "=", "df", ".", "rename", "(", "columns", "=", "slugify", ")", "df", "=", "df"...
33.2
16.5
def load(stream): """Parse the LHA document and produce the corresponding Python object. Accepts a string or a file-like object.""" if isinstance(stream, str): string = stream else: string = stream.read() tokens = tokenize(string) return parse(tokens)
[ "def", "load", "(", "stream", ")", ":", "if", "isinstance", "(", "stream", ",", "str", ")", ":", "string", "=", "stream", "else", ":", "string", "=", "stream", ".", "read", "(", ")", "tokens", "=", "tokenize", "(", "string", ")", "return", "parse", ...
31.444444
13
def list_commands_audit(self, from_sec=None, to_sec=None, scope_filter=None, command_filter=None, limit=100, offset=0, metrics=[]): '''**Description** List the commands audit. **Arguments** - from_sec: the start of the timerange for which to get commands audit. - end...
[ "def", "list_commands_audit", "(", "self", ",", "from_sec", "=", "None", ",", "to_sec", "=", "None", ",", "scope_filter", "=", "None", ",", "command_filter", "=", "None", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "metrics", "=", "[", "]",...
63.677419
41.741935
def iter_code_frequency(self, number=-1, etag=None): """Iterate over the code frequency per week. Returns a weekly aggregate of the number of additions and deletions pushed to this repository. :param int number: (optional), number of weeks to return. Default: -1 returns all...
[ "def", "iter_code_frequency", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'stats'", ",", "'code_frequency'", ",", "base_url", "=", "self", ".", "_api", ")", "return", "self...
42.521739
26.217391
def replace_component(self, name, callable, provides=None, depends=None): """Changes an existing component with a given name, invalidating all the values computed by the previous component and its successors.""" self.remove_component(name) self.add_component(name, callable, provides, dep...
[ "def", "replace_component", "(", "self", ",", "name", ",", "callable", ",", "provides", "=", "None", ",", "depends", "=", "None", ")", ":", "self", ".", "remove_component", "(", "name", ")", "self", ".", "add_component", "(", "name", ",", "callable", ","...
64.2
11.8
def jsonify(py_data, default=None, indent=4, sort_keys=True): """ Converts the inputted Python data to JSON format. :param py_data | <variant> """ return json.dumps(py_data, default=py2json, indent=indent, sort_keys=sort_keys)
[ "def", "jsonify", "(", "py_data", ",", "default", "=", "None", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", ":", "return", "json", ".", "dumps", "(", "py_data", ",", "default", "=", "py2json", ",", "indent", "=", "indent", ",", "sort_...
35.714286
16.857143
def du(path): ''' Put it all together! ''' size, err = calc(path) if err: return err else: hr, unit = convert(size) hr = str(hr) result = hr + " " + unit return result
[ "def", "du", "(", "path", ")", ":", "size", ",", "err", "=", "calc", "(", "path", ")", "if", "err", ":", "return", "err", "else", ":", "hr", ",", "unit", "=", "convert", "(", "size", ")", "hr", "=", "str", "(", "hr", ")", "result", "=", "hr",...
18.333333
21.666667
def read_list(self, request): """ :param request: an apiv2 request object :return: request if successful with entities set on request """ request_filters = request.context_params.get( self.request_filters_property, {}) request_filters.update(**self.get_limit_a...
[ "def", "read_list", "(", "self", ",", "request", ")", ":", "request_filters", "=", "request", ".", "context_params", ".", "get", "(", "self", ".", "request_filters_property", ",", "{", "}", ")", "request_filters", ".", "update", "(", "*", "*", "self", ".",...
45.5
19.590909
def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None): """Iterate over proxy servers found in the raw data""" if not isinstance(data, six.text_type): data = data.decode('utf-8') for orig_line in data.splitlines(): line = orig_line.strip().replace(' ', '') if line and n...
[ "def", "parse_raw_list_data", "(", "data", ",", "proxy_type", "=", "'http'", ",", "proxy_userpwd", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "data", "=", "data", ".", "decode", "(", "'utf-8'", ...
47.866667
14.8
def gcd(*numbers): """ Returns the greatest common divisor for a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Greatest common divisor of numbers. """ n = numbers[0] for i in numbers: n = pygcd(n, i) return n
[ "def", "gcd", "(", "*", "numbers", ")", ":", "n", "=", "numbers", "[", "0", "]", "for", "i", "in", "numbers", ":", "n", "=", "pygcd", "(", "n", ",", "i", ")", "return", "n" ]
20.071429
20.214286
def get_weekly_charts(self, chart_kind, from_date=None, to_date=None): """ Returns the weekly charts for the week starting from the from_date value to the to_date value. chart_kind should be one of "album", "artist" or "track" """ method = ".getWeekly" + chart_kind.title(...
[ "def", "get_weekly_charts", "(", "self", ",", "chart_kind", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ")", ":", "method", "=", "\".getWeekly\"", "+", "chart_kind", ".", "title", "(", ")", "+", "\"Chart\"", "chart_type", "=", "eval", "(", ...
37.642857
19.714286
def Write3DData(self, data3d, path, filetype='auto', metadata=None, progress_callback=None, sfin=True): """ :param data3d: input ndarray data :param path: output path, to specify slice number advanced formatting options (like {:06d}) can be used Check function filename_format() for more ...
[ "def", "Write3DData", "(", "self", ",", "data3d", ",", "path", ",", "filetype", "=", "'auto'", ",", "metadata", "=", "None", ",", "progress_callback", "=", "None", ",", "sfin", "=", "True", ")", ":", "self", ".", "orig_path", "=", "path", "path", "=", ...
37.227848
21.151899
def get_clan_image(self, obj: BaseAttrDict): """Get the clan badge image URL Parameters --------- obj: official_api.models.BaseAttrDict An object that has the clan badge ID either in ``.clan.badge_id`` or ``.badge_id`` Can be a clan or a profile for example. ...
[ "def", "get_clan_image", "(", "self", ",", "obj", ":", "BaseAttrDict", ")", ":", "try", ":", "badge_id", "=", "obj", ".", "clan", ".", "badge_id", "except", "AttributeError", ":", "try", ":", "badge_id", "=", "obj", ".", "badge_id", "except", "AttributeErr...
31.423077
19.884615
def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs): """Plot an outline of the FOV. """ if maptype is None: maptype=self.defaultMap xarr = [] yarr = [] radec = self.currentRaDec for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]: ...
[ "def", "plotOutline", "(", "self", ",", "maptype", "=", "None", ",", "colour", "=", "'#AAAAAA'", ",", "*", "*", "kwargs", ")", ":", "if", "maptype", "is", "None", ":", "maptype", "=", "self", ".", "defaultMap", "xarr", "=", "[", "]", "yarr", "=", "...
33.230769
17.730769
def hamming_calc(TP, POP): """ Calculate hamming loss. :param TP: true positive :type TP : dict :param POP: population :type POP : int :return: hamming loss as float """ try: length = POP return (1 / length) * (length - sum(TP.values())) except Exception: ...
[ "def", "hamming_calc", "(", "TP", ",", "POP", ")", ":", "try", ":", "length", "=", "POP", "return", "(", "1", "/", "length", ")", "*", "(", "length", "-", "sum", "(", "TP", ".", "values", "(", ")", ")", ")", "except", "Exception", ":", "return", ...
21.333333
16.533333
def get_corrector_f(rinput, meta, ins, datamodel): """Corrector for intensity flat""" from emirdrp.processing.flatfield import FlatFieldCorrector flat_info = meta['master_flat'] with rinput.master_flat.open() as hdul: _logger.info('loading intensity flat') _logger.debug('flat info: %s', ...
[ "def", "get_corrector_f", "(", "rinput", ",", "meta", ",", "ins", ",", "datamodel", ")", ":", "from", "emirdrp", ".", "processing", ".", "flatfield", "import", "FlatFieldCorrector", "flat_info", "=", "meta", "[", "'master_flat'", "]", "with", "rinput", ".", ...
42.3
14.8