text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_30_360(self, end): """ implements 30/360 Day Count Convention (4.16(f) 2006 ISDA Definitions) """ start_day = min(self.day, 30) end_day = 30 if (start_day == 30 and end.day == 31) else end.day return (360 * (end.year - self.year) + 30 * (end.month - self.month...
[ "def", "get_30_360", "(", "self", ",", "end", ")", ":", "start_day", "=", "min", "(", "self", ".", "day", ",", "30", ")", "end_day", "=", "30", "if", "(", "start_day", "==", "30", "and", "end", ".", "day", "==", "31", ")", "else", "end", ".", "...
49.714286
22.857143
def update_mandb(self, quiet=True): """Update mandb.""" if not environ.config.UpdateManPath: return print('\nrunning mandb...') cmd = 'mandb %s' % (' -q' if quiet else '') subprocess.Popen(cmd, shell=True).wait()
[ "def", "update_mandb", "(", "self", ",", "quiet", "=", "True", ")", ":", "if", "not", "environ", ".", "config", ".", "UpdateManPath", ":", "return", "print", "(", "'\\nrunning mandb...'", ")", "cmd", "=", "'mandb %s'", "%", "(", "' -q'", "if", "quiet", "...
36.857143
7.857143
def read(self, size): """ Read wrapper. Parameters ---------- size : int Number of bytes to read. """ try: return self.handle.read(size) except (OSError, serial.SerialException): print() print("Piksi disconnec...
[ "def", "read", "(", "self", ",", "size", ")", ":", "try", ":", "return", "self", ".", "handle", ".", "read", "(", "size", ")", "except", "(", "OSError", ",", "serial", ".", "SerialException", ")", ":", "print", "(", ")", "print", "(", "\"Piksi discon...
22.764706
15
def new(params, event_shape=(), validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'IndependentPoisson', [params, event_shape]): params = tf.convert_to_tensor(value=params, name='params') ...
[ "def", "new", "(", "params", ",", "event_shape", "=", "(", ")", ",", "validate_args", "=", "False", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "'IndependentPoisson'", ",", "[", "pa...
44.35
13.65
def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-established!") ...
[ "def", "_run", "(", "self", ")", ":", "self", ".", "_is_running", "=", "True", "network_fail", "=", "False", "try", ":", "while", "self", ".", "_do_run", ":", "try", ":", "if", "network_fail", "is", "True", ":", "LOGGER", ".", "info", "(", "\"Network c...
36.416667
11.958333
def event_return(events): ''' Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully. ''' _options = _get_options() api_url = _options.get('api_url') channel = _options.get('channel') username = _optio...
[ "def", "event_return", "(", "events", ")", ":", "_options", "=", "_get_options", "(", ")", "api_url", "=", "_options", ".", "get", "(", "'api_url'", ")", "channel", "=", "_options", ".", "get", "(", "'channel'", ")", "username", "=", "_options", ".", "ge...
30
15.466667
def create_xml(self, useNamespace=False): """Create an ElementTree representation of the object.""" UNTL_NAMESPACE = 'http://digital2.library.unt.edu/untl/' UNTL = '{%s}' % UNTL_NAMESPACE NSMAP = {'untl': UNTL_NAMESPACE} if useNamespace: root = Element(UNTL + self.t...
[ "def", "create_xml", "(", "self", ",", "useNamespace", "=", "False", ")", ":", "UNTL_NAMESPACE", "=", "'http://digital2.library.unt.edu/untl/'", "UNTL", "=", "'{%s}'", "%", "UNTL_NAMESPACE", "NSMAP", "=", "{", "'untl'", ":", "UNTL_NAMESPACE", "}", "if", "useNamesp...
35.045455
14.818182
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._action is not None: return F...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_created", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_updated", "is", "not", "None", ...
19.433333
19.233333
def ExpandRelativePath(method_config, params, relative_path=None): """Determine the relative path for request.""" path = relative_path or method_config.relative_path or '' for param in method_config.path_params: param_template = '{%s}' % param # For more details about "reserved word expansi...
[ "def", "ExpandRelativePath", "(", "method_config", ",", "params", ",", "relative_path", "=", "None", ")", ":", "path", "=", "relative_path", "or", "method_config", ".", "relative_path", "or", "''", "for", "param", "in", "method_config", ".", "path_params", ":", ...
44.918919
16
def _theorem5p4(adj, ub): """By Theorem 5.4, if any two vertices have ub + 1 common neighbors then we can add an edge between them. """ new_edges = set() for u, v in itertools.combinations(adj, 2): if u in adj[v]: # already an edge continue if len(adj[u].inte...
[ "def", "_theorem5p4", "(", "adj", ",", "ub", ")", ":", "new_edges", "=", "set", "(", ")", "for", "u", ",", "v", "in", "itertools", ".", "combinations", "(", "adj", ",", "2", ")", ":", "if", "u", "in", "adj", "[", "v", "]", ":", "# already an edge...
27.32
15.88
def _part(self, name, func, args, help, **kwargs): """Parses arguments of a single command (e.g. 'v'). If :args: is empty, it assumes that command takes no further arguments. :name: Name of the command. :func: Arg method to execute. :args: Dictionary of CLI arguments pointed at...
[ "def", "_part", "(", "self", ",", "name", ",", "func", ",", "args", ",", "help", ",", "*", "*", "kwargs", ")", ":", "while", "self", ".", "argv", ":", "arg", "=", "self", ".", "argv", ".", "popleft", "(", ")", "if", "arg", "==", "\"-h\"", "or",...
37.857143
16.214286
def get_terms(self, field=None): """ Create a terms aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be aggregated :returns: self, which allows the method to be chainable with the other methods """ if not fiel...
[ "def", "get_terms", "(", "self", ",", "field", "=", "None", ")", ":", "if", "not", "field", ":", "raise", "AttributeError", "(", "\"Please provide field to apply aggregation to!\"", ")", "agg", "=", "A", "(", "\"terms\"", ",", "field", "=", "field", ",", "si...
41.692308
25.846154
def activateRandomLocation(self): """ Set the location to a random point. """ self.bumpPhases = np.array([np.random.random(2)]).T self._computeActiveCells()
[ "def", "activateRandomLocation", "(", "self", ")", ":", "self", ".", "bumpPhases", "=", "np", ".", "array", "(", "[", "np", ".", "random", ".", "random", "(", "2", ")", "]", ")", ".", "T", "self", ".", "_computeActiveCells", "(", ")" ]
28.5
5.5
def append_attribute(self, name, value, content): """ Append an attribute name/value into L{Content.data}. @param name: The attribute name @type name: basestring @param value: The attribute's value @type value: basestring @param content: The current content being ...
[ "def", "append_attribute", "(", "self", ",", "name", ",", "value", ",", "content", ")", ":", "key", "=", "name", "key", "=", "'_%s'", "%", "reserved", ".", "get", "(", "key", ",", "key", ")", "setattr", "(", "content", ".", "data", ",", "key", ",",...
36.384615
8.384615
def restore_session(session: tf.Session, checkpoint_dir: str, saver: Optional[tf.train.Saver] = None) -> None: """ Restores Tensorflow session from the latest checkpoint. :param session: The TF session :param checkpoint_dir: checkpoint files directory. :param saver: The saver obj...
[ "def", "restore_session", "(", "session", ":", "tf", ".", "Session", ",", "checkpoint_dir", ":", "str", ",", "saver", ":", "Optional", "[", "tf", ".", "train", ".", "Saver", "]", "=", "None", ")", "->", "None", ":", "checkpoint_path", "=", "tf", ".", ...
44.466667
16.333333
def plotBrightLimitInV(gBright, pdf=False, png=False): """ Plot the bright limit of Gaia in V as a function of (V-I). Parameters ---------- gBright - The bright limit of Gaia in G """ vmini=np.linspace(0.0,6.0,1001) gminv=gminvFromVmini(vmini) vBright=gBright-gminv fig=plt.figure(figsize=(10,6.5)...
[ "def", "plotBrightLimitInV", "(", "gBright", ",", "pdf", "=", "False", ",", "png", "=", "False", ")", ":", "vmini", "=", "np", ".", "linspace", "(", "0.0", ",", "6.0", ",", "1001", ")", "gminv", "=", "gminvFromVmini", "(", "vmini", ")", "vBright", "=...
22.75
18.535714
def generate_source_image(source_file, processor_options, generators=None, fail_silently=True): """ Processes a source ``File`` through a series of source generators, stopping once a generator returns an image. The return value is this image instance or ``None`` if no generato...
[ "def", "generate_source_image", "(", "source_file", ",", "processor_options", ",", "generators", "=", "None", ",", "fail_silently", "=", "True", ")", ":", "processor_options", "=", "ThumbnailOptions", "(", "processor_options", ")", "# Keep record of whether the source fil...
36.907407
17.055556
def storage_class(self, value): """Set the storage class for the bucket. See https://cloud.google.com/storage/docs/storage-classes :type value: str :param value: one of "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD", or "DURABLE_REDUCED_AVAILABIL...
[ "def", "storage_class", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "_STORAGE_CLASSES", ":", "raise", "ValueError", "(", "\"Invalid storage class: %s\"", "%", "(", "value", ",", ")", ")", "self", ".", "_patch_property", "(",...
41.083333
20.333333
def _validate_compute_chunk_params( self, dates, symbols, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed. """ root = self._root_mask_term clsname = type(self).__name__ # Writing this out explicitly so this errors in tes...
[ "def", "_validate_compute_chunk_params", "(", "self", ",", "dates", ",", "symbols", ",", "initial_workspace", ")", ":", "root", "=", "self", ".", "_root_mask_term", "clsname", "=", "type", "(", "self", ")", ".", "__name__", "# Writing this out explicitly so this err...
37.413793
15.206897
def dorequest(self, request_dic, opname): """ :param request_dic: a dictionary containing parameters for the request :param opname: An API operation name, available are: loginUser,getInitialUserData,logoutUser,createNewBudget, freshStartABudget,cloneBudget,deleteTombstonedBudgets,syncCat...
[ "def", "dorequest", "(", "self", ",", "request_dic", ",", "opname", ")", ":", "# Available operations :", "def", "curate_password", "(", "message", ")", ":", "return", "message", ".", "replace", "(", "self", ".", "password", ",", "'********'", ")", "def", "e...
50.92
22.84
def short_description(func): """ Given an object with a docstring, return the first line of the docstring """ doc = inspect.getdoc(func) if doc is not None: doc = inspect.cleandoc(doc) lines = doc.splitlines() return lines[0] return ""
[ "def", "short_description", "(", "func", ")", ":", "doc", "=", "inspect", ".", "getdoc", "(", "func", ")", "if", "doc", "is", "not", "None", ":", "doc", "=", "inspect", ".", "cleandoc", "(", "doc", ")", "lines", "=", "doc", ".", "splitlines", "(", ...
22.833333
17.666667
def bind_bottom_up(lower, upper, __fval=None, **fval): """Bind 2 layers for dissection. The upper layer will be chosen for dissection on top of the lower layer, if ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501 layers, the last one will be used as default....
[ "def", "bind_bottom_up", "(", "lower", ",", "upper", ",", "__fval", "=", "None", ",", "*", "*", "fval", ")", ":", "if", "__fval", "is", "not", "None", ":", "fval", ".", "update", "(", "__fval", ")", "lower", ".", "payload_guess", "=", "lower", ".", ...
49.666667
25.466667
def to_dict(self, remove_nones=False): """ Creates a dictionary representation of the object. :param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``. :return: A dictionary representation of the report. """ if remove...
[ "def", "to_dict", "(", "self", ",", "remove_nones", "=", "False", ")", ":", "if", "remove_nones", ":", "report_dict", "=", "super", "(", ")", ".", "to_dict", "(", "remove_nones", "=", "True", ")", "else", ":", "report_dict", "=", "{", "'title'", ":", "...
34.466667
16.733333
def humanise_seconds(seconds): """Utility function to humanise seconds value into e.g. 10 seconds ago. The function will try to make a nice phrase of the seconds count provided. .. note:: Currently seconds that amount to days are not supported. :param seconds: Mandatory seconds value e.g. 1100. ...
[ "def", "humanise_seconds", "(", "seconds", ")", ":", "days", "=", "seconds", "/", "(", "3600", "*", "24", ")", "day_modulus", "=", "seconds", "%", "(", "3600", "*", "24", ")", "hours", "=", "day_modulus", "/", "3600", "hour_modulus", "=", "day_modulus", ...
30.058824
17.529412
def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): ...
[ "def", "dispatch_on", "(", "*", "dispatch_args", ")", ":", "assert", "dispatch_args", ",", "'No dispatch args passed'", "dispatch_str", "=", "'(%s,)'", "%", "', '", ".", "join", "(", "dispatch_args", ")", "def", "check", "(", "arguments", ",", "wrong", "=", "o...
35.563107
16.485437
def verify_md5(md5_expected, data, other_errors=None): "return True if okay, raise Exception if not" # O_o ? md5_recv = hashlib.md5(data).hexdigest() if md5_expected != md5_recv: if other_errors is not None: logger.critical('\n'.join(other_errors)) raise FailedVerification('orig...
[ "def", "verify_md5", "(", "md5_expected", ",", "data", ",", "other_errors", "=", "None", ")", ":", "# O_o ?", "md5_recv", "=", "hashlib", ".", "md5", "(", "data", ")", ".", "hexdigest", "(", ")", "if", "md5_expected", "!=", "md5_recv", ":", "if", "other_...
47.333333
15.555556
def _split_op( self, identifier, hs_label=None, dagger=False, args=None): """Return `name`, total `subscript`, total `superscript` and `arguments` str. All of the returned strings are fully rendered. Args: identifier (str or SymbolicLabelBase): A (non-rendered/ascii) ...
[ "def", "_split_op", "(", "self", ",", "identifier", ",", "hs_label", "=", "None", ",", "dagger", "=", "False", ",", "args", "=", "None", ")", ":", "if", "self", ".", "_isinstance", "(", "identifier", ",", "'SymbolicLabelBase'", ")", ":", "identifier", "=...
51.707317
21.195122
def print_mem(unit="MB"): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result...
[ "def", "print_mem", "(", "unit", "=", "\"MB\"", ")", ":", "try", ":", "import", "psutil", "B", "=", "float", "(", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", ".", "memory_info", "(", ")", ".", "vms", ")", "KB", "=", "B", ...
27.941176
18.176471
def parse_peddy_ped_check(lines): """Parse a .ped_check.csv file Args: lines(iterable(str)) Returns: ped_check(list(dict)) """ ped_check = [] header = [] for i,line in enumerate(lines): line = line.rstrip() if i == 0: # Header line ...
[ "def", "parse_peddy_ped_check", "(", "lines", ")", ":", "ped_check", "=", "[", "]", "header", "=", "[", "]", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "if", "i", "==", "0", "...
40.984848
27.090909
def close(self): """in write mode, closing the handle adds the sentinel value into the queue and joins the thread executing the HTTP request. in read mode, this clears out the read response object so there are no references to it, and the resources can be reclaimed. """ ...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_mode", ".", "find", "(", "'w'", ")", ">=", "0", ":", "self", ".", "_queue", ".", "put", "(", "self", ".", "_sentinel", ")", "self", ".", "_thread", ".", "join", "(", "timeout", "=", "s...
39.4
15.7
def query(query, params={}, epoch=None, expected_response_code=200, database=None): """Wrapper around ``InfluxDBClient.query()``.""" db = get_db() database = database or settings.INFLUXDB_DATABASE return db.query(query, params, epoch, expected_response_code, database=database)
[ "def", "query", "(", "query", ",", "params", "=", "{", "}", ",", "epoch", "=", "None", ",", "expected_response_code", "=", "200", ",", "database", "=", "None", ")", ":", "db", "=", "get_db", "(", ")", "database", "=", "database", "or", "settings", "....
49.666667
15.666667
def _get_all_relationships(self): """Return all relationships seen in GO Dag subset.""" relationships_all = set() for goterm in self.go2obj.values(): if goterm.relationship: relationships_all.update(goterm.relationship) if goterm.relationship_rev: ...
[ "def", "_get_all_relationships", "(", "self", ")", ":", "relationships_all", "=", "set", "(", ")", "for", "goterm", "in", "self", ".", "go2obj", ".", "values", "(", ")", ":", "if", "goterm", ".", "relationship", ":", "relationships_all", ".", "update", "("...
44.666667
8.555556
def cf_array_from_list(values): """ Creates a CFArrayRef object from a list of CF* type objects. :param values: A list of CF* type object :return: A CFArrayRef """ length = len(values) return CoreFoundation.CFArrayCreate( Cor...
[ "def", "cf_array_from_list", "(", "values", ")", ":", "length", "=", "len", "(", "values", ")", "return", "CoreFoundation", ".", "CFArrayCreate", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "values", ",", "length", ",", "ffi", ".", "addressof", "("...
24.944444
18.722222
def _find_playlist(self): """ Internal method to populate the object given the ``id`` or ``reference_id`` that has been set in the constructor. """ data = None if self.id: data = self.connection.get_item( 'find_playlist_by_id', playlist_id=self...
[ "def", "_find_playlist", "(", "self", ")", ":", "data", "=", "None", "if", "self", ".", "id", ":", "data", "=", "self", ".", "connection", ".", "get_item", "(", "'find_playlist_by_id'", ",", "playlist_id", "=", "self", ".", "id", ")", "elif", "self", "...
33.125
14.5
def _flag_is_registered(self, flag_obj): """Checks whether a Flag object is registered under long name or short name. Args: flag_obj: Flag, the Flag instance to check for. Returns: bool, True iff flag_obj is registered under long name or short name. """ flag_dict = self._flags() # ...
[ "def", "_flag_is_registered", "(", "self", ",", "flag_obj", ")", ":", "flag_dict", "=", "self", ".", "_flags", "(", ")", "# Check whether flag_obj is registered under its long name.", "name", "=", "flag_obj", ".", "name", "if", "flag_dict", ".", "get", "(", "name"...
33.65
17.9
def team_events(self, team, year=None, simple=False, keys=False): """ Get team events a team has participated in. :param team: Team to get events for. :param year: Year to get events from. :param simple: Get only vital data. :param keys: Get just the keys of the events. ...
[ "def", "team_events", "(", "self", ",", "team", ",", "year", "=", "None", ",", "simple", "=", "False", ",", "keys", "=", "False", ")", ":", "if", "year", ":", "if", "keys", ":", "return", "self", ".", "_get", "(", "'team/%s/events/%s/keys'", "%", "("...
48.8
29.4
def Start(self, hostname, port): """Starts the process status RPC server. Args: hostname (str): hostname or IP address to connect to for requests. port (int): port to connect to for requests. Returns: bool: True if the RPC server was successfully started. """ if not self._Open(ho...
[ "def", "Start", "(", "self", ",", "hostname", ",", "port", ")", ":", "if", "not", "self", ".", "_Open", "(", "hostname", ",", "port", ")", ":", "return", "False", "self", ".", "_rpc_thread", "=", "threading", ".", "Thread", "(", "name", "=", "self", ...
29.294118
20.176471
def _gen_property_table(self): """ 2D array describing each registered property together with headers - for use in __str__ """ headers = ['Property Name', 'Type', 'Value', 'Default Value'] table = [] for propval in sorted(self._properties.itervalues(), ...
[ "def", "_gen_property_table", "(", "self", ")", ":", "headers", "=", "[", "'Property Name'", ",", "'Type'", ",", "'Value'", ",", "'Default Value'", "]", "table", "=", "[", "]", "for", "propval", "in", "sorted", "(", "self", ".", "_properties", ".", "iterva...
34.8125
14.8125
def sponsor_image_url(sponsor, name): """Returns the corresponding url from the sponsors images""" if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url retu...
[ "def", "sponsor_image_url", "(", "sponsor", ",", "name", ")", ":", "if", "sponsor", ".", "files", ".", "filter", "(", "name", "=", "name", ")", ".", "exists", "(", ")", ":", "# We avoid worrying about multiple matches by always", "# returning the first one.", "ret...
45.571429
12.428571
def get_pulls_review_comments(self, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet, since=github.GithubObject.NotSet): """ :calls: `GET /repos/:owner/:repo/pulls/comments <http://developer.github.com/v3/pulls/comments>`_ :param sort: string :param direction: string...
[ "def", "get_pulls_review_comments", "(", "self", ",", "sort", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "direction", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "since", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", ...
55.333333
25.083333
def end_output (self, **kwargs): """Write XML end tag.""" self.xml_endtag(u"urlset") self.xml_end_output() self.close_fileoutput()
[ "def", "end_output", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "xml_endtag", "(", "u\"urlset\"", ")", "self", ".", "xml_end_output", "(", ")", "self", ".", "close_fileoutput", "(", ")" ]
31.6
6.8
def authenticate(self, *args, **kwargs): ''' Authenticate the user agains LDAP ''' # Get config username = kwargs.get("username", None) password = kwargs.get("password", None) # Check user in Active Directory (authorization == None if can not connect to Active D...
[ "def", "authenticate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get config", "username", "=", "kwargs", ".", "get", "(", "\"username\"", ",", "None", ")", "password", "=", "kwargs", ".", "get", "(", "\"password\"", ",", "Non...
36.285714
19.771429
def get_value(self, label, takeable=False): """ Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False ...
[ "def", "get_value", "(", "self", ",", "label", ",", "takeable", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"get_value is deprecated and will be removed \"", "\"in a future release. Please use \"", "\".at[] or .iat[] accessors instead\"", ",", "FutureWarning", "...
28.652174
20.73913
def parse_python_version(output): """Parse a Python version output returned by `python --version`. Return a dict with three keys: major, minor, and micro. Each value is a string containing a version part. Note: The micro part would be `'0'` if it's missing from the input string. """ version_li...
[ "def", "parse_python_version", "(", "output", ")", ":", "version_line", "=", "output", ".", "split", "(", "\"\\n\"", ",", "1", ")", "[", "0", "]", "version_pattern", "=", "re", ".", "compile", "(", "r\"\"\"\n ^ # Beginning of line.\n ...
36.483871
14.967742
def preprocess(content): """ 对输出内容进行预处理,转为str类型 (py3),并替换行内\r\t\n等字符为空格 do pre-process to the content, turn it into str (for py3), and replace \r\t\n with space """ if six.PY2: if not isinstance(content, unicode): if isinstance(content, str): _content = unicode(c...
[ "def", "preprocess", "(", "content", ")", ":", "if", "six", ".", "PY2", ":", "if", "not", "isinstance", "(", "content", ",", "unicode", ")", ":", "if", "isinstance", "(", "content", ",", "str", ")", ":", "_content", "=", "unicode", "(", "content", ",...
30.238095
17.285714
def add_child(self, child, rangecheck=False): """Add a child feature to this feature.""" assert self.seqid == child.seqid, \ ( 'seqid mismatch for feature {} ({} vs {})'.format( self.fid, self.seqid, child.seqid ) ) if r...
[ "def", "add_child", "(", "self", ",", "child", ",", "rangecheck", "=", "False", ")", ":", "assert", "self", ".", "seqid", "==", "child", ".", "seqid", ",", "(", "'seqid mismatch for feature {} ({} vs {})'", ".", "format", "(", "self", ".", "fid", ",", "sel...
41.25
17.05
def actualize(self): """ Removes from this forecast all the *Weather* objects having a reference timestamp in the past with respect to the current timestamp """ current_time = timeutils.now(timeformat='unix') for w in self._weathers: if w.get_reference_time(ti...
[ "def", "actualize", "(", "self", ")", ":", "current_time", "=", "timeutils", ".", "now", "(", "timeformat", "=", "'unix'", ")", "for", "w", "in", "self", ".", "_weathers", ":", "if", "w", ".", "get_reference_time", "(", "timeformat", "=", "'unix'", ")", ...
42.777778
15.444444
def _make_futures(futmap_keys, class_check, make_result_fn): """ Create futures and a futuremap for the keys in futmap_keys, and create a request-level future to be bassed to the C API. """ futmap = {} for key in futmap_keys: if class_check is not None and not...
[ "def", "_make_futures", "(", "futmap_keys", ",", "class_check", ",", "make_result_fn", ")", ":", "futmap", "=", "{", "}", "for", "key", "in", "futmap_keys", ":", "if", "class_check", "is", "not", "None", "and", "not", "isinstance", "(", "key", ",", "class_...
44.521739
21.826087
def granger(vec1,vec2,order=10,rate=200,maxfreq=0): """ GRANGER Provide a simple way of calculating the key quantities. Usage: F,pp,cohe,Fx2y,Fy2x,Fxy=granger(vec1,vec2,order,rate,maxfreq) where: F is a 1xN vector of frequencies pp is a 2xN array of power spectra ...
[ "def", "granger", "(", "vec1", ",", "vec2", ",", "order", "=", "10", ",", "rate", "=", "200", ",", "maxfreq", "=", "0", ")", ":", "from", ".", "bsmart", "import", "timefreq", ",", "pwcausalr", "from", "scipy", "import", "array", ",", "size", "if", ...
34.121212
18
def _add_notes_slide_part(cls, package, slide_part, notes_master_part): """ Create and return a new notes slide part that is fully related, but has no shape content (i.e. placeholders not cloned). """ partname = package.next_partname('/ppt/notesSlides/notesSlide%d.xml') c...
[ "def", "_add_notes_slide_part", "(", "cls", ",", "package", ",", "slide_part", ",", "notes_master_part", ")", ":", "partname", "=", "package", ".", "next_partname", "(", "'/ppt/notesSlides/notesSlide%d.xml'", ")", "content_type", "=", "CT", ".", "PML_NOTES_SLIDE", "...
45.642857
16.214286
def paint_invalid_cell(self, row, col, color='MEDIUM VIOLET RED', skip_cell=False): """ Take row, column, and turn it color """ self.SetColLabelRenderer(col, MyColLabelRenderer('#1101e0')) # SetCellRenderer doesn't work with table-based grid (HugeGrid c...
[ "def", "paint_invalid_cell", "(", "self", ",", "row", ",", "col", ",", "color", "=", "'MEDIUM VIOLET RED'", ",", "skip_cell", "=", "False", ")", ":", "self", ".", "SetColLabelRenderer", "(", "col", ",", "MyColLabelRenderer", "(", "'#1101e0'", ")", ")", "# Se...
45.666667
15.444444
def _to_zipfile(self, file_generator): """Convert files to zip archive. :return: None :rtype: :py:obj:`None` """ with zipfile.ZipFile(file_generator.to_path, mode="w", compression=zipfile.ZIP_DEFLATED) as outfile: for f in file_generator: outpath = sel...
[ "def", "_to_zipfile", "(", "self", ",", "file_generator", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "file_generator", ".", "to_path", ",", "mode", "=", "\"w\"", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "outfile", ":", "fo...
50.666667
21.666667
def getLockStatsDB(self): """Returns the number of active lock discriminated by database. @return: : Dictionary of stats. """ info_dict = {'all': {}, 'wait': {}} cur = self._conn.cursor() cur.execute("SELECT d.datname, l.granted, COU...
[ "def", "getLockStatsDB", "(", "self", ")", ":", "info_dict", "=", "{", "'all'", ":", "{", "}", ",", "'wait'", ":", "{", "}", "}", "cur", "=", "self", ".", "_conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"SELECT d.datname, l.granted, COU...
39.388889
15.388889
def __do_grep(curr_line, pattern, **kwargs): """ Do grep on a single string. See 'grep' docs for info about kwargs. :param curr_line: a single line to test. :param pattern: pattern to search. :return: (matched, position, end_position). """ # currently found position position = -1 ...
[ "def", "__do_grep", "(", "curr_line", ",", "pattern", ",", "*", "*", "kwargs", ")", ":", "# currently found position", "position", "=", "-", "1", "end_pos", "=", "-", "1", "# check if fixed strings mode", "if", "kwargs", ".", "get", "(", "'fixed_strings'", ")"...
28.04878
16.756098
def daemon_start(main, pidfile, daemon=True, workspace=None): """Start application in background mode if required and available. If not then in front mode. """ logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=wo...
[ "def", "daemon_start", "(", "main", ",", "pidfile", ",", "daemon", "=", "True", ",", "workspace", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.\"", ".", "format", "(", "pidfile"...
46.0625
22.0625
def _enqueue_fs_event(self, event): """Watchman filesystem event handler for BUILD/requirements.txt updates. Called via a thread.""" self._logger.info('enqueuing {} changes for subscription {}' .format(len(event['files']), event['subscription'])) self._event_queue.put(event)
[ "def", "_enqueue_fs_event", "(", "self", ",", "event", ")", ":", "self", ".", "_logger", ".", "info", "(", "'enqueuing {} changes for subscription {}'", ".", "format", "(", "len", "(", "event", "[", "'files'", "]", ")", ",", "event", "[", "'subscription'", "...
61
14.2
def classification_tikhonov(G, y, M, tau=0): r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in logits :math:`Y`, then solves .. math:: \operatorname*{arg min}_X \| M X - Y \|_2^2 + \tau \ tr(X^T L X) if :math:`\tau > 0`, and .. math...
[ "def", "classification_tikhonov", "(", "G", ",", "y", ",", "M", ",", "tau", "=", "0", ")", ":", "y", "[", "M", "==", "False", "]", "=", "0", "Y", "=", "_to_logits", "(", "y", ".", "astype", "(", "np", ".", "int", ")", ")", "return", "regression...
31.557143
22.571429
def unescape(str): """Undoes the effects of the escape() function.""" out = '' prev_backslash = False for char in str: if not prev_backslash and char == '\\': prev_backslash = True continue out += char prev_backslash = False return out
[ "def", "unescape", "(", "str", ")", ":", "out", "=", "''", "prev_backslash", "=", "False", "for", "char", "in", "str", ":", "if", "not", "prev_backslash", "and", "char", "==", "'\\\\'", ":", "prev_backslash", "=", "True", "continue", "out", "+=", "char",...
26.636364
15.909091
def subtract_afromb(*inputs, **kwargs): """Subtract stream a from stream b. Returns: list(IOTileReading) """ try: value_a = inputs[0].pop() value_b = inputs[1].pop() return [IOTileReading(0, 0, value_b.value - value_a.value)] except StreamEmptyError: return...
[ "def", "subtract_afromb", "(", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "try", ":", "value_a", "=", "inputs", "[", "0", "]", ".", "pop", "(", ")", "value_b", "=", "inputs", "[", "1", "]", ".", "pop", "(", ")", "return", "[", "IOTileReadi...
22.142857
19.285714
def replace_node_status(self, name, body, **kwargs): """ replace status of the specified Node This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_node_status(name, body, async_req=True)...
[ "def", "replace_node_status", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "replace...
62.375
35.291667
def spectrodir(self, filetype, **kwargs): """Returns :envvar:`SPECTRO_REDUX` or :envvar:`BOSS_SPECTRO_REDUX` depending on the value of `run2d`. Parameters ---------- filetype : str File type parameter. run2d : int or str 2D Reduction ID. ...
[ "def", "spectrodir", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "if", "str", "(", "kwargs", "[", "'run2d'", "]", ")", "in", "(", "'26'", ",", "'103'", ",", "'104'", ")", ":", "return", "os", ".", "environ", "[", "'SPECTRO_REDU...
29.5
16.15
def register(self, entry_point): """Register an extension :param str entry_point: extension to register (entry point syntax). :raise: ValueError if already registered. """ if entry_point in self.registered_extensions: raise ValueError('Extension already registered')...
[ "def", "register", "(", "self", ",", "entry_point", ")", ":", "if", "entry_point", "in", "self", ".", "registered_extensions", ":", "raise", "ValueError", "(", "'Extension already registered'", ")", "ep", "=", "EntryPoint", ".", "parse", "(", "entry_point", ")",...
37.842105
18.526316
def complete_watch(self, text, *_): """ Autocomplete for watch """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
[ "def", "complete_watch", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "self", ".", "engine", ".", "cached_descriptions", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
53.333333
17.333333
def isPositiveStrand(self): """ Check if this genomic region is on the positive strand. :return: True if this element is on the positive strand """ if self.strand is None and self.DEFAULT_STRAND == self.POSITIVE_STRAND: return True return self.strand == self.POSITIVE_STRAND
[ "def", "isPositiveStrand", "(", "self", ")", ":", "if", "self", ".", "strand", "is", "None", "and", "self", ".", "DEFAULT_STRAND", "==", "self", ".", "POSITIVE_STRAND", ":", "return", "True", "return", "self", ".", "strand", "==", "self", ".", "POSITIVE_ST...
33
17.222222
def diff(self, dt=None, abs=True): """ Returns the difference between two Time objects as an Duration. :type dt: Time or None :param abs: Whether to return an absolute interval or not :type abs: bool :rtype: Duration """ if dt is None: dt = ...
[ "def", "diff", "(", "self", ",", "dt", "=", "None", ",", "abs", "=", "True", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "pendulum", ".", "now", "(", ")", ".", "time", "(", ")", "else", ":", "dt", "=", "self", ".", "__class__", "(", ...
26.655172
23.206897
def average_values(self, *args, **kwargs) -> float: """Average the actual values of the |Variable| object. For 0-dimensional |Variable| objects, the result of method |Variable.average_values| equals |Variable.value|. The following example shows this for the sloppily defined class ...
[ "def", "average_values", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "float", ":", "try", ":", "if", "not", "self", ".", "NDIM", ":", "return", "self", ".", "value", "mask", "=", "self", ".", "get_submask", "(", "*", "args", ...
39.94186
20.133721
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: """Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4 ...
[ "def", "_get_content_range", "(", "start", ":", "Optional", "[", "int", "]", ",", "end", ":", "Optional", "[", "int", "]", ",", "total", ":", "int", ")", "->", "str", ":", "start", "=", "start", "or", "0", "end", "=", "(", "end", "or", "total", "...
32.076923
16.384615
def register_all_add_grad( add_grad_function, arg_types, exclude=(), ignore_existing=False): """Register a gradient adder for all combinations of given types. This is a convenience shorthand for calling register_add_grad when registering gradient adders for multiple types that can be interchanged for the pur...
[ "def", "register_all_add_grad", "(", "add_grad_function", ",", "arg_types", ",", "exclude", "=", "(", ")", ",", "ignore_existing", "=", "False", ")", ":", "for", "t1", "in", "arg_types", ":", "for", "t2", "in", "arg_types", ":", "if", "(", "t1", ",", "t2...
38.73913
21.782609
def write(name, value): """Temporarily change or set the environment variable during the execution of a function. Args: name: The name of the environment variable value: A value to set for the environment variable Returns: The function return value. """ def wrapped(func): ...
[ "def", "write", "(", "name", ",", "value", ")", ":", "def", "wrapped", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "existing_env", "=", "core", ...
31.4
14.9
def flip_coords(X,loop): """ Align circulation with z-axis """ if(loop[0]==1): return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X)) else: return X
[ "def", "flip_coords", "(", "X", ",", "loop", ")", ":", "if", "(", "loop", "[", "0", "]", "==", "1", ")", ":", "return", "np", ".", "array", "(", "map", "(", "lambda", "i", ":", "np", ".", "array", "(", "[", "i", "[", "2", "]", ",", "i", "...
32
22.5
def get_symbols(node, ctx_types=(ast.Load, ast.Store)): ''' Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types that may be found assigned to the `ctx` attrib...
[ "def", "get_symbols", "(", "node", ",", "ctx_types", "=", "(", "ast", ".", "Load", ",", "ast", ".", "Store", ")", ")", ":", "gen", "=", "SymbolVisitor", "(", "ctx_types", ")", "return", "gen", ".", "visit", "(", "node", ")" ]
33.384615
25.076923
def map(self, data_source_factory, timeout=0, on_timeout="local_mode"): """Sends tasks to workers and awaits the responses. When all the responses are received, reduces them and returns the result. If timeout is set greater than 0, producer will quit waiting for workers when time has passed. ...
[ "def", "map", "(", "self", ",", "data_source_factory", ",", "timeout", "=", "0", ",", "on_timeout", "=", "\"local_mode\"", ")", ":", "def", "local_launch", "(", ")", ":", "print", "\"Local launch\"", "return", "self", ".", "reduce_fn", "(", "self", ".", "m...
43.037037
23.962963
def delete(self, container, del_objects=False): """ Deletes the specified container. If the container contains objects, the command will fail unless 'del_objects' is passed as True. In that case, each object will be deleted first, and then the container. """ return self._...
[ "def", "delete", "(", "self", ",", "container", ",", "del_objects", "=", "False", ")", ":", "return", "self", ".", "_manager", ".", "delete", "(", "container", ",", "del_objects", "=", "del_objects", ")" ]
52
20.285714
def reverse_url(self, scheme: str, path: str) -> str: """ Reverses the url using scheme and path given in parameter. :param scheme: Scheme of the url :param path: Path of the url :return: """ # remove starting slash in path if present path = path.lstrip('...
[ "def", "reverse_url", "(", "self", ",", "scheme", ":", "str", ",", "path", ":", "str", ")", "->", "str", ":", "# remove starting slash in path if present", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "server", ",", "port", "=", "self", ".", "con...
42.173913
22
def deps(ctx): '''Install or update development dependencies''' header(deps.__doc__) with ctx.cd(ROOT): ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True)
[ "def", "deps", "(", "ctx", ")", ":", "header", "(", "deps", ".", "__doc__", ")", "with", "ctx", ".", "cd", "(", "ROOT", ")", ":", "ctx", ".", "run", "(", "'pip install -r requirements/develop.pip -r requirements/doc.pip'", ",", "pty", "=", "True", ")" ]
40.8
24.8
def readTrainingData(file_locations, GROUP_LABEL): ''' Used in downstream tests ''' class Mock(object): pass mock_module = Mock() mock_module.PARENT_LABEL = GROUP_LABEL for location in file_locations: with open(location) as f: tree = etree.parse(f) xml = ...
[ "def", "readTrainingData", "(", "file_locations", ",", "GROUP_LABEL", ")", ":", "class", "Mock", "(", "object", ")", ":", "pass", "mock_module", "=", "Mock", "(", ")", "mock_module", ".", "PARENT_LABEL", "=", "GROUP_LABEL", "for", "location", "in", "file_locat...
27.4
17.8
def channel_submit_row(context): """ Display the row of buttons for delete and save. """ change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) ...
[ "def", "channel_submit_row", "(", "context", ")", ":", "change", "=", "context", "[", "'change'", "]", "is_popup", "=", "context", "[", "'is_popup'", "]", "save_as", "=", "context", "[", "'save_as'", "]", "show_save", "=", "context", ".", "get", "(", "'sho...
37.7
15.166667
def worker_disabled(name, workers=None, profile='default'): ''' Disable all the workers in the modjk load balancer Example: .. code-block:: yaml loadbalancer: modjk.worker_disabled: - workers: - app1 - app2 ''' if workers is None: ...
[ "def", "worker_disabled", "(", "name", ",", "workers", "=", "None", ",", "profile", "=", "'default'", ")", ":", "if", "workers", "is", "None", ":", "workers", "=", "[", "]", "return", "_bulk_state", "(", "'modjk.bulk_disable'", ",", "name", ",", "workers",...
21.105263
23.631579
def uuid_to_date(uuid, century='20'): """Return a date created from the last 6 digits of a uuid. Arguments: uuid The unique identifier to parse. century The first 2 digits to assume in the year. Default is '20'. Examples: >>> uuid_to_date('e8820616-1462-49b6-9784-e99a32120201') ...
[ "def", "uuid_to_date", "(", "uuid", ",", "century", "=", "'20'", ")", ":", "day", "=", "int", "(", "uuid", "[", "-", "2", ":", "]", ")", "month", "=", "int", "(", "uuid", "[", "-", "4", ":", "-", "2", "]", ")", "year", "=", "int", "(", "'%s...
30.35
20.7
def convert_UCERFSource(self, node): """ Converts the Ucerf Source node into an SES Control object """ dirname = os.path.dirname(self.fname) # where the source_model_file is source_file = os.path.join(dirname, node["filename"]) if "startDate" in node.attrib and "investigationTime" in node.attri...
[ "def", "convert_UCERFSource", "(", "self", ",", "node", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "fname", ")", "# where the source_model_file is", "source_file", "=", "os", ".", "path", ".", "join", "(", "dirname", ","...
45.16129
17.483871
def wait(self=None, period=10, callback=None, *args, **kwargs): """Wait until task is complete :param period: Time in seconds between reloads :param callback: Function to call after the task has finished, arguments and keyword arguments can be provided for it :return: Return ...
[ "def", "wait", "(", "self", "=", "None", ",", "period", "=", "10", ",", "callback", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "while", "self", ".", "status", "not", "in", "[", "TaskStatus", ".", "COMPLETED", ",", "TaskStatus...
37.555556
15.722222
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified...
[ "def", "delete_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "self", ".", "storage", ".", "exists", "(", "prefixed_path", ")", ":", "try", ":", "# When was the target file modified last time?", "target_last_modified", ...
49.604651
20.209302
def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO): """Pushes the repository. @param repository: ...
[ "def", "push_repository", "(", "self", ",", "repository", ",", "docker_executable", "=", "'docker'", ",", "shutit_pexpect_child", "=", "None", ",", "expect", "=", "None", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "sh...
41.216216
17.108108
def padding(self, px): """ Add padding around four sides of box :param px: padding value in pixels. Can be an array in the format of [top right bottom left] or single value. :return: New padding added box """ # if px is not an array, have equal padding all si...
[ "def", "padding", "(", "self", ",", "px", ")", ":", "# if px is not an array, have equal padding all sides", "if", "not", "isinstance", "(", "px", ",", "list", ")", ":", "px", "=", "[", "px", "]", "*", "4", "x", "=", "max", "(", "0", ",", "self", ".", ...
33.235294
12.058824
def hazard_preparation(self): """This function is doing the hazard preparation.""" LOGGER.info('ANALYSIS : Hazard preparation') use_same_projection = ( self.hazard.crs().authid() == self._crs.authid()) self.set_state_info( 'hazard', 'use_same_projecti...
[ "def", "hazard_preparation", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Hazard preparation'", ")", "use_same_projection", "=", "(", "self", ".", "hazard", ".", "crs", "(", ")", ".", "authid", "(", ")", "==", "self", ".", "_crs", ".", ...
40.948052
16.688312
def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) ...
[ "def", "device", "(", "self", ",", "idx", ")", ":", "class", "GpuDevice", "(", "Structure", ")", ":", "pass", "c_nvmlDevice_t", "=", "POINTER", "(", "GpuDevice", ")", "c_index", "=", "c_uint", "(", "idx", ")", "device", "=", "c_nvmlDevice_t", "(", ")", ...
23.7
18.25
def create_user(self, ): """Create a user and store it in the self.user :returns: None :rtype: None :raises: None """ name = self.username_le.text() if not name: self.username_le.setPlaceholderText("Please provide a username.") return ...
[ "def", "create_user", "(", "self", ",", ")", ":", "name", "=", "self", ".", "username_le", ".", "text", "(", ")", "if", "not", "name", ":", "self", ".", "username_le", ".", "setPlaceholderText", "(", "\"Please provide a username.\"", ")", "return", "first", ...
32.72
16.12
def toggle_service_status(self, service_id): """Toggles the service status. :param int service_id: The id of the service to delete """ svc = self.client['Network_Application_Delivery_Controller_' 'LoadBalancer_Service'] return svc.toggleStatus(id=servi...
[ "def", "toggle_service_status", "(", "self", ",", "service_id", ")", ":", "svc", "=", "self", ".", "client", "[", "'Network_Application_Delivery_Controller_'", "'LoadBalancer_Service'", "]", "return", "svc", ".", "toggleStatus", "(", "id", "=", "service_id", ")" ]
35.333333
16.555556
def _update_model(self, completions): """ Creates a QStandardModel that holds the suggestion from the completion models for the QCompleter :param completionPrefix: """ # build the completion model cc_model = QtGui.QStandardItemModel() self._tooltips.clear...
[ "def", "_update_model", "(", "self", ",", "completions", ")", ":", "# build the completion model", "cc_model", "=", "QtGui", ".", "QStandardItemModel", "(", ")", "self", ".", "_tooltips", ".", "clear", "(", ")", "for", "completion", "in", "completions", ":", "...
38.612903
11.129032
def _validate_pillar_roots(pillar_roots): ''' If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list ''' if not isinstance(pillar_roots, dict): log.warning('The pillar_roots parameter is not properly formatted,' ' usin...
[ "def", "_validate_pillar_roots", "(", "pillar_roots", ")", ":", "if", "not", "isinstance", "(", "pillar_roots", ",", "dict", ")", ":", "log", ".", "warning", "(", "'The pillar_roots parameter is not properly formatted,'", "' using defaults'", ")", "return", "{", "'bas...
44.7
18.7
def get_marginal_topic_distrib(doc_topic_distrib, doc_lengths): """ Return marginal topic distribution p(T) (topic proportions) given the document-topic distribution (theta) `doc_topic_distrib` and the document lengths `doc_lengths`. The latter can be calculated with `get_doc_lengths()`. """ unnorm ...
[ "def", "get_marginal_topic_distrib", "(", "doc_topic_distrib", ",", "doc_lengths", ")", ":", "unnorm", "=", "(", "doc_topic_distrib", ".", "T", "*", "doc_lengths", ")", ".", "sum", "(", "axis", "=", "1", ")", "return", "unnorm", "/", "unnorm", ".", "sum", ...
56.571429
28.285714
def transform(self, X): """ Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas.DataFrame X. To save some computing time, you should only include those time serieses in the container, that you need. You can set th...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "if", "self", ".", "timeseries_container", "is", "None", ":", "raise", "RuntimeError", "(", "\"You have to provide a time series using the set_timeseries_container function before.\"", ")", "# Extract only features for the ...
58.648649
39.081081
def grouped_insert(t, value): """Insert value into the target tree 't' with correct grouping.""" collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale()) if value.tail is not None: val_prev = value.getprevious() if val_prev is not None: val_prev.tail = (val_prev...
[ "def", "grouped_insert", "(", "t", ",", "value", ")", ":", "collator", "=", "Collator", ".", "createInstance", "(", "Locale", "(", "t", ".", "lang", ")", "if", "t", ".", "lang", "else", "Locale", "(", ")", ")", "if", "value", ".", "tail", "is", "no...
36.359375
15.078125
def urlpatterns(self): '''load and decorate urls from all modules then store it as cached property for less loading ''' if not hasattr(self, '_urlspatterns'): urlpatterns = [] # load all urls # support .urls file and urls_conf = 'elephantblog.urls' on ...
[ "def", "urlpatterns", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_urlspatterns'", ")", ":", "urlpatterns", "=", "[", "]", "# load all urls", "# support .urls file and urls_conf = 'elephantblog.urls' on default module", "# decorate all url patterns if...
43.88
17.56
def vq_nearest_neighbor(x, means, soft_em=False, num_samples=10, temperature=None): """Find the nearest element in means to elements in x.""" bottleneck_size = common_layers.shape_list(means)[0] x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True) means_norm_sq = tf.reduce_sum...
[ "def", "vq_nearest_neighbor", "(", "x", ",", "means", ",", "soft_em", "=", "False", ",", "num_samples", "=", "10", ",", "temperature", "=", "None", ")", ":", "bottleneck_size", "=", "common_layers", ".", "shape_list", "(", "means", ")", "[", "0", "]", "x...
49.888889
18.666667
def registerDriver(iface, driver, class_implements=[]): """ Register driver adapter used by page object""" for class_item in class_implements: classImplements(class_item, iface) component.provideAdapter(factory=driver, adapts=[iface], provides=IDriver)
[ "def", "registerDriver", "(", "iface", ",", "driver", ",", "class_implements", "=", "[", "]", ")", ":", "for", "class_item", "in", "class_implements", ":", "classImplements", "(", "class_item", ",", "iface", ")", "component", ".", "provideAdapter", "(", "facto...
44.666667
16
def _getVals(self, prefix = ""): """ return the values in the vals dict in case prefix is "", change the first letter of the name to lowercase, otherwise use prefix+name as the new name """ if not hasattr(self, "vals"): self.vals = {} dict = {} for key...
[ "def", "_getVals", "(", "self", ",", "prefix", "=", "\"\"", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"vals\"", ")", ":", "self", ".", "vals", "=", "{", "}", "dict", "=", "{", "}", "for", "key", "in", "list", "(", "self", ".", "vals...
40.352941
16
def parse_readme(): """ Crude parsing of modules/README.md returns a dict of {<module_name>: <documentation>} """ name = None re_mod = re.compile(r'^\#\#\# <a name="(?P<name>[a-z_0-9]+)"></a>') readme_file = os.path.join(modules_directory(), "README.md") modules_dict = {} with open(r...
[ "def", "parse_readme", "(", ")", ":", "name", "=", "None", "re_mod", "=", "re", ".", "compile", "(", "r'^\\#\\#\\# <a name=\"(?P<name>[a-z_0-9]+)\"></a>'", ")", "readme_file", "=", "os", ".", "path", ".", "join", "(", "modules_directory", "(", ")", ",", "\"REA...
31.863636
12.136364
def build_graph(path, term_depth=1000, skim_depth=10, d_weights=False, **kwargs): """ Tokenize a text, index a term matrix, and build out a graph. Args: path (str): The file path. term_depth (int): Consider the N most frequent terms. skim_depth (int): Connect each w...
[ "def", "build_graph", "(", "path", ",", "term_depth", "=", "1000", ",", "skim_depth", "=", "10", ",", "d_weights", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Tokenize text.", "click", ".", "echo", "(", "'\\nTokenizing text...'", ")", "t", "=", "...
25.647059
21.176471
def broadcast_definition(cast_name, onto_name): """ Return the definition of a broadcast as an object with keys "cast", "onto", "cast_on", "onto_on", "cast_index", and "onto_index". These are the same as the arguments to the ``broadcast`` function. """ if not orca.is_broadcast(cast_name, onto_n...
[ "def", "broadcast_definition", "(", "cast_name", ",", "onto_name", ")", ":", "if", "not", "orca", ".", "is_broadcast", "(", "cast_name", ",", "onto_name", ")", ":", "abort", "(", "404", ")", "b", "=", "orca", ".", "get_broadcast", "(", "cast_name", ",", ...
35.4
21.533333