text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def python(self, cmd): """Execute a python script using the virtual environment python.""" python_bin = self.cmd_path('python') cmd = '{0} {1}'.format(python_bin, cmd) return self._execute(cmd)
[ "def", "python", "(", "self", ",", "cmd", ")", ":", "python_bin", "=", "self", ".", "cmd_path", "(", "'python'", ")", "cmd", "=", "'{0} {1}'", ".", "format", "(", "python_bin", ",", "cmd", ")", "return", "self", ".", "_execute", "(", "cmd", ")" ]
44.2
0.008889
def put_file(self, remote_path, local_source_file, **kwargs): """Upload a file :param remote_path: path to the target file. A target directory can also be specified instead by appending a "/" :param local_source_file: path to the local file to upload :param chunked: (optiona...
[ "def", "put_file", "(", "self", ",", "remote_path", ",", "local_source_file", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'chunked'", ",", "True", ")", ":", "return", "self", ".", "_put_file_chunked", "(", "remote_path", ",", "lo...
38.081081
0.001384
def impact_table_extractor(impact_report, component_metadata): """Extracting impact summary of the impact layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component...
[ "def", "impact_table_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "context", "=", "{", "}", "extra_args", "=", "component_metadata", ".", "extra_args", "components_list", "=", "resolve_from_dictionary", "(", "extra_args", ",", "'components_list...
34.513514
0.000762
def _build_callback(self, config): ''' Apply plugins to a route and return a new callable. ''' wrapped = config['callback'] plugins = self.plugins + config['apply'] skip = config['skip'] try: for plugin in reversed(plugins): if True in skip: break ...
[ "def", "_build_callback", "(", "self", ",", "config", ")", ":", "wrapped", "=", "config", "[", "'callback'", "]", "plugins", "=", "self", ".", "plugins", "+", "config", "[", "'apply'", "]", "skip", "=", "config", "[", "'skip'", "]", "try", ":", "for", ...
45.842105
0.008999
def process_from_webservice(id_val, id_type='pmcid', source='pmc', with_grounding=True): """Return an output from RLIMS-p for the given PubMed ID or PMC ID. Parameters ---------- id_val : str A PMCID, with the prefix PMC, or pmid, with no prefix, of the paper to ...
[ "def", "process_from_webservice", "(", "id_val", ",", "id_type", "=", "'pmcid'", ",", "source", "=", "'pmc'", ",", "with_grounding", "=", "True", ")", ":", "if", "with_grounding", ":", "fmt", "=", "'%s.normed/%s/%s'", "else", ":", "fmt", "=", "'%s/%s/%s'", "...
34.615385
0.00072
def command(self, verb, args=None): """Call a command on the server. If the user has not authenticated then authentication will be done as part of calling the command on the server. For commands that don't return a status message the status message will default to an empty stri...
[ "def", "command", "(", "self", ",", "verb", ",", "args", "=", "None", ")", ":", "if", "self", ".", "__generating", ":", "raise", "NNTPSyncError", "(", "\"Command issued while a generator is active\"", ")", "cmd", "=", "verb", "if", "args", ":", "cmd", "+=", ...
33.297872
0.001862
def parse_dash(string, width): "parse dash pattern specified with string" # DashConvert from {tk-sources}/generic/tkCanvUtil.c w = max(1, int(width + 0.5)) n = len(string) result = [] for i, c in enumerate(string): if c == " " and len(result): result[-1] += w + 1 elif c == "_": result.append(8*w) ...
[ "def", "parse_dash", "(", "string", ",", "width", ")", ":", "# DashConvert from {tk-sources}/generic/tkCanvUtil.c", "w", "=", "max", "(", "1", ",", "int", "(", "width", "+", "0.5", ")", ")", "n", "=", "len", "(", "string", ")", "result", "=", "[", "]", ...
21.375
0.044776
def difference(self, sig: Scope) -> Scope: """ Create a new Set produce by a Set subtracted by another Set """ new = Scope(sig=self._hsig.values(), state=self.state) new -= sig return new
[ "def", "difference", "(", "self", ",", "sig", ":", "Scope", ")", "->", "Scope", ":", "new", "=", "Scope", "(", "sig", "=", "self", ".", "_hsig", ".", "values", "(", ")", ",", "state", "=", "self", ".", "state", ")", "new", "-=", "sig", "return", ...
43
0.009132
def match_events(ref, est, window, distance=None): """Compute a maximum matching between reference and estimated event times, subject to a window constraint. Given two lists of event times ``ref`` and ``est``, we seek the largest set of correspondences ``(ref[i], est[j])`` such that ``distance(ref[...
[ "def", "match_events", "(", "ref", ",", "est", ",", "window", ",", "distance", "=", "None", ")", ":", "if", "distance", "is", "not", "None", ":", "# Compute the indices of feasible pairings", "hits", "=", "np", ".", "where", "(", "distance", "(", "ref", ",...
30.958333
0.000652
def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, loader, code, fname = _get_module_details(mod_name) if run_name is None: run_name...
[ "def", "run_module", "(", "mod_name", ",", "init_globals", "=", "None", ",", "run_name", "=", "None", ",", "alter_sys", "=", "False", ")", ":", "mod_name", ",", "loader", ",", "code", ",", "fname", "=", "_get_module_details", "(", "mod_name", ")", "if", ...
38.294118
0.001499
def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" try: data = self.request(project + '/') except: raise if not isinstance(data, clam.common.data.CLAMData): ...
[ "def", "get", "(", "self", ",", "project", ")", ":", "try", ":", "data", "=", "self", ".", "request", "(", "project", "+", "'/'", ")", "except", ":", "raise", "if", "not", "isinstance", "(", "data", ",", "clam", ".", "common", ".", "data", ".", "...
40.4
0.009685
def format(self, **kwargs): """Apply formatting.""" attrs = self._attrs.copy() attrs.update(kwargs) return Region(self._geojson, **attrs)
[ "def", "format", "(", "self", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "self", ".", "_attrs", ".", "copy", "(", ")", "attrs", ".", "update", "(", "kwargs", ")", "return", "Region", "(", "self", ".", "_geojson", ",", "*", "*", "attrs", ")"...
33
0.011834
def _get_user_class(self, name): """Get or create a user class of the given type.""" self._user_classes.setdefault(name, _make_user_class(self, name)) return self._user_classes[name]
[ "def", "_get_user_class", "(", "self", ",", "name", ")", ":", "self", ".", "_user_classes", ".", "setdefault", "(", "name", ",", "_make_user_class", "(", "self", ",", "name", ")", ")", "return", "self", ".", "_user_classes", "[", "name", "]" ]
51.5
0.009569
def getvector(d,s): ''' Get a vector flds data. Parameters: ----------- d -- flds data. s -- key for the data. ''' return np.array([d[s+"x"],d[s+"y"],d[s+"z"]]);
[ "def", "getvector", "(", "d", ",", "s", ")", ":", "return", "np", ".", "array", "(", "[", "d", "[", "s", "+", "\"x\"", "]", ",", "d", "[", "s", "+", "\"y\"", "]", ",", "d", "[", "s", "+", "\"z\"", "]", "]", ")" ]
16.818182
0.025641
def copy_files(files_type, class_dir, output): """Copies the files from the input folder to the output folder """ # get the last part within the file class_name = path.split(class_dir)[1] for (files, folder_type) in files_type: full_path = path.join(output, folder_type, class_name) ...
[ "def", "copy_files", "(", "files_type", ",", "class_dir", ",", "output", ")", ":", "# get the last part within the file", "class_name", "=", "path", ".", "split", "(", "class_dir", ")", "[", "1", "]", "for", "(", "files", ",", "folder_type", ")", "in", "file...
36.916667
0.002203
def _sentiment(self, distance=True): """Calculates the sentiment of an entity as it appears in text.""" sum_pos = 0 sum_neg = 0 text = self.parent entity_positions = range(self.start, self.end) non_entity_positions = set(range(len(text.words))).difference(entity_positions) if not distance: ...
[ "def", "_sentiment", "(", "self", ",", "distance", "=", "True", ")", ":", "sum_pos", "=", "0", "sum_neg", "=", "0", "text", "=", "self", ".", "parent", "entity_positions", "=", "range", "(", "self", ".", "start", ",", "self", ".", "end", ")", "non_en...
46.869565
0.013636
def _find_first_of(line, substrings): """Find earliest occurrence of one of substrings in line. Returns pair of index and found substring, or (-1, None) if no occurrences of any of substrings were found in line. """ starts = ((line.find(i), i) for i in substrings) found = [(i, sub) for i, sub i...
[ "def", "_find_first_of", "(", "line", ",", "substrings", ")", ":", "starts", "=", "(", "(", "line", ".", "find", "(", "i", ")", ",", "i", ")", "for", "i", "in", "substrings", ")", "found", "=", "[", "(", "i", ",", "sub", ")", "for", "i", ",", ...
33.583333
0.002415
def make_batches(paths: Sequence[Path], batch_size: int) -> List[Sequence[Path]]: """ Group utterances into batches for decoding. """ return [paths[i:i+batch_size] for i in range(0, len(paths), batch_size)]
[ "def", "make_batches", "(", "paths", ":", "Sequence", "[", "Path", "]", ",", "batch_size", ":", "int", ")", "->", "List", "[", "Sequence", "[", "Path", "]", "]", ":", "return", "[", "paths", "[", "i", ":", "i", "+", "batch_size", "]", "for", "i", ...
44.8
0.008772
def output(self): """! @brief (list) Returns output dynamic of the Sync network (phase coordinates of each oscillator in the network) during simulation. """ if ( (self._ccore_sync_dynamic_pointer is not None) and ( (self._dynamic is None) or (len(self._dynamic) == 0) ) ): ...
[ "def", "output", "(", "self", ")", ":", "if", "(", "(", "self", ".", "_ccore_sync_dynamic_pointer", "is", "not", "None", ")", "and", "(", "(", "self", ".", "_dynamic", "is", "None", ")", "or", "(", "len", "(", "self", ".", "_dynamic", ")", "==", "0...
49.666667
0.028571
def str_count(x, pat, regex=False): """Count the occurences of a pattern in sample of a string column. :param str pat: A string or regex pattern :param bool regex: If True, :returns: an expression containing the number of times a pattern is found in each sample. Example: >>> import vaex >...
[ "def", "str_count", "(", "x", ",", "pat", ",", "regex", "=", "False", ")", ":", "return", "_to_string_sequence", "(", "x", ")", ".", "count", "(", "pat", ",", "regex", ")" ]
25.774194
0.002413
def set_state(self, state): """ Set the state of this device to on or off. """ self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state)
[ "def", "set_state", "(", "self", ",", "state", ")", ":", "self", ".", "basicevent", ".", "SetBinaryState", "(", "BinaryState", "=", "int", "(", "state", ")", ")", "self", ".", "_state", "=", "int", "(", "state", ")" ]
32.166667
0.010101
def new() -> ulid.ULID: """ Create a new :class:`~ulid.ulid.ULID` instance. The timestamp is created from :func:`~time.time`. The randomness is created from :func:`~os.urandom`. :return: ULID from current timestamp :rtype: :class:`~ulid.ulid.ULID` """ timestamp = int(time.time() * 1000...
[ "def", "new", "(", ")", "->", "ulid", ".", "ULID", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", ".", "to_bytes", "(", "6", ",", "byteorder", "=", "'big'", ")", "randomness", "=", "os", ".", "urandom", "(", ...
31.923077
0.002342
def move_page_bottom(self): """ Move the cursor to the last item on the page. """ self.nav.page_index = self.content.range[1] self.nav.cursor_index = 0 self.nav.inverted = True
[ "def", "move_page_bottom", "(", "self", ")", ":", "self", ".", "nav", ".", "page_index", "=", "self", ".", "content", ".", "range", "[", "1", "]", "self", ".", "nav", ".", "cursor_index", "=", "0", "self", ".", "nav", ".", "inverted", "=", "True" ]
31.142857
0.008929
def project(*args, **kwargs): """ Build a projection for MongoDB. Due to https://jira.mongodb.org/browse/SERVER-3156, until MongoDB 2.6, the values must be integers and not boolean. >>> project(a=True) == {'a': 1} True Once MongoDB 2.6 is released, replace use of this function with a simp...
[ "def", "project", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "projection", "=", "dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "{", "key", ":", "int", "(", "value", ")", "for", "key", ",", "value", "in", "six", ".",...
29.2
0.002212
def init_db(self): '''这个任务数据库只在程序开始时读入, 在程序关闭时导出. 因为Gtk没有像在Qt中那么方便的使用SQLite, 而必须将所有数据读入一个 liststore中才行. ''' cache_path = os.path.join(Config.CACHE_DIR, self.app.profile['username']) if not os.path.exists(cache_path): os.maked...
[ "def", "init_db", "(", "self", ")", ":", "cache_path", "=", "os", ".", "path", ".", "join", "(", "Config", ".", "CACHE_DIR", ",", "self", ".", "app", ".", "profile", "[", "'username'", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", ...
30.870968
0.002026
def _make_expand_x_fn_for_batch_interpolation(y_ref, axis): """Make func to expand left/right (of axis) dims of tensors shaped like x.""" # This expansion is to help x broadcast with `y`, the output. # In the batch case, the output shape is going to be # Broadcast(y_ref.shape[:axis], x.shape[:-1]) + # x.s...
[ "def", "_make_expand_x_fn_for_batch_interpolation", "(", "y_ref", ",", "axis", ")", ":", "# This expansion is to help x broadcast with `y`, the output.", "# In the batch case, the output shape is going to be", "# Broadcast(y_ref.shape[:axis], x.shape[:-1]) +", "# x.shape[-1:] + y_ref.shap...
41.4
0.010789
def decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None): """Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. For incremental decompression, use a LZMADecompressor object instead. """ res...
[ "def", "decompress", "(", "data", ",", "format", "=", "FORMAT_AUTO", ",", "memlimit", "=", "None", ",", "filters", "=", "None", ")", ":", "results", "=", "[", "]", "while", "True", ":", "decomp", "=", "LZMADecompressor", "(", "format", ",", "memlimit", ...
35.961538
0.002083
def upload_job_chunk_list(self, upload_job_id, **kwargs): # noqa: E501 """List all metadata for uploaded chunks # noqa: E501 List all metadata for uploaded chunks # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass a...
[ "def", "upload_job_chunk_list", "(", "self", ",", "upload_job_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
150.692308
0.000507
def _get_env(self): """this returns an environment dictionary we want to use to run the command this will also create a fake pgpass file in order to make it possible for the script to be passwordless""" if hasattr(self, 'env'): return self.env # create a temporary pgpass file ...
[ "def", "_get_env", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'env'", ")", ":", "return", "self", ".", "env", "# create a temporary pgpass file", "pgpass", "=", "self", ".", "_get_file", "(", ")", "# format: http://www.postgresql.org/docs/9.2/stati...
41.555556
0.00915
def _from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None, window=None, **kwargs): """Generate a time-frequency coherence :class:`~gwpy.spectrogram.Spectrogram` from a pair of :class:`~gwpy.timeseries.TimeSeries`. For each `stride`, a PSD :class:`~gwpy.frequencyseries.Fre...
[ "def", "_from_timeseries", "(", "ts1", ",", "ts2", ",", "stride", ",", "fftlength", "=", "None", ",", "overlap", "=", "None", ",", "window", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# check sampling rates", "if", "ts1", ".", "sample_rate", ".", ...
34.423077
0.000543
def lock_access(repository_path, callback): """ Synchronise access to the user file between processes, this specifies which user is allowed write access at the current time """ with open(cpjoin(repository_path, 'lock_file'), 'w') as fd: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB...
[ "def", "lock_access", "(", "repository_path", ",", "callback", ")", ":", "with", "open", "(", "cpjoin", "(", "repository_path", ",", "'lock_file'", ")", ",", "'w'", ")", "as", "fd", ":", "try", ":", "fcntl", ".", "flock", "(", "fd", ",", "fcntl", ".", ...
39.833333
0.002045
def _get_key_info(self): """Get key info appropriate for signing: either from the ssh agent or from a private key. """ if self._key_info_cache is not None: return self._key_info_cache errors = [] # First try the agent. try: key_info = age...
[ "def", "_get_key_info", "(", "self", ")", ":", "if", "self", ".", "_key_info_cache", "is", "not", "None", ":", "return", "self", ".", "_key_info_cache", "errors", "=", "[", "]", "# First try the agent.", "try", ":", "key_info", "=", "agent_key_info_from_key_id",...
30.709677
0.002037
def _download_datasets(): """Utility to download datasets into package source""" def filepath(*args): return abspath(join(dirname(__file__), '..', 'vega_datasets', *args)) dataset_listing = {} for name in DATASETS_TO_DOWNLOAD: data = Dataset(name) url = data.url filename ...
[ "def", "_download_datasets", "(", ")", ":", "def", "filepath", "(", "*", "args", ")", ":", "return", "abspath", "(", "join", "(", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'vega_datasets'", ",", "*", "args", ")", ")", "dataset_listing", "=", ...
45
0.001555
def busmap_from_psql(network, session, scn_name): """ Retrieves busmap from `model_draft.ego_grid_pf_hv_busmap` on the <OpenEnergyPlatform>[www.openenergy-platform.org] by a given scenario name. If this busmap does not exist, it is created with default values. Parameters ---------- network : py...
[ "def", "busmap_from_psql", "(", "network", ",", "session", ",", "scn_name", ")", ":", "def", "fetch", "(", ")", ":", "query", "=", "session", ".", "query", "(", "EgoGridPfHvBusmap", ".", "bus0", ",", "EgoGridPfHvBusmap", ".", "bus1", ")", ".", "filter", ...
28.488372
0.000789
def set_depth_range(self, near=0., far=1.): """Set depth values Parameters ---------- near : float Near clipping plane. far : float Far clipping plane. """ self.glir.command('FUNC', 'glDepthRange', float(near), float(far))
[ "def", "set_depth_range", "(", "self", ",", "near", "=", "0.", ",", "far", "=", "1.", ")", ":", "self", ".", "glir", ".", "command", "(", "'FUNC'", ",", "'glDepthRange'", ",", "float", "(", "near", ")", ",", "float", "(", "far", ")", ")" ]
27
0.009772
def plugin_privileges(self, name): """ Retrieve list of privileges to be granted to a plugin. Args: name (string): Name of the remote plugin to examine. The ``:latest`` tag is optional, and is the default if omitted. Returns: ...
[ "def", "plugin_privileges", "(", "self", ",", "name", ")", ":", "params", "=", "{", "'remote'", ":", "name", ",", "}", "headers", "=", "{", "}", "registry", ",", "repo_name", "=", "auth", ".", "resolve_repository_name", "(", "name", ")", "header", "=", ...
29.851852
0.002404
def parse_typing_status_message(p): """Return TypingStatusMessage from hangouts_pb2.SetTypingNotification. The same status may be sent multiple times consecutively, and when a message is sent the typing status will not change to stopped. """ return TypingStatusMessage( conv_id=p.conversatio...
[ "def", "parse_typing_status_message", "(", "p", ")", ":", "return", "TypingStatusMessage", "(", "conv_id", "=", "p", ".", "conversation_id", ".", "id", ",", "user_id", "=", "from_participantid", "(", "p", ".", "sender_id", ")", ",", "timestamp", "=", "from_tim...
36.833333
0.002208
def print_solution(solution): """Prints a solution Arguments --------- solution : BaseSolution Example ------- :: [8, 9, 10, 7]: 160 [5, 6]: 131 [3, 4, 2]: 154 Total cost: 445 """ total_cost = 0 for solution in solution.routes()...
[ "def", "print_solution", "(", "solution", ")", ":", "total_cost", "=", "0", "for", "solution", "in", "solution", ".", "routes", "(", ")", ":", "cost", "=", "solution", ".", "length", "(", ")", "total_cost", "=", "total_cost", "+", "cost", "print", "(", ...
20.25
0.009823
def set_style(self, *args, **kwargs): """ Provides access to any number of style sheet settings via self._widget.SetStyleSheet() *args can be any element between semicolons, e.g. self.set_stylesheet('text-align: right; padding-left: 5px') **kwargs can be an...
[ "def", "set_style", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# assemble the string", "s", "=", "\"QLabel {\"", "for", "a", "in", "args", ":", "s", "=", "s", "+", "a", "+", "\"; \"", "for", "k", "in", "list", "(", "kwargs",...
35.772727
0.013614
def get_chat_administrators(self, *args, **kwargs): """See :func:`get_chat_administrators`""" return get_chat_administrators(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_chat_administrators", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_chat_administrators", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(...
62
0.015957
def __delete_represented_points(self, cluster): """! @brief Remove representation points of clusters from the k-d tree @param[in] cluster (cure_cluster): Cluster whose representation points should be removed. """ for point in cluster.rep: ...
[ "def", "__delete_represented_points", "(", "self", ",", "cluster", ")", ":", "for", "point", "in", "cluster", ".", "rep", ":", "self", ".", "__tree", ".", "remove", "(", "point", ",", "payload", "=", "cluster", ")" ]
36.1
0.018919
def dynamic_number_format(self, rb=1, align=1, **fmt_args): """Formatter changes based on the cell value""" fct = fmt.DynamicNumberFormatter(**fmt_args) return self.apply_number_format(fct, rb=rb, align=align)
[ "def", "dynamic_number_format", "(", "self", ",", "rb", "=", "1", ",", "align", "=", "1", ",", "*", "*", "fmt_args", ")", ":", "fct", "=", "fmt", ".", "DynamicNumberFormatter", "(", "*", "*", "fmt_args", ")", "return", "self", ".", "apply_number_format",...
57.5
0.008584
def map_peaks_to_image(peaks, r=4, vox_dims=(2, 2, 2), dims=(91, 109, 91), header=None): """ Take a set of discrete foci (i.e., 2-D array of xyz coordinates) and generate a corresponding image, convolving each focus with a hard sphere of radius r.""" data = np.zeros(dims) for ...
[ "def", "map_peaks_to_image", "(", "peaks", ",", "r", "=", "4", ",", "vox_dims", "=", "(", "2", ",", "2", ",", "2", ")", ",", "dims", "=", "(", "91", ",", "109", ",", "91", ")", ",", "header", "=", "None", ")", ":", "data", "=", "np", ".", "...
44.636364
0.001996
def _handle_match(client, channel, nick, message, matches): """ Match stores all channel info. If helga is asked something to stimulate a markov response about channel data, then we shall graciously provide it. """ generate_interrogative = _CHANNEL_GENERATE_REGEX.match(message) if generate_inter...
[ "def", "_handle_match", "(", "client", ",", "channel", ",", "nick", ",", "message", ",", "matches", ")", ":", "generate_interrogative", "=", "_CHANNEL_GENERATE_REGEX", ".", "match", "(", "message", ")", "if", "generate_interrogative", ":", "return", "generate", ...
44.3125
0.001381
def modeled_savings( baseline_model, reporting_model, result_index, temperature_data, with_disaggregated=False, confidence_level=0.90, predict_kwargs=None, ): """ Compute modeled savings, i.e., savings in which baseline and reporting usage values are based on models. This is appropri...
[ "def", "modeled_savings", "(", "baseline_model", ",", "reporting_model", ",", "result_index", ",", "temperature_data", ",", "with_disaggregated", "=", "False", ",", "confidence_level", "=", "0.90", ",", "predict_kwargs", "=", "None", ",", ")", ":", "prediction_index...
36.845161
0.001023
def object_build_methoddescriptor(node, member, localname): """create astroid for a living method descriptor object""" # FIXME get arguments ? func = build_function( getattr(member, "__name__", None) or localname, doc=member.__doc__ ) # set node's arguments to None to notice that we have no ...
[ "def", "object_build_methoddescriptor", "(", "node", ",", "member", ",", "localname", ")", ":", "# FIXME get arguments ?", "func", "=", "build_function", "(", "getattr", "(", "member", ",", "\"__name__\"", ",", "None", ")", "or", "localname", ",", "doc", "=", ...
41.727273
0.002132
def run_check_kind(_): ''' Running the script. ''' for kindv in router_post: for rec_cat in MCategory.query_all(kind=kindv): catid = rec_cat.uid catinfo = MCategory.get_by_uid(catid) for rec_post2tag in MPost2Catalog.query_by_catid(catid): post...
[ "def", "run_check_kind", "(", "_", ")", ":", "for", "kindv", "in", "router_post", ":", "for", "rec_cat", "in", "MCategory", ".", "query_all", "(", "kind", "=", "kindv", ")", ":", "catid", "=", "rec_cat", ".", "uid", "catinfo", "=", "MCategory", ".", "g...
34.928571
0.001992
def parse_setup(filepath): '''Get the kwargs from the setup function in setup.py''' # TODO: Need to parse setup.cfg and merge with the data from below # Monkey patch setuptools.setup to capture keyword arguments setup_kwargs = {} def setup_interceptor(**kwargs): setup_kwargs.update(kwargs)...
[ "def", "parse_setup", "(", "filepath", ")", ":", "# TODO: Need to parse setup.cfg and merge with the data from below", "# Monkey patch setuptools.setup to capture keyword arguments", "setup_kwargs", "=", "{", "}", "def", "setup_interceptor", "(", "*", "*", "kwargs", ")", ":", ...
29.086957
0.001447
def _func_addrs_from_symbols(self): """ Get all possible function addresses that are specified by the symbols in the binary :return: A set of addresses that are probably functions :rtype: set """ return {sym.rebased_addr for sym in self._binary.symbols if sym.is_functio...
[ "def", "_func_addrs_from_symbols", "(", "self", ")", ":", "return", "{", "sym", ".", "rebased_addr", "for", "sym", "in", "self", ".", "_binary", ".", "symbols", "if", "sym", ".", "is_function", "}" ]
34.888889
0.012422
def start_processes(self, max_restarts=-1): """ Start processes and check their status. When some process crashes, start it again. *max_restarts* is maximum amount of the restarts across all processes. *processes* is a :class:`list` of the :class:`ProcessWrapper` instances. ...
[ "def", "start_processes", "(", "self", ",", "max_restarts", "=", "-", "1", ")", ":", "while", "1", ":", "for", "process", "in", "self", ".", "processes", ":", "if", "not", "process", ":", "# When process has not been started, start it", "if", "not", "process",...
45.259259
0.000801
def set_result(self, result): """Sets the return value of work associated with the future. Should only be used by Task and unit tests. """ self._result = result self._state = self.FINISHED
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "self", ".", "_result", "=", "result", "self", ".", "_state", "=", "self", ".", "FINISHED" ]
31.857143
0.008734
def reduced_to_matrix(shape, degree, vals_by_weight): r"""Converts a reduced values dictionary into a matrix. .. note:: This is a helper used only by :func:`_specialize_surface`. The ``vals_by_weight`` mapping has keys of the form: ``(0, ..., 1, ..., 2, ...)`` where the ``0`` corresponds t...
[ "def", "reduced_to_matrix", "(", "shape", ",", "degree", ",", "vals_by_weight", ")", ":", "result", "=", "np", ".", "empty", "(", "shape", ",", "order", "=", "\"F\"", ")", "index", "=", "0", "for", "k", "in", "six", ".", "moves", ".", "xrange", "(", ...
36.952381
0.000628
def make_field(self, **kwargs): """ create serializer field """ kwargs['required'] = False kwargs['allow_null'] = True return self.field_class(**kwargs)
[ "def", "make_field", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'required'", "]", "=", "False", "kwargs", "[", "'allow_null'", "]", "=", "True", "return", "self", ".", "field_class", "(", "*", "*", "kwargs", ")" ]
36
0.01087
def pathFromHere_explore(self, astr_startPath = '/'): """ Return a list of paths from "here" in the stree, using the child explore access. :param astr_startPath: path from which to start :return: a list of paths from "here" """ self.l...
[ "def", "pathFromHere_explore", "(", "self", ",", "astr_startPath", "=", "'/'", ")", ":", "self", ".", "l_lwd", "=", "[", "]", "self", ".", "treeExplore", "(", "startPath", "=", "astr_startPath", ",", "f", "=", "self", ".", "lwd", ")", "return", "self", ...
34.833333
0.016317
def _calculatePredictedCells(self, activeBasalSegments, activeApicalSegments): """ Calculate the predicted cells, given the set of active segments. An active basal segment is enough to predict a cell. An active apical segment is *not* enough to predict a cell. When a cell has both types of segment...
[ "def", "_calculatePredictedCells", "(", "self", ",", "activeBasalSegments", ",", "activeApicalSegments", ")", ":", "cellsForBasalSegments", "=", "self", ".", "basalConnections", ".", "mapSegmentsToCells", "(", "activeBasalSegments", ")", "cellsForApicalSegments", "=", "se...
39.228571
0.002132
def log_transition(self, transition, from_state, instance, *args, **kwargs): """Log a transition. Args: transition (Transition): the name of the performed transition from_state (State): the source state instance (object): the modified object Kwargs: ...
[ "def", "log_transition", "(", "self", ",", "transition", ",", "from_state", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'xworkflows.transitions'", ")", "try", ":", "instance_repr", ...
39.4
0.002478
def walk(self, address): ''' Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded i...
[ "def", "walk", "(", "self", ",", "address", ")", ":", "for", "step", "in", "self", ".", "_walk_to_address", "(", "address", ")", ":", "node", "=", "step", "yield", "node", ".", "address", ",", "node", ".", "data", "to_process", "=", "deque", "(", ")"...
27.233333
0.002364
def join(*vectors): r""" Takes an arbitrary number of aligned vectors of the same length and combines them into a single vector (vertically). E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12 feature vector is created and returned. The feature vectors ...
[ "def", "join", "(", "*", "vectors", ")", ":", "# check supplied arguments", "if", "len", "(", "vectors", ")", "<", "2", ":", "return", "vectors", "[", "0", "]", "# process supplied arguments", "vectors", "=", "list", "(", "vectors", ")", "for", "i", "in", ...
27.95122
0.009275
def dump(type, exc): """ Always return a dumped (pickled) type and exc. If exc can't be pickled, wrap it in UnpickleableException first. """ try: return pickle.dumps(type), pickle.dumps(exc) except Exception: # get UnpickleableException inside the ...
[ "def", "dump", "(", "type", ",", "exc", ")", ":", "try", ":", "return", "pickle", ".", "dumps", "(", "type", ")", ",", "pickle", ".", "dumps", "(", "exc", ")", "except", "Exception", ":", "# get UnpickleableException inside the sandbox", "if", "\"__PEX_UNVEN...
41.666667
0.00939
def main(): """The command line interface of the ``vcs-tool`` program.""" # Initialize logging to the terminal. coloredlogs.install() # Command line option defaults. repository = None revision = None actions = [] # Parse the command line arguments. try: options, arguments = g...
[ "def", "main", "(", ")", ":", "# Initialize logging to the terminal.", "coloredlogs", ".", "install", "(", ")", "# Command line option defaults.", "repository", "=", "None", "revision", "=", "None", "actions", "=", "[", "]", "# Parse the command line arguments.", "try",...
53.308511
0.002351
def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Docs Returns ------- Counter noun chunk -> count ''' return Counter([str(c).lower() for c in doc.noun_chunks])
[ "def", "get_feats", "(", "self", ",", "doc", ")", ":", "return", "Counter", "(", "[", "str", "(", "c", ")", ".", "lower", "(", ")", "for", "c", "in", "doc", ".", "noun_chunks", "]", ")" ]
16.545455
0.057292
def _start_node(node): """ Start the given node VM. :return: bool -- True on success, False otherwise """ log.debug("_start_node: working on node `%s`", node.name) # FIXME: the following check is not optimal yet. When a node is still # in a starting state, it wil...
[ "def", "_start_node", "(", "node", ")", ":", "log", ".", "debug", "(", "\"_start_node: working on node `%s`\"", ",", "node", ".", "name", ")", "# FIXME: the following check is not optimal yet. When a node is still", "# in a starting state, it will start another node here, since the...
40.26087
0.00211
def rest_api_exists(self, rest_api_id): # type: (str) -> bool """Check if an an API Gateway REST API exists.""" client = self._client('apigateway') try: client.get_rest_api(restApiId=rest_api_id) return True except client.exceptions.NotFoundException: ...
[ "def", "rest_api_exists", "(", "self", ",", "rest_api_id", ")", ":", "# type: (str) -> bool", "client", "=", "self", ".", "_client", "(", "'apigateway'", ")", "try", ":", "client", ".", "get_rest_api", "(", "restApiId", "=", "rest_api_id", ")", "return", "True...
36.888889
0.008824
def publications(columns, n_results, queries): """Search for publications""" if not isinstance(queries, dict): query_dict = {} for q in queries: key, value = q.split('=') if key == 'distinct': if value in ['True', 'true']: query_dict.up...
[ "def", "publications", "(", "columns", ",", "n_results", ",", "queries", ")", ":", "if", "not", "isinstance", "(", "queries", ",", "dict", ")", ":", "query_dict", "=", "{", "}", "for", "q", "in", "queries", ":", "key", ",", "value", "=", "q", ".", ...
34.909091
0.000633
def defaulted_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Context manager version of :func:`set_default_config()`. Use this with a Python 'with' statement, like >>> config_yaml = ''' ... toplevel: ... param: value ... ''' >>...
[ "def", "defaulted_config", "(", "modules", ",", "params", "=", "None", ",", "yaml", "=", "None", ",", "filename", "=", "None", ",", "config", "=", "None", ",", "validate", "=", "True", ")", ":", "with", "_temporary_config", "(", ")", ":", "set_default_co...
40.419355
0.000779
def save_method(elements, module_path): """ Recursively save methods with module name and signature. """ for elem, signature in elements.items(): if isinstance(signature, dict): # Submodule case save_method(signature, module_path + (elem,)) elif isinstance(signature, Class): ...
[ "def", "save_method", "(", "elements", ",", "module_path", ")", ":", "for", "elem", ",", "signature", "in", "elements", ".", "items", "(", ")", ":", "if", "isinstance", "(", "signature", ",", "dict", ")", ":", "# Submodule case", "save_method", "(", "signa...
51.625
0.001189
def external_metadata(self, datasource_type=None, datasource_id=None): """Gets column info from the source system""" if datasource_type == 'druid': datasource = ConnectorRegistry.get_datasource( datasource_type, datasource_id, db.session) elif datasource_type == 'tabl...
[ "def", "external_metadata", "(", "self", ",", "datasource_type", "=", "None", ",", "datasource_id", "=", "None", ")", ":", "if", "datasource_type", "==", "'druid'", ":", "datasource", "=", "ConnectorRegistry", ".", "get_datasource", "(", "datasource_type", ",", ...
42.45
0.002304
def update(cls, id, params): """Update an existing vlan.""" cls.echo('Updating your vlan.') result = cls.call('hosting.vlan.update', cls.usable_id(id), params) return result
[ "def", "update", "(", "cls", ",", "id", ",", "params", ")", ":", "cls", ".", "echo", "(", "'Updating your vlan.'", ")", "result", "=", "cls", ".", "call", "(", "'hosting.vlan.update'", ",", "cls", ".", "usable_id", "(", "id", ")", ",", "params", ")", ...
40.2
0.009756
def applet_remove_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /applet-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags """ return DXHTTPRequest('/%s/removeTags' % objec...
[ "def", "applet_remove_tags", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/removeTags'", "%", "object_id", ",", "input_params", ",", "always_retr...
52.857143
0.010638
def get(self, study_id, content=None, schema=None, **kwargs): """Syntactic sugar around to make it easier to get fine-grained access to the parts of a file without composing a PhyloSchema object. Possible invocations include: w.get('pg_10') w.get('pg_10', 'trees') ...
[ "def", "get", "(", "self", ",", "study_id", ",", "content", "=", "None", ",", "schema", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "study_id", ",", "TreeRef", ")", ":", "return", "self", ".", "get", "(", "study_id", "=...
43.653846
0.001724
def read_user_choice(var_name, options): """Prompt the user to choose from several options for the given variable. The first item will be returned if no input happens. :param str var_name: Variable as specified in the context :param list options: Sequence of options that are available to select from ...
[ "def", "read_user_choice", "(", "var_name", ",", "options", ")", ":", "# Please see http://click.pocoo.org/4/api/#click.prompt", "if", "not", "isinstance", "(", "options", ",", "list", ")", ":", "raise", "TypeError", "if", "not", "options", ":", "raise", "ValueError...
32.30303
0.000911
def user_absent(name, htpasswd_file=None, runas=None): ''' Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with ''' ret = {'name': name, 'chang...
[ "def", "user_absent", "(", "name", ",", "htpasswd_file", "=", "None", ",", "runas", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "None", "}", "exi...
26.5
0.001654
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = Univers...
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "u", ".", "feed", "(", "line", ")", "u", ".", "close", "(", ")", "result", "=", "u", ".", "r...
31.45
0.001543
def get_sdk_version(self) -> str: '''Show Android SDK version.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'getprop', 'ro.build.version.sdk') return output.strip()
[ "def", "get_sdk_version", "(", "self", ")", "->", "str", ":", "output", ",", "_", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'getprop'", ",", "'ro.build.version.sdk'", ")", "return", "output", ".", "st...
42.4
0.009259
def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR): """ Returns whether the specified text is visible in the specified selector. @Params driver - the webdriver object (required) text - the text string to search for selector - the locator that is used (required) by - the method t...
[ "def", "is_text_visible", "(", "driver", ",", "text", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "try", ":", "element", "=", "driver", ".", "find_element", "(", "by", "=", "by", ",", "value", "=", "selector", ")", "return", ...
36.4375
0.001672
def create_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Creates or overwrites tags associated with a file system. Each tag is a key-value pair. If a tag key specified i...
[ "def", "create_tags", "(", "filesystemid", ",", "tags", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "ke...
27.909091
0.001049
def authorize_application( request, redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE), permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS ): """ Redirect the user to authorize the application. Redirection is done by rendering a JavaScript sni...
[ "def", "authorize_application", "(", "request", ",", "redirect_uri", "=", "'https://%s/%s'", "%", "(", "FACEBOOK_APPLICATION_DOMAIN", ",", "FACEBOOK_APPLICATION_NAMESPACE", ")", ",", "permissions", "=", "FACEBOOK_APPLICATION_INITIAL_PERMISSIONS", ")", ":", "query", "=", "...
31.37037
0.020619
def sigOmega(self,dangle): """ NAME: sigmaOmega PURPOSE: calculate the 1D sigma in frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: dangle - angle offset OUTPUT: sigma Omega ...
[ "def", "sigOmega", "(", "self", ",", "dangle", ")", ":", "dOmin", "=", "dangle", "/", "self", ".", "_tdisrupt", "meandO", "=", "self", ".", "_meandO", "sO1D2", "=", "(", "(", "numpy", ".", "sqrt", "(", "2.", "/", "numpy", ".", "pi", ")", "*", "nu...
27.735294
0.025615
def _merge_configuration(self, parent_config, child_options): """Merge parent config into the child options. The migration process requires an `options` object for the child in order to distinguish between mutually exclusive codes, add-select and add-ignore error codes. """ ...
[ "def", "_merge_configuration", "(", "self", ",", "parent_config", ",", "child_options", ")", ":", "# Copy the parent error codes so we won't override them", "error_codes", "=", "copy", ".", "deepcopy", "(", "parent_config", ".", "checked_codes", ")", "if", "self", ".", ...
43.65
0.002242
def _do_filter(cnf, args): """ :param cnf: Mapping object represents configuration data :param args: :class:`argparse.Namespace` object :return: 'cnf' may be updated """ if args.query: cnf = API.query(cnf, args.query) elif args.get: cnf = _do_get(cnf, args.get) elif args....
[ "def", "_do_filter", "(", "cnf", ",", "args", ")", ":", "if", "args", ".", "query", ":", "cnf", "=", "API", ".", "query", "(", "cnf", ",", "args", ".", "query", ")", "elif", "args", ".", "get", ":", "cnf", "=", "_do_get", "(", "cnf", ",", "args...
28.2
0.002288
def out_of_bounds(self, index): """ Check index for out of bounds :param index: index as integer, tuple or slice :return: local index as tuple """ if type(index) is int: return self.int_out_of_bounds(index) elif type(index) is slice: return self....
[ "def", "out_of_bounds", "(", "self", ",", "index", ")", ":", "if", "type", "(", "index", ")", "is", "int", ":", "return", "self", ".", "int_out_of_bounds", "(", "index", ")", "elif", "type", "(", "index", ")", "is", "slice", ":", "return", "self", "....
29
0.002225
def _pad_arrays(t, arrays, indices, span, period): """Internal routine to pad arrays for periodic models.""" N = len(t) if indices is None: indices = np.arange(N) pad_left = max(0, 0 - np.min(indices - span // 2)) pad_right = max(0, np.max(indices + span - span // 2) - (N - 1)) if pad_...
[ "def", "_pad_arrays", "(", "t", ",", "arrays", ",", "indices", ",", "span", ",", "period", ")", ":", "N", "=", "len", "(", "t", ")", "if", "indices", "is", "None", ":", "indices", "=", "np", ".", "arange", "(", "N", ")", "pad_left", "=", "max", ...
40.178571
0.000868
def find_logs( self, user_name, first_date, start_time, last_date, end_time, action, functionality, parameter, pagination): """ Search all logs, filtering by the given parameters. ...
[ "def", "find_logs", "(", "self", ",", "user_name", ",", "first_date", ",", "start_time", ",", "last_date", ",", "end_time", ",", "action", ",", "functionality", ",", "parameter", ",", "pagination", ")", ":", "if", "not", "isinstance", "(", "pagination", ",",...
37.223881
0.001563
def get_br(self): """Returns the bottom right border of the cell""" cell_below = CellBorders(self.cell_attributes, *self.cell.get_below_key_rect()) return cell_below.get_r()
[ "def", "get_br", "(", "self", ")", ":", "cell_below", "=", "CellBorders", "(", "self", ".", "cell_attributes", ",", "*", "self", ".", "cell", ".", "get_below_key_rect", "(", ")", ")", "return", "cell_below", ".", "get_r", "(", ")" ]
37.666667
0.008658
def _spot_check_that_elements_produced_by_this_generator_have_attribute(self, name): """ Helper function to spot-check that the items produces by this generator have the attribute `name`. """ g_tmp = self.values_gen.spawn() sample_element = next(g_tmp)[0] try: ...
[ "def", "_spot_check_that_elements_produced_by_this_generator_have_attribute", "(", "self", ",", "name", ")", ":", "g_tmp", "=", "self", ".", "values_gen", ".", "spawn", "(", ")", "sample_element", "=", "next", "(", "g_tmp", ")", "[", "0", "]", "try", ":", "get...
46.9
0.01046
def basis_function_ders(degree, knot_vector, span, knot, order): """ Computes derivatives of the basis functions for a single parameter. Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math...
[ "def", "basis_function_ders", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ",", "order", ")", ":", "# Initialize variables", "left", "=", "[", "1.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "right", "=", "[", "1.0"...
31.886364
0.001037
def product(pc, service, attrib, sku): """ Get a list of a service's products. The list will be in the given region, matching the specific terms and any given attribute filters or a SKU. """ pc.service = service.lower() pc.sku = sku pc.add_attributes(attribs=attrib) click.echo("Servi...
[ "def", "product", "(", "pc", ",", "service", ",", "attrib", ",", "sku", ")", ":", "pc", ".", "service", "=", "service", ".", "lower", "(", ")", "pc", ".", "sku", "=", "sku", "pc", ".", "add_attributes", "(", "attribs", "=", "attrib", ")", "click", ...
37.826087
0.001121
def _build_width_map(): """ Build a translate mapping that replaces halfwidth and fullwidth forms with their standard-width forms. """ # Though it's not listed as a fullwidth character, we'll want to convert # U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start # with that...
[ "def", "_build_width_map", "(", ")", ":", "# Though it's not listed as a fullwidth character, we'll want to convert", "# U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start", "# with that in the dictionary.", "width_map", "=", "{", "0x3000", ":", "' '", "}", "for", ...
37.133333
0.001751
def get_ordering_field_columns(self): """ Returns an OrderedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying # sort field, so we base things on column numbers. ordering = self._get_default_ordering...
[ "def", "get_ordering_field_columns", "(", "self", ")", ":", "# We must cope with more than one column having the same underlying", "# sort field, so we base things on column numbers.", "ordering", "=", "self", ".", "_get_default_ordering", "(", ")", "ordering_fields", "=", "Ordered...
43.5625
0.001404
def cartesian_product(arrays, flat=True, copy=False): """ Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions. By default arrays are flattened, which may be controlled with the flat flag. The array views can be turned into regular arrays with the...
[ "def", "cartesian_product", "(", "arrays", ",", "flat", "=", "True", ",", "copy", "=", "False", ")", ":", "arrays", "=", "np", ".", "broadcast_arrays", "(", "*", "np", ".", "ix_", "(", "*", "arrays", ")", ")", "if", "flat", ":", "return", "tuple", ...
48.454545
0.001842
def attempt_open_query_permutations(url, orig_file_path, is_header_file): """ Attempt to open a given mock data file with different permutations of the query parameters """ directory = dirname(convert_to_platform_safe(orig_file_path)) + "/" # get all filenames in directory try: file...
[ "def", "attempt_open_query_permutations", "(", "url", ",", "orig_file_path", ",", "is_header_file", ")", ":", "directory", "=", "dirname", "(", "convert_to_platform_safe", "(", "orig_file_path", ")", ")", "+", "\"/\"", "# get all filenames in directory", "try", ":", "...
36.181818
0.000489
def get_variable_ddi(name, shape, initial_value, dtype=tf.float32, init=False, trainable=True): """Wrapper for data-dependent initialization.""" # If init is a tf bool: w is assigned dynamically at runtime. # If init is a python bool: then w is determined during graph construction. w = tf.g...
[ "def", "get_variable_ddi", "(", "name", ",", "shape", ",", "initial_value", ",", "dtype", "=", "tf", ".", "float32", ",", "init", "=", "False", ",", "trainable", "=", "True", ")", ":", "# If init is a tf bool: w is assigned dynamically at runtime.", "# If init is a ...
44.833333
0.014572
def alter_and_get(self, function): """ Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serial...
[ "def", "alter_and_get", "(", "self", ",", "function", ")", ":", "check_not_none", "(", "function", ",", "\"function can't be None\"", ")", "return", "self", ".", "_encode_invoke", "(", "atomic_reference_alter_and_get_codec", ",", "function", "=", "self", ".", "_to_d...
58
0.008487
def get_interval(ticker, session) -> Session: """ Get interval from defined session Args: ticker: ticker session: session Returns: Session of start_time and end_time Examples: >>> get_interval('005490 KS Equity', 'day_open_30') Session(start_time='09:00', e...
[ "def", "get_interval", "(", "ticker", ",", "session", ")", "->", "Session", ":", "if", "'_'", "not", "in", "session", ":", "session", "=", "f'{session}_normal_0_0'", "interval", "=", "Intervals", "(", "ticker", "=", "ticker", ")", "ss_info", "=", "session", ...
41.522727
0.000535
def register_middleware(self, middleware, attach_to="request"): """ Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app lev...
[ "def", "register_middleware", "(", "self", ",", "middleware", ",", "attach_to", "=", "\"request\"", ")", ":", "if", "attach_to", "==", "\"request\"", ":", "if", "middleware", "not", "in", "self", ".", "request_middleware", ":", "self", ".", "request_middleware",...
45.217391
0.001883
async def update_data_status(self, **kwargs): """Update (PATCH) Data object. :param kwargs: The dictionary of :class:`~resolwe.flow.models.Data` attributes to be changed. """ await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={ ExecutorProtoco...
[ "async", "def", "update_data_status", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "_send_manager_command", "(", "ExecutorProtocol", ".", "UPDATE", ",", "extra_fields", "=", "{", "ExecutorProtocol", ".", "UPDATE_CHANGESET", ":", "kwargs"...
38.777778
0.008403
def _path_from_module(module): """Attempt to determine bot's filesystem path from its module.""" # Convert paths to list because Python's _NamespacePath doesn't support # indexing. paths = list(getattr(module, '__path__', [])) if len(paths) != 1: filename = getattr(mo...
[ "def", "_path_from_module", "(", "module", ")", ":", "# Convert paths to list because Python's _NamespacePath doesn't support", "# indexing.", "paths", "=", "list", "(", "getattr", "(", "module", ",", "'__path__'", ",", "[", "]", ")", ")", "if", "len", "(", "paths",...
49.25
0.00166
def dpss(npts, fw, number_of_tapers, auto_spline=True, npts_max=None): """ Calculates DPSS also known as Slepian sequences or Slepian tapers. Calculation of the DPSS (Discrete Prolate Spheroidal Sequences) and the correspondent eigenvalues. The (1 - eigenvalue) terms are also calculated. Wraps the...
[ "def", "dpss", "(", "npts", ",", "fw", ",", "number_of_tapers", ",", "auto_spline", "=", "True", ",", "npts_max", "=", "None", ")", ":", "mt", "=", "_MtspecType", "(", "\"float64\"", ")", "v", "=", "mt", ".", "empty", "(", "(", "npts", ",", "number_o...
36.166667
0.00032
def get_commit_bzs(self, from_revision, to_revision=None): """ Return a list of tuples, one per commit. Each tuple is (sha1, subject, bz_list). bz_list is a (possibly zero-length) list of numbers. """ rng = self.rev_range(from_revision, to_revision) GIT_COMMIT_FIELDS = ['...
[ "def", "get_commit_bzs", "(", "self", ",", "from_revision", ",", "to_revision", "=", "None", ")", ":", "rng", "=", "self", ".", "rev_range", "(", "from_revision", ",", "to_revision", ")", "GIT_COMMIT_FIELDS", "=", "[", "'id'", ",", "'subject'", ",", "'body'"...
44.73913
0.001903
def fingerprint_correlation(P, obs1, obs2=None, tau=1, k=None, ncv=None): r"""Compute dynamical fingerprint crosscorrelation. The dynamical fingerprint autocorrelation is the timescale amplitude spectrum of the autocorrelation of the given observables under the action of the dynamics P Parameters ...
[ "def", "fingerprint_correlation", "(", "P", ",", "obs1", ",", "obs2", "=", "None", ",", "tau", "=", "1", ",", "k", "=", "None", ",", "ncv", "=", "None", ")", ":", "return", "fingerprint", "(", "P", ",", "obs1", ",", "obs2", "=", "obs2", ",", "tau...
34.617647
0.000826