text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def calc_schm_wats_v1(self): """Calculate the actual amount of water melting within the snow cover. Required control parameters: |NHRU| |Lnk| Required flux sequences: |SBes| |WGTF| Calculated flux sequence: |Schm| Updated state sequence: |WATS| Basic equa...
[ "def", "calc_schm_wats_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "sta", "=", "self", ".", "sequences", ".", "states", ".",...
30.571429
19.730159
def reloadFileOfCurrentItem(self, rtiRegItem=None): """ Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the...
[ "def", "reloadFileOfCurrentItem", "(", "self", ",", "rtiRegItem", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"reloadFileOfCurrentItem, rtiClass={}\"", ".", "format", "(", "rtiRegItem", ")", ")", "currentIndex", "=", "self", ".", "getRowCurrentIndex", "(...
40.609756
22.682927
def _visit_content(item, parent, visitor): """ Recursively visit nodes in the project tree. :param item: LocalContent/LocalFolder/LocalFile we are traversing down from :param parent: LocalContent/LocalFolder parent or None :param visitor: object visiting the tree """ ...
[ "def", "_visit_content", "(", "item", ",", "parent", ",", "visitor", ")", ":", "if", "KindType", ".", "is_project", "(", "item", ")", ":", "visitor", ".", "visit_project", "(", "item", ")", "elif", "KindType", ".", "is_folder", "(", "item", ")", ":", "...
41.8125
9.9375
def __generate_tree(self, top, src, resources, models, ctrls, views, utils): """Creates directories and packages""" res = self.__mkdir(top) for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res res = self.__mkdir(resources) or res res = self.__mkdir(os.path....
[ "def", "__generate_tree", "(", "self", ",", "top", ",", "src", ",", "resources", ",", "models", ",", "ctrls", ",", "views", ",", "utils", ")", ":", "res", "=", "self", ".", "__mkdir", "(", "top", ")", "for", "fn", "in", "(", "src", ",", "models", ...
57.444444
23.666667
def gisland(self, dae): """Reset g(x) for islanded buses and areas""" if (not self.islanded_buses) and (not self.island_sets): return a, v = list(), list() # for islanded areas without a slack bus # TODO: fix for islanded sets without sw # for island in self...
[ "def", "gisland", "(", "self", ",", "dae", ")", ":", "if", "(", "not", "self", ".", "islanded_buses", ")", "and", "(", "not", "self", ".", "island_sets", ")", ":", "return", "a", ",", "v", "=", "list", "(", ")", ",", "list", "(", ")", "# for isla...
31.478261
15.086957
def plot(self, x, y, **kw): """plot x, y values (erasing old plot), for method options see PlotPanel.plot. """ return self.frame.plot(x,y,**kw)
[ "def", "plot", "(", "self", ",", "x", ",", "y", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "frame", ".", "plot", "(", "x", ",", "y", ",", "*", "*", "kw", ")" ]
34.4
3.8
def getOrCreate(cls, sc): """ Get the existing SQLContext or create a new one with given SparkContext. :param sc: SparkContext """ if cls._instantiatedContext is None: jsqlContext = sc._jvm.SQLContext.getOrCreate(sc._jsc.sc()) sparkSession = SparkSession(...
[ "def", "getOrCreate", "(", "cls", ",", "sc", ")", ":", "if", "cls", ".", "_instantiatedContext", "is", "None", ":", "jsqlContext", "=", "sc", ".", "_jvm", ".", "SQLContext", ".", "getOrCreate", "(", "sc", ".", "_jsc", ".", "sc", "(", ")", ")", "spark...
38.909091
16
def apply(self, q, bindings, drilldowns): """ Apply a set of grouping criteria and project them. """ info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attrib...
[ "def", "apply", "(", "self", ",", "q", ",", "bindings", ",", "drilldowns", ")", ":", "info", "=", "[", "]", "for", "drilldown", "in", "self", ".", "parse", "(", "drilldowns", ")", ":", "for", "attribute", "in", "self", ".", "cube", ".", "model", "....
45.545455
9.909091
def save(self, fname=None): """ Download the chart from the URL into a filename as a PNG The filename defaults to the chart title (chtt) if any """ if not fname: fname = self.getname() assert fname != None, 'You must specify a filename to save to' if ...
[ "def", "save", "(", "self", ",", "fname", "=", "None", ")", ":", "if", "not", "fname", ":", "fname", "=", "self", ".", "getname", "(", ")", "assert", "fname", "!=", "None", ",", "'You must specify a filename to save to'", "if", "not", "fname", ".", "ends...
32.625
15.75
def _GetUserTypeAndPassword(username, password=None, is_admin=False): """Returns the user-type and password for a user. Args: username: Username for the user. password: Password for the user. If None, or not provided, we will prompt for one via the terminal. is_admin: Indicates whether the user s...
[ "def", "_GetUserTypeAndPassword", "(", "username", ",", "password", "=", "None", ",", "is_admin", "=", "False", ")", ":", "if", "is_admin", ":", "user_type", "=", "api_user", ".", "ApiGrrUser", ".", "UserType", ".", "USER_TYPE_ADMIN", "else", ":", "user_type",...
37.05
19.45
def hi_stops(self, hi_stops): '''Set the hi stop values for this object's degrees of freedom. Parameters ---------- hi_stops : float or sequence of float A hi stop value to set on all degrees of freedom, or a list containing one such value for each degree of free...
[ "def", "hi_stops", "(", "self", ",", "hi_stops", ")", ":", "_set_params", "(", "self", ".", "ode_obj", ",", "'HiStop'", ",", "hi_stops", ",", "self", ".", "ADOF", "+", "self", ".", "LDOF", ")" ]
43.909091
26.454545
def to_xml(self): ''' Returns a DOM element containing the XML representation of the invoice @return:Element ''' if not len(self.groups): raise InvoiceError("An invoice must have at least one group " \ "of lines.") for n, v ...
[ "def", "to_xml", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "groups", ")", ":", "raise", "InvoiceError", "(", "\"An invoice must have at least one group \"", "\"of lines.\"", ")", "for", "n", ",", "v", "in", "{", "\"identifier\"", ":", "sel...
45.916667
20.607143
def expand_groups(grp): """Expand group names. Args: grp (string): group names to expand Returns: list of groups Examples: * grp[1-3] will be expanded to [grp1, grp2, grp3] * grp1 will be expanded to [grp1] """ p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P...
[ "def", "expand_groups", "(", "grp", ")", ":", "p", "=", "re", ".", "compile", "(", "r\"(?P<name>.+)\\[(?P<start>\\d+)-(?P<end>\\d+)\\]\"", ")", "m", "=", "p", ".", "match", "(", "grp", ")", "if", "m", "is", "not", "None", ":", "s", "=", "int", "(", "m"...
23.608696
20.434783
def shell_context_processor(self, fn): """ Registers a shell context processor function. """ self._defer(lambda app: app.shell_context_processor(fn)) return fn
[ "def", "shell_context_processor", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "shell_context_processor", "(", "fn", ")", ")", "return", "fn" ]
32.333333
10.333333
def set_bit(self, position: int): """ Sets the value at position :param position: integer between 0 and 7, inclusive :return: None """ if position > (self._bit_width - 1): raise ValueError('position greater than the bit width') self._value |= (1 << p...
[ "def", "set_bit", "(", "self", ",", "position", ":", "int", ")", ":", "if", "position", ">", "(", "self", ".", "_bit_width", "-", "1", ")", ":", "raise", "ValueError", "(", "'position greater than the bit width'", ")", "self", ".", "_value", "|=", "(", "...
28.75
14.75
def functions(self): """ Returns all documented module level functions in the module sorted alphabetically as a list of `pydoc.Function`. """ p = lambda o: isinstance(o, Function) and self._docfilter(o) return sorted(filter(p, self.doc.values()))
[ "def", "functions", "(", "self", ")", ":", "p", "=", "lambda", "o", ":", "isinstance", "(", "o", ",", "Function", ")", "and", "self", ".", "_docfilter", "(", "o", ")", "return", "sorted", "(", "filter", "(", "p", ",", "self", ".", "doc", ".", "va...
41.142857
15.142857
def _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool] = None, ): """Help build a random graph. :type result: networkx.Graph :type graph: networkx.Graph """ original_node_cou...
[ "def", "_helper", "(", "result", ",", "graph", ",", "number_edges_remaining", ":", "int", ",", "node_blacklist", ":", "Set", "[", "BaseEntity", "]", ",", "invert_degrees", ":", "Optional", "[", "bool", "]", "=", "None", ",", ")", ":", "original_node_count", ...
40
25.302326
def can_allow_multiple_input_shapes(spec): """ Examines a model specification and determines if it can compute results for more than one output shape. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, ...
[ "def", "can_allow_multiple_input_shapes", "(", "spec", ")", ":", "# First, check that the model actually has a neural network in it", "try", ":", "layers", "=", "_get_nn_layers", "(", "spec", ")", "except", ":", "raise", "Exception", "(", "'Unable to verify that this model co...
27.848485
25.969697
def _call(self, utterances_batch: list, utterances_ids: Optional[list]=None) -> list: """ Processes batch of utterances and returns corresponding responses batch. Each call of Agent passes incoming utterances batch through skills filter, agent skills, skills processor. Batch of dialog I...
[ "def", "_call", "(", "self", ",", "utterances_batch", ":", "list", ",", "utterances_ids", ":", "Optional", "[", "list", "]", "=", "None", ")", "->", "list", ":", "batch_size", "=", "len", "(", "utterances_batch", ")", "ids", "=", "utterances_ids", "or", ...
45
31.1
def make_posthook(self): """ Run the post hook into the project directory. """ print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.pr...
[ "def", "make_posthook", "(", "self", ")", ":", "print", "(", "id", "(", "self", ".", "posthook", ")", ",", "self", ".", "posthook", ")", "print", "(", "id", "(", "super", "(", "self", ".", "__class__", ",", "self", ")", ".", "posthook", ")", ",", ...
48.375
17.75
def cloned_workspace(clone_config, chdir=True): """Create a cloned workspace and yield it. This creates a workspace for a with-block and cleans it up on exit. By default, this will also change to the workspace's `clone_dir` for the duration of the with-block. Args: clone_config: The execut...
[ "def", "cloned_workspace", "(", "clone_config", ",", "chdir", "=", "True", ")", ":", "workspace", "=", "ClonedWorkspace", "(", "clone_config", ")", "original_dir", "=", "os", ".", "getcwd", "(", ")", "if", "chdir", ":", "os", ".", "chdir", "(", "workspace"...
32.826087
23.565217
def _CheckFileEntryType(self, file_entry): """Checks the file entry type find specifications. Args: file_entry (FileEntry): file entry. Returns: bool: True if the file entry matches the find specification, False if not or None if no file entry type specification is defined. """ ...
[ "def", "_CheckFileEntryType", "(", "self", ",", "file_entry", ")", ":", "if", "not", "self", ".", "_file_entry_types", ":", "return", "None", "return", "(", "self", ".", "_CheckIsDevice", "(", "file_entry", ")", "or", "self", ".", "_CheckIsDirectory", "(", "...
35.176471
24.058824
def authenticated(function): """Re-authenticate if session expired.""" def wrapped(*args): """Wrap function.""" try: return function(*args) except UPSError: _login(*args) return function(*args) return wrapped
[ "def", "authenticated", "(", "function", ")", ":", "def", "wrapped", "(", "*", "args", ")", ":", "\"\"\"Wrap function.\"\"\"", "try", ":", "return", "function", "(", "*", "args", ")", "except", "UPSError", ":", "_login", "(", "*", "args", ")", "return", ...
27.1
12.2
def delete(self): """ Delete this Vlan interface from the parent interface. This will also remove stale routes if the interface has networks associated with it. :return: None """ if self in self._parent.vlan_interface: self._parent.data['vlanI...
[ "def", "delete", "(", "self", ")", ":", "if", "self", "in", "self", ".", "_parent", ".", "vlan_interface", ":", "self", ".", "_parent", ".", "data", "[", "'vlanInterfaces'", "]", "=", "[", "v", "for", "v", "in", "self", ".", "_parent", ".", "vlan_int...
34.8125
12.8125
def node_to_nodal_planes(node): """ Parses the nodal plane distribution to a PMF """ if not len(node): return None npd_pmf = [] for plane in node.nodes: if not all(plane.attrib[key] for key in plane.attrib): # One plane fails - return None return None ...
[ "def", "node_to_nodal_planes", "(", "node", ")", ":", "if", "not", "len", "(", "node", ")", ":", "return", "None", "npd_pmf", "=", "[", "]", "for", "plane", "in", "node", ".", "nodes", ":", "if", "not", "all", "(", "plane", ".", "attrib", "[", "key...
34.5625
13.5625
def ConvBPDNMask(*args, **kwargs): """A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to...
[ "def", "ConvBPDNMask", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract method selection argument or set default", "method", "=", "kwargs", ".", "pop", "(", "'method'", ",", "'admm'", ")", "# Assign base class depending on method selection argument", "bas...
39.558824
19.852941
def authorize_url(self, redirect_uri, state=None): """ 构造网页授权链接 详情请参考 https://work.weixin.qq.com/api/doc#90000/90135/91022 :param redirect_uri: 授权后重定向的回调链接地址 :param state: 重定向后会带上 state 参数 :return: 返回的 JSON 数据包 """ redirect_uri = six.moves.urllib....
[ "def", "authorize_url", "(", "self", ",", "redirect_uri", ",", "state", "=", "None", ")", ":", "redirect_uri", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "quote", "(", "redirect_uri", ",", "safe", "=", "b''", ")", "url_list", "=", "[",...
30.695652
14.521739
def _convert_url_to_downloadable(url): """Convert a url to the proper style depending on its website.""" if 'drive.google.com' in url: # For future support of google drive file_id = url.split('d/')[1].split('/')[0] base_url = 'https://drive.google.com/uc?export=download&id=' out...
[ "def", "_convert_url_to_downloadable", "(", "url", ")", ":", "if", "'drive.google.com'", "in", "url", ":", "# For future support of google drive", "file_id", "=", "url", ".", "split", "(", "'d/'", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", ...
35.473684
14.578947
def stop(self): """ stops the process triggered by start Setting the shared memory boolean run to false, which should prevent the loop from repeating. Call __cleanup to make sure the process stopped. After that we could trigger start() again. """ ...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "is_alive", "(", ")", ":", "self", ".", "_proc", ".", "terminate", "(", ")", "if", "self", ".", "_proc", "is", "not", "None", ":", "self", ".", "__cleanup", "(", ")", "if", "self", ".", "...
40.7
20.5
def dfbool2intervals(df,colbool): """ ds contains bool values """ df.index=range(len(df)) intervals=bools2intervals(df[colbool]) for intervali,interval in enumerate(intervals): df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali df.loc[interval[0]:interval[1],f'{co...
[ "def", "dfbool2intervals", "(", "df", ",", "colbool", ")", ":", "df", ".", "index", "=", "range", "(", "len", "(", "df", ")", ")", "intervals", "=", "bools2intervals", "(", "df", "[", "colbool", "]", ")", "for", "intervali", ",", "interval", "in", "e...
49.357143
22.642857
def _fetchChildren(self): '''Fetch and return new child items.''' children = [] # List paths under this directory. paths = [] for name in os.listdir(self.path): paths.append(os.path.normpath(os.path.join(self.path, name))) # Handle collections. colle...
[ "def", "_fetchChildren", "(", "self", ")", ":", "children", "=", "[", "]", "# List paths under this directory.", "paths", "=", "[", "]", "for", "name", "in", "os", ".", "listdir", "(", "self", ".", "path", ")", ":", "paths", ".", "append", "(", "os", "...
27.115385
18.346154
def generate_markdown_doc(app_name, spec): """Generate Markdown Documentation for the given spec/app name. Args: app_name (str): The name of the application. spec (YapconfSpec): A yapconf specification with sources loaded. Returns (str): A valid, markdown string representation of t...
[ "def", "generate_markdown_doc", "(", "app_name", ",", "spec", ")", ":", "# Apply standard headers.", "sections", "=", "[", "HEADER", ".", "format", "(", "app_name", "=", "app_name", ")", ",", "SOURCES_HEADER", ".", "format", "(", "app_name", "=", "app_name", "...
27.64
20.56
def number(self, text): """number = digit - "0" . {digit} ;""" self._attempting(text) return concatenation([ exclusion( self.digit, "0" ), zero_or_more( self.digit, ignore_whitespace=False ), ], ignore_whitespace=False)(text).compressed(TokenType.n...
[ "def", "number", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "concatenation", "(", "[", "exclusion", "(", "self", ".", "digit", ",", "\"0\"", ")", ",", "zero_or_more", "(", "self", ".", "digit", ",", "i...
24.153846
20
def _get_imagesave_wildcards(self): 'return the wildcard string for the filesave dialog' default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() wildcards = [] e...
[ "def", "_get_imagesave_wildcards", "(", "self", ")", ":", "default_filetype", "=", "self", ".", "get_default_filetype", "(", ")", "filetypes", "=", "self", ".", "get_supported_filetypes_grouped", "(", ")", "sorted_filetypes", "=", "filetypes", ".", "items", "(", "...
43
11.666667
def get_meta(self, ignore=['uniqueid']): """Dictionary of all meta-tags, with option to ignore certain tags. See all the meta-tag properties that are shared by ALL Parameters. If a given value is 'None', that means that it is not shared among ALL Parameters. To see the different values...
[ "def", "get_meta", "(", "self", ",", "ignore", "=", "[", "'uniqueid'", "]", ")", ":", "return", "OrderedDict", "(", "[", "(", "k", ",", "getattr", "(", "self", ",", "k", ")", ")", "for", "k", "in", "_meta_fields_twig", "if", "k", "not", "in", "igno...
45.866667
18.533333
def fetch_files(self): """fetch remote files (called after start)""" if not self.to_fetch: return for remote_file, local_file in self.to_fetch: self._fetch_file(remote_file, local_file)
[ "def", "fetch_files", "(", "self", ")", ":", "if", "not", "self", ".", "to_fetch", ":", "return", "for", "remote_file", ",", "local_file", "in", "self", ".", "to_fetch", ":", "self", ".", "_fetch_file", "(", "remote_file", ",", "local_file", ")" ]
38
12.833333
def is_birthday(self, dt=None): """ Check if its the birthday. Compares the date/month values of the two dates. :rtype: bool """ if dt is None: dt = self.now(self.tz) instance = pendulum.instance(dt) return (self.month, self.day) == (instanc...
[ "def", "is_birthday", "(", "self", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "self", ".", "now", "(", "self", ".", "tz", ")", "instance", "=", "pendulum", ".", "instance", "(", "dt", ")", "return", "(", "self", ...
25.384615
17.384615
def poly2bez(poly, return_bpoints=False): """Converts a cubic or lower order Polynomial object (or a sequence of coefficients) to a CubicBezier, QuadraticBezier, or Line object as appropriate. If return_bpoints=True then this will instead only return the control points of the corresponding Bezier curve...
[ "def", "poly2bez", "(", "poly", ",", "return_bpoints", "=", "False", ")", ":", "bpoints", "=", "polynomial2bezier", "(", "poly", ")", "if", "return_bpoints", ":", "return", "bpoints", "else", ":", "return", "bpoints2bezier", "(", "bpoints", ")" ]
46.416667
15.583333
def exists(self, key, **opts): """Return if a key exists in the cache.""" key, store = self._expand_opts(key, opts) data = store.get(key) # Note that we do not actually delete the thing here as the max_age # just for this call may have triggered a False. if not data or se...
[ "def", "exists", "(", "self", ",", "key", ",", "*", "*", "opts", ")", ":", "key", ",", "store", "=", "self", ".", "_expand_opts", "(", "key", ",", "opts", ")", "data", "=", "store", ".", "get", "(", "key", ")", "# Note that we do not actually delete th...
42.777778
14.555556
def download(self, bucket, key, fileobj, extra_args=None, subscribers=None): """Downloads a file from S3 :type bucket: str :param bucket: The name of the bucket to download from :type key: str :param key: The name of the key to download from :type file...
[ "def", "download", "(", "self", ",", "bucket", ",", "key", ",", "fileobj", ",", "extra_args", "=", "None", ",", "subscribers", "=", "None", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "{", "}", "if", "subscribers", "is", "None",...
40.780488
21.414634
def submit_job(self, job_definition, parameters, job_name=None, queue=None): """Wrap submit_job with useful defaults""" if job_name is None: job_name = _random_id() response = self._client.submit_job( jobName=job_name, jobQueue=queue or self.get_active_queue()...
[ "def", "submit_job", "(", "self", ",", "job_definition", ",", "parameters", ",", "job_name", "=", "None", ",", "queue", "=", "None", ")", ":", "if", "job_name", "is", "None", ":", "job_name", "=", "_random_id", "(", ")", "response", "=", "self", ".", "...
39.090909
11.636364
def Gamma(cls, shape: 'TensorFluent', scale: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters. Args: shape: The shape parame...
[ "def", "Gamma", "(", "cls", ",", "shape", ":", "'TensorFluent'", ",", "scale", ":", "'TensorFluent'", ",", "batch_size", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Tuple", "[", "Distribution", ",", "'TensorFluent'", "]", ":", "if", "shape...
39.933333
22.333333
def parse_args(self): """ Called from ``gnotty.server.run`` and parses any CLI args provided. Also handles loading settings from the Python module specified with the ``--conf-file`` arg. CLI args take precedence over any settings defined in the Python module defined by ``...
[ "def", "parse_args", "(", "self", ")", ":", "options", ",", "_", "=", "parser", ".", "parse_args", "(", ")", "file_settings", "=", "{", "}", "if", "options", ".", "CONF_FILE", ":", "execfile", "(", "options", ".", "CONF_FILE", ",", "{", "}", ",", "fi...
48.9375
16.5
def around_me_in(self, leaderboard_name, member, **options): ''' Retrieve a page of leaders from the named leaderboard around a given member. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param options [Hash] Options to be used wh...
[ "def", "around_me_in", "(", "self", ",", "leaderboard_name", ",", "member", ",", "*", "*", "options", ")", ":", "reverse_rank_for_member", "=", "None", "if", "self", ".", "order", "==", "self", ".", "DESC", ":", "reverse_rank_for_member", "=", "self", ".", ...
38.131579
22.447368
def sent2features(sentence, template): """ extract features in a sentence :type sentence: list of token, each token is a list of tag """ return [word2features(sentence, i, template) for i in range(len(sentence))]
[ "def", "sent2features", "(", "sentence", ",", "template", ")", ":", "return", "[", "word2features", "(", "sentence", ",", "i", ",", "template", ")", "for", "i", "in", "range", "(", "len", "(", "sentence", ")", ")", "]" ]
37.333333
17.166667
def iter_detector_clss(): """Iterate over all of the detectors that are included in this sub-package. This is a convenience method for capturing all new Detectors that are added over time and it is used both by the unit tests and in the ``Scrubber.__init__`` method. """ return iter_subclasses( ...
[ "def", "iter_detector_clss", "(", ")", ":", "return", "iter_subclasses", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "Detector", ",", "_is_abstract_detector", ",", ")" ]
37.727273
15.909091
def get_kernel_loop_nest(self): """Return kernel loop nest including any preceding pragmas and following swaps.""" loop_nest = [s for s in self.kernel_ast.block_items if type(s) in [c_ast.For, c_ast.Pragma, c_ast.FuncCall]] assert len(loop_nest) >= 1, "Found to few for state...
[ "def", "get_kernel_loop_nest", "(", "self", ")", ":", "loop_nest", "=", "[", "s", "for", "s", "in", "self", ".", "kernel_ast", ".", "block_items", "if", "type", "(", "s", ")", "in", "[", "c_ast", ".", "For", ",", "c_ast", ".", "Pragma", ",", "c_ast",...
59.333333
19.333333
def all_leaders_from(self, leaderboard_name, **options): ''' Retrieves all leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard. @return the n...
[ "def", "all_leaders_from", "(", "self", ",", "leaderboard_name", ",", "*", "*", "options", ")", ":", "raw_leader_data", "=", "self", ".", "_range_method", "(", "self", ".", "redis_connection", ",", "leaderboard_name", ",", "0", ",", "-", "1", ",", "withscore...
46.666667
23.5
def encode_multipart_formdata_stream(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, value) or (key, value, MIME type) field tuples. The key is treated as the field name, and the v...
[ "def", "encode_multipart_formdata_stream", "(", "fields", ",", "boundary", "=", "None", ")", ":", "body", "=", "[", "]", "def", "body_write", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "six", ".", "binary_type", ")", ":", "item", "=", ...
36.557143
21.842857
def quokka_polygons(size=None, extract=None): """ Returns example polygons on the standard example quokke image. The result contains one polygon, covering the quokka's outline. Parameters ---------- size : None or float or tuple of int or tuple of float, optional Size of the output ima...
[ "def", "quokka_polygons", "(", "size", "=", "None", ",", "extract", "=", "None", ")", ":", "# TODO get rid of this deferred import", "from", "imgaug", ".", "augmentables", ".", "polys", "import", "Polygon", ",", "PolygonsOnImage", "left", ",", "top", "=", "0", ...
34.591837
20.265306
def _load_meta(self, size, md5): """Set key attributes to retrived metadata. Might be extended in the future to support more attributes. """ if not hasattr(self, 'local_hashes'): self.local_hashes = {} self.size = int(size) if (re.match('^[a-fA-F0-9]{32}$', ...
[ "def", "_load_meta", "(", "self", ",", "size", ",", "md5", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'local_hashes'", ")", ":", "self", ".", "local_hashes", "=", "{", "}", "self", ".", "size", "=", "int", "(", "size", ")", "if", "(", "...
31.181818
12.181818
def _set_menu_toggles(self): """Enable menu bar view item checkmarks""" toggles = [ (self.main_toolbar, "main_window_toolbar", _("Main toolbar")), (self.macro_toolbar, "macro_toolbar", _("Macro toolbar")), (self.macro_panel, "macro_panel", _("Macro panel")), ...
[ "def", "_set_menu_toggles", "(", "self", ")", ":", "toggles", "=", "[", "(", "self", ".", "main_toolbar", ",", "\"main_window_toolbar\"", ",", "_", "(", "\"Main toolbar\"", ")", ")", ",", "(", "self", ".", "macro_toolbar", ",", "\"macro_toolbar\"", ",", "_",...
44.555556
22.185185
def cache_dir(self, path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None): ''' Download all of the files in a subdir of the master ''' ret = [] path = self._check_proto(salt.utils.data.decode(path)) # We want to m...
[ "def", "cache_dir", "(", "self", ",", "path", ",", "saltenv", "=", "'base'", ",", "include_empty", "=", "False", ",", "include_pat", "=", "None", ",", "exclude_pat", "=", "None", ",", "cachedir", "=", "None", ")", ":", "ret", "=", "[", "]", "path", "...
42.66
19.22
def _flow_check_handler_internal(self): """Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity to delete stale fl...
[ "def", "_flow_check_handler_internal", "(", "self", ")", ":", "integ_flow", "=", "self", ".", "integ_br_obj", ".", "dump_flows_for", "(", "in_port", "=", "self", ".", "int_peer_port_num", ")", "ext_flow", "=", "self", ".", "ext_br_obj", ".", "dump_flows_for", "(...
53.9375
19.53125
def sync_ldap_groups(self, ldap_groups): """Synchronize LDAP groups with local group model.""" groupname_field = 'name' self.stats_group_total = len(ldap_groups) for cname, ldap_attributes in ldap_groups: defaults = {} try: for name, attribute in ...
[ "def", "sync_ldap_groups", "(", "self", ",", "ldap_groups", ")", ":", "groupname_field", "=", "'name'", "self", ".", "stats_group_total", "=", "len", "(", "ldap_groups", ")", "for", "cname", ",", "ldap_attributes", "in", "ldap_groups", ":", "defaults", "=", "{...
39.861111
20.888889
def calcHairpin(seq, mv_conc=50.0, dv_conc=0.0, dntp_conc=0.8, dna_conc=50.0, temp_c=37, max_loop=30): ''' Calculate the hairpin formation thermodynamics of a DNA sequence. **Note that the maximum length of `seq` is 60 bp.** This is a cap suggested by the Primer3 team as the longest reasona...
[ "def", "calcHairpin", "(", "seq", ",", "mv_conc", "=", "50.0", ",", "dv_conc", "=", "0.0", ",", "dntp_conc", "=", "0.8", ",", "dna_conc", "=", "50.0", ",", "temp_c", "=", "37", ",", "max_loop", "=", "30", ")", ":", "_setThermoArgs", "(", "*", "*", ...
40.214286
28.857143
def get_neighbors_in_shell(self, origin, r, dr, include_index=False, include_image=False): """ Returns all sites in a shell centered on origin (coords) between radii r-dr and r+dr. Args: origin (3x1 array): Cartesian coordinates of center of sphere. r (float): In...
[ "def", "get_neighbors_in_shell", "(", "self", ",", "origin", ",", "r", ",", "dr", ",", "include_index", "=", "False", ",", "include_image", "=", "False", ")", ":", "outer", "=", "self", ".", "get_sites_in_sphere", "(", "origin", ",", "r", "+", "dr", ",",...
46.928571
22.857143
def update_model(self): ''' a method to update model with latest training data :return: True ''' import requests url = self.endpoint_public + '/calculate' params = { 'group': self.group_name } respon...
[ "def", "update_model", "(", "self", ")", ":", "import", "requests", "url", "=", "self", ".", "endpoint_public", "+", "'/calculate'", "params", "=", "{", "'group'", ":", "self", ".", "group_name", "}", "response", "=", "requests", ".", "get", "(", "url", ...
25.647059
19.882353
def police_priority_map_exceed_map_pri7_exceed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, ...
[ "def", "police_priority_map_exceed_map_pri7_exceed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "police_priority_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"police-priority-map\"", ...
49.153846
20.153846
def do_run(self, arg): """run [args...] Restart the debugged python program. If a string is supplied it is splitted with "shlex", and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". ...
[ "def", "do_run", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "argv0", "=", "sys", ".", "argv", "[", "0", ":", "1", "]", "sys", ".", "argv", "=", "shlex", ".", "split", "(", "arg", ")", "sys", ".", "argv", "[", ":", "0", "]", "=", ...
39.230769
14.692308
def build_spotify_api(): """Build the Spotify API for future use""" data = datatools.get_data() if "spotify_client_id" not in data["discord"]["keys"]: logger.warning("No API key found with name 'spotify_client_id'") logger.info("Please add your Spotify client id with name 'spotify_client_id'...
[ "def", "build_spotify_api", "(", ")", ":", "data", "=", "datatools", ".", "get_data", "(", ")", "if", "\"spotify_client_id\"", "not", "in", "data", "[", "\"discord\"", "]", "[", "\"keys\"", "]", ":", "logger", ".", "warning", "(", "\"No API key found with name...
47.8
25.32
def cli(env, identifier): """List server credentials.""" manager = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(manager.resolve_ids, identifier, 'hardware') instance = manager.get_hardware(hardware_id) ...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "manager", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hardware_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "identifier", ",", "'hard...
43.6875
19.1875
def hostname(self, levels=1): """ Produce a hostname with specified number of subdomain levels. >>> hostname() db-01.nichols-phillips.com >>> hostname(0) laptop-56 >>> hostname(2) web-12.williamson-hopkins.jackson.com """ if levels < 1: ...
[ "def", "hostname", "(", "self", ",", "levels", "=", "1", ")", ":", "if", "levels", "<", "1", ":", "return", "self", ".", "random_element", "(", "self", ".", "hostname_prefixes", ")", "+", "'-'", "+", "self", ".", "numerify", "(", "'##'", ")", "return...
36.785714
22.357143
def describe_listeners(load_balancer_arn=None, listener_arns=None, client=None): """ Permission: elasticloadbalancing:DescribeListeners """ kwargs = dict() if load_balancer_arn: kwargs.update(dict(LoadBalancerArn=load_balancer_arn)) if listener_arns: kwargs.update(dict(ListenerAr...
[ "def", "describe_listeners", "(", "load_balancer_arn", "=", "None", ",", "listener_arns", "=", "None", ",", "client", "=", "None", ")", ":", "kwargs", "=", "dict", "(", ")", "if", "load_balancer_arn", ":", "kwargs", ".", "update", "(", "dict", "(", "LoadBa...
37.6
15.2
def send(self, data, flags=0): """Send data to the socket. The socket must be connected to a remote socket. Returns a boolean value that indicates success or failure. A false value is typically an indication that the socket or connection was closed. """ return self.llc.s...
[ "def", "send", "(", "self", ",", "data", ",", "flags", "=", "0", ")", ":", "return", "self", ".", "llc", ".", "send", "(", "self", ".", "_tco", ",", "data", ",", "flags", ")" ]
42.5
14.125
def cli(env, identifier): """Cancel all virtual guests of the dedicated host immediately. Use the 'slcli vs cancel' command to cancel an specific guest """ dh_mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host') if...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "dh_mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "host_id", "=", "helpers", ".", "resolve_id", "(", "dh_mgr", ".", "resolve_ids", ",", "identifier", ",", "'dedic...
29.428571
24.428571
def parse(cls, rule_string): """ returns a list of rules a single line may yield multiple rules """ result = parser.parseString(rule_string) rules = [] # breakout port ranges into multple rules kwargs = {} kwargs['address'] = result.ip_and_mask o...
[ "def", "parse", "(", "cls", ",", "rule_string", ")", ":", "result", "=", "parser", ".", "parseString", "(", "rule_string", ")", "rules", "=", "[", "]", "# breakout port ranges into multple rules", "kwargs", "=", "{", "}", "kwargs", "[", "'address'", "]", "="...
29.368421
16.105263
def clean(ctx, check, compiled_only, all_matches, force, verbose): """Removes a project's build artifacts. If `check` is not specified, the current working directory will be used. All `*.pyc`/`*.pyd`/`*.pyo`/`*.whl` files and `__pycache__` directories will be removed. Additionally, the following patte...
[ "def", "clean", "(", "ctx", ",", "check", ",", "compiled_only", ",", "all_matches", ",", "force", ",", "verbose", ")", ":", "force_clean_root", "=", "False", "if", "check", ":", "path", "=", "resolve_path", "(", "os", ".", "path", ".", "join", "(", "ge...
40.122449
26.204082
def get_conf_from_module(mod): """return configuration from module with defaults no worry about None type """ conf = ModuleConfig(CONF_SPEC) # get imported module mod = _get_correct_module(mod) conf.set_module(mod) # extarct from default object or from module if hasattr(mod, 'defaul...
[ "def", "get_conf_from_module", "(", "mod", ")", ":", "conf", "=", "ModuleConfig", "(", "CONF_SPEC", ")", "# get imported module", "mod", "=", "_get_correct_module", "(", "mod", ")", "conf", ".", "set_module", "(", "mod", ")", "# extarct from default object or from m...
23.894737
18.263158
def split_user_input(line, pattern=None): """Split user input into initial whitespace, escape character, function part and the rest. """ # We need to ensure that the rest of this routine deals only with unicode encoding = get_stream_enc(sys.stdin, 'utf-8') line = py3compat.cast_unicode(line, enc...
[ "def", "split_user_input", "(", "line", ",", "pattern", "=", "None", ")", ":", "# We need to ensure that the rest of this routine deals only with unicode", "encoding", "=", "get_stream_enc", "(", "sys", ".", "stdin", ",", "'utf-8'", ")", "line", "=", "py3compat", ".",...
36.346154
16.692308
def editorData( self, editor ): """ Pulls the value from the inputed editor. :param editor | <QWidget> :return <variant> """ # set the information from a multi-tag edit if ( isinstance(editor, XMultiTagEdit) ): retu...
[ "def", "editorData", "(", "self", ",", "editor", ")", ":", "# set the information from a multi-tag edit\r", "if", "(", "isinstance", "(", "editor", ",", "XMultiTagEdit", ")", ")", ":", "return", "editor", ".", "tags", "(", ")", "# set the information from a combo bo...
31.619048
13.52381
def interpolate_to_timestep(self, timestep, cumulative=None): """Interpolate data for a finer timestep using a linear interpolation. Args: timestep: Target timestep as an integer. Target timestep must be divisable by current timestep. cumulative: A boolean that s...
[ "def", "interpolate_to_timestep", "(", "self", ",", "timestep", ",", "cumulative", "=", "None", ")", ":", "assert", "timestep", "%", "self", ".", "header", ".", "analysis_period", ".", "timestep", "==", "0", ",", "'Target timestep({}) must be divisable by current ti...
48.4
22.26
def libvlc_media_new_callbacks(instance, open_cb, read_cb, seek_cb, close_cb, opaque): '''Create a media with custom callbacks to read the data from. @param instance: LibVLC instance. @param open_cb: callback to open the custom bitstream input media. @param read_cb: callback to read data (must not be NU...
[ "def", "libvlc_media_new_callbacks", "(", "instance", ",", "open_cb", ",", "read_cb", ",", "seek_cb", ",", "close_cb", ",", "opaque", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_media_new_callbacks'", ",", "None", ")", "or", "_Cfunction", "(",...
98.2
63.4
def seek(self, value): """ Seek to the specified time. Parameters ---------- value : str or int The time to seek to. Can be any of the following formats: >>> 15.4 -> 15.4 # seconds >>> (1,21.5) -> 81.5 # (min,sec) >>> (1,1,2) -> 3662 # (hr, min, sec) >>> '01:01:33.5' -> 3693.5 #(hr...
[ "def", "seek", "(", "self", ",", "value", ")", ":", "# Pause the stream", "self", ".", "pause", "(", ")", "# Make sure the movie starts at 1s as 0s gives trouble.", "self", ".", "clock", ".", "time", "=", "max", "(", "0.5", ",", "value", ")", "logger", ".", ...
28.68
15.96
def unselect(self, value=None, field=None, **kwargs): """ Find a select box on the page and unselect a particular option from it. If the select box is a multiple select, ``unselect`` can be called multiple times to unselect more than one option. The select box can be found via its name, ...
[ "def", "unselect", "(", "self", ",", "value", "=", "None", ",", "field", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "field", ":", "self", ".", "find", "(", "\"select\"", ",", "field", ",", "*", "*", "kwargs", ")", ".", "find", "(", "...
45.388889
30.5
def add_key_value(self, key, value): """ Converts the value and adds it as a data field. Args: key: value: """ if key == 'unique_id': self._unique_id = str(value) else: self._data[key] = value
[ "def", "add_key_value", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "'unique_id'", ":", "self", ".", "_unique_id", "=", "str", "(", "value", ")", "else", ":", "self", ".", "_data", "[", "key", "]", "=", "value" ]
23.166667
14.5
def cancelPendingResultsFor( self, ps ): """Cancel all pending results for the given parameters. Note that this only affects the notebook's record, not any job running in a lab. :param ps: the parameters""" k = self._parametersAsIndex(ps) if k in self._results.keys(): ...
[ "def", "cancelPendingResultsFor", "(", "self", ",", "ps", ")", ":", "k", "=", "self", ".", "_parametersAsIndex", "(", "ps", ")", "if", "k", "in", "self", ".", "_results", ".", "keys", "(", ")", ":", "# remove from results", "rs", "=", "self", ".", "_re...
37.9375
15.875
def trackSeek(path, artist, album, track, trackNum, fmt): """Actually runs the program""" hiddenName = "(Hidden Track).{}".format(fmt) trackName = track + ".{}".format(fmt) songIn = instantiateSong(path) times = findGap(songIn) saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1...
[ "def", "trackSeek", "(", "path", ",", "artist", ",", "album", ",", "track", ",", "trackNum", ",", "fmt", ")", ":", "hiddenName", "=", "\"(Hidden Track).{}\"", ".", "format", "(", "fmt", ")", "trackName", "=", "track", "+", "\".{}\"", ".", "format", "(", ...
49.444444
15.555556
def perform(self, command, params=None, **kwargs): """Execute a command. Arguments can be supplied either as a dictionary or as keyword arguments. Examples: stc.perform('LoadFromXml', {'filename':'config.xml'}) stc.perform('LoadFromXml', filename='config.xml') ...
[ "def", "perform", "(", "self", ",", "command", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_session", "(", ")", "if", "not", "params", ":", "params", "=", "{", "}", "if", "kwargs", ":", "params", ".", "update"...
32.04
20.44
def html(self): """Gives an html representation of the assessment.""" output = self.html_preamble output += self._repr_html_() output += self.html_post return output
[ "def", "html", "(", "self", ")", ":", "output", "=", "self", ".", "html_preamble", "output", "+=", "self", ".", "_repr_html_", "(", ")", "output", "+=", "self", ".", "html_post", "return", "output" ]
33.333333
10.166667
def gdcsreporter(self, analysistype='GDCS'): """ Creates a report of the GDCS results :param analysistype: The variable to use when accessing attributes in the metadata object """ logging.info('Creating {} report'.format(analysistype)) # Initialise list to store all the G...
[ "def", "gdcsreporter", "(", "self", ",", "analysistype", "=", "'GDCS'", ")", ":", "logging", ".", "info", "(", "'Creating {} report'", ".", "format", "(", "analysistype", ")", ")", "# Initialise list to store all the GDCS genes, and genera in the analysis", "gdcs", "=",...
65.5
29.230769
def extract_HBS_learning_curves(runs): """ function to get the hyperband learning curves This is an example function showing the interface to use the HB_result.get_learning_curves method. Parameters ---------- runs: list of HB_result.run objects the performed runs for an unspecified config Returns ------...
[ "def", "extract_HBS_learning_curves", "(", "runs", ")", ":", "sr", "=", "sorted", "(", "runs", ",", "key", "=", "lambda", "r", ":", "r", ".", "budget", ")", "lc", "=", "list", "(", "filter", "(", "lambda", "t", ":", "not", "t", "[", "1", "]", "is...
28.777778
20.777778
def _format_array(x, fmt): # type: (Any, str) -> str """ >>> _format_array([0, 1.0], "{:0.3f}") '[0.000, 1.000]' """ value_repr = ", ".join(fmt.format(v) for v in x) return "[{}]".format(value_repr)
[ "def", "_format_array", "(", "x", ",", "fmt", ")", ":", "# type: (Any, str) -> str", "value_repr", "=", "\", \"", ".", "join", "(", "fmt", ".", "format", "(", "v", ")", "for", "v", "in", "x", ")", "return", "\"[{}]\"", ".", "format", "(", "value_repr", ...
27.375
7.875
def read_gtf_line(cols, field="name"): """parse gtf line to get class/name information""" field = field.lower() try: group = cols[2] attrs = cols[8].split(";") name = [attr.strip().split(" ")[1] for attr in attrs if attr.strip().split(" ")[0].lower().endswith(field)] if not n...
[ "def", "read_gtf_line", "(", "cols", ",", "field", "=", "\"name\"", ")", ":", "field", "=", "field", ".", "lower", "(", ")", "try", ":", "group", "=", "cols", "[", "2", "]", "attrs", "=", "cols", "[", "8", "]", ".", "split", "(", "\";\"", ")", ...
43.714286
24.785714
def protein_map_from_twg(twg): """Build map of entity texts to validate protein grounding. Looks at the grounding of the entity texts extracted from the statements and finds proteins where there is grounding to a human protein that maps to an HGNC name that is an exact match to the entity text. Return...
[ "def", "protein_map_from_twg", "(", "twg", ")", ":", "protein_map", "=", "{", "}", "unmatched", "=", "0", "matched", "=", "0", "logger", ".", "info", "(", "'Building grounding map for human proteins'", ")", "for", "agent_text", ",", "grounding_list", ",", "_", ...
40.836364
21.072727
def delete(self, bridge): """ Delete a bridge by name :param bridge: bridge name :return: """ args = { 'name': bridge, } self._bridge_chk.check(args) return self._client.json('bridge.delete', args)
[ "def", "delete", "(", "self", ",", "bridge", ")", ":", "args", "=", "{", "'name'", ":", "bridge", ",", "}", "self", ".", "_bridge_chk", ".", "check", "(", "args", ")", "return", "self", ".", "_client", ".", "json", "(", "'bridge.delete'", ",", "args"...
19.357143
18.642857
def _link_field_to_dict(field): """ Utility for ripping apart github's Link header field. It's kind of ugly. """ if not field: return dict() return dict([ ( part.split('; ')[1][5:-1], part.split('; ')[0][1:-1], ...
[ "def", "_link_field_to_dict", "(", "field", ")", ":", "if", "not", "field", ":", "return", "dict", "(", ")", "return", "dict", "(", "[", "(", "part", ".", "split", "(", "'; '", ")", "[", "1", "]", "[", "5", ":", "-", "1", "]", ",", "part", ".",...
25
15.714286
def t_escaped_FORM_FEED_CHAR(self, t): r'\x66' # 'f' t.lexer.pop_state() t.value = unichr(0x000c) return t
[ "def", "t_escaped_FORM_FEED_CHAR", "(", "self", ",", "t", ")", ":", "# 'f'", "t", ".", "lexer", ".", "pop_state", "(", ")", "t", ".", "value", "=", "unichr", "(", "0x000c", ")", "return", "t" ]
27
13
def _retrieve_metadata(stream, channel_name): """Retrieve basic metadata by reading the first file in the cache Parameters ---------- stream: lal stream object Stream containing a channel we want to learn about channel_name: str The name of the channel we...
[ "def", "_retrieve_metadata", "(", "stream", ",", "channel_name", ")", ":", "lalframe", ".", "FrStreamGetVectorLength", "(", "channel_name", ",", "stream", ")", "channel_type", "=", "lalframe", ".", "FrStreamGetTimeSeriesType", "(", "channel_name", ",", "stream", ")"...
42.2
19.4
def set_boot_order(self, position, device): """Puts the given device to the specified position in the boot order. To indicate that no device is associated with the given position, :py:attr:`DeviceType.null` should be used. @todo setHardDiskBootOrder(), setNetwo...
[ "def", "set_boot_order", "(", "self", ",", "position", ",", "device", ")", ":", "if", "not", "isinstance", "(", "position", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"position can only be an instance of type baseinteger\"", ")", "if", "not", "isin...
40.366667
19.366667
def create(cls, domain, login, options, alias): """Create a mailbox.""" cls.echo('Creating your mailbox.') result = cls.call('domain.mailbox.create', domain, login, options) if alias: cls.echo('Creating aliases.') result = cls.set_alias(domain, login, list(alias)...
[ "def", "create", "(", "cls", ",", "domain", ",", "login", ",", "options", ",", "alias", ")", ":", "cls", ".", "echo", "(", "'Creating your mailbox.'", ")", "result", "=", "cls", ".", "call", "(", "'domain.mailbox.create'", ",", "domain", ",", "login", ",...
33.5
18.8
def exists(self, user, status=None, symmetrical=False): """ Returns boolean whether or not a relationship exists between the given users. An optional :class:`RelationshipStatus` instance can be specified. """ query = dict( to_users__from_user=self.instance, ...
[ "def", "exists", "(", "self", ",", "user", ",", "status", "=", "None", ",", "symmetrical", "=", "False", ")", ":", "query", "=", "dict", "(", "to_users__from_user", "=", "self", ".", "instance", ",", "to_users__to_user", "=", "user", ",", "to_users__site__...
31.96
19.4
def get_Generic_itemtype(sq, simplify=True): """Retrieves the item type from a PEP 484 generic or subclass of such. sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container. Consequently this also works with typing.List, typing.Set and typing.Dict. Note that for typing.Dict and map...
[ "def", "get_Generic_itemtype", "(", "sq", ",", "simplify", "=", "True", ")", ":", "if", "is_Tuple", "(", "sq", ")", ":", "if", "simplify", ":", "itm_tps", "=", "[", "x", "for", "x", "in", "get_Tuple_params", "(", "sq", ")", "]", "simplify_for_Union", "...
41.758621
21.793103
def cnst_A(self, X): r"""Compute :math:`A \mathbf{x}` component of ADMM problem constraint. """ return self.block_cat(self.cnst_A0(X), self.cnst_A1(X))
[ "def", "cnst_A", "(", "self", ",", "X", ")", ":", "return", "self", ".", "block_cat", "(", "self", ".", "cnst_A0", "(", "X", ")", ",", "self", ".", "cnst_A1", "(", "X", ")", ")" ]
29.833333
17.333333
def issue(self, CorpNum, MgtKeyType, MgtKey, Memo=None, EmailSubject=None, ForceIssue=False, UserID=None): """ 발행 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 Memo : 처리 메모 ...
[ "def", "issue", "(", "self", ",", "CorpNum", ",", "MgtKeyType", ",", "MgtKey", ",", "Memo", "=", "None", ",", "EmailSubject", "=", "None", ",", "ForceIssue", "=", "False", ",", "UserID", "=", "None", ")", ":", "if", "MgtKeyType", "not", "in", "self", ...
36.548387
18.903226
def send_response(self, msgid, error=None, result=None): """Send a response """ msg = self._encoder.create_response(msgid, error, result) self._send_message(msg)
[ "def", "send_response", "(", "self", ",", "msgid", ",", "error", "=", "None", ",", "result", "=", "None", ")", ":", "msg", "=", "self", ".", "_encoder", ".", "create_response", "(", "msgid", ",", "error", ",", "result", ")", "self", ".", "_send_message...
37.8
10
def simple_attention(memory, att_size, mask, keep_prob=1.0, scope="simple_attention"): """Simple attention without any conditions. Computes weighted sum of memory elements. """ with tf.variable_scope(scope): BS, ML, MH = tf.unstack(tf.shape(memory)) memory_do = tf.nn.dropout(memory, ...
[ "def", "simple_attention", "(", "memory", ",", "att_size", ",", "mask", ",", "keep_prob", "=", "1.0", ",", "scope", "=", "\"simple_attention\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "BS", ",", "ML", ",", "MH", "=", "tf...
51.692308
24.153846
def handle_pubrel(self): """Handle incoming PUBREL packet.""" self.logger.info("PUBREL received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubrel(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_pubrel", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"PUBREL received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "retur...
23.538462
18.307692
def unacknowledge_problem_if_not_sticky(self): """ Remove the acknowledge if it is not sticky :return: None """ if hasattr(self, 'acknowledgement') and self.acknowledgement is not None: if not self.acknowledgement.sticky: self.unacknowledge_problem()
[ "def", "unacknowledge_problem_if_not_sticky", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'acknowledgement'", ")", "and", "self", ".", "acknowledgement", "is", "not", "None", ":", "if", "not", "self", ".", "acknowledgement", ".", "sticky", ":", ...
34.555556
14.111111
def register_rate_producer(self, rate_name: str, source: Callable[..., pd.DataFrame]=None) -> Pipeline: """Marks a ``Callable`` as the producer of a named rate. This is a convenience wrapper around ``register_value_producer`` that makes sure rate data is appropriately scaled to the size of the ...
[ "def", "register_rate_producer", "(", "self", ",", "rate_name", ":", "str", ",", "source", ":", "Callable", "[", "...", ",", "pd", ".", "DataFrame", "]", "=", "None", ")", "->", "Pipeline", ":", "return", "self", ".", "_value_manager", ".", "register_rate_...
42.428571
29.619048