text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def fromHexString(value): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ r = [] p = [] for v in value: if p: r.append(int(p + v,...
[ "def", "fromHexString", "(", "value", ")", ":", "r", "=", "[", "]", "p", "=", "[", "]", "for", "v", "in", "value", ":", "if", "p", ":", "r", ".", "append", "(", "int", "(", "p", "+", "v", ",", "16", ")", ")", "p", "=", "None", "else", ":"...
23
0.004175
def login_form_factory(Form, app): """Return extended login form.""" class LoginForm(Form): def __init__(self, *args, **kwargs): """Init the login form. .. note:: The ``remember me`` option will be completely disabled. """ super(LoginFor...
[ "def", "login_form_factory", "(", "Form", ",", "app", ")", ":", "class", "LoginForm", "(", "Form", ")", ":", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Init the login form.\n\n .. note::\n\n ...
26.733333
0.00241
def setup(app): """Setup sphinx-gallery sphinx extension""" app.add_config_value('plot_gallery', True, 'html') app.add_config_value('abort_on_example_error', False, 'html') app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html') app.add_stylesheet('gallery.css') app.connect('builder-i...
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_config_value", "(", "'plot_gallery'", ",", "True", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'abort_on_example_error'", ",", "False", ",", "'html'", ")", "app", ".", "add_config_value", "...
39.3
0.002488
def find(self, compile_failure_log, target): """Find missing deps on a best-effort basis from target's transitive dependencies. Returns (class2deps, no_dep_found) tuple. `class2deps` contains classname to deps that contain the class mapping. `no_dep_found` are the classnames that are unable to find the...
[ "def", "find", "(", "self", ",", "compile_failure_log", ",", "target", ")", ":", "not_found_classnames", "=", "[", "err", ".", "classname", "for", "err", "in", "self", ".", "compile_error_extractor", ".", "extract", "(", "compile_failure_log", ")", "]", "retur...
54.7
0.008993
def metrics_api(self): """Helper for log metric-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics """ if self._metrics_api is None: if self._use_grpc: self._metrics_api = _gapic.make_metrics_api(self) ...
[ "def", "metrics_api", "(", "self", ")", ":", "if", "self", ".", "_metrics_api", "is", "None", ":", "if", "self", ".", "_use_grpc", ":", "self", ".", "_metrics_api", "=", "_gapic", ".", "make_metrics_api", "(", "self", ")", "else", ":", "self", ".", "_m...
34.583333
0.004695
def find_element_by_id(self, id_, update=False) -> Elements: '''Finds an element by id. Args: id_: The id of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: ...
[ "def", "find_element_by_id", "(", "self", ",", "id_", ",", "update", "=", "False", ")", "->", "Elements", ":", "return", "self", ".", "find_element", "(", "by", "=", "By", ".", "ID", ",", "value", "=", "id_", ",", "update", "=", "update", ")" ]
30.470588
0.003745
def get_column_index(self, header): """Get index of a column from it's header. Parameters ---------- header: str header of the column. Raises ------ ValueError: If no column could be found corresponding to `header`. """ tr...
[ "def", "get_column_index", "(", "self", ",", "header", ")", ":", "try", ":", "index", "=", "self", ".", "_column_headers", ".", "index", "(", "header", ")", "return", "index", "except", "ValueError", ":", "raise_suppressed", "(", "KeyError", "(", "(", "\"'...
28.842105
0.003534
def exit(self, timeperiods, hosts, services): """Remove ref in scheduled downtime and raise downtime log entry (exit) :param hosts: hosts objects to get item ref :type hosts: alignak.objects.host.Hosts :param services: services objects to get item ref :type services: alignak.obj...
[ "def", "exit", "(", "self", ",", "timeperiods", ",", "hosts", ",", "services", ")", ":", "if", "self", ".", "ref", "in", "hosts", ":", "item", "=", "hosts", "[", "self", ".", "ref", "]", "else", ":", "item", "=", "services", "[", "self", ".", "re...
44.673469
0.003129
def delete(self, historics_id): """ Delete one specified playback query. If the query is currently running, stop it. status_code is set to 204 on success Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete :param historics_id: playbac...
[ "def", "delete", "(", "self", ",", "historics_id", ")", ":", "return", "self", ".", "request", ".", "post", "(", "'delete'", ",", "data", "=", "dict", "(", "id", "=", "historics_id", ")", ")" ]
49.428571
0.007092
def read_voltages(self, voltage_file): """import voltages from a volt.dat file Parameters ---------- voltage_file : string Path to volt.dat file """ measurements_raw = np.loadtxt( voltage_file, skiprows=1, ) measuremen...
[ "def", "read_voltages", "(", "self", ",", "voltage_file", ")", ":", "measurements_raw", "=", "np", ".", "loadtxt", "(", "voltage_file", ",", "skiprows", "=", "1", ",", ")", "measurements", "=", "np", ".", "atleast_2d", "(", "measurements_raw", ")", "# extrac...
37.181818
0.000794
def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'): """Solve nonlinear system using safeguarded Newton iterations Parameters ---------- Return ------ """ if verbose: print = lambda txt: old_print(txt) else: print = lambda txt: None it = 0 e...
[ "def", "newton", "(", "f", ",", "x", ",", "verbose", "=", "False", ",", "tol", "=", "1e-6", ",", "maxit", "=", "5", ",", "jactype", "=", "'serial'", ")", ":", "if", "verbose", ":", "print", "=", "lambda", "txt", ":", "old_print", "(", "txt", ")",...
19.774648
0.005427
def createDAM(dam_name, config): ''' create DAM ''' if 'yahoo' == dam_name: from analyzerdam.yahooDAM import YahooDAM dam=YahooDAM() elif 'google' == dam_name: from analyzerdam.google import GoogleDAM dam=GoogleDAM() elif 'excel' ==...
[ "def", "createDAM", "(", "dam_name", ",", "config", ")", ":", "if", "'yahoo'", "==", "dam_name", ":", "from", "analyzerdam", ".", "yahooDAM", "import", "YahooDAM", "dam", "=", "YahooDAM", "(", ")", "elif", "'google'", "==", "dam_name", ":", "from", "analyz...
35.88
0.008686
def run_args(self): """ Pass in the parsed args to the script """ self.arg_parser = self._parse_args() self.args = self.arg_parser.parse_args() color_name = self.args.color if color_name is not None: color_name = color_name[0] symbol = self.arg...
[ "def", "run_args", "(", "self", ")", ":", "self", ".", "arg_parser", "=", "self", ".", "_parse_args", "(", ")", "self", ".", "args", "=", "self", ".", "arg_parser", ".", "parse_args", "(", ")", "color_name", "=", "self", ".", "args", ".", "color", "i...
31.928571
0.004348
def create(cls, options, session, build_root=None, exclude_patterns=None, tags=None): """ :param Options options: An `Options` instance to use. :param session: The Scheduler session :param string build_root: The build root. """ # Determine the literal target roots. spec_roots = cls.parse_spe...
[ "def", "create", "(", "cls", ",", "options", ",", "session", ",", "build_root", "=", "None", ",", "exclude_patterns", "=", "None", ",", "tags", "=", "None", ")", ":", "# Determine the literal target roots.", "spec_roots", "=", "cls", ".", "parse_specs", "(", ...
46.875
0.011753
def ip(ip_address, return_format=None): """Returns a summary of the information our database holds for a particular IP address (similar to /ipinfo.html). In the returned data: Count: (also reports or records) total number of packets blocked from this IP. Attacks: (also targets) number of uniqu...
[ "def", "ip", "(", "ip_address", ",", "return_format", "=", "None", ")", ":", "response", "=", "_get", "(", "'ip/{address}'", ".", "format", "(", "address", "=", "ip_address", ")", ",", "return_format", ")", "if", "'bad IP address'", "in", "str", "(", "resp...
35.166667
0.001538
def host_stanzas(self, config_access): """ returns a list of host definitions """ defn_lines = self.resolve_defn(config_access) for val_dict in self.variable_iter(config_access.get_variables()): subst = list(self.apply_substitutions(defn_lines, val_dict)) ...
[ "def", "host_stanzas", "(", "self", ",", "config_access", ")", ":", "defn_lines", "=", "self", ".", "resolve_defn", "(", "config_access", ")", "for", "val_dict", "in", "self", ".", "variable_iter", "(", "config_access", ".", "get_variables", "(", ")", ")", "...
42.7
0.004587
def ExecuteCmd(cmd, quiet=False): """ Run a command in a shell. """ result = None if quiet: with open(os.devnull, "w") as fnull: result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull) else: result = subprocess.call(cmd, shell=True) return result
[ "def", "ExecuteCmd", "(", "cmd", ",", "quiet", "=", "False", ")", ":", "result", "=", "None", "if", "quiet", ":", "with", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "as", "fnull", ":", "result", "=", "subprocess", ".", "call", "(", "cmd"...
30.666667
0.024648
def partial_derivative(self, X, y=0): """Compute partial derivative :math:`C(u|v)` of cumulative density. Args: X: `np.ndarray` y: `float` Returns: """ self.check_fit() U, V = self.split_matrix(X) if self.theta == 1: return...
[ "def", "partial_derivative", "(", "self", ",", "X", ",", "y", "=", "0", ")", ":", "self", ".", "check_fit", "(", ")", "U", ",", "V", "=", "self", ".", "split_matrix", "(", "X", ")", "if", "self", ".", "theta", "==", "1", ":", "return", "V", "el...
27.041667
0.002976
def _rotate_point(point, angle, ishape, rshape, reverse=False): """Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image. This works on a simple rotation transformation:: newx = (startx) * np.cos(angle) ...
[ "def", "_rotate_point", "(", "point", ",", "angle", ",", "ishape", ",", "rshape", ",", "reverse", "=", "False", ")", ":", "# unpack the image and rotated images shapes", "if", "reverse", ":", "angle", "=", "(", "angle", "*", "-", "1", ")", "temp", "=", "i...
27.492308
0.00054
def is_any_type_set(sett: Set[Type]) -> bool: """ Helper method to check if a set of types is the {AnyObject} singleton :param sett: :return: """ return len(sett) == 1 and is_any_type(min(sett))
[ "def", "is_any_type_set", "(", "sett", ":", "Set", "[", "Type", "]", ")", "->", "bool", ":", "return", "len", "(", "sett", ")", "==", "1", "and", "is_any_type", "(", "min", "(", "sett", ")", ")" ]
26.5
0.004566
def create_migration(self, repos, lock_repositories=github.GithubObject.NotSet, exclude_attachments=github.GithubObject.NotSet): """ :calls: `POST /user/migrations`_ :param repos: list or tuple of str :param lock_repositories: bool :param exclude_attachments: bool :rtype:...
[ "def", "create_migration", "(", "self", ",", "repos", ",", "lock_repositories", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "exclude_attachments", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "isinstance", "(", "repos", ",...
50.321429
0.004178
def vel_disp_one(self, gamma, rho0_r0_gamma, r_eff, r_ani, R_slit, dR_slit, FWHM): """ computes one realisation of the velocity dispersion realized in the slit :param gamma: power-law slope of the mass profile (isothermal = 2) :param rho0_r0_gamma: combination of Einstein radius and pow...
[ "def", "vel_disp_one", "(", "self", ",", "gamma", ",", "rho0_r0_gamma", ",", "r_eff", ",", "r_ani", ",", "R_slit", ",", "dR_slit", ",", "FWHM", ")", ":", "a", "=", "0.551", "*", "r_eff", "while", "True", ":", "r", "=", "self", ".", "P_r", "(", "a",...
54.26087
0.006299
def __write_view_tmpl(tag_key, tag_list): ''' Generate the HTML file for viewing. :param tag_key: key of the tags. :param tag_list: list of the tags. :return: None ''' view_file = os.path.join(OUT_DIR, 'view', 'view_' + tag_key.split('_')[1] + '.html') view_widget_arr = [] for sig in...
[ "def", "__write_view_tmpl", "(", "tag_key", ",", "tag_list", ")", ":", "view_file", "=", "os", ".", "path", ".", "join", "(", "OUT_DIR", ",", "'view'", ",", "'view_'", "+", "tag_key", ".", "split", "(", "'_'", ")", "[", "1", "]", "+", "'.html'", ")",...
35.645833
0.001706
def from_pandas(df, name="pandas", copy_index=True, index_name="index"): """Create an in memory DataFrame from a pandas DataFrame. :param: pandas.DataFrame df: Pandas DataFrame :param: name: unique for the DataFrame >>> import vaex, pandas as pd >>> df_pandas = pd.from_csv('test.csv') >>> df =...
[ "def", "from_pandas", "(", "df", ",", "name", "=", "\"pandas\"", ",", "copy_index", "=", "True", ",", "index_name", "=", "\"index\"", ")", ":", "import", "six", "vaex_df", "=", "vaex", ".", "dataframe", ".", "DataFrameArrays", "(", "name", ")", "def", "a...
32.580645
0.001923
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
[ "def", "set_color", "(", "index", ",", "color", ")", ":", "if", "OS", "==", "\"Darwin\"", "and", "index", "<", "20", ":", "return", "\"\\033]P%1x%s\\033\\\\\"", "%", "(", "index", ",", "color", ".", "strip", "(", "\"#\"", ")", ")", "return", "\"\\033]4;%...
38.333333
0.004255
def load_sgraph(filename, format='binary', delimiter='auto'): """ Load SGraph from text file or previously saved SGraph binary. Parameters ---------- filename : string Location of the file. Can be a local path or a remote URL. format : {'binary', 'snap', 'csv', 'tsv'}, optional ...
[ "def", "load_sgraph", "(", "filename", ",", "format", "=", "'binary'", ",", "delimiter", "=", "'auto'", ")", ":", "if", "not", "format", "in", "[", "'binary'", ",", "'snap'", ",", "'csv'", ",", "'tsv'", "]", ":", "raise", "ValueError", "(", "'Invalid for...
34
0.003314
def XXX_REMOVEME(func): """Decorator for dead code removal """ @wraps(func) def decorator(self, *args, **kwargs): msg = "~~~~~~~ XXX REMOVEME marked method called: {}.{}".format( self.__class__.__name__, func.func_name) raise RuntimeError(msg) return func(self, *args,...
[ "def", "XXX_REMOVEME", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "\"~~~~~~~ XXX REMOVEME marked method called: {}.{}\"", ".", "format", "(", "sel...
34.2
0.002849
def is_return_doc_available(self): """Returns True if this method's return is documented""" return bool(self.return_doc and (self.return_doc.get('text') or self.return_doc.get('type')))
[ "def", "is_return_doc_available", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "return_doc", "and", "(", "self", ".", "return_doc", ".", "get", "(", "'text'", ")", "or", "self", ".", "return_doc", ".", "get", "(", "'type'", ")", ")", ")" ...
66.333333
0.014925
def contraction_beveled(Di1, Di2, l=None, angle=None): r'''Returns loss coefficient for any sharp beveled pipe contraction as shown in [1]_. .. math:: K = 0.0696[1+C_B(\sin(\alpha/2)-1)](1-\beta^5)\lambda^2 + (\lambda-1)^2 .. math:: \lambda = 1 + 0.622\left[1+C_B\left(\left(\frac{\alph...
[ "def", "contraction_beveled", "(", "Di1", ",", "Di2", ",", "l", "=", "None", ",", "angle", "=", "None", ")", ":", "angle", "=", "radians", "(", "angle", ")", "beta", "=", "Di2", "/", "Di1", "CB", "=", "l", "/", "Di2", "*", "2.0", "*", "beta", "...
28.052632
0.002417
def handle_roster_push(self, stanza): """Handle a roster push received from server. """ if self.server is None and stanza.from_jid: logger.debug(u"Server address not known, cannot verify roster push" " from {0}".format(stanza.from_jid)) ret...
[ "def", "handle_roster_push", "(", "self", ",", "stanza", ")", ":", "if", "self", ".", "server", "is", "None", "and", "stanza", ".", "from_jid", ":", "logger", ".", "debug", "(", "u\"Server address not known, cannot verify roster push\"", "\" from {0}\"", ".", "for...
50.517241
0.004019
def set_color_temperature(self, temperature, effect=EFFECT_SUDDEN, transition_time=MIN_TRANSITION_TIME): """ Set the white color temperature. The bulb must be switched on. :param temperature: color temperature to set. It can be between 1700 and 6500 K :param effect: if the c...
[ "def", "set_color_temperature", "(", "self", ",", "temperature", ",", "effect", "=", "EFFECT_SUDDEN", ",", "transition_time", "=", "MIN_TRANSITION_TIME", ")", ":", "# Check bulb state", "if", "self", ".", "is_off", "(", ")", ":", "raise", "Exception", "(", "\"se...
51.92
0.005295
def enqueue_request(self, request): ''' Pushes a request from the spider into the proper throttled queue ''' if not request.dont_filter and self.dupefilter.request_seen(request): self.logger.debug("Request not added back to redis") return req_dict = self.r...
[ "def", "enqueue_request", "(", "self", ",", "request", ")", ":", "if", "not", "request", ".", "dont_filter", "and", "self", ".", "dupefilter", ".", "request_seen", "(", "request", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Request not added back ...
49.627451
0.003487
def Import(context, request): """ Read Dimensional-CSV analysis results """ form = request.form # TODO form['file'] sometimes returns a list infile = form['instrument_results_file'][0] if \ isinstance(form['instrument_results_file'], list) else \ form['instrument_results_file'] a...
[ "def", "Import", "(", "context", ",", "request", ")", ":", "form", "=", "request", ".", "form", "# TODO form['file'] sometimes returns a list", "infile", "=", "form", "[", "'instrument_results_file'", "]", "[", "0", "]", "if", "isinstance", "(", "form", "[", "...
34.302326
0.001318
def changelist_view(self, request, extra_context=None): """Add advanced_filters form to changelist context""" if extra_context is None: extra_context = {} response = self.adv_filters_handle(request, extra_context=extra_context) if re...
[ "def", "changelist_view", "(", "self", ",", "request", ",", "extra_context", "=", "None", ")", ":", "if", "extra_context", "is", "None", ":", "extra_context", "=", "{", "}", "response", "=", "self", ".", "adv_filters_handle", "(", "request", ",", "extra_cont...
47.6
0.004124
def _set_modId(self, v, load=False): """ Setter method for modId, mapped from YANG variable /logging/raslog/module/modId (list) If this variable is read-only (config: false) in the source YANG file, then _set_modId is considered as a private method. Backends looking to populate this variable should ...
[ "def", "_set_modId", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
102.090909
0.004411
def get_modelinsertion(cls, model, indent) -> str: """Return the insertion string required for the given application model. >>> from hydpy.auxs.xmltools import XSDWriter >>> from hydpy import prepare_model >>> model = prepare_model('hland_v1') >>> print(XSDWriter.get_modelinsert...
[ "def", "get_modelinsertion", "(", "cls", ",", "model", ",", "indent", ")", "->", "str", ":", "texts", "=", "[", "]", "for", "name", "in", "(", "'inputs'", ",", "'fluxes'", ",", "'states'", ")", ":", "subsequences", "=", "getattr", "(", "model", ".", ...
35.3125
0.003445
def is_satisfied_by(self, candidate: Any, **kwds: Any) -> bool: """Return True if `candidate` satisfies the specification.""" candidate_name = self._candidate_name context = self._context if context: if candidate_name in kwds: raise ValueError(f"Candidate name...
[ "def", "is_satisfied_by", "(", "self", ",", "candidate", ":", "Any", ",", "*", "*", "kwds", ":", "Any", ")", "->", "bool", ":", "candidate_name", "=", "self", ".", "_candidate_name", "context", "=", "self", ".", "_context", "if", "context", ":", "if", ...
43.8
0.002981
def updatefile(self, project_id, file_path, branch_name, content, commit_message): """ Updates an existing file in the repository :param project_id: project id :param file_path: Full path to new file. Ex. lib/class.rb :param branch_name: The name of branch :param content...
[ "def", "updatefile", "(", "self", ",", "project_id", ",", "file_path", ",", "branch_name", ",", "content", ",", "commit_message", ")", ":", "data", "=", "{", "'file_path'", ":", "file_path", ",", "'branch_name'", ":", "branch_name", ",", "'content'", ":", "c...
37.304348
0.004545
def flat_list(input_list): r""" Given a list of nested lists of arbitrary depth, returns a single level or 'flat' list. """ x = input_list if isinstance(x, list): return [a for i in x for a in flat_list(i)] else: return [x]
[ "def", "flat_list", "(", "input_list", ")", ":", "x", "=", "input_list", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "[", "a", "for", "i", "in", "x", "for", "a", "in", "flat_list", "(", "i", ")", "]", "else", ":", "return", "["...
23.454545
0.003731
def create(cls, data, **kwargs): """Create a new Workflow Object with given content.""" with db.session.begin_nested(): model = cls.dbmodel(**kwargs) model.data = data obj = cls(model) db.session.add(obj.model) return obj
[ "def", "create", "(", "cls", ",", "data", ",", "*", "*", "kwargs", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "model", "=", "cls", ".", "dbmodel", "(", "*", "*", "kwargs", ")", "model", ".", "data", "=", "data", ...
35.75
0.006826
def post_parse_action(self, entry): """separate hosts and ports after entry is parsed""" if 'source_host' in entry.keys(): host = self.ip_port_regex.findall(entry['source_host']) if host: hlist = host[0].split('.') entry['source_host'] = '.'.join(h...
[ "def", "post_parse_action", "(", "self", ",", "entry", ")", ":", "if", "'source_host'", "in", "entry", ".", "keys", "(", ")", ":", "host", "=", "self", ".", "ip_port_regex", ".", "findall", "(", "entry", "[", "'source_host'", "]", ")", "if", "host", ":...
41.1875
0.002967
def attach_(dev=None): ''' Attach a backing devices to a cache set If no dev is given, all backing devices will be attached. CLI example: .. code-block:: bash salt '*' bcache.attach sdc salt '*' bcache.attach /dev/bcache1 :return: bool or None if nuttin' happened ''' ...
[ "def", "attach_", "(", "dev", "=", "None", ")", ":", "cache", "=", "uuid", "(", ")", "if", "not", "cache", ":", "log", ".", "error", "(", "'No cache to attach %s to'", ",", "dev", ")", "return", "False", "if", "dev", "is", "None", ":", "res", "=", ...
26.522727
0.003306
def _date_by_len(self, string): """ Parses a date from a string based on its length :param string: A unicode string to parse :return: A datetime.datetime object or a unicode string """ strlen = len(string) year_num = int(string[0:2]) ...
[ "def", "_date_by_len", "(", "self", ",", "string", ")", ":", "strlen", "=", "len", "(", "string", ")", "year_num", "=", "int", "(", "string", "[", "0", ":", "2", "]", ")", "if", "year_num", "<", "50", ":", "prefix", "=", "'20'", "else", ":", "pre...
22.961538
0.003215
def get_identities(self, item): """ Return the identities from an item """ item = item['data'] for identity in ['creator']: # Todo: questions has also involved and solved_by if identity in item and item[identity]: user = self.get_sh_identity(item[identit...
[ "def", "get_identities", "(", "self", ",", "item", ")", ":", "item", "=", "item", "[", "'data'", "]", "for", "identity", "in", "[", "'creator'", "]", ":", "# Todo: questions has also involved and solved_by", "if", "identity", "in", "item", "and", "item", "[", ...
37.5
0.003717
def realimag_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs): """ Plots function(s) real and imaginary parts over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. ...
[ "def", "realimag_function", "(", "f", "=", "'1.0/(1+1j*x)'", ",", "xmin", "=", "-", "1", ",", "xmax", "=", "1", ",", "steps", "=", "200", ",", "p", "=", "'x'", ",", "g", "=", "None", ",", "erange", "=", "False", ",", "*", "*", "kwargs", ")", ":...
42.590909
0.008351
def parse(cls, msg): """Parse message string to response object.""" lines = msg.splitlines() version, status_code, reason = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, status_code=status_code, reason=reason, ...
[ "def", "parse", "(", "cls", ",", "msg", ")", ":", "lines", "=", "msg", ".", "splitlines", "(", ")", "version", ",", "status_code", ",", "reason", "=", "lines", "[", "0", "]", ".", "split", "(", ")", "headers", "=", "cls", ".", "parse_headers", "(",...
47.142857
0.005952
def addContentLen(self, content, len): """Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported. """ libxml2mod.xmlNo...
[ "def", "addContentLen", "(", "self", ",", "content", ",", "len", ")", ":", "libxml2mod", ".", "xmlNodeAddContentLen", "(", "self", ".", "_o", ",", "content", ",", "len", ")" ]
58.833333
0.005587
def centers_of_labels(labels): '''Return the i,j coordinates of the centers of a labels matrix The result returned is an 2 x n numpy array where n is the number of the label minus one, result[0,x] is the i coordinate of the center and result[x,1] is the j coordinate of the center. You can unpac...
[ "def", "centers_of_labels", "(", "labels", ")", ":", "max_labels", "=", "np", ".", "max", "(", "labels", ")", "if", "max_labels", "==", "0", ":", "return", "np", ".", "zeros", "(", "(", "2", ",", "0", ")", ",", "int", ")", "result", "=", "scind", ...
37.4
0.007823
def delete(context, resource, id, **kwargs): """Delete a specific resource""" etag = kwargs.pop('etag', None) id = id subresource = kwargs.pop('subresource', None) subresource_id = kwargs.pop('subresource_id', None) uri = '%s/%s/%s' % (context.dci_cs_api, resource, id) if subresource: ...
[ "def", "delete", "(", "context", ",", "resource", ",", "id", ",", "*", "*", "kwargs", ")", ":", "etag", "=", "kwargs", ".", "pop", "(", "'etag'", ",", "None", ")", "id", "=", "id", "subresource", "=", "kwargs", ".", "pop", "(", "'subresource'", ","...
32.933333
0.001969
def compute_kv(self, memory_antecedent): """Compute key/value Tensor kv. Args: memory_antecedent: a Tensor with dimensions {memory_input_dim} + other_dims Returns: a Tensor with dimensions memory_heads_dims + {key_dim} + other_dims """ if not self.shared_kv: raise ...
[ "def", "compute_kv", "(", "self", ",", "memory_antecedent", ")", ":", "if", "not", "self", ".", "shared_kv", ":", "raise", "ValueError", "(", "\"compute_kv can only be called with shared_kv\"", ")", "ret", "=", "mtf", ".", "einsum", "(", "[", "memory_antecedent", ...
33.823529
0.005076
def get_object(self, queryset=None): """ Fetch the object using a translated slug. """ if queryset is None: queryset = self.get_queryset() slug = self.kwargs[self.slug_url_kwarg] choices = self.get_language_choices() obj = None using_fallback...
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "if", "queryset", "is", "None", ":", "queryset", "=", "self", ".", "get_queryset", "(", ")", "slug", "=", "self", ".", "kwargs", "[", "self", ".", "slug_url_kwarg", "]", "choices...
46.155556
0.005186
def run(self): """Main entrypoint method. Returns ------- new_nodes : `list` Nodes to add to the doctree. """ if getLogger is not None: # Sphinx 1.6+ logger = getLogger(__name__) else: # Previously Sphinx's app was ...
[ "def", "run", "(", "self", ")", ":", "if", "getLogger", "is", "not", "None", ":", "# Sphinx 1.6+", "logger", "=", "getLogger", "(", "__name__", ")", "else", ":", "# Previously Sphinx's app was also the logger", "logger", "=", "self", ".", "state", ".", "docume...
34.411765
0.001108
def roll(self, count=0): '''Roll some dice! :param count: [0] Return list of sums :return: A single sum or list of ``count`` sums ''' return super(FuncRoll, self).roll(count, self._func)
[ "def", "roll", "(", "self", ",", "count", "=", "0", ")", ":", "return", "super", "(", "FuncRoll", ",", "self", ")", ".", "roll", "(", "count", ",", "self", ".", "_func", ")" ]
36.833333
0.00885
def filter_silenced(self): ''' Determine whether a check is silenced and shouldn't handle. ''' stashes = [ ('client', '/silence/{}'.format(self.event['client']['name'])), ('check', '/silence/{}/{}'.format( self.event['client']['name'], ...
[ "def", "filter_silenced", "(", "self", ")", ":", "stashes", "=", "[", "(", "'client'", ",", "'/silence/{}'", ".", "format", "(", "self", ".", "event", "[", "'client'", "]", "[", "'name'", "]", ")", ")", ",", "(", "'check'", ",", "'/silence/{}/{}'", "."...
39.857143
0.003503
def integrate_predefined(rhs, jac, y0, xout, atol, rtol, jac_type="dense", dx0=.0, dx_min=.0, dx_max=.0, nsteps=500, method=None, nderiv=0, roots=None, nroots=0, check_callable=False, check_indexing=False, **kwargs): """ Integrates a system ...
[ "def", "integrate_predefined", "(", "rhs", ",", "jac", ",", "y0", ",", "xout", ",", "atol", ",", "rtol", ",", "jac_type", "=", "\"dense\"", ",", "dx0", "=", ".0", ",", "dx_min", "=", ".0", ",", "dx_max", "=", ".0", ",", "nsteps", "=", "500", ",", ...
44.547619
0.003486
def tag_list(package): """ List the tags of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/tag/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg )...
[ "def", "tag_list", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"{url}/api/tag/{owner}/{pkg}/\"", ".", ...
23.705882
0.002387
def install(self, destination): """ Install a third party odoo add-on :param string destination: the folder where the add-on should end up at. """ logger.info( "Installing %s@%s to %s", self.repo, self.commit if self.commit else self.branch, destination )...
[ "def", "install", "(", "self", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"Installing %s@%s to %s\"", ",", "self", ".", "repo", ",", "self", ".", "commit", "if", "self", ".", "commit", "else", "self", ".", "branch", ",", "destination", "...
38.583333
0.006329
def splitFile(inputFileName, linePerFile, outPrefix): """Split a file. :param inputFileName: the name of the input file. :param linePerFile: the number of line per file (after splitting). :param outPrefix: the prefix of the output files. :type inputFileName: str :type linePerFile: int :typ...
[ "def", "splitFile", "(", "inputFileName", ",", "linePerFile", ",", "outPrefix", ")", ":", "nbTmpFile", "=", "1", "nbLine", "=", "0", "tmpFile", "=", "None", "try", ":", "with", "open", "(", "inputFileName", ",", "\"r\"", ")", "as", "inputFile", ":", "for...
31.692308
0.000471
def rev_comp(seq): """Get reverse complement of sequence. rev_comp will maintain the case of the sequence. Parameters ---------- seq : str nucleotide sequence. valid {a, c, t, g, n} Returns ------- rev_comp_seq : str reverse complement of sequence """ rev_seq =...
[ "def", "rev_comp", "(", "seq", ")", ":", "rev_seq", "=", "seq", "[", ":", ":", "-", "1", "]", "rev_comp_seq", "=", "''", ".", "join", "(", "[", "base_pairing", "[", "s", "]", "for", "s", "in", "rev_seq", "]", ")", "return", "rev_comp_seq" ]
22.222222
0.002398
def atstart(callback, *args, **kwargs): '''Schedule a callback to run before the main hook. Callbacks are run in the order they were added. This is useful for modules and classes to perform initialization and inject behavior. In particular: - Run common code before all of your hooks, such as ...
[ "def", "atstart", "(", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_atstart", "_atstart", ".", "append", "(", "(", "callback", ",", "args", ",", "kwargs", ")", ")" ]
41.809524
0.001114
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credentials') and self.credentials is not None: _dict['credentials'] = [x._to_dict() for x in self.credentials] return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'credentials'", ")", "and", "self", ".", "credentials", "is", "not", "None", ":", "_dict", "[", "'credentials'", "]", "=", "[", "x", ".", "_to_dict"...
44.666667
0.007326
def _list_to_set(self, list_key, set_key): """ Store all content of the given ListField in a redis set. Use scripting if available to avoid retrieving all values locally from the list before sending them back to the set """ if self.cls.database.support_scripting(): ...
[ "def", "_list_to_set", "(", "self", ",", "list_key", ",", "set_key", ")", ":", "if", "self", ".", "cls", ".", "database", ".", "support_scripting", "(", ")", ":", "self", ".", "cls", ".", "database", ".", "call_script", "(", "# be sure to use the script dict...
44.0625
0.002778
def async_raise(self, exc_type): """Raise the exception.""" # Should only be called on a started thread, so raise otherwise. assert self.ident is not None, 'Only started threads have thread identifier' # If the thread has died we don't want to raise an exception so log. if not self.is_alive(): ...
[ "def", "async_raise", "(", "self", ",", "exc_type", ")", ":", "# Should only be called on a started thread, so raise otherwise.", "assert", "self", ".", "ident", "is", "not", "None", ",", "'Only started threads have thread identifier'", "# If the thread has died we don't want to ...
48.380952
0.008687
def databoxes(ds, xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_data, transpose=False, **kwargs): """ Plots the listed databox objects with the specified scripts. ds list of databoxes xscript script for x data yscript script for y data eyscript script for y ...
[ "def", "databoxes", "(", "ds", ",", "xscript", "=", "0", ",", "yscript", "=", "1", ",", "eyscript", "=", "None", ",", "exscript", "=", "None", ",", "g", "=", "None", ",", "plotter", "=", "xy_data", ",", "transpose", "=", "False", ",", "*", "*", "...
37.894737
0.012994
def name(self, src=None): """Return string representing the name of this type.""" if len(self._types) > 1: return "!(%s)" % str("|".join(_get_type_name(tt, src) for tt in self._types)) else: return "!" + _get_type_name(self._types[0], src)
[ "def", "name", "(", "self", ",", "src", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_types", ")", ">", "1", ":", "return", "\"!(%s)\"", "%", "str", "(", "\"|\"", ".", "join", "(", "_get_type_name", "(", "tt", ",", "src", ")", "for", ...
47
0.010453
def cat(self, out_ndx=None): """Concatenate input index files. Generate a new index file that contains the default Gromacs index groups (if a structure file was defined) and all index groups from the input index files. :Arguments: out_ndx : filename Nam...
[ "def", "cat", "(", "self", ",", "out_ndx", "=", "None", ")", ":", "if", "out_ndx", "is", "None", ":", "out_ndx", "=", "self", ".", "output", "self", ".", "make_ndx", "(", "o", "=", "out_ndx", ",", "input", "=", "[", "'q'", "]", ")", "return", "ou...
35.25
0.003454
def while_stmt(self, while_loc, test, while_colon_loc, body, else_opt): """while_stmt: 'while' test ':' suite ['else' ':' suite]""" stmt = ast.While(test=test, body=body, orelse=[], keyword_loc=while_loc, while_colon_loc=while_colon_loc, else_loc=None, e...
[ "def", "while_stmt", "(", "self", ",", "while_loc", ",", "test", ",", "while_colon_loc", ",", "body", ",", "else_opt", ")", ":", "stmt", "=", "ast", ".", "While", "(", "test", "=", "test", ",", "body", "=", "body", ",", "orelse", "=", "[", "]", ","...
50.818182
0.005272
def _tree_store_sub_branch(self, traj_node, branch_name, store_data=pypetconstants.STORE_DATA, with_links=True, recursive=False, max_depth=None, hdf5_group=None): ...
[ "def", "_tree_store_sub_branch", "(", "self", ",", "traj_node", ",", "branch_name", ",", "store_data", "=", "pypetconstants", ".", "STORE_DATA", ",", "with_links", "=", "True", ",", "recursive", "=", "False", ",", "max_depth", "=", "None", ",", "hdf5_group", "...
42.39604
0.007074
def infofile_path(self): """ :return: :rtype: str """ return os.path.normpath(os.path.join( self.dest_path, self.config.info_file ))
[ "def", "infofile_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "dest_path", ",", "self", ".", "config", ".", "info_file", ")", ")" ]
21.777778
0.009804
def GetText(text='', entry_text='', password=False, **kwargs): """Get some text from the user. This will raise a Zenity Text Entry Dialog. It returns the text the user entered or None if the user hit cancel. text - A description of the text to enter. entry_text - The initial value of the text en...
[ "def", "GetText", "(", "text", "=", "''", ",", "entry_text", "=", "''", ",", "password", "=", "False", ",", "*", "*", "kwargs", ")", ":", "args", "=", "[", "]", "if", "text", ":", "args", ".", "append", "(", "'--text=%s'", "%", "text", ")", "if",...
31.407407
0.002288
def process_data(self, fname, tokenizer, max_size): """ Loads data from the input file. :param fname: input file name :param tokenizer: tokenizer :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ ...
[ "def", "process_data", "(", "self", ",", "fname", ",", "tokenizer", ",", "max_size", ")", ":", "logging", ".", "info", "(", "f'Processing data from {fname}'", ")", "data", "=", "[", "]", "with", "open", "(", "fname", ")", "as", "dfile", ":", "for", "idx"...
35.368421
0.002899
def get_axes_layout(self, figure_list): """ returns the axes objects the script needs to plot its data the default creates a single axes object on each figure This can/should be overwritten in a child script if more axes objects are needed Args: figure_list: a list of...
[ "def", "get_axes_layout", "(", "self", ",", "figure_list", ")", ":", "axes_list", "=", "[", "]", "if", "self", ".", "_plot_refresh", "is", "True", ":", "for", "fig", "in", "figure_list", ":", "fig", ".", "clf", "(", ")", "axes_list", ".", "append", "("...
31.454545
0.004208
def _create_external_tool(self, context, context_id, json_data): """ Create an external tool using the passed json_data. context is either COURSES_API or ACCOUNTS_API. context_id is the Canvas course_id or account_id, depending on context. https://canvas.instructure.com/doc/api...
[ "def", "_create_external_tool", "(", "self", ",", "context", ",", "context_id", ",", "json_data", ")", ":", "url", "=", "context", ".", "format", "(", "context_id", ")", "+", "\"/external_tools\"", "return", "self", ".", "_post_resource", "(", "url", ",", "b...
44.363636
0.004016
def format_usage(self, usage=None): """Return a formatted usage string. If usage is None, use self.docs['usage'], and if that is also None, generate one. """ if usage is None: usage = self.docs['usage'] if usage is not None: return usage...
[ "def", "format_usage", "(", "self", ",", "usage", "=", "None", ")", ":", "if", "usage", "is", "None", ":", "usage", "=", "self", ".", "docs", "[", "'usage'", "]", "if", "usage", "is", "not", "None", ":", "return", "usage", "[", "0", "]", "%", "se...
34.538462
0.006501
def dump(exif_dict_original): """ py:function:: piexif.load(data) Return exif as bytes. :param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbnail":bytes}) :return: Exif :rtype: bytes """ exif_dict = copy.deepcopy(exif_dict_original) he...
[ "def", "dump", "(", "exif_dict_original", ")", ":", "exif_dict", "=", "copy", ".", "deepcopy", "(", "exif_dict_original", ")", "header", "=", "b\"Exif\\x00\\x00\\x4d\\x4d\\x00\\x2a\\x00\\x00\\x00\\x08\"", "exif_is", "=", "False", "gps_is", "=", "False", "interop_is", ...
38.359712
0.000731
def show_script_error(self, parent): """ Show the last script error (if any) """ if self.service.scriptRunner.error != '': dlg = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK, message_format=self.service.scriptRun...
[ "def", "show_script_error", "(", "self", ",", "parent", ")", ":", "if", "self", ".", "service", ".", "scriptRunner", ".", "error", "!=", "''", ":", "dlg", "=", "Gtk", ".", "MessageDialog", "(", "type", "=", "Gtk", ".", "MessageType", ".", "INFO", ",", ...
42.428571
0.009879
def add_context(self, context, label=None): """Append `context` to model Arguments: context (dict): Serialised to add Schema: context.json """ assert isinstance(context, dict) item = defaults["common"].copy() item.update(defaults["inst...
[ "def", "add_context", "(", "self", ",", "context", ",", "label", "=", "None", ")", ":", "assert", "isinstance", "(", "context", ",", "dict", ")", "item", "=", "defaults", "[", "\"common\"", "]", ".", "copy", "(", ")", "item", ".", "update", "(", "def...
25.115385
0.00295
def get_occupied_slots(instance): """ Return a list of slots for which values have been set. (While a slot might be defined, if a value for that slot hasn't been set, then it's an AttributeError to request the slot's value.) """ return [slot for slot in get_all_slots(type(instance)) ...
[ "def", "get_occupied_slots", "(", "instance", ")", ":", "return", "[", "slot", "for", "slot", "in", "get_all_slots", "(", "type", "(", "instance", ")", ")", "if", "hasattr", "(", "instance", ",", "slot", ")", "]" ]
34.2
0.005698
async def get_cred_infos_by_filter(self, filt: dict = None) -> str: """ Return cred-info (json list) from wallet by input filter for schema identifier and/or credential definition identifier components; return info of all credentials for no filter. Raise WalletState if the walle...
[ "async", "def", "get_cred_infos_by_filter", "(", "self", ",", "filt", ":", "dict", "=", "None", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'HolderProver.get_cred_infos_by_filter >>> filt: %s'", ",", "filt", ")", "if", "not", "self", ".", "wallet", "....
35.865385
0.003653
def get_supported(versions=None, noarch=False): """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. """ supported = [] # Version...
[ "def", "get_supported", "(", "versions", "=", "None", ",", "noarch", "=", "False", ")", ":", "supported", "=", "[", "]", "# Versions must be given with respect to the preference", "if", "versions", "is", "None", ":", "versions", "=", "[", "]", "major", "=", "s...
35.858696
0.000295
def StopPreviousService(self): """Stops the Windows service hosting the GRR process.""" StopService( service_name=config.CONFIG["Nanny.service_name"], service_binary_name=config.CONFIG["Nanny.service_binary_name"]) if not config.CONFIG["Client.fleetspeak_enabled"]: return StopSer...
[ "def", "StopPreviousService", "(", "self", ")", ":", "StopService", "(", "service_name", "=", "config", ".", "CONFIG", "[", "\"Nanny.service_name\"", "]", ",", "service_binary_name", "=", "config", ".", "CONFIG", "[", "\"Nanny.service_binary_name\"", "]", ")", "if...
40.56
0.006744
def serialize_upload(name, storage, url): """ Serialize uploaded file by name and storage. Namespaced by the upload url. """ if isinstance(storage, LazyObject): # Unwrap lazy storage class storage._setup() cls = storage._wrapped.__class__ else: cls = storage.__class__...
[ "def", "serialize_upload", "(", "name", ",", "storage", ",", "url", ")", ":", "if", "isinstance", "(", "storage", ",", "LazyObject", ")", ":", "# Unwrap lazy storage class", "storage", ".", "_setup", "(", ")", "cls", "=", "storage", ".", "_wrapped", ".", "...
30.928571
0.002242
def iter_links_meta_element(cls, element): '''Iterate the ``meta`` element for links. This function handles refresh URLs. ''' if element.attrib.get('http-equiv', '').lower() == 'refresh': content_value = element.attrib.get('content') if content_value: ...
[ "def", "iter_links_meta_element", "(", "cls", ",", "element", ")", ":", "if", "element", ".", "attrib", ".", "get", "(", "'http-equiv'", ",", "''", ")", ".", "lower", "(", ")", "==", "'refresh'", ":", "content_value", "=", "element", ".", "attrib", ".", ...
37.173913
0.002281
def save(self): """ Saves a new rating - authenticated users can update the value if they've previously rated. """ user = self.request.user self.undoing = False rating_value = self.cleaned_data["value"] manager = self.rating_manager if user.is_aut...
[ "def", "save", "(", "self", ")", ":", "user", "=", "self", ".", "request", ".", "user", "self", ".", "undoing", "=", "False", "rating_value", "=", "self", ".", "cleaned_data", "[", "\"value\"", "]", "manager", "=", "self", ".", "rating_manager", "if", ...
39.32
0.002979
def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ _maybe_show_deprecated_notice(self) if self.callback is not None: return ctx.invoke(self.callback, **ctx.params)
[ "def", "invoke", "(", "self", ",", "ctx", ")", ":", "_maybe_show_deprecated_notice", "(", "self", ")", "if", "self", ".", "callback", "is", "not", "None", ":", "return", "ctx", ".", "invoke", "(", "self", ".", "callback", ",", "*", "*", "ctx", ".", "...
39
0.007168
def save_thumbnail(image_path, base_image_name, gallery_conf): """Save the thumbnail image""" first_image_file = image_path.format(1) thumb_dir = os.path.join(os.path.dirname(first_image_file), 'thumb') if not os.path.exists(thumb_dir): os.makedirs(thumb_dir) thumb_file = os.path.join(thumb...
[ "def", "save_thumbnail", "(", "image_path", ",", "base_image_name", ",", "gallery_conf", ")", ":", "first_image_file", "=", "image_path", ".", "format", "(", "1", ")", "thumb_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname"...
47.166667
0.001155
def project(self, from_shape, to_shape): """ Project the polygon onto an image with different shape. The relative coordinates of all points remain the same. E.g. a point at (x=20, y=20) on an image (width=100, height=200) will be projected on a new image (width=200, height=100) ...
[ "def", "project", "(", "self", ",", "from_shape", ",", "to_shape", ")", ":", "if", "from_shape", "[", "0", ":", "2", "]", "==", "to_shape", "[", "0", ":", "2", "]", ":", "return", "self", ".", "copy", "(", ")", "ls_proj", "=", "self", ".", "to_li...
33.733333
0.002882
def get_sequence(queries,fap=None,fmt='fasta', organism_taxid=9606, test=False): """ http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=uniprotkb&id=P14060+P26439&format=fasta&style=raw&Retrieve=Retrieve https://www.uniprot.org/uniprot/?format=fasta&organism=9606&query=O75116+O75116+...
[ "def", "get_sequence", "(", "queries", ",", "fap", "=", "None", ",", "fmt", "=", "'fasta'", ",", "organism_taxid", "=", "9606", ",", "test", "=", "False", ")", ":", "url", "=", "'http://www.ebi.ac.uk/Tools/dbfetch/dbfetch'", "params", "=", "{", "'id'", ":", ...
32.571429
0.021299
def showinfo(title=None, message=None, **options): """Original doc: Show an info message""" return psidialogs.message(title=title, message=message)
[ "def", "showinfo", "(", "title", "=", "None", ",", "message", "=", "None", ",", "*", "*", "options", ")", ":", "return", "psidialogs", ".", "message", "(", "title", "=", "title", ",", "message", "=", "message", ")" ]
51
0.006452
def tty(tty_reload): """Load colors in tty.""" tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
[ "def", "tty", "(", "tty_reload", ")", ":", "tty_script", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors-tty.sh\"", ")", "term", "=", "os", ".", "environ", ".", "get", "(", "\"TERM\"", ")", "if", "tty_reload", "and", "term", "==",...
31.571429
0.004405
def add_sample_file(self, sample_path, source, reference, method='', file_format='raw', file_password='', sample_name='', campai...
[ "def", "add_sample_file", "(", "self", ",", "sample_path", ",", "source", ",", "reference", ",", "method", "=", "''", ",", "file_format", "=", "'raw'", ",", "file_password", "=", "''", ",", "sample_name", "=", "''", ",", "campaign", "=", "''", ",", "conf...
41.967742
0.004882
def unique(arr, tolerance=1e-6) -> np.ndarray: """Return unique elements in 1D array, within tolerance. Parameters ---------- arr : array_like Input array. This will be flattened if it is not already 1D. tolerance : number (optional) The tolerance for uniqueness. Returns --...
[ "def", "unique", "(", "arr", ",", "tolerance", "=", "1e-6", ")", "->", "np", ".", "ndarray", ":", "arr", "=", "sorted", "(", "arr", ".", "flatten", "(", ")", ")", "unique", "=", "[", "]", "while", "len", "(", "arr", ")", ">", "0", ":", "current...
29.291667
0.001377
def setHint( self, hint ): """ Sets the hint for this line edit that will be displayed when in \ editable mode. :param hint | <str> """ self._hint = hint lineEdit = self.lineEdit() if isinstance(lineEdit, XLineEdit): li...
[ "def", "setHint", "(", "self", ",", "hint", ")", ":", "self", ".", "_hint", "=", "hint", "lineEdit", "=", "self", ".", "lineEdit", "(", ")", "if", "isinstance", "(", "lineEdit", ",", "XLineEdit", ")", ":", "lineEdit", ".", "setHint", "(", "hint", ")"...
27.416667
0.020588
def get_age(Rec, sitekey, keybase, Ages, DefaultAge): """ finds the age record for a given site """ site = Rec[sitekey] gotone = 0 if len(Ages) > 0: for agerec in Ages: if agerec["er_site_name"] == site: if "age" in list(agerec.keys()) and agerec["age"] != "":...
[ "def", "get_age", "(", "Rec", ",", "sitekey", ",", "keybase", ",", "Ages", ",", "DefaultAge", ")", ":", "site", "=", "Rec", "[", "sitekey", "]", "gotone", "=", "0", "if", "len", "(", "Ages", ")", ">", "0", ":", "for", "agerec", "in", "Ages", ":",...
41.521739
0.001024
def updateSolutionTerminal(self): ''' Update the terminal period solution for this type. Similar to other models, optimal behavior involves spending all available market resources; however, the agent must split his resources between consumption and medical care. Parameters ...
[ "def", "updateSolutionTerminal", "(", "self", ")", ":", "# Take last period data, whichever way time is flowing", "if", "self", ".", "time_flow", ":", "MedPrice", "=", "self", ".", "MedPrice", "[", "-", "1", "]", "MedShkVals", "=", "self", ".", "MedShkDstn", "[", ...
52.235294
0.019673
def get_plaintext_citations(arxiv_id): """ Get the citations of a given preprint, in plain text. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1...
[ "def", "get_plaintext_citations", "(", "arxiv_id", ")", ":", "plaintext_citations", "=", "[", "]", "# Get the list of bbl files for this preprint", "bbl_files", "=", "arxiv", ".", "get_bbl", "(", "arxiv_id", ")", "for", "bbl_file", "in", "bbl_files", ":", "# Fetch the...
37
0.001318
def _flush_data(self): """ If this relation's local unit data has been modified, publish it on the relation. This should be automatically called. """ if self._data and self._data.modified: hookenv.relation_set(self.relation_id, dict(self.to_publish.data))
[ "def", "_flush_data", "(", "self", ")", ":", "if", "self", ".", "_data", "and", "self", ".", "_data", ".", "modified", ":", "hookenv", ".", "relation_set", "(", "self", ".", "relation_id", ",", "dict", "(", "self", ".", "to_publish", ".", "data", ")", ...
43
0.006515
def get_assessment_part_item_design_session_for_bank(self, bank_id, proxy): """Gets the ``OsidSession`` associated with the assessment part item design service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` return: (osid.assessment.authoring.AssessmentPartItemDesig...
[ "def", "get_assessment_part_item_design_session_for_bank", "(", "self", ",", "bank_id", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_assessment_part_lookup", "(", ")", ":", "# This is kludgy, but only until Tom fixes spec", "raise", "errors", ".", "Unimplem...
57.181818
0.004691
def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.format(output_path)) stash.export(output_path=output_path) click.echo('Export complete!') exc...
[ "def", "export_keys", "(", "output_path", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Exporting stash to {0}...'", ".", ...
32
0.002762
def name(self): """ Return the administrator name for this session. Can be None if the session has not yet been established. .. note:: The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for ...
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "session", ":", "# protect cached property from being set before session", "try", ":", "return", "self", ".", "current_user", ".", "name", "except", "AttributeError", ":", "# TODO: Catch ConnectionError? No sessio...
36.823529
0.010903