text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def shorten_go_name_ptbl3(self, name, dcnt): """Shorten GO description for Table 3 in manuscript.""" if self._keep_this(name): return name name = name.replace("positive regulation of immune system process", "+ reg. of immune sys. process") name = n...
[ "def", "shorten_go_name_ptbl3", "(", "self", ",", "name", ",", "dcnt", ")", ":", "if", "self", ".", "_keep_this", "(", "name", ")", ":", "return", "name", "name", "=", "name", ".", "replace", "(", "\"positive regulation of immune system process\"", ",", "\"+ r...
53.16
20.48
def nlmsg_inherit(hdr=None): """Allocate a new Netlink message and inherit Netlink message header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L322 Allocates a new Netlink message and inherits the original message header. If `hdr` is not None it will be used as a template for the Netli...
[ "def", "nlmsg_inherit", "(", "hdr", "=", "None", ")", ":", "nm", "=", "nlmsg_alloc", "(", ")", "if", "hdr", ":", "new", "=", "nm", ".", "nm_nlh", "new", ".", "nlmsg_type", "=", "hdr", ".", "nlmsg_type", "new", ".", "nlmsg_flags", "=", "hdr", ".", "...
34.590909
23.318182
def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on node properties. See documentation for _OTIWrapper class.""" assert self.use_v1 return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix), query_d...
[ "def", "find_nodes", "(", "self", ",", "query_dict", "=", "None", ",", "exact", "=", "False", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "use_v1", "return", "self", ".", "_do_query", "(", "'{p}/singlePropertyS...
58.888889
17.555556
def move_by_offset(self, xoffset, yoffset): """ Moving the mouse to an offset from current mouse position. :Args: - xoffset: X offset to move to, as a positive or negative integer. - yoffset: Y offset to move to, as a positive or negative integer. """ if self._...
[ "def", "move_by_offset", "(", "self", ",", "xoffset", ",", "yoffset", ")", ":", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "pointer_action", ".", "move_by", "(", "xoffset", ",", "yoffset", ")", "self", ".", "w3c_actio...
38.647059
17.588235
def bulk_create_posts(self, posts, post_categories, post_tags, post_media_attachments): """ Actually do a db bulk creation of posts, and link up the many-to-many fields :param posts: the list of Post objects to bulk create :param post_categories: a mapping of Categories to add to newly ...
[ "def", "bulk_create_posts", "(", "self", ",", "posts", ",", "post_categories", ",", "post_tags", ",", "post_media_attachments", ")", ":", "Post", ".", "objects", ".", "bulk_create", "(", "posts", ")", "# attach many-to-ones", "for", "post_wp_id", ",", "categories"...
50.380952
31.333333
def _separable_approx2(h, N=1): """ returns the N first approximations to the 2d function h whose sum should be h """ return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0)
[ "def", "_separable_approx2", "(", "h", ",", "N", "=", "1", ")", ":", "return", "np", ".", "cumsum", "(", "[", "np", ".", "outer", "(", "fy", ",", "fx", ")", "for", "fy", ",", "fx", "in", "_separable_series2", "(", "h", ",", "N", ")", "]", ",", ...
41.6
13.2
def add_table(self, rows, cols, style=None): """ Add a table having row and column counts of *rows* and *cols* respectively and table style of *style*. *style* may be a paragraph style object or a paragraph style name. If *style* is |None|, the table inherits the default table st...
[ "def", "add_table", "(", "self", ",", "rows", ",", "cols", ",", "style", "=", "None", ")", ":", "table", "=", "self", ".", "_body", ".", "add_table", "(", "rows", ",", "cols", ",", "self", ".", "_block_width", ")", "table", ".", "style", "=", "styl...
46
18.4
def install_apt(self, fn=None, package_name=None, update=0, list_only=0): """ Installs system packages listed in apt-requirements.txt. """ r = self.local_renderer assert self.genv[ROLE] apt_req_fqfn = fn or (self.env.apt_requirments_fn and self.find_template(self.env.apt_...
[ "def", "install_apt", "(", "self", ",", "fn", "=", "None", ",", "package_name", "=", "None", ",", "update", "=", "0", ",", "list_only", "=", "0", ")", ":", "r", "=", "self", ".", "local_renderer", "assert", "self", ".", "genv", "[", "ROLE", "]", "a...
42.285714
23.071429
def _client_run(self): """MessageReceiver Link is now open - start receiving messages. Will return True if operation successful and client can remain open for further work. :rtype: bool """ self._connection.work() now = self._counter.get_current_ms() if s...
[ "def", "_client_run", "(", "self", ")", ":", "self", ".", "_connection", ".", "work", "(", ")", "now", "=", "self", ".", "_counter", ".", "get_current_ms", "(", ")", "if", "self", ".", "_last_activity_timestamp", "and", "not", "self", ".", "_was_message_re...
41.047619
17.428571
def findpeak_single(x, y, dy=None, position=None, hwhm=None, baseline=None, amplitude=None, curve='Lorentz', return_stat=False, signs=(-1, 1), return_x=None): """Find a (positive or negative) peak in the dataset. Inputs: x, y, dy: abscissa, ordinate and the error of the ordinate (ca...
[ "def", "findpeak_single", "(", "x", ",", "y", ",", "dy", "=", "None", ",", "position", "=", "None", ",", "hwhm", "=", "None", ",", "baseline", "=", "None", ",", "amplitude", "=", "None", ",", "curve", "=", "'Lorentz'", ",", "return_stat", "=", "False...
54.54386
30.894737
def visit_Dict(self, node): """ Process dict arguments. """ if self.should_check_whitelist(node): for key in node.keys: if key.s in self.whitelist or key.s.startswith("debug_"): continue self.violations.append((self.current...
[ "def", "visit_Dict", "(", "self", ",", "node", ")", ":", "if", "self", ".", "should_check_whitelist", "(", "node", ")", ":", "for", "key", "in", "node", ".", "keys", ":", "if", "key", ".", "s", "in", "self", ".", "whitelist", "or", "key", ".", "s",...
34.4375
18.5625
def variable_cols(X, tol=0.0, min_constant=0): """ Evaluates which columns are constant (0) or variable (1) Parameters ---------- X : ndarray Matrix whose columns will be checked for constant or variable. tol : float Tolerance for float-matrices. When set to 0 only equal columns wit...
[ "def", "variable_cols", "(", "X", ",", "tol", "=", "0.0", ",", "min_constant", "=", "0", ")", ":", "if", "X", "is", "None", ":", "return", "None", "from", "pyemma", ".", "_ext", ".", "variational", ".", "estimators", ".", "covar_c", ".", "_covartools",...
43.886792
26.849057
def group_add(self, name='Ungrouped'): """ Dynamically add a group instance to the system if not exist. Parameters ---------- name : str, optional ('Ungrouped' as default) Name of the group Returns ------- None """ if not hasa...
[ "def", "group_add", "(", "self", ",", "name", "=", "'Ungrouped'", ")", ":", "if", "not", "hasattr", "(", "self", ",", "name", ")", ":", "self", ".", "__dict__", "[", "name", "]", "=", "Group", "(", "self", ",", "name", ")", "self", ".", "loaded_gro...
26.0625
17.1875
def update(cls, content, dependency, version, spec="==", hashes=()): """ Updates the requirement to the latest version for the given content and adds hashes if neccessary. :param content: str, content :return: str, updated content """ new_line = "{name}{spec}{vers...
[ "def", "update", "(", "cls", ",", "content", ",", "dependency", ",", "version", ",", "spec", "=", "\"==\"", ",", "hashes", "=", "(", ")", ")", ":", "new_line", "=", "\"{name}{spec}{version}\"", ".", "format", "(", "name", "=", "dependency", ".", "full_na...
45.934783
18.586957
def trace(): """ trace finds the line, the filename and error message and returns it to the user """ import traceback import sys tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # script name + line number line = tbinfo.split(", ")[1] # Get Python sy...
[ "def", "trace", "(", ")", ":", "import", "traceback", "import", "sys", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "tbinfo", "=", "traceback", ".", "format_tb", "(", "tb", ")", "[", "0", "]", "# script name + line number", "line", "=", ...
25.75
12.125
def QA_util_get_pre_trade_date(cursor_date, n=1): """ 得到前 n 个交易日 (不包含当前交易日) :param date: :param n: """ cursor_date = QA_util_format_date2str(cursor_date) if cursor_date in trade_date_sse: return QA_util_date_gap(cursor_date, n, "lt") real_aft_trade_date = QA_util_get_real_date(c...
[ "def", "QA_util_get_pre_trade_date", "(", "cursor_date", ",", "n", "=", "1", ")", ":", "cursor_date", "=", "QA_util_format_date2str", "(", "cursor_date", ")", "if", "cursor_date", "in", "trade_date_sse", ":", "return", "QA_util_date_gap", "(", "cursor_date", ",", ...
31.5
15.166667
def get_post_data(self): ''' Get all the arguments from post request. Only get the first argument by default. ''' post_data = {} for key in self.request.arguments: post_data[key] = self.get_arguments(key)[0] return post_data
[ "def", "get_post_data", "(", "self", ")", ":", "post_data", "=", "{", "}", "for", "key", "in", "self", ".", "request", ".", "arguments", ":", "post_data", "[", "key", "]", "=", "self", ".", "get_arguments", "(", "key", ")", "[", "0", "]", "return", ...
34.625
21.625
def encode_features(X, enc_map=None): """Converts categorical values in each column of X to integers in the range [0, n_unique_values_in_column - 1], if X is not already of integer type. If mapping is not provided, it is calculated based on the values in X. Unknown values during prediction get a value...
[ "def", "encode_features", "(", "X", ",", "enc_map", "=", "None", ")", ":", "if", "enc_map", "is", "None", ":", "fit", "=", "True", "# We will calculate enc_map, so initialize the list of column mappings.", "enc_map", "=", "[", "]", "else", ":", "fit", "=", "Fals...
39.423077
24.423077
def managed_process(process): """Wrapper for subprocess.Popen to work across various Python versions, when using the with syntax.""" try: yield process finally: for stream in [process.stdout, process.stdin, process.stderr]: if stream: stream.close() proces...
[ "def", "managed_process", "(", "process", ")", ":", "try", ":", "yield", "process", "finally", ":", "for", "stream", "in", "[", "process", ".", "stdout", ",", "process", ".", "stdin", ",", "process", ".", "stderr", "]", ":", "if", "stream", ":", "strea...
35.555556
18.444444
def move_arc(x, y, r, speed = 1, orientation = True): # WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions """ Moves the cursor in an arc of radius r to (x, y) at a certain speed :param x: target x-ordinate :param y: target y-ordinate :par...
[ "def", "move_arc", "(", "x", ",", "y", ",", "r", ",", "speed", "=", "1", ",", "orientation", "=", "True", ")", ":", "# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions", "_x", ",", "_y", "=", "win32api", ".", ...
41.444444
20.851852
def cleanup(): """Cleanup the output directory""" if _output_dir and os.path.exists(_output_dir): log.msg_warn("Cleaning up output directory at '{output_dir}' ..." .format(output_dir=_output_dir)) if not _dry_run: shutil.rmtree(_output_dir)
[ "def", "cleanup", "(", ")", ":", "if", "_output_dir", "and", "os", ".", "path", ".", "exists", "(", "_output_dir", ")", ":", "log", ".", "msg_warn", "(", "\"Cleaning up output directory at '{output_dir}' ...\"", ".", "format", "(", "output_dir", "=", "_output_di...
41.571429
14.428571
def match(self, message: Message) -> bool: """ Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not """ if self.template: return...
[ "def", "match", "(", "self", ",", "message", ":", "Message", ")", "->", "bool", ":", "if", "self", ".", "template", ":", "return", "self", ".", "template", ".", "match", "(", "message", ")", "return", "True" ]
25.428571
19.142857
def create_mailbox(self, actor, loop): '''Create the mailbox for ``actor``.''' client = MailboxClient(actor.monitor.address, actor, loop) loop.call_soon_threadsafe(self.hand_shake, actor) return client
[ "def", "create_mailbox", "(", "self", ",", "actor", ",", "loop", ")", ":", "client", "=", "MailboxClient", "(", "actor", ".", "monitor", ".", "address", ",", "actor", ",", "loop", ")", "loop", ".", "call_soon_threadsafe", "(", "self", ".", "hand_shake", ...
45.8
14.2
def append_varint32(self, value): """Appends a signed 32-bit integer to the internal buffer, encoded as a varint. (Note that a negative varint32 will always require 10 bytes of space.) """ if not wire_format.INT32_MIN <= value <= wire_format.INT32_MAX: raise errors.E...
[ "def", "append_varint32", "(", "self", ",", "value", ")", ":", "if", "not", "wire_format", ".", "INT32_MIN", "<=", "value", "<=", "wire_format", ".", "INT32_MAX", ":", "raise", "errors", ".", "EncodeError", "(", "'Value out of range: %d'", "%", "value", ")", ...
49.125
12.5
def _register_aggregate(agg, con): """Register a Python class that performs aggregation in SQLite. Parameters ---------- agg : type con : sqlalchemy.Connection """ nargs = number_of_arguments(agg.step) - 1 # because self con.connection.connection.create_aggregate(agg.__name__, nargs, a...
[ "def", "_register_aggregate", "(", "agg", ",", "con", ")", ":", "nargs", "=", "number_of_arguments", "(", "agg", ".", "step", ")", "-", "1", "# because self", "con", ".", "connection", ".", "connection", ".", "create_aggregate", "(", "agg", ".", "__name__", ...
31.4
18.6
def _field_sort_name(cls, name): """Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `dat...
[ "def", "_field_sort_name", "(", "cls", ",", "name", ")", ":", "if", "isinstance", "(", "cls", ".", "__dict__", "[", "name", "]", ",", "DateItemField", ")", ":", "name", "=", "re", ".", "sub", "(", "'year'", ",", "'date0'", ",", "name", ")", "name", ...
44.357143
15
def check_pause(self, low): ''' Check to see if this low chunk has been paused ''' if not self.jid: # Can't pause on salt-ssh since we can't track continuous state return pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid) sta...
[ "def", "check_pause", "(", "self", ",", "low", ")", ":", "if", "not", "self", ".", "jid", ":", "# Can't pause on salt-ssh since we can't track continuous state", "return", "pause_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "opts", "[", "'cach...
42.25
14.204545
def make_cutout(self, data, masked_array=False): """ Create a (masked) cutout array from the input ``data`` using the minimal bounding box of the source segment. If ``masked_array`` is `False` (default), then the returned cutout array is simply a `~numpy.ndarray`. The returned ...
[ "def", "make_cutout", "(", "self", ",", "data", ",", "masked_array", "=", "False", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "if", "data", ".", "shape", "!=", "self", ".", "_segment_img", ".", "shape", ":", "raise", "ValueError"...
42.75
23.416667
def move_asset_ahead(self, asset_id, composition_id, reference_id): """Reorders assets in a composition by moving the specified asset in front of a reference asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Compos...
[ "def", "move_asset_ahead", "(", "self", ",", "asset_id", ",", "composition_id", ",", "reference_id", ")", ":", "self", ".", "_provider_session", ".", "move_asset_ahead", "(", "self", ",", "asset_id", ",", "composition_id", ",", "reference_id", ")" ]
50.777778
20.944444
def skip(self): """ Advance the internal pointer to the end of the data area in the stream. This allows the next call to :meth:`Reader.read` to succeed, as though all the data had been read by the application. """ self.stream.seek(self.bytes_remaining(), os.SEEK_C...
[ "def", "skip", "(", "self", ")", ":", "self", ".", "stream", ".", "seek", "(", "self", ".", "bytes_remaining", "(", ")", ",", "os", ".", "SEEK_CUR", ")", "self", ".", "_pos", "=", "self", ".", "length" ]
38.555556
12.555556
def map_fit(interface, state, label, inp): """ Function calculates sigmoid function (g) for every sample. With g it calculates part of Hessian matrix and gradient, aggregates and output them. It also calculates J function which is needed for checking the convergence of parameters theta. """ import numpy...
[ "def", "map_fit", "(", "interface", ",", "state", ",", "label", ",", "inp", ")", ":", "import", "numpy", "as", "np", "out", "=", "interface", ".", "output", "(", "0", ")", "H", ",", "J", ",", "grad", "=", "0", ",", "0", ",", "0", "for", "row", ...
50.461538
29
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0): """Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_mod...
[ "def", "find_model", "(", "model_name", ",", "apps", "=", "settings", ".", "INSTALLED_APPS", ",", "fuzziness", "=", "0", ")", ":", "# if it looks like a file system path rather than django project.app.model path the return it as a string", "if", "'/'", "in", "model_name", "...
38.434783
21.130435
def _dqdv_split_frames(cell, tidy=False, **kwargs): """Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_...
[ "def", "_dqdv_split_frames", "(", "cell", ",", "tidy", "=", "False", ",", "*", "*", "kwargs", ")", ":", "charge_dfs", ",", "cycles", ",", "minimum_v", ",", "maximum_v", "=", "_collect_capacity_curves", "(", "cell", ",", "direction", "=", "\"charge\"", ")", ...
30.044118
21.132353
def _first_line_re(): """ Return a regular expression based on first_line_re suitable for matching strings. """ if isinstance(first_line_re.pattern, str): return first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. return re.compile(first_line_re.pattern.d...
[ "def", "_first_line_re", "(", ")", ":", "if", "isinstance", "(", "first_line_re", ".", "pattern", ",", "str", ")", ":", "return", "first_line_re", "# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.", "return", "re", ".", "compile", "(", "first_line_re", ...
31.9
18.3
def prepend_model(self, value, model): """ Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key """ if '.' not in valu...
[ "def", "prepend_model", "(", "self", ",", "value", ",", "model", ")", ":", "if", "'.'", "not", "in", "value", ":", "direction", "=", "''", "if", "value", ".", "startswith", "(", "'-'", ")", ":", "value", "=", "value", "[", "1", ":", "]", "direction...
30.352941
10.470588
def get_queryset(self, request): """Limit to Tenants that this user can access.""" qs = super(TenantAdmin, self).get_queryset(request) if not request.user.is_superuser: tenants_by_group_manager_role = qs.filter( group__tenantrole__user=request.user, gr...
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "TenantAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "tenants_by_group_manager_role", ...
46.642857
17.571429
def compute_exported_specifications(svc_ref): # type: (pelix.framework.ServiceReference) -> List[str] """ Computes the list of specifications exported by the given service :param svc_ref: A ServiceReference :return: The list of exported specifications (or an empty list) """ if svc_ref.get_p...
[ "def", "compute_exported_specifications", "(", "svc_ref", ")", ":", "# type: (pelix.framework.ServiceReference) -> List[str]", "if", "svc_ref", ".", "get_property", "(", "pelix", ".", "remote", ".", "PROP_EXPORT_NONE", ")", ":", "# The export of this service is explicitly forbi...
36.886364
23.704545
def _extract_from_sans(self): """Looks for different TLDs as well as different sub-domains in SAN list""" self.logger.info("{} Trying to find Subdomains in SANs list".format(COLORED_COMBOS.NOTIFY)) if self.host.naked: domain = self.host.naked tld_less = domain.split(".")[...
[ "def", "_extract_from_sans", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"{} Trying to find Subdomains in SANs list\"", ".", "format", "(", "COLORED_COMBOS", ".", "NOTIFY", ")", ")", "if", "self", ".", "host", ".", "naked", ":", "domain",...
48.214286
21.428571
def plot_grid(grid_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec): """Plot a grid of points over the array of data on the figure. Parameters -----------. grid_arcsec : ndarray or data.array.grids.RegularGrid A grid of (y,x) coordinates in arc-seconds which may be plott...
[ "def", "plot_grid", "(", "grid_arcsec", ",", "array", ",", "units", ",", "kpc_per_arcsec", ",", "pointsize", ",", "zoom_offset_arcsec", ")", ":", "if", "grid_arcsec", "is", "not", "None", ":", "if", "zoom_offset_arcsec", "is", "not", "None", ":", "grid_arcsec"...
46
27.12
def execute_or_create_resource(self, device_id, _resource_path, **kwargs): # noqa: E501 """Execute a function on a Resource or create new Object instance # noqa: E501 With this API, you can [execute a function](/docs/current/connecting/handle-resource-webapp.html#the-execute-operation) on an existing...
[ "def", "execute_or_create_resource", "(", "self", ",", "device_id", ",", "_resource_path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", "...
131.416667
103.75
def expandvars(self, text, environ=None, cache=None): """ Recursively expands the text variables, vs. the os.path \ method which only works at one level. The cache value should be \ left blank as it is used to protect against recursion. :param t...
[ "def", "expandvars", "(", "self", ",", "text", ",", "environ", "=", "None", ",", "cache", "=", "None", ")", ":", "if", "not", "environ", ":", "environ", "=", "os", ".", "environ", "# make sure we have data", "if", "not", "text", ":", "return", "''", "#...
30.678571
16.607143
def jsonHook(encoded): """Custom JSON decoder that allows construction of a new ``Smi`` instance from a decoded JSON object. :param encoded: a JSON decoded object literal (a dict) :returns: "encoded" or one of the these objects: :class:`Smi`, :class:`MzmlScan`, :class:`Mzml...
[ "def", "jsonHook", "(", "encoded", ")", ":", "if", "'__Smi__'", "in", "encoded", ":", "return", "Smi", ".", "_fromJSON", "(", "encoded", "[", "'__Smi__'", "]", ")", "elif", "'__MzmlScan__'", "in", "encoded", ":", "return", "MzmlScan", ".", "_fromJSON", "("...
42.421053
17.842105
def plugin(cls, name): """ Retrieves the plugin based on the inputted name. :param name | <str> :return <Plugin> """ cls.loadPlugins() plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}) return plugs.get(nstr(name))
[ "def", "plugin", "(", "cls", ",", "name", ")", ":", "cls", ".", "loadPlugins", "(", ")", "plugs", "=", "getattr", "(", "cls", ",", "'_%s__plugins'", "%", "cls", ".", "__name__", ",", "{", "}", ")", "return", "plugs", ".", "get", "(", "nstr", "(", ...
27.272727
14.545455
def can_lookup_assets(self): """Tests if this user can perform ``Asset`` lookups. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a ``PermissionDenied``. This is intended as a h...
[ "def", "can_lookup_assets", "(", "self", ")", ":", "url_path", "=", "construct_url", "(", "'authorization'", ",", "bank_id", "=", "self", ".", "_catalog_idstr", ")", "return", "self", ".", "_get_request", "(", "url_path", ")", "[", "'assetHints'", "]", "[", ...
39.684211
26.052632
def find_label(self, label: Label): """ Helper function that iterates over the program and looks for a JumpTarget that has a Label matching the input label. :param label: Label object to search for in program :return: Program index where ``label`` is found """ fo...
[ "def", "find_label", "(", "self", ",", "label", ":", "Label", ")", ":", "for", "index", ",", "action", "in", "enumerate", "(", "self", ".", "program", ")", ":", "if", "isinstance", "(", "action", ",", "JumpTarget", ")", ":", "if", "label", "==", "act...
39.666667
16.066667
def print(self, *objects, **kwargs): """Micmic print interface""" file = kwargs.get("file") if file is not None and file is not sys.stdout: PRINT(*objects, **kwargs) else: sep = STR(kwargs.get("sep", " ")) end = STR(kwargs.get("end", "\n")) text = sep.join(STR(o) for o in objects) self.imp_pr...
[ "def", "print", "(", "self", ",", "*", "objects", ",", "*", "*", "kwargs", ")", ":", "file", "=", "kwargs", ".", "get", "(", "\"file\"", ")", "if", "file", "is", "not", "None", "and", "file", "is", "not", "sys", ".", "stdout", ":", "PRINT", "(", ...
21.823529
19
async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :clas...
[ "async", "def", "fetch_emoji", "(", "self", ",", "emoji_id", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_custom_emoji", "(", "self", ".", "id", ",", "emoji_id", ")", "return", "Emoji", "(", "guild", "=", "self", ",", ...
25.551724
21.62069
def parse_function(fn): """Get the source of a function and return its AST.""" try: return parse_string(inspect.getsource(fn)) except (IOError, OSError) as e: raise ValueError( 'Cannot differentiate function: %s. Tangent must be able to access the ' 'source code of the function. Functions ...
[ "def", "parse_function", "(", "fn", ")", ":", "try", ":", "return", "parse_string", "(", "inspect", ".", "getsource", "(", "fn", ")", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "e", ":", "raise", "ValueError", "(", "'Cannot differentiate fun...
45
18.8
def _fetch_file(self, remote, local): """fetch a single file""" full_remote = "%s:%s" % (self.location, remote) self.log.info("fetching %s from %s", local, full_remote) for i in range(10): # wait up to 10s for remote file to exist check = check_output(self.ssh_cmd...
[ "def", "_fetch_file", "(", "self", ",", "remote", ",", "local", ")", ":", "full_remote", "=", "\"%s:%s\"", "%", "(", "self", ".", "location", ",", "remote", ")", "self", ".", "log", ".", "info", "(", "\"fetching %s from %s\"", ",", "local", ",", "full_re...
44
14.785714
def postprocess_variants(items): """Provide post-processing of variant calls: filtering and effects annotation. """ vrn_key = "vrn_file" if not isinstance(items, dict): items = [utils.to_single_data(x) for x in items] if "vrn_file_joint" in items[0]: vrn_key = "vrn_file_joint...
[ "def", "postprocess_variants", "(", "items", ")", ":", "vrn_key", "=", "\"vrn_file\"", "if", "not", "isinstance", "(", "items", ",", "dict", ")", ":", "items", "=", "[", "utils", ".", "to_single_data", "(", "x", ")", "for", "x", "in", "items", "]", "if...
51.510204
18.387755
def run_all(): """ Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects. """ DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(date...
[ "def", "run_all", "(", ")", ":", "DATA_DIR", "=", "\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels\"", "dates", "=", "os", ".", "listdir", "(", "\"/home/share/LAMOST/DR2/DR2_release\"", ")", "dates", "=", "np", ".", "array", "(", "dates", ")", "dates", "=...
41.3125
17.1875
def decode_offset_fetch_response(cls, data): """ Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in r...
[ "def", "decode_offset_fetch_response", "(", "cls", ",", "data", ")", ":", "(", "(", "correlation_id", ",", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>i'", ",", "data", ",", "0", ")", "(", "(", "num_topics", ",", ")", ",", "cur", ")", "=", ...
37.545455
21.454545
def prune_contours(self, area_thresh=1000.0, dist_thresh=20, preserve_topology=True): """Removes all white connected components with area less than area_thresh. Parameters ---------- area_thresh : float The minimum area for which a white connected compo...
[ "def", "prune_contours", "(", "self", ",", "area_thresh", "=", "1000.0", ",", "dist_thresh", "=", "20", ",", "preserve_topology", "=", "True", ")", ":", "# get all contours (connected components) from the binary image", "contours", ",", "hierarchy", "=", "cv2", ".", ...
39.841463
15.292683
def text_with_newlines(text, line_length=78, newline='\n'): '''Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0. ''' if line_length > 0: if len(text) <= line_length: return text else: return newline....
[ "def", "text_with_newlines", "(", "text", ",", "line_length", "=", "78", ",", "newline", "=", "'\\n'", ")", ":", "if", "line_length", ">", "0", ":", "if", "len", "(", "text", ")", "<=", "line_length", ":", "return", "text", "else", ":", "return", "newl...
34.285714
21.428571
def targetLow(self): """Return the low byte of the target address field. Used in All-Link Cleanup messages. """ low_byte = None if self.target is not None and self._messageFlags.isBroadcast: low_byte = self.target.bytes[0] return low_byte
[ "def", "targetLow", "(", "self", ")", ":", "low_byte", "=", "None", "if", "self", ".", "target", "is", "not", "None", "and", "self", ".", "_messageFlags", ".", "isBroadcast", ":", "low_byte", "=", "self", ".", "target", ".", "bytes", "[", "0", "]", "...
32.333333
14.333333
def get_user_by_name(uname,**kwargs): """ Get a user by username """ try: user_i = db.DBSession.query(User).filter(User.username==uname).one() return user_i except NoResultFound: return None
[ "def", "get_user_by_name", "(", "uname", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user_i", "=", "db", ".", "DBSession", ".", "query", "(", "User", ")", ".", "filter", "(", "User", ".", "username", "==", "uname", ")", ".", "one", "(", ")", ...
25.555556
15.111111
def _selfConsistentIteration(self, relative_tolerance=1.0e-6, maximum_iterations=1000, verbose=True, print_warning=False): """ Determine free energies by self-consistent iteration. OPTIONAL ARGUMENTS relative_tolerance (float between 0 and 1) - relative tolerance for convergence (def...
[ "def", "_selfConsistentIteration", "(", "self", ",", "relative_tolerance", "=", "1.0e-6", ",", "maximum_iterations", "=", "1000", ",", "verbose", "=", "True", ",", "print_warning", "=", "False", ")", ":", "# Iteratively update dimensionless free energies until convergence...
41.783784
32.918919
def object_attributes( thing, all=False ) : ''' Return a sorted list of names defined by thing that are not also names in a standard object, except include __doc__. ''' standard_names = set( dir( object() ) ) things_names = set( dir( thing ) ) if not all : things_names -= standard_na...
[ "def", "object_attributes", "(", "thing", ",", "all", "=", "False", ")", ":", "standard_names", "=", "set", "(", "dir", "(", "object", "(", ")", ")", ")", "things_names", "=", "set", "(", "dir", "(", "thing", ")", ")", "if", "not", "all", ":", "thi...
35.454545
13.818182
def get_header(self, configuration=False): """Get the log file header If configuration is True, this returns the daemon configuration :return: A string list containing project name, daemon name, version, licence etc. :rtype: list """ header = [u"-----", ...
[ "def", "get_header", "(", "self", ",", "configuration", "=", "False", ")", ":", "header", "=", "[", "u\"-----\"", ",", "u\" █████╗ ██╗ ██╗ ██████╗ ███╗ ██╗ █████╗ ██╗ ██╗\",", "", "u\" ██╔══██╗██║ ██║██╔════╝ ████╗ ██║██╔══██╗██║ ██╔╝\",", "", "u\" ███████║██║ ...
45.1
24.333333
def neg_loglikelihood(y, mean, scale, shape, skewness): """ Negative loglikelihood function Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Poisson distribution scale : float ...
[ "def", "neg_loglikelihood", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "-", "np", ".", "sum", "(", "-", "mean", "+", "np", ".", "log", "(", "mean", ")", "*", "y", "-", "sp", ".", "gammaln", "(", "y",...
27.76
22.72
def setDirection(self, outputLocation, inputLocation): """ Sets the output-to-input direction by setting both the locations \ at the same time. :param outputLocation | <XConnectionLocation> :param inputLocation | <XConnectionLocation> """ ...
[ "def", "setDirection", "(", "self", ",", "outputLocation", ",", "inputLocation", ")", ":", "self", ".", "setOutputLocation", "(", "outputLocation", ")", "self", ".", "setInputLocation", "(", "inputLocation", ")" ]
39.9
15.1
def make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype='band'): """ Generates the b and a coefficients for a butterworth bandpass IIR filter. Parameters ---------- CenterFreq : float central frequency of bandpass bandwidth : float width of the bandpa...
[ "def", "make_butterworth_bandpass_b_a", "(", "CenterFreq", ",", "bandwidth", ",", "SampleFreq", ",", "order", "=", "5", ",", "btype", "=", "'band'", ")", ":", "lowcut", "=", "CenterFreq", "-", "bandwidth", "/", "2", "highcut", "=", "CenterFreq", "+", "bandwi...
32.928571
21.214286
def process_attributes_of_node(attrs, node_name, class_type): """ prepare the model fields, nodes and relations Args: node_name (str): name of the node we are currently processing attrs (dict): attribute dict class_type (str): Type of class. C...
[ "def", "process_attributes_of_node", "(", "attrs", ",", "node_name", ",", "class_type", ")", ":", "# print(\"Node: %s\" % node_name)", "attrs", "[", "'_nodes'", "]", "=", "{", "}", "attrs", "[", "'_linked_models'", "]", "=", "defaultdict", "(", "list", ")", "att...
51.061538
18.938462
def add_user_to_allow(self, name, user): """Add a user to the given acl allow block.""" # Clear user from both allow and deny before adding if not self.remove_user_from_acl(name, user): return False if name not in self._acl: return False self._acl[name]...
[ "def", "add_user_to_allow", "(", "self", ",", "name", ",", "user", ")", ":", "# Clear user from both allow and deny before adding", "if", "not", "self", ".", "remove_user_from_acl", "(", "name", ",", "user", ")", ":", "return", "False", "if", "name", "not", "in"...
29.25
18.083333
def run(self, tag=None, output=None, **kwargs): """ runs the extractor Args: ----- output: ['filepath', None] """ start = datetime.datetime.now() count = 0 if tag: tag = Uri(tag) xml_generator = etree.iterparse(self.so...
[ "def", "run", "(", "self", ",", "tag", "=", "None", ",", "output", "=", "None", ",", "*", "*", "kwargs", ")", ":", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "count", "=", "0", "if", "tag", ":", "tag", "=", "Uri", "(", "...
35.615385
15.871795
def num_sequences(fileh): """ Determine how many sequences there are in fasta file/stream. :param fileh: the stream to read the fasta data from, or a string giving the filename of the file to load. Note that if a stream is given, it will be consumed by this function :r...
[ "def", "num_sequences", "(", "fileh", ")", ":", "if", "type", "(", "fileh", ")", ".", "__name__", "==", "\"str\"", ":", "fh", "=", "open", "(", "fileh", ")", "else", ":", "fh", "=", "fileh", "count", "=", "0", "for", "_", "in", "fastaIterator", "("...
30.470588
21.764706
def median(self, default=None): """ Calculate the median value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the median value or `None`. """ return numpy.asscalar(numpy.median(self.v...
[ "def", "median", "(", "self", ",", "default", "=", "None", ")", ":", "return", "numpy", ".", "asscalar", "(", "numpy", ".", "median", "(", "self", ".", "values", ")", ")", "if", "self", ".", "values", "else", "default" ]
43.5
23
def verify(self, key, data, signature, mecha=MechanismRSAPKCS1): """ C_VerifyInit/C_Verify :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data that was signed :type data: (binary) string or list/tuple of bytes ...
[ "def", "verify", "(", "self", ",", "key", ",", "data", ",", "signature", ",", "mecha", "=", "MechanismRSAPKCS1", ")", ":", "m", "=", "mecha", ".", "to_native", "(", ")", "data1", "=", "ckbytelist", "(", "data", ")", "rv", "=", "self", ".", "lib", "...
36.448276
15.62069
def check_outdated(package, version): """ Given the name of a package on PyPI and a version (both strings), checks if the given version is the latest version of the package available. Returns a 2-tuple (is_outdated, latest_version) where is_outdated is a boolean which is True if the given version i...
[ "def", "check_outdated", "(", "package", ",", "version", ")", ":", "from", "pkg_resources", "import", "parse_version", "parsed_version", "=", "parse_version", "(", "version", ")", "latest", "=", "None", "with", "utils", ".", "cache_file", "(", "package", ",", ...
33.833333
20.907407
def collect_hosts(hosts, randomize=True): """ Collects a comma-separated set of hosts (host:port) and optionally randomize the returned list. """ if isinstance(hosts, six.string_types): hosts = hosts.strip().split(',') result = [] for host_port in hosts: res = host_port.sp...
[ "def", "collect_hosts", "(", "hosts", ",", "randomize", "=", "True", ")", ":", "if", "isinstance", "(", "hosts", ",", "six", ".", "string_types", ")", ":", "hosts", "=", "hosts", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "result", "=", ...
23.952381
18.904762
def lrucache(func, size): """ A simple implementation of a least recently used (LRU) cache. Memoizes the recent calls of a computationally intensive function. Parameters ---------- func : function Must be unary (takes a single argument) size : int The size of the cache (num...
[ "def", "lrucache", "(", "func", ",", "size", ")", ":", "if", "size", "==", "0", ":", "return", "func", "elif", "size", "<", "0", ":", "raise", "ValueError", "(", "\"size argument must be a positive integer\"", ")", "# this only works for unary functions", "if", ...
26.857143
22.530612
def storage_del(self, key=None): """ Remove the value stored with the key from storage. If key is not supplied then all values for the module are removed. """ if not self._module: return self._storage_init() module_name = self._module.module_full_name ...
[ "def", "storage_del", "(", "self", ",", "key", "=", "None", ")", ":", "if", "not", "self", ".", "_module", ":", "return", "self", ".", "_storage_init", "(", ")", "module_name", "=", "self", ".", "_module", ".", "module_full_name", "return", "self", ".", ...
37.3
13.9
def write_roc(roc_structure, inputfilename, options, fw_type = None): """ writes ROC output :param roc_structure: a.k.a auc_structure, generated in /common_tools/classification/make_auc_structure() :param inputfilename: name of the file specified on the command line that contains the ensemble. This will...
[ "def", "write_roc", "(", "roc_structure", ",", "inputfilename", ",", "options", ",", "fw_type", "=", "None", ")", ":", "# check if ./ROC_DATA exists. If not, create it", "rocdir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", ...
32.214286
21.785714
def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the nod...
[ "def", "pprint", "(", "self", ",", "index", "=", "False", ",", "delimiter", "=", "'-'", ")", ":", "lines", "=", "_build_tree_string", "(", "self", ",", "0", ",", "index", ",", "delimiter", ")", "[", "0", "]", "print", "(", "'\\n'", "+", "'\\n'", "....
33
21.957447
def image_path_from_index(self, index): """ given image index, find out full path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of this image """ assert self.image_set_index is not No...
[ "def", "image_path_from_index", "(", "self", ",", "index", ")", ":", "assert", "self", ".", "image_set_index", "is", "not", "None", ",", "\"Dataset not initialized\"", "name", "=", "self", ".", "image_set_index", "[", "index", "]", "image_file", "=", "os", "."...
32.705882
17.176471
def vcs_init(self): """Initialize VCS repository.""" VCS(os.path.join(self.outdir, self.name), self.pkg_data)
[ "def", "vcs_init", "(", "self", ")", ":", "VCS", "(", "os", ".", "path", ".", "join", "(", "self", ".", "outdir", ",", "self", ".", "name", ")", ",", "self", ".", "pkg_data", ")" ]
41
15
def shrink_dsp(self, inputs=None, outputs=None, cutoff=None, inputs_dist=None, wildcard=True): """ Returns a reduced dispatcher. :param inputs: Input data nodes. :type inputs: list[str], iterable, optional :param outputs: Ending data n...
[ "def", "shrink_dsp", "(", "self", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ",", "cutoff", "=", "None", ",", "inputs_dist", "=", "None", ",", "wildcard", "=", "True", ")", ":", "bfs", "=", "None", "if", "inputs", ":", "# Get all data nod...
32.185714
19.657143
def parseMemory(buffer, size): """parse an XML in-memory block and build a tree. """ ret = libxml2mod.xmlParseMemory(buffer, size) if ret is None:raise parserError('xmlParseMemory() failed') return xmlDoc(_obj=ret)
[ "def", "parseMemory", "(", "buffer", ",", "size", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseMemory", "(", "buffer", ",", "size", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParseMemory() failed'", ")", "return", "xmlDoc", ...
45.2
11
def draw_dynamics_set(dynamics, xtitle = None, ytitle = None, xlim = None, ylim = None, xlabels = False, ylabels = False): """! @brief Draw lists of dynamics of neurons (oscillators) in the network. @param[in] dynamics (list): List of network outputs that are represented by values of output of osci...
[ "def", "draw_dynamics_set", "(", "dynamics", ",", "xtitle", "=", "None", ",", "ytitle", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "xlabels", "=", "False", ",", "ylabels", "=", "False", ")", ":", "# Calculate edge for confortable...
41.465116
23.395349
def WaitUntilNoFlowsToProcess(self, timeout=None): """Waits until flow processing thread is done processing flows. Args: timeout: If specified, is a max number of seconds to spend waiting. Raises: TimeOutWhileWaitingForFlowsToBeProcessedError: if timeout is reached. """ t = self.flow_h...
[ "def", "WaitUntilNoFlowsToProcess", "(", "self", ",", "timeout", "=", "None", ")", ":", "t", "=", "self", ".", "flow_handler_thread", "if", "not", "t", ":", "return", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "with", "self",...
31.793103
21.862069
def refresh_db(**kwargs): ''' Update list of available packages from installed repos CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) cmd = 'xbps-install...
[ "def", "refresh_db", "(", "*", "*", "kwargs", ")", ":", "# Remove rtag file to keep multiple refreshes from happening in pkg states", "salt", ".", "utils", ".", "pkg", ".", "clear_rtag", "(", "__opts__", ")", "cmd", "=", "'xbps-install -Sy'", "call", "=", "__salt__", ...
24.954545
22.681818
def create_datapipeline(self): """Creates the data pipeline if it does not already exist Returns: dict: the response of the Boto3 command """ tags = [{"key": "app_group", "value": self.group}, {"key": "app_name", "value": self.app_name}] response = self.client.c...
[ "def", "create_datapipeline", "(", "self", ")", ":", "tags", "=", "[", "{", "\"key\"", ":", "\"app_group\"", ",", "\"value\"", ":", "self", ".", "group", "}", ",", "{", "\"key\"", ":", "\"app_name\"", ",", "\"value\"", ":", "self", ".", "app_name", "}", ...
38.5
21.722222
def CallClient(self, action_cls, request=None, next_state=None, request_data=None, **kwargs): """Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many re...
[ "def", "CallClient", "(", "self", ",", "action_cls", ",", "request", "=", "None", ",", "next_state", "=", "None", ",", "request_data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "action_identifier", "=", "action_registry", ".", "ID_BY_ACTI...
38.141304
21.163043
def get_list_objects_arg_dict(self, node_type): """Create a dict of arguments that will be passed to listObjects(). If {node_type} is a CN, add filtering to include only objects from this GMN instance in the ObjectList returned by CNCore.listObjects(). """ arg_dict = { ...
[ "def", "get_list_objects_arg_dict", "(", "self", ",", "node_type", ")", ":", "arg_dict", "=", "{", "# Restrict query for faster debugging", "# \"fromDate\": datetime.datetime(2017, 1, 1),", "# \"toDate\": datetime.datetime(2017, 1, 10),", "}", "if", "node_type", "==", "\"cn\"", ...
39.6
20.4
def urlretrieve(uri, saveas=None, retries=3, cache_dir=None): '''urllib.urlretrieve wrapper''' retries = int(retries) if retries else 3 # FIXME: make random filename (saveas) in cache_dir... # cache_dir = cache_dir or CACHE_DIR while retries: try: _path, headers = urllib.urlretri...
[ "def", "urlretrieve", "(", "uri", ",", "saveas", "=", "None", ",", "retries", "=", "3", ",", "cache_dir", "=", "None", ")", ":", "retries", "=", "int", "(", "retries", ")", "if", "retries", "else", "3", "# FIXME: make random filename (saveas) in cache_dir...",...
33.65
17.45
def add_package(package_name, package_path='templates', encoding='utf-8'): """Adds the given package to the template search routine""" if not _has_jinja: raise RuntimeError(_except_text) _jload.add_loader(PackageLoader(package_name, package_path, encoding))
[ "def", "add_package", "(", "package_name", ",", "package_path", "=", "'templates'", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "not", "_has_jinja", ":", "raise", "RuntimeError", "(", "_except_text", ")", "_jload", ".", "add_loader", "(", "PackageLoader", ...
54.6
17.2
def absolute_git_root_dir(fpath=""): """Absolute path to the git root directory containing a given file or directory. """ if len(fpath) == 0: dirname_str = os.getcwd() else: dirname_str = os.path.dirname(fpath) dirname_str = os.path.abspath(dirname_str) dirnames = dirname_str...
[ "def", "absolute_git_root_dir", "(", "fpath", "=", "\"\"", ")", ":", "if", "len", "(", "fpath", ")", "==", "0", ":", "dirname_str", "=", "os", ".", "getcwd", "(", ")", "else", ":", "dirname_str", "=", "os", ".", "path", ".", "dirname", "(", "fpath", ...
33.388889
11.277778
def set_chassis_datacenter(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host...
[ "def", "set_chassis_datacenter", "(", "location", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "return", "set_general", "(", "'cfgLocation'", ",", "'cfgLocationDatacenter'", ",", "location", ",", "ho...
27.233333
24.433333
def create_sns_event(app_name, env, region, rules): """Create SNS lambda event from rules. Args: app_name (str): name of the lambda function env (str): Environment/Account for lambda function region (str): AWS region of the lambda function rules (str): Trigger rules from the set...
[ "def", "create_sns_event", "(", "app_name", ",", "env", ",", "region", ",", "rules", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ",", "region_name", "=", "region", ")", "sns_client", "=", "session", ".", "client", ...
36.84375
19.75
def turn_on(self): """Turn Air Purifier on""" if self.device_status != 'on': body = helpers.req_body(self.manager, 'devicestatus') body['uuid'] = self.uuid body['status'] = 'on' head = helpers.req_headers(self.manager) r, _ = helpers.call_api(...
[ "def", "turn_on", "(", "self", ")", ":", "if", "self", ".", "device_status", "!=", "'on'", ":", "body", "=", "helpers", ".", "req_body", "(", "self", ".", "manager", ",", "'devicestatus'", ")", "body", "[", "'uuid'", "]", "=", "self", ".", "uuid", "b...
38.0625
18.8125
def _fetch_system_by_machine_id(self): ''' Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response ''' machine_id = generate_machine_id() ...
[ "def", "_fetch_system_by_machine_id", "(", "self", ")", ":", "machine_id", "=", "generate_machine_id", "(", ")", "try", ":", "url", "=", "self", ".", "api_url", "+", "'/inventory/v1/hosts?insights_id='", "+", "machine_id", "net_logger", ".", "info", "(", "\"GET %s...
38.896552
16.62069
def get_display_name(value): """ display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with the content of the phrase. """ display_name = DisplayName() token, value = get_phrase(value) display...
[ "def", "get_display_name", "(", "value", ")", ":", "display_name", "=", "DisplayName", "(", ")", "token", ",", "value", "=", "get_phrase", "(", "value", ")", "display_name", ".", "extend", "(", "token", "[", ":", "]", ")", "display_name", ".", "defects", ...
31.153846
14.692308
def RPC(self, url, opname, obj, replytype=None, **kw): '''Send a request, return the reply. See Send() and Recieve() docstrings for details. ''' self.Send(url, opname, obj, **kw) return self.Receive(replytype, **kw)
[ "def", "RPC", "(", "self", ",", "url", ",", "opname", ",", "obj", ",", "replytype", "=", "None", ",", "*", "*", "kw", ")", ":", "self", ".", "Send", "(", "url", ",", "opname", ",", "obj", ",", "*", "*", "kw", ")", "return", "self", ".", "Rece...
41.833333
14.5
def hash(self): """Returns the SHA256 of the pipfile's data.""" content = json.dumps(self.data, sort_keys=True, separators=(",", ":")) return hashlib.sha256(content.encode("utf8")).hexdigest()
[ "def", "hash", "(", "self", ")", ":", "content", "=", "json", ".", "dumps", "(", "self", ".", "data", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ")", "return", "hashlib", ".", "sha256", "(", "content", "...
53.25
22
def mangleIR(data, ignore_errors=False): """Mangle a raw Kira data packet into shorthand""" try: # Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin # Determine a median value for the timing packets and categorize each # timing as longer or shorter than that. This wil...
[ "def", "mangleIR", "(", "data", ",", "ignore_errors", "=", "False", ")", ":", "try", ":", "# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin", "# Determine a median value for the timing packets and categorize each", "# timing as longer or shorter than that. This wil...
49.727273
20.909091
def _create_kubernetes_state_prometheus_instance(self, instance): """ Set up the kubernetes_state instance so it can be used in OpenMetricsBaseCheck """ ksm_instance = deepcopy(instance) endpoint = instance.get('kube_state_url') if endpoint is None: raise Chec...
[ "def", "_create_kubernetes_state_prometheus_instance", "(", "self", ",", "instance", ")", ":", "ksm_instance", "=", "deepcopy", "(", "instance", ")", "endpoint", "=", "instance", ".", "get", "(", "'kube_state_url'", ")", "if", "endpoint", "is", "None", ":", "rai...
65.884393
32.265896
def ingest_containers(self, containers=None): """ Transform the YAML into a dict with normalized keys """ containers = containers or self.stream or {} output_containers = [] for container_name, definition in containers.items(): container = definition.copy() ...
[ "def", "ingest_containers", "(", "self", ",", "containers", "=", "None", ")", ":", "containers", "=", "containers", "or", "self", ".", "stream", "or", "{", "}", "output_containers", "=", "[", "]", "for", "container_name", ",", "definition", "in", "containers...
31.071429
14.928571
def _get_client_by_id(self, client_id): """Get GRR client dictionary and make sure valid approvals exist. Args: client_id: GRR client ID. Returns: GRR API Client object """ client = self.grr_api.Client(client_id) print('Checking for client approval') self._check_approval_wrappe...
[ "def", "_get_client_by_id", "(", "self", ",", "client_id", ")", ":", "client", "=", "self", ".", "grr_api", ".", "Client", "(", "client_id", ")", "print", "(", "'Checking for client approval'", ")", "self", ".", "_check_approval_wrapper", "(", "client", ",", "...
30.071429
15.928571
def _from_dict(cls, _dict): """Initialize a MessageContext object from a json dictionary.""" args = {} if 'global' in _dict: args['global_'] = MessageContextGlobal._from_dict( _dict.get('global')) if 'skills' in _dict: args['skills'] = MessageConte...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'global'", "in", "_dict", ":", "args", "[", "'global_'", "]", "=", "MessageContextGlobal", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'global'", ")", ")", ...
39.5
12.3
def _check_transition_id(self, transition): """Checks the validity of a transition id Checks whether the transition id is already used by another transition within the state :param rafcon.core.transition.Transition transition: The transition to be checked :return bool validity, str mes...
[ "def", "_check_transition_id", "(", "self", ",", "transition", ")", ":", "transition_id", "=", "transition", ".", "transition_id", "if", "transition_id", "in", "self", ".", "transitions", "and", "transition", "is", "not", "self", ".", "transitions", "[", "transi...
54.384615
30.076923