text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def filename_fix_existing(filename, dirname): """Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already. """ name, ext = filename.rsplit('.', 1) names = [x for x in os.listdir(dirname) if x.startswith(name)] names = [x.rsplit('.', 1)[0] for x in...
[ "def", "filename_fix_existing", "(", "filename", ",", "dirname", ")", ":", "name", ",", "ext", "=", "filename", ".", "rsplit", "(", "'.'", ",", "1", ")", "names", "=", "[", "x", "for", "x", "in", "os", ".", "listdir", "(", "dirname", ")", "if", "x"...
41.823529
0.001376
def load_obj(fn): """Load 3d mesh form .obj' file. Args: fn: Input file name or file-like object. Returns: dictionary with the following keys (some of which may be missing): position: np.float32, (n, 3) array, vertex positions uv: np.float32, (n, 2) array, vertex uv coordinates n...
[ "def", "load_obj", "(", "fn", ")", ":", "position", "=", "[", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "np", ".", "float32", ")", "]", "normal", "=", "[", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "np", ".", "float32", ")", "]"...
31.833333
0.01676
def _populate_attributes(self, config, record, context, data): """ Use a record found in LDAP to populate attributes. """ search_return_attributes = config['search_return_attributes'] for attr in search_return_attributes.keys(): if attr in record["attributes"]: ...
[ "def", "_populate_attributes", "(", "self", ",", "config", ",", "record", ",", "context", ",", "data", ")", ":", "search_return_attributes", "=", "config", "[", "'search_return_attributes'", "]", "for", "attr", "in", "search_return_attributes", ".", "keys", "(", ...
45.25
0.003091
def wait_for_finish(self): """ Call is_test_finished() on all plugins 'till one of them initiates exit """ if not self.interrupted.is_set(): logger.info("Waiting for test to finish...") logger.info('Artifacts dir: {dir}'.format(dir=self.artifacts_dir)) ...
[ "def", "wait_for_finish", "(", "self", ")", ":", "if", "not", "self", ".", "interrupted", ".", "is_set", "(", ")", ":", "logger", ".", "info", "(", "\"Waiting for test to finish...\"", ")", "logger", ".", "info", "(", "'Artifacts dir: {dir}'", ".", "format", ...
41.482759
0.002437
def parse_bismark_mbias(self, f): """ Parse the Bismark M-Bias plot data """ s = f['s_name'] self.bismark_mbias_data['meth']['CpG_R1'][s] = {} self.bismark_mbias_data['meth']['CHG_R1'][s] = {} self.bismark_mbias_data['meth']['CHH_R1'][s] = {} self.bismark_mbias_data['cov'...
[ "def", "parse_bismark_mbias", "(", "self", ",", "f", ")", ":", "s", "=", "f", "[", "'s_name'", "]", "self", ".", "bismark_mbias_data", "[", "'meth'", "]", "[", "'CpG_R1'", "]", "[", "s", "]", "=", "{", "}", "self", ".", "bismark_mbias_data", "[", "'m...
42.489362
0.002447
def get_conversion(scale, limits): """ Get the conversion equations for each axis. limits: dict of min and max values for the axes in the order blr. """ fb = float(scale) / float(limits['b'][1] - limits['b'][0]) fl = float(scale) / float(limits['l'][1] - limits['l'][0]) fr = float(scale) / ...
[ "def", "get_conversion", "(", "scale", ",", "limits", ")", ":", "fb", "=", "float", "(", "scale", ")", "/", "float", "(", "limits", "[", "'b'", "]", "[", "1", "]", "-", "limits", "[", "'b'", "]", "[", "0", "]", ")", "fl", "=", "float", "(", "...
36.533333
0.001779
def serialize( self, value, # type: Any state # type: _ProcessorState ): # type: (...) -> ET.Element """Serialize the value and returns it.""" xml_value = _hooks_apply_before_serialize(self._hooks, state, value) return self._processor.serialize(x...
[ "def", "serialize", "(", "self", ",", "value", ",", "# type: Any", "state", "# type: _ProcessorState", ")", ":", "# type: (...) -> ET.Element", "xml_value", "=", "_hooks_apply_before_serialize", "(", "self", ".", "_hooks", ",", "state", ",", "value", ")", "return", ...
36.444444
0.011905
def join(self, timeout=None): """Blocking wait for the execution to finish :param float timeout: Maximum time to wait or None for infinitely :return: True if the execution finished, False if no state machine was started or a timeout occurred :rtype: bool """ if self.__wa...
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "__wait_for_finishing_thread", ":", "if", "not", "timeout", ":", "# signal handlers won't work if timeout is None and the thread is joined", "while", "True", ":", "self", ".", "__w...
45.05
0.004348
def log_every_n(level, msg, n, *args): """Log 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: The level at which to log. msg: The message to be logged. n: The number of times this should be called before i...
[ "def", "log_every_n", "(", "level", ",", "msg", ",", "n", ",", "*", "args", ")", ":", "count", "=", "_GetNextLogCountPerToken", "(", "_GetFileAndLine", "(", ")", ")", "log_if", "(", "level", ",", "msg", ",", "not", "(", "count", "%", "n", ")", ",", ...
34.428571
0.00202
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution i...
[ "def", "getLocalIPaddress", "(", ")", ":", "try", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "s", ".", "connect", "(", "(", "'google.com'", ",", "0", ")", ")", "my_local_ip", "=", "s"...
44.235294
0.009115
def chord(ref, est, **kwargs): r'''Chord evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict Dictionary...
[ "def", "chord", "(", "ref", ",", "est", ",", "*", "*", "kwargs", ")", ":", "namespace", "=", "'chord'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_interval"...
28.365854
0.000831
def texture_from_image(renderer, image_name): """Create an SDL2 Texture from an image file""" soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
[ "def", "texture_from_image", "(", "renderer", ",", "image_name", ")", ":", "soft_surface", "=", "ext", ".", "load_image", "(", "image_name", ")", "texture", "=", "SDL_CreateTextureFromSurface", "(", "renderer", ".", "renderer", ",", "soft_surface", ")", "SDL_FreeS...
44.5
0.003676
def _put(self, *args, **kwargs): """ A wrapper for putting things. It will also json encode your 'data' parameter :returns: The response of your put :rtype: dict :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerE...
[ "def", "_put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'data'", "in", "kwargs", ":", "kwargs", "[", "'data'", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "'data'", "]", ")", "response", "=", "requests", "....
37
0.005857
def check_server_power(): """ Check if the server is powered on Skip this check, if the --noPowerState is set """ if power_state_flag: power_state = get_data(sess, oid_power_state, helper) power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power'...
[ "def", "check_server_power", "(", ")", ":", "if", "power_state_flag", ":", "power_state", "=", "get_data", "(", "sess", ",", "oid_power_state", ",", "helper", ")", "power_state_summary_output", ",", "power_state_long_output", "=", "state_summary", "(", "power_state", ...
49.333333
0.004425
def check_program(name): """ Uses the shell program "which" to determine whether the named program is available on the shell PATH. """ with open(os.devnull, "w") as null: try: subprocess.check_call(("which", name), stdout=null, stderr=null) except subprocess.CalledPr...
[ "def", "check_program", "(", "name", ")", ":", "with", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "as", "null", ":", "try", ":", "subprocess", ".", "check_call", "(", "(", "\"which\"", ",", "name", ")", ",", "stdout", "=", "null", ",", "...
30.5
0.005305
def delete(self, workflow_id, email_id): """ Removes an individual Automation workflow email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_i...
[ "def", "delete", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_bu...
38.846154
0.005803
def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. """ if self._regularizer is None: return 0.0 else: return se...
[ "def", "get_regularization_penalty", "(", "self", ")", "->", "Union", "[", "float", ",", "torch", ".", "Tensor", "]", ":", "if", "self", ".", "_regularizer", "is", "None", ":", "return", "0.0", "else", ":", "return", "self", ".", "_regularizer", "(", "se...
37
0.005865
def get_attribute_statement(self, subject, attributes): """ Build an AttributeStatement XML block for a SAML 1.1 Assertion. """ attribute_statement = etree.Element('AttributeStatement') attribute_statement.append(subject) for name, value in attributes.items(): ...
[ "def", "get_attribute_statement", "(", "self", ",", "subject", ",", "attributes", ")", ":", "attribute_statement", "=", "etree", ".", "Element", "(", "'AttributeStatement'", ")", "attribute_statement", ".", "append", "(", "subject", ")", "for", "name", ",", "val...
49
0.003337
def unescape(str): """Undoes the effects of the escape() function.""" out = '' prev_backslash = False for char in str: if not prev_backslash and char == '\\': prev_backslash = True continue out += char prev_backslash = False return out
[ "def", "unescape", "(", "str", ")", ":", "out", "=", "''", "prev_backslash", "=", "False", "for", "char", "in", "str", ":", "if", "not", "prev_backslash", "and", "char", "==", "'\\\\'", ":", "prev_backslash", "=", "True", "continue", "out", "+=", "char",...
26.636364
0.0033
def _setup_genome_annotations(g, args, ann_groups): """Configure genome annotations to install based on datatarget. """ available_anns = g.get("annotations", []) + g.pop("annotations_available", []) anns = [] for orig_target in args.datatarget: if orig_target in ann_groups: targe...
[ "def", "_setup_genome_annotations", "(", "g", ",", "args", ",", "ann_groups", ")", ":", "available_anns", "=", "g", ".", "get", "(", "\"annotations\"", ",", "[", "]", ")", "+", "g", ".", "pop", "(", "\"annotations_available\"", ",", "[", "]", ")", "anns"...
36.705882
0.003125
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value ...
[ "def", "deserialize_by_field", "(", "value", ",", "field", ")", ":", "if", "isinstance", "(", "field", ",", "forms", ".", "DateTimeField", ")", ":", "value", "=", "parse_datetime", "(", "value", ")", "elif", "isinstance", "(", "field", ",", "forms", ".", ...
35.333333
0.002299
def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog( self.iface.mainWindo...
[ "def", "show_shakemap_importer", "(", "self", ")", ":", "# import here only so that it is AFTER i18n set up", "from", "safe", ".", "gui", ".", "tools", ".", "shake_grid", ".", "shakemap_converter_dialog", "import", "(", "ShakemapConverterDialog", ")", "dialog", "=", "Sh...
41
0.005305
def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched")
[ "def", "get_dev_examples", "(", "self", ",", "data_dir", ")", ":", "return", "self", ".", "_create_examples", "(", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"dev_matched.tsv\"", ")", ")", ",", "\"dev_matched\"", ...
39.8
0.009852
def sphinx(ctx, browse=False, clean=False, watchdog=False, kill=False, status=False, opts=''): """Build Sphinx docs.""" cfg = config.load() if kill or status: if not watchdogctl(ctx, kill=kill): notify.info("No process bound to port {}".format(ctx.rituals.docs.watchdog.port)) re...
[ "def", "sphinx", "(", "ctx", ",", "browse", "=", "False", ",", "clean", "=", "False", ",", "watchdog", "=", "False", ",", "kill", "=", "False", ",", "status", "=", "False", ",", "opts", "=", "''", ")", ":", "cfg", "=", "config", ".", "load", "(",...
35.890756
0.002506
def _plot(self): """Draw all the serie slices""" total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return if self.half_pie: current_angle = 3 * pi / 2 else: current_angle = 0 for index, serie in enumerate(self....
[ "def", "_plot", "(", "self", ")", ":", "total", "=", "sum", "(", "map", "(", "sum", ",", "map", "(", "lambda", "x", ":", "x", ".", "values", ",", "self", ".", "series", ")", ")", ")", "if", "total", "==", "0", ":", "return", "if", "self", "."...
31.615385
0.004728
def delete_from_matching_blacklist(db, entity): """Remove an blacklisted entity from the registry. This function removes the given blacklisted entity from the registry. It checks first whether the excluded entity is already on the registry. When it is found, the entity is removed. Otherwise, it will ra...
[ "def", "delete_from_matching_blacklist", "(", "db", ",", "entity", ")", ":", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "mb", "=", "session", ".", "query", "(", "MatchingBlacklist", ")", ".", "filter", "(", "MatchingBlacklist", ".", "exc...
35.772727
0.001238
def all(self, list_id, subscriber_hash, **queryparams): """ Get the last 50 events of a member’s activity on a specific list, including opens, clicks, and unsubscribes. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param subscriber_hash: The...
[ "def", "all", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "*", "*", "queryparams", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "="...
46.722222
0.003497
def induce(self, b, filestem='default', examples=None, pos=None, neg=None, cn2sd=True, printOutput=False): """ Generate features and find subgroups. :param filestem: The base name of this experiment. ...
[ "def", "induce", "(", "self", ",", "b", ",", "filestem", "=", "'default'", ",", "examples", "=", "None", ",", "pos", "=", "None", ",", "neg", "=", "None", ",", "cn2sd", "=", "True", ",", "printOutput", "=", "False", ")", ":", "# Write the inputs", "s...
41.396552
0.005289
def initialize_mpi(mpi=False): """initialize mpi settings""" if mpi: import mpi4py.MPI comm = mpi4py.MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() else: comm = None rank = 0 size = 1 return...
[ "def", "initialize_mpi", "(", "mpi", "=", "False", ")", ":", "if", "mpi", ":", "import", "mpi4py", ".", "MPI", "comm", "=", "mpi4py", ".", "MPI", ".", "COMM_WORLD", "rank", "=", "comm", ".", "Get_rank", "(", ")", "size", "=", "comm", ".", "Get_size",...
24.588235
0.004608
def genlmsg_len(gnlh): """Return length of message payload including user header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L224 Positional arguments: gnlh -- Generic Netlink message header (genlmsghdr class instance). Returns: Length of user payload including an event...
[ "def", "genlmsg_len", "(", "gnlh", ")", ":", "nlh", "=", "nlmsghdr", "(", "bytearray_ptr", "(", "gnlh", ".", "bytearray", ",", "-", "NLMSG_HDRLEN", ",", "oob", "=", "True", ")", ")", "return", "nlh", ".", "nlmsg_len", "-", "GENL_HDRLEN", "-", "NLMSG_HDRL...
36.923077
0.004065
def get_runinfo(galaxy_url, galaxy_apikey, run_folder, storedir): """Retrieve flattened run information for a processed directory from Galaxy nglims API. """ galaxy_api = GalaxyApiAccess(galaxy_url, galaxy_apikey) fc_name, fc_date = flowcell.parse_dirname(run_folder) galaxy_info = galaxy_api.run_det...
[ "def", "get_runinfo", "(", "galaxy_url", ",", "galaxy_apikey", ",", "run_folder", ",", "storedir", ")", ":", "galaxy_api", "=", "GalaxyApiAccess", "(", "galaxy_url", ",", "galaxy_apikey", ")", "fc_name", ",", "fc_date", "=", "flowcell", ".", "parse_dirname", "("...
55.64
0.005654
def isin_start(elems, line): """Check if an element from a list starts a string. :type elems: list :type line: str """ found = False elems = [elems] if type(elems) is not list else elems for e in elems: if line.lstrip().lower().startswith(e): found = True br...
[ "def", "isin_start", "(", "elems", ",", "line", ")", ":", "found", "=", "False", "elems", "=", "[", "elems", "]", "if", "type", "(", "elems", ")", "is", "not", "list", "else", "elems", "for", "e", "in", "elems", ":", "if", "line", ".", "lstrip", ...
23.357143
0.002941
def wait_any(futures, timeout=None): '''Wait for the completion of any (the first) one of multiple futures :param list futures: A list of :class:`Future`\s :param timeout: The maximum time to wait. With ``None``, will block indefinitely. :type timeout: float or None :returns: One o...
[ "def", "wait_any", "(", "futures", ",", "timeout", "=", "None", ")", ":", "for", "fut", "in", "futures", ":", "if", "fut", ".", "complete", ":", "return", "fut", "wait", "=", "_Wait", "(", "futures", ")", "for", "fut", "in", "futures", ":", "fut", ...
27.592593
0.002594
def pairs_to_dict(response, decode_keys=False): "Create a dict given a list of key/value pairs" if response is None: return {} if decode_keys: # the iter form is faster, but I don't know how to make that work # with a nativestr() map return dict(izip(imap(nativestr, response[...
[ "def", "pairs_to_dict", "(", "response", ",", "decode_keys", "=", "False", ")", ":", "if", "response", "is", "None", ":", "return", "{", "}", "if", "decode_keys", ":", "# the iter form is faster, but I don't know how to make that work", "# with a nativestr() map", "retu...
36.818182
0.00241
def _list_hosts(): ''' Return the hosts found in the hosts file in as an OrderedDict ''' try: return __context__['hosts._list_hosts'] except KeyError: count = 0 hfn = __get_hosts_filename() ret = odict.OrderedDict() try: with salt.utils.files.fopen...
[ "def", "_list_hosts", "(", ")", ":", "try", ":", "return", "__context__", "[", "'hosts._list_hosts'", "]", "except", "KeyError", ":", "count", "=", "0", "hfn", "=", "__get_hosts_filename", "(", ")", "ret", "=", "odict", ".", "OrderedDict", "(", ")", "try",...
37.181818
0.002383
def blocks(self, *args, **kwargs): """ Interface to apply audiolazy.blocks directly in a stream, returning another stream. Use keyword args. """ return Stream(blocks(iter(self), *args, **kwargs))
[ "def", "blocks", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Stream", "(", "blocks", "(", "iter", "(", "self", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
35
0.004651
def stack_outputs(self, name): """ Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict. """ try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] return {x['OutputKey']: x['OutputV...
[ "def", "stack_outputs", "(", "self", ",", "name", ")", ":", "try", ":", "stack", "=", "self", ".", "cf_client", ".", "describe_stacks", "(", "StackName", "=", "name", ")", "[", "'Stacks'", "]", "[", "0", "]", "return", "{", "x", "[", "'OutputKey'", "...
41
0.00716
def eval(cls, exp, files=None): """ :param str|unicode exp: Haskell expression to evaluate. :rtype: str|unicode """ return cls.show(cls.get(exp, files=files))
[ "def", "eval", "(", "cls", ",", "exp", ",", "files", "=", "None", ")", ":", "return", "cls", ".", "show", "(", "cls", ".", "get", "(", "exp", ",", "files", "=", "files", ")", ")" ]
32.166667
0.010101
def IOWR(type, nr, size): """ An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size))
[ "def", "IOWR", "(", "type", ",", "nr", ",", "size", ")", ":", "return", "IOC", "(", "IOC_READ", "|", "IOC_WRITE", ",", "type", ",", "nr", ",", "IOC_TYPECHECK", "(", "size", ")", ")" ]
32.5
0.003745
def do_denyaccess(self, line): """denyaccess <subject> Remove subject from access policy.""" subject, = self._split_args(line, 1, 0) self._command_processor.get_session().get_access_control().remove_allowed_subject( subject ) self._print_info_if_verbose( '...
[ "def", "do_denyaccess", "(", "self", ",", "line", ")", ":", "subject", ",", "=", "self", ".", "_split_args", "(", "line", ",", "1", ",", "0", ")", "self", ".", "_command_processor", ".", "get_session", "(", ")", ".", "get_access_control", "(", ")", "."...
42
0.007772
def delete_job(job_id, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ delete a job with a specific job id """ headers = token_manager.get_access_token_headers() data_url = get_data_url_for_job(job_id, ...
[ "def", "delete_job", "(", "job_id", ",", "deployment_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "data_url", "=", "get_data_url_f...
35
0.002928
def delete_keyring(service): """Delete an existing Ceph keyring.""" keyring = _keyring_path(service) if not os.path.exists(keyring): log('Keyring does not exist at %s' % keyring, level=WARNING) return os.remove(keyring) log('Deleted ring at %s.' % keyring, level=INFO)
[ "def", "delete_keyring", "(", "service", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "log", "(", "'Keyring does not exist at %s'", "%", "keyring", ",", "level", "=...
33
0.003279
def _set_nport(self, v, load=False): """ Setter method for nport, mapped from YANG variable /rbridge_id/ag/pg/nport (container) If this variable is read-only (config: false) in the source YANG file, then _set_nport is considered as a private method. Backends looking to populate this variable should ...
[ "def", "_set_nport", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
68.545455
0.00654
def __oscillator_property(self, index): """! @brief Calculate Landau-Stuart oscillator constant property that is based on frequency and radius. @param[in] index (uint): Oscillator index whose property is calculated. @return (double) Oscillator property. ...
[ "def", "__oscillator_property", "(", "self", ",", "index", ")", ":", "return", "numpy", ".", "array", "(", "1j", "*", "self", ".", "__frequency", "[", "index", "]", "+", "self", ".", "__radius", "[", "index", "]", "**", "2", ",", "dtype", "=", "numpy...
41.272727
0.028017
def stop(self, activity, action): ''' Mark a task as completed :param activity: The virtualenv activity name :type activity: ``str`` :param action: The virtualenv action :type action: :class:`tox.session.Action` ''' try: self._remove_runnin...
[ "def", "stop", "(", "self", ",", "activity", ",", "action", ")", ":", "try", ":", "self", ".", "_remove_running_action", "(", "activity", ",", "action", ")", "except", "ValueError", ":", "retox_log", ".", "debug", "(", "\"Could not find action %s in env %s\"", ...
32.8125
0.005556
def spec(self): """ Generate spec for the processor as a Python dictionary. A spec is a standard way to describe a MountainLab processor in a way that is easy to process, yet still understandable by humans. This method generates a Python dictionary that complies with a spec ...
[ "def", "spec", "(", "self", ")", ":", "pspec", "=", "{", "}", "pspec", "[", "'name'", "]", "=", "self", ".", "NAME", "pspec", "[", "'version'", "]", "=", "self", ".", "VERSION", "pspec", "[", "'description'", "]", "=", "self", ".", "DESCRIPTION", "...
40.72
0.009597
def actualize (self): """ Generates actual build instructions. """ if self.actualized_: return self.actualized_ = True ps = self.properties () properties = self.adjust_properties (ps) actual_targets = [] for i in self.targets (): ...
[ "def", "actualize", "(", "self", ")", ":", "if", "self", ".", "actualized_", ":", "return", "self", ".", "actualized_", "=", "True", "ps", "=", "self", ".", "properties", "(", ")", "properties", "=", "self", ".", "adjust_properties", "(", "ps", ")", "a...
36.954545
0.012582
def _slicespec2boundsspec(slicespec,scs): """ Convert an iterable slicespec (supplying r1,r2,c1,c2 of a Slice) into a BoundingRegion specification. Exact inverse of _boundsspec2slicespec(). """ r1,r2,c1,c2 = slicespec left,bottom = scs.matrix2sheet(r2,c1) ...
[ "def", "_slicespec2boundsspec", "(", "slicespec", ",", "scs", ")", ":", "r1", ",", "r2", ",", "c1", ",", "c2", "=", "slicespec", "left", ",", "bottom", "=", "scs", ".", "matrix2sheet", "(", "r2", ",", "c1", ")", "right", ",", "top", "=", "scs", "."...
30.076923
0.032258
def cmd_signing_setup(self, args): '''setup signing key on board''' if len(args) == 0: print("usage: signing setup passphrase") return if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return passphrase = args[...
[ "def", "cmd_signing_setup", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "print", "(", "\"usage: signing setup passphrase\"", ")", "return", "if", "not", "self", ".", "master", ".", "mavlink20", "(", ")", ":", "print...
38.52381
0.003619
def remove(self, objs): """ Removes the given `objs` from this `LinkCollection`. - **objs** can be a list of :py:class:`.PanoptesObject` instances, a list of object IDs, a single :py:class:`.PanoptesObject` instance, or a single object ID. Examples:: or...
[ "def", "remove", "(", "self", ",", "objs", ")", ":", "if", "self", ".", "readonly", ":", "raise", "NotImplementedError", "(", "'{} links can\\'t be modified'", ".", "format", "(", "self", ".", "_slug", ")", ")", "if", "not", "self", ".", "_parent", ".", ...
33.026316
0.001548
def floating_ip_pool_list(self): ''' List all floating IP pools .. versionadded:: 2016.3.0 ''' nt_ks = self.compute_conn pools = nt_ks.floating_ip_pools.list() response = {} for pool in pools: response[pool.name] = { 'name': po...
[ "def", "floating_ip_pool_list", "(", "self", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "pools", "=", "nt_ks", ".", "floating_ip_pools", ".", "list", "(", ")", "response", "=", "{", "}", "for", "pool", "in", "pools", ":", "response", "[", "pool...
25.214286
0.005464
def expected_h(nvals, fit="RANSAC"): """ Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculation. Args: nvals (iterable of int): the values of n used to calculate the individual (R/S)_n KWargs: fit (str): the fitting met...
[ "def", "expected_h", "(", "nvals", ",", "fit", "=", "\"RANSAC\"", ")", ":", "rsvals", "=", "[", "expected_rs", "(", "n", ")", "for", "n", "in", "nvals", "]", "poly", "=", "poly_fit", "(", "np", ".", "log", "(", "nvals", ")", ",", "np", ".", "log"...
29.272727
0.007519
def get_internal_broks(self): """Get all broks from self.broks_internal_raised and append them to our broks to manage :return: None """ statsmgr.gauge('get-new-broks-count.broker', len(self.internal_broks)) # Add the broks to our global list self.external_broks.e...
[ "def", "get_internal_broks", "(", "self", ")", ":", "statsmgr", ".", "gauge", "(", "'get-new-broks-count.broker'", ",", "len", "(", "self", ".", "internal_broks", ")", ")", "# Add the broks to our global list", "self", ".", "external_broks", ".", "extend", "(", "s...
37
0.007916
def osCopy(self): """ Triggers the OS "copy" keyboard shortcut """ k = Keyboard() k.keyDown("{CTRL}") k.type("c") k.keyUp("{CTRL}")
[ "def", "osCopy", "(", "self", ")", ":", "k", "=", "Keyboard", "(", ")", "k", ".", "keyDown", "(", "\"{CTRL}\"", ")", "k", ".", "type", "(", "\"c\"", ")", "k", ".", "keyUp", "(", "\"{CTRL}\"", ")" ]
27.666667
0.011696
def revert(self, revision_id): """Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`inven...
[ "def", "revert", "(", "self", ",", "revision_id", ")", ":", "if", "self", ".", "model", "is", "None", ":", "raise", "MissingModelError", "(", ")", "revision", "=", "self", ".", "revisions", "[", "revision_id", "]", "with", "db", ".", "session", ".", "b...
31.970588
0.001786
def chrome_tracing_dump(self, filename=None): """Return a list of profiling events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome w...
[ "def", "chrome_tracing_dump", "(", "self", ",", "filename", "=", "None", ")", ":", "# TODO(rkn): Support including the task specification data in the", "# timeline.", "# TODO(rkn): This should support viewing just a window of time or a", "# limited number of events.", "profile_table", ...
44.942029
0.000631
def setup(cli): """Everything to make skypipe ready to use""" if not cli.global_config.loaded: setup_dotcloud_account(cli) discover_satellite(cli) cli.success("Skypipe is ready for action")
[ "def", "setup", "(", "cli", ")", ":", "if", "not", "cli", ".", "global_config", ".", "loaded", ":", "setup_dotcloud_account", "(", "cli", ")", "discover_satellite", "(", "cli", ")", "cli", ".", "success", "(", "\"Skypipe is ready for action\"", ")" ]
34.666667
0.004695
def _remove_dict_keys_with_value(dict_, val): """Removes `dict` keys which have have `self` as value.""" return {k: v for k, v in dict_.items() if v is not val}
[ "def", "_remove_dict_keys_with_value", "(", "dict_", ",", "val", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "dict_", ".", "items", "(", ")", "if", "v", "is", "not", "val", "}" ]
54
0.018293
def _getVals(self, prefix = ""): """ return the values in the vals dict in case prefix is "", change the first letter of the name to lowercase, otherwise use prefix+name as the new name """ if not hasattr(self, "vals"): self.vals = {} dict = {} for key...
[ "def", "_getVals", "(", "self", ",", "prefix", "=", "\"\"", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"vals\"", ")", ":", "self", ".", "vals", "=", "{", "}", "dict", "=", "{", "}", "for", "key", "in", "list", "(", "self", ".", "vals...
40.352941
0.007123
def defaultRetryPredicate(exception): """ >>> defaultRetryPredicate(socket.error()) True >>> defaultRetryPredicate(socket.gaierror()) True >>> defaultRetryPredicate(HTTPException()) True >>> defaultRetryPredicate(requests.ConnectionError()) True >>> defaultRetryPredicate(AzureExc...
[ "def", "defaultRetryPredicate", "(", "exception", ")", ":", "return", "(", "isinstance", "(", "exception", ",", "(", "socket", ".", "error", ",", "socket", ".", "gaierror", ",", "HTTPException", ",", "requests", ".", "ConnectionError", ",", "requests", ".", ...
37.83871
0.001663
def _create_index(self): 'Create the index' try: self.conn.indices.create( index=self.index, timeout=60, request_timeout=60, body={ 'settings': { 'number_of_shards': self.shards, 'number_of_replicas': self.re...
[ "def", "_create_index", "(", "self", ")", ":", "try", ":", "self", ".", "conn", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "index", ",", "timeout", "=", "60", ",", "request_timeout", "=", "60", ",", "body", "=", "{", "'settings'",...
38.428571
0.00363
def parsefile(self, filename): """Parse from the file """ with open(filename, 'rb') as fd: return self.parse(fd.read())
[ "def", "parsefile", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "return", "self", ".", "parse", "(", "fd", ".", "read", "(", ")", ")" ]
30.2
0.012903
def event_update_list(request, slug): """ Returns a list view of updates for a given event. If the event is over, it will be in chronological order. If the event is upcoming or still going, it will be in reverse chronological order. """ event = get_object_or_404(Event, slug=slug) updates...
[ "def", "event_update_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "updates", "=", "Update", ".", "objects", ".", "filter", "(", "event__slug", "=", "slug", ")", "if", "event...
36.789474
0.001395
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
[ "def", "separate", "(", "text", ")", ":", "alphabet", "=", "'abcdefghijklmnopqrstuvwxyz'", "words", "=", "text", ".", "split", "(", ")", "standardwords", "=", "[", "]", "for", "word", "in", "words", ":", "newstr", "=", "''", "for", "char", "in", "word", ...
33.384615
0.006726
def _api_arguments(self): """Argument specific to working with TC API. --tc_token token Token provided by ThreatConnect for app Authorization. --tc_token_expires token_expires Expiration time for the passed Token. --api_access_id access_id Access ID used for HM...
[ "def", "_api_arguments", "(", "self", ")", ":", "# TC main >= 4.4 token will be passed to jobs.", "self", ".", "add_argument", "(", "'--tc_token'", ",", "default", "=", "None", ",", "help", "=", "'ThreatConnect API Token'", ")", "self", ".", "add_argument", "(", "'-...
40.666667
0.007206
def application_uri(self): """The base URI of the application (wsgiref.util.application_uri).""" if self._application_uri is None: self._application_uri = application_uri(self.environ) return self._application_uri
[ "def", "application_uri", "(", "self", ")", ":", "if", "self", ".", "_application_uri", "is", "None", ":", "self", ".", "_application_uri", "=", "application_uri", "(", "self", ".", "environ", ")", "return", "self", ".", "_application_uri" ]
49
0.008032
def age_range(self): """A tuple of two ints - the minimum and maximum age of the person.""" if self.date_range is None: return None, None start_date = DateRange(self.date_range.start, self.date_range.start) end_date = DateRange(self.date_range.end, self.date_range.end) ...
[ "def", "age_range", "(", "self", ")", ":", "if", "self", ".", "date_range", "is", "None", ":", "return", "None", ",", "None", "start_date", "=", "DateRange", "(", "self", ".", "date_range", ".", "start", ",", "self", ".", "date_range", ".", "start", ")...
49.444444
0.004415
def select_attribute(source, name, val=None): ''' Yields elements from the source having the given attrivute, optionally with the given attribute value source - if an element, starts with all child elements in order; can also be any other iterator name - attribute name to check val - if None check o...
[ "def", "select_attribute", "(", "source", ",", "name", ",", "val", "=", "None", ")", ":", "def", "check", "(", "x", ")", ":", "if", "val", "is", "None", ":", "return", "name", "in", "x", ".", "xml_attributes", "else", ":", "return", "name", "in", "...
48.076923
0.006279
def _struct_get_field(expr, field_name): """Get the `field_name` field from the ``Struct`` expression `expr`. Parameters ---------- field_name : str The name of the field to access from the ``Struct`` typed expression `expr`. Must be a Python ``str`` type; programmatic struct field ...
[ "def", "_struct_get_field", "(", "expr", ",", "field_name", ")", ":", "return", "ops", ".", "StructField", "(", "expr", ",", "field_name", ")", ".", "to_expr", "(", ")", ".", "name", "(", "field_name", ")" ]
34.375
0.00177
def add(self, metric_name, stat, config=None): """ Register a metric with this sensor Arguments: metric_name (MetricName): The name of the metric stat (AbstractMeasurableStat): The statistic to keep config (MetricConfig): A special configuration for this metr...
[ "def", "add", "(", "self", ",", "metric_name", ",", "stat", ",", "config", "=", "None", ")", ":", "with", "self", ".", "_lock", ":", "metric", "=", "KafkaMetric", "(", "metric_name", ",", "stat", ",", "config", "or", "self", ".", "_config", ")", "sel...
40.866667
0.00319
def get_scope_names(self) -> list: """ Return the list of all contained scope from global to local """ # allow global scope to have an None string instance lscope = [] for scope in reversed(self.get_scope_list()): if scope.name is not None: # h...
[ "def", "get_scope_names", "(", "self", ")", "->", "list", ":", "# allow global scope to have an None string instance", "lscope", "=", "[", "]", "for", "scope", "in", "reversed", "(", "self", ".", "get_scope_list", "(", ")", ")", ":", "if", "scope", ".", "name"...
36.909091
0.004808
def get_password(self, service, username): """Get password of the username for the service """ collection = self.get_preferred_collection() items = collection.search_items( {"username": username, "service": service}) for item in items: if hasattr(item, 'un...
[ "def", "get_password", "(", "self", ",", "service", ",", "username", ")", ":", "collection", "=", "self", ".", "get_preferred_collection", "(", ")", "items", "=", "collection", ".", "search_items", "(", "{", "\"username\"", ":", "username", ",", "\"service\"",...
43.916667
0.003717
def worker_failed(): """Fail worker. Used by bots only for now.""" participant_id = request.args.get("participant_id") if not participant_id: return error_response( error_type="bad request", error_text="participantId parameter is required" ) try: _worker_failed(parti...
[ "def", "worker_failed", "(", ")", ":", "participant_id", "=", "request", ".", "args", ".", "get", "(", "\"participant_id\"", ")", "if", "not", "participant_id", ":", "return", "error_response", "(", "error_type", "=", "\"bad request\"", ",", "error_text", "=", ...
30.888889
0.00349
def log_config(self, value): """ { "Type": "<driver_name>", "Config": {"key1": "val1"}} """ if not isinstance(value, dict): raise TypeError("log_config must be a dict. {0} was passed".format(value)) config = value.get('config') driver_type = value.get('t...
[ "def", "log_config", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"log_config must be a dict. {0} was passed\"", ".", "format", "(", "value", ")", ")", "config", "=", "value...
40.043478
0.007423
def word_tokenize(sentence, format=None): """ Vietnamese word segmentation Parameters ========== sentence: {unicode, str} raw sentence Returns ======= tokens: list of text tagged sentence Examples -------- >>> # -*- coding: utf-8 -*- >>> from underthe...
[ "def", "word_tokenize", "(", "sentence", ",", "format", "=", "None", ")", ":", "tokens", "=", "tokenize", "(", "sentence", ")", "crf_model", "=", "CRFModel", ".", "instance", "(", ")", "output", "=", "crf_model", ".", "predict", "(", "tokens", ",", "form...
26.904762
0.002562
def rhn_schema_version(context): """ Function to parse the output of command ``/usr/bin/rhn-schema-version``. Sample input:: 5.6.0.10-2.el6sat Examples: >>> db_ver = shared[rhn_schema_version] >>> db_ver '5.6.0.10-2.el6sat' """ if context.content: cont...
[ "def", "rhn_schema_version", "(", "context", ")", ":", "if", "context", ".", "content", ":", "content", "=", "context", ".", "content", "if", "len", "(", "content", ")", "==", "1", "and", "'No such'", "not", "in", "content", "[", "0", "]", ":", "ver", ...
23.4
0.002053
def checkerboard_matrix_filtering(similarity_matrix, kernel_width, peak_range): """ Moving the checkerboard matrix over the main diagonal of the similarity matrix one sample at a time. :param similarity_matrix: :param peak_range: the number of samples in which the peak detection algorithms finds a peak...
[ "def", "checkerboard_matrix_filtering", "(", "similarity_matrix", ",", "kernel_width", ",", "peak_range", ")", ":", "checkerboard_matrix", "=", "get_checkerboard_matrix", "(", "kernel_width", ")", "# The values calculated in this step are starting from the 'kernel_width' position and...
47.709677
0.003976
def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0])
[ "def", "add", "(", "self", ",", "string", ",", "start", ",", "end", ",", "line", ")", ":", "if", "string", ".", "strip", "(", ")", ":", "# Only add if not entirely whitespace.", "self", ".", "start_lineno", "=", "min", "(", "self", ".", "start_lineno", "...
40.571429
0.006897
def _get_path(fname: str) -> str: """ :meth: download get path of file from pythainlp-corpus :param str fname: file name :return: path to downloaded file """ path = get_corpus_path(fname) if not path: download(fname) path = get_corpus_path(fname) return path
[ "def", "_get_path", "(", "fname", ":", "str", ")", "->", "str", ":", "path", "=", "get_corpus_path", "(", "fname", ")", "if", "not", "path", ":", "download", "(", "fname", ")", "path", "=", "get_corpus_path", "(", "fname", ")", "return", "path" ]
26.909091
0.003268
def _build_crawlid_info(self, master, dict): ''' Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object ''' master['total_pending'] = 0 master['total_domains'] = 0 maste...
[ "def", "_build_crawlid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'appid'", "]", "=", "dict", "[", "'appid'", "]", "master", ...
45.27451
0.003815
def Getvar(self, var, info_cb=DEFAULT_MESSAGE_CALLBACK): """Returns the given variable's definition. Args: var: A variable the bootloader tracks. Use 'all' to get them all. info_cb: See Download. Usually no messages. Returns: Value of var according to the current ...
[ "def", "Getvar", "(", "self", ",", "var", ",", "info_cb", "=", "DEFAULT_MESSAGE_CALLBACK", ")", ":", "return", "self", ".", "_SimpleCommand", "(", "b'getvar'", ",", "arg", "=", "var", ",", "info_cb", "=", "info_cb", ")" ]
36.818182
0.004819
def guest_delete_nic(self, userid, vdev, active=False): """ delete the nic for the vm :param str userid: the user id of the vm :param str vdev: nic device number, 1- to 4- hexadecimal digits :param bool active: whether delete a nic on active guest system """ self._networ...
[ "def", "guest_delete_nic", "(", "self", ",", "userid", ",", "vdev", ",", "active", "=", "False", ")", ":", "self", ".", "_networkops", ".", "delete_nic", "(", "userid", ",", "vdev", ",", "active", "=", "active", ")" ]
44.625
0.005495
def J(self): ''' Compute Jacobian. Analyze dr graph first to disable unnecessary caching ''' result = self.dr_wrt(self.x, profiler=self.profiler).copy() if self.profiler: self.profiler.harvest() return np.atleast_2d(result) if not sp.issparse(result) else resu...
[ "def", "J", "(", "self", ")", ":", "result", "=", "self", ".", "dr_wrt", "(", "self", ".", "x", ",", "profiler", "=", "self", ".", "profiler", ")", ".", "copy", "(", ")", "if", "self", ".", "profiler", ":", "self", ".", "profiler", ".", "harvest"...
39.375
0.006211
def cli_schema(self, *args): """Display a single schema definition""" key = None if len(args) > 1: key = args[1] args = list(args) if '-config' in args or '-c' in args: store = configschemastore try: args.remove('-c') ...
[ "def", "cli_schema", "(", "self", ",", "*", "args", ")", ":", "key", "=", "None", "if", "len", "(", "args", ")", ">", "1", ":", "key", "=", "args", "[", "1", "]", "args", "=", "list", "(", "args", ")", "if", "'-config'", "in", "args", "or", "...
33.153846
0.003757
def collapseCycles(self): """Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node. """ # This algorithm determines Strongly Connected Components. Look it up. # It is adapted to suit our data structures. # Phase 0: prepare the ...
[ "def", "collapseCycles", "(", "self", ")", ":", "# This algorithm determines Strongly Connected Components. Look it up.", "# It is adapted to suit our data structures.", "# Phase 0: prepare the graph", "imports", "=", "{", "}", "for", "u", "in", "self", ".", "modules", ":", ...
34.393939
0.002141
def xstep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{x}`. """ self.YU[:] = self.Y - self.U b = self.DSf + self.rho*sl.rfftn(self.YU, None, self.cri.axisN) if self.cri.Cd == 1: self.Xf[:] = sl.solvedbi_sm(self.Df, self.mu + self.r...
[ "def", "xstep", "(", "self", ")", ":", "self", ".", "YU", "[", ":", "]", "=", "self", ".", "Y", "-", "self", ".", "U", "b", "=", "self", ".", "DSf", "+", "self", ".", "rho", "*", "sl", ".", "rfftn", "(", "self", ".", "YU", ",", "None", ",...
38.535714
0.004521
async def verify_docker_image_task(chain, link): """Verify the docker image Link. Args: chain (ChainOfTrust): the chain we're operating on. link (LinkOfTrust): the task link we're checking. """ errors = [] # workerType worker_type = get_worker_type(link.task) if worker_type...
[ "async", "def", "verify_docker_image_task", "(", "chain", ",", "link", ")", ":", "errors", "=", "[", "]", "# workerType", "worker_type", "=", "get_worker_type", "(", "link", ".", "task", ")", "if", "worker_type", "not", "in", "chain", ".", "context", ".", ...
34.785714
0.006
def autobuild_bootstrap_file(file_name, image_list): """Combine multiple firmware images into a single bootstrap hex file. The files listed in image_list must be products of either this tile or any dependency tile and should correspond exactly with the base name listed on the products section of the mo...
[ "def", "autobuild_bootstrap_file", "(", "file_name", ",", "image_list", ")", ":", "family", "=", "utilities", ".", "get_family", "(", "'module_settings.json'", ")", "target", "=", "family", ".", "platform_independent_target", "(", ")", "resolver", "=", "ProductResol...
41.452381
0.001684
def reduce(function, initval=None): """ Curried version of the built-in reduce. >>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] ) 15 """ if initval is None: return lambda s: __builtin__.reduce(function, s) else: return lambda s: __builtin__.reduce(function, s, initval)
[ "def", "reduce", "(", "function", ",", "initval", "=", "None", ")", ":", "if", "initval", "is", "None", ":", "return", "lambda", "s", ":", "__builtin__", ".", "reduce", "(", "function", ",", "s", ")", "else", ":", "return", "lambda", "s", ":", "__bui...
24.454545
0.043011
def cancel(): """Returns a threading.Event() that will get set when SIGTERM, or SIGINT are triggered. This can be used to cancel execution of threads. """ cancel = threading.Event() def cancel_execution(signum, frame): signame = SIGNAL_NAMES.get(signum, signum) logger.info("Signal %...
[ "def", "cancel", "(", ")", ":", "cancel", "=", "threading", ".", "Event", "(", ")", "def", "cancel_execution", "(", "signum", ",", "frame", ")", ":", "signame", "=", "SIGNAL_NAMES", ".", "get", "(", "signum", ",", "signum", ")", "logger", ".", "info", ...
35.466667
0.001832
def to_input(self, mol=None, charge=None, spin_multiplicity=None, title=None, functional=None, basis_set=None, route_parameters=None, input_parameters=None, link0_parameters=None, dieze_tag=None, cart_coords=False): """ Create a new input object using ...
[ "def", "to_input", "(", "self", ",", "mol", "=", "None", ",", "charge", "=", "None", ",", "spin_multiplicity", "=", "None", ",", "title", "=", "None", ",", "functional", "=", "None", ",", "basis_set", "=", "None", ",", "route_parameters", "=", "None", ...
34.44898
0.00288
def render(self): """Render reply from Python object to XML string""" tpl = '<xml>\n{data}\n</xml>' nodes = [] msg_type = '<MsgType><![CDATA[{msg_type}]]></MsgType>'.format( msg_type=self.type ) nodes.append(msg_type) for name, field in self._fields.it...
[ "def", "render", "(", "self", ")", ":", "tpl", "=", "'<xml>\\n{data}\\n</xml>'", "nodes", "=", "[", "]", "msg_type", "=", "'<MsgType><![CDATA[{msg_type}]]></MsgType>'", ".", "format", "(", "msg_type", "=", "self", ".", "type", ")", "nodes", ".", "append", "(",...
36.785714
0.003788
def get_all_project_owners(project_ids=None, **kwargs): """ Get the project owner entries for all the requested projects. If the project_ids argument is None, return all the owner entries for ALL projects """ projowner_qry = db.DBSession.query(ProjectOwner) if project_ids is n...
[ "def", "get_all_project_owners", "(", "project_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "projowner_qry", "=", "db", ".", "DBSession", ".", "query", "(", "ProjectOwner", ")", "if", "project_ids", "is", "not", "None", ":", "projowner_qry", "=", ...
32.8125
0.009259
def setup_file_logger(filename, formatting, log_level): """ A helper function for creating a file logger. Accepts arguments, as it is used in Status and LoggingWriter. """ logger = logging.getLogger() # If a stream handler has been attached, remove it. if logger.handlers: logger.remo...
[ "def", "setup_file_logger", "(", "filename", ",", "formatting", ",", "log_level", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "# If a stream handler has been attached, remove it.", "if", "logger", ".", "handlers", ":", "logger", ".", "removeHandl...
35.8125
0.001701
def multiple_input(*args, **kwargs): ''' Multiline input ''' multiline_input = wtforms.SelectMultipleField(*args, **kwargs) multiline_input.input_type = 'multiline' return multiline_input
[ "def", "multiple_input", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "multiline_input", "=", "wtforms", ".", "SelectMultipleField", "(", "*", "args", ",", "*", "*", "kwargs", ")", "multiline_input", ".", "input_type", "=", "'multiline'", "return", ...
29.285714
0.004739
def load_image(self, file_path, redraw=True): """ Accepts a path to an 8 x 8 image file and updates the LED matrix with the image """ if not os.path.exists(file_path): raise IOError('%s not found' % file_path) img = Image.open(file_path).convert('RGB') ...
[ "def", "load_image", "(", "self", ",", "file_path", ",", "redraw", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "IOError", "(", "'%s not found'", "%", "file_path", ")", "img", "=", "Image", ...
27.375
0.004415
def date_range(start, end, length, time_unit='us'): """ Computes a date range given a start date, end date and the number of samples. """ step = (1./compute_density(start, end, length, time_unit)) if pd and isinstance(start, pd.Timestamp): start = start.to_datetime64() step = np.time...
[ "def", "date_range", "(", "start", ",", "end", ",", "length", ",", "time_unit", "=", "'us'", ")", ":", "step", "=", "(", "1.", "/", "compute_density", "(", "start", ",", "end", ",", "length", ",", "time_unit", ")", ")", "if", "pd", "and", "isinstance...
39.5
0.002475
def save(self, *args, **kwargs): """ saves creates or updates current resource returns new resource """ self._pre_save(*args, **kwargs) response = self._save(*args, **kwargs) response = self._post_save(response, *args, **kwargs) return response
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pre_save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "response", "=", "self", ".", "_save", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
33.333333
0.006494
def __get_constants(self): """ Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs. """ helper = ConstantClass(self._constants_class_name, self._io) helper.reload() constants = helper.constants() for name,...
[ "def", "__get_constants", "(", "self", ")", ":", "helper", "=", "ConstantClass", "(", "self", ".", "_constants_class_name", ",", "self", ".", "_io", ")", "helper", ".", "reload", "(", ")", "constants", "=", "helper", ".", "constants", "(", ")", "for", "n...
41.384615
0.007273
def register(name, fn=None): """ Decorator to register a function as a hook Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_...
[ "def", "register", "(", "name", ",", "fn", "=", "None", ")", ":", "def", "_hook_add", "(", "func", ")", ":", "if", "name", "not", "in", "_hooks", ":", "logger", ".", "debug", "(", "\"Creating new hook %s\"", "%", "name", ")", "_hooks", "[", "name", "...
28.142857
0.000981