text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def encode(epochs, iso_8601=True): # @NoSelf """ Encodes the epoch(s) into UTC string(s). For CDF_EPOCH: The input should be either a float or list of floats (in numpy, a np.float64 or a np.ndarray of np.float64) Each epoch is encoded, by default...
[ "def", "encode", "(", "epochs", ",", "iso_8601", "=", "True", ")", ":", "# @NoSelf", "if", "(", "isinstance", "(", "epochs", ",", "int", ")", "or", "isinstance", "(", "epochs", ",", "np", ".", "int64", ")", ")", ":", "return", "CDFepoch", ".", "encod...
49.276596
0.001693
def ekf_ext_encode(self, timestamp, Windspeed, WindDir, WindZ, Airspeed, beta, alpha): ''' Extended EKF state estimates for ASLUAVs timestamp : Time since system start [us] (uint64_t) Windspeed : Magnitude of wind velocity ...
[ "def", "ekf_ext_encode", "(", "self", ",", "timestamp", ",", "Windspeed", ",", "WindDir", ",", "WindZ", ",", "Airspeed", ",", "beta", ",", "alpha", ")", ":", "return", "MAVLink_ekf_ext_message", "(", "timestamp", ",", "Windspeed", ",", "WindDir", ",", "WindZ...
64.214286
0.009868
def create_session(target='', timeout_sec=10): '''Create an intractive TensorFlow session. Helper function that creates TF session that uses growing GPU memory allocation and opration timeout. 'allow_growth' flag prevents TF from allocating the whole GPU memory an once, which is useful when having multiple p...
[ "def", "create_session", "(", "target", "=", "''", ",", "timeout_sec", "=", "10", ")", ":", "graph", "=", "tf", ".", "Graph", "(", ")", "config", "=", "tf", ".", "ConfigProto", "(", ")", "config", ".", "gpu_options", ".", "allow_growth", "=", "True", ...
43.923077
0.012007
def persist_experiment(experiment): """ Persist this experiment in the benchbuild database. Args: experiment: The experiment we want to persist. """ from benchbuild.utils.schema import Experiment, Session session = Session() cfg_exp = experiment.id LOG.debug("Using experiment ...
[ "def", "persist_experiment", "(", "experiment", ")", ":", "from", "benchbuild", ".", "utils", ".", "schema", "import", "Experiment", ",", "Session", "session", "=", "Session", "(", ")", "cfg_exp", "=", "experiment", ".", "id", "LOG", ".", "debug", "(", "\"...
25.571429
0.001076
def get_kbs_info(kbtype="", searchkbname=""): """A convenience method. :param kbtype: type of kb -- get only kb's of this type :param searchkbname: get only kb's where this sting appears in the name """ # query + order by query = models.KnwKB.query.order_by( models.KnwKB.name) # fil...
[ "def", "get_kbs_info", "(", "kbtype", "=", "\"\"", ",", "searchkbname", "=", "\"\"", ")", ":", "# query + order by", "query", "=", "models", ".", "KnwKB", ".", "query", ".", "order_by", "(", "models", ".", "KnwKB", ".", "name", ")", "# filters", "if", "k...
30.875
0.001965
def _start_monitoring(self): """ Internal method that monitors the directory for changes """ # Grab all the timestamp info before = self._file_timestamp_info(self.path) while True: gevent.sleep(1) after = self._file_timestamp_info(self.path) ...
[ "def", "_start_monitoring", "(", "self", ")", ":", "# Grab all the timestamp info", "before", "=", "self", ".", "_file_timestamp_info", "(", "self", ".", "path", ")", "while", "True", ":", "gevent", ".", "sleep", "(", "1", ")", "after", "=", "self", ".", "...
33.407407
0.009698
def _parse_processor_embedded_health(self, data): """Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: processor details like cpu arch and number of cpus. """ processor = self.get_value_as_list((data['...
[ "def", "_parse_processor_embedded_health", "(", "self", ",", "data", ")", ":", "processor", "=", "self", ".", "get_value_as_list", "(", "(", "data", "[", "'GET_EMBEDDED_HEALTH_DATA'", "]", "[", "'PROCESSORS'", "]", ")", ",", "'PROCESSOR'", ")", "if", "processor"...
45.366667
0.001439
def find_longest_match(self, alo, ahi, blo, bhi): """Find longest matching block in a[alo:ahi] and b[blo:bhi]. If isjunk is not defined: Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where alo <= i <= i+k <= ahi blo <= j <= j+k <= bhi and for all (i',j...
[ "def", "find_longest_match", "(", "self", ",", "alo", ",", "ahi", ",", "blo", ",", "bhi", ")", ":", "# CAUTION: stripping common prefix or suffix would be incorrect.", "# E.g.,", "# ab", "# acab", "# Longest matching block is \"ab\", but if common prefix is", "# stripped...
44.706422
0.002008
def get_datasets(self, mart='ENSEMBL_MART_ENSEMBL'): """Get available datasets from mart you've selected""" datasets = self.datasets(mart, raw=True) return pd.read_csv(StringIO(datasets), header=None, usecols=[1, 2], names = ["Name", "Description"],sep="\t")
[ "def", "get_datasets", "(", "self", ",", "mart", "=", "'ENSEMBL_MART_ENSEMBL'", ")", ":", "datasets", "=", "self", ".", "datasets", "(", "mart", ",", "raw", "=", "True", ")", "return", "pd", ".", "read_csv", "(", "StringIO", "(", "datasets", ")", ",", ...
61.2
0.019355
def enter_command_mode(self): """ Go into command mode. """ self.application.layout.focus(self.command_buffer) self.application.vi_state.input_mode = InputMode.INSERT self.previewer.save()
[ "def", "enter_command_mode", "(", "self", ")", ":", "self", ".", "application", ".", "layout", ".", "focus", "(", "self", ".", "command_buffer", ")", "self", ".", "application", ".", "vi_state", ".", "input_mode", "=", "InputMode", ".", "INSERT", "self", "...
28.75
0.008439
def _get_signature_object(func, as_instance, eat_self): """ Given an arbitrary, possibly callable object, try to create a suitable signature object. Return a (reduced func, signature) tuple, or None. """ if isinstance(func, ClassTypes) and not as_instance: # If it's a type and should be ...
[ "def", "_get_signature_object", "(", "func", ",", "as_instance", ",", "eat_self", ")", ":", "if", "isinstance", "(", "func", ",", "ClassTypes", ")", "and", "not", "as_instance", ":", "# If it's a type and should be modelled as a type, use __init__.", "try", ":", "func...
33.225806
0.000943
def display_workflows(prefix, **kwargs): """Display workflows in a table. This generates SVG files. Use this in a Jupyter notebook and ship the images :param prefix: name prefix for svg files generated. :param kwargs: keyword arguments containing a workflow each. """ from IPython.display import...
[ "def", "display_workflows", "(", "prefix", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "Markdown", "def", "create_svg", "(", "name", ",", "workflow", ")", ":", "\"\"\"Create an SVG file with rendered graph from a...
40.827586
0.000825
def get_all_package_releases(self, package_name: str) -> Iterable[Tuple[str, str]]: """ Returns a tuple of release data (version, manifest_ur) for every release of the given package name available on the current registry. """ validate_package_name(package_name) self._vali...
[ "def", "get_all_package_releases", "(", "self", ",", "package_name", ":", "str", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "validate_package_name", "(", "package_name", ")", "self", ".", "_validate_set_registry", "(", ")", "...
51.272727
0.008711
def uninstall(packages, purge=False, options=None): """ Remove one or more packages. If *purge* is ``True``, the package configuration files will be removed from the system. Extra *options* may be passed to ``apt-get`` if necessary. """ manager = MANAGER command = "purge" if purge else...
[ "def", "uninstall", "(", "packages", ",", "purge", "=", "False", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "command", "=", "\"purge\"", "if", "purge", "else", "\"remove\"", "if", "options", "is", "None", ":", "options", "=", "[", ...
32.421053
0.001577
def check_param(param, param_name, dtype, constraint=None, iterable=True, max_depth=2): """ checks the dtype of a parameter, and whether it satisfies a numerical contraint Parameters --------- param : object param_name : str, name of the parameter dtype : str, desired dt...
[ "def", "check_param", "(", "param", ",", "param_name", ",", "dtype", ",", "constraint", "=", "None", ",", "iterable", "=", "True", ",", "max_depth", "=", "2", ")", ":", "msg", "=", "[", "]", "msg", ".", "append", "(", "param_name", "+", "\" must be \""...
30.833333
0.002095
def reconnectPorts(root: LNode, srcPort: LPort, oldSplits: List[Tuple[LNode, LEdge]], newSplitNode: LNode): """ :ivar root: top LNode instance in which are nodes and links stored :ivar srcPort: for SLICE it is port which is connected to input of SLICE node for C...
[ "def", "reconnectPorts", "(", "root", ":", "LNode", ",", "srcPort", ":", "LPort", ",", "oldSplits", ":", "List", "[", "Tuple", "[", "LNode", ",", "LEdge", "]", "]", ",", "newSplitNode", ":", "LNode", ")", ":", "# sort oldSplit nodes because they are not in sam...
38.347826
0.001105
def manage_event(self, event) -> None: """Received new metadata. Operation initialized means new event, also happens if reconnecting. Operation changed updates existing events state. """ name = EVENT_NAME.format( topic=event[EVENT_TOPIC], source=event.get(EVENT_SOURC...
[ "def", "manage_event", "(", "self", ",", "event", ")", "->", "None", ":", "name", "=", "EVENT_NAME", ".", "format", "(", "topic", "=", "event", "[", "EVENT_TOPIC", "]", ",", "source", "=", "event", ".", "get", "(", "EVENT_SOURCE_IDX", ")", ")", "if", ...
39.47619
0.002356
def IsSocket(self): """Determines if the file entry is a socket. Returns: bool: True if the file entry is a socket. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entr...
[ "def", "IsSocket", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type",...
32.181818
0.008242
def set_phases(self, literals=[]): """ Sets polarities of a given list of variables. """ if self.glucose: pysolvers.glucose41_setphases(self.glucose, literals)
[ "def", "set_phases", "(", "self", ",", "literals", "=", "[", "]", ")", ":", "if", "self", ".", "glucose", ":", "pysolvers", ".", "glucose41_setphases", "(", "self", ".", "glucose", ",", "literals", ")" ]
28.857143
0.009615
def loadgrants(source=None, setspec=None, all_grants=False): """Harvest grants from OpenAIRE. :param source: Load the grants from a local sqlite db (offline). The value of the parameter should be a path to the local file. :type source: str :param setspec: Harvest specific set through OAI-PMH ...
[ "def", "loadgrants", "(", "source", "=", "None", ",", "setspec", "=", "None", ",", "all_grants", "=", "False", ")", ":", "assert", "all_grants", "or", "setspec", "or", "source", ",", "\"Either '--all', '--setspec' or '--source' is required parameter.\"", "if", "all_...
42.451613
0.000743
def restart_service(service_name, minimum_running_time=None): ''' Restart OpenStack service immediately, or only if it's running longer than specified value CLI Example: .. code-block:: bash salt '*' openstack_mng.restart_service neutron salt '*' openstack_mng.restart_service neut...
[ "def", "restart_service", "(", "service_name", ",", "minimum_running_time", "=", "None", ")", ":", "if", "minimum_running_time", ":", "ret_code", "=", "False", "# get system services list for interesting openstack service", "services", "=", "__salt__", "[", "'cmd.run'", "...
37.025
0.001974
def groups(self) -> Set[str]: """The set of option-groups created by ``define``. .. versionadded:: 3.1 """ return set(opt.group_name for opt in self._options.values())
[ "def", "groups", "(", "self", ")", "->", "Set", "[", "str", "]", ":", "return", "set", "(", "opt", ".", "group_name", "for", "opt", "in", "self", ".", "_options", ".", "values", "(", ")", ")" ]
32.5
0.01
def clean(self): ''' Verify that the user and staffMember are not mismatched. Location can only be specified if user and staffMember are not. ''' if self.staffMember and self.staffMember.userAccount and \ self.user and not self.staffMember.userAccount == self.user: ...
[ "def", "clean", "(", "self", ")", ":", "if", "self", ".", "staffMember", "and", "self", ".", "staffMember", ".", "userAccount", "and", "self", ".", "user", "and", "not", "self", ".", "staffMember", ".", "userAccount", "==", "self", ".", "user", ":", "r...
47.916667
0.008532
def qnwlogn(n, mu=None, sig2=None): """ Computes nodes and weights for multivariate lognormal distribution Parameters ---------- n : int or array_like(float) A length-d iterable of the number of nodes in each dimension mu : scalar or array_like(float), optional(default=zeros(d)) ...
[ "def", "qnwlogn", "(", "n", ",", "mu", "=", "None", ",", "sig2", "=", "None", ")", ":", "nodes", ",", "weights", "=", "qnwnorm", "(", "n", ",", "mu", ",", "sig2", ")", "return", "np", ".", "exp", "(", "nodes", ")", ",", "weights" ]
28.512821
0.00087
def addLogEntry(self, entry, save=True): """This is called when a new log entry is created""" # create log directory if it doesn't exist # error will be thrown if this is not possible _busy = Purr.BusyIndicator() self._initIndexDir() # discard temporary watchers -- these ...
[ "def", "addLogEntry", "(", "self", ",", "entry", ",", "save", "=", "True", ")", ":", "# create log directory if it doesn't exist", "# error will be thrown if this is not possible", "_busy", "=", "Purr", ".", "BusyIndicator", "(", ")", "self", ".", "_initIndexDir", "("...
43.181818
0.002059
def watch(self, filepath, func=None, delay=None): """Add the given filepath for watcher list. Once you have intialized a server, watch file changes before serve the server:: server.watch('static/*.stylus', 'make static') def alert(): print('foo') ...
[ "def", "watch", "(", "self", ",", "filepath", ",", "func", "=", "None", ",", "delay", "=", "None", ")", ":", "if", "isinstance", "(", "func", ",", "string_types", ")", ":", "func", "=", "shell", "(", "func", ")", "self", ".", "watcher", ".", "watch...
40.28
0.00194
def items(iterable): """ Iterates over the items of a sequence. If the sequence supports the dictionary protocol (iteritems/items) then we use that. Otherwise we use the enumerate built-in function. """ if hasattr(iterable, 'iteritems'): return (p for p in iterable.iteritems()) e...
[ "def", "items", "(", "iterable", ")", ":", "if", "hasattr", "(", "iterable", ",", "'iteritems'", ")", ":", "return", "(", "p", "for", "p", "in", "iterable", ".", "iteritems", "(", ")", ")", "elif", "hasattr", "(", "iterable", ",", "'items'", ")", ":"...
36.916667
0.002203
def extract_calc_id_datadir(filename, datadir=None): """ Extract the calculation ID from the given filename or integer: >>> extract_calc_id_datadir('/mnt/ssd/oqdata/calc_25.hdf5') (25, '/mnt/ssd/oqdata') >>> extract_calc_id_datadir('/mnt/ssd/oqdata/wrong_name.hdf5') Traceback (most recent call ...
[ "def", "extract_calc_id_datadir", "(", "filename", ",", "datadir", "=", "None", ")", ":", "datadir", "=", "datadir", "or", "get_datadir", "(", ")", "try", ":", "calc_id", "=", "int", "(", "filename", ")", "except", "ValueError", ":", "filename", "=", "os",...
37
0.001198
def install_requirements_command(requirements_path): '''install requirements.txt''' cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt' #TODO refactor python logic if sys.platform == "win32": cmds = cmds.format('python') else: cmds = cmds.format('py...
[ "def", "install_requirements_command", "(", "requirements_path", ")", ":", "cmds", "=", "'cd '", "+", "requirements_path", "+", "' && {0} -m pip install --user -r requirements.txt'", "#TODO refactor python logic", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "cmds"...
38.444444
0.008475
def _edges2conns(G, edge_data=False): """Create a mapping from graph edges to agent connections to be created. :param G: NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each node. :param bool edge_data: If ``True``, stores also edge data to the returned dictionary....
[ "def", "_edges2conns", "(", "G", ",", "edge_data", "=", "False", ")", ":", "cm", "=", "{", "}", "for", "n", "in", "G", ".", "nodes", "(", "data", "=", "True", ")", ":", "if", "edge_data", ":", "cm", "[", "n", "[", "1", "]", "[", "'addr'", "]"...
33.36
0.001166
def _memoize(self, name, getter, *args, **kwargs): """ Cache a stable expensive-to-get item value for later (optimized) retrieval. """ field = "custom_m_" + name cached = self.fetch(field) if cached: value = cached else: value = getter(*args, **kwa...
[ "def", "_memoize", "(", "self", ",", "name", ",", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "field", "=", "\"custom_m_\"", "+", "name", "cached", "=", "self", ".", "fetch", "(", "field", ")", "if", "cached", ":", "value", "=", ...
39.583333
0.00823
def _install_eslint(self, bootstrap_dir): """Install the ESLint distribution. :rtype: string """ with pushd(bootstrap_dir): result, install_command = self.install_module( package_manager=self.node_distribution.get_package_manager(package_manager=PACKAGE_MANAGER_YARNPKG), workunit_...
[ "def", "_install_eslint", "(", "self", ",", "bootstrap_dir", ")", ":", "with", "pushd", "(", "bootstrap_dir", ")", ":", "result", ",", "install_command", "=", "self", ".", "install_module", "(", "package_manager", "=", "self", ".", "node_distribution", ".", "g...
42.1875
0.008696
def pairs(args): """ %prog pairs pairsfile <fastbfile|fastqfile> Parse ALLPATHS pairs file, and write pairs IDs and single read IDs in respective ids files: e.g. `lib1.pairs.fastq`, `lib2.pairs.fastq`, and single `frags.fastq` (with single reads from lib1/2). """ from jcvi.assembly.preproce...
[ "def", "pairs", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "preprocess", "import", "run_FastbAndQualb2Fastq", "p", "=", "OptionParser", "(", "pairs", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--header\"", ",", "default", "=", "...
34.341463
0.001381
def postponed_from_when(self): """ A string describing when the event was postponed from (in the local time zone). """ what = self.what if what: return _("{what} from {when}").format(what=what, when=self.cancellationpa...
[ "def", "postponed_from_when", "(", "self", ")", ":", "what", "=", "self", ".", "what", "if", "what", ":", "return", "_", "(", "\"{what} from {when}\"", ")", ".", "format", "(", "what", "=", "what", ",", "when", "=", "self", ".", "cancellationpage", ".", ...
40.125
0.012195
def register_defaults(self): """Register :class:`~gears.processors.DirectivesProcessor` as a preprocessor for `text/css` and `application/javascript` MIME types. """ self.register('text/css', DirectivesProcessor.as_handler()) self.register('application/javascript', DirectivesProc...
[ "def", "register_defaults", "(", "self", ")", ":", "self", ".", "register", "(", "'text/css'", ",", "DirectivesProcessor", ".", "as_handler", "(", ")", ")", "self", ".", "register", "(", "'application/javascript'", ",", "DirectivesProcessor", ".", "as_handler", ...
55.666667
0.00885
def check_unknown_attachment_in_space(confluence, space_key): """ Detect errors in space :param confluence: :param space_key: :return: """ page_ids = get_all_pages_ids(confluence, space_key) print("Start review pages {} in {}".format(len(page_ids), space_key)) for page_id in...
[ "def", "check_unknown_attachment_in_space", "(", "confluence", ",", "space_key", ")", ":", "page_ids", "=", "get_all_pages_ids", "(", "confluence", ",", "space_key", ")", "print", "(", "\"Start review pages {} in {}\"", ".", "format", "(", "len", "(", "page_ids", ")...
33.461538
0.002237
def _context_build(self, pending=False): """ Create a context dict from standard task configuration. The context is constructed in a standard way and is passed to str.format() on configuration. The context consists of the entire os.environ, the config 'defines', and a set of pre...
[ "def", "_context_build", "(", "self", ",", "pending", "=", "False", ")", ":", "log", "=", "self", ".", "_params", ".", "get", "(", "'log'", ",", "self", ".", "_discard", ")", "log", ".", "debug", "(", "\"called with pending=%s\"", ",", "pending", ")", ...
37.745455
0.002347
def installed(name, default=False, user=None): ''' Verify that the specified python is installed with pyenv. pyenv is installed if necessary. name The version of python to install default : False Whether to make this python the default. user: None The user to run pyenv...
[ "def", "installed", "(", "name", ",", "default", "=", "False", ",", "user", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", "nam...
27.666667
0.00097
def _set_roi_mask(self, roi_mask): """Sets a new ROI mask.""" if isinstance(roi_mask, np.ndarray): # not (roi_mask is None or roi_mask=='auto'): self._verify_shape_compatibility(roi_mask, 'ROI set') self.roi_mask = roi_mask self.roi_list = np....
[ "def", "_set_roi_mask", "(", "self", ",", "roi_mask", ")", ":", "if", "isinstance", "(", "roi_mask", ",", "np", ".", "ndarray", ")", ":", "# not (roi_mask is None or roi_mask=='auto'):", "self", ".", "_verify_shape_compatibility", "(", "roi_mask", ",", "'ROI set'", ...
41.615385
0.009042
def array_2d_from_array_1d(self, array_1d): """ Map a 1D array the same dimension as the grid to its original masked 2D array. Parameters ----------- array_1d : ndarray The 1D array which is mapped to its masked 2D array. """ return mapping_util.map_masked_1d...
[ "def", "array_2d_from_array_1d", "(", "self", ",", "array_1d", ")", ":", "return", "mapping_util", ".", "map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two", "(", "array_1d", "=", "array_1d", ",", "shape", "=", "self", ".", "mask", ".", "shape", ",", ...
46.8
0.010482
def patch_statusreporter(): """Monkey patch robotframework to do postmortem debugging """ from robot.running.statusreporter import StatusReporter orig_exit = StatusReporter.__exit__ def __exit__(self, exc_type, exc_val, exc_tb): if exc_val and isinstance(exc_val, Exception): se...
[ "def", "patch_statusreporter", "(", ")", ":", "from", "robot", ".", "running", ".", "statusreporter", "import", "StatusReporter", "orig_exit", "=", "StatusReporter", ".", "__exit__", "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_val", ",", "exc_tb",...
32.769231
0.002283
def ticket_field_options(self, field_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_fields#list-ticket-field-options" api_path = "/api/v2/ticket_fields/{field_id}/options.json" api_path = api_path.format(field_id=field_id) return self.call(api_path, **kwargs)
[ "def", "ticket_field_options", "(", "self", ",", "field_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/ticket_fields/{field_id}/options.json\"", "api_path", "=", "api_path", ".", "format", "(", "field_id", "=", "field_id", ")", "return", "self...
62.4
0.009494
def show_clusters(sample, clusters, centers, initial_centers = None, **kwargs): """! @brief Display K-Means clustering results. @param[in] sample (list): Dataset that was used for clustering. @param[in] clusters (array_like): Clusters that were allocated by the algorithm. ...
[ "def", "show_clusters", "(", "sample", ",", "clusters", ",", "centers", ",", "initial_centers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "visualizer", "=", "cluster_visualizer", "(", ")", "visualizer", ".", "append_clusters", "(", "clusters", ",", "sa...
49.526316
0.013549
def get_template_by_name(name,**kwargs): """ Get a specific resource template, by name. """ try: tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one() return tmpl_i except NoResultFoun...
[ "def", "get_template_by_name", "(", "name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "tmpl_i", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "filter", "(", "Template", ".", "name", "==", "name", ")", ".", "options", "(",...
43.9
0.011161
def t_INITIAL_asm_sharp(self, t): r'[ \t]*\#' # Only matches if at beginning of line and "#" if self.find_column(t) == 1: t.lexer.push_state('prepro') # Start preprocessor self.expectingDirective = True
[ "def", "t_INITIAL_asm_sharp", "(", "self", ",", "t", ")", ":", "# Only matches if at beginning of line and \"#\"", "if", "self", ".", "find_column", "(", "t", ")", "==", "1", ":", "t", ".", "lexer", ".", "push_state", "(", "'prepro'", ")", "# Start preprocessor"...
48
0.008197
def migrate_codec(config_old, config_new): '''Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection` ''' assert mongodict.__version__ i...
[ "def", "migrate_codec", "(", "config_old", ",", "config_new", ")", ":", "assert", "mongodict", ".", "__version__", "in", "[", "(", "0", ",", "3", ",", "0", ")", ",", "(", "0", ",", "3", ",", "1", ")", "]", "connection", "=", "pymongo", ".", "Connec...
40
0.001953
def simple_lmm(snps,pheno,K=None,covs=None, test='lrt',NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False): """ Univariate fixed effects linear mixed model test for all SNPs Args: snps: [N x S] SP.array of S SNPs for N individuals pheno: [N x 1] SP.array of 1 phenotype for N...
[ "def", "simple_lmm", "(", "snps", ",", "pheno", ",", "K", "=", "None", ",", "covs", "=", "None", ",", "test", "=", "'lrt'", ",", "NumIntervalsDelta0", "=", "100", ",", "NumIntervalsDeltaAlt", "=", "0", ",", "searchDelta", "=", "False", ")", ":", "t0", ...
38.2
0.011912
def fromxml(node): """Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = ElementTree.parse(Stri...
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "ElementTree", ".", "parse", "(", "StringIO", "(", "node", ")", ")", ".", "get...
50.288889
0.009536
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): """ Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: i...
[ "def", "conv_output_length", "(", "input_length", ",", "filter_size", ",", "border_mode", ",", "stride", ",", "dilation", "=", "1", ")", ":", "if", "input_length", "is", "None", ":", "return", "None", "assert", "border_mode", "in", "{", "'same'", ",", "'vali...
44.619048
0.001045
def _get_preset_id(package, size): """Get the preset id given the keyName of the preset.""" for preset in package['activePresets'] + package['accountRestrictedActivePresets']: if preset['keyName'] == size or preset['id'] == size: return preset['id'] raise SoftLayer.SoftLayerError("Could...
[ "def", "_get_preset_id", "(", "package", ",", "size", ")", ":", "for", "preset", "in", "package", "[", "'activePresets'", "]", "+", "package", "[", "'accountRestrictedActivePresets'", "]", ":", "if", "preset", "[", "'keyName'", "]", "==", "size", "or", "pres...
50.428571
0.008357
def append_some(ol,*eles,**kwargs): ''' from elist.elist import * ol = [1,2,3,4] id(ol) append_some(ol,5,6,7,8,mode="original") ol id(ol) #### ol = [1,2,3,4] id(ol) new = append_some(ol,5,6,7,8) new id(new) ''' i...
[ "def", "append_some", "(", "ol", ",", "*", "eles", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'mode'", "in", "kwargs", ")", ":", "mode", "=", "kwargs", "[", "\"mode\"", "]", "else", ":", "mode", "=", "\"new\"", "return", "(", "extend", "(", "...
21.3
0.011236
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vizio media player platform.""" host = config.get(CONF_HOST) token = config.get(CONF_ACCESS_TOKEN) name = config.get(CONF_NAME) volume_step = config.get(CONF_VOLUME_STEP) device_type = config.get(CONF_DEVICE_CLASS...
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "host", "=", "config", ".", "get", "(", "CONF_HOST", ")", "token", "=", "config", ".", "get", "(", "CONF_ACCESS_TOKEN", ")", "name", "...
49.52
0.000792
def read(self, timeout=None): ''' Read from the transport. If no data is available, should return None. The timeout is ignored as this returns only data that has already been buffered locally. ''' # NOTE: copying over this comment from Connection, because there is ...
[ "def", "read", "(", "self", ",", "timeout", "=", "None", ")", ":", "# NOTE: copying over this comment from Connection, because there is", "# knowledge captured here, even if the details are stale", "# Because of the timer callback to dataRead when we re-buffered,", "# there's a chance that...
47.933333
0.001363
def dl_pb_file(inputs): """ Download a file from physiobank. The input args are to be unpacked for the use of multiprocessing map, because python2 doesn't have starmap... """ basefile, subdir, db, dl_dir, keep_subdirs, overwrite = inputs # Full url of file url = posixpath.join(config...
[ "def", "dl_pb_file", "(", "inputs", ")", ":", "basefile", ",", "subdir", ",", "db", ",", "dl_dir", ",", "keep_subdirs", ",", "overwrite", "=", "inputs", "# Full url of file", "url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "d...
33.830189
0.001626
def auth_required(self): """ If any ancestor required an authentication, this node needs it too. """ if self._auth: return self._auth, self return self.__parent__.auth_required()
[ "def", "auth_required", "(", "self", ")", ":", "if", "self", ".", "_auth", ":", "return", "self", ".", "_auth", ",", "self", "return", "self", ".", "__parent__", ".", "auth_required", "(", ")" ]
32
0.008696
def get_signal_peaks_and_prominences(data): """ Get the signal peaks and peak prominences. :param data array: One-dimensional array. :return peaks array: The peaks of our signal. :return prominences array: The prominences of the peaks. """ peaks, _ = sig.find_peaks(...
[ "def", "get_signal_peaks_and_prominences", "(", "data", ")", ":", "peaks", ",", "_", "=", "sig", ".", "find_peaks", "(", "data", ")", "prominences", "=", "sig", ".", "peak_prominences", "(", "data", ",", "peaks", ")", "[", "0", "]", "return", "peaks", ",...
34
0.009547
def _get_swig_version(env, swig): """Run the SWIG command line tool to get and return the version number""" swig = env.subst(swig) pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'], stdin = 'devnull', stderr = 'devnull',...
[ "def", "_get_swig_version", "(", "env", ",", "swig", ")", ":", "swig", "=", "env", ".", "subst", "(", "swig", ")", "pipe", "=", "SCons", ".", "Action", ".", "_subproc", "(", "env", ",", "SCons", ".", "Util", ".", "CLVar", "(", "swig", ")", "+", "...
43.941176
0.018349
def daily(target_coll, source_coll, interp_days=32, interp_method='linear'): """Generate daily ETa collection from ETo and ETf collections Parameters ---------- target_coll : ee.ImageCollection Source images will be interpolated to each target image time_start. Target images should have...
[ "def", "daily", "(", "target_coll", ",", "source_coll", ",", "interp_days", "=", "32", ",", "interp_method", "=", "'linear'", ")", ":", "# # DEADBEEF - This module is assuming that the time band is already in", "# # the source collection.", "# # Uncomment the following to add a...
46.480263
0.001524
def create_tipo_acesso(self): """Get an instance of tipo_acesso services facade.""" return TipoAcesso( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_tipo_acesso", "(", "self", ")", ":", "return", "TipoAcesso", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
31.857143
0.008734
def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for docum...
[ "def", "comparison_operator_query", "(", "comparison_operator", ")", ":", "def", "_comparison_operator_query", "(", "expression", ")", ":", "\"\"\"Apply binary operator to expression.\"\"\"", "def", "_apply_comparison_operator", "(", "index", ",", "expression", "=", "expressi...
45.3125
0.001351
def print_boolean_net(self, out_file=None): """Return a Boolean network from the assembled graph. See https://github.com/ialbert/booleannet for details about the format used to encode the Boolean rules. Parameters ---------- out_file : Optional[str] A file n...
[ "def", "print_boolean_net", "(", "self", ",", "out_file", "=", "None", ")", ":", "init_str", "=", "''", "for", "node_key", "in", "self", ".", "graph", ".", "nodes", "(", ")", ":", "node_name", "=", "self", ".", "graph", ".", "node", "[", "node_key", ...
36.683333
0.000885
def get_explore_posts(self) -> Iterator[Post]: """Get Posts which are worthy of exploring suggested by Instagram. :return: Iterator over Posts of the user's suggested posts. """ data = self.context.get_json('explore/', {}) yield from (Post(self.context, node) ...
[ "def", "get_explore_posts", "(", "self", ")", "->", "Iterator", "[", "Post", "]", ":", "data", "=", "self", ".", "context", ".", "get_json", "(", "'explore/'", ",", "{", "}", ")", "yield", "from", "(", "Post", "(", "self", ".", "context", ",", "node"...
63.090909
0.008523
def sign_message(privkey_path, message, passphrase=None): ''' Use Crypto.Signature.PKCS1_v1_5 to sign a message. Returns the signature. ''' key = get_rsa_key(privkey_path, passphrase) log.debug('salt.crypt.sign_message: Signing message.') if HAS_M2: md = EVP.MessageDigest('sha1') ...
[ "def", "sign_message", "(", "privkey_path", ",", "message", ",", "passphrase", "=", "None", ")", ":", "key", "=", "get_rsa_key", "(", "privkey_path", ",", "passphrase", ")", "log", ".", "debug", "(", "'salt.crypt.sign_message: Signing message.'", ")", "if", "HAS...
38.857143
0.001795
def delete_collection_initializer_configuration(self, **kwargs): # noqa: E501 """delete_collection_initializer_configuration # noqa: E501 delete collection of InitializerConfiguration # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP r...
[ "def", "delete_collection_initializer_configuration", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", ...
166.137931
0.000413
def _yield_all(self, l): ''' Given a iterable like list or tuple the function yields each of its items with _yield ''' if l is not None: if type(l) in [list, tuple]: for f in l: for x in self._yield(f): yield x else: ...
[ "def", "_yield_all", "(", "self", ",", "l", ")", ":", "if", "l", "is", "not", "None", ":", "if", "type", "(", "l", ")", "in", "[", "list", ",", "tuple", "]", ":", "for", "f", "in", "l", ":", "for", "x", "in", "self", ".", "_yield", "(", "f"...
32.272727
0.013699
def create_random_population(num=100): """ create a list of people with randomly generated names and stats """ people = [] for _ in range(num): nme = 'blah' tax_min = random.randint(1,40)/100 tax_max = tax_min + random.randint(1,40)/100 tradition = random.randint(1,10...
[ "def", "create_random_population", "(", "num", "=", "100", ")", ":", "people", "=", "[", "]", "for", "_", "in", "range", "(", "num", ")", ":", "nme", "=", "'blah'", "tax_min", "=", "random", ".", "randint", "(", "1", ",", "40", ")", "/", "100", "...
33.75
0.018018
def point(self, clear_screen=True, x=10, y=10, point_color='black'): """ Draw a single pixel at (x, y) """ if clear_screen: self.clear() return self.draw.point((x, y), fill=point_color)
[ "def", "point", "(", "self", ",", "clear_screen", "=", "True", ",", "x", "=", "10", ",", "y", "=", "10", ",", "point_color", "=", "'black'", ")", ":", "if", "clear_screen", ":", "self", ".", "clear", "(", ")", "return", "self", ".", "draw", ".", ...
25.666667
0.008368
def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False): """ Add accessors to cls from the delegate class. Parameters ---------- cls : the class to add the methods/properties to delegate : the class to get methods/prope...
[ "def", "_add_delegate_accessors", "(", "cls", ",", "delegate", ",", "accessors", ",", "typ", ",", "overwrite", "=", "False", ")", ":", "def", "_create_delegator_property", "(", "name", ")", ":", "def", "_getter", "(", "self", ")", ":", "return", "self", "....
31.77551
0.001869
def create(self, data, **kwargs): """Create a new object. Args: data (dict): Parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If auth...
[ "def", "create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "CreateMixin", ".", "_check_missing_create_attrs", "(", "self", ",", "data", ")", "path", "=", "'%s/%s'", "%", "(", "self", ".", "path", ",", "data", ".", "pop", "(", "'iss...
42.166667
0.001932
def iteritems(self): """Return a iterable for (name, value) pairs of public attributes.""" for name, value in self.__dict__.iteritems(): if (not name) or name[0] == "_": continue yield name, value
[ "def", "iteritems", "(", "self", ")", ":", "for", "name", ",", "value", "in", "self", ".", "__dict__", ".", "iteritems", "(", ")", ":", "if", "(", "not", "name", ")", "or", "name", "[", "0", "]", "==", "\"_\"", ":", "continue", "yield", "name", "...
36.5
0.013393
def update_storage_policy(policy, policy_dict, service_instance=None): ''' Updates a storage policy. Supported capability types: scalar, set, range. policy Name of the policy to update. policy_dict Dictionary containing the changes to apply to the policy. (example in salt....
[ "def", "update_storage_policy", "(", "policy", ",", "policy_dict", ",", "service_instance", "=", "None", ")", ":", "log", ".", "trace", "(", "'updating storage policy, dict = %s'", ",", "policy_dict", ")", "profile_manager", "=", "salt", ".", "utils", ".", "pbm", ...
38.621622
0.000683
def has_change_permission(self, page, lang, method=None): """Return ``True`` if the current user has permission to change the page.""" # the user has always the right to look at a page content # if he doesn't try to modify it. if method != 'POST': return True ...
[ "def", "has_change_permission", "(", "self", ",", "page", ",", "lang", ",", "method", "=", "None", ")", ":", "# the user has always the right to look at a page content", "# if he doesn't try to modify it.", "if", "method", "!=", "'POST'", ":", "return", "True", "# right...
34.176471
0.001674
def get(self, name, default=_MISSING): """Get a metadata field.""" name = self._convert_name(name) if name not in self._fields: if default is _MISSING: default = self._default_value(name) return default if name in _UNICODEFIELDS: value ...
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "if", "name", "not", "in", "self", ".", "_fields", ":", "if", "default", "is", "_MISSING", ":", "default",...
33.607143
0.002066
def build(subparsers): """ Build source packages. The mp build program runs all of the resources listed in a Metatab file and produces one or more Metapack packages with those resources localized. It will always try to produce a Filesystem package, and may optionally produce Excel, Zip and CSV ...
[ "def", "build", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'build'", ",", "help", "=", "'Build derived packages'", ",", "description", "=", "build", ".", "__doc__", ",", "formatter_class", "=", "argparse", ".", "RawDescr...
38.344086
0.008748
def listAttachments(self, oid): """ list attachements for a given OBJECT ID """ url = self._url + "/%s/attachments" % oid params = { "f":"json" } return self._get(url, params, securityHandler=self._securityHandler, ...
[ "def", "listAttachments", "(", "self", ",", "oid", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/%s/attachments\"", "%", "oid", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "return", "self", ".", "_get", "(", "url", ",", "params", ",", "s...
39.7
0.014778
def _on_click(self): """Handles clicks and calls callback.""" if callable(self.__callback): self.__callback((self.bold, self.italic, self.underline, self.overstrike))
[ "def", "_on_click", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "__callback", ")", ":", "self", ".", "__callback", "(", "(", "self", ".", "bold", ",", "self", ".", "italic", ",", "self", ".", "underline", ",", "self", ".", "overstrike"...
47.75
0.015464
def get_ploidy(items, region=None): """Retrieve ploidy of a region, handling special cases. """ chrom = chromosome_special_cases(region[0] if isinstance(region, (list, tuple)) else None) ploidy = _configured_ploidy(items) sexes = _configured_genders(items) if...
[ "def", "get_ploidy", "(", "items", ",", "region", "=", "None", ")", ":", "chrom", "=", "chromosome_special_cases", "(", "region", "[", "0", "]", "if", "isinstance", "(", "region", ",", "(", "list", ",", "tuple", ")", ")", "else", "None", ")", "ploidy",...
42.916667
0.001899
def check_lazy_load_perceel(f): ''' Decorator function to lazy load a :class:`Perceel`. ''' def wrapper(self): perceel = self if (getattr(perceel, '_%s' % f.__name__, None) is None): log.debug( 'Lazy loading Perceel %s in Sectie %s in Afdeling %d', ...
[ "def", "check_lazy_load_perceel", "(", "f", ")", ":", "def", "wrapper", "(", "self", ")", ":", "perceel", "=", "self", "if", "(", "getattr", "(", "perceel", ",", "'_%s'", "%", "f", ".", "__name__", ",", "None", ")", "is", "None", ")", ":", "log", "...
30.769231
0.001212
def watch(ctx): """Automatically run build whenever a relevant file changes. """ watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', ...
[ "def", "watch", "(", "ctx", ")", ":", "watcher", "=", "Watcher", "(", "ctx", ")", "watcher", ".", "watch_directory", "(", "path", "=", "'{pkg.source_less}'", ",", "ext", "=", "'.less'", ",", "action", "=", "lambda", "e", ":", "build", "(", "ctx", ",", ...
29
0.001965
def set_exit_callback(self, callback: Callable[[int], None]) -> None: """Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libr...
[ "def", "set_exit_callback", "(", "self", ",", "callback", ":", "Callable", "[", "[", "int", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_exit_callback", "=", "callback", "Subprocess", ".", "initialize", "(", ")", "Subprocess", ".", "_wai...
43.238095
0.002155
def land_address(self): """ :example 세종특별자치시 어진동 507 """ pattern = self.random_element(self.land_address_formats) return self.generator.parse(pattern)
[ "def", "land_address", "(", "self", ")", ":", "pattern", "=", "self", ".", "random_element", "(", "self", ".", "land_address_formats", ")", "return", "self", ".", "generator", ".", "parse", "(", "pattern", ")" ]
30.833333
0.010526
def logstate(self): """Print a status message about the logger.""" if self.logfile is None: print 'Logging has not been activated.' else: state = self.log_active and 'active' or 'temporarily suspended' print 'Filename :',self.logfname print '...
[ "def", "logstate", "(", "self", ")", ":", "if", "self", ".", "logfile", "is", "None", ":", "print", "'Logging has not been activated.'", "else", ":", "state", "=", "self", ".", "log_active", "and", "'active'", "or", "'temporarily suspended'", "print", "'Filename...
45.25
0.01444
def as_dict(self): """Return all properties and values in a dictionary (includes private properties)""" return {config_name: getattr(self, config_name) for config_name, _ in self._iter_config_props()}
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "config_name", ":", "getattr", "(", "self", ",", "config_name", ")", "for", "config_name", ",", "_", "in", "self", ".", "_iter_config_props", "(", ")", "}" ]
57.25
0.012931
def plural(self): ''' Tries to scrape the plural version from vandale.nl. ''' element = self._first('NN') if element: if re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U): results = re.search('meervoud: ([\w|\s|\'|\-|,]+)', element, re.U).groups()[0].split(', ') results = [x.replace('ook ', '')...
[ "def", "plural", "(", "self", ")", ":", "element", "=", "self", ".", "_first", "(", "'NN'", ")", "if", "element", ":", "if", "re", ".", "search", "(", "'meervoud: ([\\w|\\s|\\'|\\-|,]+)'", ",", "element", ",", "re", ".", "U", ")", ":", "results", "=", ...
32.615385
0.045872
def add_basic_auth(dolt, username, password): """ Send basic auth username and password. Normally you can use httplib2.Http.add_credentials() to add username and password. However this has two disadvantages. 1. Some poorly implemented APIs require basic auth but don't send a "401 Authorizat...
[ "def", "add_basic_auth", "(", "dolt", ",", "username", ",", "password", ")", ":", "return", "dolt", ".", "with_headers", "(", "Authorization", "=", "'Basic %s'", "%", "base64", ".", "b64encode", "(", "'%s:%s'", "%", "(", "username", ",", "password", ")", "...
45.2
0.008667
def write_Text_into_file( text, old_file_name, out_dir, suffix='__split', verbose=True ): ''' Based on *old_file_name*, *suffix* and *out_dir*, constructs a new file name and writes *text* (in the ascii normalised JSON format) into the new file. ''' name = os.path.basename( old_file_name ) if ...
[ "def", "write_Text_into_file", "(", "text", ",", "old_file_name", ",", "out_dir", ",", "suffix", "=", "'__split'", ",", "verbose", "=", "True", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "old_file_name", ")", "if", "'.'", "in", "name...
44.578947
0.030058
def Read(self, length): """Read a block of data from the file.""" result = b"" # The total available size in the file length = int(length) length = min(length, self.size - self.offset) while length > 0: data = self._ReadPartial(length) if not data: break length -= le...
[ "def", "Read", "(", "self", ",", "length", ")", ":", "result", "=", "b\"\"", "# The total available size in the file", "length", "=", "int", "(", "length", ")", "length", "=", "min", "(", "length", ",", "self", ".", "size", "-", "self", ".", "offset", ")...
21.9375
0.013661
def _get_tbl_numpy_dtype(self, colnum, include_endianness=True): """ Get numpy type for the input column """ table_type = self._info['hdutype'] table_type_string = _hdu_type_map[table_type] try: ftype = self._info['colinfo'][colnum]['eqtype'] if ta...
[ "def", "_get_tbl_numpy_dtype", "(", "self", ",", "colnum", ",", "include_endianness", "=", "True", ")", ":", "table_type", "=", "self", ".", "_info", "[", "'hdutype'", "]", "table_type_string", "=", "_hdu_type_map", "[", "table_type", "]", "try", ":", "ftype",...
33.804878
0.001403
def save(self): """ Save the UFO.""" # handle glyphs that were muted for name in self.mutedGlyphsNames: if name not in self.font: continue if self.logger: self.logger.info("removing muted glyph %s", name) del self.font[name] # XXX ...
[ "def", "save", "(", "self", ")", ":", "# handle glyphs that were muted", "for", "name", "in", "self", ".", "mutedGlyphsNames", ":", "if", "name", "not", "in", "self", ".", "font", ":", "continue", "if", "self", ".", "logger", ":", "self", ".", "logger", ...
42.62069
0.002373
def acquire(self): """ Try to aquire the lock. """ if self.timeout is not None: sleep_intervals = int(self.timeout / self.sleep_time) else: sleep_intervals = float('inf') while not self.acquire_try_once() and sleep_intervals > 0: ...
[ "def", "acquire", "(", "self", ")", ":", "if", "self", ".", "timeout", "is", "not", "None", ":", "sleep_intervals", "=", "int", "(", "self", ".", "timeout", "/", "self", ".", "sleep_time", ")", "else", ":", "sleep_intervals", "=", "float", "(", "'inf'"...
32.6875
0.011152
def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) self._delete_entity()
[ "def", "locked_delete", "(", "self", ")", ":", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "delete", "(", "self", ".", "_key_name", ")", "self", ".", "_delete_entity", "(", ")" ]
24.142857
0.011429
def parse(url): ''' Parse a salt:// URL; return the path and a possible saltenv query. ''' if not url.startswith('salt://'): return url, None # urlparse will split on valid filename chars such as '?' and '&' resource = url.split('salt://', 1)[-1] if '?env=' in resource: # "...
[ "def", "parse", "(", "url", ")", ":", "if", "not", "url", ".", "startswith", "(", "'salt://'", ")", ":", "return", "url", ",", "None", "# urlparse will split on valid filename chars such as '?' and '&'", "resource", "=", "url", ".", "split", "(", "'salt://'", ",...
29.863636
0.001475
def GetEntries(dataList, title="Select", msg=""): """ Get entries of the list title: Window name mag: Label of the check button return data dictionary like: {'y': '5.0', 'x': '100', 'z': 'save'} """ root = tkinter.Tk() root.title(title) label = tkinter.Label(root, text=msg) ...
[ "def", "GetEntries", "(", "dataList", ",", "title", "=", "\"Select\"", ",", "msg", "=", "\"\"", ")", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "root", ".", "title", "(", "title", ")", "label", "=", "tkinter", ".", "Label", "(", "root", ",",...
22.058824
0.001277
def process_binding_statements(self): """Looks for Binding events in the graph and extracts them into INDRA statements. In particular, looks for a Binding event node with outgoing edges with relations Theme and Theme2 - the entities these edges point to are the two constituents ...
[ "def", "process_binding_statements", "(", "self", ")", ":", "G", "=", "self", ".", "G", "statements", "=", "[", "]", "binding_nodes", "=", "self", ".", "find_event_with_outgoing_edges", "(", "'Binding'", ",", "[", "'Theme'", ",", "'Theme2'", "]", ")", "for",...
40.464286
0.001724
def _ProcessUnknownMessages(message, encoded_message): """Store any remaining unknown fields as strings. ProtoRPC currently ignores unknown values for which no type can be determined (and logs a "No variant found" message). For the purposes of reserializing, this is quite harmful (since it throws away ...
[ "def", "_ProcessUnknownMessages", "(", "message", ",", "encoded_message", ")", ":", "if", "not", "encoded_message", ":", "return", "message", "decoded_message", "=", "json", ".", "loads", "(", "six", ".", "ensure_str", "(", "encoded_message", ")", ")", "message_...
42.555556
0.000851
def migrate(vm_, target, live=1, port=0, node=-1, ssl=None, change_home_server=0): ''' Migrates the virtual machine to another hypervisor CLI Example: .. code-block:: bash salt '*' virt.migrate <vm name> <target hypervisor> [live] [port] [node] [ssl] [change_home_server] Opti...
[ "def", "migrate", "(", "vm_", ",", "target", ",", "live", "=", "1", ",", "port", "=", "0", ",", "node", "=", "-", "1", ",", "ssl", "=", "None", ",", "change_home_server", "=", "0", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":...
25.974359
0.001903
def cli_default_perms(self, *args): """Show default permissions for all schemata""" for key, item in schemastore.items(): # self.log(item, pretty=True) if item['schema'].get('no_perms', False): self.log('Schema without permissions:', key) continue...
[ "def", "cli_default_perms", "(", "self", ",", "*", "args", ")", ":", "for", "key", ",", "item", "in", "schemastore", ".", "items", "(", ")", ":", "# self.log(item, pretty=True)", "if", "item", "[", "'schema'", "]", ".", "get", "(", "'no_perms'", ",", "Fa...
40.565217
0.002094
def slugs_configuration_camera_send(self, target, idOrder, order, force_mavlink1=False): ''' Control for camara. target : The system setting the commands (uint8_t) idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR ...
[ "def", "slugs_configuration_camera_send", "(", "self", ",", "target", ",", "idOrder", ",", "order", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "slugs_configuration_camera_encode", "(", "target", ",", "idOrder"...
58.1
0.011864
def encode_call(self, call): """ Replace callables with tokens to reduce object memory footprint. A callable token is an integer that denotes the order in which the callable was encountered by the encoder, i.e. the first callable encoded is assigned token 0, the second callable ...
[ "def", "encode_call", "(", "self", ",", "call", ")", ":", "# Callable name is None when callable is part of exclude list", "if", "call", "is", "None", ":", "return", "None", "itokens", "=", "call", ".", "split", "(", "self", ".", "_callables_separator", ")", "otok...
35.384615
0.002116
def path_complete(self, text: str, line: str, begidx: int, endidx: int, path_filter: Optional[Callable[[str], bool]] = None) -> List[str]: """Performs completion of local file system paths :param text: the string prefix we are attempting to match (all returned matches must begin w...
[ "def", "path_complete", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "path_filter", ":", "Optional", "[", "Callable", "[", "[", "str", "]", ",", "bool", "]", "]", "=", "...
41.307692
0.00248