text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def post(self, request, question_level, question_number, format=None): """ Use this Function to submit Comment. """ user = User.objects.get(username=request.user.username) question = Question.objects.filter(question_level=question_level).filter(question_number=question_number) ...
[ "def", "post", "(", "self", ",", "request", ",", "question_level", ",", "question_number", ",", "format", "=", "None", ")", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "request", ".", "user", ".", "username", ")", "quest...
59.685714
0.011776
def _set_perms(self, perms): """ Sets the access permissions of the map. :param perms: the new permissions. """ assert isinstance(perms, str) and len(perms) <= 3 and perms.strip() in ['', 'r', 'w', 'x', 'rw', 'r x', 'rx', 'rwx', 'wx', ] self._perms = perms
[ "def", "_set_perms", "(", "self", ",", "perms", ")", ":", "assert", "isinstance", "(", "perms", ",", "str", ")", "and", "len", "(", "perms", ")", "<=", "3", "and", "perms", ".", "strip", "(", ")", "in", "[", "''", ",", "'r'", ",", "'w'", ",", "...
37.25
0.009836
def locked_blocks_iterator(blockfile, start_info=(0, 0), cached_headers=50, batch_size=50): """ This method loads blocks from disk, skipping any orphan blocks. """ f = blockfile current_state = [] def change_state(bc, ops): for op, bh, work in ops: if op == 'add': ...
[ "def", "locked_blocks_iterator", "(", "blockfile", ",", "start_info", "=", "(", "0", ",", "0", ")", ",", "cached_headers", "=", "50", ",", "batch_size", "=", "50", ")", ":", "f", "=", "blockfile", "current_state", "=", "[", "]", "def", "change_state", "(...
30
0.001656
def infer_subexpr(self, expr, diagnostic=None): """ Infer type on the subexpr """ expr.infer_node = InferNode(parent=self.infer_node) expr.infer_type(diagnostic=diagnostic)
[ "def", "infer_subexpr", "(", "self", ",", "expr", ",", "diagnostic", "=", "None", ")", ":", "expr", ".", "infer_node", "=", "InferNode", "(", "parent", "=", "self", ".", "infer_node", ")", "expr", ".", "infer_type", "(", "diagnostic", "=", "diagnostic", ...
34.5
0.009434
def _GetNativeEolStyle(platform=sys.platform): ''' Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the current platform. ''' _NATIVE_EOL_STYLE_MAP = { 'win32' : EOL_STYLE_WINDOWS, 'linux2' : EOL_STYLE_UNIX, 'linux' : EOL_STYLE_UNIX, ...
[ "def", "_GetNativeEolStyle", "(", "platform", "=", "sys", ".", "platform", ")", ":", "_NATIVE_EOL_STYLE_MAP", "=", "{", "'win32'", ":", "EOL_STYLE_WINDOWS", ",", "'linux2'", ":", "EOL_STYLE_UNIX", ",", "'linux'", ":", "EOL_STYLE_UNIX", ",", "'darwin'", ":", "EOL...
29.333333
0.011009
def copyCurrentLayout(self, sourceViewSUID, targetViewSUID, body, verbose=None): """ Copy one network view layout onto another, setting the node location and view scale to match. This makes visually comparing networks simple. :param sourceViewSUID: Source network view SUID (or "current") ...
[ "def", "copyCurrentLayout", "(", "self", ",", "sourceViewSUID", ",", "targetViewSUID", ",", "body", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'apply/layouts/copycat/'", "+", "str", "(", "so...
56.428571
0.008717
def normal_name( self, rm_namespaces=('Template',), capital_links=False, _code: str = None, *, code: str = None, capitalize=False ) -> str: """Return normal form of self.name. - Remove comments. - Remove language code. - Remove...
[ "def", "normal_name", "(", "self", ",", "rm_namespaces", "=", "(", "'Template'", ",", ")", ",", "capital_links", "=", "False", ",", "_code", ":", "str", "=", "None", ",", "*", ",", "code", ":", "str", "=", "None", ",", "capitalize", "=", "False", ")"...
35.851351
0.001101
def _process_settings(**kwargs): """ Apply user supplied settings. """ # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style s...
[ "def", "_process_settings", "(", "*", "*", "kwargs", ")", ":", "# If we are in this method due to a signal, only reload for our settings", "setting_name", "=", "kwargs", ".", "get", "(", "'setting'", ",", "None", ")", "if", "setting_name", "is", "not", "None", "and", ...
36.333333
0.001625
def css( self, filelist ): """This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.""" if isinstance( filelist, basestring ): self.link( href=filelist, rel='stylesheet', type='text/css', media='all' ) else:...
[ "def", "css", "(", "self", ",", "filelist", ")", ":", "if", "isinstance", "(", "filelist", ",", "basestring", ")", ":", "self", ".", "link", "(", "href", "=", "filelist", ",", "rel", "=", "'stylesheet'", ",", "type", "=", "'text/css'", ",", "media", ...
48.111111
0.029478
def dr( self, cell_lengths ): """ Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell. Returns (np.array(x,y,z)): dr """ half_cell_lengths = cell_lengths / 2.0 t...
[ "def", "dr", "(", "self", ",", "cell_lengths", ")", ":", "half_cell_lengths", "=", "cell_lengths", "/", "2.0", "this_dr", "=", "self", ".", "final_site", ".", "r", "-", "self", ".", "initial_site", ".", "r", "for", "i", "in", "range", "(", "3", ")", ...
34
0.036566
def solve(self, value, filter_): """Get slice or entry defined by an index from the given value. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.SliceFilter An instance of ``SliceFilter``to so...
[ "def", "solve", "(", "self", ",", "value", ",", "filter_", ")", ":", "try", ":", "return", "value", "[", "filter_", ".", "slice", "or", "filter_", ".", "index", "]", "except", "IndexError", ":", "return", "None" ]
29.866667
0.002162
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: """Return a data structure evaluated as a reader macro from the input stream.""" start = ctx.reader.advance() assert start == "#" token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": ...
[ "def", "_read_reader_macro", "(", "ctx", ":", "ReaderContext", ")", "->", "LispReaderForm", ":", "start", "=", "ctx", ".", "reader", ".", "advance", "(", ")", "assert", "start", "==", "\"#\"", "token", "=", "ctx", ".", "reader", ".", "peek", "(", ")", ...
32.645161
0.00096
def invert_delete_row2(self, key, value): """ Invert of type two where there are two columns given """ self.rows = filter(lambda x: x.get(key) == x.get(value), self.rows)
[ "def", "invert_delete_row2", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "rows", "=", "filter", "(", "lambda", "x", ":", "x", ".", "get", "(", "key", ")", "==", "x", ".", "get", "(", "value", ")", ",", "self", ".", "rows", ")"...
40.4
0.009709
def tag(self): """ Return the tag's name (or id number) for this task. :returns: An int (tag id) or string (tag name, eg "foo-build"). This seems to depend on the task method. For example, buildArch, tagBuild, and tagNotification tasks always return ...
[ "def", "tag", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'buildArch'", ":", "# Note: buildArch tag will be an int here.", "return", "self", ".", "params", "[", "1", "]", "if", "self", ".", "method", "in", "(", "'createdistrepo'", ",", "'distR...
43.904762
0.002123
def create_environment(home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, download=False, no_setuptools=False, no_pip=False, no_wheel=False, symlink=True): """ Creates a ne...
[ "def", "create_environment", "(", "home_dir", ",", "site_packages", "=", "False", ",", "clear", "=", "False", ",", "unzip_setuptools", "=", "False", ",", "prompt", "=", "None", ",", "search_dirs", "=", "None", ",", "download", "=", "False", ",", "no_setuptoo...
28.113636
0.000781
def process(filename=None, url=None, key=None): """ Yeilds DOE CODE records based on provided input sources param: filename (str): Path to a DOE CODE .json file url (str): URL for a DOE CODE server json file key (str): API Key for connecting to DOE CODE server """ if filena...
[ "def", "process", "(", "filename", "=", "None", ",", "url", "=", "None", ",", "key", "=", "None", ")", ":", "if", "filename", "is", "not", "None", ":", "yield", "from", "process_json", "(", "filename", ")", "elif", "url", "and", "key", ":", "yield", ...
30.5
0.002273
def publish(self, channel_id): """ publish: publishes tree to Kolibri Args: channel_id (str): channel's id on Kolibri Studio Returns: None """ payload = { "channel_id":channel_id, } response = config.SESSION.post(config.publish_...
[ "def", "publish", "(", "self", ",", "channel_id", ")", ":", "payload", "=", "{", "\"channel_id\"", ":", "channel_id", ",", "}", "response", "=", "config", ".", "SESSION", ".", "post", "(", "config", ".", "publish_channel_url", "(", ")", ",", "data", "=",...
35.090909
0.010101
def topic_offsets_for_timestamp(consumer, timestamp, topics): """Given an initialized KafkaConsumer, timestamp, and list of topics, looks up the offsets for the given topics by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given ...
[ "def", "topic_offsets_for_timestamp", "(", "consumer", ",", "timestamp", ",", "topics", ")", ":", "tp_timestamps", "=", "{", "}", "for", "topic", "in", "topics", ":", "topic_partitions", "=", "consumer_partitions_for_topic", "(", "consumer", ",", "topic", ")", "...
51.645161
0.001226
def salsa20_8(B, x, src, s_start, dest, d_start): """Salsa20/8 http://en.wikipedia.org/wiki/Salsa20""" # Merged blockxor for speed for i in xrange(16): x[i] = B[i] = B[i] ^ src[s_start + i] # This is the actual Salsa 20/8: four identical double rounds for i in xrange(4): R(x, 4, 0,...
[ "def", "salsa20_8", "(", "B", ",", "x", ",", "src", ",", "s_start", ",", "dest", ",", "d_start", ")", ":", "# Merged blockxor for speed", "for", "i", "in", "xrange", "(", "16", ")", ":", "x", "[", "i", "]", "=", "B", "[", "i", "]", "=", "B", "[...
49.590909
0.090827
def dollarfy(x): """Replaces Math elements in element list 'x' with a $-enclosed string. stringify() passes through TeX math. Use dollarfy(x) first to replace Math elements with math strings set in dollars. 'x' should be a deep copy so that the underlying document is left untouched. Returns 'x'....
[ "def", "dollarfy", "(", "x", ")", ":", "def", "_dollarfy", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "# pylint: disable=unused-argument", "\"\"\"Replaces Math elements\"\"\"", "if", "key", "==", "'Math'", ":", "return", "Str", "(", "'$'", ...
34.5625
0.001761
def clean_url(url): """ Remove params, query and fragment parts from URL so that `os.path.basename` and `os.path.splitext` can work correctly. @param url: URL to clean. @type url: str @return: Cleaned URL. @rtype: str """ parsed = urlparse(url.strip()) reconstructed = ParseResu...
[ "def", "clean_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ".", "strip", "(", ")", ")", "reconstructed", "=", "ParseResult", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "parsed", ".", "path", ",", "params", ...
27.1875
0.002222
def run_steps_from_string(self, spec, language_name='en'): """ Called from within step definitions to run other steps. """ caller = inspect.currentframe().f_back line = caller.f_lineno - 1 fname = caller.f_code.co_filename steps = parse_steps(spec, fname, line, ...
[ "def", "run_steps_from_string", "(", "self", ",", "spec", ",", "language_name", "=", "'en'", ")", ":", "caller", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", "line", "=", "caller", ".", "f_lineno", "-", "1", "fname", "=", "caller", ".", ...
39.3
0.00995
def angledependentairtransmission(twotheta, mu_air, sampletodetectordistance): """Correction for the angle dependent absorption of air in the scattered beam path. Inputs: twotheta: matrix of two-theta values mu_air: the linear absorption coefficient of air sampletodetect...
[ "def", "angledependentairtransmission", "(", "twotheta", ",", "mu_air", ",", "sampletodetectordistance", ")", ":", "return", "np", ".", "exp", "(", "mu_air", "*", "sampletodetectordistance", "/", "np", ".", "cos", "(", "twotheta", ")", ")" ]
42.357143
0.00165
def get_download_link(cookie, tokens, path): '''在下载之前, 要先获取最终的下载链接. path - 一个文件的绝对路径. @return red_url, red_url 是重定向后的URL, 如果获取失败, 就返回原来的dlink; ''' metas = get_metas(cookie, tokens, path) if (not metas or metas.get('errno', -1) != 0 or 'info' not in metas or len(metas['i...
[ "def", "get_download_link", "(", "cookie", ",", "tokens", ",", "path", ")", ":", "metas", "=", "get_metas", "(", "cookie", ",", "tokens", ",", "path", ")", "if", "(", "not", "metas", "or", "metas", ".", "get", "(", "'errno'", ",", "-", "1", ")", "!...
32.608696
0.001295
def fibo(max_value=None): """Generator for fibonaccial decay. Args: max_value: The maximum value to yield. Once the value in the true fibonacci sequence exceeds this, the value of max_value will forever after be yielded. """ a = 1 b = 1 while True: if m...
[ "def", "fibo", "(", "max_value", "=", "None", ")", ":", "a", "=", "1", "b", "=", "1", "while", "True", ":", "if", "max_value", "is", "None", "or", "a", "<", "max_value", ":", "yield", "a", "a", ",", "b", "=", "b", ",", "a", "+", "b", "else", ...
26.8125
0.002252
def clone(self): """Return a cloned (deep) copy of self.""" return Leaf(self.type, self.value, (self.prefix, (self.lineno, self.column)), fixers_applied=self.fixers_applied)
[ "def", "clone", "(", "self", ")", ":", "return", "Leaf", "(", "self", ".", "type", ",", "self", ".", "value", ",", "(", "self", ".", "prefix", ",", "(", "self", ".", "lineno", ",", "self", ".", "column", ")", ")", ",", "fixers_applied", "=", "sel...
45
0.008734
def ngrams(path, elem, ignore_hash=True): """ Yields N-grams from a JSTOR DfR dataset. Parameters ---------- path : string Path to unzipped JSTOR DfR folder containing N-grams. elem : string Name of subdirectory containing N-grams. (e.g. 'bigrams'). ignore_hash : bool ...
[ "def", "ngrams", "(", "path", ",", "elem", ",", "ignore_hash", "=", "True", ")", ":", "grams", "=", "GramGenerator", "(", "path", ",", "elem", ",", "ignore_hash", "=", "ignore_hash", ")", "return", "FeatureSet", "(", "{", "k", ":", "Feature", "(", "f",...
26.714286
0.001721
def process_login(context, request): """Authenticate username and password and log in user""" username = request.json['username'] password = request.json['password'] # Do the password validation. user = context.authenticate(username, password) if not user: @request.after def adj...
[ "def", "process_login", "(", "context", ",", "request", ")", ":", "username", "=", "request", ".", "json", "[", "'username'", "]", "password", "=", "request", ".", "json", "[", "'password'", "]", "# Do the password validation.", "user", "=", "context", ".", ...
30.6
0.001056
def _update_keymap(self, first_keycode, count): """Internal function, called to refresh the keymap cache. """ # Delete all sym->code maps for the changed codes lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items(): i = 0 while i...
[ "def", "_update_keymap", "(", "self", ",", "first_keycode", ",", "count", ")", ":", "# Delete all sym->code maps for the changed codes", "lastcode", "=", "first_keycode", "+", "count", "for", "keysym", ",", "codes", "in", "self", ".", "_keymap_syms", ".", "items", ...
33.297297
0.001577
def files_to_image_frame(cls, url, sc, class_num, partition_num=-1, bigdl_type="float"): """ Extract hadoop sequence files from an HDFS path as ImageFrame ...
[ "def", "files_to_image_frame", "(", "cls", ",", "url", ",", "sc", ",", "class_num", ",", "partition_num", "=", "-", "1", ",", "bigdl_type", "=", "\"float\"", ")", ":", "jvalue", "=", "callBigDlFunc", "(", "bigdl_type", ",", "\"seqFilesToImageFrame\"", ",", "...
41.6
0.009401
def _compute_permanent_id(private_key): """ Internal helper. Return an authenticated service's permanent ID given an RSA private key object. The permanent ID is the base32 encoding of the SHA1 hash of the first 10 bytes (80 bits) of the public key. """ pub = private_key.public_key() p =...
[ "def", "_compute_permanent_id", "(", "private_key", ")", ":", "pub", "=", "private_key", ".", "public_key", "(", ")", "p", "=", "pub", ".", "public_bytes", "(", "encoding", "=", "serialization", ".", "Encoding", ".", "PEM", ",", "format", "=", "serialization...
34.526316
0.001484
def reset(self): """ Resets the agent to its initial state (e.g. on experiment start). Updates the Model's internal episode and time step counter, internal states, and resets preprocessors. """ self.episode, self.timestep, self.next_internals = self.model.reset() self.cur...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "episode", ",", "self", ".", "timestep", ",", "self", ".", "next_internals", "=", "self", ".", "model", ".", "reset", "(", ")", "self", ".", "current_internals", "=", "self", ".", "next_internals" ]
50
0.008427
def close(self): """Closes the underlying database file.""" if hasattr(self.db, 'close'): with self.write_mutex: self.db.close()
[ "def", "close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "db", ",", "'close'", ")", ":", "with", "self", ".", "write_mutex", ":", "self", ".", "db", ".", "close", "(", ")" ]
33.6
0.011628
def allocate_sync_ensembles(self): """! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @return (list) Grours (lists) of indexes of synchronous oscillators. ...
[ "def", "allocate_sync_ensembles", "(", "self", ")", ":", "if", "self", ".", "__ccore_pcnn_dynamic_pointer", "is", "not", "None", ":", "return", "wrapper", ".", "pcnn_dynamic_allocate_sync_ensembles", "(", "self", ".", "__ccore_pcnn_dynamic_pointer", ")", "sync_ensembles...
40.933333
0.011138
def dim_dtau(self, pars): r""" :math:`\frac{\partial \hat{\rho''}(\omega)}{\partial \tau} = \rho_0 \frac{-m \omega^c c \tau^{c-1} sin(\frac{c \pi}{2} }{1 + 2 (\omega \tau)^c cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho_0 \frac{\left[-m (\omega \tau)^c sin(\frac{c \pi}{2} ...
[ "def", "dim_dtau", "(", "self", ",", "pars", ")", ":", "self", ".", "_set_parameters", "(", "pars", ")", "# term1", "nom1", "=", "-", "self", ".", "m", "*", "np", ".", "sin", "(", "self", ".", "ang", ")", "*", "self", ".", "w", "**", "self", "....
42.076923
0.001787
def handle_items(repo, **kwargs): """:return: repo.files()""" log.info('items: %s %s' %(repo, kwargs)) if not hasattr(repo, 'items'): return [] return [i.serialize() for i in repo.items(**kwargs)]
[ "def", "handle_items", "(", "repo", ",", "*", "*", "kwargs", ")", ":", "log", ".", "info", "(", "'items: %s %s'", "%", "(", "repo", ",", "kwargs", ")", ")", "if", "not", "hasattr", "(", "repo", ",", "'items'", ")", ":", "return", "[", "]", "return"...
35.833333
0.009091
def _busy_wait_ms(self, ms): """Busy wait for the specified number of milliseconds.""" start = time.time() delta = ms/1000.0 while (time.time() - start) <= delta: pass
[ "def", "_busy_wait_ms", "(", "self", ",", "ms", ")", ":", "start", "=", "time", ".", "time", "(", ")", "delta", "=", "ms", "/", "1000.0", "while", "(", "time", ".", "time", "(", ")", "-", "start", ")", "<=", "delta", ":", "pass" ]
34.333333
0.009479
def wait_for_tasks(self, raise_if_error=True): """ Wait for the running tasks lauched from the sessions. Note that it also wait for tasks that are started from other tasks callbacks, like on_finished. :param raise_if_error: if True, raise all possible encountered er...
[ "def", "wait_for_tasks", "(", "self", ",", "raise_if_error", "=", "True", ")", ":", "errors", "=", "[", "]", "tasks_seen", "=", "TaskCache", "(", ")", "while", "True", ":", "for", "session", "in", "self", ".", "values", "(", ")", ":", "errs", "=", "s...
38.714286
0.0018
def run(self): """Load all artists into the database """ df = ArtistsInputData().load() # get base model instances, merge ID column via the unique wiki ID # (base and derived model instances must have the same ID values) base_data = self.client.df_query(self.session.que...
[ "def", "run", "(", "self", ")", ":", "df", "=", "ArtistsInputData", "(", ")", ".", "load", "(", ")", "# get base model instances, merge ID column via the unique wiki ID", "# (base and derived model instances must have the same ID values)", "base_data", "=", "self", ".", "cl...
31.818182
0.001848
def list_rows( self, table, selected_fields=None, max_results=None, page_token=None, start_index=None, page_size=None, retry=DEFAULT_RETRY, ): """List the rows of the table. See https://cloud.google.com/bigquery/docs/reference/...
[ "def", "list_rows", "(", "self", ",", "table", ",", "selected_fields", "=", "None", ",", "max_results", "=", "None", ",", "page_token", "=", "None", ",", "start_index", "=", "None", ",", "page_size", "=", "None", ",", "retry", "=", "DEFAULT_RETRY", ",", ...
41.087379
0.000923
def getExponentialFormatPrecision(self, result=None): """ Returns the precision for the Analysis Service and result provided. Results with a precision value above this exponential format precision should be formatted as scientific notation. If the Calculate Precision according to Uncert...
[ "def", "getExponentialFormatPrecision", "(", "self", ",", "result", "=", "None", ")", ":", "if", "not", "result", "or", "self", ".", "getPrecisionFromUncertainty", "(", ")", "is", "False", ":", "return", "self", ".", "_getExponentialFormatPrecision", "(", ")", ...
43.333333
0.00094
def extend_settings(self, data_id, files, secrets): """Extend the settings the manager will serialize. :param data_id: The :class:`~resolwe.flow.models.Data` object id being prepared for. :param files: The settings dictionary to be serialized. Keys are filenames, values ...
[ "def", "extend_settings", "(", "self", ",", "data_id", ",", "files", ",", "secrets", ")", ":", "data", "=", "Data", ".", "objects", ".", "select_related", "(", "'process'", ")", ".", "get", "(", "pk", "=", "data_id", ")", "files", "[", "ExecutorFiles", ...
52.185185
0.002091
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
[ "def", "_log_joint", "(", "current_target_log_prob", ",", "current_momentum", ")", ":", "momentum_log_prob", "=", "-", "sum", "(", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "0.5", "*", "(", "m", "**", "2.", ")", ")", "for", "m", "in", "curr...
57.6
0.013699
def unfold(self, mode): """ Unfolds a dense tensor in mode n. Parameters ---------- mode : int Mode in which tensor is unfolded Returns ------- unfolded_dtensor : unfolded_dtensor object Tensor unfolded along mode Example...
[ "def", "unfold", "(", "self", ",", "mode", ")", ":", "sz", "=", "array", "(", "self", ".", "shape", ")", "N", "=", "len", "(", "sz", ")", "order", "=", "(", "[", "mode", "]", ",", "from_to_without", "(", "N", "-", "1", ",", "-", "1", ",", "...
33.916667
0.002388
def shadowUpdate(self, srcJSONPayload, srcCallback, srcTimeout): """ **Description** Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive res...
[ "def", "shadowUpdate", "(", "self", ",", "srcJSONPayload", ",", "srcCallback", ",", "srcTimeout", ")", ":", "# Validate JSON", "self", ".", "_basicJSONParserHandler", ".", "setString", "(", "srcJSONPayload", ")", "if", "self", ".", "_basicJSONParserHandler", ".", ...
52.491525
0.009192
def get_api_gateway_resource(name): """Get the resource associated with our gateway.""" client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resources = clie...
[ "def", "get_api_gateway_resource", "(", "name", ")", ":", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "x", "in", "client", ".", "get_rest_apis", "(", ")", ".",...
41.923077
0.001795
def sumlogs(x, axis=None, out=None): """Sum of vector where numbers are represented by their logarithms. Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that it works even when elements have large magnitude. """ maxx = x.max(axis=axis, keepdims=True) xnorm = x - maxx ...
[ "def", "sumlogs", "(", "x", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "maxx", "=", "x", ".", "max", "(", "axis", "=", "axis", ",", "keepdims", "=", "True", ")", "xnorm", "=", "x", "-", "maxx", "np", ".", "exp", "(", "xnorm"...
30.352941
0.00188
def _check_item_type(item, field_name, allowed_types, expect_list=False, required_channels='all'): """ Check the item's type against a set of allowed types. Vary the print message regarding whether the item can be None. Helper to `BaseRecord.check_field`. Parameters --------...
[ "def", "_check_item_type", "(", "item", ",", "field_name", ",", "allowed_types", ",", "expect_list", "=", "False", ",", "required_channels", "=", "'all'", ")", ":", "if", "expect_list", ":", "if", "not", "isinstance", "(", "item", ",", "list", ")", ":", "r...
37.5
0.001499
def get_version( here_path, default_version=DEFAULT_VERSION, ): """tries to resolve version number Args: here_path (str): path to project local dir default_version (str): what version to return if all else fails Returns: str: semantic_version information for library...
[ "def", "get_version", "(", "here_path", ",", "default_version", "=", "DEFAULT_VERSION", ",", ")", ":", "if", "'site-packages'", "in", "here_path", ":", "# Running as dependency", "return", "_version_from_file", "(", "here_path", ")", "if", "os", ".", "environ", "....
30.2
0.000802
def heritability(args): """ %prog pg.tsv MZ-twins.csv DZ-twins.csv Plot composite figures ABCD on absolute difference of 4 traits, EFGH on heritability of 4 traits. The 4 traits are: telomere length, ccn.chrX, ccn.chrY, TRA.PPM """ p = OptionParser(heritability.__doc__) opts, args, iopt...
[ "def", "heritability", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "heritability", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"12x18\"", ")", "if", "len", "(...
31.702703
0.000827
def create_index(modules): '''This takes a dict of modules and created the RST index file.''' for key in modules.keys(): file_path = join(HERE, '%s_modules/_list_of_modules.rst' % key) list_file = open(file_path, 'w') # Write the generic header list_file.write('%s\n' % AUTOGEN) ...
[ "def", "create_index", "(", "modules", ")", ":", "for", "key", "in", "modules", ".", "keys", "(", ")", ":", "file_path", "=", "join", "(", "HERE", ",", "'%s_modules/_list_of_modules.rst'", "%", "key", ")", "list_file", "=", "open", "(", "file_path", ",", ...
37.25
0.001637
def bc2pg(dataset, db_url, table, schema, query, append, pagesize, sortby, max_workers): """Download a DataBC WFS layer to postgres - an ogr2ogr wrapper. \b $ bcdata bc2pg bc-airports --db_url postgresql://postgres:postgres@localhost:5432/postgis The default target database can be specified by sett...
[ "def", "bc2pg", "(", "dataset", ",", "db_url", ",", "table", ",", "schema", ",", "query", ",", "append", ",", "pagesize", ",", "sortby", ",", "max_workers", ")", ":", "src", "=", "bcdata", ".", "validate_name", "(", "dataset", ")", "src_schema", ",", "...
33.969697
0.001156
def simple_peakfinder(x, y, delta): '''Detect local maxima and minima in a vector A point is considered a maximum peak if it has the maximal value, and was preceded (to the left) by a value lower by `delta`. Args ---- y: ndarray array of values to find local maxima and minima in de...
[ "def", "simple_peakfinder", "(", "x", ",", "y", ",", "delta", ")", ":", "import", "numpy", "y", "=", "numpy", ".", "asarray", "(", "y", ")", "max_ind", "=", "list", "(", ")", "min_ind", "=", "list", "(", ")", "local_min", "=", "numpy", ".", "inf", ...
25.675676
0.001521
def opened(self): """Send the connect message to the server.""" # give up if there are no more ddp versions to try if self._ddp_version_index == len(DDP_VERSIONS): self.ddpsocket._debug_log('* DDP VERSION MISMATCH') self.emit('version_mismatch', DDP_VERSIONS) ...
[ "def", "opened", "(", "self", ")", ":", "# give up if there are no more ddp versions to try", "if", "self", ".", "_ddp_version_index", "==", "len", "(", "DDP_VERSIONS", ")", ":", "self", ".", "ddpsocket", ".", "_debug_log", "(", "'* DDP VERSION MISMATCH'", ")", "sel...
37.541667
0.002165
def extract_features(self, data_frame, pre=''): """ This method extracts all the features available to the Tremor Processor class. :param data_frame: the data frame :type data_frame: pandas.DataFrame :return: amplitude_by_fft, frequency_by_fft, amplitude_by_welch...
[ "def", "extract_features", "(", "self", ",", "data_frame", ",", "pre", "=", "''", ")", ":", "try", ":", "magnitude_partial_autocorrelation", "=", "self", ".", "partial_autocorrelation", "(", "data_frame", ".", "mag_sum_acc", ")", "magnitude_agg_linear", "=", "self...
83.434783
0.00927
def ROCCurve(y_true, y_score): """compute Receiver operating characteristic (ROC) Note: this implementation is restricted to the binary classification task. Parameters ---------- y_true : array, shape = [n_samples] true binary labels y_score : array, shape = [n_samples] targe...
[ "def", "ROCCurve", "(", "y_true", ",", "y_score", ")", ":", "y_true", "=", "np", ".", "ravel", "(", "y_true", ")", "classes", "=", "np", ".", "unique", "(", "y_true", ")", "# ROC only for binary classification", "if", "classes", ".", "shape", "[", "0", "...
30.734043
0.000335
def freeze_of_gait(self, x): """ This method assess freeze of gait following :cite:`g-BachlinPRMHGT10`. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :return freeze_time: What times do freeze ...
[ "def", "freeze_of_gait", "(", "self", ",", "x", ")", ":", "data", "=", "self", ".", "resample_signal", "(", "x", ")", ".", "values", "f_res", "=", "self", ".", "sampling_frequency", "/", "self", ".", "window", "f_nr_LBs", "=", "int", "(", "self", ".", ...
39.785714
0.008322
def format_problems( problems: List, *, as_df: bool = False ) -> Union[List, DataFrame]: """ Format the given problems list as a DataFrame. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ...
[ "def", "format_problems", "(", "problems", ":", "List", ",", "*", ",", "as_df", ":", "bool", "=", "False", ")", "->", "Union", "[", "List", ",", "DataFrame", "]", ":", "if", "as_df", ":", "problems", "=", "pd", ".", "DataFrame", "(", "problems", ",",...
30.194444
0.000891
def visit_binop(self, node): """ Called when if a binary operation is found. Only check for string formatting operations. @param node: currently checking node """ if node.op != "%": return pattern = node.left.as_string() # If the pattern's not...
[ "def", "visit_binop", "(", "self", ",", "node", ")", ":", "if", "node", ".", "op", "!=", "\"%\"", ":", "return", "pattern", "=", "node", ".", "left", ".", "as_string", "(", ")", "# If the pattern's not a constant string, we don't know whether a", "# dictionary or ...
36.434783
0.002326
def get_config(): ''' Get the status of all the firewall profiles Returns: dict: A dictionary of all profiles on the system Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_config ''' profiles = {} ...
[ "def", "get_config", "(", ")", ":", "profiles", "=", "{", "}", "curr", "=", "None", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'show'", ",", "'allprofiles'", "]", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_...
28.486486
0.001835
def sort_topologically(graph): """ Stackless topological sorting. graph = { 3: [1], 5: [3], 4: [2], 6: [4], } sort_topologically(graph) [[1, 2], [3, 4], [5, 6]] """ levels_by_name = {} names_by_level = defaultdict(list) def add_level_to_name(nam...
[ "def", "sort_topologically", "(", "graph", ")", ":", "levels_by_name", "=", "{", "}", "names_by_level", "=", "defaultdict", "(", "list", ")", "def", "add_level_to_name", "(", "name", ",", "level", ")", ":", "levels_by_name", "[", "name", "]", "=", "level", ...
26.313725
0.002155
def rsq_adj(self): """Adjusted R-squared.""" n = self.n k = self.k return 1.0 - ((1.0 - self.rsq) * (n - 1.0) / (n - k - 1.0))
[ "def", "rsq_adj", "(", "self", ")", ":", "n", "=", "self", ".", "n", "k", "=", "self", ".", "k", "return", "1.0", "-", "(", "(", "1.0", "-", "self", ".", "rsq", ")", "*", "(", "n", "-", "1.0", ")", "/", "(", "n", "-", "k", "-", "1.0", "...
31.6
0.012346
def render_activity(activity, grouped_activity=None, *args, **kwargs): """ Given an activity, will attempt to render the matching template snippet for that activity's content object or will return a simple representation of the activity. Also takes an optional 'grouped_activity' argument that would...
[ "def", "render_activity", "(", "activity", ",", "grouped_activity", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "template_name", "=", "'activity_monitor/includes/models/{0.app_label}_{0.model}.html'", ".", "format", "(", "activity", ".", "conte...
40.047619
0.002323
def prove(self, file, challenge, tag): """Returns a proof of ownership of the given file based on the challenge. The proof consists of a hash of the specified file chunk and the complete merkle branch. :param file: a file that supports `read()`, `seek()` and `tell()` :param cha...
[ "def", "prove", "(", "self", ",", "file", ",", "challenge", ",", "tag", ")", ":", "leaf", "=", "MerkleLeaf", "(", "challenge", ".", "index", ",", "MerkleHelper", ".", "get_chunk_hash", "(", "file", ",", "challenge", ".", "seed", ",", "filesz", "=", "ta...
56.647059
0.002043
def show(i): """ Input: { (the same as list; can use wildcards) } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ o=...
[ "def", "show", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "of", "=", "i", ".", "get", "(", "'out_file'", ",", "''", ")", "if", "of", "!=", "''", ":", "xof", "=", "os", ".", "path", ".", "splitext", "(", "...
27.418919
0.045181
def get_child_bins(self, bin_id): """Gets the children of the given bin. arg: bin_id (osid.id.Id): the ``Id`` to query return: (osid.resource.BinList) - the children of the bin raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ``null`` raise...
[ "def", "get_child_bins", "(", "self", ",", "bin_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.get_child_bins", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ".", "get_...
43.3
0.00226
def authorize(self, login, password, scopes=None, note='', note_url='', client_id='', client_secret=''): """Obtain an authorization token from the GitHub API for the GitHub API. :param str login: (required) :param str password: (required) :param list scopes: (o...
[ "def", "authorize", "(", "self", ",", "login", ",", "password", ",", "scopes", "=", "None", ",", "note", "=", "''", ",", "note_url", "=", "''", ",", "client_id", "=", "''", ",", "client_secret", "=", "''", ")", ":", "json", "=", "None", "# TODO: Brea...
41.944444
0.001942
def _print_layers(targets, components, tasks): """ Print dependency information, grouping components based on their position in the dependency graph. Components with no dependnecies will be in layer 0, components that only depend on layer 0 will be in layer 1, and so on. If there's a circular depe...
[ "def", "_print_layers", "(", "targets", ",", "components", ",", "tasks", ")", ":", "layer", "=", "0", "expected_count", "=", "len", "(", "tasks", ")", "counts", "=", "{", "}", "def", "_add_layer", "(", "resolved", ",", "dep_fn", ")", ":", "nonlocal", "...
36.756098
0.000646
def get_baremetal_physnet(self, context): """Returns dictionary which contains mac to hostname mapping""" port = context.current host_id = context.host cmd = ['show network physical-topology hosts'] try: response = self._run_eos_cmds(cmd) binding_profile =...
[ "def", "get_baremetal_physnet", "(", "self", ",", "context", ")", ":", "port", "=", "context", ".", "current", "host_id", "=", "context", ".", "host", "cmd", "=", "[", "'show network physical-topology hosts'", "]", "try", ":", "response", "=", "self", ".", "...
49.166667
0.001663
def mann_whitney_u(sample1, sample2, use_continuity=True): """ Computes the Mann-Whitney rank test on both samples. Each sample is expected to be of the form:: {1: 5, 2: 20, 3: 12, ...} Returns a named tuple with: ``u`` equal to min(U for sample1, U for sample2), and ``p`` equ...
[ "def", "mann_whitney_u", "(", "sample1", ",", "sample2", ",", "use_continuity", "=", "True", ")", ":", "# Merge dictionaries, adding values if keys match.", "sample", "=", "sample1", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "sample2", ".", "items", "...
30.763158
0.000829
def fg_box_logits(self): """ Returns: #fg x ? x 4 """ return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits')
[ "def", "fg_box_logits", "(", "self", ")", ":", "return", "tf", ".", "gather", "(", "self", ".", "box_logits", ",", "self", ".", "proposals", ".", "fg_inds", "(", ")", ",", "name", "=", "'fg_box_logits'", ")" ]
49.666667
0.019868
def query_geonames_country(self, placename, country): """ Like query_geonames, but this time limited to a specified country. """ # first, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alter...
[ "def", "query_geonames_country", "(", "self", ",", "placename", ",", "country", ")", ":", "# first, try for an exact phrase match", "q", "=", "{", "\"multi_match\"", ":", "{", "\"query\"", ":", "placename", ",", "\"fields\"", ":", "[", "'name^5'", ",", "'asciiname...
53.380952
0.008764
def take_node_screenshot(self, element, screenshot_path): from PIL import Image """Take a screenshot of a node Args: element (object): the proxy_element screenshot_path (str): the path where the screenshot will be saved """ temp_path = os.path.join(tempd...
[ "def", "take_node_screenshot", "(", "self", ",", "element", ",", "screenshot_path", ")", ":", "from", "PIL", "import", "Image", "temp_path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "screenshot_path", ")", "el_x", "=", "int", "(", "element...
27.6
0.002333
def complete(self): """ When *local_workflow_require_branches* of the task was set to *True*, returns whether the :py:meth:`run` method has been called before. Otherwise, the call is forwarded to the super class. """ if self.task.local_workflow_require_branches: ...
[ "def", "complete", "(", "self", ")", ":", "if", "self", ".", "task", ".", "local_workflow_require_branches", ":", "return", "self", ".", "_has_run", "else", ":", "return", "super", "(", "LocalWorkflowProxy", ",", "self", ")", ".", "complete", "(", ")" ]
41
0.009547
def get(self, oid, host, port, community): """ Perform SNMP get for a given OID """ # Initialize return value ret = {} # Convert OID to tuple if necessary if not isinstance(oid, tuple): oid = self._convert_to_oid(oid) # Convert Host to IP if ...
[ "def", "get", "(", "self", ",", "oid", ",", "host", ",", "port", ",", "community", ")", ":", "# Initialize return value", "ret", "=", "{", "}", "# Convert OID to tuple if necessary", "if", "not", "isinstance", "(", "oid", ",", "tuple", ")", ":", "oid", "="...
27.142857
0.002033
def armor(type_name, der_bytes, headers=None): """ Armors a DER-encoded byte string in PEM :param type_name: A unicode string that will be capitalized and placed in the header and footer of the block. E.g. "CERTIFICATE", "PRIVATE KEY", etc. This will appear as "-----BEGIN CERTIFICAT...
[ "def", "armor", "(", "type_name", ",", "der_bytes", ",", "headers", "=", "None", ")", ":", "if", "not", "isinstance", "(", "der_bytes", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "unwrap", "(", "'''\n der_bytes must be a byte string, not %s\n...
27.333333
0.000589
def group_re(self): ''' Return a regexp pattern with named groups ''' out = '' for token, data in self.tokens(): if token == 'TXT': out += re.escape(data) elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0]) elif token == 'ANON': out += '(?:%s)' %...
[ "def", "group_re", "(", "self", ")", ":", "out", "=", "''", "for", "token", ",", "data", "in", "self", ".", "tokens", "(", ")", ":", "if", "token", "==", "'TXT'", ":", "out", "+=", "re", ".", "escape", "(", "data", ")", "elif", "token", "==", "...
42.125
0.017442
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not funct...
[ "def", "set_day_time", "(", "self", ",", "hour", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "DayTimeCommand", "(", "hour", "%", "24", ")", "self", ".", "_commands", ".", "add_command", "(", "command_to_send", ...
55.636364
0.008039
def _buildFileUrl(self, xml_req): """Builds url for fetching the files from FM.""" return '%(protocol)s://%(host)s:%(port)s%(xml_req)s'%{ 'protocol': self._protocol, 'host': self._host, 'port': self._port, 'xml_req': xml_req, }
[ "def", "_buildFileUrl", "(", "self", ",", "xml_req", ")", ":", "return", "'%(protocol)s://%(host)s:%(port)s%(xml_req)s'", "%", "{", "'protocol'", ":", "self", ".", "_protocol", ",", "'host'", ":", "self", ".", "_host", ",", "'port'", ":", "self", ".", "_port",...
29.75
0.040816
def operator_si(u): """operator_si operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
[ "def", "operator_si", "(", "u", ")", ":", "global", "_aux", "if", "np", ".", "ndim", "(", "u", ")", "==", "2", ":", "P", "=", "_P2", "elif", "np", ".", "ndim", "(", "u", ")", "==", "3", ":", "P", "=", "_P3", "else", ":", "raise", "ValueError"...
25.111111
0.008529
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
[ "def", "evaluate", "(", "data_loader", ")", ":", "translation_out", "=", "[", "]", "all_inst_ids", "=", "[", "]", "avg_loss_denom", "=", "0", "avg_loss", "=", "0.0", "for", "_", ",", "(", "src_seq", ",", "tgt_seq", ",", "src_valid_length", ",", "tgt_valid_...
40.318182
0.002201
def auth_creds(cls, username, password): """ Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it. :return: string token """ store...
[ "def", "auth_creds", "(", "cls", ",", "username", ",", "password", ")", ":", "store", "=", "goldman", ".", "sess", ".", "store", "login", "=", "store", ".", "find", "(", "cls", ".", "RTYPE", ",", "'username'", ",", "username", ")", "if", "not", "logi...
37.444444
0.001929
def addSummaryMetrics(self, dict_to_plot): """ Take the parsed stats from the DamageProfiler and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['std'] = { 'title': 'Read length std. dev.', 'description': 'Read length...
[ "def", "addSummaryMetrics", "(", "self", ",", "dict_to_plot", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'std'", "]", "=", "{", "'title'", ":", "'Read length std. dev.'", ",", "'description'", ":", "'Read length std. dev.'", ",", "'suffi...
31.057143
0.001784
def class_case(string): """ Converts a string to class case. For example:: class_case('one_two_three') -> 'OneTwoThree' """ if not string: return string string = string.replace(' ', '_').replace('-', '_') parts = de_camel(string, '_', _lowercase=False).split('_') rv = '' ...
[ "def", "class_case", "(", "string", ")", ":", "if", "not", "string", ":", "return", "string", "string", "=", "string", ".", "replace", "(", "' '", ",", "'_'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", "parts", "=", "de_camel", "(", "string", ...
29.111111
0.001848
def get_base_url(html: str) -> str: """ Search for login url from VK login page """ forms = BeautifulSoup(html, 'html.parser').find_all('form') if not forms: raise VVKBaseUrlException('Form for login not found') elif len(forms) > 1: raise VVKBaseUrlException('More than one login ...
[ "def", "get_base_url", "(", "html", ":", "str", ")", "->", "str", ":", "forms", "=", "BeautifulSoup", "(", "html", ",", "'html.parser'", ")", ".", "find_all", "(", "'form'", ")", "if", "not", "forms", ":", "raise", "VVKBaseUrlException", "(", "'Form for lo...
35.461538
0.002114
def hash_data(data, hashlen=None, alphabet=None): r""" Get a unique hash depending on the state of the data. Args: data (object): any sort of loosely organized data hashlen (None): (default = None) alphabet (None): (default = None) Returns: str: text - hash string ...
[ "def", "hash_data", "(", "data", ",", "hashlen", "=", "None", ",", "alphabet", "=", "None", ")", ":", "if", "alphabet", "is", "None", ":", "alphabet", "=", "ALPHABET_27", "if", "hashlen", "is", "None", ":", "hashlen", "=", "HASH_LEN2", "if", "isinstance"...
36.04918
0.000885
def delete_dimension(dimension_id,**kwargs): """ Delete a dimension from the DB. Raises and exception if the dimension does not exist """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.id==dimension_id).one() db.DBSession.query(Unit).filter(Unit.dimension_id==dimens...
[ "def", "delete_dimension", "(", "dimension_id", ",", "*", "*", "kwargs", ")", ":", "try", ":", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", ".", "filter", "(", "Dimension", ".", "id", "==", "dimension_id", ")", ".", "o...
38.214286
0.016423
def describe_log_group(awsclient, log_group_name): """Get info on the specified log group :param log_group_name: log group name :return: """ client_logs = awsclient.get_client('logs') request = { 'logGroupNamePrefix': log_group_name, 'limit': 1 } response = client_logs....
[ "def", "describe_log_group", "(", "awsclient", ",", "log_group_name", ")", ":", "client_logs", "=", "awsclient", ".", "get_client", "(", "'logs'", ")", "request", "=", "{", "'logGroupNamePrefix'", ":", "log_group_name", ",", "'limit'", ":", "1", "}", "response",...
25.235294
0.002247
def com_google_fonts_check_metadata_menu_and_latin(family_metadata): """METADATA.pb should contain at least "menu" and "latin" subsets.""" missing = [] for s in ["menu", "latin"]: if s not in list(family_metadata.subsets): missing.append(s) if missing != []: yield FAIL, ("Subsets \"menu\" and \"l...
[ "def", "com_google_fonts_check_metadata_menu_and_latin", "(", "family_metadata", ")", ":", "missing", "=", "[", "]", "for", "s", "in", "[", "\"menu\"", ",", "\"latin\"", "]", ":", "if", "s", "not", "in", "list", "(", "family_metadata", ".", "subsets", ")", "...
39.538462
0.013308
def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self...
[ "def", "report", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_stack", ":", "self", ".", "stop", "(", "self", ".", "_stack", "[", "-", "1", "]", ")", "now", "=", "get_now_utc_pendulum", "(", ")", "grand_total", "=", "datetime", ".", ...
36.139535
0.001253
def removePixmap(self, pixmap): """ Removes the pixmap from this widgets list of pixmaps. :param pixmap | <QPixmap> """ scene = self.scene() for item in self.items(): if item.basePixmap() == pixmap: scene.removeItem(item)...
[ "def", "removePixmap", "(", "self", ",", "pixmap", ")", ":", "scene", "=", "self", ".", "scene", "(", ")", "for", "item", "in", "self", ".", "items", "(", ")", ":", "if", "item", ".", "basePixmap", "(", ")", "==", "pixmap", ":", "scene", ".", "re...
30.272727
0.008746
def retrieve_flags(flag_dict, flag_filter): """Read the flags from a dictionary and return them in a usable form. Will return a list of (flag, value) for all flags in "flag_dict" matching the filter "flag_filter". """ return [(f[0], f[1]) for f in flag_dict.items() if isinstanc...
[ "def", "retrieve_flags", "(", "flag_dict", ",", "flag_filter", ")", ":", "return", "[", "(", "f", "[", "0", "]", ",", "f", "[", "1", "]", ")", "for", "f", "in", "flag_dict", ".", "items", "(", ")", "if", "isinstance", "(", "f", "[", "0", "]", "...
39.777778
0.008197
def createBinaryRelation(self, m): """ Initialize a two-dimensional array of size m by m. :ivar int m: A value for m. """ binaryRelation = [] for i in range(m): binaryRelation.append(range(m)) binaryRelation[i][i] = 0 return binaryRel...
[ "def", "createBinaryRelation", "(", "self", ",", "m", ")", ":", "binaryRelation", "=", "[", "]", "for", "i", "in", "range", "(", "m", ")", ":", "binaryRelation", ".", "append", "(", "range", "(", "m", ")", ")", "binaryRelation", "[", "i", "]", "[", ...
26.166667
0.009231
def does_not_contain(*avoid_keys, error_cls=ValueError): """Decorator: value must not contain any of the :attr:`avoid_keys`. """ def decorator(func): def not_contains(instance, attribute, value): instance_name = instance.__class__.__name__ num_matched_keys = len(set(avoid_k...
[ "def", "does_not_contain", "(", "*", "avoid_keys", ",", "error_cls", "=", "ValueError", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "not_contains", "(", "instance", ",", "attribute", ",", "value", ")", ":", "instance_name", "=", "instance", ...
44.5
0.001
def do(cmdline, runas=None, env=None): ''' Execute a ruby command with rbenv's shims from the user or the system CLI Example: .. code-block:: bash salt '*' rbenv.do 'gem list bundler' salt '*' rbenv.do 'gem list bundler' deploy ''' if not cmdline: # This is a positiona...
[ "def", "do", "(", "cmdline", ",", "runas", "=", "None", ",", "env", "=", "None", ")", ":", "if", "not", "cmdline", ":", "# This is a positional argument so this should never happen, but this", "# will handle cases where someone explicitly passes a false value for", "# cmdline...
30.1875
0.001337
def read_out_tweets(processed_tweets, speech_convertor=None): """ Input - list of processed 'Tweets' output - list of spoken responses """ return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text) for index, (user, text) in enumerate(processed_tweets)]
[ "def", "read_out_tweets", "(", "processed_tweets", ",", "speech_convertor", "=", "None", ")", ":", "return", "[", "\"tweet number {num} by {user}. {text}.\"", ".", "format", "(", "num", "=", "index", "+", "1", ",", "user", "=", "user", ",", "text", "=", "text"...
44.714286
0.009404
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups)...
[ "def", "add_record", "(", "self", ",", "msg_id", ",", "rec", ")", ":", "d", "=", "self", ".", "_defaults", "(", ")", "d", ".", "update", "(", "rec", ")", "d", "[", "'msg_id'", "]", "=", "msg_id", "line", "=", "self", ".", "_dict_to_list", "(", "d...
40
0.012232
def parse_extend(self, c, i): """Parse extended pattern lists.""" # Start list parsing success = True index = i.index list_type = c try: c = next(i) if c != '(': raise StopIteration while c != ')': c = n...
[ "def", "parse_extend", "(", "self", ",", "c", ",", "i", ")", ":", "# Start list parsing", "success", "=", "True", "index", "=", "i", ".", "index", "list_type", "=", "c", "try", ":", "c", "=", "next", "(", "i", ")", "if", "c", "!=", "'('", ":", "r...
27
0.002043
def _conversations(group, delta=datetime.timedelta(hours=1)): """ Group texts into conversations. The function returns an iterator over records grouped by conversations. See :ref:`Using bandicoot <conversations-label>` for a definition of conversations. A conversation begins when one person se...
[ "def", "_conversations", "(", "group", ",", "delta", "=", "datetime", ".", "timedelta", "(", "hours", "=", "1", ")", ")", ":", "last_time", "=", "None", "results", "=", "[", "]", "for", "g", "in", "group", ":", "if", "last_time", "is", "None", "or", ...
27.461538
0.000902
def add_headers(self, header_name, value, *values): """ Add new header :param header_name: name of the header to add :param value: header value :param values: additional header values (in a result request/response must be concatenated by the coma \ or by the separate header string) :return: None """ if...
[ "def", "add_headers", "(", "self", ",", "header_name", ",", "value", ",", "*", "values", ")", ":", "if", "self", ".", "__ro_flag", ":", "raise", "RuntimeError", "(", "'ro'", ")", "header_name", "=", "self", ".", "normalize_name", "(", "header_name", ")", ...
32.578947
0.029827