text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def link(self, content, raw_url, title=''): """ Filters links. """ if self.check_url(raw_url): url = self.rewrite_url(raw_url) maybe_title = ' title="%s"' % escape_html(title) if title else '' url = escape_html(url) return ('<a href="%s"%s>...
[ "def", "link", "(", "self", ",", "content", ",", "raw_url", ",", "title", "=", "''", ")", ":", "if", "self", ".", "check_url", "(", "raw_url", ")", ":", "url", "=", "self", ".", "rewrite_url", "(", "raw_url", ")", "maybe_title", "=", "' title=\"%s\"'",...
39.181818
14.636364
def index(self): """ Returns the first occurrence of the bank in your :class:`.PluginsManager` """ if self.manager is None: raise IndexError('Bank not contains a manager') return self.manager.banks.index(self)
[ "def", "index", "(", "self", ")", ":", "if", "self", ".", "manager", "is", "None", ":", "raise", "IndexError", "(", "'Bank not contains a manager'", ")", "return", "self", ".", "manager", ".", "banks", ".", "index", "(", "self", ")" ]
31.875
17.125
def convert(self, layer=2, split_sign = '_', *args, **kwargs): """convert data to DataFrame""" return series2df(self.series, *args, **kwargs)
[ "def", "convert", "(", "self", ",", "layer", "=", "2", ",", "split_sign", "=", "'_'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "series2df", "(", "self", ".", "series", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
51.666667
12
def Clear(self): """Wipes the transaction log.""" try: with io.open(self.logfile, "wb") as fd: fd.write(b"") except (IOError, OSError): pass
[ "def", "Clear", "(", "self", ")", ":", "try", ":", "with", "io", ".", "open", "(", "self", ".", "logfile", ",", "\"wb\"", ")", "as", "fd", ":", "fd", ".", "write", "(", "b\"\"", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "pass" ]
23.714286
17.142857
def new_evaluation_result(self, has_improved: bool) -> bool: """ Returns true if the parameters should be reset to the ones with the best validation score. :param has_improved: Whether the model improved on held-out validation data. :return: True if parameters should be reset to the one...
[ "def", "new_evaluation_result", "(", "self", ",", "has_improved", ":", "bool", ")", "->", "bool", ":", "if", "self", ".", "lr", "is", "None", ":", "assert", "self", ".", "base_lr", "is", "not", "None", "self", ".", "lr", "=", "self", ".", "base_lr", ...
47.363636
23.454545
def list_discussion_topics_courses(self, course_id, exclude_context_module_locked_topics=None, include=None, only_announcements=None, order_by=None, scope=None, search_term=None): """ List discussion topics. Returns the paginated list of discussion topics for this course or group. ...
[ "def", "list_discussion_topics_courses", "(", "self", ",", "course_id", ",", "exclude_context_module_locked_topics", "=", "None", ",", "include", "=", "None", ",", "only_announcements", "=", "None", ",", "order_by", "=", "None", ",", "scope", "=", "None", ",", "...
47.166667
22.148148
def encrypt_password(self, email, password): """ Get the RSA key for the user and encrypt the users password :param email: steam account :param password: password for account :return: encrypted password """ res = self.session.http.get(self._get_rsa_key_url, params...
[ "def", "encrypt_password", "(", "self", ",", "email", ",", "password", ")", ":", "res", "=", "self", ".", "session", ".", "http", ".", "get", "(", "self", ".", "_get_rsa_key_url", ",", "params", "=", "dict", "(", "username", "=", "email", ",", "donotca...
49.846154
22.615385
def set_keepalive(self, interval): """ Set a keepalive to occur every ``interval`` on this connection. """ pinger = functools.partial(self.ping, 'keep-alive') self.reactor.scheduler.execute_every(period=interval, func=pinger)
[ "def", "set_keepalive", "(", "self", ",", "interval", ")", ":", "pinger", "=", "functools", ".", "partial", "(", "self", ".", "ping", ",", "'keep-alive'", ")", "self", ".", "reactor", ".", "scheduler", ".", "execute_every", "(", "period", "=", "interval", ...
43.333333
15
def plot_connectivity_significance(s, fs=2, freq_range=(-np.inf, np.inf), diagonal=0, border=False, fig=None): """Plot significance. Significance is drawn as a background image where dark vertical stripes indicate freuquencies where a evaluates to True. Parameters ---------- a : array, shape (...
[ "def", "plot_connectivity_significance", "(", "s", ",", "fs", "=", "2", ",", "freq_range", "=", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", ",", "diagonal", "=", "0", ",", "border", "=", "False", ",", "fig", "=", "None", ")", ":", "a"...
32.986842
24.934211
def setup(cls, ikpdb_log_arg): """ activates DEBUG logging level based on the `ikpdb_log_arg` parameter string. `ikpdb_log_arg` corresponds to the `--ikpdb-log` command line argument. `ikpdb_log_arg` is composed of a serie of letters that set the `DEBUG` lo...
[ "def", "setup", "(", "cls", ",", "ikpdb_log_arg", ")", ":", "if", "not", "ikpdb_log_arg", ":", "return", "IKPdbLogger", ".", "enabled", "=", "True", "logging_configuration_string", "=", "ikpdb_log_arg", ".", "lower", "(", ")", "for", "letter", "in", "logging_c...
35.731707
18.707317
def get_template(template_dict, parameter_overrides=None): """ Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run and parameter values have been substituted. Parameters ---------- template_dict : dict unproc...
[ "def", "get_template", "(", "template_dict", ",", "parameter_overrides", "=", "None", ")", ":", "template_dict", "=", "template_dict", "or", "{", "}", "if", "template_dict", ":", "template_dict", "=", "SamTranslatorWrapper", "(", "template_dict", ")", ".", "run_pl...
32.807692
23.807692
def when_called_with(self, *some_args, **some_kwargs): """Asserts the val callable when invoked with the given args and kwargs raises the expected exception.""" if not self.expected: raise TypeError('expected exception not set, raises() must be called first') try: self.va...
[ "def", "when_called_with", "(", "self", ",", "*", "some_args", ",", "*", "*", "some_kwargs", ")", ":", "if", "not", "self", ".", "expected", ":", "raise", "TypeError", "(", "'expected exception not set, raises() must be called first'", ")", "try", ":", "self", "...
50.608696
18.478261
def get_night_light_state(self): """Return the state of the night light (on/off).""" if not self.camera_extended_properties: return None night_light = self.camera_extended_properties.get('nightLight') if not night_light: return None if night_light.get('e...
[ "def", "get_night_light_state", "(", "self", ")", ":", "if", "not", "self", ".", "camera_extended_properties", ":", "return", "None", "night_light", "=", "self", ".", "camera_extended_properties", ".", "get", "(", "'nightLight'", ")", "if", "not", "night_light", ...
27.923077
19.384615
def GetNetworks(alias=None,location=None): """Gets the list of Networks mapped to the account in the specified datacenter. https://t3n.zendesk.com/entries/21024721-Get-Networks :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group ...
[ "def", "GetNetworks", "(", "alias", "=", "None", ",", "location", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "...
54.333333
27.166667
def getNumberOfQCSamples(self): """ Returns the number of Quality Control samples. :returns: number of QC samples :rtype: integer """ qc_analyses = self.getQCAnalyses() qc_samples = [a.getSample().UID() for a in qc_analyses] # discarding any duplicate valu...
[ "def", "getNumberOfQCSamples", "(", "self", ")", ":", "qc_analyses", "=", "self", ".", "getQCAnalyses", "(", ")", "qc_samples", "=", "[", "a", ".", "getSample", "(", ")", ".", "UID", "(", ")", "for", "a", "in", "qc_analyses", "]", "# discarding any duplica...
34.9
7.3
def handle_completion_info_list(self, call_id, payload): """Handler for a completion response.""" self.log.debug('handle_completion_info_list: in') # filter out completions without `typeInfo` field to avoid server bug. See #324 completions = [c for c in payload["completions"] if "typeInf...
[ "def", "handle_completion_info_list", "(", "self", ",", "call_id", ",", "payload", ")", ":", "self", ".", "log", ".", "debug", "(", "'handle_completion_info_list: in'", ")", "# filter out completions without `typeInfo` field to avoid server bug. See #324", "completions", "=",...
68.714286
27.571429
def load_and_parse(self, package_name, root_dir, relative_dirs, resource_type, tags=None): """Load and parse models in a list of directories. Returns a dict that maps unique ids onto ParsedNodes""" extension = "[!.#~]*.sql" if tags is None: tags = ...
[ "def", "load_and_parse", "(", "self", ",", "package_name", ",", "root_dir", ",", "relative_dirs", ",", "resource_type", ",", "tags", "=", "None", ")", ":", "extension", "=", "\"[!.#~]*.sql\"", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "if", ...
32.155556
19.8
def magic_mprun(self, parameter_s=''): """ Execute a statement under the line-by-line memory profiler from the memory_profiler module. Usage: %mprun -f func1 -f func2 <statement> The given statement (which doesn't require quote marks) is run via the LineProfiler. Profiling is enabled for the...
[ "def", "magic_mprun", "(", "self", ",", "parameter_s", "=", "''", ")", ":", "try", ":", "from", "StringIO", "import", "StringIO", "except", "ImportError", ":", "# Python 3.x", "from", "io", "import", "StringIO", "# Local imports to avoid hard dependency.", "from", ...
33.95082
21.344262
def _windows_cpudata(): ''' Return some CPU information on Windows minions ''' # Provides: # num_cpus # cpu_model grains = {} if 'NUMBER_OF_PROCESSORS' in os.environ: # Cast to int so that the logic isn't broken when used as a # conditional in templating. Also follows...
[ "def", "_windows_cpudata", "(", ")", ":", "# Provides:", "# num_cpus", "# cpu_model", "grains", "=", "{", "}", "if", "'NUMBER_OF_PROCESSORS'", "in", "os", ".", "environ", ":", "# Cast to int so that the logic isn't broken when used as a", "# conditional in templating. Als...
34.6
20.3
async def pin(self, disable_notification: bool = False): """ Pin message :param disable_notification: :return: """ return await self.chat.pin_message(self.message_id, disable_notification)
[ "async", "def", "pin", "(", "self", ",", "disable_notification", ":", "bool", "=", "False", ")", ":", "return", "await", "self", ".", "chat", ".", "pin_message", "(", "self", ".", "message_id", ",", "disable_notification", ")" ]
28.75
18.25
def evalParam(p): """ Get value of parameter """ while isinstance(p, Param): p = p.get() if isinstance(p, RtlSignalBase): return p.staticEval() # use rather param inheritance instead of param as param value return toHVal(p)
[ "def", "evalParam", "(", "p", ")", ":", "while", "isinstance", "(", "p", ",", "Param", ")", ":", "p", "=", "p", ".", "get", "(", ")", "if", "isinstance", "(", "p", ",", "RtlSignalBase", ")", ":", "return", "p", ".", "staticEval", "(", ")", "# use...
23.818182
15.636364
def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10, histResolution=.5,plotToo=False): """ let's keep the chunkMs as high as we reasonably can. 50ms is good. Things get flakey at lower numbers like 10ms. IMPORTANT! for this to work, prevent 0s...
[ "def", "phasicTonic", "(", "self", ",", "m1", "=", "None", ",", "m2", "=", "None", ",", "chunkMs", "=", "50", ",", "quietPercentile", "=", "10", ",", "histResolution", "=", ".5", ",", "plotToo", "=", "False", ")", ":", "# prepare sectioning values to be us...
41.234568
16.111111
def accumulate_dict_from_superclasses(cls, propname): ''' Traverse the class hierarchy and accumulate the special dicts ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__dataspecs__``, ``__o...
[ "def", "accumulate_dict_from_superclasses", "(", "cls", ",", "propname", ")", ":", "cachename", "=", "\"__cached_all\"", "+", "propname", "# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base", "# classes, and the cache must be separate for each class", "if", "...
37.25
17.25
def replace(self, key, value, time, compress_level=-1): """ Replace a key/value to server ony if it does exist. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param time: Time in seconds that ...
[ "def", "replace", "(", "self", ",", "key", ",", "value", ",", "time", ",", "compress_level", "=", "-", "1", ")", ":", "return", "self", ".", "_set_add_replace", "(", "'replace'", ",", "key", ",", "value", ",", "time", ",", "compress_level", "=", "compr...
41.388889
17.055556
def filename(file_name, start_on=None, ignore=(), use_short=True, **queries): '''Returns a blox template from a valid file path''' with open(file_name) as template_file: return file(template_file, start_on=start_on, ignore=ignore, use_short=use_short, **queries)
[ "def", "filename", "(", "file_name", ",", "start_on", "=", "None", ",", "ignore", "=", "(", ")", ",", "use_short", "=", "True", ",", "*", "*", "queries", ")", ":", "with", "open", "(", "file_name", ")", "as", "template_file", ":", "return", "file", "...
68.75
28.75
def get_packages_of_type(self, package_types, mask=None): """Get packages that match a certain type. Each ordering package has a type, so return all packages that match the types we are looking for :param list package_types: List of strings representing the package ...
[ "def", "get_packages_of_type", "(", "self", ",", "package_types", ",", "mask", "=", "None", ")", ":", "_filter", "=", "{", "'type'", ":", "{", "'keyName'", ":", "{", "'operation'", ":", "'in'", ",", "'options'", ":", "[", "{", "'name'", ":", "'data'", ...
34.461538
21.346154
def spec_compliant_encrypt(claims, jwk, add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :pa...
[ "def", "spec_compliant_encrypt", "(", "claims", ",", "jwk", ",", "add_header", "=", "None", ",", "alg", "=", "'RSA-OAEP'", ",", "enc", "=", "'A128CBC-HS256'", ",", "rng", "=", "get_random_bytes", ")", ":", "# We need 5 components for JWE token", "# 1. Generate heade...
36.901639
20.770492
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'): """Load engines.""" loaded_engines = {} for module_name_or_dict in engines: if not isinstance(module_name_or_dict, dict): module_name_or_dict = { class_key: module_name...
[ "def", "load_engines", "(", "manager", ",", "class_name", ",", "base_module", ",", "engines", ",", "class_key", "=", "'ENGINE'", ",", "engine_type", "=", "'engine'", ")", ":", "loaded_engines", "=", "{", "}", "for", "module_name_or_dict", "in", "engines", ":",...
45.689655
27.534483
def from_const(cls, value, size, dtype=type(None)): """ Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the S...
[ "def", "from_const", "(", "cls", ",", "value", ",", "size", ",", "dtype", "=", "type", "(", "None", ")", ")", ":", "assert", "isinstance", "(", "size", ",", "(", "int", ",", "long", ")", ")", "and", "size", ">=", "0", ",", "\"size must be a positive ...
38.774194
23.741935
def visit(self, obj): """Visit a node or a list of nodes. Other values are ignored""" if isinstance(obj, list): return [self.visit(elt) for elt in obj] elif isinstance(obj, ast.AST): return self._visit_one(obj)
[ "def", "visit", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "self", ".", "visit", "(", "elt", ")", "for", "elt", "in", "obj", "]", "elif", "isinstance", "(", "obj", ",", "ast", ".", "...
42.166667
6.666667
def _dumps(self, obj): """ If :prop:serialized is True, @obj will be serialized using :prop:serializer """ if not self.serialized: return obj return self.serializer.dumps(obj)
[ "def", "_dumps", "(", "self", ",", "obj", ")", ":", "if", "not", "self", ".", "serialized", ":", "return", "obj", "return", "self", ".", "serializer", ".", "dumps", "(", "obj", ")" ]
32.142857
7.428571
def accept_milestone_request(session, milestone_request_id): """ Accept a milestone request """ params_data = { 'action': 'accept', } # POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action= # accept endpoint = 'milestone_requests/{}'.format(milestone_request_i...
[ "def", "accept_milestone_request", "(", "session", ",", "milestone_request_id", ")", ":", "params_data", "=", "{", "'action'", ":", "'accept'", ",", "}", "# POST /api/projects/0.1/milestone_requests/{milestone_request_id}/?action=", "# accept", "endpoint", "=", "'milestone_re...
35.947368
16.052632
def hacking_docstring_multiline_end(physical_line, previous_logical, tokens): r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class...
[ "def", "hacking_docstring_multiline_end", "(", "physical_line", ",", "previous_logical", ",", "tokens", ")", ":", "docstring", "=", "is_docstring", "(", "tokens", ",", "previous_logical", ")", "if", "docstring", ":", "if", "'\\n'", "not", "in", "docstring", ":", ...
43.25
18.25
def _process_interval(self, mod, interval): ''' Process beacons with intervals Return True if a beacon should be run on this loop ''' log.trace('Processing interval %s for beacon mod %s', interval, mod) loop_interval = self.opts['loop_interval'] if mod in self.int...
[ "def", "_process_interval", "(", "self", ",", "mod", ",", "interval", ")", ":", "log", ".", "trace", "(", "'Processing interval %s for beacon mod %s'", ",", "interval", ",", "mod", ")", "loop_interval", "=", "self", ".", "opts", "[", "'loop_interval'", "]", "i...
39.35
14.25
def get_urls_for_profiles(edx_video_id, profiles): """ Returns a dict mapping profiles to URLs. If the profiles or video is not found, urls will be blank. Args: edx_video_id (str): id of the video profiles (list): list of profiles we want to search for Returns: (dict): A d...
[ "def", "get_urls_for_profiles", "(", "edx_video_id", ",", "profiles", ")", ":", "profiles_to_urls", "=", "{", "profile", ":", "None", "for", "profile", "in", "profiles", "}", "try", ":", "video_info", "=", "get_video_info", "(", "edx_video_id", ")", "except", ...
30.958333
20.375
def api_auth(func): """ If the user is not logged in, this decorator looks for basic HTTP auth data in the request header. """ @wraps(func) def _decorator(request, *args, **kwargs): authentication = APIAuthentication(request) if authentication.authenticate(): return ...
[ "def", "api_auth", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_decorator", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "authentication", "=", "APIAuthentication", "(", "request", ")", "if", "authentication", ...
29.384615
14.769231
def write_project_summary(samples, qsign_info=None): """Write project summary information on the provided samples. write out dirs, genome resources, """ work_dir = samples[0][0]["dirs"]["work"] out_file = os.path.join(work_dir, "project-summary.yaml") upload_dir = (os.path.join(work_dir, sample...
[ "def", "write_project_summary", "(", "samples", ",", "qsign_info", "=", "None", ")", ":", "work_dir", "=", "samples", "[", "0", "]", "[", "0", "]", "[", "\"dirs\"", "]", "[", "\"work\"", "]", "out_file", "=", "os", ".", "path", ".", "join", "(", "wor...
54.153846
21.538462
def add_socket(self, socket): """ Add a socket to the multiplexer. :param socket: The socket. If it was added already, it won't be added a second time. """ if socket not in self._sockets: self._sockets.add(socket) socket.on_closed.connect(self...
[ "def", "add_socket", "(", "self", ",", "socket", ")", ":", "if", "socket", "not", "in", "self", ".", "_sockets", ":", "self", ".", "_sockets", ".", "add", "(", "socket", ")", "socket", ".", "on_closed", ".", "connect", "(", "self", ".", "remove_socket"...
32.6
12.6
def updateSynapses(self, synapses, delta): """Update a set of synapses in the segment. @param tp The owner TP @param synapses List of synapse indices to update @param delta How much to add to each permanence @returns True if synapse reached 0 """ reached0 = False if delta >...
[ "def", "updateSynapses", "(", "self", ",", "synapses", ",", "delta", ")", ":", "reached0", "=", "False", "if", "delta", ">", "0", ":", "for", "synapse", "in", "synapses", ":", "self", ".", "syns", "[", "synapse", "]", "[", "2", "]", "=", "newValue", ...
29.344828
20.448276
def say_tmp_filepath( text = None, preference_program = "festival" ): """ Say specified text to a temporary file and return the filepath. """ filepath = shijian.tmp_filepath() + ".wav" say( text = text, preference_program = preference_program, ...
[ "def", "say_tmp_filepath", "(", "text", "=", "None", ",", "preference_program", "=", "\"festival\"", ")", ":", "filepath", "=", "shijian", ".", "tmp_filepath", "(", ")", "+", "\".wav\"", "say", "(", "text", "=", "text", ",", "preference_program", "=", "prefe...
26.428571
14.714286
def calc_am_um_v1(self): """Calculate the flown through area and the wetted perimeter of the main channel. Note that the main channel is assumed to have identical slopes on both sides and that water flowing exactly above the main channel is contributing to |AM|. Both theoretical surfaces seperatin...
[ "def", "calc_am_um_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "if", "flu", ".", "h", "<=", "0.", ":", "flu", ".", "am",...
27.545455
23.420455
def max_load(network, boundaries=[], filename=None, two_cb=False): """Plot maximum loading of each line. Parameters ---------- network: PyPSA network container Holds topology of grid including results from powerflow analysis filename: str or None Save figure in this direct...
[ "def", "max_load", "(", "network", ",", "boundaries", "=", "[", "]", ",", "filename", "=", "None", ",", "two_cb", "=", "False", ")", ":", "cmap_line", "=", "plt", ".", "cm", ".", "jet", "cmap_link", "=", "plt", ".", "cm", ".", "jet", "array_line", ...
30.463768
21.608696
def get_issues(self, sortby=None): """ Retrieves the issues in the collection. :param sortby: the properties to sort the issues by :type sortby: list(str) :rtype: list(tidypy.Issue) """ self._ensure_cleaned_issues() return self._sort_issues(self._cleaned...
[ "def", "get_issues", "(", "self", ",", "sortby", "=", "None", ")", ":", "self", ".", "_ensure_cleaned_issues", "(", ")", "return", "self", ".", "_sort_issues", "(", "self", ".", "_cleaned_issues", ",", "sortby", ")" ]
29.636364
13.818182
def detect_functions_called(contract): """ Returns a list of InternallCall, SolidityCall calls made in a function Returns: (list): List of all InternallCall, SolidityCall """ result = [] # Obtain all functions reachable by this contract. for func...
[ "def", "detect_functions_called", "(", "contract", ")", ":", "result", "=", "[", "]", "# Obtain all functions reachable by this contract.", "for", "func", "in", "contract", ".", "all_functions_called", ":", "# Loop through all nodes in the function, add all calls to a list.", "...
37.117647
16.647059
def fmt_text(text, bg = None, fg = None, attr = None, plain = False): """ Apply given console formating around given text. """ if not plain: if fg is not None: text = TEXT_FORMATING['fg'][fg] + text if bg is not None: text = TEXT_FO...
[ "def", "fmt_text", "(", "text", ",", "bg", "=", "None", ",", "fg", "=", "None", ",", "attr", "=", "None", ",", "plain", "=", "False", ")", ":", "if", "not", "plain", ":", "if", "fg", "is", "not", "None", ":", "text", "=", "TEXT_FORMATING", "[", ...
40.285714
14.142857
def get_chromosomes(self, sv=False): """Return a list of all chromosomes found in database Args: sv(bool): if sv variants should be choosen Returns: res(iterable(str)): An iterable with all chromosomes in the database """ if sv: ...
[ "def", "get_chromosomes", "(", "self", ",", "sv", "=", "False", ")", ":", "if", "sv", ":", "res", "=", "self", ".", "db", ".", "structural_variant", ".", "distinct", "(", "'chrom'", ")", "else", ":", "res", "=", "self", ".", "db", ".", "variant", "...
30.466667
20.6
def removeTopology(self, topology_name, state_manager_name): """ Removes the topology from the local cache. """ topologies = [] for top in self.topologies: if (top.name == topology_name and top.state_manager_name == state_manager_name): # Remove topologyInfo if (topol...
[ "def", "removeTopology", "(", "self", ",", "topology_name", ",", "state_manager_name", ")", ":", "topologies", "=", "[", "]", "for", "top", "in", "self", ".", "topologies", ":", "if", "(", "top", ".", "name", "==", "topology_name", "and", "top", ".", "st...
33.666667
15.266667
def _handle_start_relation(self, attrs): """ Handle opening relation element :param attrs: Attributes of the element :type attrs: Dict """ self._curr = { 'attributes': dict(attrs), 'members': [], 'rel_id': None, 'tags': {} ...
[ "def", "_handle_start_relation", "(", "self", ",", "attrs", ")", ":", "self", ".", "_curr", "=", "{", "'attributes'", ":", "dict", "(", "attrs", ")", ",", "'members'", ":", "[", "]", ",", "'rel_id'", ":", "None", ",", "'tags'", ":", "{", "}", "}", ...
28.6875
11.3125
def read_namespaced_stateful_set(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set # noqa: E501 read the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_re...
[ "def", "read_namespaced_stateful_set", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retu...
56.2
29.4
def ref(host, seq, takeoff, emergency=False): """ Basic behaviour of the drone: take-off/landing, emergency stop/reset) Parameters: seq -- sequence number takeoff -- True: Takeoff / False: Land emergency -- True: Turn off the engines """ p = 0b10001010101000000000000000000 if takeof...
[ "def", "ref", "(", "host", ",", "seq", ",", "takeoff", ",", "emergency", "=", "False", ")", ":", "p", "=", "0b10001010101000000000000000000", "if", "takeoff", ":", "p", "|=", "0b1000000000", "if", "emergency", ":", "p", "|=", "0b100000000", "at", "(", "h...
27.133333
14.2
def _ParseLine(self, parser_mediator, structure): """Parses a logline and store appropriate attributes. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens de...
[ "def", "_ParseLine", "(", "self", ",", "parser_mediator", ",", "structure", ")", ":", "# TODO: Verify if date and time value is locale dependent.", "month", ",", "day_of_month", ",", "year", ",", "hours", ",", "minutes", ",", "seconds", ",", "milliseconds", "=", "("...
40.416667
21.25
def managed(name, probes, defaults=None): ''' Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. :param probes: Defines the probes as expected to be configured on the ...
[ "def", "managed", "(", "name", ",", "probes", ",", "defaults", "=", "None", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "result", "=", "True", "comment", "=", "''", "rpm_probes_config", "=", "_retrieve_rpm_probes", "(", ")", "# retrieves the RPM ...
35.083744
24.128079
def get_application_instance(): """ Returns the current `QApplication <http://doc.qt.nokia.com/qapplication.html>`_ instance or create one if it doesn't exists. :return: Application instance. :rtype: QApplication """ instance = QApplication.instance() if not instance: instance ...
[ "def", "get_application_instance", "(", ")", ":", "instance", "=", "QApplication", ".", "instance", "(", ")", "if", "not", "instance", ":", "instance", "=", "QApplication", "(", "sys", ".", "argv", ")", "return", "instance" ]
27.076923
16.461538
def parse_host(host): """Parses host name and port number from a string. """ if re.match(r'^(\d+)$', host) is not None: return ("0.0.0.0", int(host)) if re.match(r'^(\w+)://', host) is None: host = "//" + host o = parse.urlparse(host) hostname = o.hostname or "0.0.0.0" port =...
[ "def", "parse_host", "(", "host", ")", ":", "if", "re", ".", "match", "(", "r'^(\\d+)$'", ",", "host", ")", "is", "not", "None", ":", "return", "(", "\"0.0.0.0\"", ",", "int", "(", "host", ")", ")", "if", "re", ".", "match", "(", "r'^(\\w+)://'", "...
31.818182
8.272727
def match(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) t...
[ "def", "match", "(", "self", ",", "origin", "=", "None", ",", "rel", "=", "None", ",", "target", "=", "None", ",", "attrs", "=", "None", ",", "include_ids", "=", "False", ")", ":", "#Can't use items or we risk client side RuntimeError: dictionary changed size duri...
58
35.375
def add_result(self, code, message=None): """ add a result to the internal result list arguments: same arguments as for Result() """ self._results.append(Result(code, message))
[ "def", "add_result", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "self", ".", "_results", ".", "append", "(", "Result", "(", "code", ",", "message", ")", ")" ]
27.75
10.5
def fetch(self, is_dl_forced=False): """ Override Source.fetch() Fetches resources from String We also fetch ensembl to determine if protein pairs are from the same species Args: :param is_dl_forced (bool): Force download Returns: :return ...
[ "def", "fetch", "(", "self", ",", "is_dl_forced", "=", "False", ")", ":", "file_paths", "=", "self", ".", "_get_file_paths", "(", "self", ".", "tax_ids", ",", "'protein_links'", ")", "self", ".", "get_files", "(", "is_dl_forced", ",", "file_paths", ")", "s...
31.25
17.25
def valid_totp( token, secret, digest_method=hashlib.sha1, token_length=6, interval_length=30, clock=None, window=0, ): """Check if given token is valid time-based one-time password for given secret. :param token: token which is being checked :typ...
[ "def", "valid_totp", "(", "token", ",", "secret", ",", "digest_method", "=", "hashlib", ".", "sha1", ",", "token_length", "=", "6", ",", "interval_length", "=", "30", ",", "clock", "=", "None", ",", "window", "=", "0", ",", ")", ":", "if", "_is_possibl...
32.892857
17.857143
def stop_timer(self, request_len, reply_len, server_time=None, exception=False): """ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data...
[ "def", "stop_timer", "(", "self", ",", "request_len", ",", "reply_len", ",", "server_time", "=", "None", ",", "exception", "=", "False", ")", ":", "if", "not", "self", ".", "container", ".", "enabled", ":", "return", "None", "# stop the timer", "if", "self...
35.246575
18.452055
def _dispatch_change_event(self, object, trait_name, old, new, handler): """ Prepare and dispatch a trait change event to a listener. """ # Extract the arguments needed from the handler. args = self.argument_transform(object, trait_name, old, new) # Send a description of the event to the change event ...
[ "def", "_dispatch_change_event", "(", "self", ",", "object", ",", "trait_name", ",", "old", ",", "new", ",", "handler", ")", ":", "# Extract the arguments needed from the handler.", "args", "=", "self", ".", "argument_transform", "(", "object", ",", "trait_name", ...
46.740741
23.62963
def get_times_from_cli(cli_token): """Convert a CLI token to a datetime tuple. Argument: cli_token (str): an isoformat datetime token ([ISO date]:[ISO date]) or a special value among: * thisday * thisweek * thismonth * thisyear...
[ "def", "get_times_from_cli", "(", "cli_token", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "if", "cli_token", "==", "\"thisday\"", ":", "return", "today", ",", "today", "elif", "cli_token", "==", "\"thisweek\"", ":", "return", ...
37.816327
23.77551
def _milliBad(self, ismRNA=False): """ calculate badness in parts per thousand i.e. number of non-identical matches """ sizeMult = self._sizeMult qAlnSize, tAlnSize = self.qspan * sizeMult, self.tspan alnSize = min(qAlnSize, tAlnSize) if alnSize <= 0: ...
[ "def", "_milliBad", "(", "self", ",", "ismRNA", "=", "False", ")", ":", "sizeMult", "=", "self", ".", "_sizeMult", "qAlnSize", ",", "tAlnSize", "=", "self", ".", "qspan", "*", "sizeMult", ",", "self", ".", "tspan", "alnSize", "=", "min", "(", "qAlnSize...
31.958333
18.291667
def remove_callback(self, callback): """Remove callback previously registered.""" if callback in self._async_callbacks: self._async_callbacks.remove(callback)
[ "def", "remove_callback", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_async_callbacks", ":", "self", ".", "_async_callbacks", ".", "remove", "(", "callback", ")" ]
45.75
4.75
def header(self, name, value): """ Store all message headers, optionally clean them up. This simply stores all message headers so we can send them to DSPAM. Additionally, headers that have the same prefix as the ones we're about to add are deleted. """ self.mess...
[ "def", "header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "message", "+=", "\"{}: {}\\r\\n\"", ".", "format", "(", "name", ",", "value", ")", "logger", ".", "debug", "(", "'<{}> Received {} header'", ".", "format", "(", "self", ".",...
40.75
18.875
def run_containers(command, parser, cl_args, unknown_args): """ run containers subcommand """ cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ'] topology = cl_args['topology-name'] container_id = cl_args['id'] try: result = tracker_access.get_topology_info(cluster, env, topology,...
[ "def", "run_containers", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "cluster", ",", "role", ",", "env", "=", "cl_args", "[", "'cluster'", "]", ",", "cl_args", "[", "'role'", "]", ",", "cl_args", "[", "'environ'", "]", ...
39.219512
18.609756
def find_ds_mapping(data_source, es_major_version): """ Find the mapping given a perceval data source :param data_source: name of the perceval data source :param es_major_version: string with the major version for Elasticsearch :return: a dict with the mappings (raw and enriched) """ mappin...
[ "def", "find_ds_mapping", "(", "data_source", ",", "es_major_version", ")", ":", "mappings", "=", "{", "\"raw\"", ":", "None", ",", "\"enriched\"", ":", "None", "}", "# Backend connectors", "connectors", "=", "get_connectors", "(", ")", "try", ":", "raw_klass", ...
33.088235
22.441176
def Ry(rads: Union[float, sympy.Basic]) -> YPowGate: """Returns a gate with the matrix e^{-i Y rads / 2}.""" pi = sympy.pi if protocols.is_parameterized(rads) else np.pi return YPowGate(exponent=rads / pi, global_shift=-0.5)
[ "def", "Ry", "(", "rads", ":", "Union", "[", "float", ",", "sympy", ".", "Basic", "]", ")", "->", "YPowGate", ":", "pi", "=", "sympy", ".", "pi", "if", "protocols", ".", "is_parameterized", "(", "rads", ")", "else", "np", ".", "pi", "return", "YPow...
58.25
13.5
def oracle_eval(command): """ Retrieve password from the given command """ p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if p.returncode == 0: return p.stdout.readline().strip().decode('utf-8') else: die( "Erro...
[ "def", "oracle_eval", "(", "command", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "p", ".", "wait", "(",...
39.727273
22.636364
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceCumulativeStatisticsContext for this WorkspaceCumulativeStatisticsInstance :rtype: twili...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "WorkspaceCumulativeStatisticsContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspac...
46.785714
27.928571
def call(method, *args, **kwargs): ''' Invoke an arbitrary pyeapi method. method The name of the pyeapi method to invoke. args A list of arguments to send to the method invoked. kwargs Key-value dictionary to send to the method invoked. transport: ``https`` Sp...
[ "def", "call", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "clean_kwargs", "(", "*", "*", "kwargs", ")", "if", "'pyeapi.call'", "in", "__proxy__", ":", "return", "__proxy__", "[", "'pyeapi.call'", "]", "(", "metho...
30.723684
29.592105
def predict(self, sequences): """ Return netChop predictions for each position in each sequence. Parameters ----------- sequences : list of string Amino acid sequences to predict cleavage for Returns ----------- list of list of float ...
[ "def", "predict", "(", "self", ",", "sequences", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".fsa\"", ",", "mode", "=", "\"w\"", ")", "as", "input_fd", ":", "for", "(", "i", ",", "sequence", ")", "in", "enumerate", "...
36.705882
19.294118
def get_reports(self, report_ids): ''' Get reports by list of ids :param report_ids: list of reports ids :return dictionary of id/report (json string) ''' res = {} for rid in report_ids: print('Fetching report %d' % rid) resp = requests.get...
[ "def", "get_reports", "(", "self", ",", "report_ids", ")", ":", "res", "=", "{", "}", "for", "rid", "in", "report_ids", ":", "print", "(", "'Fetching report %d'", "%", "rid", ")", "resp", "=", "requests", ".", "get", "(", "'%s/api/report?report_id=%d'", "%...
35.266667
15.8
def hash_bytes(value, hasher=hashlib.sha256): # type: (bytes, Callable) -> str """ Generate a hash for a bytes value. The hash will be generated by generating a hash with HMAC using the session secret as the key and the given hash function. :param value: Bytes value to hash :param hasher: ...
[ "def", "hash_bytes", "(", "value", ",", "hasher", "=", "hashlib", ".", "sha256", ")", ":", "# type: (bytes, Callable) -> str", "return", "hmac", ".", "new", "(", "get_secret", "(", ")", ",", "value", ",", "hasher", ")", ".", "hexdigest", "(", ")" ]
35.384615
14.153846
def bucket_keys_to_guarantee_result_set_size(self, bucket_key, N, tree_depth): """ Returns list of bucket keys based on the specified bucket key and minimum result size N. """ if tree_depth == len(bucket_key): #print 'Returning leaf bucket key %s with %d vectors' % (...
[ "def", "bucket_keys_to_guarantee_result_set_size", "(", "self", ",", "bucket_key", ",", "N", ",", "tree_depth", ")", ":", "if", "tree_depth", "==", "len", "(", "bucket_key", ")", ":", "#print 'Returning leaf bucket key %s with %d vectors' % (self.bucket_key, self.vector_count...
45.59375
24.96875
def ones(n, d=None): """ Creates a TT-vector of all ones""" c = _vector.vector() if d is None: c.n = _np.array(n, dtype=_np.int32) c.d = c.n.size else: c.n = _np.array([n] * d, dtype=_np.int32) c.d = d c.r = _np.ones((c.d + 1,), dtype=_np.int32) c.get_ps() c.c...
[ "def", "ones", "(", "n", ",", "d", "=", "None", ")", ":", "c", "=", "_vector", ".", "vector", "(", ")", "if", "d", "is", "None", ":", "c", ".", "n", "=", "_np", ".", "array", "(", "n", ",", "dtype", "=", "_np", ".", "int32", ")", "c", "."...
26.923077
16.153846
def doBenchmark(plats): ''' Perform the benchmark... ''' logger = logging.getLogger("osrframework.utils") # defining the results dict res = {} # args args = [] #for p in plats: # args.append( (str(p),) ) # selecting the number of tries to be performed tries = [1, 4, 8 ,16, 24, 32, 40, 48, 56, 64] ...
[ "def", "doBenchmark", "(", "plats", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"osrframework.utils\"", ")", "# defining the results dict", "res", "=", "{", "}", "# args", "args", "=", "[", "]", "#for p in plats:", "#\targs.append( (str(p),) )", "...
23.416667
25.916667
def aq_esc_telemetry_encode(self, time_boot_ms, seq, num_motors, num_in_seq, escid, status_age, data_version, data0, data1): ''' Sends ESC32 telemetry data for up to 4 motors. Multiple messages may be sent in sequence when system has > 4 motors. Data is de...
[ "def", "aq_esc_telemetry_encode", "(", "self", ",", "time_boot_ms", ",", "seq", ",", "num_motors", ",", "num_in_seq", ",", "escid", ",", "status_age", ",", "data_version", ",", "data0", ",", "data1", ")", ":", "return", "MAVLink_aq_esc_telemetry_message", "(", "...
73.413793
41.827586
def del_Unnamed(df): """ Deletes all the unnamed columns :param df: pandas dataframe """ cols_del=[c for c in df.columns if 'Unnamed' in c] return df.drop(cols_del,axis=1)
[ "def", "del_Unnamed", "(", "df", ")", ":", "cols_del", "=", "[", "c", "for", "c", "in", "df", ".", "columns", "if", "'Unnamed'", "in", "c", "]", "return", "df", ".", "drop", "(", "cols_del", ",", "axis", "=", "1", ")" ]
23.625
11.625
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},): """ run n_iterations of SuccessiveHalving Parameters ---------- n_iterations: int number of iterations to be performed in this run min_n_workers: int minimum number of workers before starting the run """ self.wait_for_worke...
[ "def", "run", "(", "self", ",", "n_iterations", "=", "1", ",", "min_n_workers", "=", "1", ",", "iteration_kwargs", "=", "{", "}", ",", ")", ":", "self", ".", "wait_for_workers", "(", "min_n_workers", ")", "iteration_kwargs", ".", "update", "(", "{", "'re...
27.517241
23.206897
def reset(cls): """Reset the registry to the standard codecs.""" cls._codecs = {} c = cls._codec for (name, encode, decode) in cls._common_codec_data: cls._codecs[name] = c(encode, decode)
[ "def", "reset", "(", "cls", ")", ":", "cls", ".", "_codecs", "=", "{", "}", "c", "=", "cls", ".", "_codec", "for", "(", "name", ",", "encode", ",", "decode", ")", "in", "cls", ".", "_common_codec_data", ":", "cls", ".", "_codecs", "[", "name", "]...
37.833333
14.833333
def GetOptionString(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: string, the value of the option or None if the option doesn't exist....
[ "def", "GetOptionString", "(", "self", ",", "section", ",", "option", ")", ":", "if", "self", ".", "config", ".", "has_option", "(", "section", ",", "option", ")", ":", "return", "self", ".", "config", ".", "get", "(", "section", ",", "option", ")", ...
31.214286
20.214286
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt', include_class_id=False, result_constructor=FilePath): """ Return a temp filename tmp_dir: directory where temporary files will be stored prefix: text to append to start of file name su...
[ "def", "getTmpFilename", "(", "self", ",", "tmp_dir", "=", "None", ",", "prefix", "=", "'tmp'", ",", "suffix", "=", "'.txt'", ",", "include_class_id", "=", "False", ",", "result_constructor", "=", "FilePath", ")", ":", "# check not none", "if", "not", "tmp_d...
48.326531
22.306122
def companyDF(symbol, token='', version=''): '''Company reference data https://iexcloud.io/docs/api/#company Updates at 4am and 5am UTC every day Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame:...
[ "def", "companyDF", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "c", "=", "company", "(", "symbol", ",", "token", ",", "version", ")", "df", "=", "_companyToDF", "(", "c", ")", "return", "df" ]
23.411765
17.411765
def _process_query(self, query): """Takes a key/val pair and returns the Elasticsearch code for it""" key, val = query field_name, field_action = split_field_action(key) # Boost by name__action overrides boost by name. boost = self.field_boosts.get(key) if boost is None:...
[ "def", "_process_query", "(", "self", ",", "query", ")", ":", "key", ",", "val", "=", "query", "field_name", ",", "field_action", "=", "split_field_action", "(", "key", ")", "# Boost by name__action overrides boost by name.", "boost", "=", "self", ".", "field_boos...
34.884615
20.576923
def plot_sed(sed, showlnl=False, **kwargs): """Render a plot of a spectral energy distribution. Parameters ---------- showlnl : bool Overlay a map of the delta-loglikelihood values vs. flux in each energy bin. cmap : str Color...
[ "def", "plot_sed", "(", "sed", ",", "showlnl", "=", "False", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "kwargs", ".", "pop", "(", "'ax'", ",", "plt", ".", "gca", "(", ")", ")", "cmap", "=", "kwargs", ".", "get", "(", "'cmap'", ",", "'BuGn'"...
28.609756
19.390244
def dot(self, other): """Calculates the dot product of this vector and another vector.""" dot_product = 0 a = self.elements b = other.elements a_len = len(a) b_len = len(b) i = j = 0 while i < a_len and j < b_len: a_val = a[i] b_va...
[ "def", "dot", "(", "self", ",", "other", ")", ":", "dot_product", "=", "0", "a", "=", "self", ".", "elements", "b", "=", "other", ".", "elements", "a_len", "=", "len", "(", "a", ")", "b_len", "=", "len", "(", "b", ")", "i", "=", "j", "=", "0"...
25.363636
17.136364
def pairwise( iterable: Iterable, default_value: Any, ) -> Iterable[Tuple[Any, Any]]: """Return pairs of items from `iterable`. pairwise([1, 2, 3], default_value=None) -> (1, 2) (2, 3), (3, None) """ a, b = tee(iterable) _ = next(b, default_value) return zip_longest(a, b, fillvalue=defa...
[ "def", "pairwise", "(", "iterable", ":", "Iterable", ",", "default_value", ":", "Any", ",", ")", "->", "Iterable", "[", "Tuple", "[", "Any", ",", "Any", "]", "]", ":", "a", ",", "b", "=", "tee", "(", "iterable", ")", "_", "=", "next", "(", "b", ...
29.090909
16.363636
def get_transition(self, frame_idx, env_idx): """ Single transition with given index """ past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx) data_dict = { 'observations': past_frame, 'observations_next': future_frame, 'actions': self.act...
[ "def", "get_transition", "(", "self", ",", "frame_idx", ",", "env_idx", ")", ":", "past_frame", ",", "future_frame", "=", "self", ".", "get_frame_with_future", "(", "frame_idx", ",", "env_idx", ")", "data_dict", "=", "{", "'observations'", ":", "past_frame", "...
37.8125
21.0625
def get_fuel_prices(self) -> GetFuelPricesResponse: """Fetches fuel prices for all stations.""" response = requests.get( '{}/prices'.format(API_URL_BASE), headers=self._get_headers(), timeout=self._timeout, ) if not response.ok: raise Fuel...
[ "def", "get_fuel_prices", "(", "self", ")", "->", "GetFuelPricesResponse", ":", "response", "=", "requests", ".", "get", "(", "'{}/prices'", ".", "format", "(", "API_URL_BASE", ")", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", ...
33.583333
15.666667
def _parse_template(self, has_content): """Parse a template at the head of the wikicode string.""" reset = self._head context = contexts.TEMPLATE_NAME if has_content: context |= contexts.HAS_TEMPLATE try: template = self._parse(context) except BadR...
[ "def", "_parse_template", "(", "self", ",", "has_content", ")", ":", "reset", "=", "self", ".", "_head", "context", "=", "contexts", ".", "TEMPLATE_NAME", "if", "has_content", ":", "context", "|=", "contexts", ".", "HAS_TEMPLATE", "try", ":", "template", "="...
34.642857
9.5
def get_open_clinvar_submission(self, user_id, institute_id): """Retrieve the database id of an open clinvar submission for a user and institute, if none is available then create a new submission and return it Args: user_id(str): a user ID institute_id(str)...
[ "def", "get_open_clinvar_submission", "(", "self", ",", "user_id", ",", "institute_id", ")", ":", "LOG", ".", "info", "(", "\"Retrieving an open clinvar submission for user '%s' and institute %s\"", ",", "user_id", ",", "institute_id", ")", "query", "=", "dict", "(", ...
44.909091
28.545455
def add_cell_footer(self): """ Add footer cell """ # check if there's already a cell footer... if true, do not add a second cell footer. # this situation happens when exporting to ipynb and then importing from ipynb. logging.info('Adding footer cell') for cell ...
[ "def", "add_cell_footer", "(", "self", ")", ":", "# check if there's already a cell footer... if true, do not add a second cell footer.", "# this situation happens when exporting to ipynb and then importing from ipynb.", "logging", ".", "info", "(", "'Adding footer cell'", ")", "for", ...
36.241379
19.758621
def vx(self,*args,**kwargs): """ NAME: vx PURPOSE: return x velocity at time t INPUT: t - (optional) time at which to get the velocity vo= (Object-wide default) physical scale for velocities to use to convert use_physical= use to ove...
[ "def", "vx", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thiso", "=", "self", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "len", "(", "thiso", ".", "shape", ")", "==", "2", ":", "thiso", "=", "thiso", ...
36.461538
19.461538
def bakan_bahar_ensemble_align(coords, tolerance = 0.001, verbose = False ): ''' input: a list of coordinates in the format: [ [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 1 [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 2 # etc. ] ''' rmsd_tolerance = float("in...
[ "def", "bakan_bahar_ensemble_align", "(", "coords", ",", "tolerance", "=", "0.001", ",", "verbose", "=", "False", ")", ":", "rmsd_tolerance", "=", "float", "(", "\"inf\"", ")", "average_struct_coords", "=", "np", ".", "array", "(", "random", ".", "choice", "...
42.619048
26.619048
def _cert_callback(callback, der_cert, reason): """ Constructs an asn1crypto.x509.Certificate object and calls the export callback :param callback: The callback to call :param der_cert: A byte string of the DER-encoded certificate :param reason: None if cert is being e...
[ "def", "_cert_callback", "(", "callback", ",", "der_cert", ",", "reason", ")", ":", "if", "not", "callback", ":", "return", "callback", "(", "x509", ".", "Certificate", ".", "load", "(", "der_cert", ")", ",", "reason", ")" ]
25.052632
22.105263
def query(self, query): '''Returns objects matching criteria expressed in `query`. Follows links.''' results = super(SymlinkDatastore, self).query(query) return self._follow_link_gen(results)
[ "def", "query", "(", "self", ",", "query", ")", ":", "results", "=", "super", "(", "SymlinkDatastore", ",", "self", ")", ".", "query", "(", "query", ")", "return", "self", ".", "_follow_link_gen", "(", "results", ")" ]
50
18.5
def yyparse(self, lexfile): """ Args: lexfile (str): Flex file to be parsed Returns: DFA: A dfa automaton """ temp = tempfile.gettempdir() self.outfile = temp+'/'+''.join( random.choice( string.ascii_uppercase + string.d...
[ "def", "yyparse", "(", "self", ",", "lexfile", ")", ":", "temp", "=", "tempfile", ".", "gettempdir", "(", ")", "self", ".", "outfile", "=", "temp", "+", "'/'", "+", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase...
36.033333
11.3
def gen_part_from_line(lines: Iterable[str], part_index: int, splitter: str = None) -> Generator[str, None, None]: """ Splits lines with ``splitter`` and yields a specified part by index. Args: lines: iterable of strings part_index: index of par...
[ "def", "gen_part_from_line", "(", "lines", ":", "Iterable", "[", "str", "]", ",", "part_index", ":", "int", ",", "splitter", ":", "str", "=", "None", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "for", "line", "in", "lines"...
28.611111
16.5
def determine_offset(self): """Determines the offset of the contours w.r.t. other data columns Notes ----- - the "frame" column of `rtdc_dataset` is compared to the first contour in the contour text file to determine an offset by one event - modifies the pro...
[ "def", "determine_offset", "(", "self", ")", ":", "# In case of regular RTDC, the first contour is", "# missing. In case of fRTDC, it is there, so we", "# might have an offset. We find out if the first", "# contour frame is missing by comparing it to", "# the \"frame\" column of the rtdc dataset...
38.068966
16.862069
def extract_pool_attr(cls, req): """ Extract pool attributes from arbitary dict. """ attr = {} if 'id' in req: attr['id'] = int(req['id']) if 'name' in req: attr['name'] = req['name'] if 'description' in req: attr['description'] = req[...
[ "def", "extract_pool_attr", "(", "cls", ",", "req", ")", ":", "attr", "=", "{", "}", "if", "'id'", "in", "req", ":", "attr", "[", "'id'", "]", "=", "int", "(", "req", "[", "'id'", "]", ")", "if", "'name'", "in", "req", ":", "attr", "[", "'name'...
36.736842
16.631579