text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def sign(self, data): """Sign a bytes-like object using the signing (private) key. :param bytes data: The data to sign :return: The signed data :rtype: bytes """ if self.signing_key is None: raise MissingSigningKeyError("KeyPair does not contain secret key. "...
[ "def", "sign", "(", "self", ",", "data", ")", ":", "if", "self", ".", "signing_key", "is", "None", ":", "raise", "MissingSigningKeyError", "(", "\"KeyPair does not contain secret key. \"", "\"Use Keypair.from_seed method to create a new keypair with a secret key.\"", ")", "...
42.636364
0.008351
def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False): """Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exi...
[ "def", "create_complete_files", "(", "climan", ",", "path", ",", "cmd", ",", "*", "cmds", ",", "zsh_sourceable", "=", "False", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "path", ")", "zsh_dir", "=", "path", "/", "'zsh'", "if", "not", "zsh_dir"...
43.791667
0.000931
def register_machine(self, machine): """Registers the machine previously created using :py:func:`create_machine` or opened using :py:func:`open_machine` within this VirtualBox installation. After successful method invocation, the :py:class:`IMachineRegisteredEvent` event is fi...
[ "def", "register_machine", "(", "self", ",", "machine", ")", ":", "if", "not", "isinstance", "(", "machine", ",", "IMachine", ")", ":", "raise", "TypeError", "(", "\"machine can only be an instance of type IMachine\"", ")", "self", ".", "_call", "(", "\"registerMa...
40.041667
0.00813
def wait_for_completion(self, operation_timeout=None): """ Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully. If the job completed in error, an :exc:`~zhmcclient.HTTPError...
[ "def", "wait_for_completion", "(", "self", ",", "operation_timeout", "=", "None", ")", ":", "if", "operation_timeout", "is", "None", ":", "operation_timeout", "=", "self", ".", "session", ".", "retry_timeout_config", ".", "operation_timeout", "if", "operation_timeou...
40.811594
0.000693
def _parse_body(self, body): """ For just call a deserializer for FORMAT""" if is_python3(): return json.loads(body.decode('UTF-8')) else: return json.loads(body)
[ "def", "_parse_body", "(", "self", ",", "body", ")", ":", "if", "is_python3", "(", ")", ":", "return", "json", ".", "loads", "(", "body", ".", "decode", "(", "'UTF-8'", ")", ")", "else", ":", "return", "json", ".", "loads", "(", "body", ")" ]
30.166667
0.016129
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int: """Sum the total number of cycles over a list of tokens.""" return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))
[ "def", "_sum_cycles_from_tokens", "(", "self", ",", "tokens", ":", "List", "[", "str", "]", ")", "->", "int", ":", "return", "sum", "(", "(", "int", "(", "self", ".", "_nonnumber_pattern", ".", "sub", "(", "''", ",", "t", ")", ")", "for", "t", "in"...
68
0.009709
def _kappaShapelets(self, shapelets, beta): """ calculates the convergence kappa given lensing potential shapelet coefficients (laplacian/2) :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :returns: set of kappa shapelets. :raises: A...
[ "def", "_kappaShapelets", "(", "self", ",", "shapelets", ",", "beta", ")", ":", "output", "=", "np", ".", "zeros", "(", "(", "len", "(", "shapelets", ")", "+", "1", ",", "len", "(", "shapelets", ")", "+", "1", ")", ",", "'complex'", ")", "for", "...
45.45
0.017241
def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='master'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2014.7.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be eith...
[ "def", "event", "(", "tagmatch", "=", "'*'", ",", "count", "=", "-", "1", ",", "quiet", "=", "False", ",", "sock_dir", "=", "None", ",", "pretty", "=", "False", ",", "node", "=", "'master'", ")", ":", "statemod", "=", "salt", ".", "loader", ".", ...
35.603175
0.000868
def _fromfile(self): """Read TIFF IFD structure and its tags from file. File cursor must be at storage position of IFD offset and is left at offset to next IFD. Raises StopIteration if offset (first bytes read) is 0. """ fd = self.parent._fd byte_order = self.p...
[ "def", "_fromfile", "(", "self", ")", ":", "fd", "=", "self", ".", "parent", ".", "_fd", "byte_order", "=", "self", ".", "parent", ".", "byte_order", "offset_size", "=", "self", ".", "parent", ".", "offset_size", "fmt", "=", "{", "4", ":", "'I'", ","...
31.583333
0.00128
def splitpath(self): """ p.splitpath() -> Return (p.parent, p.name). """ parent, child = os.path.split(self) return self.__class__(parent), child
[ "def", "splitpath", "(", "self", ")", ":", "parent", ",", "child", "=", "os", ".", "path", ".", "split", "(", "self", ")", "return", "self", ".", "__class__", "(", "parent", ")", ",", "child" ]
41.5
0.011834
def watch_firings(self, flag): """Whether or not the Rule firings are being watched.""" lib.EnvSetDefruleWatchFirings(self._env, int(flag), self._rule)
[ "def", "watch_firings", "(", "self", ",", "flag", ")", ":", "lib", ".", "EnvSetDefruleWatchFirings", "(", "self", ".", "_env", ",", "int", "(", "flag", ")", ",", "self", ".", "_rule", ")" ]
55
0.011976
def forward_word(self, e): # (M-f) u"""Move forward to the end of the next word. Words are composed of letters and digits.""" self.l_buffer.forward_word(self.argument_reset) self.finalize()
[ "def", "forward_word", "(", "self", ",", "e", ")", ":", "# (M-f)\r", "self", ".", "l_buffer", ".", "forward_word", "(", "self", ".", "argument_reset", ")", "self", ".", "finalize", "(", ")" ]
44.2
0.013333
def from_code(cls, co): """Disassemble a Python code object into a Code object.""" co_code = co.co_code labels = dict((addr, Label()) for addr in findlabels(co_code)) linestarts = dict(cls._findlinestarts(co)) cellfree = co.co_cellvars + co.co_freevars code = CodeList() ...
[ "def", "from_code", "(", "cls", ",", "co", ")", ":", "co_code", "=", "co", ".", "co_code", "labels", "=", "dict", "(", "(", "addr", ",", "Label", "(", ")", ")", "for", "addr", "in", "findlabels", "(", "co_code", ")", ")", "linestarts", "=", "dict",...
39.397059
0.008012
def toggle(self, ax=None): """Creates a play/pause button to start/stop the animation Parameters ---------- ax : matplotlib.axes.Axes, optional The matplotlib axes to attach the button to. """ if ax is None: adjust_plot = {'bottom': .2} ...
[ "def", "toggle", "(", "self", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "adjust_plot", "=", "{", "'bottom'", ":", ".2", "}", "rect", "=", "[", ".78", ",", ".03", ",", ".1", ",", ".07", "]", "plt", ".", "subplots_adjust", ...
33.210526
0.00154
def by_name(name): """Return a device by name. Args: name (str): The name of the device to return. Returns: :class:`~.SoCo`: The first device encountered among all zone with the given player name. If none are found `None` is returned. """ devices = discover(all_househol...
[ "def", "by_name", "(", "name", ")", ":", "devices", "=", "discover", "(", "all_households", "=", "True", ")", "for", "device", "in", "(", "devices", "or", "[", "]", ")", ":", "if", "device", ".", "player_name", "==", "name", ":", "return", "device", ...
28.666667
0.002252
def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
[ "def", "add_example", "(", "self", ",", "example", ")", ":", "self", ".", "check_example", "(", "example", ")", "self", ".", "examples", ".", "append", "(", "example", ")" ]
42.75
0.011494
def get_values(self): """ Returns: the selected instruments """ elements_selected = {} for index in range(self.tree_loaded_model.rowCount()): element_name = str(self.tree_loaded_model.item(index).text()) if element_name in self.elements_old: ...
[ "def", "get_values", "(", "self", ")", ":", "elements_selected", "=", "{", "}", "for", "index", "in", "range", "(", "self", ".", "tree_loaded_model", ".", "rowCount", "(", ")", ")", ":", "element_name", "=", "str", "(", "self", ".", "tree_loaded_model", ...
40.785714
0.008562
def indentjoin(strlist, indent='\n ', suffix=''): r""" Convineince indentjoin similar to '\n '.join(strlist) but indent is also prefixed Args: strlist (?): indent (str): suffix (str): Returns: str: joined list """ indent_ = indent strlist = list...
[ "def", "indentjoin", "(", "strlist", ",", "indent", "=", "'\\n '", ",", "suffix", "=", "''", ")", ":", "indent_", "=", "indent", "strlist", "=", "list", "(", "strlist", ")", "if", "len", "(", "strlist", ")", "==", "0", ":", "return", "''", "return...
23.75
0.002024
def _determine_current_dimension_size(self, dim_name, max_size): """ Helper method to determine the current size of a dimension. """ # Limited dimension. if self.dimensions[dim_name] is not None: return max_size def _find_dim(h5group, dim): if dim...
[ "def", "_determine_current_dimension_size", "(", "self", ",", "dim_name", ",", "max_size", ")", ":", "# Limited dimension.", "if", "self", ".", "dimensions", "[", "dim_name", "]", "is", "not", "None", ":", "return", "max_size", "def", "_find_dim", "(", "h5group"...
31.535714
0.002198
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Returns a new dataset with each array indexed along the specified dimension(s). This method selects values from each array using its `__getitem__` method, except this method does not require knowing the order of ea...
[ "def", "isel", "(", "self", ",", "indexers", "=", "None", ",", "drop", "=", "False", ",", "*", "*", "indexers_kwargs", ")", ":", "indexers", "=", "either_dict_or_kwargs", "(", "indexers", ",", "indexers_kwargs", ",", "'isel'", ")", "indexers_list", "=", "s...
41.184211
0.000624
def spkcov(spk, idcode, cover=None): """ Find the coverage window for a specified ephemeris object in a specified SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcov_c.html :param spk: Name of SPK file. :type spk: str :param idcode: ID code of ephemeris object. :ty...
[ "def", "spkcov", "(", "spk", ",", "idcode", ",", "cover", "=", "None", ")", ":", "spk", "=", "stypes", ".", "stringToCharP", "(", "spk", ")", "idcode", "=", "ctypes", ".", "c_int", "(", "idcode", ")", "if", "cover", "is", "None", ":", "cover", "=",...
33.043478
0.001279
def schedule_hangup(self, call_params): """REST Schedule Hangup Helper """ path = '/' + self.api_version + '/ScheduleHangup/' method = 'POST' return self.request(path, method, call_params)
[ "def", "schedule_hangup", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ScheduleHangup/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ...
37.166667
0.008772
def asyncio_run_forever(setup_coro, shutdown_coro, *, stop_signals={signal.SIGINT}, debug=False): ''' A proposed-but-not-implemented asyncio.run_forever() API based on @vxgmichel's idea. See discussions on https://github.com/python/asyncio/pull/465 ''' async def wait_for_...
[ "def", "asyncio_run_forever", "(", "setup_coro", ",", "shutdown_coro", ",", "*", ",", "stop_signals", "=", "{", "signal", ".", "SIGINT", "}", ",", "debug", "=", "False", ")", ":", "async", "def", "wait_for_stop", "(", ")", ":", "loop", "=", "current_loop",...
35.25
0.000863
def start_supporting_containers(sitedir, srcdir, passwords, get_container_name, extra_containers, log_syslog=False): """ Start all supporting containers (containers required for CKAN to operate) if they aren't already running, along with some extra containers specified by the user """ if...
[ "def", "start_supporting_containers", "(", "sitedir", ",", "srcdir", ",", "passwords", ",", "get_container_name", ",", "extra_containers", ",", "log_syslog", "=", "False", ")", ":", "if", "docker", ".", "is_boot2docker", "(", ")", ":", "docker", ".", "data_only_...
37.907407
0.002381
def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader: "Returns appropriate `Dataset` for validation, training, or test (`ds_type`)." #TODO: refactor return (self.train_dl if ds_type == DatasetType.Train else self.test_dl if ds_type == DatasetType.Test else ...
[ "def", "dl", "(", "self", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ")", "->", "DeviceDataLoader", ":", "#TODO: refactor", "return", "(", "self", ".", "train_dl", "if", "ds_type", "==", "DatasetType", ".", "Train", "else", "self",...
58.875
0.016736
def setup_data(self, data, params): """ Verify & return data """ check_required_aesthetics( self.REQUIRED_AES, data.columns, self.__class__.__name__) return data
[ "def", "setup_data", "(", "self", ",", "data", ",", "params", ")", ":", "check_required_aesthetics", "(", "self", ".", "REQUIRED_AES", ",", "data", ".", "columns", ",", "self", ".", "__class__", ".", "__name__", ")", "return", "data" ]
25.444444
0.008439
def get_config_attribute(self, name, attribute): """ Look for the attribute in the config. Start with the named module and then walk up through any containing group and then try the general section of the config. """ # A user can set a param to None in the config to pre...
[ "def", "get_config_attribute", "(", "self", ",", "name", ",", "attribute", ")", ":", "# A user can set a param to None in the config to prevent a param", "# being used. This is important when modules do something like", "#", "# color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD", "confi...
43.325
0.001129
def p_ioport_width(self, p): 'ioport : sigtypes width portname' p[0] = self.create_ioport(p[1], p[3], width=p[2], lineno=p.lineno(3)) p.set_lineno(0, p.lineno(1))
[ "def", "p_ioport_width", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "create_ioport", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "width", "=", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno"...
45.75
0.010753
def service(cls): ''' Marks the decorated class as a singleton ``service``. Injects following classmethods: .. py:method:: .get(context) Returns a singleton instance of the class for given ``context`` :param context: context to look in :type context: :class:`C...
[ "def", "service", "(", "cls", ")", ":", "if", "not", "cls", ":", "return", "None", "# Inject methods", "def", "get", "(", "cls", ",", "context", ")", ":", "return", "context", ".", "get_service", "(", "cls", ")", "cls", ".", "get", "=", "get", ".", ...
22.038462
0.001672
def get_resources_of_type(network_id, type_id, **kwargs): """ Return the Nodes, Links and ResourceGroups which have the type specified. """ nodes_with_type = db.DBSession.query(Node).join(ResourceType).filter(Node.network_id==network_id, ResourceType.type_id==type_id).all() links_with_t...
[ "def", "get_resources_of_type", "(", "network_id", ",", "type_id", ",", "*", "*", "kwargs", ")", ":", "nodes_with_type", "=", "db", ".", "DBSession", ".", "query", "(", "Node", ")", ".", "join", "(", "ResourceType", ")", ".", "filter", "(", "Node", ".", ...
59.363636
0.015083
def update_metadata(self, loadbalancer, metadata, node=None): """ Updates the existing metadata with the supplied dictionary. If 'node' is supplied, the metadata for that node is updated instead of for the load balancer. """ # Get the existing metadata md = self.g...
[ "def", "update_metadata", "(", "self", ",", "loadbalancer", ",", "metadata", ",", "node", "=", "None", ")", ":", "# Get the existing metadata", "md", "=", "self", ".", "get_metadata", "(", "loadbalancer", ",", "raw", "=", "True", ")", "id_lookup", "=", "dict...
46.529412
0.001858
def labels(self): """ Returns the list of labels that will be used to represent this axis' information. :return [<str>, ..] """ if self._labels is None: self._labels = map(self.labelFormat().format, self.values()) return self._lab...
[ "def", "labels", "(", "self", ")", ":", "if", "self", ".", "_labels", "is", "None", ":", "self", ".", "_labels", "=", "map", "(", "self", ".", "labelFormat", "(", ")", ".", "format", ",", "self", ".", "values", "(", ")", ")", "return", "self", "....
31.4
0.009288
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0): """KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var)...
[ "def", "kl_divergence", "(", "mu", ",", "log_var", ",", "mu_p", "=", "0.0", ",", "log_var_p", "=", "0.0", ")", ":", "batch_size", "=", "shape_list", "(", "mu", ")", "[", "0", "]", "prior_distribution", "=", "tfp", ".", "distributions", ".", "Normal", "...
38.7
0.008827
def _init_idxs_strpat(self, usr_hdrs): """List of indexes whose values will be strings.""" strpat = self.strpat_hdrs.keys() self.idxs_strpat = [ Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in strpat]
[ "def", "_init_idxs_strpat", "(", "self", ",", "usr_hdrs", ")", ":", "strpat", "=", "self", ".", "strpat_hdrs", ".", "keys", "(", ")", "self", ".", "idxs_strpat", "=", "[", "Idx", "for", "Hdr", ",", "Idx", "in", "self", ".", "hdr2idx", ".", "items", "...
51
0.011583
def get_product_order_book(self, product_id, level=1): """Get a list of open orders for a product. The amount of detail shown can be customized with the `level` parameter: * 1: Only the best bid and ask * 2: Top 50 bids and asks (aggregated) * 3: Full order book (non agg...
[ "def", "get_product_order_book", "(", "self", ",", "product_id", ",", "level", "=", "1", ")", ":", "params", "=", "{", "'level'", ":", "level", "}", "return", "self", ".", "_send_message", "(", "'get'", ",", "'/products/{}/book'", ".", "format", "(", "prod...
35.25641
0.001415
def main(options): """A simple connection test to login and print the server time.""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) print(client.si.CurrentTime()) client.logout()
[ "def", "main", "(", "options", ")", ":", "client", "=", "Client", "(", "server", "=", "options", ".", "server", ",", "username", "=", "options", ".", "username", ",", "password", "=", "options", ".", "password", ")", "print", "(", "'Successfully connected ...
38.25
0.01278
def send(self): """ Sends the report to IOpipe. """ if self.sent is True: return self.sent = True logger.debug("Sending report to IOpipe:") logger.debug(json.dumps(self.report, indent=2, sort_keys=True)) self.client.submit_future(send_report,...
[ "def", "send", "(", "self", ")", ":", "if", "self", ".", "sent", "is", "True", ":", "return", "self", ".", "sent", "=", "True", "logger", ".", "debug", "(", "\"Sending report to IOpipe:\"", ")", "logger", ".", "debug", "(", "json", ".", "dumps", "(", ...
29.166667
0.00831
def _states(self, state, processedstates=[]): #pylint: disable=dangerous-default-value """Iterate over all states in no particular order""" processedstates.append(state) for nextstate in state.epsilon: if not nextstate in processedstates: self._states(nextstate, proc...
[ "def", "_states", "(", "self", ",", "state", ",", "processedstates", "=", "[", "]", ")", ":", "#pylint: disable=dangerous-default-value", "processedstates", ".", "append", "(", "state", ")", "for", "nextstate", "in", "state", ".", "epsilon", ":", "if", "not", ...
38.923077
0.013514
def register(self, resource, event, trigger, **kwargs): """Called in trunk plugin's AFTER_INIT""" super(AristaTrunkDriver, self).register(resource, event, trigger, kwargs) registry.subscribe(self.subport_create, resources...
[ "def", "register", "(", "self", ",", "resource", ",", "event", ",", "trigger", ",", "*", "*", "kwargs", ")", ":", "super", "(", "AristaTrunkDriver", ",", "self", ")", ".", "register", "(", "resource", ",", "event", ",", "trigger", ",", "kwargs", ")", ...
55.5625
0.002212
def hist_path(self): """Absolute path of the HIST file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._hist_path except AttributeError: path = self.outdir.has_abiext("HIST") if path: sel...
[ "def", "hist_path", "(", "self", ")", ":", "# Lazy property to avoid multiple calls to has_abiext.", "try", ":", "return", "self", ".", "_hist_path", "except", "AttributeError", ":", "path", "=", "self", ".", "outdir", ".", "has_abiext", "(", "\"HIST\"", ")", "if"...
39.444444
0.011019
def makePickle(self, record): """ Use JSON. """ #ei = record.exc_info #if ei: # dummy = self.format(record) # just to get traceback text into record.exc_text # record.exc_info = None # to avoid Unpickleable error s = '%s%s:%i:%s\n' % (self.prefix, r...
[ "def", "makePickle", "(", "self", ",", "record", ")", ":", "#ei = record.exc_info", "#if ei:", "# dummy = self.format(record) # just to get traceback text into record.exc_text", "# record.exc_info = None # to avoid Unpickleable error", "s", "=", "'%s%s:%i:%s\\n'", "%", "(", ...
37.416667
0.015217
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
[ "def", "parse", "(", "self", ",", "inputstring", ",", "document", ")", ":", "link", "=", "json", ".", "loads", "(", "inputstring", ")", "env", "=", "document", ".", "settings", ".", "env", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "e...
41.346939
0.001446
def re_get(self, pattern): """Return values whose key matches `pattern` :param pattern: Regular expression :return: Found values, as a dict. """ return {k: self[k] for k in self.re_keys(pattern)}
[ "def", "re_get", "(", "self", ",", "pattern", ")", ":", "return", "{", "k", ":", "self", "[", "k", "]", "for", "k", "in", "self", ".", "re_keys", "(", "pattern", ")", "}" ]
32.857143
0.008475
def _partialParseTimeStr(self, s, sourceTime): """ test if giving C{s} matched CRE_TIME, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base ...
[ "def", "_partialParseTimeStr", "(", "self", ",", "s", ",", "sourceTime", ")", ":", "parseStr", "=", "None", "chunk1", "=", "chunk2", "=", "''", "# Natural language time strings", "m", "=", "self", ".", "ptc", ".", "CRE_TIME", ".", "search", "(", "s", ")", ...
32.351351
0.001622
def get_news(self): """ function to get news articles """ if self.topic is None or self.topic is 'Top Stories': resp = requests.get(top_news_url, params=self.params_dict) else: topic_code = topicMap[process.extractOne(self.topic, self.topics)[0]] ...
[ "def", "get_news", "(", "self", ")", ":", "if", "self", ".", "topic", "is", "None", "or", "self", ".", "topic", "is", "'Top Stories'", ":", "resp", "=", "requests", ".", "get", "(", "top_news_url", ",", "params", "=", "self", ".", "params_dict", ")", ...
43.3
0.00905
def T(a,b): """ Simple interface to the kinetic function. >>> from pyquante2 import pgbf,cgbf >>> from pyquante2.basis.pgbf import pgbf >>> s = pgbf(1) >>> isclose(T(s,s),1.5) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(T(sc,sc),1.5) True >>> sc = cgbf(exps=[1],coefs...
[ "def", "T", "(", "a", ",", "b", ")", ":", "if", "b", ".", "contracted", ":", "return", "sum", "(", "cb", "*", "T", "(", "pb", ",", "a", ")", "for", "(", "cb", ",", "pb", ")", "in", "b", ")", "elif", "a", ".", "contracted", ":", "return", ...
25.038462
0.014793
def update_project_files(cfg, proj_version): """ Update version string in project files :rtype : dict :param cfg:project configuration :param proj_version:current version :return:dict :raise ValueError: """ counters = {'files': 0, 'changes': 0} for project_file in cfg.files: ...
[ "def", "update_project_files", "(", "cfg", ",", "proj_version", ")", ":", "counters", "=", "{", "'files'", ":", "0", ",", "'changes'", ":", "0", "}", "for", "project_file", "in", "cfg", ".", "files", ":", "if", "not", "project_file", ".", "file", ".", ...
33.968254
0.002271
def course_register_user(self, course, username=None, password=None, force=False): """ Register a user to the course :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :param password: Password ...
[ "def", "course_register_user", "(", "self", ",", "course", ",", "username", "=", "None", ",", "password", "=", "None", ",", "force", "=", "False", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "session_username", "(", ")", ...
50.888889
0.00857
def version_gt(version, gt): """ Code for parsing simple, numeric versions. Letters will be stripped prior to comparison. Simple appendages such as 1-rc1 are supported. Test cases for function are present on dscan/tests/fingerprint_tests.py """ version_split = strip_letters(version).split('.') ...
[ "def", "version_gt", "(", "version", ",", "gt", ")", ":", "version_split", "=", "strip_letters", "(", "version", ")", ".", "split", "(", "'.'", ")", "gt_split", "=", "strip_letters", "(", "gt", ")", ".", "split", "(", "'.'", ")", "v_len", "=", "len", ...
25.93
0.001486
def xpointerNewContext(self, here, origin): """Create a new XPointer context """ if here is None: here__o = None else: here__o = here._o if origin is None: origin__o = None else: origin__o = origin._o ret = libxml2mod.xmlXPtrNewContext(self._o, here__o, origin__o) ...
[ "def", "xpointerNewContext", "(", "self", ",", "here", ",", "origin", ")", ":", "if", "here", "is", "None", ":", "here__o", "=", "None", "else", ":", "here__o", "=", "here", ".", "_o", "if", "origin", "is", "None", ":", "origin__o", "=", "None", "els...
43.2
0.018141
def expression_filters(self): """ Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, ExpressionFilter)}
[ "def", "expression_filters", "(", "self", ")", ":", "return", "{", "name", ":", "filter", "for", "name", ",", "filter", "in", "iter", "(", "self", ".", "filters", ".", "items", "(", ")", ")", "if", "isinstance", "(", "filter", ",", "ExpressionFilter", ...
43.666667
0.011236
def makeDirectory(self, full_path, dummy = 40841): """Make a directory >>> nd.makeDirectory('/test') :param full_path: The full path to get the directory property. Should be end with '/'. :return: ``True`` when success to make a directory or ``False`` """ i...
[ "def", "makeDirectory", "(", "self", ",", "full_path", ",", "dummy", "=", "40841", ")", ":", "if", "full_path", "[", "-", "1", "]", "is", "not", "'/'", ":", "full_path", "+=", "'/'", "data", "=", "{", "'dstresource'", ":", "full_path", ",", "'userid'",...
28.761905
0.009615
def setPWMFrequency(self, pwm, device=DEFAULT_DEVICE_ID, message=True): """ Set the PWM frequency. :Parameters: pwm : `int` The PWN frequency to set in hertz. :Keywords: device : `int` The device is the integer number of the hardware devices ...
[ "def", "setPWMFrequency", "(", "self", ",", "pwm", ",", "device", "=", "DEFAULT_DEVICE_ID", ",", "message", "=", "True", ")", ":", "return", "self", ".", "_setPWMFrequency", "(", "pwm", ",", "device", ",", "message", ")" ]
34.076923
0.002195
def _new_name(method, old_name): """Return a method with a deprecation warning.""" # Looks suspiciously like a decorator, but isn't! @wraps(method) def _method(*args, **kwargs): warnings.warn( "method '{}' has been deprecated, please rename to '{}'".format( old_name,...
[ "def", "_new_name", "(", "method", ",", "old_name", ")", ":", "# Looks suspiciously like a decorator, but isn't!", "@", "wraps", "(", "method", ")", "def", "_method", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"metho...
26.2
0.001473
def transformer_ae_base(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
[ "def", "transformer_ae_base", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "4096", "hparams", ".", "num_hidden_layers", ...
27.5
0.035242
def save_function_tuple(self, func): """ Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces ...
[ "def", "save_function_tuple", "(", "self", ",", "func", ")", ":", "if", "is_tornado_coroutine", "(", "func", ")", ":", "self", ".", "save_reduce", "(", "_rebuild_tornado_coroutine", ",", "(", "func", ".", "__wrapped__", ",", ")", ",", "obj", "=", "func", "...
37.3125
0.001632
def to_xyz(self, buf=None, sort_index=True, index=False, header=False, float_format='{:.6f}'.format, overwrite=True): """Write xyz-file Args: buf (str): StringIO-like, optional buffer to write to sort_index (bool): If sort_index is true, the ...
[ "def", "to_xyz", "(", "self", ",", "buf", "=", "None", ",", "sort_index", "=", "True", ",", "index", "=", "False", ",", "header", "=", "False", ",", "float_format", "=", "'{:.6f}'", ".", "format", ",", "overwrite", "=", "True", ")", ":", "if", "sort_...
41.795455
0.002125
def get_base_domain(domain, use_fresh_psl=False): """ Gets the base domain name for the given domain .. note:: Results are based on a list of public domain suffixes at https://publicsuffix.org/list/public_suffix_list.dat. Args: domain (str): A domain or subdomain use_fr...
[ "def", "get_base_domain", "(", "domain", ",", "use_fresh_psl", "=", "False", ")", ":", "psl_path", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "\"public_suffix_list.dat\"", ")", "def", "download_psl", "(", ")", ":", "url", "=", "\"https://publi...
35.272727
0.000627
def update_storage_class(self, new_class, client=None): """Update blob's storage class via a rewrite-in-place. This helper will wait for the rewrite to complete before returning, so it may take some time for large files. See https://cloud.google.com/storage/docs/per-object-stora...
[ "def", "update_storage_class", "(", "self", ",", "new_class", ",", "client", "=", "None", ")", ":", "if", "new_class", "not", "in", "self", ".", "_STORAGE_CLASSES", ":", "raise", "ValueError", "(", "\"Invalid storage class: %s\"", "%", "(", "new_class", ",", "...
41.821429
0.001669
def scaled_pressure_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' The pressure readings for the typical setup of one absolute and differential pressure sensor. The units are as specified in each field. ...
[ "def", "scaled_pressure_send", "(", "self", ",", "time_boot_ms", ",", "press_abs", ",", "press_diff", ",", "temperature", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "scaled_pressure_encode", "(", "time_boot_ms...
64.076923
0.009467
async def connect(self, *args, **kwargs): """Connect to a Juju controller. This supports two calling conventions: The controller and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``controller...
[ "async", "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "disconnect", "(", ")", "if", "'endpoint'", "not", "in", "kwargs", "and", "len", "(", "args", ")", "<", "2", ":", "if", "args", "an...
47.025
0.000521
def _get_shells(): ''' Return the valid shells on this system ''' start = time.time() if 'sh.last_shells' in __context__: if start - __context__['sh.last_shells'] > 5: __context__['sh.last_shells'] = start else: __context__['sh.shells'] = __salt__['cmd.shells'...
[ "def", "_get_shells", "(", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "'sh.last_shells'", "in", "__context__", ":", "if", "start", "-", "__context__", "[", "'sh.last_shells'", "]", ">", "5", ":", "__context__", "[", "'sh.last_shells'", "]...
33
0.002105
def _init_actions(self, create_standard_actions): """ Init context menu action """ menu_advanced = QtWidgets.QMenu(_('Advanced')) self.add_menu(menu_advanced) self._sub_menus = { 'Advanced': menu_advanced } if create_standard_actions: # Undo ...
[ "def", "_init_actions", "(", "self", ",", "create_standard_actions", ")", ":", "menu_advanced", "=", "QtWidgets", ".", "QMenu", "(", "_", "(", "'Advanced'", ")", ")", "self", ".", "add_menu", "(", "menu_advanced", ")", "self", ".", "_sub_menus", "=", "{", ...
43.537736
0.000424
def show_ring(devname): ''' Queries the specified network device for rx/tx ring parameter information CLI Example: .. code-block:: bash salt '*' ethtool.show_ring <devname> ''' try: ring = ethtool.get_ringparam(devname) except IOError: log.error('Ring parameters n...
[ "def", "show_ring", "(", "devname", ")", ":", "try", ":", "ring", "=", "ethtool", ".", "get_ringparam", "(", "devname", ")", "except", "IOError", ":", "log", ".", "error", "(", "'Ring parameters not supported on %s'", ",", "devname", ")", "return", "'Not suppo...
21.545455
0.00202
def admin_tools_render_dashboard_css( context, location='index', dashboard=None): """ Template tag that renders the dashboard css files, it takes two optional arguments: ``location`` The location of the dashboard, it can be 'index' (for the admin index dashboard) or 'app_index' ...
[ "def", "admin_tools_render_dashboard_css", "(", "context", ",", "location", "=", "'index'", ",", "dashboard", "=", "None", ")", ":", "if", "dashboard", "is", "None", ":", "dashboard", "=", "get_dashboard", "(", "context", ",", "location", ")", "context", ".", ...
34.375
0.001179
def cirq_to_tk(circuit: cirq.Circuit) -> Circuit: """Converts a Cirq :py:class:`Circuit` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` object. :param circuit: The input Cirq :py:class:`Circuit` :raises NotImplementedError: If the input contains a Cirq :py:class:`Circuit` operation whi...
[ "def", "cirq_to_tk", "(", "circuit", ":", "cirq", ".", "Circuit", ")", "->", "Circuit", ":", "qubit_list", "=", "_indexed_qubits_from_circuit", "(", "circuit", ")", "qid_to_num", "=", "{", "q", ":", "i", "for", "i", ",", "q", "in", "enumerate", "(", "qub...
42.820513
0.008782
def _init_sort(self): """ Prepare the data to be sorted. If not yet sorted, import all tracked objects from the tracked index. Extend the tracking information by implicit information to make sorting easier (DSU pattern). """ if not self.sorted: # Ident...
[ "def", "_init_sort", "(", "self", ")", ":", "if", "not", "self", ".", "sorted", ":", "# Identify the snapshot that tracked the largest amount of memory.", "tmax", "=", "None", "maxsize", "=", "0", "for", "snapshot", "in", "self", ".", "snapshots", ":", "if", "sn...
42.5
0.002301
def _info(self): """Returns an OrderedDict of information, for human display.""" d = OrderedDict() d['vid'] = self.vid d['sname'] = self.sname d['vname'] = self.vname return d
[ "def", "_info", "(", "self", ")", ":", "d", "=", "OrderedDict", "(", ")", "d", "[", "'vid'", "]", "=", "self", ".", "vid", "d", "[", "'sname'", "]", "=", "self", ".", "sname", "d", "[", "'vname'", "]", "=", "self", ".", "vname", "return", "d" ]
24.111111
0.008889
def aside_view_declaration(self, view_name): """ Find and return a function object if one is an aside_view for the given view_name Aside methods declare their view provision via @XBlockAside.aside_for(view_name) This function finds those declarations for a block. Arguments: ...
[ "def", "aside_view_declaration", "(", "self", ",", "view_name", ")", ":", "if", "view_name", "in", "self", ".", "_combined_asides", ":", "# pylint: disable=unsupported-membership-test", "return", "getattr", "(", "self", ",", "self", ".", "_combined_asides", "[", "vi...
39.705882
0.008683
async def list_state(self, request): """Fetches list of data entries, optionally filtered by address prefix. Request: query: - head: The id of the block to use as the head of the chain - address: Return entries whose addresses begin with this ...
[ "async", "def", "list_state", "(", "self", ",", "request", ")", ":", "paging_controls", "=", "self", ".", "_get_paging_controls", "(", "request", ")", "head", ",", "root", "=", "await", "self", ".", "_head_to_root", "(", "request", ".", "url", ".", "query"...
40.333333
0.001345
def get_doc_entries(target: typing.Callable) -> list: """ Gets the lines of documentation from the given target, which are formatted so that each line is a documentation entry. :param target: :return: A list of strings containing the documentation block entries """ raw = get_docstr...
[ "def", "get_doc_entries", "(", "target", ":", "typing", ".", "Callable", ")", "->", "list", ":", "raw", "=", "get_docstring", "(", "target", ")", "if", "not", "raw", ":", "return", "[", "]", "raw_lines", "=", "[", "line", ".", "strip", "(", ")", "for...
24.621622
0.001056
def getBucketValues(self): """ See the function description in base.py """ # Need to re-create? if self._bucketValues is None: scaledValues = self.encoder.getBucketValues() self._bucketValues = [] for scaledValue in scaledValues: value = math.pow(10, scaledValue) s...
[ "def", "getBucketValues", "(", "self", ")", ":", "# Need to re-create?", "if", "self", ".", "_bucketValues", "is", "None", ":", "scaledValues", "=", "self", ".", "encoder", ".", "getBucketValues", "(", ")", "self", ".", "_bucketValues", "=", "[", "]", "for",...
26.357143
0.010471
def main(): """Will be used to create the console script""" import optparse import sys import codecs import locale import six from .algorithm import get_display parser = optparse.OptionParser() parser.add_option('-e', '--encoding', dest='encoding', ...
[ "def", "main", "(", ")", ":", "import", "optparse", "import", "sys", "import", "codecs", "import", "locale", "import", "six", "from", ".", "algorithm", "import", "get_display", "parser", "=", "optparse", ".", "OptionParser", "(", ")", "parser", ".", "add_opt...
31.610169
0.00104
def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs): '''Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool Strict safety checking...
[ "def", "save", "(", "filename_audio", ",", "filename_jam", ",", "jam", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "y", "=", "jam", ".", "sandbox", ".", "muda", ".", "_audio", "[", "'y'", "]", "sr", "...
23.482759
0.00141
def columnSimilarities(self, threshold=0.0): """ Compute similarities between columns of this matrix. The threshold parameter is a trade-off knob between estimate quality and computational cost. The default threshold setting of 0 guarantees deterministically correct res...
[ "def", "columnSimilarities", "(", "self", ",", "threshold", "=", "0.0", ")", ":", "java_sims_mat", "=", "self", ".", "_java_matrix_wrapper", ".", "call", "(", "\"columnSimilarities\"", ",", "float", "(", "threshold", ")", ")", "return", "CoordinateMatrix", "(", ...
40.55
0.001204
def write_csv(graph, prefix): """ Write ``graph`` as tables of nodes (``prefix-nodes.csv``) and edges (``prefix-edges.csv``). Parameters ---------- graph : :ref:`networkx.Graph <networkx:graph>` prefix : str """ node_headers = list(set([a for n, attrs in graph.nodes(data=True) ...
[ "def", "write_csv", "(", "graph", ",", "prefix", ")", ":", "node_headers", "=", "list", "(", "set", "(", "[", "a", "for", "n", ",", "attrs", "in", "graph", ".", "nodes", "(", "data", "=", "True", ")", "for", "a", "in", "attrs", ".", "keys", "(", ...
41.896552
0.002414
def micro_indices(self): """Indices of micro elements represented in this coarse-graining.""" return tuple(sorted(idx for part in self.partition for idx in part))
[ "def", "micro_indices", "(", "self", ")", ":", "return", "tuple", "(", "sorted", "(", "idx", "for", "part", "in", "self", ".", "partition", "for", "idx", "in", "part", ")", ")" ]
58.666667
0.011236
def _idx_col_by_name(table): """ Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names. :param dict table: Metadata :return dict _table: Metadata """ _columns = OrderedDict() # Iter for each column in the list try: for _colum...
[ "def", "_idx_col_by_name", "(", "table", ")", ":", "_columns", "=", "OrderedDict", "(", ")", "# Iter for each column in the list", "try", ":", "for", "_column", "in", "table", "[", "\"columns\"", "]", ":", "try", ":", "_name", "=", "_column", "[", "\"variableN...
33.259259
0.002165
def sum(self, axis): """Sums all data along axis, returns d-1 dimensional histogram""" axis = self.get_axis_number(axis) if self.dimensions == 2: new_hist = Hist1d else: new_hist = Histdd return new_hist.from_histogram(np.sum(self.histogram, axis=axis), ...
[ "def", "sum", "(", "self", ",", "axis", ")", ":", "axis", "=", "self", ".", "get_axis_number", "(", "axis", ")", "if", "self", ".", "dimensions", "==", "2", ":", "new_hist", "=", "Hist1d", "else", ":", "new_hist", "=", "Histdd", "return", "new_hist", ...
49
0.008016
async def start_serving(self, address=None, sockets=None, **kw): """create the server endpoint. """ if self._server: raise RuntimeError('Already serving') server = DGServer(self._loop) loop = self._loop if sockets: for sock in sockets: ...
[ "async", "def", "start_serving", "(", "self", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "self", ".", "_server", ":", "raise", "RuntimeError", "(", "'Already serving'", ")", "server", "=", "DGServer", ...
41.578947
0.002475
def tickets_create_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets" api_path = "/api/v2/tickets/create_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "tickets_create_many", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/tickets/create_many.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",",...
63.75
0.011628
def interp(var, indexes_coords, method, **kwargs): """ Make an interpolation of Variable Parameters ---------- var: Variable index_coords: Mapping from dimension name to a pair of original and new coordinates. Original coordinates should be sorted in strictly ascending order. ...
[ "def", "interp", "(", "var", ",", "indexes_coords", ",", "method", ",", "*", "*", "kwargs", ")", ":", "if", "not", "indexes_coords", ":", "return", "var", ".", "copy", "(", ")", "# simple speed up for the local interpolation", "if", "method", "in", "[", "'li...
31.465517
0.000531
def format_BLB(): """Sets some formatting options in Matplotlib.""" rc("figure", facecolor="white") rc('font', family = 'serif', size=10) #, serif = 'cmr10') rc('xtick', labelsize=10) rc('ytick', labelsize=10) rc('axes', linewidth=1) rc('xtick.major', size=4, width=1) rc('xtick.m...
[ "def", "format_BLB", "(", ")", ":", "rc", "(", "\"figure\"", ",", "facecolor", "=", "\"white\"", ")", "rc", "(", "'font'", ",", "family", "=", "'serif'", ",", "size", "=", "10", ")", "#, serif = 'cmr10')\r", "rc", "(", "'xtick'", ",", "labelsize", "=", ...
37.545455
0.01182
def get_resource(self, uri, resource_type=None, response_format=None): ''' Retrieve resource: - Issues an initial GET request - If 200, continues, 404, returns False, otherwise raises Exception - Parse resource type - If custom resource type parser provided, this fires - Else, or if custom parser ...
[ "def", "get_resource", "(", "self", ",", "uri", ",", "resource_type", "=", "None", ",", "response_format", "=", "None", ")", ":", "# handle uri", "uri", "=", "self", ".", "parse_uri", "(", "uri", ")", "# remove fcr:metadata if included, as handled below", "if", ...
33.738462
0.026141
def blend(self, cycles=1): """ Explands the existing Palette by inserting the blending colour between all Colours already in the Palette. Changes the Palette in-place. args: cycles(int): number of *blend* cycles to apply. (Default is 1) Example usage: ...
[ "def", "blend", "(", "self", ",", "cycles", "=", "1", ")", ":", "for", "j", "in", "range", "(", "int", "(", "cycles", ")", ")", ":", "new_colours", "=", "[", "]", "for", "i", ",", "c", "in", "enumerate", "(", "self", ".", "_colours", ")", ":", ...
27.46
0.001406
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the boxscore string. """ # If both the runs scored and allowed are None, the game hasn't been # played yet, and the DataFrame should be Non...
[ "def", "dataframe", "(", "self", ")", ":", "# If both the runs scored and allowed are None, the game hasn't been", "# played yet, and the DataFrame should be None.", "if", "self", ".", "_runs_allowed", "is", "None", "and", "self", ".", "_runs_scored", "is", "None", ":", "re...
40.787879
0.001451
def have_graph(self, graph): """Return whether I have a graph by this name.""" graph = self.pack(graph) return bool(self.sql('graphs_named', graph).fetchone()[0])
[ "def", "have_graph", "(", "self", ",", "graph", ")", ":", "graph", "=", "self", ".", "pack", "(", "graph", ")", "return", "bool", "(", "self", ".", "sql", "(", "'graphs_named'", ",", "graph", ")", ".", "fetchone", "(", ")", "[", "0", "]", ")" ]
45.75
0.010753
def shippingaddress_update(self, tid, session, **kwargs): '''taobao.trade.shippingaddress.update 更改交易的收货地址''' request = TOPRequest('taobao.trade.shippingaddress.update') request['tid'] = tid for k, v in kwargs.iteritems(): if k not in ('receiver_name','receiver_phone','receiv...
[ "def", "shippingaddress_update", "(", "self", ",", "tid", ",", "session", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.trade.shippingaddress.update'", ")", "request", "[", "'tid'", "]", "=", "tid", "for", "k", ",", "v", "i...
59.888889
0.023766
def plot(self, timestep="AUTO", metric="AUTO", server=False, **kwargs): """ Plot training set (and validation set if available) scoring history for an H2OBinomialModel. The timestep and metric arguments are restricted to what is available in its scoring history. :param str timestep: A ...
[ "def", "plot", "(", "self", ",", "timestep", "=", "\"AUTO\"", ",", "metric", "=", "\"AUTO\"", ",", "server", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert_is_type", "(", "metric", ",", "\"AUTO\"", ",", "\"logloss\"", ",", "\"auc\"", ",", "\"...
56.066667
0.008187
def construct_FAO_ontology(): """ Construct FAO variable ontology for use with Eidos. """ df = pd.read_csv("south_sudan_data_fao.csv") gb = df.groupby("Element") d = [ { "events": [ { k: [ {e: [process_variable_name(k, e)]}...
[ "def", "construct_FAO_ontology", "(", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "\"south_sudan_data_fao.csv\"", ")", "gb", "=", "df", ".", "groupby", "(", "\"Element\"", ")", "d", "=", "[", "{", "\"events\"", ":", "[", "{", "k", ":", "[", "{", ...
25.833333
0.001555
def check_sparsity(x, fraction=0.6): ''' check_sparsity(x) yields either x or an array equivalent to x with a different sparsity based on a heuristic: if x is a sparse array with more than 60% of its elements specified, it is made dense; otherwise, it is left alone. The optional argument fracti...
[ "def", "check_sparsity", "(", "x", ",", "fraction", "=", "0.6", ")", ":", "if", "not", "sps", ".", "issparse", "(", "x", ")", ":", "return", "x", "n", "=", "numel", "(", "x", ")", "if", "n", "==", "0", ":", "return", "x", "if", "len", "(", "x...
41.928571
0.013333
def make_linkcode_resolve(package, url_fmt): """Returns a linkcode_resolve function for the given URL format revision is a git commit reference (hash or name) package is the name of the root module of the package url_fmt is along the lines of ('https://github.com/USER/PROJECT/' ...
[ "def", "make_linkcode_resolve", "(", "package", ",", "url_fmt", ")", ":", "revision", "=", "_get_git_revision", "(", ")", "return", "partial", "(", "_linkcode_resolve", ",", "revision", "=", "revision", ",", "package", "=", "package", ",", "url_fmt", "=", "url...
39.714286
0.001757
def push(stack, x, op_id): """Push a value onto the stack (i.e. record it on the tape). Args: stack: The stack object, which must support appending values. x: The value to append. If it is a mutable object like an array or list, it will be copied before being added onto the stack. op_id: A uniq...
[ "def", "push", "(", "stack", ",", "x", ",", "op_id", ")", ":", "if", "isinstance", "(", "x", ",", "numpy", ".", "ndarray", ")", ":", "x", "=", "x", ".", "copy", "(", ")", "elif", "isinstance", "(", "x", ",", "list", ")", ":", "x", "=", "x", ...
33.555556
0.009662
def _det_large_enough_mask(x, det_bounds): """Returns whether the input matches the given determinant limit. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. det_bounds: A floating-point `Tensor` that must broadcast to shape `[B1, ..., Bn]`, giving the desired lower bound on the ...
[ "def", "_det_large_enough_mask", "(", "x", ",", "det_bounds", ")", ":", "# For the curious: I wonder whether it is possible and desirable to", "# use a Cholesky decomposition-based algorithm for this, since the", "# only matrices whose determinant this code cares about will be PSD.", "# Didn't...
44.375
0.011029
def component(self, component, value=None): """ Set and/or get component value. :param component: component name to return :param value: if value is not None, this value will be set as a component value :return: str """ if isinstance(component, str) is True: component = WURI.Component(component) if va...
[ "def", "component", "(", "self", ",", "component", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "component", ",", "str", ")", "is", "True", ":", "component", "=", "WURI", ".", "Component", "(", "component", ")", "if", "value", "is", ...
32.153846
0.032558
def _validate_netconfig(self, conf): """ Validate network configuration Args: conf(dict): spec Returns: None Raises: :exc:`~lago.utils.LagoInitException`: If a VM has more than one management network configured, or a network whi...
[ "def", "_validate_netconfig", "(", "self", ",", "conf", ")", ":", "nets", "=", "conf", ".", "get", "(", "'nets'", ",", "{", "}", ")", "if", "len", "(", "nets", ")", "==", "0", ":", "# TO-DO: add default networking if no network is configured", "raise", "Lago...
34.885246
0.000914
def _create_blank_page(self): """Create html page to show while the kernel is starting""" loading_template = Template(BLANK) page = loading_template.substitute(css_path=self.css_path) return page
[ "def", "_create_blank_page", "(", "self", ")", ":", "loading_template", "=", "Template", "(", "BLANK", ")", "page", "=", "loading_template", ".", "substitute", "(", "css_path", "=", "self", ".", "css_path", ")", "return", "page" ]
45.4
0.008658
def AcceptableMimeType(accept_patterns, mime_type): """Return True iff mime_type is acceptable for one of accept_patterns. Note that this function assumes that all patterns in accept_patterns will be simple types of the form "type/subtype", where one or both of these can be "*". We do not support param...
[ "def", "AcceptableMimeType", "(", "accept_patterns", ",", "mime_type", ")", ":", "if", "'/'", "not", "in", "mime_type", ":", "raise", "exceptions", ".", "InvalidUserInputError", "(", "'Invalid MIME type: \"%s\"'", "%", "mime_type", ")", "unsupported_patterns", "=", ...
40.676471
0.000706
def stop(self): """Stop the name server. """ self.listener.setsockopt(LINGER, 1) self.loop = False with nslock: self.listener.close()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "listener", ".", "setsockopt", "(", "LINGER", ",", "1", ")", "self", ".", "loop", "=", "False", "with", "nslock", ":", "self", ".", "listener", ".", "close", "(", ")" ]
25.571429
0.010811
def _update_indicator(self,K,L): """ update the indicator """ _update = {'term': self.n_terms*np.ones((K,L)).T.ravel(), 'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(), 'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()} ...
[ "def", "_update_indicator", "(", "self", ",", "K", ",", "L", ")", ":", "_update", "=", "{", "'term'", ":", "self", ".", "n_terms", "*", "np", ".", "ones", "(", "(", "K", ",", "L", ")", ")", ".", "T", ".", "ravel", "(", ")", ",", "'row'", ":",...
61.857143
0.036446