text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def collect(self): """ Collect memory stats of LXCs. """ lxc_metrics = ["memory.usage_in_bytes", "memory.limit_in_bytes"] if os.path.isdir(self.config["sys_path"]) is False: self.log.debug("sys_path '%s' isn't directory.", self.config["sys_p...
[ "def", "collect", "(", "self", ")", ":", "lxc_metrics", "=", "[", "\"memory.usage_in_bytes\"", ",", "\"memory.limit_in_bytes\"", "]", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "config", "[", "\"sys_path\"", "]", ")", "is", "False", ":", "sel...
39.138889
0.001385
def save_cb(self, mode): """Save image, figure, and plot data arrays.""" # This just defines the basename. # Extension has to be explicitly defined or things can get messy. w = Widgets.SaveDialog(title='Save {0} data'.format(mode)) filename = w.get_path() if filename is...
[ "def", "save_cb", "(", "self", ",", "mode", ")", ":", "# This just defines the basename.", "# Extension has to be explicitly defined or things can get messy.", "w", "=", "Widgets", ".", "SaveDialog", "(", "title", "=", "'Save {0} data'", ".", "format", "(", "mode", ")",...
31.607143
0.002193
def handle_build_cache( conf: Config, name: str, tag: str, icb: ImageCachingBehavior): """Handle Docker image build cache. Return image ID if image is cached, and there's no need to redo the build. Return None if need to build the image (whether cached locally or not). Raise RuntimeError if not...
[ "def", "handle_build_cache", "(", "conf", ":", "Config", ",", "name", ":", "str", ",", "tag", ":", "str", ",", "icb", ":", "ImageCachingBehavior", ")", ":", "if", "icb", ".", "pull_if_cached", "or", "(", "icb", ".", "pull_if_not_cached", "and", "get_cached...
45.533333
0.000717
def delete_dependency(self, from_task_name, to_task_name): """ Delete a dependency between two tasks. """ logger.debug('Deleting dependency from {0} to {1}'.format(from_task_name, to_task_name)) if not self.state.allow_change_graph: raise DagobahError("job's graph is immutable in it...
[ "def", "delete_dependency", "(", "self", ",", "from_task_name", ",", "to_task_name", ")", ":", "logger", ".", "debug", "(", "'Deleting dependency from {0} to {1}'", ".", "format", "(", "from_task_name", ",", "to_task_name", ")", ")", "if", "not", "self", ".", "s...
46.1
0.008511
def find_target_container(portal_type, record): """Locates a target container for the given portal_type and record :param record: The dictionary representation of a content object :type record: dict :returns: folder which contains the object :rtype: object """ portal_type = portal_type or r...
[ "def", "find_target_container", "(", "portal_type", ",", "record", ")", ":", "portal_type", "=", "portal_type", "or", "record", ".", "get", "(", "\"portal_type\"", ")", "container", "=", "get_container_for", "(", "portal_type", ")", "if", "container", ":", "retu...
28.366667
0.001136
def ner(sentence, format=None): """ Location and classify named entities in text Parameters ========== sentence: {unicode, str} raw sentence Returns ======= tokens: list of tuple with word, pos tag, chunking tag, ner tag tagged sentence Examples -------- ...
[ "def", "ner", "(", "sentence", ",", "format", "=", "None", ")", ":", "sentence", "=", "chunk", "(", "sentence", ")", "crf_model", "=", "CRFNERPredictor", ".", "Instance", "(", ")", "result", "=", "crf_model", ".", "predict", "(", "sentence", ",", "format...
25
0.0011
def label(self, value): """ :type: string """ self._completeIfNotSet(self._label) self._label.value = value
[ "def", "label", "(", "self", ",", "value", ")", ":", "self", ".", "_completeIfNotSet", "(", "self", ".", "_label", ")", "self", ".", "_label", ".", "value", "=", "value" ]
23.666667
0.013605
def show_hids(target_vid = 0, target_pid = 0, output = None): """Check all HID devices conected to PC hosts.""" # first be kind with local encodings if not output: # beware your script should manage encodings output = sys.stdout # then the big cheese... from . import tools ...
[ "def", "show_hids", "(", "target_vid", "=", "0", ",", "target_pid", "=", "0", ",", "output", "=", "None", ")", ":", "# first be kind with local encodings\r", "if", "not", "output", ":", "# beware your script should manage encodings\r", "output", "=", "sys", ".", "...
38.076923
0.009192
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs): """Roll this array by an offset along one or more dimensions. Unlike shift, roll may rotate all variables, including coordinates if specified. The direction of rotation is consistent with :py:func:`numpy.roll`. Par...
[ "def", "roll", "(", "self", ",", "shifts", "=", "None", ",", "roll_coords", "=", "None", ",", "*", "*", "shifts_kwargs", ")", ":", "ds", "=", "self", ".", "_to_temp_dataset", "(", ")", ".", "roll", "(", "shifts", "=", "shifts", ",", "roll_coords", "=...
35.325
0.001377
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None): """ Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matche...
[ "def", "select_eps", "(", "xmrs", ",", "nodeid", "=", "None", ",", "iv", "=", "None", ",", "label", "=", "None", ",", "pred", "=", "None", ")", ":", "epmatch", "=", "lambda", "n", ":", "(", "(", "nodeid", "is", "None", "or", "n", ".", "nodeid", ...
43.076923
0.001747
def create(self, validated_data): """ Create a new user from the data passed to the serializer. If the provided email has not been verified yet, the user is created and a verification email is sent to the address. Otherwise we send a notification to the email address that ...
[ "def", "create", "(", "self", ",", "validated_data", ")", ":", "email", "=", "validated_data", ".", "pop", "(", "\"email\"", ")", "password", "=", "validated_data", ".", "pop", "(", "\"password\"", ")", "# We don't save the user instance yet in case the provided email...
33.304348
0.001268
def optional_data(self, product_type): """Schedules tasks, if any, that produce product_type to be executed before the requesting task. There need not be any tasks that produce the required product type. All this method guarantees is that if there are any then they will be executed before the requesting t...
[ "def", "optional_data", "(", "self", ",", "product_type", ")", ":", "self", ".", "_optional_dependencies", ".", "add", "(", "product_type", ")", "self", ".", "require_data", "(", "product_type", ")" ]
42.7
0.009174
def use_plenary_resource_view(self): """Pass through to provider ResourceLookupSession.use_plenary_resource_view""" self._object_views['resource'] = PLENARY # self._get_provider_session('resource_lookup_session') # To make sure the session is tracked for session in self._get_provider_ses...
[ "def", "use_plenary_resource_view", "(", "self", ")", ":", "self", ".", "_object_views", "[", "'resource'", "]", "=", "PLENARY", "# self._get_provider_session('resource_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_provide...
49.444444
0.00883
def handle(self, key, value): ''' Processes a vaild action info request @param key: The key that matched the request @param value: The value associated with the key ''' # very similar to stop # break down key elements = key.split(":") spiderid = e...
[ "def", "handle", "(", "self", ",", "key", ",", "value", ")", ":", "# very similar to stop", "# break down key", "elements", "=", "key", ".", "split", "(", "\":\"", ")", "spiderid", "=", "elements", "[", "1", "]", "appid", "=", "elements", "[", "2", "]", ...
35.288889
0.001225
def retry(self, retry_message=''): """Forces a currently running asynchronous pipeline to retry. Note this may not be called by synchronous or generator pipelines. Those must instead raise the 'Retry' exception during execution. Args: retry_message: Optional message explaining why the retry happ...
[ "def", "retry", "(", "self", ",", "retry_message", "=", "''", ")", ":", "if", "not", "self", ".", "async", ":", "raise", "UnexpectedPipelineError", "(", "'May only call retry() method for asynchronous pipelines.'", ")", "if", "self", ".", "try_cancel", "(", ")", ...
34
0.008174
def fill_kwargs(self, **kwargs): """ Fill empty variable objects by name with the values from any present keyword arguments. """ for var, val in kwargs.items(): self.setval(var, val)
[ "def", "fill_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "var", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "self", ".", "setval", "(", "var", ",", "val", ")" ]
32.571429
0.008547
def __extract_clusters(self): """! @brief Extract clusters and noise from order database. """ self.__clusters = [] self.__noise = [] current_cluster = self.__noise for optics_object in self.__ordered_database: if (optics_obje...
[ "def", "__extract_clusters", "(", "self", ")", ":", "self", ".", "__clusters", "=", "[", "]", "self", ".", "__noise", "=", "[", "]", "current_cluster", "=", "self", ".", "__noise", "for", "optics_object", "in", "self", ".", "__ordered_database", ":", "if",...
42.894737
0.009604
def _version_find_existing(): """Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Available tags are pulled from origin repository before. :return: available versions :rtype: set """ _tool_run('git fetch...
[ "def", "_version_find_existing", "(", ")", ":", "_tool_run", "(", "'git fetch origin -t'", ")", "git_tags", "=", "[", "x", "for", "x", "in", "(", "y", ".", "strip", "(", ")", "for", "y", "in", "(", "_tool_run", "(", "'git tag -l'", ")", ".", "stdout", ...
39.466667
0.00165
def setitem_via_sibseqs(ol,value,*sibseqs): ''' from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] setitem_via_sibseqs(y,"500",1,1) y ''' this = ol pathlist = list(sibseqs) for i in range(0,pathlist.__len__()-1): key = pathlist[i] thi...
[ "def", "setitem_via_sibseqs", "(", "ol", ",", "value", ",", "*", "sibseqs", ")", ":", "this", "=", "ol", "pathlist", "=", "list", "(", "sibseqs", ")", "for", "i", "in", "range", "(", "0", ",", "pathlist", ".", "__len__", "(", ")", "-", "1", ")", ...
25.8
0.012469
def data_to_premis(data, premis_version=utils.PREMIS_VERSION): """Given tuple ``data`` representing a PREMIS entity (object, event or agent), return an ``lxml.etree._Element`` instance. E.g.,:: >>> p = data_to_premis(( 'event', utils.PREMIS_META, ( 'e...
[ "def", "data_to_premis", "(", "data", ",", "premis_version", "=", "utils", ".", "PREMIS_VERSION", ")", ":", "nsmap", "=", "utils", ".", "PREMIS_VERSIONS_MAP", "[", "premis_version", "]", "[", "\"namespaces\"", "]", "return", "_data_to_lxml_el", "(", "data", ",",...
44.740741
0.001621
def now(cls, tzinfo=None): """[tz] -> new datetime with tz's local day and time.""" obj = cls.utcnow() if tzinfo is None: tzinfo = localtz() return obj.astimezone(tzinfo)
[ "def", "now", "(", "cls", ",", "tzinfo", "=", "None", ")", ":", "obj", "=", "cls", ".", "utcnow", "(", ")", "if", "tzinfo", "is", "None", ":", "tzinfo", "=", "localtz", "(", ")", "return", "obj", ".", "astimezone", "(", "tzinfo", ")" ]
31.166667
0.010417
def get_phased_quantities(stimes, smags, serrs, period): '''Does phase-folding for the mag/flux time-series given a period. Given finite and sigma-clipped times, magnitudes, and errors, along with the period at which to phase-fold the data, perform the phase-folding and return the phase-folded values. ...
[ "def", "get_phased_quantities", "(", "stimes", ",", "smags", ",", "serrs", ",", "period", ")", ":", "# phase the mag series using the given period and faintest mag time", "# mintime = stimes[npwhere(smags == npmax(smags))]", "# phase the mag series using the given period and epoch = min(...
33.730769
0.001662
def switch_update_record_with_switch(self, userid, interface, switch=None): """Update information in switch table.""" if not self._get_switch_by_user_interface(userid, interface): msg = "User %s with nic %s does not exist in DB" % (userid, ...
[ "def", "switch_update_record_with_switch", "(", "self", ",", "userid", ",", "interface", ",", "switch", "=", "None", ")", ":", "if", "not", "self", ".", "_get_switch_by_user_interface", "(", "userid", ",", "interface", ")", ":", "msg", "=", "\"User %s with nic %...
52.407407
0.002082
def update_kb_attributes(kb_name, new_name, new_description=''): """Update kb kb_name with a new name and (optionally) description. :param kb_name: the name of the kb to update :param new_name: the new name for the kb :param new_description: the new description for the kb """ models.KnwKB.query...
[ "def", "update_kb_attributes", "(", "kb_name", ",", "new_name", ",", "new_description", "=", "''", ")", ":", "models", ".", "KnwKB", ".", "query", ".", "filter_by", "(", "name", "=", "kb_name", ")", ".", "update", "(", "{", "\"name\"", ":", "new_name", "...
45.111111
0.002415
def pole(conic, plane): """ Calculates the pole of a polar plane for a given conic section. """ v = dot(N.linalg.inv(conic),plane) return v[:-1]/v[-1]
[ "def", "pole", "(", "conic", ",", "plane", ")", ":", "v", "=", "dot", "(", "N", ".", "linalg", ".", "inv", "(", "conic", ")", ",", "plane", ")", "return", "v", "[", ":", "-", "1", "]", "/", "v", "[", "-", "1", "]" ]
27.428571
0.015152
def setup_log(name): '''Returns a logging instance for the provided name. The returned object is an instance of logging.Logger. Logged messages will be printed to stderr when running in the CLI, or forwarded to XBMC's log when running in XBMC mode. ''' _log = logging.getLogger(name) _log.set...
[ "def", "setup_log", "(", "name", ")", ":", "_log", "=", "logging", ".", "getLogger", "(", "name", ")", "_log", ".", "setLevel", "(", "GLOBAL_LOG_LEVEL", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Fo...
39.6
0.001645
def update_recent_file_menu(self): """Update recent file menu""" recent_files = [] for fname in self.recent_files: if self.is_file_opened(fname) is None and osp.isfile(fname): recent_files.append(fname) self.recent_file_menu.clear() if recent_fi...
[ "def", "update_recent_file_menu", "(", "self", ")", ":", "recent_files", "=", "[", "]", "for", "fname", "in", "self", ".", "recent_files", ":", "if", "self", ".", "is_file_opened", "(", "fname", ")", "is", "None", "and", "osp", ".", "isfile", "(", "fname...
50.176471
0.002301
def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0]
[ "def", "find_best_akaike", "(", "list_of_fits", ")", ":", "res", "=", "sorted", "(", "list_of_fits", ",", "key", "=", "lambda", "x", ":", "x", ".", "aic", ")", "return", "res", "[", "0", "]" ]
45.75
0.010753
def make_parser(handler): """ Convenience function to construct a document parser with namespaces enabled and validation disabled. Document validation is a nice feature, but enabling validation can require the LIGO LW DTD to be downloaded from the LDAS document server if the DTD is not included inline in the XML...
[ "def", "make_parser", "(", "handler", ")", ":", "parser", "=", "sax", ".", "make_parser", "(", ")", "parser", ".", "setContentHandler", "(", "handler", ")", "parser", ".", "setFeature", "(", "sax", ".", "handler", ".", "feature_namespaces", ",", "True", ")...
42.866667
0.022831
def convert_padding(builder, layer, input_names, output_names, keras_layer): """ Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural n...
[ "def", "convert_padding", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "_check_data_format", "(", "keras_layer", ")", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "...
35.442308
0.008448
def query_other_gene_name(): """ Returns list of alternative short name by query query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Alternative short name default: CVAP ...
[ "def", "query_other_gene_name", "(", ")", ":", "args", "=", "get_args", "(", "request_args", "=", "request", ".", "args", ",", "allowed_str_args", "=", "[", "'name'", ",", "'entry_name'", "]", ",", "allowed_int_args", "=", "[", "'limit'", "]", ")", "return",...
19.808511
0.001024
def get_profile_model(): """ Return the model class for the currently-active user profile model, as defined by the ``AUTH_PROFILE_MODULE`` setting. :return: The model that is used as profile. """ if (not hasattr(settings, 'AUTH_PROFILE_MODULE') or not settings.AUTH_PROFILE_MODULE): ...
[ "def", "get_profile_model", "(", ")", ":", "if", "(", "not", "hasattr", "(", "settings", ",", "'AUTH_PROFILE_MODULE'", ")", "or", "not", "settings", ".", "AUTH_PROFILE_MODULE", ")", ":", "raise", "SiteProfileNotAvailable", "profile_mod", "=", "get_model", "(", "...
33.533333
0.001934
def set_bootdev(bootdev='default', persist=False, uefiboot=False, **kwargs): ''' Set boot device to use on next reboot :param bootdev: - network: Request network boot - hd: Boot from hard drive - safe: Boot from hard drive, requesting 'safe mode' - optical: boot from CD/DVD/...
[ "def", "set_bootdev", "(", "bootdev", "=", "'default'", ",", "persist", "=", "False", ",", "uefiboot", "=", "False", ",", "*", "*", "kwargs", ")", ":", "with", "_IpmiCommand", "(", "*", "*", "kwargs", ")", "as", "s", ":", "return", "s", ".", "set_boo...
33.575
0.000724
def monitored(name, **params): ''' Makes sure an URL is monitored by uptime. Checks if URL is already monitored, and if not, adds it. ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __salt__['uptime.check_exists'](name=name): ret['result'] = True ret['...
[ "def", "monitored", "(", "name", ",", "*", "*", "params", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__salt__", "[", "'uptime.check_exists'...
35.37931
0.000949
def _train_model(self, train_X, train_Y=None, val_X=None, val_Y=None): """Train the model. Parameters ---------- train_X : array_like Training data, shape (num_samples, num_features). train_Y : array_like, optional (default = None) Reference training da...
[ "def", "_train_model", "(", "self", ",", "train_X", ",", "train_Y", "=", "None", ",", "val_X", "=", "None", ",", "val_Y", "=", "None", ")", ":", "pbar", "=", "tqdm", "(", "range", "(", "self", ".", "num_epochs", ")", ")", "for", "i", "in", "pbar", ...
34.352941
0.001665
def parse_oxide(self): """ Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide. Returns: oxide_type (str): Type of oxide ozonide/peroxide/superoxide/hydroxide/None. nbonds (int): Number of peroxide/superoxide/hydroxide bonds in st...
[ "def", "parse_oxide", "(", "self", ")", ":", "structure", "=", "self", ".", "structure", "relative_cutoff", "=", "self", ".", "relative_cutoff", "o_sites_frac_coords", "=", "[", "]", "h_sites_frac_coords", "=", "[", "]", "lattice", "=", "structure", ".", "latt...
39
0.000704
def input(self, *args, **kwargs): """ Adapt the input and check for errors. Returns a tuple of adapted (args, kwargs) or raises AnticipateErrors """ errors = [] if args and self.arg_names: args = list(args) # Replace args inline that have...
[ "def", "input", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "if", "args", "and", "self", ".", "arg_names", ":", "args", "=", "list", "(", "args", ")", "# Replace args inline that have adapters", "for", "i"...
31.393939
0.001873
def humanize_filesize(value): """ Return an humanized file size. """ value = float(value) if value == 1: return '1 Byte' elif value < 1024: return '%d Bytes' % value elif value < 1024: return '%dB' % value for i, s in enumerate(SUFFIXES): unit = 1024 ** (i ...
[ "def", "humanize_filesize", "(", "value", ")", ":", "value", "=", "float", "(", "value", ")", "if", "value", "==", "1", ":", "return", "'1 Byte'", "elif", "value", "<", "1024", ":", "return", "'%d Bytes'", "%", "value", "elif", "value", "<", "1024", ":...
24.444444
0.002188
def InitFromDataPoints(self, start_stats, complete_stats): """Check that this approval applies to the given token. Args: start_stats: A list of lists, each containing two values (a timestamp and the number of clients started at this time). complete_stats: A list of lists, each containing tw...
[ "def", "InitFromDataPoints", "(", "self", ",", "start_stats", ",", "complete_stats", ")", ":", "self", ".", "start_points", "=", "self", ".", "_ConvertToResultList", "(", "start_stats", ")", "self", ".", "complete_points", "=", "self", ".", "_ConvertToResultList",...
41.6
0.001567
def known(self, words: List[str]) -> List[str]: """ Return a list of given words that found in the spelling dictionary :param str words: A list of words to check if they are in the spelling dictionary """ return list(w for w in words if w in self.__WORDS)
[ "def", "known", "(", "self", ",", "words", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "list", "(", "w", "for", "w", "in", "words", "if", "w", "in", "self", ".", "__WORDS", ")" ]
41.428571
0.010135
def set_type(self, type, header='Content-Type', requote=True): """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the par...
[ "def", "set_type", "(", "self", ",", "type", ",", "header", "=", "'Content-Type'", ",", "requote", "=", "True", ")", ":", "# BAW: should we be strict?", "if", "not", "type", ".", "count", "(", "'/'", ")", "==", "1", ":", "raise", "ValueError", "# Set the C...
40.225806
0.001566
def write_tex(matrix, version, out, scale=1, border=None, color='black', unit='pt', url=None): """\ Serializes the matrix as LaTeX PGF picture. Requires the `PGF/TikZ <https://en.wikipedia.org/wiki/PGF/TikZ>`_ package (i.e. ``\\usepackage{pgf}``) in the LaTeX source. :param matrix: The matrix to s...
[ "def", "write_tex", "(", "matrix", ",", "version", ",", "out", ",", "scale", "=", "1", ",", "border", "=", "None", ",", "color", "=", "'black'", ",", "unit", "=", "'pt'", ",", "url", "=", "None", ")", ":", "def", "point", "(", "x", ",", "y", ")...
49.931818
0.001786
def stop(self): """ Restore the TTY to its original state. """ _curses.nocbreak() self.window.keypad(0) _curses.echo() _curses.resetty() _curses.endwin() self.running = False
[ "def", "stop", "(", "self", ")", ":", "_curses", ".", "nocbreak", "(", ")", "self", ".", "window", ".", "keypad", "(", "0", ")", "_curses", ".", "echo", "(", ")", "_curses", ".", "resetty", "(", ")", "_curses", ".", "endwin", "(", ")", "self", "....
23.7
0.00813
def font_extents(self): """Return the extents of the currently selected font. Values are given in the current user-space coordinate system. Because font metrics are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. I...
[ "def", "font_extents", "(", "self", ")", ":", "extents", "=", "ffi", ".", "new", "(", "'cairo_font_extents_t *'", ")", "cairo", ".", "cairo_font_extents", "(", "self", ".", "_pointer", ",", "extents", ")", "self", ".", "_check_status", "(", ")", "# returning...
48.189655
0.000701
def _bounded_int_doc(cls): """Add bounded int docstring template to class init.""" def __init__(self, value=None, min=None, max=None, step=None, **kwargs): if value is not None: kwargs['value'] = value if min is not None: kwargs['min'] = min if max is not None: ...
[ "def", "_bounded_int_doc", "(", "cls", ")", ":", "def", "__init__", "(", "self", ",", "value", "=", "None", ",", "min", "=", "None", ",", "max", "=", "None", ",", "step", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "not",...
32.9375
0.001845
def eval(e, amplitude, e_0, alpha, e_cutoff, beta): """One dimensional power law with an exponential cutoff model function """ xx = e / e_0 return amplitude * xx ** (-alpha) * np.exp(-(e / e_cutoff) ** beta)
[ "def", "eval", "(", "e", ",", "amplitude", ",", "e_0", ",", "alpha", ",", "e_cutoff", ",", "beta", ")", ":", "xx", "=", "e", "/", "e_0", "return", "amplitude", "*", "xx", "**", "(", "-", "alpha", ")", "*", "np", ".", "exp", "(", "-", "(", "e"...
39.166667
0.008333
def clone(srcpath, destpath, vcs=None): """Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of new repository :param str vcs: Either ``git``, ``hg``, or ``svn`` :returns VCSRepo: The newly cloned repository If ``vcs`` is not giv...
[ "def", "clone", "(", "srcpath", ",", "destpath", ",", "vcs", "=", "None", ")", ":", "vcs", "=", "vcs", "or", "probe", "(", "srcpath", ")", "cls", "=", "_get_repo_class", "(", "vcs", ")", "return", "cls", ".", "clone", "(", "srcpath", ",", "destpath",...
33.333333
0.001946
def relations(): """Get a nested dictionary of relation data for all related units""" rels = {} for reltype in relation_types(): relids = {} for relid in relation_ids(reltype): units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} for unit in related_unit...
[ "def", "relations", "(", ")", ":", "rels", "=", "{", "}", "for", "reltype", "in", "relation_types", "(", ")", ":", "relids", "=", "{", "}", "for", "relid", "in", "relation_ids", "(", "reltype", ")", ":", "units", "=", "{", "local_unit", "(", ")", "...
38.230769
0.001965
def perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB'): """ Calculates various performance metrics of a strategy, for use in plotting.show_perf_stats. Parameters ---------- returns : pd.Series Daily returns of the strategy, n...
[ "def", "perf_stats", "(", "returns", ",", "factor_returns", "=", "None", ",", "positions", "=", "None", ",", "transactions", "=", "None", ",", "turnover_denom", "=", "'AGB'", ")", ":", "stats", "=", "pd", ".", "Series", "(", ")", "for", "stat_func", "in"...
38.083333
0.000533
def factory(cls, **kwargs): """ Factory method that can be used to easily instantiate a class instance :param cls: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class. """ for name, obj in inspect...
[ "def", "factory", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "obj", "in", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", "and", "...
35.25
0.001727
def get_inner_fts(elt)->List[str]: "List the inner functions of a class." fts = [] for ft_name in elt.__dict__.keys(): if ft_name.startswith('_'): continue ft = getattr(elt, ft_name) if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name}') if inspect.ismethod(ft): f...
[ "def", "get_inner_fts", "(", "elt", ")", "->", "List", "[", "str", "]", ":", "fts", "=", "[", "]", "for", "ft_name", "in", "elt", ".", "__dict__", ".", "keys", "(", ")", ":", "if", "ft_name", ".", "startswith", "(", "'_'", ")", ":", "continue", "...
45.4
0.015119
def gcd(vector): """ Calculate the greatest common divisor (GCD) of a sequence of numbers. The sequence can be a list of numbers or a Numpy vector of numbers. The computations are carried out with a precision of 1E-12 if the objects are not `fractions <https://docs.python.org/3/library/fractions.ht...
[ "def", "gcd", "(", "vector", ")", ":", "# pylint: disable=C1801", "if", "not", "len", "(", "vector", ")", ":", "return", "None", "if", "len", "(", "vector", ")", "==", "1", ":", "return", "vector", "[", "0", "]", "if", "len", "(", "vector", ")", "=...
37.192308
0.001008
def _init_deferred_buffers(self): """ Initialize or reinitalize all the deferred transfer buffers Calling this method will drop all pending transactions so use with care. """ # List of transfers that have been started, but # not completed (started by write_reg, r...
[ "def", "_init_deferred_buffers", "(", "self", ")", ":", "# List of transfers that have been started, but", "# not completed (started by write_reg, read_reg,", "# reg_write_repeat and reg_read_repeat)", "self", ".", "_transfer_list", "=", "collections", ".", "deque", "(", ")", "# ...
42.473684
0.002424
def parse_grid_xml(self): """Parse the grid xyz and calculate the bounding box of the event. :raises: GridXmlParseError The grid xyz dataset looks like this:: <?xml version="1.0" encoding="US-ASCII" standalone="yes"?> <shakemap_grid xmlns:xsi="http://www.w3.org/2001/XMLS...
[ "def", "parse_grid_xml", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'ParseGridXml requested.'", ")", "grid_path", "=", "self", ".", "grid_file_path", "(", ")", "try", ":", "document", "=", "minidom", ".", "parse", "(", "grid_path", ")", "shakemap_g...
47.122581
0.000268
def _dispatch_event(self): """ Dispatch the event to the handler. """ data = self._prepare_data() if data is not None: self._handler(self._event, data) self._reset_event_data()
[ "def", "_dispatch_event", "(", "self", ")", ":", "data", "=", "self", ".", "_prepare_data", "(", ")", "if", "data", "is", "not", "None", ":", "self", ".", "_handler", "(", "self", ".", "_event", ",", "data", ")", "self", ".", "_reset_event_data", "(", ...
25.444444
0.008439
def group(store=None, overwrite=False, chunk_store=None, cache_attrs=True, synchronizer=None, path=None): """Create a group. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system. overwrite : bool, optional If True, dele...
[ "def", "group", "(", "store", "=", "None", ",", "overwrite", "=", "False", ",", "chunk_store", "=", "None", ",", "cache_attrs", "=", "True", ",", "synchronizer", "=", "None", ",", "path", "=", "None", ")", ":", "# handle polymorphic store arg", "store", "=...
31.035714
0.000558
def wd_db004(self, value=None): """ Corresponds to IDD Field `wd_db004` corresponding most frequent wind direction Mean wind speed coincident with 0.4% dry-bulb temperature degrees true from north (east = 90 deg) Args: value (float): value for IDD Field `wd_db004` ...
[ "def", "wd_db004", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float...
36.173913
0.002342
def _get_firmware_file_in_new_path(searching_path): """Gets the raw firmware file in a new path Gets the raw firmware file from the extracted directory structure and creates a hard link to that in a file path and cleans up the lookup extract path. :param searching_path: the directory structure to s...
[ "def", "_get_firmware_file_in_new_path", "(", "searching_path", ")", ":", "firmware_file_path", "=", "_get_firmware_file", "(", "searching_path", ")", "if", "not", "firmware_file_path", ":", "return", "None", "# Note(deray): the path of the new firmware file will be of the form:"...
39.703704
0.000911
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(':...
[ "def", "assert_fingerprint", "(", "cert", ",", "fingerprint", ")", ":", "fingerprint", "=", "fingerprint", ".", "replace", "(", "':'", ",", "''", ")", ".", "lower", "(", ")", "digest_length", "=", "len", "(", "fingerprint", ")", "hashfunc", "=", "HASHFUNC_...
35.32
0.001103
def split_sql(sql): """generate hunks of SQL that are between the bookends return: tuple of beginning bookend, closing bookend, and contents note: beginning & end of string are returned as None""" bookends = ("\n", ";", "--", "/*", "*/") last_bookend_found = None start = 0 while sta...
[ "def", "split_sql", "(", "sql", ")", ":", "bookends", "=", "(", "\"\\n\"", ",", "\";\"", ",", "\"--\"", ",", "\"/*\"", ",", "\"*/\"", ")", "last_bookend_found", "=", "None", "start", "=", "0", "while", "start", "<=", "len", "(", "sql", ")", ":", "res...
38.388889
0.001412
def update_ports_tree(ports_tree): ''' Updates the ports tree, either the default or the `ports_tree` specified CLI Example: .. code-block:: bash salt '*' poudriere.update_ports_tree staging ''' _check_config_exists() if ports_tree: cmd = 'poudriere ports -u -p {0}'.format...
[ "def", "update_ports_tree", "(", "ports_tree", ")", ":", "_check_config_exists", "(", ")", "if", "ports_tree", ":", "cmd", "=", "'poudriere ports -u -p {0}'", ".", "format", "(", "ports_tree", ")", "else", ":", "cmd", "=", "'poudriere ports -u'", "ret", "=", "__...
24.176471
0.002342
def save_config(**kwargs): """Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/value pairs to save to the config file. """ if kwargs == {}: kwargs = config._config current_config = _load_config() current_config.update(**...
[ "def", "save_config", "(", "*", "*", "kwargs", ")", ":", "if", "kwargs", "==", "{", "}", ":", "kwargs", "=", "config", ".", "_config", "current_config", "=", "_load_config", "(", ")", "current_config", ".", "update", "(", "*", "*", "kwargs", ")", "# wr...
31.35
0.001548
def __map_axis(self, axis): """Get the linux xpad code from the Windows xinput code.""" start_code, start_value = axis value = start_value code = self.manager.codes['xpad'][start_code] return code, value
[ "def", "__map_axis", "(", "self", ",", "axis", ")", ":", "start_code", ",", "start_value", "=", "axis", "value", "=", "start_value", "code", "=", "self", ".", "manager", ".", "codes", "[", "'xpad'", "]", "[", "start_code", "]", "return", "code", ",", "...
39.666667
0.00823
def getAll(self): """Get all objects Returns: List: list of all objects """ objs = [] for obj in self.model.db: objs.append(self._cast_model(obj)) return objs
[ "def", "getAll", "(", "self", ")", ":", "objs", "=", "[", "]", "for", "obj", "in", "self", ".", "model", ".", "db", ":", "objs", ".", "append", "(", "self", ".", "_cast_model", "(", "obj", ")", ")", "return", "objs" ]
23
0.008368
def merge(*tables, **kwargs): """ Convenience function to combine multiple tables (via :func:`petl.transform.sorts.mergesort`) then combine duplicate rows by merging under the given key (via :func:`petl.transform.reductions.mergeduplicates`). E.g.:: >>> import petl as etl >>> table1...
[ "def", "merge", "(", "*", "tables", ",", "*", "*", "kwargs", ")", ":", "assert", "'key'", "in", "kwargs", ",", "'keyword argument \"key\" is required'", "key", "=", "kwargs", "[", "'key'", "]", "t1", "=", "mergesort", "(", "*", "tables", ",", "*", "*", ...
39.052632
0.000657
def date_is_valid(dates): """Checks if dates (e.g. ["17", "11"] ) is valid and returns bool Checks if the first element is between 1 and 31 and the second element is between 1 and 12. Keyword arguments: dates -- list of numbers Returns: True if the date is valid, False otherwise. """...
[ "def", "date_is_valid", "(", "dates", ")", ":", "if", "(", "int", "(", "dates", "[", "0", "]", ")", "<", "1", "or", "int", "(", "dates", "[", "0", "]", ")", ">", "31", "or", "int", "(", "dates", "[", "1", "]", ")", "<", "1", "or", "int", ...
23.4
0.002053
def topic(self, channel, topic=None): """change or request the topic of a channel""" if topic: channel += ' :' + topic self.send_line('TOPIC %s' % channel)
[ "def", "topic", "(", "self", ",", "channel", ",", "topic", "=", "None", ")", ":", "if", "topic", ":", "channel", "+=", "' :'", "+", "topic", "self", ".", "send_line", "(", "'TOPIC %s'", "%", "channel", ")" ]
37.4
0.010471
def whole_line_styled(p): """ Checks to see if the whole p tag will end up being bold or italics. Returns a tuple (boolean, boolean). The first boolean will be True if the whole line is bold, False otherwise. The second boolean will be True if the whole line is italics, False otherwise. """ ...
[ "def", "whole_line_styled", "(", "p", ")", ":", "r_tags", "=", "p", ".", "xpath", "(", "'.//w:r'", ",", "namespaces", "=", "p", ".", "nsmap", ")", "tags_are_bold", "=", "[", "is_bold", "(", "r", ")", "or", "is_underlined", "(", "r", ")", "for", "r", ...
37.133333
0.001751
def list_helper(self,k,pak,attr,col): """ helper to setup list multiplier parameters for a given k, pak, attr set. Parameters ---------- k : int or iterable of int the zero-based stress period indices pak : flopy.PakBase= the MODFLOW package ...
[ "def", "list_helper", "(", "self", ",", "k", ",", "pak", ",", "attr", ",", "col", ")", ":", "# special case for horrible HFB6 exception", "# if type(pak) == flopy.modflow.mfhfb.ModflowHfb:", "# filename = pak.file_name[0]", "# else:", "filename", "=", "attr", ".", "ge...
35.6
0.010941
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access point...
[ "def", "AddWiFiConnection", "(", "self", ",", "dev_path", ",", "connection_name", ",", "ssid_name", ",", "key_mgmt", ")", ":", "dev_obj", "=", "dbusmock", ".", "get_object", "(", "dev_path", ")", "connection_path", "=", "'/org/freedesktop/NetworkManager/Settings/'", ...
38.680412
0.001819
def filterItems(self, terms, caseSensitive=False): """ Filters the items in this tree based on the inputed text. :param terms | <str> || {<str> datatype: [<str> opt, ..]} caseSensitive | <bool> """ ...
[ "def", "filterItems", "(", "self", ",", "terms", ",", "caseSensitive", "=", "False", ")", ":", "# create a dictionary of options", "if", "type", "(", "terms", ")", "!=", "dict", ":", "terms", "=", "{", "'*'", ":", "nativestring", "(", "terms", ")", "}", ...
36.857143
0.010248
def set_serializer(self, serializer_name, compression=None): """ Configure the serializer to use for communication with the server. The serializer specified must be valid and in the :py:data:`.g_serializer_drivers` map. :param str serializer_name: The name of the serializer to use. :param str compression: ...
[ "def", "set_serializer", "(", "self", ",", "serializer_name", ",", "compression", "=", "None", ")", ":", "self", ".", "serializer", "=", "Serializer", "(", "serializer_name", ",", "charset", "=", "'UTF-8'", ",", "compression", "=", "compression", ")", "self", ...
46.090909
0.023211
def working_area(files, name=""): """ Copy all files to a temporary directory (the working area) Optionally names the working area name Returns path to the working area """ with tempfile.TemporaryDirectory() as dir: dir = Path(Path(dir) / name) dir.mkdir(exist_ok=True) f...
[ "def", "working_area", "(", "files", ",", "name", "=", "\"\"", ")", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "dir", ":", "dir", "=", "Path", "(", "Path", "(", "dir", ")", "/", "name", ")", "dir", ".", "mkdir", "(", "exist...
31.333333
0.002066
def import_private_key(self, pem_text, password=None): """ Import a private key from data in PEM-format :param pem_text: text with private key :param password: If it is not None, then result will be decrypt with the given password :return: None """ if isinstance(pem_text, str) is True: pem_text = pem_te...
[ "def", "import_private_key", "(", "self", ",", "pem_text", ",", "password", "=", "None", ")", ":", "if", "isinstance", "(", "pem_text", ",", "str", ")", "is", "True", ":", "pem_text", "=", "pem_text", ".", "encode", "(", ")", "if", "password", "is", "n...
35.933333
0.028933
def realtime_observations(cls, buoy, data_type='txt'): """Retrieve the realtime buoy data from NDBC. Parameters ---------- buoy : str Name of buoy data_type : str Type of data requested, must be one of 'txt' standard meteorological data ...
[ "def", "realtime_observations", "(", "cls", ",", "buoy", ",", "data_type", "=", "'txt'", ")", ":", "endpoint", "=", "cls", "(", ")", "parsers", "=", "{", "'txt'", ":", "endpoint", ".", "_parse_met", ",", "'drift'", ":", "endpoint", ".", "_parse_drift", "...
37.47619
0.002477
def sort_by(self, attr_or_key, direction='asc'): """Sort the view by an attribute or key :param attr_or_key: The attribute or key to sort by :param direction: Either `asc` or `desc` indicating the direction of sorting """ # work out the direction ...
[ "def", "sort_by", "(", "self", ",", "attr_or_key", ",", "direction", "=", "'asc'", ")", ":", "# work out the direction", "if", "direction", "in", "(", "'+'", ",", "'asc'", ",", "gtk", ".", "SORT_ASCENDING", ")", ":", "direction", "=", "gtk", ".", "SORT_ASC...
40.090909
0.002215
def configure_sbi(): """Configure an SBI using POSTed configuration.""" # Need an ID for the subarray - guessing I just get # the list of inactive subarrays and use the first inactive_list = SubarrayList().inactive request_data = request.data LOG.debug('request is of type %s', type(request_data)...
[ "def", "configure_sbi", "(", ")", ":", "# Need an ID for the subarray - guessing I just get", "# the list of inactive subarrays and use the first", "inactive_list", "=", "SubarrayList", "(", ")", ".", "inactive", "request_data", "=", "request", ".", "data", "LOG", ".", "deb...
44.058824
0.001307
def registration_settings(request): '''Expose selected settings to templates''' context = {} for setting in ( 'WAFER_SSO', 'WAFER_HIDE_LOGIN', 'WAFER_REGISTRATION_OPEN', 'WAFER_REGISTRATION_MODE', 'WAFER_TALKS_OPEN', 'WAFER_VIDEO_LICENS...
[ "def", "registration_settings", "(", "request", ")", ":", "context", "=", "{", "}", "for", "setting", "in", "(", "'WAFER_SSO'", ",", "'WAFER_HIDE_LOGIN'", ",", "'WAFER_REGISTRATION_OPEN'", ",", "'WAFER_REGISTRATION_MODE'", ",", "'WAFER_TALKS_OPEN'", ",", "'WAFER_VIDEO...
30.538462
0.002445
def must_be_true(self, constraints, expression) -> bool: """Check if expression is True and that it can not be False with current constraints""" solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True) return solutions == [True]
[ "def", "must_be_true", "(", "self", ",", "constraints", ",", "expression", ")", "->", "bool", ":", "solutions", "=", "self", ".", "get_all_values", "(", "constraints", ",", "expression", ",", "maxcnt", "=", "2", ",", "silent", "=", "True", ")", "return", ...
68
0.014545
def generate_numa(self, vcpu_num): """ Generate guest CPU <numa> XML child Configures 1, 2 or 4 vCPUs per cell. Args: vcpu_num(str): number of virtual CPUs Returns: lxml.etree.Element: numa XML element """ if int(vcpu_num) == 2: ...
[ "def", "generate_numa", "(", "self", ",", "vcpu_num", ")", ":", "if", "int", "(", "vcpu_num", ")", "==", "2", ":", "# 2 vCPUs is a special case.", "# We wish to have 2 cells,", "# with 1 vCPU in each.", "# This is also the common case.", "total_cells", "=", "2", "cpus_p...
32.257576
0.000912
def flags(self, index): """Reimplemented from QtCore.QAbstractItemModel Only the value is editable """ if index.column() == 1: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable else: return QtCore.Qt.ItemIsEnabled | Qt...
[ "def", "flags", "(", "self", ",", "index", ")", ":", "if", "index", ".", "column", "(", ")", "==", "1", ":", "return", "QtCore", ".", "Qt", ".", "ItemIsEnabled", "|", "QtCore", ".", "Qt", ".", "ItemIsSelectable", "|", "QtCore", ".", "Qt", ".", "Ite...
37.333333
0.008721
def process_sentence(sentence, start_word="<S>", end_word="</S>"): """Seperate a sentence string into a list of string words, add start_word and end_word, see ``create_vocab()`` and ``tutorial_tfrecord3.py``. Parameters ---------- sentence : str A sentence. start_word : str or None ...
[ "def", "process_sentence", "(", "sentence", ",", "start_word", "=", "\"<S>\"", ",", "end_word", "=", "\"</S>\"", ")", ":", "if", "start_word", "is", "not", "None", ":", "process_sentence", "=", "[", "start_word", "]", "else", ":", "process_sentence", "=", "[...
28.634146
0.001647
def _parse_config_options( config: Mapping[str, Union[ResourceOptions, Mapping[str, Any]]]=None): """Parse CORS configuration (default or per-route) :param config: Mapping from Origin to Resource configuration (allowed headers etc) defined either as mapping or `ResourceOptions` instance...
[ "def", "_parse_config_options", "(", "config", ":", "Mapping", "[", "str", ",", "Union", "[", "ResourceOptions", ",", "Mapping", "[", "str", ",", "Any", "]", "]", "]", "=", "None", ")", ":", "if", "config", "is", "None", ":", "return", "{", "}", "if"...
33.735849
0.00163
def _setup_install_commands_from_kwargs(kwargs, keys=tuple()): """Setup install commands for conda.""" cmd_list = [] if kwargs.get('override_channels', False) and 'channel' not in kwargs: raise TypeError('conda search: override_channels requires channel') if 'env' in kwargs:...
[ "def", "_setup_install_commands_from_kwargs", "(", "kwargs", ",", "keys", "=", "tuple", "(", ")", ")", ":", "cmd_list", "=", "[", "]", "if", "kwargs", ".", "get", "(", "'override_channels'", ",", "False", ")", "and", "'channel'", "not", "in", "kwargs", ":"...
38.608696
0.002198
def e(self,analytic=False,pot=None,**kwargs): """ NAME: e PURPOSE: calculate the eccentricity, either numerically from the numerical orbit integration or using analytical means INPUT: analytic(= False) compute this analytically pot - pote...
[ "def", "e", "(", "self", ",", "analytic", "=", "False", ",", "pot", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "pot", "is", "None", ":", "pot", "=", "flatten_potential", "(", "pot", ")", "_check_consistent_units", "(", "self", ",", ...
32.488372
0.012509
def get_or_add_childTnLst(self): """Return parent element for a new `p:video` child element. The `p:video` element causes play controls to appear under a video shape (pic shape containing video). There can be more than one video shape on a slide, which causes the precondition to vary. I...
[ "def", "get_or_add_childTnLst", "(", "self", ")", ":", "childTnLst", "=", "self", ".", "_childTnLst", "if", "childTnLst", "is", "None", ":", "childTnLst", "=", "self", ".", "_add_childTnLst", "(", ")", "return", "childTnLst" ]
50.529412
0.002286
def _reduce(self, name, skipna=True, **kwargs): """ Return a scalar result of performing the reduction operation. Parameters ---------- name : str Name of the function, supported values are: { any, all, min, max, sum, mean, median, prod, std, ...
[ "def", "_reduce", "(", "self", ",", "name", ",", "skipna", "=", "True", ",", "*", "*", "kwargs", ")", ":", "raise", "TypeError", "(", "\"cannot perform {name} with type {dtype}\"", ".", "format", "(", "name", "=", "name", ",", "dtype", "=", "self", ".", ...
31
0.002407
def startstop_bool(pack): """Make a bool array based on start and stop conditions. pack: pack.ChannelPack instance If there is start conditions but no stop conditions, this is legal, the True section will begin at first start and remain the rest of the array. Likewise, if there is stop con...
[ "def", "startstop_bool", "(", "pack", ")", ":", "b_TRUE", "=", "np", ".", "ones", "(", "pack", ".", "rec_cnt", ")", "==", "True", "# NOQA", "start_list", "=", "pack", ".", "conconf", ".", "conditions_list", "(", "'startcond'", ")", "stop_list", "=", "pac...
29.3125
0.000688
def read_dependencies(filename): """Read in the dependencies from the virtualenv requirements file. """ dependencies = [] filepath = os.path.join('requirements', filename) with open(filepath, 'r') as stream: for line in stream: package = line.strip().split('#')[0].strip() ...
[ "def", "read_dependencies", "(", "filename", ")", ":", "dependencies", "=", "[", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "'requirements'", ",", "filename", ")", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "stream", ":", "...
35.75
0.002273
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @g...
[ "def", "genty_repeat", "(", "count", ")", ":", "if", "count", "<", "0", ":", "raise", "ValueError", "(", "\"Really? Can't have {0} iterations. Please pick a value >= 0.\"", ".", "format", "(", "count", ")", ")", "def", "wrap", "(", "test_method", ")", ":", "test...
27
0.001153
def put(self, url, params=None, headers=None, content=None, form_content=None): # type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest """Create a PUT request object. :param str url: The request URL. :param dict params: Request ...
[ "def", "put", "(", "self", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "content", "=", "None", ",", "form_content", "=", "None", ")", ":", "# type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -...
48
0.009294
def ReadHuntObject(self, hunt_id): """Reads a hunt object from the database.""" try: return self._DeepCopy(self.hunts[hunt_id]) except KeyError: raise db.UnknownHuntError(hunt_id)
[ "def", "ReadHuntObject", "(", "self", ",", "hunt_id", ")", ":", "try", ":", "return", "self", ".", "_DeepCopy", "(", "self", ".", "hunts", "[", "hunt_id", "]", ")", "except", "KeyError", ":", "raise", "db", ".", "UnknownHuntError", "(", "hunt_id", ")" ]
33
0.014778
def create(graph, reset_probability=0.15, threshold=1e-2, max_iterations=20, _single_precision=False, _distributed='auto', verbose=True): """ Compute the PageRank for each vertex in the graph. Return a model object with total PageRank as well as the Pag...
[ "def", "create", "(", "graph", ",", "reset_probability", "=", "0.15", ",", "threshold", "=", "1e-2", ",", "max_iterations", "=", "20", ",", "_single_precision", "=", "False", ",", "_distributed", "=", "'auto'", ",", "verbose", "=", "True", ")", ":", "from"...
31.022989
0.000718
def source_range_tuple(start, end, nr_var_dict): """ Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing tuples of the start and end index for each source variable type. """ starts = np.array([0 for nr_var in SOURCE...
[ "def", "source_range_tuple", "(", "start", ",", "end", ",", "nr_var_dict", ")", ":", "starts", "=", "np", ".", "array", "(", "[", "0", "for", "nr_var", "in", "SOURCE_VAR_TYPES", ".", "itervalues", "(", ")", "]", ")", "ends", "=", "np", ".", "array", ...
34.341463
0.002072
def ambiguous_identifier(logical_line, tokens): r"""Never use the characters 'l', 'O', or 'I' as variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead. Okay: L = 0 Okay: o = 123 Okay: i = 42 E741: l = ...
[ "def", "ambiguous_identifier", "(", "logical_line", ",", "tokens", ")", ":", "idents_to_avoid", "=", "(", "'l'", ",", "'O'", ",", "'I'", ")", "prev_type", ",", "prev_text", ",", "prev_start", ",", "prev_end", ",", "__", "=", "tokens", "[", "0", "]", "for...
35.7
0.000545
def _make_kl_divergence_fn( distribution_b, use_exact_kl=False, test_points_reduce_axis=(), # `None` == "all"; () == "none". test_points_fn=tf.convert_to_tensor, weight=None): """Creates a callable computing `KL[a,b]` from `a`, a `tfd.Distribution`.""" if use_exact_kl is None: kl_divergenc...
[ "def", "_make_kl_divergence_fn", "(", "distribution_b", ",", "use_exact_kl", "=", "False", ",", "test_points_reduce_axis", "=", "(", ")", ",", "# `None` == \"all\"; () == \"none\".", "test_points_fn", "=", "tf", ".", "convert_to_tensor", ",", "weight", "=", "None", ")...
47.097561
0.012684
def must_contain(self, value, q, strict=False): """if value must contain q""" if value is not None: if value.find(q) != -1: return self.shout('Value %r does not contain %r', strict, value, q)
[ "def", "must_contain", "(", "self", ",", "value", ",", "q", ",", "strict", "=", "False", ")", ":", "if", "value", "is", "not", "None", ":", "if", "value", ".", "find", "(", "q", ")", "!=", "-", "1", ":", "return", "self", ".", "shout", "(", "'V...
39.666667
0.00823
def update_from_shiftfile(shiftfile,wcsname=None,force=False): """ Update headers of all images specified in shiftfile with shifts from shiftfile. Parameters ---------- shiftfile : str Filename of shiftfile. wcsname : str Label to give to new WCS solution being created by t...
[ "def", "update_from_shiftfile", "(", "shiftfile", ",", "wcsname", "=", "None", ",", "force", "=", "False", ")", ":", "f", "=", "open", "(", "fileutil", ".", "osfn", "(", "shiftfile", ")", ")", "shift_lines", "=", "[", "x", ".", "strip", "(", ")", "fo...
35.052632
0.017527
def cross_join(*tables, **kwargs): """ Perform a cross join (cartesian product) amongst a list of tables, with optional set of prefixes to apply to overlapping column names Parameters ---------- tables : ibis.expr.types.TableExpr Returns ------- joined : TableExpr Examples ...
[ "def", "cross_join", "(", "*", "tables", ",", "*", "*", "kwargs", ")", ":", "# TODO(phillipc): Implement prefix keyword argument", "op", "=", "ops", ".", "CrossJoin", "(", "*", "tables", ",", "*", "*", "kwargs", ")", "return", "op", ".", "to_expr", "(", ")...
21.705882
0.000648
def _add_freq_options(config, opts, var2vcf_opts): """ Setting -f option for vardict and var2vcf_valid Prioritizing settings in resources/vardict/options, then algorithm/min_allele_fraction: min_allele_fraction "-f" in opts var2vcfopts -> vardict -f var2vcf -f yes ...
[ "def", "_add_freq_options", "(", "config", ",", "opts", ",", "var2vcf_opts", ")", ":", "if", "\"-f\"", "not", "in", "opts", ":", "freq", "=", "float", "(", "utils", ".", "get_in", "(", "config", ",", "(", "\"algorithm\"", ",", "\"min_allele_fraction\"", ")...
70.555556
0.009324