text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def merged_cell_ranges(self): """Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, row_hi)) """ for row_number, row in enumerate(self.raw_sheet.rows()): for col_number, cell in enumerate(row): rspan, cspan = cell.span if (rspan, cspan) != (1...
[ "def", "merged_cell_ranges", "(", "self", ")", ":", "for", "row_number", ",", "row", "in", "enumerate", "(", "self", ".", "raw_sheet", ".", "rows", "(", ")", ")", ":", "for", "col_number", ",", "cell", "in", "enumerate", "(", "row", ")", ":", "rspan", ...
40.1
13.4
def get_number_of_agents_for_scheduling(self, context): """Return number of agents on which the router will be scheduled.""" num_agents = len(self.get_l3_agents(context, active=True, filters={'agent_modes': [bc.constants.L3_AGENT_MODE_LEGACY, bc.constant...
[ "def", "get_number_of_agents_for_scheduling", "(", "self", ",", "context", ")", ":", "num_agents", "=", "len", "(", "self", ".", "get_l3_agents", "(", "context", ",", "active", "=", "True", ",", "filters", "=", "{", "'agent_modes'", ":", "[", "bc", ".", "c...
44.8125
19.8125
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False): """ Create a track object from a filename. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: filename: A string containing the path to t...
[ "def", "track_from_filename", "(", "filename", ",", "filetype", "=", "None", ",", "timeout", "=", "DEFAULT_ASYNC_TIMEOUT", ",", "force_upload", "=", "False", ")", ":", "filetype", "=", "filetype", "or", "filename", ".", "split", "(", "'.'", ")", "[", "-", ...
36.434783
25.913043
def logs_sidecars_jobs(job_uuid: str, job_name: str, log_lines: Optional[Union[str, Iterable[str]]]) -> None: """Signal handling for sidecars logs.""" handle_job_logs(job_uuid=job_uuid, job_name=job_name, log_lines=log_lines) ...
[ "def", "logs_sidecars_jobs", "(", "job_uuid", ":", "str", ",", "job_name", ":", "str", ",", "log_lines", ":", "Optional", "[", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", "]", ")", "->", "None", ":", "handle_job_logs", "(", "job_uuid", ...
34.692308
11.615385
def setText(self, text): """ Sets the text for this instance to the inputed text. :param text | <str> """ super(XTextEdit, self).setText(projex.text.toAscii(text))
[ "def", "setText", "(", "self", ",", "text", ")", ":", "super", "(", "XTextEdit", ",", "self", ")", ".", "setText", "(", "projex", ".", "text", ".", "toAscii", "(", "text", ")", ")" ]
31
14.142857
def random_pos(self, context_iterable, num_permutations): """Obtains random positions w/ replacement which match sequence context. Parameters ---------- context_iterable: iterable containing two element tuple Records number of mutations in each context. context_iterable ...
[ "def", "random_pos", "(", "self", ",", "context_iterable", ",", "num_permutations", ")", ":", "position_list", "=", "[", "]", "for", "contxt", ",", "n", "in", "context_iterable", ":", "pos_array", "=", "self", ".", "random_context_pos", "(", "n", ",", "num_p...
38.590909
19.272727
def save(self, obj): """Required functionality.""" if not obj.id: obj.id = uuid() stored_data = { '_id': obj.id, 'value': json.loads(obj.to_data()) } index_vals = obj.indexes() or {} for key in obj.__class__.index_names() or []: ...
[ "def", "save", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ".", "id", ":", "obj", ".", "id", "=", "uuid", "(", ")", "stored_data", "=", "{", "'_id'", ":", "obj", ".", "id", ",", "'value'", ":", "json", ".", "loads", "(", "obj", "."...
30.058824
17.764706
def nameop_put_collision( cls, collisions, nameop ): """ Record a nameop as collided with another nameop in this block. """ # these are supposed to have been put here by nameop_set_collided history_id_key = nameop.get('__collided_history_id_key__', None) history_id = name...
[ "def", "nameop_put_collision", "(", "cls", ",", "collisions", ",", "nameop", ")", ":", "# these are supposed to have been put here by nameop_set_collided", "history_id_key", "=", "nameop", ".", "get", "(", "'__collided_history_id_key__'", ",", "None", ")", "history_id", "...
42.809524
22.428571
async def rename_conversation(self, rename_conversation_request): """Rename a conversation. Both group and one-to-one conversations may be renamed, but the official Hangouts clients have mixed support for one-to-one conversations with custom names. """ response = hangout...
[ "async", "def", "rename_conversation", "(", "self", ",", "rename_conversation_request", ")", ":", "response", "=", "hangouts_pb2", ".", "RenameConversationResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/renameconversation'", ",", "rename_c...
45.909091
19.545455
def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient): '''Copy directory from HDFS to local''' if not os.path.exists(localDirectory): os.makedirs(localDirectory) try: listing = hdfsClient.list_status(hdfsDirectory) except Exception as exception: nni_log(LogType....
[ "def", "copyHdfsDirectoryToLocal", "(", "hdfsDirectory", ",", "localDirectory", ",", "hdfsClient", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "localDirectory", ")", ":", "os", ".", "makedirs", "(", "localDirectory", ")", "try", ":", "listi...
49.619048
25.047619
def get_users_info(self, user_id_list, lang="zh_CN"): """ 批量获取用户基本信息。 :param user_id_list: 用户 ID 的列表 :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 """ return self.post( url="https://api.weixin.qq.com/cgi-bin/user/info/batchget"...
[ "def", "get_users_info", "(", "self", ",", "user_id_list", ",", "lang", "=", "\"zh_CN\"", ")", ":", "return", "self", ".", "post", "(", "url", "=", "\"https://api.weixin.qq.com/cgi-bin/user/info/batchget\"", ",", "data", "=", "{", "\"user_list\"", ":", "[", "{",...
28.789474
15.526316
def image_size(self, pnmfile): """Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255 """ pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r') pnmfileout = pout.read(200) pout....
[ "def", "image_size", "(", "self", ",", "pnmfile", ")", ":", "pout", "=", "os", ".", "popen", "(", "self", ".", "shellsetup", "+", "self", ".", "pnmfile", "+", "' '", "+", "pnmfile", ",", "'r'", ")", "pnmfileout", "=", "pout", ".", "read", "(", "200...
37
15.055556
def infer_dict_fromkeys(node, context=None): """Infer dict.fromkeys :param nodes.Call node: dict.fromkeys() call to infer :param context.InferenceContext: node context :rtype nodes.Dict: a Dictionary containing the values that astroid was able to infer. In case the inference failed for ...
[ "def", "infer_dict_fromkeys", "(", "node", ",", "context", "=", "None", ")", ":", "def", "_build_dict_with_elements", "(", "elements", ")", ":", "new_node", "=", "nodes", ".", "Dict", "(", "col_offset", "=", "node", ".", "col_offset", ",", "lineno", "=", "...
38.530303
19.363636
def get_latex(ink_filename): """Get the LaTeX string from a file by the *.ink filename.""" tex_file = os.path.splitext(ink_filename)[0] + ".tex" with open(tex_file) as f: tex_content = f.read().strip() pattern = re.compile(r"\\begin\{displaymath\}(.*?)\\end\{displaymath\}", ...
[ "def", "get_latex", "(", "ink_filename", ")", ":", "tex_file", "=", "os", ".", "path", ".", "splitext", "(", "ink_filename", ")", "[", "0", "]", "+", "\".tex\"", "with", "open", "(", "tex_file", ")", "as", "f", ":", "tex_content", "=", "f", ".", "rea...
38.846154
15.576923
def on_raise(self, node): # ('type', 'inst', 'tback') """Raise statement: note difference for python 2 and 3.""" if version_info[0] == 3: excnode = node.exc msgnode = node.cause else: excnode = node.type msgnode = node.inst out = self.ru...
[ "def", "on_raise", "(", "self", ",", "node", ")", ":", "# ('type', 'inst', 'tback')", "if", "version_info", "[", "0", "]", "==", "3", ":", "excnode", "=", "node", ".", "exc", "msgnode", "=", "node", ".", "cause", "else", ":", "excnode", "=", "node", "....
38.214286
10.357143
def outputs(ctx, client, revision, paths): r"""Show output files in the repository. <PATHS> Files to show. If no files are given all output files are shown. """ graph = Graph(client) filter = graph.build(paths=paths, revision=revision) output_paths = graph.output_paths click.echo('\n'.j...
[ "def", "outputs", "(", "ctx", ",", "client", ",", "revision", ",", "paths", ")", ":", "graph", "=", "Graph", "(", "client", ")", "filter", "=", "graph", ".", "build", "(", "paths", "=", "paths", ",", "revision", "=", "revision", ")", "output_paths", ...
31.090909
20.590909
def _sequential_topk(timestep: int, beam_size: int, inactive: mx.nd.NDArray, scores: mx.nd.NDArray, hypotheses: List[ConstrainedHypothesis], best_ids: mx.nd.NDArray, best_word_ids: mx.nd.NDArray...
[ "def", "_sequential_topk", "(", "timestep", ":", "int", ",", "beam_size", ":", "int", ",", "inactive", ":", "mx", ".", "nd", ".", "NDArray", ",", "scores", ":", "mx", ".", "nd", ".", "NDArray", ",", "hypotheses", ":", "List", "[", "ConstrainedHypothesis"...
44.581633
23.214286
def extend(self, *args): """ Extend a given object with all the properties in passed-in object(s). """ args = list(args) for i in args: self.obj.update(i) return self._wrap(self.obj)
[ "def", "extend", "(", "self", ",", "*", "args", ")", ":", "args", "=", "list", "(", "args", ")", "for", "i", "in", "args", ":", "self", ".", "obj", ".", "update", "(", "i", ")", "return", "self", ".", "_wrap", "(", "self", ".", "obj", ")" ]
24.2
13.2
def link(target, link_to): """ Create a link to a target file or a folder. For simplicity sake, both target and link_to must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: l...
[ "def", "link", "(", "target", ",", "link_to", ")", ":", "assert", "isinstance", "(", "target", ",", "str", ")", "assert", "os", ".", "path", ".", "exists", "(", "target", ")", "assert", "isinstance", "(", "link_to", ",", "str", ")", "# Create the path to...
29.741935
17.870968
def send_event(self, name, *args, **kwargs): """ Send an event to the native handler. This call is queued and batched. Parameters ---------- name : str The event name to be processed by MainActivity.processMessages. *args: args The arguments requ...
[ "def", "send_event", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "n", "=", "len", "(", "self", ".", "_bridge_queue", ")", "# Add to queue", "self", ".", "_bridge_queue", ".", "append", "(", "(", "name", ",", "args",...
29.6
17.485714
def isDescendantOf(self, other): '''Returns whether this Key is a descendant of `other`. >>> Key('/Comedy/MontyPython').isDescendantOf(Key('/Comedy')) True ''' if isinstance(other, Key): return other.isAncestorOf(self) raise TypeError('%s is not of type %s' % (other, Key))
[ "def", "isDescendantOf", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Key", ")", ":", "return", "other", ".", "isAncestorOf", "(", "self", ")", "raise", "TypeError", "(", "'%s is not of type %s'", "%", "(", "other", ",", "...
30.4
22.8
def create_transformation(self, rotation=None, translation=None): """ Creates a transformation matrix woth rotations and translation. Args: rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3` translation: 3 component vector as a list, tuple, or :py...
[ "def", "create_transformation", "(", "self", ",", "rotation", "=", "None", ",", "translation", "=", "None", ")", ":", "mat", "=", "None", "if", "rotation", "is", "not", "None", ":", "mat", "=", "Matrix44", ".", "from_eulers", "(", "Vector3", "(", "rotati...
33.521739
23.608696
def history_forward(self, count=1): """ Move forwards through the history. :param count: Amount of items to move forward. """ self._set_history_search() # Go forward in history. found_something = False for i in range(self.working_index + 1, len(self._wo...
[ "def", "history_forward", "(", "self", ",", "count", "=", "1", ")", ":", "self", ".", "_set_history_search", "(", ")", "# Go forward in history.", "found_something", "=", "False", "for", "i", "in", "range", "(", "self", ".", "working_index", "+", "1", ",", ...
31.478261
16.26087
def list_jobs(config, *, status=JobStatus.Active, filter_by_type=None, filter_by_worker=None): """ Return a list of Celery jobs. Args: config (Config): Reference to the configuration object from which the settings are retrieved. status (JobStatus): The status of the jo...
[ "def", "list_jobs", "(", "config", ",", "*", ",", "status", "=", "JobStatus", ".", "Active", ",", "filter_by_type", "=", "None", ",", "filter_by_worker", "=", "None", ")", ":", "celery_app", "=", "create_app", "(", "config", ")", "# option to filter by the wor...
34.415094
20.075472
def register(self, name, path, description, final_words=None): """ Registers a new recipe in the context of the current plugin. :param name: Name of the recipe :param path: Absolute path of the recipe folder :param description: A meaningful description of the recipe :par...
[ "def", "register", "(", "self", ",", "name", ",", "path", ",", "description", ",", "final_words", "=", "None", ")", ":", "return", "self", ".", "__app", ".", "recipes", ".", "register", "(", "name", ",", "path", ",", "self", ".", "_plugin", ",", "des...
49
23
def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) ...
[ "def", "handleNotification", "(", "self", ",", "req", ")", ":", "name", "=", "req", "[", "\"method\"", "]", "params", "=", "req", "[", "\"params\"", "]", "try", ":", "#to get a callable obj ", "obj", "=", "getMethodByName", "(", "self", ".", "service", ","...
37.888889
11.444444
def analyze(self, text, index=None, analyzer=None, tokenizer=None, filters=None, field=None): """ Performs the analysis process on a text and return the tokens breakdown of the text (See :ref:`es-guide-reference-api-admin-indices-optimize`) """ if filters is None: f...
[ "def", "analyze", "(", "self", ",", "text", ",", "index", "=", "None", ",", "analyzer", "=", "None", ",", "tokenizer", "=", "None", ",", "filters", "=", "None", ",", "field", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "="...
32
22.484848
def _get_window(self, other=None): """ Get the window length over which to perform some operation. Parameters ---------- other : object, default None The other object that is involved in the operation. Such an object is involved for operations like covari...
[ "def", "_get_window", "(", "self", ",", "other", "=", "None", ")", ":", "axis", "=", "self", ".", "obj", ".", "_get_axis", "(", "self", ".", "axis", ")", "length", "=", "len", "(", "axis", ")", "+", "(", "other", "is", "not", "None", ")", "*", ...
29.15
18.35
def _actionsFreqsAngles(self,*args,**kwargs): """ NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,vz[,...
[ "def", "_actionsFreqsAngles", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "galpy", ".", "orbit", "import", "Orbit", "_firstFlip", "=", "kwargs", ".", "get", "(", "'_firstFlip'", ",", "False", ")", "#If the orbit was already inte...
54.115385
21.833333
def _to_dict(self): """Return keyrange's state as a dict. :rtype: dict :returns: state of this instance. """ mapping = {} if self.start_open: mapping["start_open"] = self.start_open if self.start_closed: mapping["start_closed"] = self.st...
[ "def", "_to_dict", "(", "self", ")", ":", "mapping", "=", "{", "}", "if", "self", ".", "start_open", ":", "mapping", "[", "\"start_open\"", "]", "=", "self", ".", "start_open", "if", "self", ".", "start_closed", ":", "mapping", "[", "\"start_closed\"", "...
23.333333
19.809524
def post_headline(self, name, level, message): """Asynchronously update the sticky headline for a service. Args: name (string): The name of the service level (int): A message level in states.*_LEVEL message (string): The user facing error message that will be stored ...
[ "def", "post_headline", "(", "self", ",", "name", ",", "level", ",", "message", ")", ":", "self", ".", "_client", ".", "post_headline", "(", "name", ",", "level", ",", "message", ")" ]
39.727273
19.363636
def value_to_bool(config_val, evar): """ Massages the 'true' and 'false' strings to bool equivalents. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :rtype: bool :return: True or False, depending on the value. ...
[ "def", "value_to_bool", "(", "config_val", ",", "evar", ")", ":", "if", "not", "config_val", ":", "return", "False", "if", "config_val", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'true'", ":", "return", "True", "else", ":", "return", "Fals...
28.125
17
def get_sphinx_autodoc( self, depth=None, exclude=None, width=72, error=False, raised=False, no_comment=False, ): r""" Return exception list in `reStructuredText`_ auto-determining callable name. :param depth: Hierarchy levels to inclu...
[ "def", "get_sphinx_autodoc", "(", "self", ",", "depth", "=", "None", ",", "exclude", "=", "None", ",", "width", "=", "72", ",", "error", "=", "False", ",", "raised", "=", "False", ",", "no_comment", "=", "False", ",", ")", ":", "# This code is cog-specif...
39.574713
24.45977
def primitive_datatype(self, t: URIRef) -> Optional[URIRef]: """ Return the data type for primitive type t, if any :param t: type :return: corresponding data type """ for sco in self._o.objects(t, RDFS.subClassOf): sco_type = self._o.value(sco, RDF.type) ...
[ "def", "primitive_datatype", "(", "self", ",", "t", ":", "URIRef", ")", "->", "Optional", "[", "URIRef", "]", ":", "for", "sco", "in", "self", ".", "_o", ".", "objects", "(", "t", ",", "RDFS", ".", "subClassOf", ")", ":", "sco_type", "=", "self", "...
51.176471
19.294118
def _leave_status(self, subreddit, statusurl): """Abdicate status in a subreddit. :param subreddit: The name of the subreddit to leave `status` from. :param statusurl: The API URL which will be used in the leave request. Please use :meth:`leave_contributor` or :meth:`leave_moderator...
[ "def", "_leave_status", "(", "self", ",", "subreddit", ",", "statusurl", ")", ":", "if", "isinstance", "(", "subreddit", ",", "six", ".", "string_types", ")", ":", "subreddit", "=", "self", ".", "get_subreddit", "(", "subreddit", ")", "data", "=", "{", "...
41.6
19.4
def _get_bs4_string(soup): """ Outputs a BeautifulSoup object as a string that should hopefully be minimally modified """ if len(soup.find_all("script")) == 0: soup_str = soup.prettify(formatter=None).strip() else: soup_str = str(soup.html) soup_str = re.sub("&amp;", "&", sou...
[ "def", "_get_bs4_string", "(", "soup", ")", ":", "if", "len", "(", "soup", ".", "find_all", "(", "\"script\"", ")", ")", "==", "0", ":", "soup_str", "=", "soup", ".", "prettify", "(", "formatter", "=", "None", ")", ".", "strip", "(", ")", "else", "...
36.083333
13.75
def get_saml_assertion(cls, ticket): """ http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0 SAML request values: RequestID [REQUIRED]: unique identifier for the request IssueInstant [REQUIRED]: timestamp of the request samlp:AssertionArtifact...
[ "def", "get_saml_assertion", "(", "cls", ",", "ticket", ")", ":", "# RequestID [REQUIRED] - unique identifier for the request", "request_id", "=", "uuid4", "(", ")", "# e.g. 2014-06-02T09:21:03.071189", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")"...
32
15.666667
def foreground(color, content, readline=False): """ Color the text of the content :param color: pick a constant, any constant :type color: int :param content: Whatever you want to say... :type content: unicode :return: ansi string :rtype: unicode """ return encode(color, readline=re...
[ "def", "foreground", "(", "color", ",", "content", ",", "readline", "=", "False", ")", ":", "return", "encode", "(", "color", ",", "readline", "=", "readline", ")", "+", "content", "+", "encode", "(", "DEFAULT", ",", "readline", "=", "readline", ")" ]
33.090909
16.545455
def dump(self, *args, **kwargs): """ Build a list of dicts, by calling :meth:`Node.dump` on each item. Each keyword provides a function that extracts a value from a Node. Examples: >>> c = Collection([Scalar(1), Scalar(2)]) >>> c.dump(x2=Q*2, m1...
[ "def", "dump", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "each", "(", "Q", ".", "dump", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
28.8
18
def predict_survival_function(self, X, times=None): """ Predict the survival function for individuals, given their covariates. This assumes that the individual just entered the study (that is, we do not condition on how long they have already lived for.) Parameters ---------- ...
[ "def", "predict_survival_function", "(", "self", ",", "X", ",", "times", "=", "None", ")", ":", "return", "np", ".", "exp", "(", "-", "self", ".", "predict_cumulative_hazard", "(", "X", ",", "times", "=", "times", ")", ")" ]
42.791667
27.625
def all_ip_address_in_subnet(ip_net, cidr): """ Function to return every ip in a subnet :param ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 :param cidr: CIDR value of 0 to 32 :return: A list of ip address's """ ip_address_list...
[ "def", "all_ip_address_in_subnet", "(", "ip_net", ",", "cidr", ")", ":", "ip_address_list", "=", "list", "(", ")", "if", "not", "ip_mask", "(", "'{ip_net}/{cidr}'", ".", "format", "(", "ip_net", "=", "ip_net", ",", "cidr", "=", "cidr", ")", ",", "return_tu...
49.391304
31.304348
def ensure(user, action, subject): """ Similar to ``can`` but will raise a AccessDenied Exception if does not have access""" ability = Ability(user, get_authorization_method()) if ability.cannot(action, subject): raise AccessDenied()
[ "def", "ensure", "(", "user", ",", "action", ",", "subject", ")", ":", "ability", "=", "Ability", "(", "user", ",", "get_authorization_method", "(", ")", ")", "if", "ability", ".", "cannot", "(", "action", ",", "subject", ")", ":", "raise", "AccessDenied...
49.8
6.8
def actor_url(parser, token): """ Renders the URL for a particular actor instance :: <a href="{% actor_url request.user %}">View your actions</a> <a href="{% actor_url another_user %}">{{ another_user }}'s actions</a> """ bits = token.split_contents() if len(bits) != 2: ...
[ "def", "actor_url", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"Accepted format \"", "\"{% actor_url [actor_instance] %}\"", ...
30.0625
21.8125
def authorgroup(self): """A list of namedtuples representing the article's authors organized by affiliation, in the form (affiliation_id, dptid, organization, city, postalcode, addresspart, country, auid, indexed_name, surname, given_name). If "given_name" is not present, fall ba...
[ "def", "authorgroup", "(", "self", ")", ":", "out", "=", "[", "]", "fields", "=", "'affiliation_id dptid organization city postalcode '", "'addresspart country auid indexed_name surname given_name'", "auth", "=", "namedtuple", "(", "'Author'", ",", "fields", ")", "items",...
51.45
20.6
def _parse_arg(valid_classifications): """ Command line parser for coco Parameters ---------- valid_classifications: list Available classifications, used for checking input parameters. Returns ------- args : ArgumentParser namespace """ parser = argparse.ArgumentParser( ...
[ "def", "_parse_arg", "(", "valid_classifications", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'The country converter (coco): a Python package for '", "'converting country names between '", "'different classifications schemes. '", "'...
44.457627
22.474576
def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set()""" if self.multi: #multi parameters can be passed as parameterid=choice...
[ "def", "valuefrompostdata", "(", "self", ",", "postdata", ")", ":", "if", "self", ".", "multi", ":", "#multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value)", "found", "=", "False", "if", "self"...
47.178571
17.142857
def CreateControls(self): """Create our sub-controls""" wx.EVT_LIST_COL_CLICK(self, self.GetId(), self.OnReorder) wx.EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnNodeSelected) wx.EVT_MOTION(self, self.OnMouseMove) wx.EVT_LIST_ITEM_ACTIVATED(self, self.GetId(), self.OnNodeAct...
[ "def", "CreateControls", "(", "self", ")", ":", "wx", ".", "EVT_LIST_COL_CLICK", "(", "self", ",", "self", ".", "GetId", "(", ")", ",", "self", ".", "OnReorder", ")", "wx", ".", "EVT_LIST_ITEM_SELECTED", "(", "self", ",", "self", ".", "GetId", "(", ")"...
50
18.142857
def get_name(self, func): ''' Get the name to reference a function by :param func: function to get the name of :type func: callable ''' if hasattr(func, 'name'): return func.name return '%s.%s' % ( func.__module__, func.__name...
[ "def", "get_name", "(", "self", ",", "func", ")", ":", "if", "hasattr", "(", "func", ",", "'name'", ")", ":", "return", "func", ".", "name", "return", "'%s.%s'", "%", "(", "func", ".", "__module__", ",", "func", ".", "__name__", ")" ]
22.785714
19.357143
def tojsonarrays(table, source=None, prefix=None, suffix=None, output_header=False, *args, **kwargs): """ Write a table in JSON format, with rows output as JSON arrays. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], ... ...
[ "def", "tojsonarrays", "(", "table", ",", "source", "=", "None", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ",", "output_header", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "output_header", ":", "obj", "=", ...
31.64
17.32
def get_pair(self, pair): """get pair description Parameters ---------- pair : :any:`list` of nodes Descr Returns ------- type Descr """ i, j = pair return (self._nodes[i.name()], self._nodes[j....
[ "def", "get_pair", "(", "self", ",", "pair", ")", ":", "i", ",", "j", "=", "pair", "return", "(", "self", ".", "_nodes", "[", "i", ".", "name", "(", ")", "]", ",", "self", ".", "_nodes", "[", "j", ".", "name", "(", ")", "]", ")" ]
20.933333
19.333333
def duration_minutes(duration): """returns minutes from duration, otherwise we keep bashing in same math""" if isinstance(duration, list): res = dt.timedelta() for entry in duration: res += entry return duration_minutes(res) elif isinstance(duration, dt.timedelta): ...
[ "def", "duration_minutes", "(", "duration", ")", ":", "if", "isinstance", "(", "duration", ",", "list", ")", ":", "res", "=", "dt", ".", "timedelta", "(", ")", "for", "entry", "in", "duration", ":", "res", "+=", "entry", "return", "duration_minutes", "("...
31.833333
12.75
def CheckApproversForLabel(self, token, client_urn, requester, approvers, label): """Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is suffici...
[ "def", "CheckApproversForLabel", "(", "self", ",", "token", ",", "client_urn", ",", "requester", ",", "approvers", ",", "label", ")", ":", "auth", "=", "self", ".", "reader", ".", "GetAuthorizationForSubject", "(", "label", ")", "if", "not", "auth", ":", "...
39.804878
19.853659
def _get_param_names(self): """ Get mappable parameters from YAML. """ template = Template(self.yaml_string) names = ['yaml_string'] # always include the template for match in re.finditer(template.pattern, template.template): name = match.group('named') or ma...
[ "def", "_get_param_names", "(", "self", ")", ":", "template", "=", "Template", "(", "self", ".", "yaml_string", ")", "names", "=", "[", "'yaml_string'", "]", "# always include the template", "for", "match", "in", "re", ".", "finditer", "(", "template", ".", ...
37.909091
11.909091
def gapfill(model, universal=None, lower_bound=0.05, penalties=None, demand_reactions=True, exchange_reactions=False, iterations=1): """Perform gapfilling on a model. See documentation for the class GapFiller. Parameters ---------- model : cobra.Model The model to p...
[ "def", "gapfill", "(", "model", ",", "universal", "=", "None", ",", "lower_bound", "=", "0.05", ",", "penalties", "=", "None", ",", "demand_reactions", "=", "True", ",", "exchange_reactions", "=", "False", ",", "iterations", "=", "1", ")", ":", "gapfiller"...
42.310345
21.689655
def home(self) -> str: """ Return the robot to the home position and update the position tracker """ self.hardware.home() self.current_position = self._position() return 'Homed'
[ "def", "home", "(", "self", ")", "->", "str", ":", "self", ".", "hardware", ".", "home", "(", ")", "self", ".", "current_position", "=", "self", ".", "_position", "(", ")", "return", "'Homed'" ]
31.285714
13.285714
def reduce_by_window(self, window_config, reduce_function): """Return a new Streamlet in which each element of this Streamlet are collected over a window defined by window_config and then reduced using the reduce_function reduce_function takes two element at one time and reduces them to one element that...
[ "def", "reduce_by_window", "(", "self", ",", "window_config", ",", "reduce_function", ")", ":", "from", "heronpy", ".", "streamlet", ".", "impl", ".", "reducebywindowbolt", "import", "ReduceByWindowStreamlet", "reduce_streamlet", "=", "ReduceByWindowStreamlet", "(", "...
59.6
21.8
def _create_event(self, event_state, event_type, event_value, proc_list, proc_desc, peak_time): """Add a new item in the log list. Item is added only if the criticity (event_state) is WARNING or CRITICAL. """ if event_state == "WARNING" or event_state == "CRITICAL"...
[ "def", "_create_event", "(", "self", ",", "event_state", ",", "event_type", ",", "event_value", ",", "proc_list", ",", "proc_desc", ",", "peak_time", ")", ":", "if", "event_state", "==", "\"WARNING\"", "or", "event_state", "==", "\"CRITICAL\"", ":", "# Define th...
37.432432
15.945946
def _get_footer(self, footer): """ Gets the html footer """ if footer is None: html = self.footer() else: html = footer return html
[ "def", "_get_footer", "(", "self", ",", "footer", ")", ":", "if", "footer", "is", "None", ":", "html", "=", "self", ".", "footer", "(", ")", "else", ":", "html", "=", "footer", "return", "html" ]
21.666667
11.888889
def pattern(ref, est, **kwargs): r'''Pattern detection evaluation Parameters ---------- ref : jams.Annotation Reference annotation object est : jams.Annotation Estimated annotation object kwargs Additional keyword arguments Returns ------- scores : dict ...
[ "def", "pattern", "(", "ref", ",", "est", ",", "*", "*", "kwargs", ")", ":", "namespace", "=", "'pattern_jku'", "ref", "=", "coerce_annotation", "(", "ref", ",", "namespace", ")", "est", "=", "coerce_annotation", "(", "est", ",", "namespace", ")", "ref_p...
27.341463
20.121951
def get_categorical_feature_names(example): """Returns a list of feature names for byte type features. Args: example: An example. Returns: A list of categorical feature names (e.g. ['education', 'marital_status'] ) """ features = get_example_features(example) return sorted([ feature_name for...
[ "def", "get_categorical_feature_names", "(", "example", ")", ":", "features", "=", "get_example_features", "(", "example", ")", "return", "sorted", "(", "[", "feature_name", "for", "feature_name", "in", "features", "if", "features", "[", "feature_name", "]", ".", ...
28.857143
21.071429
def grouplabelencode(data, mapping, nacode=None, nastate=False): """Encode data array with grouped labels Parameters: ----------- data : list array with labels mapping : dict, list of list the index of each element is used as encoding. Each element is a single label (str) o...
[ "def", "grouplabelencode", "(", "data", ",", "mapping", ",", "nacode", "=", "None", ",", "nastate", "=", "False", ")", ":", "# What value is used for missing data?", "if", "nastate", ":", "if", "nacode", "is", "None", ":", "nacode", "=", "len", "(", "mapping...
31.263158
19.657895
def install_file_legacy(path, sudo=False, from_path=None, **substitutions): '''Install file with path on the host target. The from file is the first of this list which exists: * custom file * custom file.template * common file * common file.template ''' # source paths 'from_custom' ...
[ "def", "install_file_legacy", "(", "path", ",", "sudo", "=", "False", ",", "from_path", "=", "None", ",", "*", "*", "substitutions", ")", ":", "# source paths 'from_custom' and 'from_common'", "from_path", "=", "from_path", "or", "path", "# remove beginning '/' (if an...
37.704545
18.25
def child_added(self, child): """ Overwrite the content view """ view = child.widget if view is not None: self.dialog.setContentView(view)
[ "def", "child_added", "(", "self", ",", "child", ")", ":", "view", "=", "child", ".", "widget", "if", "view", "is", "not", "None", ":", "self", ".", "dialog", ".", "setContentView", "(", "view", ")" ]
34
8
def Delete(self): """Delete disk. This request will error if disk is protected and cannot be removed (e.g. a system disk) >>> clc.v2.Server("WA1BTDIX01").Disks().disks[2].Delete().WaitUntilComplete() 0 """ disk_set = [{'diskId': o.id, 'sizeGB': o.size} for o in self.parent.disks if o!=self] self.paren...
[ "def", "Delete", "(", "self", ")", ":", "disk_set", "=", "[", "{", "'diskId'", ":", "o", ".", "id", ",", "'sizeGB'", ":", "o", ".", "size", "}", "for", "o", "in", "self", ".", "parent", ".", "disks", "if", "o", "!=", "self", "]", "self", ".", ...
40.277778
30.055556
def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]: """ Return the state reachable from a given state for a particular gene. """ result: List[State] = [] active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state) transition: Transition = self.find_tr...
[ "def", "available_state_for_gene", "(", "self", ",", "gene", ":", "Gene", ",", "state", ":", "State", ")", "->", "Tuple", "[", "State", ",", "...", "]", ":", "result", ":", "List", "[", "State", "]", "=", "[", "]", "active_multiplex", ":", "Tuple", "...
52.133333
14.8
def _render(self, request, template=None, status=200, context={}, headers={}, prefix_template_path=True): """ Render a HTTP response. :param request: A django.http.HttpRequest instance. :param template: A string describing the path to a template. :param status: An integer descri...
[ "def", "_render", "(", "self", ",", "request", ",", "template", "=", "None", ",", "status", "=", "200", ",", "context", "=", "{", "}", ",", "headers", "=", "{", "}", ",", "prefix_template_path", "=", "True", ")", ":", "format", "=", "self", ".", "_...
45.109756
26.963415
def addarchive(self, name): """ Add (i.e. copy) the contents of another tarball to this one. :param name: File path to the tar archive. :type name: unicode | str """ with tarfile.open(name, 'r') as st: for member in st.getmembers(): self.tarfi...
[ "def", "addarchive", "(", "self", ",", "name", ")", ":", "with", "tarfile", ".", "open", "(", "name", ",", "'r'", ")", "as", "st", ":", "for", "member", "in", "st", ".", "getmembers", "(", ")", ":", "self", ".", "tarfile", ".", "addfile", "(", "m...
35.8
13.6
def _load_compiled(self, file_path): """ Accepts a path to a compiled plugin and returns a module object. file_path: A string that represents a complete file path to a compiled plugin. """ name = os.path.splitext(os.path.split(file_path)[-1])[0] plugin_directory ...
[ "def", "_load_compiled", "(", "self", ",", "file_path", ")", ":", "name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "file_path", ")", "[", "-", "1", "]", ")", "[", "0", "]", "plugin_directory", "=", "os", ...
45.714286
22.428571
def start_server(self, datacenter_id, server_id): """ Starts the server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` """ ...
[ "def", "start_server", "(", "self", ",", "datacenter_id", ",", "server_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/start'", "%", "(", "datacenter_id", ",", "server_id", ")", ",", "method", "=", ...
28.444444
16.444444
def upload(self, href, vobject_item): """Upload a new or replace an existing item.""" if self.is_fake: return content = vobject_item.serialize() try: item = self.get(href) etesync_item = item.etesync_item etesync_item.content = content ...
[ "def", "upload", "(", "self", ",", "href", ",", "vobject_item", ")", ":", "if", "self", ".", "is_fake", ":", "return", "content", "=", "vobject_item", ".", "serialize", "(", ")", "try", ":", "item", "=", "self", ".", "get", "(", "href", ")", "etesync...
31.3125
17.875
def _check_stop(self, iters, elapsed_time, converged): """ Defines the stopping criterion. """ r_c = self.config['resources'] stop = False if converged==0: stop=True if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']: ...
[ "def", "_check_stop", "(", "self", ",", "iters", ",", "elapsed_time", ",", "converged", ")", ":", "r_c", "=", "self", ".", "config", "[", "'resources'", "]", "stop", "=", "False", "if", "converged", "==", "0", ":", "stop", "=", "True", "if", "r_c", "...
30.333333
18.866667
def match(self, node, results=None): """ Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard...
[ "def", "match", "(", "self", ",", "node", ",", "results", "=", "None", ")", ":", "if", "self", ".", "type", "is", "not", "None", "and", "node", ".", "type", "!=", "self", ".", "type", ":", "return", "False", "if", "self", ".", "content", "is", "n...
31.291667
14.791667
def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False resp...
[ "def", "set_remote_events", "(", "enable", ")", ":", "state", "=", "__utils__", "[", "'mac_utils.validate_enabled'", "]", "(", "enable", ")", "cmd", "=", "'systemsetup -setremoteappleevents {0}'", ".", "format", "(", "state", ")", "__utils__", "[", "'mac_utils.execu...
27.535714
25.821429
def check_secure(): """Check request, return False if using SSL or local connection.""" if this.request.is_secure(): return True # using SSL elif this.request.META['REMOTE_ADDR'] in [ 'localhost', '127.0.0.1', ]: return True # loc...
[ "def", "check_secure", "(", ")", ":", "if", "this", ".", "request", ".", "is_secure", "(", ")", ":", "return", "True", "# using SSL", "elif", "this", ".", "request", ".", "META", "[", "'REMOTE_ADDR'", "]", "in", "[", "'localhost'", ",", "'127.0.0.1'", ",...
38.7
12.6
def calc_login_v1(self): """Refresh the input log sequence for the different MA processes. Required derived parameters: |Nmb| |MA_Order| Required flux sequence: |QPIn| Updated log sequence: |LogIn| Example: Assume there are three response functions, involving one...
[ "def", "calc_login_v1", "(", "self", ")", ":", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "log", "=", "self", ".", "sequences", ".", "logs", ".", "fa...
30.965517
18.068966
def check(self, instance): """ Returns a dictionary that looks a lot like what's sent back by db.serverStatus() """ def total_seconds(td): """ Returns total seconds of a timedelta in a way that's safe for Python < 2.7 """ ...
[ "def", "check", "(", "self", ",", "instance", ")", ":", "def", "total_seconds", "(", "td", ")", ":", "\"\"\"\n Returns total seconds of a timedelta in a way that's safe for\n Python < 2.7\n \"\"\"", "if", "hasattr", "(", "td", ",", "'total_sec...
41.86514
24.145038
def sympy_to_py(func, args): """ Turn a symbolic expression into a Python lambda function, which has the names of the variables and parameters as it's argument names. :param func: sympy expression :param args: variables and parameters in this model :return: lambda function to be used for numeri...
[ "def", "sympy_to_py", "(", "func", ",", "args", ")", ":", "# replace the derivatives with printable variables.", "derivatives", "=", "{", "var", ":", "Variable", "(", "var", ".", "name", ")", "for", "var", "in", "args", "if", "isinstance", "(", "var", ",", "...
43.377358
18.622642
def square_edge_grill(alpha, l=None, Dh=None, fd=None): r'''Returns the loss coefficient for a square grill or square bar screen or perforated plate with squared edges of thickness l, as shown in [1]_. for Dh < l < 50D .. math:: K = \frac{0.5(1-\alpha) + (1-\alpha^2)}{\alpha^2} else: ...
[ "def", "square_edge_grill", "(", "alpha", ",", "l", "=", "None", ",", "Dh", "=", "None", ",", "fd", "=", "None", ")", ":", "if", "Dh", "and", "l", "and", "fd", "and", "l", ">", "50", "*", "Dh", ":", "return", "(", "0.5", "*", "(", "1", "-", ...
27.055556
24.981481
def uploadFile(self, filename, ispickle=False, athome=False): """ Uploads a single file to Redunda. :param str filename: The name of the file to upload :param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False. :returns: returns nothing ...
[ "def", "uploadFile", "(", "self", ",", "filename", ",", "ispickle", "=", "False", ",", "athome", "=", "False", ")", ":", "print", "(", "\"Uploading file {} to Redunda.\"", ".", "format", "(", "filename", ")", ")", "_", ",", "tail", "=", "os", ".", "path"...
37.217391
22.913043
def grad(self, X, mean=None, lenscale=None): r""" Get the gradients of this basis w.r.t.\ the mean and length scales. Parameters ---------- x: ndarray (n, d) array of observations where n is the number of samples, and d is the dimensionality of x. ...
[ "def", "grad", "(", "self", ",", "X", ",", "mean", "=", "None", ",", "lenscale", "=", "None", ")", ":", "d", "=", "X", ".", "shape", "[", "1", "]", "mean", "=", "self", ".", "_check_dim", "(", "d", ",", "mean", ",", "paramind", "=", "0", ")",...
39.016667
21.533333
def _handle_next_task(self): """ We have to catch three ways a task can be "done": 1. normal execution: the task runs/fails and puts a result back on the queue, 2. new dependencies: the task yielded new deps that were not complete and will be rescheduled and dependencies adde...
[ "def", "_handle_next_task", "(", "self", ")", ":", "self", ".", "_idle_since", "=", "None", "while", "True", ":", "self", ".", "_purge_children", "(", ")", "# Deal with subprocess failures", "try", ":", "task_id", ",", "status", ",", "expl", ",", "missing", ...
41.434783
19.985507
def find(value, find, start=0): """ Return index of `find` in `value` beginning at `start` :param value: :param find: :param start: :return: If NOT found, return the length of `value` string """ l = len(value) if is_list(find): m = l for f in find: i = val...
[ "def", "find", "(", "value", ",", "find", ",", "start", "=", "0", ")", ":", "l", "=", "len", "(", "value", ")", "if", "is_list", "(", "find", ")", ":", "m", "=", "l", "for", "f", "in", "find", ":", "i", "=", "value", ".", "find", "(", "f", ...
23.272727
17.363636
def run(self): """ Run the task - compose full series + add to our results """ empty = False while not empty: try: s = self.series.get() result_dict = itunes.get_rss_feed_data_from_series(s) self.storer.store(result_dict) self.logger.info('Retrieved and stored %...
[ "def", "run", "(", "self", ")", ":", "empty", "=", "False", "while", "not", "empty", ":", "try", ":", "s", "=", "self", ".", "series", ".", "get", "(", ")", "result_dict", "=", "itunes", ".", "get_rss_feed_data_from_series", "(", "s", ")", "self", "....
29.4375
15.6875
def _read_coll( ctx: ReaderContext, f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]], end_token: str, coll_name: str, ): """Read a collection from the input stream and create the collection using f.""" coll: List = [] reader = ctx.reader while True: ...
[ "def", "_read_coll", "(", "ctx", ":", "ReaderContext", ",", "f", ":", "Callable", "[", "[", "Collection", "[", "Any", "]", "]", ",", "Union", "[", "llist", ".", "List", ",", "lset", ".", "Set", ",", "vector", ".", "Vector", "]", "]", ",", "end_toke...
28.916667
16.625
def single_line_stdout(cmd, expected_errors=(), shell=True, sudo=False, quiet=False): """ Runs a command and returns the first line of the result, that would be written to `stdout`, as a string. The output itself can be suppressed. :param cmd: Command to run. :type cmd: unicode :param expected_...
[ "def", "single_line_stdout", "(", "cmd", ",", "expected_errors", "=", "(", ")", ",", "shell", "=", "True", ",", "sudo", "=", "False", ",", "quiet", "=", "False", ")", ":", "return", "single_line", "(", "stdout_result", "(", "cmd", ",", "expected_errors", ...
41.4
23.5
def clone(self, **kwargs): """ Clone a part. .. versionadded:: 2.3 :param kwargs: (optional) additional keyword=value arguments :type kwargs: dict :return: cloned :class:`models.Part` :raises APIError: if the `Part` could not be cloned Example -...
[ "def", "clone", "(", "self", ",", "*", "*", "kwargs", ")", ":", "parent", "=", "self", ".", "parent", "(", ")", "return", "self", ".", "_client", ".", "_create_clone", "(", "parent", ",", "self", ",", "*", "*", "kwargs", ")" ]
25.842105
19.105263
def initialize_bfd(self, abfd): """Initialize underlying libOpcodes library using BFD.""" self._ptr = _opcodes.initialize_bfd(abfd._ptr) # Already done inside opcodes.c #self.architecture = abfd.architecture #self.machine = abfd.machine #self.endian = abfd....
[ "def", "initialize_bfd", "(", "self", ",", "abfd", ")", ":", "self", ".", "_ptr", "=", "_opcodes", ".", "initialize_bfd", "(", "abfd", ".", "_ptr", ")", "# Already done inside opcodes.c", "#self.architecture = abfd.architecture", "#self.machine = abfd.machine", "#self.e...
39.6875
12.875
def evolve(self, new_date): """ evolve to the new process state at the next date, i.e. do one step in the simulation :param date new_date: date of the new state :return State: """ if self.state.date == new_date and not self.initial_state.date == new_date: ret...
[ "def", "evolve", "(", "self", ",", "new_date", ")", ":", "if", "self", ".", "state", ".", "date", "==", "new_date", "and", "not", "self", ".", "initial_state", ".", "date", "==", "new_date", ":", "return", "self", ".", "state", "self", ".", "state", ...
36.916667
18.916667
def _JMS_to_Bern_I(C, qq): """From JMS to BernI basis (= traditional SUSY basis in this case) for $\Delta F=2$ operators. `qq` should be 'sb', 'db', 'ds' or 'cu'""" if qq in ['sb', 'db', 'ds']: dd = 'dd' ij = tuple(dflav[q] for q in qq) elif qq == 'cu': dd = 'uu' ij =...
[ "def", "_JMS_to_Bern_I", "(", "C", ",", "qq", ")", ":", "if", "qq", "in", "[", "'sb'", ",", "'db'", ",", "'ds'", "]", ":", "dd", "=", "'dd'", "ij", "=", "tuple", "(", "dflav", "[", "q", "]", "for", "q", "in", "qq", ")", "elif", "qq", "==", ...
41.814815
17.592593
def list_l3_agent_hosting_routers(self, router, **_params): """Fetches a list of L3 agents hosting a router.""" return self.get((self.router_path + self.L3_AGENTS) % router, params=_params)
[ "def", "list_l3_agent_hosting_routers", "(", "self", ",", "router", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "(", "self", ".", "router_path", "+", "self", ".", "L3_AGENTS", ")", "%", "router", ",", "params", "=", "_params", ...
56.5
12.25
def _write_ccr(self, f, g, level: int): ''' Write a CCR to file "g" from file "f" with level "level". Currently, only handles gzip compression. Parameters: f : file Uncompressed file to read from g : file File to read the compresse...
[ "def", "_write_ccr", "(", "self", ",", "f", ",", "g", ",", "level", ":", "int", ")", ":", "f", ".", "seek", "(", "8", ")", "data", "=", "f", ".", "read", "(", ")", "uSize", "=", "len", "(", "data", ")", "section_type", "=", "CDF", ".", "CCR_"...
33.405405
17.837838
def _const_node_to_py_ast(ctx: GeneratorContext, lisp_ast: Const) -> GeneratedPyAST: """Generate Python AST nodes for a :const Lisp AST node. Nested values in collections for :const nodes are not parsed. Consequently, this function cannot be called recursively for those nested values. Instead, call `_c...
[ "def", "_const_node_to_py_ast", "(", "ctx", ":", "GeneratorContext", ",", "lisp_ast", ":", "Const", ")", "->", "GeneratedPyAST", ":", "assert", "lisp_ast", ".", "op", "==", "NodeOp", ".", "CONST", "node_type", "=", "lisp_ast", ".", "type", "handle_const_node", ...
52.916667
21.25
def safe_re_encode(s, encoding_to, errors="backslashreplace"): """Re-encode str or binary so that is compatible with a given encoding (replacing unsupported chars). We use ASCII as default, which gives us some output that contains \x99 and \u9999 for every character > 127, for easier debugging. (e....
[ "def", "safe_re_encode", "(", "s", ",", "encoding_to", ",", "errors", "=", "\"backslashreplace\"", ")", ":", "# prev = s", "if", "not", "encoding_to", ":", "encoding_to", "=", "\"ASCII\"", "if", "compat", ".", "is_bytes", "(", "s", ")", ":", "s", "=", "s",...
40.529412
21.470588
def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:5...
[ "def", "get_host", "(", "name", "=", "None", ",", "ipv4addr", "=", "None", ",", "mac", "=", "None", ",", "return_fields", "=", "None", ",", "*", "*", "api_opts", ")", ":", "infoblox", "=", "_get_infoblox", "(", "*", "*", "api_opts", ")", "host", "=",...
32.066667
27.533333
def graft_neuron(root_section): '''Returns a neuron starting at root_section''' assert isinstance(root_section, Section) return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)])
[ "def", "graft_neuron", "(", "root_section", ")", ":", "assert", "isinstance", "(", "root_section", ",", "Section", ")", "return", "Neuron", "(", "soma", "=", "Soma", "(", "root_section", ".", "points", "[", ":", "1", "]", ")", ",", "neurites", "=", "[", ...
53.25
17.75
def file(self, path): """ Reads the body to match from a disk file. Arguments: path (str): relative or absolute path to file to read from. Returns: self: current Mock instance. """ with open(path, 'r') as f: self.body(str(f.read()))
[ "def", "file", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "self", ".", "body", "(", "str", "(", "f", ".", "read", "(", ")", ")", ")" ]
25.583333
16.25
def list_adresposities_by_subadres_and_huisnummer(self, subadres, huisnummer): ''' List all `adresposities` for a subadres and a :class:`Huisnummer`. :param subadres: A string representing a certain subadres. :param huisnummer: The :class:`Huisnummer` for which the \ `adresp...
[ "def", "list_adresposities_by_subadres_and_huisnummer", "(", "self", ",", "subadres", ",", "huisnummer", ")", ":", "try", ":", "hid", "=", "huisnummer", ".", "id", "except", "AttributeError", ":", "hid", "=", "huisnummer", "def", "creator", "(", ")", ":", "res...
38.71875
18.34375
def add_role(self, role, description=None): """ Creates a new group """ new_group = AuthGroup(role=role, creator=self.client) try: new_group.save() return True except NotUniqueError: return False
[ "def", "add_role", "(", "self", ",", "role", ",", "description", "=", "None", ")", ":", "new_group", "=", "AuthGroup", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", "try", ":", "new_group", ".", "save", "(", ")", "return"...
32
13.375
def to_list(item_or_list): """ Convert a single item, a tuple, a generator or anything else to a list. :param item_or_list: single item or iterable to convert :return: a list """ if isinstance(item_or_list, list): return item_or_list elif isinstance(item_or_list, (str, bytes)): ...
[ "def", "to_list", "(", "item_or_list", ")", ":", "if", "isinstance", "(", "item_or_list", ",", "list", ")", ":", "return", "item_or_list", "elif", "isinstance", "(", "item_or_list", ",", "(", "str", ",", "bytes", ")", ")", ":", "return", "[", "item_or_list...
30
14.4
def build_constraints(self, coef, constraint_lam, constraint_l2): """ builds the GAM block-diagonal constraint matrix in quadratic form out of constraint matrices specified for each feature. Parameters ---------- coefs : array-like containing the coefficients of a term ...
[ "def", "build_constraints", "(", "self", ",", "coef", ",", "constraint_lam", ",", "constraint_l2", ")", ":", "C", "=", "sp", ".", "sparse", ".", "csc_matrix", "(", "np", ".", "zeros", "(", "(", "self", ".", "n_coefs", ",", "self", ".", "n_coefs", ")", ...
33.62069
24.310345