text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def make_fortran_patterns(): "Strongly inspired from idlelib.ColorDelegator.make_pat" kwstr = 'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate de...
[ "def", "make_fortran_patterns", "(", ")", ":", "kwstr", "=", "'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate decimal delim default dime...
269
0.000872
def passed(self): ''' Set the report status to PASSED ''' self.set_status(Report.PASSED) if 'reason' in self._data_fields: del self._data_fields['reason']
[ "def", "passed", "(", "self", ")", ":", "self", ".", "set_status", "(", "Report", ".", "PASSED", ")", "if", "'reason'", "in", "self", ".", "_data_fields", ":", "del", "self", ".", "_data_fields", "[", "'reason'", "]" ]
28.571429
0.009709
def num_buttons(self): """The number of buttons on a device with the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability. Buttons on a pad device are numbered sequentially, see `Tablet pad button numbers`_ for details. Returns: int: The number of buttons supported by the device. Raises: ...
[ "def", "num_buttons", "(", "self", ")", ":", "num", "=", "self", ".", "_libinput", ".", "libinput_device_tablet_pad_get_num_buttons", "(", "self", ".", "_handle", ")", "if", "num", "<", "0", ":", "raise", "AttributeError", "(", "'This device is not a tablet pad de...
27.944444
0.030769
def handleServerEvents(self, msg): """ dispatch msg to the right handler """ self.log.debug('MSG %s', msg) self.handleConnectionState(msg) if msg.typeName == "error": self.handleErrorEvents(msg) elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]: if sel...
[ "def", "handleServerEvents", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "'MSG %s'", ",", "msg", ")", "self", ".", "handleConnectionState", "(", "msg", ")", "if", "msg", ".", "typeName", "==", "\"error\"", ":", "self", "."...
35.808219
0.000745
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = None allowed_names = [] eof = F...
[ "def", "text_fd_to_metric_families", "(", "fd", ")", ":", "name", "=", "None", "allowed_names", "=", "[", "]", "eof", "=", "False", "seen_metrics", "=", "set", "(", ")", "def", "build_metric", "(", "name", ",", "documentation", ",", "typ", ",", "unit", "...
44.45122
0.002013
def report_up(self, service, port): """ Report the given service's present node as up by creating/updating its respective znode in Zookeeper and setting the znode's data to the serialized representation of the node. Waits for zookeeper to be connected before taking any action. ...
[ "def", "report_up", "(", "self", ",", "service", ",", "port", ")", ":", "wait_on_any", "(", "self", ".", "connected", ",", "self", ".", "shutdown", ")", "node", "=", "Node", ".", "current", "(", "service", ",", "port", ")", "path", "=", "self", ".", ...
38.448276
0.00175
async def insert(self, **kwargs): """ Accepts request object, retrieves data from the one`s body and creates new account. """ if kwargs: # Create autoincrement for account pk = await self.autoincrement() kwargs.update({"id": pk}) # Create account with received data and autoincrement await ...
[ "async", "def", "insert", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "# Create autoincrement for account", "pk", "=", "await", "self", ".", "autoincrement", "(", ")", "kwargs", ".", "update", "(", "{", "\"id\"", ":", "pk", "}", ...
22
0.050817
def filter_nonspellcheckable_tokens(line, block_out_regexes=None): """Return line with paths, urls and emails filtered out. Block out other strings of text matching :block_out_regexes: if passed in. """ all_block_out_regexes = [ r"[^\s]*:[^\s]*[/\\][^\s]*", r"[^\s]*[/\\][^\s]*", ...
[ "def", "filter_nonspellcheckable_tokens", "(", "line", ",", "block_out_regexes", "=", "None", ")", ":", "all_block_out_regexes", "=", "[", "r\"[^\\s]*:[^\\s]*[/\\\\][^\\s]*\"", ",", "r\"[^\\s]*[/\\\\][^\\s]*\"", ",", "r\"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+\\b\"", "]",...
37.764706
0.00152
def init_logging(to_file=False, logfile=None, default_logfile='/tmp/resync.log', human=True, verbose=False, eval_mode=False, default_logger='client', extra_loggers=None): """Initialize logging. Use of log levels: DEBUG - very verbose, for evaluation of output (-e) INFO...
[ "def", "init_logging", "(", "to_file", "=", "False", ",", "logfile", "=", "None", ",", "default_logfile", "=", "'/tmp/resync.log'", ",", "human", "=", "True", ",", "verbose", "=", "False", ",", "eval_mode", "=", "False", ",", "default_logger", "=", "'client'...
37.954545
0.001168
def write(self, fptr): """Write a fragment table box to file. """ self._validate(writing=True) self._write_superbox(fptr, b'ftbl')
[ "def", "write", "(", "self", ",", "fptr", ")", ":", "self", ".", "_validate", "(", "writing", "=", "True", ")", "self", ".", "_write_superbox", "(", "fptr", ",", "b'ftbl'", ")" ]
31.6
0.012346
def build_extraction_dataset(folder, dataset_filename, sender_known=True): """Builds signature extraction dataset using emails in the `folder`. The emails in the `folder` should be annotated i.e. signature lines should be marked with `#sig#`. """ if os.path.exists(datas...
[ "def", "build_extraction_dataset", "(", "folder", ",", "dataset_filename", ",", "sender_known", "=", "True", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "dataset_filename", ")", ":", "os", ".", "remove", "(", "dataset_filename", ")", "with", "open...
43.516129
0.000725
def reconfigure(name, cpu=None, cpuset=None, cpushare=None, memory=None, profile=None, network_profile=None, nic_opts=None, bridge=None, gateway=None, autostart...
[ "def", "reconfigure", "(", "name", ",", "cpu", "=", "None", ",", "cpuset", "=", "None", ",", "cpushare", "=", "None", ",", "memory", "=", "None", ",", "profile", "=", "None", ",", "network_profile", "=", "None", ",", "nic_opts", "=", "None", ",", "br...
30.792308
0.000968
def variables(self): '''return a list of available variables''' return sorted(list(self.mapping.vars.keys()), key = lambda v : self.mapping.vars[v].index)
[ "def", "variables", "(", "self", ")", ":", "return", "sorted", "(", "list", "(", "self", ".", "mapping", ".", "vars", ".", "keys", "(", ")", ")", ",", "key", "=", "lambda", "v", ":", "self", ".", "mapping", ".", "vars", "[", "v", "]", ".", "ind...
47.25
0.026042
def verify_key(self, url): """For verifying your API key. Provide the URL of your site or blog you will be checking spam from. """ response = self._request('verify-key', { 'blog': url, 'key': self._key }) if response.stat...
[ "def", "verify_key", "(", "self", ",", "url", ")", ":", "response", "=", "self", ".", "_request", "(", "'verify-key'", ",", "{", "'blog'", ":", "url", ",", "'key'", ":", "self", ".", "_key", "}", ")", "if", "response", ".", "status", "is", "200", "...
28.4375
0.012766
def add_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Adds a role for a user on a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: manager.add_user_role(user, role, project) else: ...
[ "def", "add_tenant_user_role", "(", "request", ",", "project", "=", "None", ",", "user", "=", "None", ",", "role", "=", "None", ",", "group", "=", "None", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "adm...
45.444444
0.002398
def fast_hamiltonian_terms(Ep, epsilonp, detuning_knob, omega_level, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Hamiltonian terms. We test a basic t...
[ "def", "fast_hamiltonian_terms", "(", "Ep", ",", "epsilonp", ",", "detuning_knob", ",", "omega_level", ",", "rm", ",", "xi", ",", "theta", ",", "unfolding", ",", "matrix_form", "=", "False", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ...
37.632353
0.002284
def run(self): # No "_" in the name, but nevertheless, running in the backed """After the fork. Now the process starts running """ self.preRun_() self.running=True while(self.running): if (self.active): # activated: shared mem client has been reserved ...
[ "def", "run", "(", "self", ")", ":", "# No \"_\" in the name, but nevertheless, running in the backed", "self", ".", "preRun_", "(", ")", "self", ".", "running", "=", "True", "while", "(", "self", ".", "running", ")", ":", "if", "(", "self", ".", "active", "...
33.866667
0.015326
def update_managed_repos(force=False): """For any active, managed repos, update the Dusty-managed copy to bring it up to date with the latest master.""" log_to_client('Pulling latest updates for all active managed repos:') update_specs_repo_and_known_hosts() repos_to_update = get_all_repos(active_on...
[ "def", "update_managed_repos", "(", "force", "=", "False", ")", ":", "log_to_client", "(", "'Pulling latest updates for all active managed repos:'", ")", "update_specs_repo_and_known_hosts", "(", ")", "repos_to_update", "=", "get_all_repos", "(", "active_only", "=", "True",...
52.181818
0.001712
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): """Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param b...
[ "def", "declare", "(", "self", ",", "exchange", "=", "''", ",", "exchange_type", "=", "'direct'", ",", "passive", "=", "False", ",", "durable", "=", "False", ",", "auto_delete", "=", "False", ",", "arguments", "=", "None", ")", ":", "if", "not", "compa...
51.157895
0.001514
def save_datasets(self, datasets, compute=True, **kwargs): """Save all datasets to one or more files. Subclasses can use this method to save all datasets to one single file or optimize the writing of individual datasets. By default this simply calls `save_dataset` for each dataset provi...
[ "def", "save_datasets", "(", "self", ",", "datasets", ",", "compute", "=", "True", ",", "*", "*", "kwargs", ")", ":", "results", "=", "[", "]", "for", "ds", "in", "datasets", ":", "results", ".", "append", "(", "self", ".", "save_dataset", "(", "ds",...
46.863636
0.00095
def get_url(self, link): """ URL of service """ view_name = SupportedServices.get_detail_view_for_model(link.service) return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])
[ "def", "get_url", "(", "self", ",", "link", ")", ":", "view_name", "=", "SupportedServices", ".", "get_detail_view_for_model", "(", "link", ".", "service", ")", "return", "reverse", "(", "view_name", ",", "kwargs", "=", "{", "'uuid'", ":", "link", ".", "se...
41.833333
0.011719
def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>": isList=True else: isList=False data=[] if fname==None: fname=self.files ...
[ "def", "_getattr", "(", "self", ",", "attri", ",", "fname", "=", "None", ",", "numtype", "=", "'cycNum'", ")", ":", "if", "str", "(", "fname", ".", "__class__", ")", "==", "\"<type 'list'>\"", ":", "isList", "=", "True", "else", ":", "isList", "=", "...
37.210526
0.019986
def getFormattedHTML(self, indent=' '): ''' getFormattedHTML - Get formatted and xhtml of this document, replacing the original whitespace with a pretty-printed version @param indent - space/tab/newline of each level of indent, or integer for how many spaces per level ...
[ "def", "getFormattedHTML", "(", "self", ",", "indent", "=", "' '", ")", ":", "from", ".", "Formatter", "import", "AdvancedHTMLFormatter", "html", "=", "self", ".", "getHTML", "(", ")", "formatter", "=", "AdvancedHTMLFormatter", "(", "indent", ",", "None", "...
40.888889
0.009296
def issues_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Use: :issue|bug|feature|support:`ticket_number` When invoked as :issue:, turns into just a "#NN" hyperlink to `releases_issue_uri`. When invoked otherwise, turns into "[Type] <#NN hyperlink>: ". Spaces present ...
[ "def", "issues_role", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "parts", "=", "utils", ".", "unescape", "(", "text", ")", ".", "split", "(", ")...
37.084507
0.00074
def list(self, **params): """ Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "lead_sources", "=", "self", ".", "http_client", ".", "get", "(", "\"/lead_sources\"", ",", "params", "=", "params", ")", "return", "lead_sources" ]
35.857143
0.009709
def register_updates(self, callback): """Register a callback to notify a listener of state changes.""" _LOGGER.debug("Registered callback for state: %s", self._stateName) self._observer_callbacks.append(callback)
[ "def", "register_updates", "(", "self", ",", "callback", ")", ":", "_LOGGER", ".", "debug", "(", "\"Registered callback for state: %s\"", ",", "self", ".", "_stateName", ")", "self", ".", "_observer_callbacks", ".", "append", "(", "callback", ")" ]
58.25
0.008475
def kms_encrypt(value, key, aws_config=None): """Encrypt and value with KMS key. Args: value (str): value to encrypt key (str): key id or alias aws_config (optional[dict]): aws credentials dict of arguments passed into boto3 session example: aws_c...
[ "def", "kms_encrypt", "(", "value", ",", "key", ",", "aws_config", "=", "None", ")", ":", "aws_config", "=", "aws_config", "or", "{", "}", "aws", "=", "boto3", ".", "session", ".", "Session", "(", "*", "*", "aws_config", ")", "client", "=", "aws", "....
35.681818
0.001241
def rand_rotate(anglerange, *imagez): """ :param anglerange: :param imagez: :return: """ r = float(anglerange[1] - anglerange[0]) s = anglerange[0] def _rand_rotate(*imgz): angle = np.random.random(1)[0] * r + s out = tuple(rotate(img, angle) for img in imgz) ret...
[ "def", "rand_rotate", "(", "anglerange", ",", "*", "imagez", ")", ":", "r", "=", "float", "(", "anglerange", "[", "1", "]", "-", "anglerange", "[", "0", "]", ")", "s", "=", "anglerange", "[", "0", "]", "def", "_rand_rotate", "(", "*", "imgz", ")", ...
25.933333
0.002481
def disable_backup(self): """ Disables dumper backup. """ for dumper in list(self.dumpers.values()): dumper.set_backup(False)
[ "def", "disable_backup", "(", "self", ")", ":", "for", "dumper", "in", "list", "(", "self", ".", "dumpers", ".", "values", "(", ")", ")", ":", "dumper", ".", "set_backup", "(", "False", ")" ]
27.333333
0.011834
def compute_gt_results(est_file, ref_file, boundaries_id, labels_id, config, bins=251, annotator_id=0): """Computes the results by using the ground truth dataset identified by the annotator parameter. Return ------ results : dict Dictionary of the results (see functio...
[ "def", "compute_gt_results", "(", "est_file", ",", "ref_file", ",", "boundaries_id", ",", "labels_id", ",", "config", ",", "bins", "=", "251", ",", "annotator_id", "=", "0", ")", ":", "if", "config", "[", "\"hier\"", "]", ":", "ref_times", ",", "ref_labels...
39.66129
0.000397
def get_file(path, dest, saltenv='base', makedirs=False, template=None, gzip=None, **kwargs): ''' .. versionchanged:: 2018.3.0 ``dest`` can now be a directory Used to get a single file from the salt master CLI Exampl...
[ "def", "get_file", "(", "path", ",", "dest", ",", "saltenv", "=", "'base'", ",", "makedirs", "=", "False", ",", "template", "=", "None", ",", "gzip", "=", "None", ",", "*", "*", "kwargs", ")", ":", "(", "path", ",", "dest", ")", "=", "_render_filen...
32.402985
0.001788
def _connectToFlickr(self): """Establish the actual TCP connection to Flickr""" if self.connected_to_flickr: logger.debug("Already connected to flickr") return True logger.debug("Connecting to flickr") # Do flickr authentication _flickr = flickrapi.Flick...
[ "def", "_connectToFlickr", "(", "self", ")", ":", "if", "self", ".", "connected_to_flickr", ":", "logger", ".", "debug", "(", "\"Already connected to flickr\"", ")", "return", "True", "logger", ".", "debug", "(", "\"Connecting to flickr\"", ")", "# Do flickr authent...
30.833333
0.013106
def server_handler(args): """server_handler.""" if not db.setup(url=args.db, echo=args.db_echo): return if not _check_db_revision(): return app = create_app() listener = '{:s}:{:d}'.format(args.host, args.port) if args.debug: logging.getLogger('werkzeug').disabled = True...
[ "def", "server_handler", "(", "args", ")", ":", "if", "not", "db", ".", "setup", "(", "url", "=", "args", ".", "db", ",", "echo", "=", "args", ".", "db_echo", ")", ":", "return", "if", "not", "_check_db_revision", "(", ")", ":", "return", "app", "=...
32.125
0.000755
def p_valueofSimpleSyntax(self, p): """valueofSimpleSyntax : NUMBER | NEGATIVENUMBER | NUMBER64 | NEGATIVENUMBER64 | HEX_STRING | BIN_STRING ...
[ "def", "p_valueofSimpleSyntax", "(", "self", ",", "p", ")", ":", "# libsmi for objectIdentifier_defval:", "# This is only for some MIBs with invalid numerical", "# OID notation for DEFVALs. We DO NOT parse them", "# correctly. We just don't want to produce a", "# parser error.", "n", "="...
40
0.002442
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT """Take the absolute derivate of an image in memory.""" #Create 2 empty arrays in memory of the same dimensions as 'array' tmpArray = np.zeros(array.shape,dtype=np.float64) outArray = np.zeros(array.shape, dtype=np.float64) # Ge...
[ "def", "qderiv", "(", "array", ")", ":", "# TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT", "#Create 2 empty arrays in memory of the same dimensions as 'array'", "tmpArray", "=", "np", ".", "zeros", "(", "array", ".", "shape", ",", "dtype", "=", "np", ".", "float64", ...
37.268293
0.026786
def _selectedBlocks(self): """Return selected blocks and tuple (startBlock, endBlock) """ cursor = self.textCursor() return self.document().findBlock(cursor.selectionStart()), \ self.document().findBlock(cursor.selectionEnd())
[ "def", "_selectedBlocks", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "return", "self", ".", "document", "(", ")", ".", "findBlock", "(", "cursor", ".", "selectionStart", "(", ")", ")", ",", "self", ".", "document", "(", ...
44.666667
0.010989
def _svcomp_score(category, result): """ Return the achieved score of a task according to the SV-COMP scoring scheme. @param category: result category as determined by get_result_category @param result: the result given by the tool """ assert result is not None result_class = get_result_clas...
[ "def", "_svcomp_score", "(", "category", ",", "result", ")", ":", "assert", "result", "is", "not", "None", "result_class", "=", "get_result_classification", "(", "result", ")", "if", "category", "==", "CATEGORY_CORRECT_UNCONFIRMED", ":", "if", "result_class", "=="...
32.571429
0.001704
def clean_notify(self): """ Clean the notify_on_enrollment field. """ return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
[ "def", "clean_notify", "(", "self", ")", ":", "return", "self", ".", "cleaned_data", ".", "get", "(", "self", ".", "Fields", ".", "NOTIFY", ",", "self", ".", "NotificationTypes", ".", "DEFAULT", ")" ]
35.6
0.016484
def _purge_expired(self): """ Remove all expired entries from the cache that do not have a reference count. """ time_horizon = time.time() - self._keep_time new_cache = {} dec_count_for = [] for (k, v) in self._cache.items(): if v.count > 0: ...
[ "def", "_purge_expired", "(", "self", ")", ":", "time_horizon", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_keep_time", "new_cache", "=", "{", "}", "dec_count_for", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "self", ".", "_cac...
33.69697
0.001748
def create_sum(self, bound=1): """ Create a totalizer object encoding a cardinality constraint on the new list of relaxation literals obtained in :func:`process_sels` and :func:`process_sums`. The clauses encoding the sum of the relaxation literals are ...
[ "def", "create_sum", "(", "self", ",", "bound", "=", "1", ")", ":", "if", "self", ".", "solver", "!=", "'mc'", ":", "# standard totalizer-based encoding", "# new totalizer sum", "t", "=", "ITotalizer", "(", "lits", "=", "self", ".", "rels", ",", "ubound", ...
36.903846
0.001015
def refkeys(self,fields): "returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet." # todo doc: better explanation of what refkeys are and how fields plays in dd=collections.defaultdict(list) if any(f not in self.REFKEYS for f in fields): raise ValueError(fields,'not all...
[ "def", "refkeys", "(", "self", ",", "fields", ")", ":", "# todo doc: better explanation of what refkeys are and how fields plays in\r", "dd", "=", "collections", ".", "defaultdict", "(", "list", ")", "if", "any", "(", "f", "not", "in", "self", ".", "REFKEYS", "for...
52.111111
0.027254
def accept_project_bid(session, bid_id): """ Accept a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'accept' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bid_id) ...
[ "def", "accept_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'accept'", "}", "# POST /api/projects/0.1/bids/{bid_id}/?action=revoke", ...
35.545455
0.001245
def loadInstance(self): """ Loads the plugin from the proxy information that was created from the registry file. """ if self._loaded: return self._loaded = True module_path = self.modulePath() package = projex.packageFromPath(module_path) ...
[ "def", "loadInstance", "(", "self", ")", ":", "if", "self", ".", "_loaded", ":", "return", "self", ".", "_loaded", "=", "True", "module_path", "=", "self", ".", "modulePath", "(", ")", "package", "=", "projex", ".", "packageFromPath", "(", "module_path", ...
26.371429
0.00209
def get_reply(session, url, post=False, data=None, headers=None, quiet=False): """ Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with...
[ "def", "get_reply", "(", "session", ",", "url", ",", "post", "=", "False", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "quiet", "=", "False", ")", ":", "request_headers", "=", "{", "}", "if", "headers", "is", "None", "else", "headers"...
30.12766
0.000684
def model_set(method_name): """ Creates a setter that will call the model method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the model. @type method_name: str """ def model_set(value, context, **_params):...
[ "def", "model_set", "(", "method_name", ")", ":", "def", "model_set", "(", "value", ",", "context", ",", "*", "*", "_params", ")", ":", "method", "=", "getattr", "(", "context", "[", "\"model\"", "]", ",", "method_name", ")", "return", "_set", "(", "me...
34.230769
0.002188
def breakpoint(args): """ %prog breakpoint mstmap.input > breakpoints.bed Find scaffold breakpoints using genetic map. Use variation.vcf.mstmap() to generate the input for this routine. """ from jcvi.utils.iter import pairwise p = OptionParser(breakpoint.__doc__) p.add_option("--diff",...
[ "def", "breakpoint", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "iter", "import", "pairwise", "p", "=", "OptionParser", "(", "breakpoint", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--diff\"", ",", "default", "=", ".1", ",", "t...
29.463415
0.002404
def lambda_not_found_response(*args): """ Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask Response """ response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION) return make_response(response_data, ServiceEr...
[ "def", "lambda_not_found_response", "(", "*", "args", ")", ":", "response_data", "=", "jsonify", "(", "ServiceErrorResponses", ".", "_NO_LAMBDA_INTEGRATION", ")", "return", "make_response", "(", "response_data", ",", "ServiceErrorResponses", ".", "HTTP_STATUS_CODE_502", ...
43.375
0.011299
def merge(cwd, rev=None, opts='', git_opts='', user=None, password=None, identity=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Interface to `git-merge(1)`_ cwd The path to the git checkout ...
[ "def", "merge", "(", "cwd", ",", "rev", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding"...
32.06087
0.000526
def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception:...
[ "def", "Commit", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "lock...
17.590909
0.058824
def connect(self, uri, link_quality_callback, link_error_callback): """ Connect the link driver to a specified URI of the format: radio://<dongle nbr>/<radio channel>/[250K,1M,2M] The callback for linkQuality can be called at any moment from the driver to report back the link qu...
[ "def", "connect", "(", "self", ",", "uri", ",", "link_quality_callback", ",", "link_error_callback", ")", ":", "# check if the URI is a radio URI", "if", "not", "re", ".", "search", "(", "'^radio://'", ",", "uri", ")", ":", "raise", "WrongUriType", "(", "'Not a ...
37.97561
0.000626
def KL_divergence(P,Q): ''' Compute the KL divergence between distributions P and Q P and Q should be dictionaries linking symbols to probabilities. the keys to P and Q should be the same. ''' assert(P.keys()==Q.keys()) distance = 0 for k in P.keys(): distance += P[k] *...
[ "def", "KL_divergence", "(", "P", ",", "Q", ")", ":", "assert", "(", "P", ".", "keys", "(", ")", "==", "Q", ".", "keys", "(", ")", ")", "distance", "=", "0", "for", "k", "in", "P", ".", "keys", "(", ")", ":", "distance", "+=", "P", "[", "k"...
24.5
0.014045
def _merge_bee(self, bee): '''Shifts a random value for a supplied bee with in accordance with another random bee's value Args: bee (EmployerBee): supplied bee to merge Returns: tuple: (score of new position, values of new position, fitness funct...
[ "def", "_merge_bee", "(", "self", ",", "bee", ")", ":", "random_dimension", "=", "randint", "(", "0", ",", "len", "(", "self", ".", "_value_ranges", ")", "-", "1", ")", "second_bee", "=", "randint", "(", "0", ",", "self", ".", "_num_employers", "-", ...
39
0.001854
def remove_redistribution(self, protocol): """Removes a protocol redistribution to OSPF Args: protocol (str): protocol to redistribute route_map_name (str): route-map to be used to filter the protocols Returns: ...
[ "def", "remove_redistribution", "(", "self", ",", "protocol", ")", ":", "protocols", "=", "[", "'bgp'", ",", "'rip'", ",", "'static'", ",", "'connected'", "]", "if", "protocol", "not", "in", "protocols", ":", "raise", "ValueError", "(", "'redistributed protoco...
42.85
0.002283
def weather_history_at_id(self, id, start=None, end=None): """ Queries the OWM Weather API for weather history for the specified city ID. A list of *Weather* objects is returned. It is possible to query for weather history in a closed time period, whose boundaries can be passed a...
[ "def", "weather_history_at_id", "(", "self", ",", "id", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "assert", "type", "(", "id", ")", "is", "int", ",", "\"'id' must be an int\"", "if", "id", "<", "0", ":", "raise", "ValueError", "(", ...
51.981132
0.002494
def int_to_roman(num): """ https://stackoverflow.com/questions/42875103/integer-to-roman-number https://stackoverflow.com/questions/33486183/convert-from-numbers-to-roman-notation """ conv = ( ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ...
[ "def", "int_to_roman", "(", "num", ")", ":", "conv", "=", "(", "(", "\"M\"", ",", "1000", ")", ",", "(", "\"CM\"", ",", "900", ")", ",", "(", "\"D\"", ",", "500", ")", ",", "(", "\"CD\"", ",", "400", ")", ",", "(", "\"C\"", ",", "100", ")", ...
21.821429
0.001567
def result(self) -> workflow.IntervalGeneratorType: """ Generate intervals indicating the valid sentences. """ config = cast(SentenceSegementationConfig, self.config) index = -1 labels = None while True: # 1. Find the start of the sentence. ...
[ "def", "result", "(", "self", ")", "->", "workflow", ".", "IntervalGeneratorType", ":", "config", "=", "cast", "(", "SentenceSegementationConfig", ",", "self", ".", "config", ")", "index", "=", "-", "1", "labels", "=", "None", "while", "True", ":", "# 1. F...
37.206349
0.001663
def _exists(self, path): '''IMPORTANT: expects `path` to already be deref()'erenced.''' try: return bool(self._stat(path)) except os.error: return False
[ "def", "_exists", "(", "self", ",", "path", ")", ":", "try", ":", "return", "bool", "(", "self", ".", "_stat", "(", "path", ")", ")", "except", "os", ".", "error", ":", "return", "False" ]
28.5
0.017045
def on(self, evt, func): '''Set a callback handler for a pubsub event''' if evt not in self._callbacks: raise NotImplementedError('callback "%s"' % evt) else: self._callbacks[evt] = func
[ "def", "on", "(", "self", ",", "evt", ",", "func", ")", ":", "if", "evt", "not", "in", "self", ".", "_callbacks", ":", "raise", "NotImplementedError", "(", "'callback \"%s\"'", "%", "evt", ")", "else", ":", "self", ".", "_callbacks", "[", "evt", "]", ...
38.166667
0.008547
def find(self, *args, **kwargs): """Same as :meth:`pymongo.collection.Collection.find`, except it returns the right document class. """ return Cursor(self, *args, wrap=self.document_class, **kwargs)
[ "def", "find", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Cursor", "(", "self", ",", "*", "args", ",", "wrap", "=", "self", ".", "document_class", ",", "*", "*", "kwargs", ")" ]
45.2
0.008696
def save_four_ds9(rectwv_coeff, debugplot=0): """Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level ...
[ "def", "save_four_ds9", "(", "rectwv_coeff", ",", "debugplot", "=", "0", ")", ":", "for", "limits", ",", "rectified", ",", "suffix", "in", "zip", "(", "[", "'frontiers'", ",", "'frontiers'", ",", "'boundaries'", ",", "'boundaries'", "]", ",", "[", "False",...
36.615385
0.001024
def apply(self, localArray): """ Apply stencil to data @param localArray local array @return new array on local proc """ # input dist array inp = daZeros(localArray.shape, localArray.dtype) inp[...] = localArray inp.setComm(self.comm) # o...
[ "def", "apply", "(", "self", ",", "localArray", ")", ":", "# input dist array", "inp", "=", "daZeros", "(", "localArray", ".", "shape", ",", "localArray", ".", "dtype", ")", "inp", "[", "...", "]", "=", "localArray", "inp", ".", "setComm", "(", "self", ...
29.018519
0.001235
def buy(ctx, buy_amount, buy_asset, price, sell_asset, order_expiration, account): """ Buy a specific asset at a certain rate against a base asset """ amount = Amount(buy_amount, buy_asset) price = Price( price, base=sell_asset, quote=buy_asset, bitshares_instance=ctx.bitshares ) print_t...
[ "def", "buy", "(", "ctx", ",", "buy_amount", ",", "buy_asset", ",", "price", ",", "sell_asset", ",", "order_expiration", ",", "account", ")", ":", "amount", "=", "Amount", "(", "buy_amount", ",", "buy_asset", ")", "price", "=", "Price", "(", "price", ","...
40.5
0.009662
def session(context, data): """Set some HTTP parameters for all subsequent requests. This includes ``user`` and ``password`` for HTTP basic authentication, and ``user_agent`` as a header. """ context.http.reset() user = context.get('user') password = context.get('password') if user is...
[ "def", "session", "(", "context", ",", "data", ")", ":", "context", ".", "http", ".", "reset", "(", ")", "user", "=", "context", ".", "get", "(", "'user'", ")", "password", "=", "context", ".", "get", "(", "'password'", ")", "if", "user", "is", "no...
30.8
0.001049
def create_pipeline_box(self, pipeline_key, name, **kwargs): '''Creates a box int the pipeline specified with the provided attributes. Args: name required name string kwargs {...} see StreakBox object for details return (status code, box dict) ''' #req sanity check if not (pipeline_key and name): ...
[ "def", "create_pipeline_box", "(", "self", ",", "pipeline_key", ",", "name", ",", "*", "*", "kwargs", ")", ":", "#req sanity check", "if", "not", "(", "pipeline_key", "and", "name", ")", ":", "return", "requests", ".", "codes", ".", "bad_request", ",", "No...
24.56
0.047022
def all_leaves(self, graph=None): """ Return a list of all leaves (nodes with no downstreams) """ if graph is None: graph = self.graph return [key for key in graph if not graph[key]]
[ "def", "all_leaves", "(", "self", ",", "graph", "=", "None", ")", ":", "if", "graph", "is", "None", ":", "graph", "=", "self", ".", "graph", "return", "[", "key", "for", "key", "in", "graph", "if", "not", "graph", "[", "key", "]", "]" ]
42.8
0.009174
def web_task(f): """ Checks if the task is called through the web interface. Task return value should be in format {'data': ...}. """ @wraps(f) def web_task_decorator(*args, **kwargs): jc = JobContext.get_current_context() if not isinstance(jc, WebJobContext): raise ...
[ "def", "web_task", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "web_task_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "jc", "=", "JobContext", ".", "get_current_context", "(", ")", "if", "not", "isinstance", "(", "jc",...
32.588235
0.001754
def set_foreground(self, fg, isRGBA=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate c...
[ "def", "set_foreground", "(", "self", ",", "fg", ",", "isRGBA", "=", "None", ")", ":", "# Implementation note: wxPython has a separate concept of pen and", "# brush - the brush fills any outline trace left by the pen.", "# Here we set both to the same colour - if a figure is not to be", ...
46.111111
0.002361
def unsubscribe(id_or_symbols): """ 取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ current_universe = Environment.get_instance().get_universe() if isinstance(...
[ "def", "unsubscribe", "(", "id_or_symbols", ")", ":", "current_universe", "=", "Environment", ".", "get_instance", "(", ")", ".", "get_universe", "(", ")", "if", "isinstance", "(", "id_or_symbols", ",", "six", ".", "string_types", ")", ":", "order_book_id", "=...
41.238095
0.002257
def zoom_level_from_geometry(geometry, splits=4): """Generate optimum zoom level for geometry. Notes ----- The obvious solution would be >>> mercantile.bounding_tile(*geometry.get_shape(WGS84_CRS).bounds).z However, if the geometry is split between two or four tiles, the resulting zoom le...
[ "def", "zoom_level_from_geometry", "(", "geometry", ",", "splits", "=", "4", ")", ":", "# This import is here to avoid cyclic references", "from", "telluric", ".", "vectors", "import", "generate_tile_coordinates", "# We split the geometry and compute the zoom level for each chunk",...
34.708333
0.002336
def _cutoff(table, frequency_cutoff): '''Generate new codon frequency table given a mean cutoff. :param table: codon frequency table of form {amino acid: codon: frequency} :type table: dict :param frequency_cutoff: value between 0 and 1.0 for mean frequency cutoff :type frequency_cutoff: float ...
[ "def", "_cutoff", "(", "table", ",", "frequency_cutoff", ")", ":", "new_table", "=", "{", "}", "# IDEA: cutoff should be relative to most-frequent codon, not average?", "for", "amino_acid", ",", "codons", "in", "table", ".", "iteritems", "(", ")", ":", "average_cutoff...
40.8
0.001198
def check_network_role(self, public_key): """ Check the public key of a node on the network to see if they are permitted to participate. The roles being checked are the following, from first to last: "network" "default" The first role that is ...
[ "def", "check_network_role", "(", "self", ",", "public_key", ")", ":", "state_root", "=", "self", ".", "_current_root_func", "(", ")", "if", "state_root", "==", "INIT_ROOT_KEY", ":", "LOGGER", ".", "debug", "(", "\"Chain head is not set yet. Permit all.\"", ")", "...
36.53125
0.001667
def _refresh(self, http): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http: an object to be used to make HTTP reques...
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "if", "not", "self", ".", "store", ":", "self", ".", "_do_refresh_request", "(", "http", ")", "else", ":", "self", ".", "store", ".", "acquire_lock", "(", ")", "try", ":", "new_cred", "=", "self"...
35.724138
0.00188
def transaction(self, transaction_id, expand_merchant=False): """ Returns an individual transaction, fetched by its id. Official docs: https://monzo.com/docs/#retrieve-transaction :param transaction_id: Monzo transaction ID :type transaction_id: str :param e...
[ "def", "transaction", "(", "self", ",", "transaction_id", ",", "expand_merchant", "=", "False", ")", ":", "endpoint", "=", "'/transactions/{}'", ".", "format", "(", "transaction_id", ")", "data", "=", "dict", "(", ")", "if", "expand_merchant", ":", "data", "...
32.36
0.002401
def ls(self, directory, note=None, loglevel=logging.DEBUG): """Helper proc to list files in a directory @param directory: directory to list. If the directory doesn't exist, shutit.fail() is called (i.e. the build fails.) @param note: See send() @type directory: string ...
[ "def", "ls", "(", "self", ",", "directory", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "# should this blow up?", "shutit", ".", "handle_note", "(", "note", ")", "if", "not", ...
35.25
0.03681
def _get_action_endpoint(action): """ Return the endpoint base on the view's action :param action: :return: """ _endpoint = None if is_method(action): if hasattr(action, "_rule_cache"): rc = action._rule_cache if rc: k = list(rc.keys())[0] ...
[ "def", "_get_action_endpoint", "(", "action", ")", ":", "_endpoint", "=", "None", "if", "is_method", "(", "action", ")", ":", "if", "hasattr", "(", "action", ",", "\"_rule_cache\"", ")", ":", "rc", "=", "action", ".", "_rule_cache", "if", "rc", ":", "k",...
37.148148
0.000972
def destroy(self): """Close the connection, and close any associated CBS authentication session. """ try: self.lock() _logger.debug("Unlocked connection %r to close.", self.container_id) self._close() finally: self.release() ...
[ "def", "destroy", "(", "self", ")", ":", "try", ":", "self", ".", "lock", "(", ")", "_logger", ".", "debug", "(", "\"Unlocked connection %r to close.\"", ",", "self", ".", "container_id", ")", "self", ".", "_close", "(", ")", "finally", ":", "self", ".",...
31
0.008547
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.title_of_design_condition = None else: self.title_of_design_condition = vals[i] i += 1 i...
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "title_of_design_condition", "=", "None", "else", ":", "self", ".", "title_of_design_condition", "=", "vals",...
24.767241
0.000223
def from_interval(self, startnote, shorthand, up=True): """Shortcut to from_interval_shorthand.""" return self.from_interval_shorthand(startnote, shorthand, up)
[ "def", "from_interval", "(", "self", ",", "startnote", ",", "shorthand", ",", "up", "=", "True", ")", ":", "return", "self", ".", "from_interval_shorthand", "(", "startnote", ",", "shorthand", ",", "up", ")" ]
58
0.011364
async def get(self, name, timeout=None, autoremove=True): """Wait for a value to be set for a key. This is the primary way to receive values from AwaitableDict. You pass in the name of the key you want to wait for, the maximum amount of time you want to wait and then you can await the r...
[ "async", "def", "get", "(", "self", ",", "name", ",", "timeout", "=", "None", ",", "autoremove", "=", "True", ")", ":", "self", ".", "_ensure_declared", "(", "name", ")", "try", ":", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_data", "["...
40.02439
0.001785
def prebinned_hist(counts, binlims, ax=None, *args, **kwargs): """Plot a histogram with counts, binlims already given. Example ======= >>> gaus = np.random.normal(size=100) >>> counts, binlims = np.histogram(gaus, bins='auto') >>> prebinned_hist(countsl binlims) """ ax = get_ax(ax) ...
[ "def", "prebinned_hist", "(", "counts", ",", "binlims", ",", "ax", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "get_ax", "(", "ax", ")", "x", "=", "bincenters", "(", "binlims", ")", "weights", "=", "counts", "return...
32.461538
0.002304
def rk4(x, h, y, f): """ Code from http://doswa.com/2009/04/21/improved-rk4-implementation.html :param int x: curent time :param float h: time step (dt) :param list y: [position, velocity] :params function f: velocity, accelation[x+h] = f(x, state) :return int t, list...
[ "def", "rk4", "(", "x", ",", "h", ",", "y", ",", "f", ")", ":", "k1", "=", "h", "*", "f", "(", "x", ",", "y", ")", "k2", "=", "h", "*", "f", "(", "x", "+", "0.5", "*", "h", ",", "y", "+", "0.5", "*", "k1", ")", "k3", "=", "h", "*"...
36.785714
0.001894
def site(self, action): """ Returns site query """ query = None viewdays = 7 hostpath = self.uri + self.endpoint if action == 'siteinfo': query = hostpath + ( '?action=query' '&meta=siteinfo|siteviews' '...
[ "def", "site", "(", "self", ",", "action", ")", ":", "query", "=", "None", "viewdays", "=", "7", "hostpath", "=", "self", ".", "uri", "+", "self", ".", "endpoint", "if", "action", "==", "'siteinfo'", ":", "query", "=", "hostpath", "+", "(", "'?action...
33.34375
0.001821
def set_double_stack(socket_obj, double_stack=True): # type: (socket.socket, bool) -> None """ Sets up the IPv6 double stack according to the operating system :param socket_obj: A socket object :param double_stack: If True, use the double stack, else only support IPv6 :raise AttributeError: Pyt...
[ "def", "set_double_stack", "(", "socket_obj", ",", "double_stack", "=", "True", ")", ":", "# type: (socket.socket, bool) -> None", "try", ":", "# Use existing value", "opt_ipv6_only", "=", "socket", ".", "IPV6_V6ONLY", "except", "AttributeError", ":", "# Use \"known\" val...
35.777778
0.001008
def gen_post_map(file_name, ext_url=''): ''' Generate the urls for posts. :return: None ''' with open(file_name, 'a') as fout: for kind_key in router_post: recent_posts = MPost.query_all(kind=kind_key, limit=1000000) for recent_post in recent_posts: ur...
[ "def", "gen_post_map", "(", "file_name", ",", "ext_url", "=", "''", ")", ":", "with", "open", "(", "file_name", ",", "'a'", ")", "as", "fout", ":", "for", "kind_key", "in", "router_post", ":", "recent_posts", "=", "MPost", ".", "query_all", "(", "kind", ...
40.071429
0.001742
async def getChatMember(self, chat_id, user_id): """ See: https://core.telegram.org/bots/api#getchatmember """ p = _strip(locals()) return await self._api_request('getChatMember', _rectify(p))
[ "async", "def", "getChatMember", "(", "self", ",", "chat_id", ",", "user_id", ")", ":", "p", "=", "_strip", "(", "locals", "(", ")", ")", "return", "await", "self", ".", "_api_request", "(", "'getChatMember'", ",", "_rectify", "(", "p", ")", ")" ]
53.25
0.009259
def download_file(pk): """Download the file reference in `models.ReleaseFile` with the given pk. """ release_file = models.ReleaseFile.objects.get(pk=pk) logging.info("Downloading %s", release_file.url) proxies = None if settings.LOCALSHOP_HTTP_PROXY: proxies = settings.LOCALSHOP_HTTP_...
[ "def", "download_file", "(", "pk", ")", ":", "release_file", "=", "models", ".", "ReleaseFile", ".", "objects", ".", "get", "(", "pk", "=", "pk", ")", "logging", ".", "info", "(", "\"Downloading %s\"", ",", "release_file", ".", "url", ")", "proxies", "="...
38.956522
0.001089
def get_motor_force(self, motor_name): """ Retrieves the force or torque applied to a joint along/about its active axis. """ return self.call_remote_api('simxGetJointForce', self.get_object_handle(motor_name), streaming=True)
[ "def", "get_motor_force", "(", "self", ",", "motor_name", ")", ":", "return", "self", ".", "call_remote_api", "(", "'simxGetJointForce'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "streaming", "=", "True", ")" ]
61.8
0.009585
def merge_batches(self, data): """Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches ...
[ "def", "merge_batches", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "ssp", ".", "csr_matrix", ")", ":", "return", "ssp", ".", "vstack", "(", "data", ")", "if", "isinstance", "(", "data", "[", "0", "]", ...
33.1875
0.038462
def _qnwsimp1(n, a, b): """ Compute univariate Simpson quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) An n ele...
[ "def", "_qnwsimp1", "(", "n", ",", "a", ",", "b", ")", ":", "if", "n", "%", "2", "==", "0", ":", "print", "(", "\"WARNING qnwsimp: n must be an odd integer. Increasing by 1\"", ")", "n", "+=", "1", "nodes", "=", "np", ".", "linspace", "(", "a", ",", "b...
21.478261
0.000968
def tree(): """ Display a tree of asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() # Get the root classes root = [] for ac in classes: if ac.parentid is None: root.append(ac) # logger.debug(ac.parentid) # header ...
[ "def", "tree", "(", ")", ":", "session", "=", "AppAggregate", "(", ")", ".", "open_session", "(", ")", "classes", "=", "session", ".", "query", "(", "AssetClass", ")", ".", "all", "(", ")", "# Get the root classes", "root", "=", "[", "]", "for", "ac", ...
29.8125
0.002033
def confirmed_reservation(self): """ This method create a new record set for hotel room reservation line ------------------------------------------------------------------- @param self: The object pointer @return: new record set for hotel room reservation line. """ ...
[ "def", "confirmed_reservation", "(", "self", ")", ":", "reservation_line_obj", "=", "self", ".", "env", "[", "'hotel.room.reservation.line'", "]", "vals", "=", "{", "}", "for", "reservation", "in", "self", ":", "reserv_checkin", "=", "datetime", ".", "strptime",...
59.511364
0.000376
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow): ''' Finds interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : np.array Array of end-of-perio...
[ "def", "getPointsForInterpolation", "(", "self", ",", "EndOfPrdvP", ",", "aNrmNow", ")", ":", "cNrmNow", "=", "self", ".", "uPinv", "(", "EndOfPrdvP", ")", "mNrmNow", "=", "cNrmNow", "+", "aNrmNow", "# Limiting consumption is zero as m approaches mNrmMin", "c_for_inte...
33.451613
0.010309
def grab_names_from_emails(email_list): """Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' ...
[ "def", "grab_names_from_emails", "(", "email_list", ")", ":", "all_staff", "=", "STAFF_LIST", "emails_names", "=", "{", "}", "for", "email", "in", "email_list", ":", "for", "person", "in", "all_staff", ":", "if", "email", "==", "person", "[", "'email'", "]",...
23.694444
0.001126
def update_children_comments(self): """ Banana banana """ if self.comment is None: return for sym in self.get_children_symbols(): if isinstance(sym, ParameterSymbol): sym.comment = self.comment.params.get(sym.argname) elif isin...
[ "def", "update_children_comments", "(", "self", ")", ":", "if", "self", ".", "comment", "is", "None", ":", "return", "for", "sym", "in", "self", ".", "get_children_symbols", "(", ")", ":", "if", "isinstance", "(", "sym", ",", "ParameterSymbol", ")", ":", ...
44.285714
0.002105
def minimize_qes(fitted_rates, rates, weights, combs): """Varies QEs to minimize the deviation of the rates from the fitted_rates. Parameters ---------- fitted_rates: numpy array of fitted rates from fit_angular_distribution rates: numpy array of rates of all PMT combinations weights: numpy arr...
[ "def", "minimize_qes", "(", "fitted_rates", ",", "rates", ",", "weights", ",", "combs", ")", ":", "def", "make_quality_function", "(", "fitted_rates", ",", "rates", ",", "weights", ",", "combs", ")", ":", "def", "quality_function", "(", "qes", ")", ":", "s...
33.5625
0.000905
def _axes_style(style=None, rc=None): """ Return a parameter dict for the aesthetic style of the plots. NOTE: This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick. If you'd like to use these styles then import Seaborn! This affects things lik...
[ "def", "_axes_style", "(", "style", "=", "None", ",", "rc", "=", "None", ")", ":", "if", "isinstance", "(", "style", ",", "dict", ")", ":", "style_dict", "=", "style", "else", ":", "# Define colors here", "dark_gray", "=", "\".15\"", "light_gray", "=", "...
33.263889
0.000406
def _scrub_key(key): """ RETURN JUST THE :. CHARACTERS """ if key == None: return None output = [] for c in key: if c in [":", "."]: output.append(c) return "".join(output)
[ "def", "_scrub_key", "(", "key", ")", ":", "if", "key", "==", "None", ":", "return", "None", "output", "=", "[", "]", "for", "c", "in", "key", ":", "if", "c", "in", "[", "\":\"", ",", "\".\"", "]", ":", "output", ".", "append", "(", "c", ")", ...
18.166667
0.008734
def get_options(): """Return a list of acceptable QT APIs, in decreasing order of preference """ #already imported Qt somewhere. Use that loaded = loaded_api() if loaded is not None: return [loaded] mpl = sys.modules.get('matplotlib', None) if mpl is not None and not check_vers...
[ "def", "get_options", "(", ")", ":", "#already imported Qt somewhere. Use that", "loaded", "=", "loaded_api", "(", ")", "if", "loaded", "is", "not", "None", ":", "return", "[", "loaded", "]", "mpl", "=", "sys", ".", "modules", ".", "get", "(", "'matplotlib'"...
31.904762
0.008696
def reset_analog_sample_clock(state=False): """Reset the clock line. Use this just before starting a run to avoid timing issues. """ set_digital_line_state(expt_settings.dev1_clock_out_name, state) set_digital_line_state(expt_settings.dev2_clock_out_name, state) set_digital_line_state(expt_sett...
[ "def", "reset_analog_sample_clock", "(", "state", "=", "False", ")", ":", "set_digital_line_state", "(", "expt_settings", ".", "dev1_clock_out_name", ",", "state", ")", "set_digital_line_state", "(", "expt_settings", ".", "dev2_clock_out_name", ",", "state", ")", "set...
45.888889
0.002375
def get_stats_history(self, item=None, nb=0): """Return the stats history (JSON format).""" s = self.get_json_history(nb=nb) if item is None: return self._json_dumps(s) if isinstance(s, dict): try: return self._json_dumps({item: s[item]}) ...
[ "def", "get_stats_history", "(", "self", ",", "item", "=", "None", ",", "nb", "=", "0", ")", ":", "s", "=", "self", ".", "get_json_history", "(", "nb", "=", "nb", ")", "if", "item", "is", "None", ":", "return", "self", ".", "_json_dumps", "(", "s",...
38.347826
0.002212