text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def prepare_patchset(project, patchset, binaries, ips, urls): """ Create black/white lists and default / project waivers and iterates over patchset file """ # Get Various Lists / Project Waivers lists = get_lists.GetLists() # Get file name black list and project waivers file_audit_list, fil...
[ "def", "prepare_patchset", "(", "project", ",", "patchset", ",", "binaries", ",", "ips", ",", "urls", ")", ":", "# Get Various Lists / Project Waivers", "lists", "=", "get_lists", ".", "GetLists", "(", ")", "# Get file name black list and project waivers", "file_audit_l...
34.35
0.002358
def fmap(self, f: Callable[[T], B]) -> 'List[B]': """doufo.List.fmap: map `List` Args: `self`: `f` (`Callable[[T], B]`): any callable funtion Returns: return (`List[B]`): A `List` of objected from `f`. Raises: """ return Lis...
[ "def", "fmap", "(", "self", ",", "f", ":", "Callable", "[", "[", "T", "]", ",", "B", "]", ")", "->", "'List[B]'", ":", "return", "List", "(", "[", "f", "(", "x", ")", "for", "x", "in", "self", ".", "unbox", "(", ")", "]", ")" ]
34.2
0.022792
def write_json_report(sample_id, data1, data2): """Writes the report Parameters ---------- data1 data2 Returns ------- """ parser_map = { "base_sequence_quality": ">>Per base sequence quality", "sequence_quality": ">>Per sequence quality scores", "base_gc_...
[ "def", "write_json_report", "(", "sample_id", ",", "data1", ",", "data2", ")", ":", "parser_map", "=", "{", "\"base_sequence_quality\"", ":", "\">>Per base sequence quality\"", ",", "\"sequence_quality\"", ":", "\">>Per sequence quality scores\"", ",", "\"base_gc_content\""...
30.254237
0.000543
def _max(self, memory, addr, **kwargs): """ Gets the maximum solution of an address. """ return memory.state.solver.max(addr, exact=kwargs.pop('exact', self._exact), **kwargs)
[ "def", "_max", "(", "self", ",", "memory", ",", "addr", ",", "*", "*", "kwargs", ")", ":", "return", "memory", ".", "state", ".", "solver", ".", "max", "(", "addr", ",", "exact", "=", "kwargs", ".", "pop", "(", "'exact'", ",", "self", ".", "_exac...
40.6
0.014493
def pydeps(**args): """Entry point for the ``pydeps`` command. This function should do all the initial parameter and environment munging before calling ``_pydeps`` (so that function has a clean execution path). """ _args = args if args else cli.parse_args(sys.argv[1:]) inp = target...
[ "def", "pydeps", "(", "*", "*", "args", ")", ":", "_args", "=", "args", "if", "args", "else", "cli", ".", "parse_args", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "inp", "=", "target", ".", "Target", "(", "_args", "[", "'fname'", "]", ")...
32.741935
0.000957
def _get_base_command(self): """Gets the command that will be run when the app controller is called. """ command_parts = [] cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) if self._command is None: raise ApplicationError('_command has not been set.') ...
[ "def", "_get_base_command", "(", "self", ")", ":", "command_parts", "=", "[", "]", "cd_command", "=", "''", ".", "join", "(", "[", "'cd '", ",", "str", "(", "self", ".", "WorkingDir", ")", ",", "';'", "]", ")", "if", "self", ".", "_command", "is", ...
36.72
0.002123
def pods(namespace='default', **kwargs): ''' Return a list of kubernetes pods defined in the namespace CLI Examples:: salt '*' kubernetes.pods salt '*' kubernetes.pods namespace=default ''' cfg = _setup_conn(**kwargs) try: api_instance = kubernetes.client.CoreV1Api() ...
[ "def", "pods", "(", "namespace", "=", "'default'", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "_setup_conn", "(", "*", "*", "kwargs", ")", "try", ":", "api_instance", "=", "kubernetes", ".", "client", ".", "CoreV1Api", "(", ")", "api_response", "="...
31.115385
0.002398
def clock(self, interval, basis="system"): """Return a NodeInput tuple for triggering an event every interval. Args: interval (int): The interval at which this input should trigger. If basis == system (the default), this interval must be in seconds. Otherwis...
[ "def", "clock", "(", "self", ",", "interval", ",", "basis", "=", "\"system\"", ")", ":", "if", "basis", "==", "\"system\"", ":", "if", "(", "interval", "%", "10", ")", "==", "0", ":", "tick", "=", "self", ".", "allocator", ".", "attach_stream", "(", ...
46.142857
0.002426
def next(self, acceleration=0.0): """Continue rotation in direction of last drag.""" q = quaternion_slerp(self._qpre, self._qnow, 2.0 + acceleration, False) self._qpre, self._qnow = self._qnow, q
[ "def", "next", "(", "self", ",", "acceleration", "=", "0.0", ")", ":", "q", "=", "quaternion_slerp", "(", "self", ".", "_qpre", ",", "self", ".", "_qnow", ",", "2.0", "+", "acceleration", ",", "False", ")", "self", ".", "_qpre", ",", "self", ".", "...
54
0.009132
def main(bot): """ Entry point for the command line launcher. :param bot: the IRC bot to run :type bot: :class:`fatbotslim.irc.bot.IRC` """ greenlet = spawn(bot.run) try: greenlet.join() except KeyboardInterrupt: print '' # cosmetics matters log.info("Killed by ...
[ "def", "main", "(", "bot", ")", ":", "greenlet", "=", "spawn", "(", "bot", ".", "run", ")", "try", ":", "greenlet", ".", "join", "(", ")", "except", "KeyboardInterrupt", ":", "print", "''", "# cosmetics matters", "log", ".", "info", "(", "\"Killed by use...
24.4375
0.002463
def upload(self, url, filename, data=None, formname=None, otherfields=()): """Upload a file to the url :param url: :param filename: The name of the file :param data: A file object or data to use rather than reading from the file. :return: ...
[ "def", "upload", "(", "self", ",", "url", ",", "filename", ",", "data", "=", "None", ",", "formname", "=", "None", ",", "otherfields", "=", "(", ")", ")", ":", "if", "data", "is", "None", ":", "data", "=", "open", "(", "filename", ",", "'rb'", ")...
43.411765
0.001988
def post(self, uri, params={}, data={}): '''A generic method to make POST requests on the given URI.''' return requests.post( urlparse.urljoin(self.BASE_URL, uri), params=params, data=json.dumps(data), verify=False, auth=self.auth, headers = {'Content-type': 'applicat...
[ "def", "post", "(", "self", ",", "uri", ",", "params", "=", "{", "}", ",", "data", "=", "{", "}", ")", ":", "return", "requests", ".", "post", "(", "urlparse", ".", "urljoin", "(", "self", ".", "BASE_URL", ",", "uri", ")", ",", "params", "=", "...
58.333333
0.014085
def set_defaults(self, config_file): """Set defaults. """ self.defaults = Defaults(config_file) self.locations = Locations(self.defaults) self.python = Python() self.setuptools = Setuptools() self.scp = SCP() self.scms = SCMFactory() self.urlparser...
[ "def", "set_defaults", "(", "self", ",", "config_file", ")", ":", "self", ".", "defaults", "=", "Defaults", "(", "config_file", ")", "self", ".", "locations", "=", "Locations", "(", "self", ".", "defaults", ")", "self", ".", "python", "=", "Python", "(",...
35.392857
0.001965
def reducePrecision(element): """ Because opacities, letter spacings, stroke widths and all that don't need to be preserved in SVG files with 9 digits of precision. Takes all of these attributes, in the given element node and its children, and reduces their precision to the current Decimal context'...
[ "def", "reducePrecision", "(", "element", ")", ":", "num", "=", "0", "styles", "=", "_getStyle", "(", "element", ")", "for", "lengthAttr", "in", "[", "'opacity'", ",", "'flood-opacity'", ",", "'fill-opacity'", ",", "'stroke-opacity'", ",", "'stop-opacity'", ",...
41.659091
0.001599
def save(self, filename): """Pickle the whole collection to *filename*. If no extension is provided, ".collection" is appended. """ cPickle.dump(self, open(self._canonicalize(filename), 'wb'), protocol=cPickle.HIGHEST_PROTOCOL)
[ "def", "save", "(", "self", ",", "filename", ")", ":", "cPickle", ".", "dump", "(", "self", ",", "open", "(", "self", ".", "_canonicalize", "(", "filename", ")", ",", "'wb'", ")", ",", "protocol", "=", "cPickle", ".", "HIGHEST_PROTOCOL", ")" ]
40.571429
0.013793
def select(data, field_name): """ return list with values from field_name """ if isinstance(data, Cube): return data._select(_normalize_selects(field_name)) if isinstance(data, PartFlatList): return data.select(field_name) if isinstance(data, UniqueIndex): data = ( ...
[ "def", "select", "(", "data", ",", "field_name", ")", ":", "if", "isinstance", "(", "data", ",", "Cube", ")", ":", "return", "data", ".", "_select", "(", "_normalize_selects", "(", "field_name", ")", ")", "if", "isinstance", "(", "data", ",", "PartFlatLi...
30.309524
0.000761
def backward(self, gradient, image=None, strict=True): """Interface to model.backward for attacks. Parameters ---------- gradient : `numpy.ndarray` Gradient of some loss w.r.t. the logits. image : `numpy.ndarray` Single input with shape as expected by the...
[ "def", "backward", "(", "self", ",", "gradient", ",", "image", "=", "None", ",", "strict", "=", "True", ")", ":", "assert", "self", ".", "has_gradient", "(", ")", "assert", "gradient", ".", "ndim", "==", "1", "if", "image", "is", "None", ":", "image"...
25.823529
0.002195
def make_traverser(cls, source_data, target_data, relation_operation, accessor=None, manage_back_references=True): """ Factory method to create a tree traverser depending on the input source and target data combination. :param source_data: Source data. :pa...
[ "def", "make_traverser", "(", "cls", ",", "source_data", ",", "target_data", ",", "relation_operation", ",", "accessor", "=", "None", ",", "manage_back_references", "=", "True", ")", ":", "reg", "=", "get_current_registry", "(", ")", "prx_fac", "=", "reg", "."...
52.298851
0.001941
def build(self, backend=None): '''Set up the model for sampling/fitting. Performs any steps that require access to all model terms (e.g., scaling priors on each term), then calls the BackEnd's build() method. Args: backend (str): The name of the backend to use for model fit...
[ "def", "build", "(", "self", ",", "backend", "=", "None", ")", ":", "# retain only the complete cases", "n_total", "=", "len", "(", "self", ".", "data", ".", "index", ")", "if", "len", "(", "self", ".", "completes", ")", ":", "completes", "=", "[", "se...
42.731707
0.000558
def rm(*components, **kwargs): """ Remove a file or directory. If path is a directory, this recursively removes the directory and any contents. Non-existent paths are silently ignored. Supports Unix style globbing by default (disable using glob=False). For details on globbing pattern expansion...
[ "def", "rm", "(", "*", "components", ",", "*", "*", "kwargs", ")", ":", "_path", "=", "path", "(", "*", "components", ")", "glob", "=", "kwargs", ".", "get", "(", "\"glob\"", ",", "True", ")", "paths", "=", "iglob", "(", "_path", ")", "if", "glob...
32.962963
0.001092
def main(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the homework assignment.""" parser = ArgumentParser(description="Convert Jupyter Notebook assignments to PDFs") parser.add_argument( "--hw", type=int, required=True, help="Homework number t...
[ "def", "main", "(", "argv", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", "=", "None", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Convert Jupyter Notebook assignments to PDFs\"", ")", "parser", ".", "add_argu...
30
0.002307
def index(): """main functionality of webserver""" default = ["pagan", "python", "avatar", "github"] slogan = request.forms.get("slogan") if not slogan: if request.get_cookie("hist1"): slogan = request.get_cookie("hist1") else: slogan = "pagan" if not reques...
[ "def", "index", "(", ")", ":", "default", "=", "[", "\"pagan\"", ",", "\"python\"", ",", "\"avatar\"", ",", "\"github\"", "]", "slogan", "=", "request", ".", "forms", ".", "get", "(", "\"slogan\"", ")", "if", "not", "slogan", ":", "if", "request", ".",...
37.744186
0.000601
def get_file_str(path, saltenv='base'): ''' Download a file from a URL to the Minion cache directory and return the contents of that file Returns ``False`` if Salt was unable to cache a file from a URL. CLI Example: .. code-block:: bash salt '*' cp.get_file_str salt://my/file '''...
[ "def", "get_file_str", "(", "path", ",", "saltenv", "=", "'base'", ")", ":", "fn_", "=", "cache_file", "(", "path", ",", "saltenv", ")", "if", "isinstance", "(", "fn_", ",", "six", ".", "string_types", ")", ":", "try", ":", "with", "salt", ".", "util...
26.047619
0.001764
def install_host(use_threaded_wrapper): """Install required components into supported hosts An unsupported host will still run, but may encounter issues, especially with threading. """ for install in (_install_maya, _install_houdini, _install_nuke, ...
[ "def", "install_host", "(", "use_threaded_wrapper", ")", ":", "for", "install", "in", "(", "_install_maya", ",", "_install_houdini", ",", "_install_nuke", ",", "_install_nukeassist", ",", "_install_hiero", ",", "_install_nukestudio", ",", "_install_blender", ")", ":",...
27.619048
0.001667
def add_alias(self, alias: sym.Symbol, namespace: "Namespace") -> None: """Add a Symbol alias for the given Namespace.""" self._aliases.swap(lambda m: m.assoc(alias, namespace))
[ "def", "add_alias", "(", "self", ",", "alias", ":", "sym", ".", "Symbol", ",", "namespace", ":", "\"Namespace\"", ")", "->", "None", ":", "self", ".", "_aliases", ".", "swap", "(", "lambda", "m", ":", "m", ".", "assoc", "(", "alias", ",", "namespace"...
63.666667
0.010363
def p_lvalue_one(self, p): 'lvalue : identifier' p[0] = Lvalue(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_lvalue_one", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Lvalue", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", ...
34.5
0.014184
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
[ "def", "permissions", "(", "self", ",", "actor", ",", "inherited", "=", "None", ")", ":", "if", "inherited", "is", "not", "None", ":", "return", "inherited", "|", "super", "(", "BaseScopedNameMixin", ",", "self", ")", ".", "permissions", "(", "actor", ")...
52.9
0.009294
def markdown(text, mode='', context='', raw=False): """Render an arbitrary markdown document. :param str text: (required), the text of the document to render :param str mode: (optional), 'markdown' or 'gfm' :param str context: (optional), only important when using mode 'gfm', this is the reposi...
[ "def", "markdown", "(", "text", ",", "mode", "=", "''", ",", "context", "=", "''", ",", "raw", "=", "False", ")", ":", "return", "gh", ".", "markdown", "(", "text", ",", "mode", ",", "context", ",", "raw", ")" ]
42.153846
0.001786
def addhash(frame,**kw): ''' helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be add...
[ "def", "addhash", "(", "frame", ",", "*", "*", "kw", ")", ":", "hashes", "=", "genhash", "(", "frame", ",", "*", "*", "kw", ")", "frame", "[", "'data'", "]", "=", "rfn", ".", "rec_append_fields", "(", "frame", "[", "'data'", "]", ",", "'hash'", "...
22.9
0.018868
def parse_site(sample, convention, Z): """ parse the site name from the sample name using the specified convention """ convention = str(convention) site = sample # default is that site = sample # # # Sample is final letter on site designation eg: TG001a (used by SIO lab # in San Diego) if conv...
[ "def", "parse_site", "(", "sample", ",", "convention", ",", "Z", ")", ":", "convention", "=", "str", "(", "convention", ")", "site", "=", "sample", "# default is that site = sample", "#", "#", "# Sample is final letter on site designation eg: TG001a (used by SIO lab", ...
27.897959
0.000707
def integrate_calib(name,chan_per_coarse,fullstokes=False,**kwargs): ''' Folds Stokes I noise diode data and integrates along coarse channels Parameters ---------- name : str Path to noise diode filterbank file chan_per_coarse : int Number of frequency bins per coarse channel ...
[ "def", "integrate_calib", "(", "name", ",", "chan_per_coarse", ",", "fullstokes", "=", "False", ",", "*", "*", "kwargs", ")", ":", "#Load data", "obs", "=", "Waterfall", "(", "name", ",", "max_load", "=", "150", ")", "data", "=", "obs", ".", "data", "#...
29.804348
0.024718
def _status_filter_to_query(clause): """ Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as...
[ "def", "_status_filter_to_query", "(", "clause", ")", ":", "if", "clause", "[", "\"value\"", "]", "==", "\"RUNNING\"", ":", "mongo_clause", "=", "MongoRunDAO", ".", "RUNNING_NOT_DEAD_CLAUSE", "elif", "clause", "[", "\"value\"", "]", "==", "\"DEAD\"", ":", "mongo...
41.65
0.002347
def name(self): """ Return the String assosciated with the tag name """ if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG): return u'' return self.sb[self.m_name]
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "m_name", "==", "-", "1", "or", "(", "self", ".", "m_event", "!=", "const", ".", "START_TAG", "and", "self", ".", "m_event", "!=", "const", ".", "END_TAG", ")", ":", "return", "u''", "return"...
31.125
0.011719
def apply_flow(self, flowrate): r""" Convert the invaded sequence into an invaded time for a given flow rate considering the volume of invaded pores and throats. Parameters ---------- flowrate : float The flow rate of the injected fluid Returns ...
[ "def", "apply_flow", "(", "self", ",", "flowrate", ")", ":", "net", "=", "self", ".", "project", ".", "network", "P12", "=", "net", "[", "'throat.conns'", "]", "aa", "=", "self", "[", "'throat.invasion_sequence'", "]", "bb", "=", "sp", ".", "argsort", ...
38.486486
0.00137
def _updated(self, url, payload, template=None): """ Generic call to see if a template request returns 304 accepts: - a string to combine with the API endpoint - a dict of format values, in case they're required by 'url' - a template name to check for As per the A...
[ "def", "_updated", "(", "self", ",", "url", ",", "payload", ",", "template", "=", "None", ")", ":", "# If the template is more than an hour old, try a 304", "if", "(", "abs", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tz...
39.333333
0.001378
def proto_0203(theABF): """protocol: vast IV.""" abf=ABF(theABF) abf.log.info("analyzing as a fast IV") plot=ABFplot(abf) plot.title="" m1,m2=.7,1 plt.figure(figsize=(SQUARESIZE,SQUARESIZE/2)) plt.subplot(121) plot.figure_sweeps() plt.axvspan(m1,m2,color='r',ec=None,alpha=.1) ...
[ "def", "proto_0203", "(", "theABF", ")", ":", "abf", "=", "ABF", "(", "theABF", ")", "abf", ".", "log", ".", "info", "(", "\"analyzing as a fast IV\"", ")", "plot", "=", "ABFplot", "(", "abf", ")", "plot", ".", "title", "=", "\"\"", "m1", ",", "m2", ...
25.7
0.035
def json_struct_to_xml(json_obj, root, custom_namespace=None): """Converts a Open511 JSON fragment to XML. Takes a dict deserialized from JSON, returns an lxml Element. This won't provide a conforming document if you pass in a full JSON document; it's for translating little fragments, and is mostly us...
[ "def", "json_struct_to_xml", "(", "json_obj", ",", "root", ",", "custom_namespace", "=", "None", ")", ":", "if", "isinstance", "(", "root", ",", "(", "str", ",", "unicode", ")", ")", ":", "if", "root", ".", "startswith", "(", "'!'", ")", ":", "root", ...
42.408163
0.002352
def from_buffer(obj): """Return ``(pointer_address, length_in_bytes)`` for a buffer object.""" if hasattr(obj, 'buffer_info'): # Looks like a array.array object. address, length = obj.buffer_info() return address, length * obj.itemsize else: # Other buffers. # XXX Unf...
[ "def", "from_buffer", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'buffer_info'", ")", ":", "# Looks like a array.array object.", "address", ",", "length", "=", "obj", ".", "buffer_info", "(", ")", "return", "address", ",", "length", "*", "obj",...
45.769231
0.001647
def save_config( self, cmd="copy running-configuration startup-configuration", confirm=False, confirm_response="", ): """Saves Config""" return super(DellForce10SSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
[ "def", "save_config", "(", "self", ",", "cmd", "=", "\"copy running-configuration startup-configuration\"", ",", "confirm", "=", "False", ",", "confirm_response", "=", "\"\"", ",", ")", ":", "return", "super", "(", "DellForce10SSH", ",", "self", ")", ".", "save_...
30.9
0.009434
def _comparison_helper( a: "BitVecFunc", b: Union[BitVec, int], operation: Callable, default_value: bool, inputs_equal: bool, ) -> Bool: """ Helper function for comparison operations with BitVecFuncs. :param a: The BitVecFunc to compare. :param b: A BitVec or int to compare to. ...
[ "def", "_comparison_helper", "(", "a", ":", "\"BitVecFunc\"", ",", "b", ":", "Union", "[", "BitVec", ",", "int", "]", ",", "operation", ":", "Callable", ",", "default_value", ":", "bool", ",", "inputs_equal", ":", "bool", ",", ")", "->", "Bool", ":", "...
29.194444
0.000921
def chown(path, user, group): ''' Chown a file, pass the file the desired user and group path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/passwd root root ''' path = o...
[ "def", "chown", "(", "path", ",", "user", ",", "group", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "uid", "=", "user_to_uid", "(", "user", ")", "gid", "=", "group_to_gid", "(", "group", ")", "err", "=", "''", "...
20.659091
0.00105
def create_with_secret(self, name, secret, encryption): """Creates a new user on the local node Args: name (str): The name of the user to craete secret (str): The secret (password) to assign to this user encryption (str): Specifies how the secret is encoded. Valid...
[ "def", "create_with_secret", "(", "self", ",", "name", ",", "secret", ",", "encryption", ")", ":", "try", ":", "encryption", "=", "encryption", "or", "DEFAULT_ENCRYPTION", "enc", "=", "ENCRYPTION_MAP", "[", "encryption", "]", "except", "KeyError", ":", "raise"...
35.5
0.002286
def k_value_reduction(ent_pipe_id, exit_pipe_id, q, fitting_angle=180, rounded=False, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH): """Calculates the minor loss coefficient (k-value) of a square, tapered, or rounded reduction in a pipe. Defaults to square. To...
[ "def", "k_value_reduction", "(", "ent_pipe_id", ",", "exit_pipe_id", ",", "q", ",", "fitting_angle", "=", "180", ",", "rounded", "=", "False", ",", "nu", "=", "con", ".", "WATER_NU", ",", "pipe_rough", "=", "mats", ".", "PVC_PIPE_ROUGH", ")", ":", "if", ...
43.553191
0.001911
def get_cmd(self): """ This function combines and return the commanline call of the program. """ cmd = [] if self.path is not None: if '/' in self.path and not os.path.exists(self.path): debug.log('Error: path contains / but does not exist: %s'%self.path) else: ...
[ "def", "get_cmd", "(", "self", ")", ":", "cmd", "=", "[", "]", "if", "self", ".", "path", "is", "not", "None", ":", "if", "'/'", "in", "self", ".", "path", "and", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "d...
45.653846
0.018977
def strictjoin(L, keycols, nullvals=None, renaming=None, Names=None): """ Combine two or more numpy ndarray with structured dtypes on common key column(s). Merge a list (or dictionary) of numpy arrays, given by `L`, on key columns listed in `keycols`. The ``strictjoin`` assumes the following ...
[ "def", "strictjoin", "(", "L", ",", "keycols", ",", "nullvals", "=", "None", ",", "renaming", "=", "None", ",", "Names", "=", "None", ")", ":", "if", "isinstance", "(", "L", ",", "dict", ")", ":", "Names", "=", "L", ".", "keys", "(", ")", "LL", ...
36.491713
0.008696
def _dispatch(self, func, args=None): """Send message to parent process Arguments: func (str): Name of function for parent to call args (list, optional): Arguments passed to function when called """ data = json.dumps( { "header": "py...
[ "def", "_dispatch", "(", "self", ",", "func", ",", "args", "=", "None", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "\"header\"", ":", "\"pyblish-qml:popen.request\"", ",", "\"payload\"", ":", "{", "\"name\"", ":", "func", ",", "\"args\"", ":"...
30.093023
0.001497
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
[ "def", "get_follows", "(", "self", ",", "model_or_obj_or_qs", ")", ":", "fname", "=", "self", ".", "fname", "(", "model_or_obj_or_qs", ")", "if", "isinstance", "(", "model_or_obj_or_qs", ",", "QuerySet", ")", ":", "return", "self", ".", "filter", "(", "*", ...
36.153846
0.012448
def get_all_recurrings(self, params=None): """ Get all recurrings This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list """ ...
[ "def", "get_all_recurrings", "(", "self", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "return", "self", ".", "_iterate_through_pages", "(", "self", ".", "get_recurrings_per_page", ",", "resource", "=", "RECURRIN...
38.666667
0.008421
def _collection_literal_to_py_ast( ctx: GeneratorContext, form: Iterable[LispForm] ) -> Iterable[GeneratedPyAST]: """Turn a quoted collection literal of Lisp forms into Python AST nodes. This function can only handle constant values. It does not call back into the generic AST generators, so only consta...
[ "def", "_collection_literal_to_py_ast", "(", "ctx", ":", "GeneratorContext", ",", "form", ":", "Iterable", "[", "LispForm", "]", ")", "->", "Iterable", "[", "GeneratedPyAST", "]", ":", "yield", "from", "map", "(", "partial", "(", "_const_val_to_py_ast", ",", "...
47
0.00232
def to_Fastq(self, qual_scores): '''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file''' if len(self) != len(qual_scores): raise Error('Error making Fastq from Fasta, lengths differ.', self.id) return Fastq(self.id, self.seq, ''....
[ "def", "to_Fastq", "(", "self", ",", "qual_scores", ")", ":", "if", "len", "(", "self", ")", "!=", "len", "(", "qual_scores", ")", ":", "raise", "Error", "(", "'Error making Fastq from Fasta, lengths differ.'", ",", "self", ".", "id", ")", "return", "Fastq",...
74.8
0.013228
def __adjustStopOrder(self, tick): ''' update stop order if needed ''' if not self.__stopOrderId: return if self.__stopOrder.action == Action.SELL: orgStopPrice=self.__buyOrder.price * 0.95 newStopPrice=max(((tick.close + orgStopPrice) / 2), tick.close * 0.85...
[ "def", "__adjustStopOrder", "(", "self", ",", "tick", ")", ":", "if", "not", "self", ".", "__stopOrderId", ":", "return", "if", "self", ".", "__stopOrder", ".", "action", "==", "Action", ".", "SELL", ":", "orgStopPrice", "=", "self", ".", "__buyOrder", "...
49.685714
0.009024
def translate_key_val(val, delimiter='='): ''' CLI input is a list of key/val pairs, but the API expects a dictionary in the format {key: val} ''' if isinstance(val, dict): return val val = translate_stringlist(val) new_val = {} for item in val: try: lvalue, r...
[ "def", "translate_key_val", "(", "val", ",", "delimiter", "=", "'='", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "return", "val", "val", "=", "translate_stringlist", "(", "val", ")", "new_val", "=", "{", "}", "for", "item", "in", ...
31.833333
0.001695
def disable_nn_ha(self, active_name, snn_host_id, snn_check_point_dir_list, snn_name=None): """ Disable high availability with automatic failover for an HDFS NameNode. @param active_name: Name of the NamdeNode role that is going to be active after High Availability is disabled...
[ "def", "disable_nn_ha", "(", "self", ",", "active_name", ",", "snn_host_id", ",", "snn_check_point_dir_list", ",", "snn_name", "=", "None", ")", ":", "args", "=", "dict", "(", "activeNnName", "=", "active_name", ",", "snnHostId", "=", "snn_host_id", ",", "snnC...
43.809524
0.01383
def _raw_predict(self, Xnew=None, Ynew=None, filteronly=False, p_balance=False, **kw): """ Performs the actual prediction for new X points. Inner function. It is called only from inside this class. Input: --------------------- Xnews: vector or (n_points,1) matrix ...
[ "def", "_raw_predict", "(", "self", ",", "Xnew", "=", "None", ",", "Ynew", "=", "None", ",", "filteronly", "=", "False", ",", "p_balance", "=", "False", ",", "*", "*", "kw", ")", ":", "# Set defaults", "if", "Ynew", "is", "None", ":", "Ynew", "=", ...
37.844037
0.017482
def get_array_shape(self, key): """Return array's shape""" data = self.model.get_data() return data[key].shape
[ "def", "get_array_shape", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "return", "data", "[", "key", "]", ".", "shape" ]
33.5
0.014599
def remove(self): """Detach this element from his father.""" if self._own_index is not None and self.parent: self.parent.pop(self._own_index) return self
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "_own_index", "is", "not", "None", "and", "self", ".", "parent", ":", "self", ".", "parent", ".", "pop", "(", "self", ".", "_own_index", ")", "return", "self" ]
37
0.010582
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:...
[ "def", "mac2eui64", "(", "mac", ",", "prefix", "=", "None", ")", ":", "# http://tools.ietf.org/html/rfc4291#section-2.5.1", "eui64", "=", "re", ".", "sub", "(", "r'[.:-]'", ",", "''", ",", "mac", ")", ".", "lower", "(", ")", "eui64", "=", "eui64", "[", "...
34.526316
0.001484
def get_offset_from_rva(self, rva): """Get the file offset corresponding to this RVA. Given a RVA , this method will find the section where the data lies and return the offset within the file. """ s = self.get_section_by_rva(rva) if not s: #...
[ "def", "get_offset_from_rva", "(", "self", ",", "rva", ")", ":", "s", "=", "self", ".", "get_section_by_rva", "(", "rva", ")", "if", "not", "s", ":", "# If not found within a section assume it might", "# point to overlay data or otherwise data present", "# but not contain...
36.7
0.011952
def avail_images(call=None): ''' Return a dict of all available images on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) compconn = get_co...
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_images function must be called with '", "'-f or --function, or with the --list-images option'", ")", "compconn", "=", "get_conn",...
34.802632
0.000368
def set_log_stdout(): """ 设置输出到标准输出中 :param: 无 :return: 无 举例如下:: from fishbase.fish_logger import * set_log_stdout() logger.info('test fish base log') logger.warn('test fish base log') logger.error('test fish base log') print('log ok') """ ...
[ "def", "set_log_stdout", "(", ")", ":", "_formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s %(levelname)s %(filename)s[ln:%(lineno)d] %(message)s'", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "stdout_handler", "=", "logging", ".",...
21.37037
0.001658
def live_streaming(self): """Return live streaming generator.""" url = STREAM_ENDPOINT # override params params = STREAMING_BODY params['from'] = "{0}_web".format(self.user_id) params['to'] = self.device_id params['resource'] = "cameras/{0}".format(self.device_id...
[ "def", "live_streaming", "(", "self", ")", ":", "url", "=", "STREAM_ENDPOINT", "# override params", "params", "=", "STREAMING_BODY", "params", "[", "'from'", "]", "=", "\"{0}_web\"", ".", "format", "(", "self", ".", "user_id", ")", "params", "[", "'to'", "]"...
35.222222
0.002047
def get_buckets(self, transport, bucket_type=None, timeout=None): """ get_buckets(bucket_type=None, timeout=None) Get the list of buckets as :class:`RiakBucket <riak.bucket.RiakBucket>` instances. .. warning:: Do not use this in production, as it requires traversing ...
[ "def", "get_buckets", "(", "self", ",", "transport", ",", "bucket_type", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "not", "riak", ".", "disable_list_exceptions", ":", "raise", "ListError", "(", ")", "_validate_timeout", "(", "timeout", ")", ...
36.878788
0.001601
def monitor(app, endpoint_type='url:1', get_endpoint_fn=None, latency_buckets=None, mmc_period_sec=30, multiprocess_mode='all'): """ Regiesters a bunch of metrics for Sanic server (request latency, count, etc) and exposes /metrics endpoint to allow Prometh...
[ "def", "monitor", "(", "app", ",", "endpoint_type", "=", "'url:1'", ",", "get_endpoint_fn", "=", "None", ",", "latency_buckets", "=", "None", ",", "mmc_period_sec", "=", "30", ",", "multiprocess_mode", "=", "'all'", ")", ":", "multiprocess_on", "=", "'promethe...
43.75
0.000294
def getFTPs(accessions, ftp, search, exclude, convert = False, threads = 1, attempt = 1, max_attempts = 2): """ download genome info from NCBI """ info = wget(ftp)[0] allMatches = [] for genome in open(info, encoding = 'utf8'): genome = str(genome) matches, genomeInfo...
[ "def", "getFTPs", "(", "accessions", ",", "ftp", ",", "search", ",", "exclude", ",", "convert", "=", "False", ",", "threads", "=", "1", ",", "attempt", "=", "1", ",", "max_attempts", "=", "2", ")", ":", "info", "=", "wget", "(", "ftp", ")", "[", ...
38.815789
0.012566
def running(processid): """Check the validity of a process ID. Arguments: processid (int): Process ID number. Returns: True if process ID is found otherwise False. """ try: # From kill(2) # If sig is 0 (the null signal), error checking is performed but no ...
[ "def", "running", "(", "processid", ")", ":", "try", ":", "# From kill(2)", "# If sig is 0 (the null signal), error checking is performed but no", "# signal is actually sent. The null signal can be used to check the", "# validity of pid", "os", ".", "kill", "(", "processid", ...
27.333333
0.001473
def get_go2obj(self, goids): """Return GO Terms for each user-specified GO ID. Note missing GO IDs.""" goids = goids.intersection(self.go2obj.keys()) if len(goids) != len(goids): goids_missing = goids.difference(goids) print(" {N} MISSING GO IDs: {GOs}".format(N=len(goid...
[ "def", "get_go2obj", "(", "self", ",", "goids", ")", ":", "goids", "=", "goids", ".", "intersection", "(", "self", ".", "go2obj", ".", "keys", "(", ")", ")", "if", "len", "(", "goids", ")", "!=", "len", "(", "goids", ")", ":", "goids_missing", "=",...
56.714286
0.012407
def save(self): ''' Persists this object to the database. Each field knows how to store itself so we don't have to worry about it ''' redis = type(self).get_redis() pipe = to_pipeline(redis) pipe.hset(self.key(), 'id', self.id) for fieldname, field in self.proxy: ...
[ "def", "save", "(", "self", ")", ":", "redis", "=", "type", "(", "self", ")", ".", "get_redis", "(", ")", "pipe", "=", "to_pipeline", "(", "redis", ")", "pipe", ".", "hset", "(", "self", ".", "key", "(", ")", ",", "'id'", ",", "self", ".", "id"...
30.407407
0.002361
def get_or_create_exh_obj(full_cname=False, exclude=None, callables_fname=None): r""" Return global exception handler if set, otherwise create a new one and return it. :param full_cname: Flag that indicates whether fully qualified function/method/class property names are obtained for...
[ "def", "get_or_create_exh_obj", "(", "full_cname", "=", "False", ",", "exclude", "=", "None", ",", "callables_fname", "=", "None", ")", ":", "if", "not", "hasattr", "(", "__builtin__", ",", "\"_EXH\"", ")", ":", "set_exh_obj", "(", "ExHandle", "(", "full_cna...
41.913043
0.002027
def _get_stddevs(self, rup, arias, stddev_types, sites): """ Return standard deviations as defined in table 1, p. 200. """ stddevs = [] # Magnitude dependent inter-event term (Eq. 13) if rup.mag < 4.7: tau = 0.611 elif rup.mag > 7.6: tau = ...
[ "def", "_get_stddevs", "(", "self", ",", "rup", ",", "arias", ",", "stddev_types", ",", "sites", ")", ":", "stddevs", "=", "[", "]", "# Magnitude dependent inter-event term (Eq. 13)", "if", "rup", ".", "mag", "<", "4.7", ":", "tau", "=", "0.611", "elif", "...
38.588235
0.001487
def search(self, query, **kwargs): """ Cruddy provides a limited but useful interface to search GSI indexes in DynamoDB with the following limitations (hopefully some of these will be expanded or eliminated in the future. * The GSI must be configured with a only HASH and not a R...
[ "def", "search", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_new_response", "(", ")", "if", "self", ".", "_check_supported_op", "(", "'search'", ",", "response", ")", ":", "if", "'='", "not", "in", "q...
47.471698
0.000779
def put (self, ch): '''This puts a characters at the current cursor position. ''' if isinstance(ch, bytes): ch = self._decode(ch) self.put_abs (self.cur_r, self.cur_c, ch)
[ "def", "put", "(", "self", ",", "ch", ")", ":", "if", "isinstance", "(", "ch", ",", "bytes", ")", ":", "ch", "=", "self", ".", "_decode", "(", "ch", ")", "self", ".", "put_abs", "(", "self", ".", "cur_r", ",", "self", ".", "cur_c", ",", "ch", ...
26.25
0.018433
def get_huc8(prefix): """ Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath) """ if not prefix.isdigit(): # Look up hucs by name name = prefix prefix = None for row in hucs: if row.basin.lower() == name.lower(): ...
[ "def", "get_huc8", "(", "prefix", ")", ":", "if", "not", "prefix", ".", "isdigit", "(", ")", ":", "# Look up hucs by name", "name", "=", "prefix", "prefix", "=", "None", "for", "row", "in", "hucs", ":", "if", "row", ".", "basin", ".", "lower", "(", "...
28.958333
0.001393
def sort_by_abundance_usearch61(seq_path, output_dir='.', rev=False, minlen=64, remove_usearch_logs=False, HALT_EXEC=False, outp...
[ "def", "sort_by_abundance_usearch61", "(", "seq_path", ",", "output_dir", "=", "'.'", ",", "rev", "=", "False", ",", "minlen", "=", "64", ",", "remove_usearch_logs", "=", "False", ",", "HALT_EXEC", "=", "False", ",", "output_fna_filepath", "=", "None", ",", ...
39.076923
0.00048
def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins are fully loaded so that Image.EXTENSION is populated. Image.init() format = Image.EXTENSION.get...
[ "def", "save_image", "(", "image", ",", "destination", "=", "None", ",", "filename", "=", "None", ",", "*", "*", "options", ")", ":", "if", "destination", "is", "None", ":", "destination", "=", "BytesIO", "(", ")", "filename", "=", "filename", "or", "'...
40.857143
0.000683
def get_contents_entry(node): """Fetch the contents of the entry. Returns the exact binary contents of the file.""" try: node = node.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Ent...
[ "def", "get_contents_entry", "(", "node", ")", ":", "try", ":", "node", "=", "node", ".", "disambiguate", "(", "must_exist", "=", "1", ")", "except", "SCons", ".", "Errors", ".", "UserError", ":", "# There was nothing on disk with which to disambiguate", "# this e...
41.714286
0.001675
def read_features(self, tol=1e-3): """Reads the features from a file and stores them in the current object. Parameters ---------- tol: float Tolerance level to detect duration of audio. """ try: # Read JSON file with open(self....
[ "def", "read_features", "(", "self", ",", "tol", "=", "1e-3", ")", ":", "try", ":", "# Read JSON file", "with", "open", "(", "self", ".", "file_struct", ".", "features_file", ")", "as", "f", ":", "feats", "=", "json", ".", "load", "(", "f", ")", "# S...
45.445946
0.000873
def _pprint_fasta(fasta, annotations=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print each record in the FASTA file. """ annotations = annotations or [] # Annotations by chromosome. as_by_chrom = collections.defaultdict(lambda: [a for a in anno...
[ "def", "_pprint_fasta", "(", "fasta", ",", "annotations", "=", "None", ",", "annotation_file", "=", "None", ",", "block_length", "=", "10", ",", "blocks_per_line", "=", "6", ")", ":", "annotations", "=", "annotations", "or", "[", "]", "# Annotations by chromos...
40.6
0.002407
def upload_freesurfer_archive(self, filename, object_identifier=None, read_only=False): """Create an anatomy object on local disk from a Freesurfer anatomy tar file. If the given file is a Freesurfer file it will be copied to the created subject's upload directory. Parameters --...
[ "def", "upload_freesurfer_archive", "(", "self", ",", "filename", ",", "object_identifier", "=", "None", ",", "read_only", "=", "False", ")", ":", "# At this point we expect the file to be a (compressed) tar archive.", "# Extract the archive contents into a new temporary directory"...
44.191011
0.002238
def dot(self, other): """ Compute the dot product of two Vectors. We support (Numpy array, list, SparseVector, or SciPy sparse) and a target NumPy array that is either 1- or 2-dimensional. Equivalent to calling numpy.dot of the two vectors. >>> dense = DenseVector(array....
[ "def", "dot", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "==", "np", ".", "ndarray", ":", "if", "other", ".", "ndim", ">", "1", ":", "assert", "len", "(", "self", ")", "==", "other", ".", "shape", "[", "0", "]", ","...
39.285714
0.001183
def cross_validate(data=None, folds=5, repeat=1, metrics=None, reporters=None, model_def=None, **kwargs): """Shortcut to cross-validate a single configuration. ModelDefinition variables are passed in as keyword args, along with the cross-validation parameters. """ md_kwargs = {} ...
[ "def", "cross_validate", "(", "data", "=", "None", ",", "folds", "=", "5", ",", "repeat", "=", "1", ",", "metrics", "=", "None", ",", "reporters", "=", "None", ",", "model_def", "=", "None", ",", "*", "*", "kwargs", ")", ":", "md_kwargs", "=", "{",...
38.863636
0.002283
def CherryPyWSGIServer(bind_addr, wsgi_app, numthreads = 10, server_name = None, max = -1, request_queue_size = 5, timeout = 10, shutdown_timeout = 5): """...
[ "def", "CherryPyWSGIServer", "(", "bind_addr", ",", "wsgi_app", ",", "numthreads", "=", "10", ",", "server_name", "=", "None", ",", "max", "=", "-", "1", ",", "request_queue_size", "=", "5", ",", "timeout", "=", "10", ",", "shutdown_timeout", "=", "5", "...
38.705882
0.031157
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None): """The VAN decoder. Args: x: The analogy information to decode. skip_connections: The encoder layers which can be used as skip connections. output_shape: The shape of the desired output image. first_depth: The depth of th...
[ "def", "van_dec_2d", "(", "x", ",", "skip_connections", ",", "output_shape", ",", "first_depth", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "'van_dec'", ")", ":", "dec", "=", "tf", ".", "layers", ".", "conv2d_transpose...
30.953846
0.002408
async def auto_add(self, device, recursive=None, automount=True): """ Automatically attempt to mount or unlock a device, but be quiet if the device is not supported. :param device: device object, block device path or mount path :param bool recursive: recursively mount and unlock...
[ "async", "def", "auto_add", "(", "self", ",", "device", ",", "recursive", "=", "None", ",", "automount", "=", "True", ")", ":", "device", ",", "created", "=", "await", "self", ".", "_find_device_losetup", "(", "device", ")", "if", "created", "and", "recu...
43.45
0.001125
def cells(self): """A dictionary of dictionaries containing all cells. """ return {row_key: {column_key:cell for column_key, cell in zip(self._column_keys, cells)} for row_key, cells in self._rows_mapping.items()}
[ "def", "cells", "(", "self", ")", ":", "return", "{", "row_key", ":", "{", "column_key", ":", "cell", "for", "column_key", ",", "cell", "in", "zip", "(", "self", ".", "_column_keys", ",", "cells", ")", "}", "for", "row_key", ",", "cells", "in", "self...
49.8
0.01581
async def digital_pin_write(self, pin, value): """ Set the specified pin to the specified value directly without port manipulation. :param pin: pin number :param value: pin value :returns: No return value """ command = (PrivateConstants.SET_DIGITAL_PIN_VALUE, ...
[ "async", "def", "digital_pin_write", "(", "self", ",", "pin", ",", "value", ")", ":", "command", "=", "(", "PrivateConstants", ".", "SET_DIGITAL_PIN_VALUE", ",", "pin", ",", "value", ")", "await", "self", ".", "_send_command", "(", "command", ")" ]
25.785714
0.008021
def rooms_favorite(self, room_id=None, room_name=None, favorite=True): """Favorite or unfavorite room.""" if room_id is not None: return self.__call_api_post('rooms.favorite', roomId=room_id, favorite=favorite) elif room_name is not None: return self.__call_api_post('room...
[ "def", "rooms_favorite", "(", "self", ",", "room_id", "=", "None", ",", "room_name", "=", "None", ",", "favorite", "=", "True", ")", ":", "if", "room_id", "is", "not", "None", ":", "return", "self", ".", "__call_api_post", "(", "'rooms.favorite'", ",", "...
56.875
0.008658
def remove_commented_topic(self, topic_id): """ 删除回复的话题(删除所有自己发布的评论) :param topic_id: 话题ID :return: None """ return [self.remove_comment(topic_id, item['id']) for item in self.list_user_comments(topic_id)]
[ "def", "remove_commented_topic", "(", "self", ",", "topic_id", ")", ":", "return", "[", "self", ".", "remove_comment", "(", "topic_id", ",", "item", "[", "'id'", "]", ")", "for", "item", "in", "self", ".", "list_user_comments", "(", "topic_id", ")", "]" ]
31.875
0.015267
def get_project_pod_spec(volume_mounts, volumes, image, command, args, ports, env_vars=None, env_from=None, container_na...
[ "def", "get_project_pod_spec", "(", "volume_mounts", ",", "volumes", ",", "image", ",", "command", ",", "args", ",", "ports", ",", "env_vars", "=", "None", ",", "env_from", "=", "None", ",", "container_name", "=", "None", ",", "resources", "=", "None", ","...
38.34
0.001017
def modularity_finetune_dir(W, ci=None, gamma=1, seed=None): ''' The optimal community structure is a subdivision of the network into nonoverlapping groups of nodes in a way that maximizes the number of within-group edges, and minimizes the number of between-group edges. The modularity is a statisti...
[ "def", "modularity_finetune_dir", "(", "W", ",", "ci", "=", "None", ",", "gamma", "=", "1", ",", "seed", "=", "None", ")", ":", "rng", "=", "get_rng", "(", "seed", ")", "n", "=", "len", "(", "W", ")", "# number of nodes", "if", "ci", "is", "None", ...
37.02
0.000789
def clone(self, document): ''' Serialize a document, remove its _id, and deserialize as a new object ''' wrapped = document.wrap() if '_id' in wrapped: del wrapped['_id'] return type(document).unwrap(wrapped, session=self)
[ "def", "clone", "(", "self", ",", "document", ")", ":", "wrapped", "=", "document", ".", "wrap", "(", ")", "if", "'_id'", "in", "wrapped", ":", "del", "wrapped", "[", "'_id'", "]", "return", "type", "(", "document", ")", ".", "unwrap", "(", "wrapped"...
28.75
0.033755
def get_source_tags(self, id, **kwargs): # noqa: E501 """Get all tags associated with a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_so...
[ "def", "get_source_tags", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_source_t...
41.857143
0.002225
def compute_zoom_level(bounds, domain, levels): """ Computes a zoom level given a bounds polygon, a polygon of the overall domain and the number of zoom levels to divide the data into. Parameters ---------- bounds: shapely.geometry.Polygon Polygon representing the area of the curren...
[ "def", "compute_zoom_level", "(", "bounds", ",", "domain", ",", "levels", ")", ":", "area_fraction", "=", "min", "(", "bounds", ".", "area", "/", "domain", ".", "area", ",", "1", ")", "return", "int", "(", "min", "(", "round", "(", "np", ".", "log2",...
30.909091
0.001427
def read(self, filenames, encoding=None): """Read and parse a filename or a list of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directo...
[ "def", "read", "(", "self", ",", "filenames", ",", "encoding", "=", "None", ")", ":", "if", "PY2", "and", "isinstance", "(", "filenames", ",", "bytes", ")", ":", "# we allow for a little unholy magic for Python 2 so that", "# people not using unicode_literals can still ...
40.742857
0.00137
def eigh_robust(a, b=None, eigvals=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, check_finite=True): """Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v ...
[ "def", "eigh_robust", "(", "a", ",", "b", "=", "None", ",", "eigvals", "=", "None", ",", "eigvals_only", "=", "False", ",", "overwrite_a", "=", "False", ",", "overwrite_b", "=", "False", ",", "turbo", "=", "True", ",", "check_finite", "=", "True", ")",...
41.666667
0.00034
def lowstate_file_refs(chunks): ''' Create a list of file ref objects to reconcile ''' refs = {} for chunk in chunks: saltenv = 'base' crefs = [] for state in chunk: if state == '__env__': saltenv = chunk[state] elif state == 'saltenv':...
[ "def", "lowstate_file_refs", "(", "chunks", ")", ":", "refs", "=", "{", "}", "for", "chunk", "in", "chunks", ":", "saltenv", "=", "'base'", "crefs", "=", "[", "]", "for", "state", "in", "chunk", ":", "if", "state", "==", "'__env__'", ":", "saltenv", ...
28.571429
0.001613
def process_result(result): """ Process a result object by: 1. Saving the lyrics to the corresponding file(if applicable). 2. Printing the lyrics or the corresponding error/success message. 3. Returning a boolean indicating if the lyrics were found or not. """ found = result.sour...
[ "def", "process_result", "(", "result", ")", ":", "found", "=", "result", ".", "source", "is", "not", "None", "if", "found", ":", "if", "hasattr", "(", "result", ".", "song", ",", "'filename'", ")", ":", "audiofile", "=", "eyed3", ".", "load", "(", "...
35.958333
0.001129
def get_trim_index(biased_list): """Returns the trim index from a ``bool`` list Provided with a list of ``bool`` elements (``[False, False, True, True]``), this function will assess the index of the list that minimizes the number of True elements (biased positions) at the extremities. To do so, it ...
[ "def", "get_trim_index", "(", "biased_list", ")", ":", "# Return index 0 if there are no biased positions", "if", "set", "(", "biased_list", ")", "==", "{", "False", "}", ":", "return", "0", "if", "set", "(", "biased_list", "[", ":", "5", "]", ")", "==", "{"...
36.54
0.000533
def get_basic_logger(clevel='WARNING',flevel='DEBUG', style="default",filename=None,filemode='w'): """ Return a basic logger via a log file and/or terminal. Example 1: log only to the console, accepting levels "INFO" and above >>> logger = utils.get_basic_logger() Example 2: ...
[ "def", "get_basic_logger", "(", "clevel", "=", "'WARNING'", ",", "flevel", "=", "'DEBUG'", ",", "style", "=", "\"default\"", ",", "filename", "=", "None", ",", "filemode", "=", "'w'", ")", ":", "name", "=", "\"\"", "#-- define formats", "if", "style", "=="...
32.947368
0.008375
def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize: "Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`." if crop_target is None: return None ch,r,c = img.shape target_r,target_c = crop_target ratio = (min if do_crop else max)(r/target_r, c/target_c) ret...
[ "def", "_get_resize_target", "(", "img", ",", "crop_target", ",", "do_crop", "=", "False", ")", "->", "TensorImageSize", ":", "if", "crop_target", "is", "None", ":", "return", "None", "ch", ",", "r", ",", "c", "=", "img", ".", "shape", "target_r", ",", ...
51.428571
0.021858
def parse_xdot_label_directive(self, new): """ Parses the label drawing directive, updating the label components. """ components = XdotAttrParser().parse_xdot_data(new) pos_x = min( [c.x for c in components] ) pos_y = min( [c.y for c in components] ) move_to...
[ "def", "parse_xdot_label_directive", "(", "self", ",", "new", ")", ":", "components", "=", "XdotAttrParser", "(", ")", ".", "parse_xdot_data", "(", "new", ")", "pos_x", "=", "min", "(", "[", "c", ".", "x", "for", "c", "in", "components", "]", ")", "pos...
29.722222
0.016304