text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def zulu(self): ''' a method to report ISO UTC datetime string from a labDT object NOTE: for timezone offset string use .isoformat() instead :return: string in ISO UTC format ''' # construct ISO UTC string from labDT utc_dt = self.astimezone(pytz.utc) i...
[ "def", "zulu", "(", "self", ")", ":", "# construct ISO UTC string from labDT\r", "utc_dt", "=", "self", ".", "astimezone", "(", "pytz", ".", "utc", ")", "iso_dt", "=", "utc_dt", ".", "isoformat", "(", ")", "return", "iso_dt", ".", "replace", "(", "'+00:00'",...
29.230769
21.846154
def extract_slices(z, freq, sample_freq, show_plot=False): """ Iterates through z trace and pulls out slices of length period_samples and assigns them a phase from -180 to 180. Each slice then becomes a column in the 2d array that is returned. Such that the row (the first index) refers to phase (i.e...
[ "def", "extract_slices", "(", "z", ",", "freq", ",", "sample_freq", ",", "show_plot", "=", "False", ")", ":", "dt", "=", "1", "/", "sample_freq", "# dt between samples", "period", "=", "1", "/", "freq", "# period of oscillation of motion", "period_samples", "=",...
38.181818
25.381818
def add_data_item(self, data_item: DataItem) -> None: """Add a data item to the group. :param data_item: The :py:class:`nion.swift.Facade.DataItem` object to add. .. versionadded:: 1.0 Scriptable: Yes """ display_item = data_item._data_item.container.get_display_item_f...
[ "def", "add_data_item", "(", "self", ",", "data_item", ":", "DataItem", ")", "->", "None", ":", "display_item", "=", "data_item", ".", "_data_item", ".", "container", ".", "get_display_item_for_data_item", "(", "data_item", ".", "_data_item", ")", "if", "data_it...
39.666667
29.416667
def enrol(self, event): """A user tries to self-enrol with the enrolment form""" if self.config.allow_registration is False: self.log('Someone tried to register although enrolment is closed.') return self.log('Client trying to register a new account:', event, pretty=Tru...
[ "def", "enrol", "(", "self", ",", "event", ")", ":", "if", "self", ".", "config", ".", "allow_registration", "is", "False", ":", "self", ".", "log", "(", "'Someone tried to register although enrolment is closed.'", ")", "return", "self", ".", "log", "(", "'Cli...
39.596154
25.365385
def remove(name: str) -> bool: """ Remove corpus :param string name: corpus name :return: True or False """ db = TinyDB(corpus_db_path()) temp = Query() data = db.search(temp.name == name) if len(data) > 0: path = get_corpus_path(name) os.remove(path) db.rem...
[ "def", "remove", "(", "name", ":", "str", ")", "->", "bool", ":", "db", "=", "TinyDB", "(", "corpus_db_path", "(", ")", ")", "temp", "=", "Query", "(", ")", "data", "=", "db", ".", "search", "(", "temp", ".", "name", "==", "name", ")", "if", "l...
20.166667
16.166667
def graph_order(self): """ Get graph-order tuple for node. :: >>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode >>> root_container = UniqueTreeContainer(name="root") >>> outer_container = UniqueTreeContainer(name="outer") >>> i...
[ "def", "graph_order", "(", "self", ")", ":", "parentage", "=", "tuple", "(", "reversed", "(", "self", ".", "parentage", ")", ")", "graph_order", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "parentage", ")", "-", "1", ")", ":", "paren...
34.297297
19.486486
def find_source_lines(self): """Mark all executable source lines in fn as executed 0 times.""" strs = trace.find_strings(self.filename) lines = trace.find_lines_from_code(self.fn.__code__, strs) self.firstcodelineno = sys.maxint for lineno in lines: self.firstcodeline...
[ "def", "find_source_lines", "(", "self", ")", ":", "strs", "=", "trace", ".", "find_strings", "(", "self", ".", "filename", ")", "lines", "=", "trace", ".", "find_lines_from_code", "(", "self", ".", "fn", ".", "__code__", ",", "strs", ")", "self", ".", ...
49.9
11.4
def get_git_info(): """Get a dict with useful git info.""" start_dir = abspath(curdir) try: chdir(dirname(abspath(__file__))) re_patt_str = (r'commit\s+(?P<commit_hash>\w+).*?Author:\s+' r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+' ...
[ "def", "get_git_info", "(", ")", ":", "start_dir", "=", "abspath", "(", "curdir", ")", "try", ":", "chdir", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ")", "re_patt_str", "=", "(", "r'commit\\s+(?P<commit_hash>\\w+).*?Author:\\s+'", "r'(?P<author...
44.65
19.25
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, ...
[ "def", "refresh_actions", "(", "self", ")", ":", "self", ".", "options_menu", ".", "clear", "(", ")", "# Decide what additional actions to show", "if", "self", ".", "undocked_window", "is", "None", ":", "additional_actions", "=", "[", "MENU_SEPARATOR", ",", "self"...
35.277778
15.277778
def reverse_lookup(self, state, path): """ Returns a chrome URL for a given path, given the current package depth in an error bundle. State may either be an error bundle or the actual package stack. """ # Make sure the path starts with a forward slash. if not pa...
[ "def", "reverse_lookup", "(", "self", ",", "state", ",", "path", ")", ":", "# Make sure the path starts with a forward slash.", "if", "not", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "'/%s'", "%", "path", "# If the state is an error bundle, extra...
35.232143
21.232143
def fill_fields(self, **kwargs): """Fills the fields referenced by kwargs keys and fill them with the value""" for name, value in kwargs.items(): field = getattr(self, name) field.send_keys(value)
[ "def", "fill_fields", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "field", "=", "getattr", "(", "self", ",", "name", ")", "field", ".", "send_keys", "(", "value", ")" ]
39.833333
2.833333
def new_job( self, task, person, tank, target_host, target_port, loadscheme=None, detailed_time=None, notify_list=None, trace=False): """ :return: job_nr, upload_token :rtype: ...
[ "def", "new_job", "(", "self", ",", "task", ",", "person", ",", "tank", ",", "target_host", ",", "target_port", ",", "loadscheme", "=", "None", ",", "detailed_time", "=", "None", ",", "notify_list", "=", "None", ",", "trace", "=", "False", ")", ":", "i...
35.431373
16.019608
def TCA_select(bus, addr, channel): """ This function will write to the control register of the TCA module to select the channel that will be exposed on the TCA module. After doing this, the desired module can be used as it would be normally. (Th...
[ "def", "TCA_select", "(", "bus", ",", "addr", ",", "channel", ")", ":", "if", "addr", "<", "0x70", "or", "addr", ">", "0x77", ":", "print", "(", "\"The TCA address(\"", "+", "str", "(", "addr", ")", "+", "\") is invalid. Aborting\"", ")", "return", "Fals...
43.057143
19.971429
def plus(self, a): """ Add. """ return Vector(self.x+a.x, self.y+a.y, self.z+a.z)
[ "def", "plus", "(", "self", ",", "a", ")", ":", "return", "Vector", "(", "self", ".", "x", "+", "a", ".", "x", ",", "self", ".", "y", "+", "a", ".", "y", ",", "self", ".", "z", "+", "a", ".", "z", ")" ]
31.666667
13
def prepare(self, cache): """Prepare to run next shot.""" if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
[ "def", "prepare", "(", "self", ",", "cache", ")", ":", "if", "cache", "is", "not", "None", ":", "np", ".", "copyto", "(", "self", ".", "qubits", ",", "cache", ")", "else", ":", "self", ".", "qubits", ".", "fill", "(", "0.0", ")", "self", ".", "...
31.5
8.625
def create_file_from_text(self, share_name, directory_name, file_name, text, encoding='utf-8', content_settings=None, metadata=None, timeout=None): ''' Creates a new file from str/unicode, or updates the content of an existing file, with aut...
[ "def", "create_file_from_text", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "text", ",", "encoding", "=", "'utf-8'", ",", "content_settings", "=", "None", ",", "metadata", "=", "None", ",", "timeout", "=", "None", ")", ":", ...
43.657895
18.394737
def untar_file(filename, location): """ Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmo...
[ "def", "untar_file", "(", "filename", ",", "location", ")", ":", "ensure_dir", "(", "location", ")", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "'.gz'", ")", "or", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "'.tgz'",...
40.205479
16.726027
def make_nxml_from_text(text): """Return raw text wrapped in NXML structure. Parameters ---------- text : str The raw text content to be wrapped in an NXML structure. Returns ------- nxml_str : str The NXML string wrapping the raw text input. """ text = _escape_xml(...
[ "def", "make_nxml_from_text", "(", "text", ")", ":", "text", "=", "_escape_xml", "(", "text", ")", "header", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\" ?>'", "+", "'<OAI-PMH><article><body><sec id=\"s1\"><p>'", "footer", "=", "'</p></sec></body></article></OAI-PMH>'", "n...
27.789474
18.947368
def f(s): """ Basic support for 3.6's f-strings, in 3.5! Formats "s" using appropriate globals and locals dictionaries. This f-string: f"hello a is {a}" simply becomes f("hello a is {a}") In other words, just throw parentheses around the string, and you're done! Implem...
[ "def", "f", "(", "s", ")", ":", "frame", "=", "sys", ".", "_getframe", "(", "1", ")", "d", "=", "dict", "(", "builtins", ".", "__dict__", ")", "d", ".", "update", "(", "frame", ".", "f_globals", ")", "d", ".", "update", "(", "frame", ".", "f_lo...
29.583333
12.416667
def empty(self, name, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.empty`.""" return self._write_op(self._empty_nosync, name, **kwargs)
[ "def", "empty", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_empty_nosync", ",", "name", ",", "*", "*", "kwargs", ")" ]
47
8.25
def export(self, file_path=None, export_format=None): """ Write the users to a file. """ with io.open(file_path, mode='w', encoding="utf-8") as export_file: if export_format == 'yaml': import yaml yaml.safe_dump(self.to_dict(), export_file, default_flow_style=...
[ "def", "export", "(", "self", ",", "file_path", "=", "None", ",", "export_format", "=", "None", ")", ":", "with", "io", ".", "open", "(", "file_path", ",", "mode", "=", "'w'", ",", "encoding", "=", "\"utf-8\"", ")", "as", "export_file", ":", "if", "e...
53
19.666667
def samples_by_indices(self, indices): """ Gather a batch of samples by indices, applying the mapping described by the (optional) `indices` array passed to the constructor. Parameters ---------- indices: 1D-array of ints or slice The samples to retrie...
[ "def", "samples_by_indices", "(", "self", ",", "indices", ")", ":", "indices", "=", "self", ".", "sampler", ".", "map_indices", "(", "indices", ")", "return", "self", ".", "samples_by_indices_nomapping", "(", "indices", ")" ]
30.333333
17.888889
def get_adjacency_matrix(self, show_in_console=False): """ return the matrix as a list of lists raw graph = {'1': ['2', '3', '4'], '2': ['6', '7']} 6 nodes: ['1', '2', '3', '4', '6', '7'] 5 links: [['1', '2'], ['1', '3'], ['1', '4'], ['2', '6'], ['2', '7']] [0, 1, 1, 1, 0, 0] ...
[ "def", "get_adjacency_matrix", "(", "self", ",", "show_in_console", "=", "False", ")", ":", "self", ".", "links", "=", "[", "[", "i", ",", "j", "]", "for", "i", "in", "self", ".", "graph", "for", "j", "in", "self", ".", "graph", "[", "i", "]", "]...
36
14.304348
def DeleteJob(self, job_id, token=None): """Deletes cron job with the given URN.""" job_urn = self.CRON_JOBS_PATH.Add(job_id) aff4.FACTORY.Delete(job_urn, token=token)
[ "def", "DeleteJob", "(", "self", ",", "job_id", ",", "token", "=", "None", ")", ":", "job_urn", "=", "self", ".", "CRON_JOBS_PATH", ".", "Add", "(", "job_id", ")", "aff4", ".", "FACTORY", ".", "Delete", "(", "job_urn", ",", "token", "=", "token", ")"...
44
2.5
def _ensure_opened(self): """Start monitors, or restart after a fork. Hold the lock when calling this. """ if not self._opened: self._opened = True self._update_servers() # Start or restart the events publishing thread. if self._publish_t...
[ "def", "_ensure_opened", "(", "self", ")", ":", "if", "not", "self", ".", "_opened", ":", "self", ".", "_opened", "=", "True", "self", ".", "_update_servers", "(", ")", "# Start or restart the events publishing thread.", "if", "self", ".", "_publish_tp", "or", ...
31.125
14.375
def GetRunlevelsLSB(states): """Accepts a string and returns a list of strings of numeric LSB runlevels.""" if not states: return set() valid = set(["0", "1", "2", "3", "4", "5", "6"]) _LogInvalidRunLevels(states, valid) return valid.intersection(set(states.split()))
[ "def", "GetRunlevelsLSB", "(", "states", ")", ":", "if", "not", "states", ":", "return", "set", "(", ")", "valid", "=", "set", "(", "[", "\"0\"", ",", "\"1\"", ",", "\"2\"", ",", "\"3\"", ",", "\"4\"", ",", "\"5\"", ",", "\"6\"", "]", ")", "_LogInv...
39.285714
11.571429
def create(self, *args, **kwargs): """Adds created http status response and location link.""" resource = super(JsonServerResource, self).create(*args, **kwargs) return ResourceResult( body=resource, status=get_http_status_code_value(http.client.CREATED), loca...
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resource", "=", "super", "(", "JsonServerResource", ",", "self", ")", ".", "create", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ResourceResult", "(", ...
41.444444
21
def write(self, s): """ Write wrapper. Parameters ---------- s : bytes Bytes to write """ try: return self.handle.write(s) except OSError: print() print("Piksi disconnected") print() ra...
[ "def", "write", "(", "self", ",", "s", ")", ":", "try", ":", "return", "self", ".", "handle", ".", "write", "(", "s", ")", "except", "OSError", ":", "print", "(", ")", "print", "(", "\"Piksi disconnected\"", ")", "print", "(", ")", "raise", "IOError"...
19.75
16.625
def console(self): """ Call the function as a console script. Command line arguments are parsed, preprocessors are called, then the function is called. If a 'debug' attribute is set by the command line arguments, and it is True, any exception raised by the underlying fu...
[ "def", "console", "(", "self", ")", ":", "# First, let's parse the arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "self", ".", "description", ")", "self", ".", "setup_args", "(", "parser", ")", "args", "=", "parser", "."...
35.909091
17.606061
def generate_data_for_edit_page(self): """ Generate a custom representation of table's fields in dictionary type if exist edit form else use default representation. :return: dict """ if not self.can_edit: return {} if self.edit_form: ret...
[ "def", "generate_data_for_edit_page", "(", "self", ")", ":", "if", "not", "self", ".", "can_edit", ":", "return", "{", "}", "if", "self", ".", "edit_form", ":", "return", "self", ".", "edit_form", ".", "to_dict", "(", ")", "return", "self", ".", "generat...
25.533333
19.4
def request(self, method, endpoint, body=None, timeout=-1): """ Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __error_middleware. """ if method not in set(['GET', 'POST', 'PUT', 'DELETE']): raise Exception('Invalid/Forb...
[ "def", "request", "(", "self", ",", "method", ",", "endpoint", ",", "body", "=", "None", ",", "timeout", "=", "-", "1", ")", ":", "if", "method", "not", "in", "set", "(", "[", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'DELETE'", "]", ")", ":", ...
30.588235
19.235294
def commit( self, message: str, files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None, allow_empty: bool = False, ): """ Commits changes to the repo :param message: first line of the message :type message: str ...
[ "def", "commit", "(", "self", ",", "message", ":", "str", ",", "files_to_add", ":", "typing", ".", "Optional", "[", "typing", ".", "Union", "[", "typing", ".", "List", "[", "str", "]", ",", "str", "]", "]", "=", "None", ",", "allow_empty", ":", "bo...
30.219512
17.682927
def startswith(self, event_property, value): """A starts-with filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.startswith('path', '/cube') >>> print(filtered) request(elapsed_ms).re(path, "^/cube") """ c = self...
[ "def", "startswith", "(", "self", ",", "event_property", ",", "value", ")", ":", "c", "=", "self", ".", "copy", "(", ")", "c", ".", "filters", ".", "append", "(", "filters", ".", "RE", "(", "event_property", ",", "\"^{value}\"", ".", "format", "(", "...
35.916667
16.5
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
[ "def", "hincrby", "(", "self", ",", "hashkey", ",", "attribute", ",", "increment", "=", "1", ")", ":", "return", "self", ".", "_hincrby", "(", "hashkey", ",", "attribute", ",", "'HINCRBY'", ",", "long", ",", "increment", ")" ]
39.25
21.75
def create_model(self, model_server_workers=None, role=None, vpc_config_override=VPC_CONFIG_DEFAULT, endpoint_type=None): """Create a SageMaker ``TensorFlowModel`` object that can be deployed to an ``Endpoint``. Args: role (str): The ``ExecutionRoleArn`` IAM Role ARN fo...
[ "def", "create_model", "(", "self", ",", "model_server_workers", "=", "None", ",", "role", "=", "None", ",", "vpc_config_override", "=", "VPC_CONFIG_DEFAULT", ",", "endpoint_type", "=", "None", ")", ":", "role", "=", "role", "or", "self", ".", "role", "if", ...
64.310345
38.448276
def formatter_factory(show_defaults=True): """Formatter factory""" def get_help_string(self, action): lhelp = action.help if isinstance(show_defaults, (list, tuple)): if "-" + action.dest in show_defaults: return lhelp if '%(default)' not in action.help: ...
[ "def", "formatter_factory", "(", "show_defaults", "=", "True", ")", ":", "def", "get_help_string", "(", "self", ",", "action", ")", ":", "lhelp", "=", "action", ".", "help", "if", "isinstance", "(", "show_defaults", ",", "(", "list", ",", "tuple", ")", "...
41.047619
16.809524
def get_independencies(self, condition=None): """ Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition=None. Returns conditionally independent variables if condition!=None Parameter --------- ...
[ "def", "get_independencies", "(", "self", ",", "condition", "=", "None", ")", ":", "JPD", "=", "self", ".", "copy", "(", ")", "if", "condition", ":", "JPD", ".", "conditional_distribution", "(", "condition", ")", "independencies", "=", "Independencies", "(",...
41.870968
23.483871
def DeleteGroup(r, group, dry_run=False): """ Deletes a node group. @type group: str @param group: the node group to delete @type dry_run: bool @param dry_run: whether to peform a dry run @rtype: int @return: job id """ query = { "dry-run": dry_run, } return r...
[ "def", "DeleteGroup", "(", "r", ",", "group", ",", "dry_run", "=", "False", ")", ":", "query", "=", "{", "\"dry-run\"", ":", "dry_run", ",", "}", "return", "r", ".", "request", "(", "\"delete\"", ",", "\"/2/groups/%s\"", "%", "group", ",", "query", "="...
19.888889
20.555556
def extract_random_video_patch(videos, num_frames=-1): """For every video, extract a random consecutive patch of num_frames. Args: videos: 5-D Tensor, (NTHWC) num_frames: Integer, if -1 then the entire video is returned. Returns: video_patch: 5-D Tensor, (NTHWC) with T = num_frames. Raises: Val...
[ "def", "extract_random_video_patch", "(", "videos", ",", "num_frames", "=", "-", "1", ")", ":", "if", "num_frames", "==", "-", "1", ":", "return", "videos", "batch_size", ",", "num_total_frames", ",", "h", ",", "w", ",", "c", "=", "common_layers", ".", "...
40.578947
21.105263
def parents(self): """ Returns list of parents changesets. """ return [self.repository.get_changeset(parent.rev()) for parent in self._ctx.parents() if parent.rev() >= 0]
[ "def", "parents", "(", "self", ")", ":", "return", "[", "self", ".", "repository", ".", "get_changeset", "(", "parent", ".", "rev", "(", ")", ")", "for", "parent", "in", "self", ".", "_ctx", ".", "parents", "(", ")", "if", "parent", ".", "rev", "("...
35.5
12.5
def _create_mapping(grammar): # type: (Grammar) -> (Dict[int, Set[Type[Rule]]], Dict[int, Set[Type[Rule]]]) """ Create mapping between symbols and rules rewritable to these symbols. :param grammar: Grammar to use. :return: Tuple of two dictionaries. First dictionary maps rule to terminal hash. ...
[ "def", "_create_mapping", "(", "grammar", ")", ":", "# type: (Grammar) -> (Dict[int, Set[Type[Rule]]], Dict[int, Set[Type[Rule]]])", "termmap", "=", "dict", "(", ")", "rulemap", "=", "dict", "(", ")", "for", "r", "in", "grammar", ".", "rules", ":", "if", "len", "(...
33.6
11.36
def check_versions(self, conn): """ :param conn: a DB API 2 connection :returns: a message with the versions that will be applied or None """ scripts = self.read_scripts(skip_versions=self.get_db_versions(conn)) versions = [s['version'] for s in scripts] if versio...
[ "def", "check_versions", "(", "self", ",", "conn", ")", ":", "scripts", "=", "self", ".", "read_scripts", "(", "skip_versions", "=", "self", ".", "get_db_versions", "(", "conn", ")", ")", "versions", "=", "[", "s", "[", "'version'", "]", "for", "s", "i...
47.727273
18.272727
def add_intf_router(self, rout_id, tenant_id, subnet_lst): """Add the interfaces to a router. """ try: for subnet_id in subnet_lst: body = {'subnet_id': subnet_id} intf = self.neutronclient.add_interface_router(rout_id, ...
[ "def", "add_intf_router", "(", "self", ",", "rout_id", ",", "tenant_id", ",", "subnet_lst", ")", ":", "try", ":", "for", "subnet_id", "in", "subnet_lst", ":", "body", "=", "{", "'subnet_id'", ":", "subnet_id", "}", "intf", "=", "self", ".", "neutronclient"...
45.461538
17
async def create_and_store_my_did(wallet_handle: int, did_json: str) -> (str, str): """ Creates keys (signing and encryption keys) for a new DID (owned by the caller of the library). Identity's DID must be either explicitly provided, or taken as the first 16 bit of verk...
[ "async", "def", "create_and_store_my_did", "(", "wallet_handle", ":", "int", ",", "did_json", ":", "str", ")", "->", "(", "str", ",", "str", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"creat...
47.574468
26.297872
def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ _logger.info('Creating a new channel') self._connection.channel(...
[ "def", "open_channel", "(", "self", ")", ":", "_logger", ".", "info", "(", "'Creating a new channel'", ")", "self", ".", "_connection", ".", "channel", "(", "on_open_callback", "=", "self", ".", "on_channel_open", ")" ]
50.285714
14.285714
def parse_children(parent): """Recursively parse child tags until match is found""" components = [] for tag in parent.children: matched = parse_tag(tag) if matched: components.append(matched) elif hasattr(tag, 'contents'): components += parse_children(tag) ...
[ "def", "parse_children", "(", "parent", ")", ":", "components", "=", "[", "]", "for", "tag", "in", "parent", ".", "children", ":", "matched", "=", "parse_tag", "(", "tag", ")", "if", "matched", ":", "components", ".", "append", "(", "matched", ")", "el...
29.909091
12.727273
def _restoreResults(newdir,origdir): """ Move (not copy) all files from newdir back to the original directory """ for fname in glob.glob(os.path.join(newdir,'*')): shutil.move(fname,os.path.join(origdir,os.path.basename(fname)))
[ "def", "_restoreResults", "(", "newdir", ",", "origdir", ")", ":", "for", "fname", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "newdir", ",", "'*'", ")", ")", ":", "shutil", ".", "move", "(", "fname", ",", "os", ".", "pat...
48.8
9.8
def set_USRdict(self,USRdict={}): """ Set the USRdict, containing user-defined info about the instance Useful for arbitrary info (e.g.: manufacturing date, material...) Parameters ---------- USRdict : dict A user-defined dictionary containing info about the instan...
[ "def", "set_USRdict", "(", "self", ",", "USRdict", "=", "{", "}", ")", ":", "self", ".", "_check_inputs", "(", "USRdict", "=", "USRdict", ")", "self", ".", "_USRdict", "=", "USRdict" ]
30.692308
20.307692
def _disconnect(self): """Disconnect from the transport.""" if not self.protocol or not self.protocol.transport: self.protocol = None # Make sure protocol is None return _LOGGER.info('Disconnecting from gateway') self.protocol.transport.close() self.proto...
[ "def", "_disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "protocol", "or", "not", "self", ".", "protocol", ".", "transport", ":", "self", ".", "protocol", "=", "None", "# Make sure protocol is None", "return", "_LOGGER", ".", "info", "(", "'D...
40.375
13.125
def policy_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy net function.""" # Use the bottom_layers as the bottom part of the network and just add the # required layers on top of it. if bottom_layers is None: bottom_layers = [...
[ "def", "policy_net", "(", "rng_key", ",", "batch_observations_shape", ",", "num_actions", ",", "bottom_layers", "=", "None", ")", ":", "# Use the bottom_layers as the bottom part of the network and just add the", "# required layers on top of it.", "if", "bottom_layers", "is", "...
35.533333
17
def update_dimensions(self, dims): """ Update multiple dimension on the cube. .. code-block:: python cube.update_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_siz...
[ "def", "update_dimensions", "(", "self", ",", "dims", ")", ":", "if", "isinstance", "(", "dims", ",", "collections", ".", "Mapping", ")", ":", "dims", "=", "dims", ".", "itervalues", "(", ")", "for", "dim", "in", "dims", ":", "# Defer to update dimension f...
32.25
15.8125
def remove_note(self, username, index): """Remove a single usernote from the usernotes. Arguments: username: the user that for whom you're removing a note (str) index: the index of the note which is to be removed (int) Returns the update message for the usernotes wiki ...
[ "def", "remove_note", "(", "self", ",", "username", ",", "index", ")", ":", "self", ".", "cached_json", "[", "'users'", "]", "[", "username", "]", "[", "'ns'", "]", ".", "pop", "(", "index", ")", "# Go ahead and remove the user's entry if they have no more notes...
40.75
24.5
def py2js_tickformatter(formatter, msg=''): """ Uses flexx.pyscript to compile a python tick formatter to JS code """ try: from flexx.pyscript import py2js except ImportError: param.main.param.warning( msg+'Ensure Flexx is installed ("conda install -c bokeh flexx" ' ...
[ "def", "py2js_tickformatter", "(", "formatter", ",", "msg", "=", "''", ")", ":", "try", ":", "from", "flexx", ".", "pyscript", "import", "py2js", "except", "ImportError", ":", "param", ".", "main", ".", "param", ".", "warning", "(", "msg", "+", "'Ensure ...
37.24
15.8
def draw(self): """Draw all the sprites in the system using their renderers. This method is convenient to call from you Pyglet window's on_draw handler to redraw particles when needed. """ glPushAttrib(GL_ALL_ATTRIB_BITS) self.draw_score() for sprite in s...
[ "def", "draw", "(", "self", ")", ":", "glPushAttrib", "(", "GL_ALL_ATTRIB_BITS", ")", "self", ".", "draw_score", "(", ")", "for", "sprite", "in", "self", ":", "sprite", ".", "draw", "(", ")", "glPopAttrib", "(", ")" ]
33.090909
15.181818
def get_url(self, obj, view_name, request, format): """ Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ # Unsaved objects ...
[ "def", "get_url", "(", "self", ",", "obj", ",", "view_name", ",", "request", ",", "format", ")", ":", "# Unsaved objects will not yet have a valid URL.", "if", "hasattr", "(", "obj", ",", "'pk'", ")", "and", "obj", ".", "pk", "is", "None", ":", "return", "...
43.428571
21.428571
def rectwidth(self, wavelengths=None): """Calculate :ref:`bandpass rectangular width <synphot-formula-rectw>`. Parameters ---------- wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None` Wavelength values for sampling. If not a Quantity, assumed...
[ "def", "rectwidth", "(", "self", ",", "wavelengths", "=", "None", ")", ":", "equvw", "=", "self", ".", "equivwidth", "(", "wavelengths", "=", "wavelengths", ")", "tpeak", "=", "self", ".", "tpeak", "(", "wavelengths", "=", "wavelengths", ")", "if", "tpea...
31.24
18.92
def whoami(self) -> dict: """Returns the basic information about the authenticated character. Obviously doesn't do anything if this Preston instance is not authenticated, so it returns an empty dict. Args: None Returns: character info if authenticated, ...
[ "def", "whoami", "(", "self", ")", "->", "dict", ":", "if", "not", "self", ".", "access_token", ":", "return", "{", "}", "self", ".", "_try_refresh_access_token", "(", ")", "return", "self", ".", "session", ".", "get", "(", "self", ".", "WHOAMI_URL", "...
30.8125
19.9375
def get_xray_daemon(): """Parse X-Ray Daemon address environment variable. If the environment variable is not set, raise an exception to signal that we're unable to send data to X-Ray. """ env_value = os.environ.get('AWS_XRAY_DAEMON_ADDRESS') if env_value is None: raise XRayDaemonNotFou...
[ "def", "get_xray_daemon", "(", ")", ":", "env_value", "=", "os", ".", "environ", ".", "get", "(", "'AWS_XRAY_DAEMON_ADDRESS'", ")", "if", "env_value", "is", "None", ":", "raise", "XRayDaemonNotFoundError", "(", ")", "xray_ip", ",", "xray_port", "=", "env_value...
35.666667
16.333333
def _from_dict(cls, _dict): """Initialize a TopHitsResults object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'hits' in _dict: args['hits'] = [ QueryResult._from_d...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'matching_results'", "in", "_dict", ":", "args", "[", "'matching_results'", "]", "=", "_dict", ".", "get", "(", "'matching_results'", ")", "if", "'hits'", "in", "_dict...
38.7
16.1
def all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. O...
[ "def", "all_matches", "(", "self", ",", "target", ",", "choices", ",", "group", "=", "False", ",", "include_rank", "=", "False", ")", ":", "dist", "=", "self", ".", "get_distance", "# Keep everything here as an iterator in case we're given a lot of", "# choices", "m...
30.119048
23.761905
def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) a = torch.inverse(m[:2,:2].t()) c.flow = torch.mm(c.flow - m[:2,2], a).view(size) return c
[ "def", "_affine_inv_mult", "(", "c", ",", "m", ")", ":", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "size", "m", "[", "0", ",", "1", "]", "*=", "h", "/", "w", "m", "[", "1", ",", "0", "]", "*=", ...
29.8
18.2
def Hvap(self): r'''Enthalpy of vaporization of the chemical at its current temperature, in units of [J/kg]. This property uses the object-oriented interface :obj:`thermo.phase_change.EnthalpyVaporization`, but converts its results from molar to mass units. Examples ...
[ "def", "Hvap", "(", "self", ")", ":", "Hvamp", "=", "self", ".", "Hvapm", "if", "Hvamp", ":", "return", "property_molar_to_mass", "(", "Hvamp", ",", "self", ".", "MW", ")", "return", "None" ]
30.588235
22.117647
def header_output(self): '''只输出cookie的key-value字串. 比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 ''' result = [] for key in self.keys(): result.append(key + '=' + self.get(key).value) return '; '.join(result)
[ "def", "header_output", "(", "self", ")", ":", "result", "=", "[", "]", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "result", ".", "append", "(", "key", "+", "'='", "+", "self", ".", "get", "(", "key", ")", ".", "value", ")", "retur...
31.777778
18.888889
def check_partial(func, *args, **kwargs): """Create a partial to be used by goodtables.""" new_func = partial(func, *args, **kwargs) new_func.check = func.check return new_func
[ "def", "check_partial", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_func", "=", "partial", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "new_func", ".", "check", "=", "func", ".", "check", "return", "new_f...
37.6
7.2
def add_member(self, user): """ Add member to team :param user: User object or user's username :return: Added user. """ user = Transform.to_user(user) data = { 'id': user } extra = { 'resource': self.__class__.__name__, ...
[ "def", "add_member", "(", "self", ",", "user", ")", ":", "user", "=", "Transform", ".", "to_user", "(", "user", ")", "data", "=", "{", "'id'", ":", "user", "}", "extra", "=", "{", "'resource'", ":", "self", ".", "__class__", ".", "__name__", ",", "...
30.409091
15.136364
def get_field_errors(self, bound_field): """ Determine the kind of input field and create a list of potential errors which may occur during validation of that field. This list is returned to be displayed in '$dirty' state if the field does not validate for that criteria. """ ...
[ "def", "get_field_errors", "(", "self", ",", "bound_field", ")", ":", "errors", "=", "super", "(", "NgFormValidationMixin", ",", "self", ")", ".", "get_field_errors", "(", "bound_field", ")", "if", "bound_field", ".", "is_hidden", ":", "return", "errors", "ide...
65.9
33.4
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.wr...
[ "def", "store_env", "(", "path", "=", "None", ")", ":", "path", "=", "path", "or", "get_store_env_tmp", "(", ")", "env_dict", "=", "yaml", ".", "safe_dump", "(", "os", ".", "environ", ".", "data", ",", "default_flow_style", "=", "False", ")", "with", "...
26
26
def group_dict(self, group: str) -> Dict[str, Any]: """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') de...
[ "def", "group_dict", "(", "self", ",", "group", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "dict", "(", "(", "opt", ".", "name", ",", "opt", ".", "value", "(", ")", ")", "for", "name", ",", "opt", "in", "self", ...
31.318182
20.818182
def run(self, *args): """Move an identity into a unique identity.""" params = self.parser.parse_args(args) from_id = params.from_id to_uuid = params.to_uuid code = self.move(from_id, to_uuid) return code
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "params", "=", "self", ".", "parser", ".", "parse_args", "(", "args", ")", "from_id", "=", "params", ".", "from_id", "to_uuid", "=", "params", ".", "to_uuid", "code", "=", "self", ".", "move", ...
22.272727
20.272727
def find(self, path=None, name=None): """ Returns most recent version of the matching file. If there are multiple files of the same name and version, a random one is used. """ if path is None and name is None: # TODO: Correct error type raise ValueError("...
[ "def", "find", "(", "self", ",", "path", "=", "None", ",", "name", "=", "None", ")", ":", "if", "path", "is", "None", "and", "name", "is", "None", ":", "# TODO: Correct error type", "raise", "ValueError", "(", "\"Path or name is required.\"", ")", "# Entries...
41.066667
17.733333
def user_orgs(self, login): """Get the user public organizations""" if login in self._users_orgs: return self._users_orgs[login] url = urijoin(self.base_url, 'users', login, 'orgs') try: r = self.fetch(url) orgs = r.text except requests.except...
[ "def", "user_orgs", "(", "self", ",", "login", ")", ":", "if", "login", "in", "self", ".", "_users_orgs", ":", "return", "self", ".", "_users_orgs", "[", "login", "]", "url", "=", "urijoin", "(", "self", ".", "base_url", ",", "'users'", ",", "login", ...
31.95
17.6
def continue_worker(oid, restart_point="continue_next", **kwargs): """Restart workflow with given id (uuid) at given point. By providing the ``restart_point`` you can change the point of which the workflow will continue from. * restart_prev: will restart from the previous task * continue_next: wil...
[ "def", "continue_worker", "(", "oid", ",", "restart_point", "=", "\"continue_next\"", ",", "*", "*", "kwargs", ")", ":", "if", "'stop_on_halt'", "not", "in", "kwargs", ":", "kwargs", "[", "'stop_on_halt'", "]", "=", "False", "workflow_object", "=", "workflow_o...
29.472222
20.888889
def install(self, release_id): """Download and install an artifact into the remote release directory, optionally with a different name the the artifact had. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be created a...
[ "def", "install", "(", "self", ",", "release_id", ")", ":", "release_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_releases", ",", "release_id", ")", "if", "not", "self", ".", "_runner", ".", "exists", "(", "release_path", ")", ":", ...
51.5
25.368421
def pdf_copy(input: str, output: str, pages: [int], yes_to_all=False): """ Copy pages from the input file in a new output file. :param input: name of the input pdf file :param output: name of the output pdf file :param pages: list containing the page numbers to copy in the new file """ if n...
[ "def", "pdf_copy", "(", "input", ":", "str", ",", "output", ":", "str", ",", "pages", ":", "[", "int", "]", ",", "yes_to_all", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "input", ")", ":", "print", "(", "\"Error. ...
34.642857
15.571429
def _create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, ranking=True, verbose=True): """ A unified interface for training recommender models. Based on simple characteristics of the data, a type of model is s...
[ "def", "_create", "(", "observation_data", ",", "user_id", "=", "'user_id'", ",", "item_id", "=", "'item_id'", ",", "target", "=", "None", ",", "user_data", "=", "None", ",", "item_data", "=", "None", ",", "ranking", "=", "True", ",", "verbose", "=", "Tr...
40.184211
25.723684
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when action is not found """ start_response( "404 Not Found", [('Content-type', 'text/plain')]) ...
[ "def", "on_view_not_found", "(", "self", ",", "environ", ":", "Dict", "[", "str", ",", "Any", "]", ",", "start_response", ":", "Callable", "[", "[", "str", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", ",", "None", "]", ",", "...
41.888889
14.888889
def stop(self, actor, exc=None, exit_code=None): """Gracefully stop the ``actor``. """ if actor.state <= ACTOR_STATES.RUN: # The actor has not started the stopping process. Starts it now. actor.state = ACTOR_STATES.STOPPING actor.event('start').clear() ...
[ "def", "stop", "(", "self", ",", "actor", ",", "exc", "=", "None", ",", "exit_code", "=", "None", ")", ":", "if", "actor", ".", "state", "<=", "ACTOR_STATES", ".", "RUN", ":", "# The actor has not started the stopping process. Starts it now.", "actor", ".", "s...
41.3
14.55
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
[ "def", "_set", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "setbit", "(", "pos", ")" ]
30.75
7.75
def convert_seconds(self, time_seconds): """Convert a time in seconds to the device timestamp units. KATCP v4 and earlier, specified all timestamps in milliseconds. Since KATCP v5, all timestamps are in seconds. If the device KATCP version has been detected, this method converts a value...
[ "def", "convert_seconds", "(", "self", ",", "time_seconds", ")", ":", "if", "self", ".", "protocol_flags", ".", "major", ">=", "SEC_TS_KATCP_MAJOR", ":", "return", "time_seconds", "else", ":", "device_time", "=", "time_seconds", "*", "SEC_TO_MS_FAC", "if", "self...
46.647059
21.588235
def read_raster(raster_file): """Read raster by GDAL. Args: raster_file: raster file path. Returns: Raster object. """ ds = gdal_Open(raster_file) band = ds.GetRasterBand(1) data = band.ReadAsArray() xsize = band.XSize ysi...
[ "def", "read_raster", "(", "raster_file", ")", ":", "ds", "=", "gdal_Open", "(", "raster_file", ")", "band", "=", "ds", ".", "GetRasterBand", "(", "1", ")", "data", "=", "band", ".", "ReadAsArray", "(", ")", "xsize", "=", "band", ".", "XSize", "ysize",...
27.37037
14.925926
def json_load_object_hook(dct): """ Hook for json.parse(...) to parse Xero date formats. """ for key, value in dct.items(): if isinstance(value, six.string_types): value = parse_date(value) if value: dct[key] = value return dct
[ "def", "json_load_object_hook", "(", "dct", ")", ":", "for", "key", ",", "value", "in", "dct", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "parse_date", "(", "value", ")", "i...
28.3
11.8
def everything(self, include_deleted=False, content_id=None, subtopic_id=None, prefix=None): '''Returns a generator of all labels in the store. If `include_deleted` is :const:`True`, labels that have been overwritten with more recent labels are also included. If `con...
[ "def", "everything", "(", "self", ",", "include_deleted", "=", "False", ",", "content_id", "=", "None", ",", "subtopic_id", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "content_id", "is", "not", "None", ":", "ranges", "=", "[", "(", "(", ...
46.030303
21.484848
def pid(self): """The pid of this process. :raises: Will raise a ``Process.UnboundProcess`` exception if the process is not bound to a context. """ self._assert_bound() return PID(self._context.ip, self._context.port, self.name)
[ "def", "pid", "(", "self", ")", ":", "self", ".", "_assert_bound", "(", ")", "return", "PID", "(", "self", ".", "_context", ".", "ip", ",", "self", ".", "_context", ".", "port", ",", "self", ".", "name", ")" ]
31.875
17.625
def addPolicyURI(self, policy_uri): """Add a authentication policy to this response This method is intended to be used by the provider to add a policy that the provider conformed to when authenticating the user. @param policy_uri: The identifier for the preferred type of au...
[ "def", "addPolicyURI", "(", "self", ",", "policy_uri", ")", ":", "if", "policy_uri", "not", "in", "self", ".", "auth_policies", ":", "self", ".", "auth_policies", ".", "append", "(", "policy_uri", ")" ]
45.416667
22.916667
def prepare_query(self, symbol, start_date, end_date): """Method returns prepared request query for Yahoo YQL API.""" query = \ 'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \ % (symbol, start_date, end_date) re...
[ "def", "prepare_query", "(", "self", ",", "symbol", ",", "start_date", ",", "end_date", ")", ":", "query", "=", "'select * from yahoo.finance.historicaldata where symbol = \"%s\" and startDate = \"%s\" and endDate = \"%s\"'", "%", "(", "symbol", ",", "start_date", ",", "end...
46.285714
25.714286
def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params)
[ "def", "list_lbaas_loadbalancers", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'loadbalancers'", ",", "self", ".", "lbaas_loadbalancers_path", ",", "retrieve_all", ",", "*", "*", "_p...
64
16.5
def p_return_statement_2(self, p): """return_statement : RETURN expr SEMI | RETURN expr AUTOSEMI """ p[0] = self.asttypes.Return(expr=p[2]) p[0].setpos(p)
[ "def", "p_return_statement_2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "asttypes", ".", "Return", "(", "expr", "=", "p", "[", "2", "]", ")", "p", "[", "0", "]", ".", "setpos", "(", "p", ")" ]
34.833333
6.666667
def load_subcommand(subparsers): """Load this subcommand""" parser_analyze = subparsers.add_parser('echo_conf', help='Echo sample configuration file') parser_analyze.set_defaults(func=echo_conf)
[ "def", "load_subcommand", "(", "subparsers", ")", ":", "parser_analyze", "=", "subparsers", ".", "add_parser", "(", "'echo_conf'", ",", "help", "=", "'Echo sample configuration file'", ")", "parser_analyze", ".", "set_defaults", "(", "func", "=", "echo_conf", ")" ]
50.75
17.25
def validate_dtype(termname, dtype, missing_value): """ Validate a `dtype` and `missing_value` passed to Term.__new__. Ensures that we know how to represent ``dtype``, and that missing_value is specified for types without default missing values. Returns ------- validated_dtype, validated_m...
[ "def", "validate_dtype", "(", "termname", ",", "dtype", ",", "missing_value", ")", ":", "if", "dtype", "is", "NotSpecified", ":", "raise", "DTypeNotSpecified", "(", "termname", "=", "termname", ")", "try", ":", "dtype", "=", "dtype_class", "(", "dtype", ")",...
35.171875
21.609375
def animate(self, filename='constellation.mp4', epochs=[1900,2100], dt=5, dpi=300, fps=10, **kw): ''' Animate a finder chart. ''' scatter = self.finder(**kw) plt.tight_layout() figure = plt.gcf() if '.gif' in filename: try: writer = a...
[ "def", "animate", "(", "self", ",", "filename", "=", "'constellation.mp4'", ",", "epochs", "=", "[", "1900", ",", "2100", "]", ",", "dt", "=", "5", ",", "dpi", "=", "300", ",", "fps", "=", "10", ",", "*", "*", "kw", ")", ":", "scatter", "=", "s...
36.59375
24.78125
def transform_audio(self, y): '''Apply the scale transform to the tempogram Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['temposcale'] : np.ndarray, shape=(n_frames, n_fmt) The sca...
[ "def", "transform_audio", "(", "self", ",", "y", ")", ":", "data", "=", "super", "(", "TempoScale", ",", "self", ")", ".", "transform_audio", "(", "y", ")", "data", "[", "'temposcale'", "]", "=", "np", ".", "abs", "(", "fmt", "(", "data", ".", "pop...
32.947368
23.052632
def extract_from_directory(path_in, path_out): """Run Eidos on a set of text files in a folder. The output is produced in the specified output folder but the output files aren't processed by this function. Parameters ---------- path_in : str Path to an input folder with some text files...
[ "def", "extract_from_directory", "(", "path_in", ",", "path_out", ")", ":", "path_in", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path_in", ")", ")", "path_out", "=", "os", ".", "path", ".", "realpath", "(...
36.888889
19.833333
def scale_T(T, P_I, I_F): """Scale T with a block diagonal matrix. Helper function that scales T with a right multiplication by a block diagonal inverse, so that T is the identity at C-node rows. Parameters ---------- T : {bsr_matrix} Tentative prolongator, with square blocks in the BS...
[ "def", "scale_T", "(", "T", ",", "P_I", ",", "I_F", ")", ":", "if", "not", "isspmatrix_bsr", "(", "T", ")", ":", "raise", "TypeError", "(", "'Expected BSR matrix T'", ")", "elif", "T", ".", "blocksize", "[", "0", "]", "!=", "T", ".", "blocksize", "["...
37.633663
18.831683
def insert(self, context): """ Build the project. :param resort.engine.execution.Context context: Current execution context. """ if self.__dependency: self.__execute(context, "install") else: self.__execute(context, "package")
[ "def", "insert", "(", "self", ",", "context", ")", ":", "if", "self", ".", "__dependency", ":", "self", ".", "__execute", "(", "context", ",", "\"install\"", ")", "else", ":", "self", ".", "__execute", "(", "context", ",", "\"package\"", ")" ]
18.846154
17.153846
def _get_fieldsets_post_form_or_formset(self, request, form, obj=None): """ Generic get_fieldsets code, shared by TranslationAdmin and TranslationInlineModelAdmin. """ base_fields = self.replace_orig_field(form.base_fields.keys()) fields = base_fields + list(self.get_read...
[ "def", "_get_fieldsets_post_form_or_formset", "(", "self", ",", "request", ",", "form", ",", "obj", "=", "None", ")", ":", "base_fields", "=", "self", ".", "replace_orig_field", "(", "form", ".", "base_fields", ".", "keys", "(", ")", ")", "fields", "=", "b...
51
18.25
def add_update_callback(self, callback, device): """Register as callback for when a matching device changes.""" self._update_callbacks.append([callback, device]) _LOGGER.debug('Added update callback to %s on %s', callback, device)
[ "def", "add_update_callback", "(", "self", ",", "callback", ",", "device", ")", ":", "self", ".", "_update_callbacks", ".", "append", "(", "[", "callback", ",", "device", "]", ")", "_LOGGER", ".", "debug", "(", "'Added update callback to %s on %s'", ",", "call...
62.75
15.25
def types_msg(instance, types): """ Create an error message for a failure to match the given types. If the ``instance`` is an object and contains a ``name`` property, it will be considered to be a description of that object and used as its type. Otherwise the message is simply the reprs of the giv...
[ "def", "types_msg", "(", "instance", ",", "types", ")", ":", "reprs", "=", "[", "]", "for", "type", "in", "types", ":", "try", ":", "reprs", ".", "append", "(", "repr", "(", "type", "[", "\"name\"", "]", ")", ")", "except", "Exception", ":", "reprs...
30.555556
23.111111
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list ...
[ "def", "word_list_to_long", "(", "val_list", ",", "big_endian", "=", "True", ")", ":", "# allocate list for long int", "long_list", "=", "[", "None", "]", "*", "int", "(", "len", "(", "val_list", ")", "/", "2", ")", "# fill registers list with register items", "...
37.73913
17.478261
def apk(self, args): """Create an APK using the given distribution.""" ctx = self.ctx dist = self._dist # Manually fixing these arguments at the string stage is # unsatisfactory and should probably be changed somehow, but # we can't leave it until later as the build.py ...
[ "def", "apk", "(", "self", ",", "args", ")", ":", "ctx", "=", "self", ".", "ctx", "dist", "=", "self", ".", "_dist", "# Manually fixing these arguments at the string stage is", "# unsatisfactory and should probably be changed somehow, but", "# we can't leave it until later as...
43.961039
18.409091
def summarize(self, file: Optional[TextIO] = None) -> None: """Print a summary of the graph.""" print(self.summary_str(), file=file)
[ "def", "summarize", "(", "self", ",", "file", ":", "Optional", "[", "TextIO", "]", "=", "None", ")", "->", "None", ":", "print", "(", "self", ".", "summary_str", "(", ")", ",", "file", "=", "file", ")" ]
48.666667
7.666667