text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def box_iter(self): """Get an iterator over all boxes in the Sudoku""" for i in utils.range_(self.order): for j in utils.range_(self.order): yield self.box(i * 3, j * 3)
[ "def", "box_iter", "(", "self", ")", ":", "for", "i", "in", "utils", ".", "range_", "(", "self", ".", "order", ")", ":", "for", "j", "in", "utils", ".", "range_", "(", "self", ".", "order", ")", ":", "yield", "self", ".", "box", "(", "i", "*", ...
41.8
0.00939
def update_model_in_repo_based_on_filename(self, model): """ Adds a model to the repo (not initially visible) Args: model: the model to be added. If the model has no filename, a name is invented Returns: the filename of the model added to the repo """ if m...
[ "def", "update_model_in_repo_based_on_filename", "(", "self", ",", "model", ")", ":", "if", "model", ".", "_tx_filename", "is", "None", ":", "for", "fn", "in", "self", ".", "all_models", ".", "filename_to_model", ":", "if", "self", ".", "all_models", ".", "f...
43.809524
0.002128
def _run_command(command, targets, options): # type: (str, List[str], List[str]) -> bool """Runs `command` + `targets` + `options` in a subprocess and returns a boolean determined by the process return code. >>> result = run_command('pylint', ['foo.py', 'some_module'], ['-E']) >>> result Tr...
[ "def", "_run_command", "(", "command", ",", "targets", ",", "options", ")", ":", "# type: (str, List[str], List[str]) -> bool", "print", "(", "'{0}: targets={1} options={2}'", ".", "format", "(", "command", ",", "targets", ",", "options", ")", ")", "cmd", "=", "["...
29.047619
0.001587
def convert_cifar10(directory, output_directory, output_filename='cifar10.hdf5'): """Converts the CIFAR-10 dataset to HDF5. Converts the CIFAR-10 dataset to an HDF5 dataset compatible with :class:`fuel.datasets.CIFAR10`. The converted dataset is saved as 'cifar10.hdf5'. It assu...
[ "def", "convert_cifar10", "(", "directory", ",", "output_directory", ",", "output_filename", "=", "'cifar10.hdf5'", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "output_filename", ")", "h5file", "=", "h5py", ".", ...
32.903614
0.000355
def process_message(message, notification): """ Function to process a JSON message delivered from Amazon """ # Confirm that there are 'notificationType' and 'mail' fields in our # message if not set(VITAL_MESSAGE_FIELDS) <= set(message): # At this point we're sure that it's Amazon sendin...
[ "def", "process_message", "(", "message", ",", "notification", ")", ":", "# Confirm that there are 'notificationType' and 'mail' fields in our", "# message", "if", "not", "set", "(", "VITAL_MESSAGE_FIELDS", ")", "<=", "set", "(", "message", ")", ":", "# At this point we'r...
44.333333
0.001052
def Uri(self): """ Constructs the connection URI from name, noSsl and port instance variables. """ return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[ (((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))]))
[ "def", "Uri", "(", "self", ")", ":", "return", "(", "\"%s://%s%s\"", "%", "(", "(", "\"https\"", ",", "\"http\"", ")", "[", "self", ".", "_noSsl", "==", "True", "]", ",", "self", ".", "_name", ",", "(", "\":\"", "+", "str", "(", "self", ".", "_po...
77.5
0.035144
def buy_product(self, product_pk): """ determina si el customer ha comprado un producto """ if self.invoice_sales.filter(lines_sales__product_final__pk=product_pk).exists() \ or self.ticket_sales.filter(lines_sales__product_final__pk=product_pk).exists(): retu...
[ "def", "buy_product", "(", "self", ",", "product_pk", ")", ":", "if", "self", ".", "invoice_sales", ".", "filter", "(", "lines_sales__product_final__pk", "=", "product_pk", ")", ".", "exists", "(", ")", "or", "self", ".", "ticket_sales", ".", "filter", "(", ...
39.777778
0.010929
def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line. """ parser = argparse.ArgumentParser(description='QTPyLib Reporting', ...
[ "def", "load_cli_args", "(", "self", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'QTPyLib Reporting'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "parser", ".", "add_argument", "(", ...
45.307692
0.002494
def get_position(self): """ 获取持仓 :return: """ xq_positions = self._get_position() balance = self.get_balance()[0] position_list = [] for pos in xq_positions: volume = pos["weight"] * balance["asset_balance"] / 100 position_list.appe...
[ "def", "get_position", "(", "self", ")", ":", "xq_positions", "=", "self", ".", "_get_position", "(", ")", "balance", "=", "self", ".", "get_balance", "(", ")", "[", "0", "]", "position_list", "=", "[", "]", "for", "pos", "in", "xq_positions", ":", "vo...
34.04
0.002286
def upgradedb(options): """ Add 'fake' data migrations for existing tables from legacy GeoNode versions """ version = options.get('version') if version in ['1.1', '1.2']: sh("python manage.py migrate maps 0001 --fake") sh("python manage.py migrate avatar 0001 --fake") elif versio...
[ "def", "upgradedb", "(", "options", ")", ":", "version", "=", "options", ".", "get", "(", "'version'", ")", "if", "version", "in", "[", "'1.1'", ",", "'1.2'", "]", ":", "sh", "(", "\"python manage.py migrate maps 0001 --fake\"", ")", "sh", "(", "\"python man...
37.916667
0.002146
def SensorShare(self, sensor_id, parameters): """ Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor...
[ "def", "SensorShare", "(", "self", ",", "sensor_id", ",", "parameters", ")", ":", "if", "not", "parameters", "[", "'user'", "]", "[", "'id'", "]", ":", "parameters", "[", "'user'", "]", ".", "pop", "(", "'id'", ")", "if", "not", "parameters", "[", "'...
35.857143
0.009056
def has_known_bases(klass, context=None): """Return true if all base classes of a class could be inferred.""" try: return klass._all_bases_known except AttributeError: pass for base in klass.bases: result = safe_infer(base, context=context) # TODO: check for A->B->A->B pa...
[ "def", "has_known_bases", "(", "klass", ",", "context", "=", "None", ")", ":", "try", ":", "return", "klass", ".", "_all_bases_known", "except", "AttributeError", ":", "pass", "for", "base", "in", "klass", ".", "bases", ":", "result", "=", "safe_infer", "(...
34.611111
0.001563
def _partition(iter_dims, data_sources): """ Partition data sources into 1. Dictionary of data sources associated with radio sources. 2. List of data sources to feed multiple times. 3. List of data sources to feed once. """ src_nr_vars = set(source_var_types().values()) iter_dims = set...
[ "def", "_partition", "(", "iter_dims", ",", "data_sources", ")", ":", "src_nr_vars", "=", "set", "(", "source_var_types", "(", ")", ".", "values", "(", ")", ")", "iter_dims", "=", "set", "(", "iter_dims", ")", "src_data_sources", "=", "collections", ".", "...
32.384615
0.001537
def _tag_ebs(self, conn, role): """ set tags, carrying the cluster name, instance role and instance id for the EBS storage """ tags = {'Name': 'spilo_' + self.cluster_name, 'Role': role, 'Instance': self.instance_id} volumes = conn.get_all_volumes(filters={'attachment.instance-id': self.instance...
[ "def", "_tag_ebs", "(", "self", ",", "conn", ",", "role", ")", ":", "tags", "=", "{", "'Name'", ":", "'spilo_'", "+", "self", ".", "cluster_name", ",", "'Role'", ":", "role", ",", "'Instance'", ":", "self", ".", "instance_id", "}", "volumes", "=", "c...
75.4
0.013123
def _repr_mimebundle_(self, *args, **kwargs): """Return a MIME bundle for display in Jupyter frontends.""" chart = self.to_chart() dct = chart.to_dict() return alt.renderers.get()(dct)
[ "def", "_repr_mimebundle_", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "chart", "=", "self", ".", "to_chart", "(", ")", "dct", "=", "chart", ".", "to_dict", "(", ")", "return", "alt", ".", "renderers", ".", "get", "(", ")", ...
42.4
0.009259
def wrap_key(self, key_material, wrapping_method, key_wrap_algorithm, encryption_key): """ Args: key_material (bytes): The bytes of the key to wrap. Required. wrapping_method (WrappingMethod): A WrappingMethod en...
[ "def", "wrap_key", "(", "self", ",", "key_material", ",", "wrapping_method", ",", "key_wrap_algorithm", ",", "encryption_key", ")", ":", "if", "wrapping_method", "==", "enums", ".", "WrappingMethod", ".", "ENCRYPT", ":", "if", "key_wrap_algorithm", "==", "enums", ...
41.092308
0.002194
def onBinaryMessage(self, msg, fromClient): data = bytearray() data.extend(msg) """ self.print_debug("message length: {}".format(len(data))) self.print_debug("message data: {}".format(hexlify(data))) """ try: self.queue.put_nowait(data) except asyncio.QueueFull: pass
[ "def", "onBinaryMessage", "(", "self", ",", "msg", ",", "fromClient", ")", ":", "data", "=", "bytearray", "(", ")", "data", ".", "extend", "(", "msg", ")", "try", ":", "self", ".", "queue", ".", "put_nowait", "(", "data", ")", "except", "asyncio", "....
21.461538
0.041237
def initialize_directories(self): """Automatically create local directories required by pip-accel.""" makedirs(self.config.source_index) makedirs(self.config.eggs_cache)
[ "def", "initialize_directories", "(", "self", ")", ":", "makedirs", "(", "self", ".", "config", ".", "source_index", ")", "makedirs", "(", "self", ".", "config", ".", "eggs_cache", ")" ]
47.5
0.010363
def stop(self): """ Stop all the processes """ Global.LOGGER.info("stopping the flow manager") self._stop_actions() self.isrunning = False Global.LOGGER.debug("flow manager stopped")
[ "def", "stop", "(", "self", ")", ":", "Global", ".", "LOGGER", ".", "info", "(", "\"stopping the flow manager\"", ")", "self", ".", "_stop_actions", "(", ")", "self", ".", "isrunning", "=", "False", "Global", ".", "LOGGER", ".", "debug", "(", "\"flow manag...
28.875
0.008403
def user_admin_view(model, login_view="Login", template_dir=None): """ :param UserStruct: The User model structure containing other classes :param login_view: The login view interface :param template_dir: The directory containing the view pages :return: UserAdmin Doc: User Admin is a view t...
[ "def", "user_admin_view", "(", "model", ",", "login_view", "=", "\"Login\"", ",", "template_dir", "=", "None", ")", ":", "Pylot", ".", "context_", "(", "COMPONENT_USER_ADMIN", "=", "True", ")", "User", "=", "model", ".", "UserStruct", ".", "User", "LoginView...
36.251429
0.001534
def parse_qa_tile(x, y, zoom, data, parse_direction=False, **kwargs): """ Return an OSM networkx graph from the input OSM QA tile data Parameters ---------- data : string x : int tile's x coordinate y : int tile's y coordinate zoom : int tile's zoom level >>...
[ "def", "parse_qa_tile", "(", "x", ",", "y", ",", "zoom", ",", "data", ",", "parse_direction", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "osmqa", "importer", ",", "parser", "=", "make_importer_parser", "(", "osmqa", ".", "QATileParser", "...
26.095238
0.001761
def run_command(args, cwd = None, shell = False, timeout = None, env = None): ''' Run a shell command with a timeout. See http://stackoverflow.com/questions/1191374/subprocess-with-timeout ''' from subprocess import PIPE, Popen from StringIO import StringIO import fcntl, os, signal p = P...
[ "def", "run_command", "(", "args", ",", "cwd", "=", "None", ",", "shell", "=", "False", ",", "timeout", "=", "None", ",", "env", "=", "None", ")", ":", "from", "subprocess", "import", "PIPE", ",", "Popen", "from", "StringIO", "import", "StringIO", "imp...
30.828571
0.020665
def parse_metric(metric, metric_mapping=METRIC_TREE): """Takes a metric formatted by Envoy and splits it into a unique metric name. Returns the unique metric name, a list of tags, and the name of the submission method. Example: 'listener.0.0.0.0_80.downstream_cx_total' -> ('listener.dow...
[ "def", "parse_metric", "(", "metric", ",", "metric_mapping", "=", "METRIC_TREE", ")", ":", "metric_parts", "=", "[", "]", "tag_names", "=", "[", "]", "tag_values", "=", "[", "]", "tag_builder", "=", "[", "]", "unknown_tags", "=", "[", "]", "num_tags", "=...
32.393939
0.001362
def rate_matrix(C, dt=1.0, method='KL', sparsity=None, t_agg=None, pi=None, tol=1.0E7, K0=None, maxiter=100000, on_error='raise'): r"""Estimate a reversible rate matrix from a count matrix. Parameters ---------- C : (N,N) ndarray count matrix at a lag time dt ...
[ "def", "rate_matrix", "(", "C", ",", "dt", "=", "1.0", ",", "method", "=", "'KL'", ",", "sparsity", "=", "None", ",", "t_agg", "=", "None", ",", "pi", "=", "None", ",", "tol", "=", "1.0E7", ",", "K0", "=", "None", ",", "maxiter", "=", "100000", ...
44.88785
0.001833
def add_dry_run(parser): ''' :param parser: :return: ''' default_format = 'table' resp_formats = ['raw', 'table', 'colored_table', 'json'] available_options = ', '.join(['%s' % opt for opt in resp_formats]) def dry_run_resp_format(value): if value not in resp_formats: raise argparse.ArgumentT...
[ "def", "add_dry_run", "(", "parser", ")", ":", "default_format", "=", "'table'", "resp_formats", "=", "[", "'raw'", ",", "'table'", ",", "'colored_table'", ",", "'json'", "]", "available_options", "=", "', '", ".", "join", "(", "[", "'%s'", "%", "opt", "fo...
31.6875
0.011483
def ok_tags(tags: dict) -> bool: """ Whether input tags dict is OK as an indy-sdk tags structure (depth=1, string values). """ if not tags: return True depth = 0 queue = [(i, depth+1) for i in tags.values() if isinstance(i, dict)] max_depth = 0 ...
[ "def", "ok_tags", "(", "tags", ":", "dict", ")", "->", "bool", ":", "if", "not", "tags", ":", "return", "True", "depth", "=", "0", "queue", "=", "[", "(", "i", ",", "depth", "+", "1", ")", "for", "i", "in", "tags", ".", "values", "(", ")", "i...
38.0625
0.008013
def transduce(self, es): """ returns the list of output Expressions obtained by adding the given inputs to the current state, one by one, to both the forward and backward RNNs, and concatenating. @param es: a list of Expression see also add_inputs(xs) ...
[ "def", "transduce", "(", "self", ",", "es", ")", ":", "for", "e", "in", "es", ":", "ensure_freshness", "(", "e", ")", "for", "(", "fb", ",", "bb", ")", "in", "self", ".", "builder_layers", ":", "fs", "=", "fb", ".", "initial_state", "(", ")", "."...
41.703704
0.012153
def intersect_keys(keys, reffile, cache=False, clean_accs=False): """Extract SeqRecords from the index by matching keys. keys - an iterable of sequence identifiers/accessions to select reffile - name of a FASTA file to extract the specified sequences from cache - save an index of the reference FASTA se...
[ "def", "intersect_keys", "(", "keys", ",", "reffile", ",", "cache", "=", "False", ",", "clean_accs", "=", "False", ")", ":", "# Build/load the index of reference sequences", "index", "=", "None", "if", "cache", ":", "refcache", "=", "reffile", "+", "'.sqlite'", ...
39.555556
0.000548
def get_position_encoding( length, hidden_size, min_timescale=1.0, max_timescale=1.0e4): """Return positional encoding. Calculates the position encoding as a mix of sine and cosine functions with geometrically increasing wavelengths. Defined and formulized in Attention is All You Need, section 3.5. Args...
[ "def", "get_position_encoding", "(", "length", ",", "hidden_size", ",", "min_timescale", "=", "1.0", ",", "max_timescale", "=", "1.0e4", ")", ":", "position", "=", "tf", ".", "to_float", "(", "tf", ".", "range", "(", "length", ")", ")", "num_timescales", "...
39
0.009268
def extract_file_name(content_dispo): """Extract file name from the input request body""" # print type(content_dispo) # print repr(content_dispo) # convertion of escape string (str type) from server # to unicode object content_dispo = content_dispo.decode('unicode-escape').strip('"') file_na...
[ "def", "extract_file_name", "(", "content_dispo", ")", ":", "# print type(content_dispo)", "# print repr(content_dispo)", "# convertion of escape string (str type) from server", "# to unicode object", "content_dispo", "=", "content_dispo", ".", "decode", "(", "'unicode-escape'", ")...
37.142857
0.001876
def create_zip_dir(zipfile_path, *file_list): """ This function creates a zipfile located in zipFilePath with the files in the file list # fileList can be both a comma separated list or an array """ try: if isinstance(file_list, (list, tuple)): #unfolding list of list or tuple if len(file_...
[ "def", "create_zip_dir", "(", "zipfile_path", ",", "*", "file_list", ")", ":", "try", ":", "if", "isinstance", "(", "file_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "#unfolding list of list or tuple", "if", "len", "(", "file_list", ")", "==", "1...
45.8
0.025663
def fix_varscan_output(line, normal_name="", tumor_name=""): """Fix a varscan VCF line. Fixes the ALT column and also fixes floating point values output as strings to by Floats: FREQ, SSC. This function was contributed by Sean Davis <sdavis2@mail.nih.gov>, with minor modifications by Luca Beltrame...
[ "def", "fix_varscan_output", "(", "line", ",", "normal_name", "=", "\"\"", ",", "tumor_name", "=", "\"\"", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "tofix", "=", "(", "\"##INFO=<ID=SSC\"", ",", "\"##FORMAT=<ID=FREQ\"", ")", "if", "(", "line",...
33.571429
0.001653
def ReadArtifact(self, name, cursor=None): """Looks up an artifact with given name from the database.""" cursor.execute("SELECT definition FROM artifacts WHERE name = %s", [name]) row = cursor.fetchone() if row is None: raise db.UnknownArtifactError(name) else: return _RowToArtifact(row...
[ "def", "ReadArtifact", "(", "self", ",", "name", ",", "cursor", "=", "None", ")", ":", "cursor", ".", "execute", "(", "\"SELECT definition FROM artifacts WHERE name = %s\"", ",", "[", "name", "]", ")", "row", "=", "cursor", ".", "fetchone", "(", ")", "if", ...
34.777778
0.009346
def calc_am_um_v1(self): """Calculate the flown through area and the wetted perimeter of the main channel. Note that the main channel is assumed to have identical slopes on both sides and that water flowing exactly above the main channel is contributing to |AM|. Both theoretical surfaces seperatin...
[ "def", "calc_am_um_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "if", "flu", ".", "h", "<=", "0.", ":", "flu", ".", "am",...
27.545455
0.000398
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for...
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "for", "p", "in", "group", ...
38.081967
0.002098
def info(self): """ Use the priors that make up the model_mapper to generate information on each parameter of the overall model. This information is extracted from each priors *model_info* property. """ info = [] for prior_model_name, prior_model in self.prior_model_tup...
[ "def", "info", "(", "self", ")", ":", "info", "=", "[", "]", "for", "prior_model_name", ",", "prior_model", "in", "self", ".", "prior_model_tuples", ":", "info", ".", "append", "(", "prior_model", ".", "name", "+", "'\\n'", ")", "info", ".", "extend", ...
36.769231
0.008163
def persist(self, status=None): """ Enables persistent mode for the current mock. Returns: self: current Mock instance. """ self._persist = status if type(status) is bool else True
[ "def", "persist", "(", "self", ",", "status", "=", "None", ")", ":", "self", ".", "_persist", "=", "status", "if", "type", "(", "status", ")", "is", "bool", "else", "True" ]
28.25
0.008584
def bishop88_mpp(photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth, method='newton'): """ Find max power point. Parameters ---------- photocurrent : numeric photogenerated current (Iph or IL) in amperes [A] saturation_current : numeric ...
[ "def", "bishop88_mpp", "(", "photocurrent", ",", "saturation_current", ",", "resistance_series", ",", "resistance_shunt", ",", "nNsVth", ",", "method", "=", "'newton'", ")", ":", "# collect args", "args", "=", "(", "photocurrent", ",", "saturation_current", ",", "...
37.690909
0.00047
def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name...
[ "def", "get_task", "(", "name", ")", ":", "url", "=", "_get_url", "(", ")", "if", "version", "(", ")", "<", "'0.13'", ":", "task_url", "=", "'{0}/task?name={1}'", ".", "format", "(", "url", ",", "name", ")", "else", ":", "task_url", "=", "'{0}/kapacito...
22.268293
0.002099
def time_since(self, mtype): '''return the time since the last message of type mtype was received''' if not mtype in self.messages: return time.time() - self.start_time return time.time() - self.messages[mtype]._timestamp
[ "def", "time_since", "(", "self", ",", "mtype", ")", ":", "if", "not", "mtype", "in", "self", ".", "messages", ":", "return", "time", ".", "time", "(", ")", "-", "self", ".", "start_time", "return", "time", ".", "time", "(", ")", "-", "self", ".", ...
50.6
0.011673
def parse_output(self, s): ''' Example output: AVR Memory Usage ---------------- Device: atmega2561 Program: 4168 bytes (1.6% Full) (.text + .data + .bootloader) Data: 72 bytes (0.9% Full) (.data + .bss + .noinit) ''' ...
[ "def", "parse_output", "(", "self", ",", "s", ")", ":", "for", "x", "in", "s", ".", "splitlines", "(", ")", ":", "if", "'%'", "in", "x", ":", "name", "=", "x", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "strip", "(", ")", ".", "lowe...
30.214286
0.002291
def infer(cls, sub_ija, T_ia, root_state, pc=0.01, gap_limit=0.01, Nit=30, dp=1e-5, **kwargs): """ Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` ...
[ "def", "infer", "(", "cls", ",", "sub_ija", ",", "T_ia", ",", "root_state", ",", "pc", "=", "0.01", ",", "gap_limit", "=", "0.01", ",", "Nit", "=", "30", ",", "dp", "=", "1e-5", ",", "*", "*", "kwargs", ")", ":", "from", "scipy", "import", "linal...
36.877551
0.011048
def upload(branch, user, tool): """ Commit + push to branch Returns username, commit hash """ with ProgressBar(_("Uploading")): language = os.environ.get("LANGUAGE") commit_message = [_("automated commit by {}").format(tool)] # If LANGUAGE environment variable is set, we nee...
[ "def", "upload", "(", "branch", ",", "user", ",", "tool", ")", ":", "with", "ProgressBar", "(", "_", "(", "\"Uploading\"", ")", ")", ":", "language", "=", "os", ".", "environ", ".", "get", "(", "\"LANGUAGE\"", ")", "commit_message", "=", "[", "_", "(...
35.409091
0.00125
def local_to_global(self, index): """ Calculate local index from global index :param index: input index :return: local index for data """ if (type(index) is int) or (type(index) is slice): if len(self.__mask) > 1: raise IndexError('check length of par...
[ "def", "local_to_global", "(", "self", ",", "index", ")", ":", "if", "(", "type", "(", "index", ")", "is", "int", ")", "or", "(", "type", "(", "index", ")", "is", "slice", ")", ":", "if", "len", "(", "self", ".", "__mask", ")", ">", "1", ":", ...
31.023256
0.00218
def as_signed(self): """ Returns the field *value* of the `Decimal` field as a signed integer.""" return self._cast(self._value, self._min(True), self._max(True), True)
[ "def", "as_signed", "(", "self", ")", ":", "return", "self", ".", "_cast", "(", "self", ".", "_value", ",", "self", ".", "_min", "(", "True", ")", ",", "self", ".", "_max", "(", "True", ")", ",", "True", ")" ]
60.666667
0.016304
def getTimeSinceLastUpdate(IOType): """Return the elapsed time since last update.""" global last_update_times # assert(IOType in ['net', 'disk', 'process_disk']) current_time = time() last_time = last_update_times.get(IOType) if not last_time: time_since_update = 1 else: time...
[ "def", "getTimeSinceLastUpdate", "(", "IOType", ")", ":", "global", "last_update_times", "# assert(IOType in ['net', 'disk', 'process_disk'])", "current_time", "=", "time", "(", ")", "last_time", "=", "last_update_times", ".", "get", "(", "IOType", ")", "if", "not", "...
35.25
0.002304
def delete_license_request(request): """Submission to remove a license acceptance request.""" uuid_ = request.matchdict['uuid'] posted_uids = [x['uid'] for x in request.json.get('licensors', [])] with db_connect() as db_conn: with db_conn.cursor() as cursor: remove_license_requests(...
[ "def", "delete_license_request", "(", "request", ")", ":", "uuid_", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "posted_uids", "=", "[", "x", "[", "'uid'", "]", "for", "x", "in", "request", ".", "json", ".", "get", "(", "'licensors'", ",", "[...
33.916667
0.002392
def from_dict(data, ctx): """ Instantiate a new UnitsAvailable from a dict (generally from loading a JSON response). The data used to instantiate the UnitsAvailable is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ ...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'default'", ")", "is", "not", "None", ":", "data", "[", "'default'", "]", "=", "ctx", ".", "order", ".", "UnitsAvai...
32.885714
0.001688
def computeScaledProbabilities( listOfScales=[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0], listofkValues=[64, 128, 256], kw=32, n=1000, numWorkers=10, nTrials=1000, ): """ Compute the impact of S on match probabilities for a fixed value of n. """ # Create arguments for t...
[ "def", "computeScaledProbabilities", "(", "listOfScales", "=", "[", "1.0", ",", "1.5", ",", "2.0", ",", "2.5", ",", "3.0", ",", "3.5", ",", "4.0", "]", ",", "listofkValues", "=", "[", "64", ",", "128", ",", "256", "]", ",", "kw", "=", "32", ",", ...
31.9375
0.013295
def _phiforce(self,R,z,phi=0.,t=0.): """ NAME: _phiforce PURPOSE: evaluate the azimuthal force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_phiforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_scf", ".", "phiforce", "(", "R", ",", "z", ",", "phi", "=", "phi", ",", "use_physical", "=", "False", ")" ]
27.705882
0.01848
def all_blackboxes(indices): """Generator over all possible blackboxings of these indices. Args: indices (tuple[int]): Nodes to blackbox. Yields: Blackbox: The next |Blackbox| of ``indices``. """ for partition in all_partitions(indices): # TODO? don't consider the empty set...
[ "def", "all_blackboxes", "(", "indices", ")", ":", "for", "partition", "in", "all_partitions", "(", "indices", ")", ":", "# TODO? don't consider the empty set here", "# (pass `nonempty=True` to `powerset`)", "for", "output_indices", "in", "utils", ".", "powerset", "(", ...
34.526316
0.001484
def cc(self, cc_emails, global_substitutions=None, is_multiple=False, p=0): """Adds Cc objects to the Personalization object :param cc_emails: An Cc or list of Cc objects :type cc_emails: Cc, list(Cc), tuple :param global_substitutions: A dict of substitutions for all recipients ...
[ "def", "cc", "(", "self", ",", "cc_emails", ",", "global_substitutions", "=", "None", ",", "is_multiple", "=", "False", ",", "p", "=", "0", ")", ":", "if", "isinstance", "(", "cc_emails", ",", "list", ")", ":", "for", "email", "in", "cc_emails", ":", ...
46.692308
0.001614
def _get_mark_if_any(self): """Parse a mark section.""" line = self.next_line() if line.startswith(b'mark :'): return line[len(b'mark :'):] else: self.push_line(line) return None
[ "def", "_get_mark_if_any", "(", "self", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", ".", "startswith", "(", "b'mark :'", ")", ":", "return", "line", "[", "len", "(", "b'mark :'", ")", ":", "]", "else", ":", "self", ".", ...
29.875
0.00813
def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many...
[ "def", "get_long_query", "(", "self", ",", "base_object_query", ",", "limit_to", "=", "100", ",", "max_calls", "=", "None", ",", "start_record", "=", "0", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", "base_object_query", ")",...
37.770492
0.001269
def search_users(self, user_name): """Searches for users via provisioning API. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be searched for :returns: list of usernames that contain user_name as substring :raises: HTTP...
[ "def", "search_users", "(", "self", ",", "user_name", ")", ":", "action_path", "=", "'users'", "if", "user_name", ":", "action_path", "+=", "'?search={}'", ".", "format", "(", "user_name", ")", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",",...
31.538462
0.002367
def generate_rss(self, path='rss.xml', only_excerpt=True, https=False): """ Generate the RSS feed. Args: path (str): Where to save the RSS file. Make sure that your jinja templates refer to the same path using <link>. only_excerpt (bool): If True (the default), don't include the full body of ...
[ "def", "generate_rss", "(", "self", ",", "path", "=", "'rss.xml'", ",", "only_excerpt", "=", "True", ",", "https", "=", "False", ")", ":", "feed", "=", "russell", ".", "feed", ".", "get_rss_feed", "(", "self", ",", "only_excerpt", "=", "only_excerpt", ",...
45.3125
0.033784
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True): """Draw barplots grouped by modality of modality percentage per group Parameters ---------- Returns ------- Raises ------ """ if percentages: counts = 100 ...
[ "def", "bar", "(", "self", ",", "counts", ",", "phenotype_to_color", "=", "None", ",", "ax", "=", "None", ",", "percentages", "=", "True", ")", ":", "if", "percentages", ":", "counts", "=", "100", "*", "(", "counts", ".", "T", "/", "counts", ".", "...
32.825
0.001479
def macaroon_ops(self, macaroons): ''' This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. For macaroons minted with previous bakery versions, it always returns a single LoginOp operation. :param macaroons: :return: '''...
[ "def", "macaroon_ops", "(", "self", ",", "macaroons", ")", ":", "if", "len", "(", "macaroons", ")", "==", "0", ":", "raise", "ValueError", "(", "'no macaroons provided'", ")", "storage_id", ",", "ops", "=", "_decode_macaroon_id", "(", "macaroons", "[", "0", ...
37.730769
0.000994
def extract_xyz_matrix_from_chain(self, chain_id, atoms_of_interest = []): '''Create a pandas coordinates dataframe from the lines in the specified chain.''' chains = [l[21] for l in self.structure_lines if len(l) > 21] chain_lines = [l for l in self.structure_lines if len(l) > 21 and l[21] == c...
[ "def", "extract_xyz_matrix_from_chain", "(", "self", ",", "chain_id", ",", "atoms_of_interest", "=", "[", "]", ")", ":", "chains", "=", "[", "l", "[", "21", "]", "for", "l", "in", "self", ".", "structure_lines", "if", "len", "(", "l", ")", ">", "21", ...
90.2
0.028571
def authors(self): ''' Queryset for all distinct authors this course had so far. Important for statistics. Note that this may be different from the list of people being registered for the course, f.e. when they submit something and the leave the course. ''' qs...
[ "def", "authors", "(", "self", ")", ":", "qs", "=", "self", ".", "_valid_submissions", "(", ")", ".", "values_list", "(", "'authors'", ",", "flat", "=", "True", ")", ".", "distinct", "(", ")", "return", "qs" ]
50.375
0.014634
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.st...
[ "def", "_remove_nonascii", "(", "self", ",", "df", ")", ":", "df_copy", "=", "df", ".", "copy", "(", "deep", "=", "True", ")", "for", "col", "in", "df_copy", ".", "columns", ":", "if", "(", "df_copy", "[", "col", "]", ".", "dtype", "==", "np", "....
35
0.008357
def bins(self) -> List[np.ndarray]: """List of bin matrices.""" return [binning.bins for binning in self._binnings]
[ "def", "bins", "(", "self", ")", "->", "List", "[", "np", ".", "ndarray", "]", ":", "return", "[", "binning", ".", "bins", "for", "binning", "in", "self", ".", "_binnings", "]" ]
43
0.015267
def getAnnotations_via_id(self, annotation_ids, LIMIT=25, _print=True, crawl=False): """tids = list of strings or ints that are the ids of the annotations themselves""" url_base = self...
[ "def", "getAnnotations_via_id", "(", "self", ",", "annotation_ids", ",", "LIMIT", "=", "25", ",", "_print", "=", "True", ",", "crawl", "=", "False", ")", ":", "url_base", "=", "self", ".", "base_url", "+", "'/api/1/term/get-annotation/{id}?key='", "+", "self",...
44.923077
0.011745
def copy(self, parent=None, name=None, verbose=True): """Create a copy under parent. All children are copied as well. Parameters ---------- parent : WrightTools Collection (optional) Parent to copy within. If None, copy is created in root of new tempfile...
[ "def", "copy", "(", "self", ",", "parent", "=", "None", ",", "name", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "natural_name", "if", "parent", "is", "None", ":", "from", ".", "_...
31.113636
0.001416
def simulateSytematicError(N_SAMPLES=5, N_IMAGES=10, SHOW_DETECTED_PATTERN=True, # GRAYSCALE=False, HEIGHT=500, PLOT_RESULTS=True, PLOT_ERROR_ARRAY=True, CAMERA_PARAM=None, PERSPECTIVE=True, ROTATION=True, R...
[ "def", "simulateSytematicError", "(", "N_SAMPLES", "=", "5", ",", "N_IMAGES", "=", "10", ",", "SHOW_DETECTED_PATTERN", "=", "True", ",", "# GRAYSCALE=False,\r", "HEIGHT", "=", "500", ",", "PLOT_RESULTS", "=", "True", ",", "PLOT_ERROR_ARRAY", "=", "True", ",", ...
38.310249
0.000634
def exec_commands(commands: str, **parameters: Any) -> None: """Execute the given Python commands. Function |exec_commands| is thought for testing purposes only (see the main documentation on module |hyd|). Seperate individual commands by semicolons and replaced whitespaces with underscores: >>> ...
[ "def", "exec_commands", "(", "commands", ":", "str", ",", "*", "*", "parameters", ":", "Any", ")", "->", "None", ":", "cmdlist", "=", "commands", ".", "split", "(", "';'", ")", "print", "(", "f'Start to execute the commands {cmdlist} for testing purposes.'", ")"...
37.916667
0.000714
def _handle_weekly_repeat_in(self): """ Handles repeating both weekly and biweekly events, if the current year and month are inside it's l_start_date and l_end_date. Four possibilites: 1. The event starts this month and ends repeating this month. 2. The event star...
[ "def", "_handle_weekly_repeat_in", "(", "self", ")", ":", "self", ".", "day", "=", "self", ".", "event", ".", "l_start_date", ".", "day", "self", ".", "count_first", "=", "False", "repeats", "=", "{", "'WEEKLY'", ":", "7", ",", "'BIWEEKLY'", ":", "14", ...
48.423077
0.001558
def find_dongle_port(): """Convenience method which attempts to find the port where a BLED112 dongle is connected. This relies on the `pyserial.tools.list_ports.grep method <https://pyserial.readthedocs.io/en/latest/tools.html#serial.tools.list_ports.grep>`_, and simply searches for a...
[ "def", "find_dongle_port", "(", ")", ":", "logger", ".", "debug", "(", "'Attempting to find Bluegiga dongle...'", ")", "# TODO this will probably only work on Windows at the moment", "ports", "=", "list", "(", "serial", ".", "tools", ".", "list_ports", ".", "grep", "(",...
50
0.008411
def submission_status(self, submission_id=None): """submission status of the last submission associated with the account. Args: submission_id (str): submission of interest, defaults to the last submission done with the account Returns: dict: submission s...
[ "def", "submission_status", "(", "self", ",", "submission_id", "=", "None", ")", ":", "if", "submission_id", "is", "None", ":", "submission_id", "=", "self", ".", "submission_id", "if", "submission_id", "is", "None", ":", "raise", "ValueError", "(", "'You need...
35.38
0.00165
def get_bookmarks(self, time=None, chan=None): """ Raises ------ IndexError When there is no selected rater """ # get bookmarks inside window try: bookmarks = self.rater.find('bookmarks') except AttributeError: raise Ind...
[ "def", "get_bookmarks", "(", "self", ",", "time", "=", "None", ",", "chan", "=", "None", ")", ":", "# get bookmarks inside window", "try", ":", "bookmarks", "=", "self", ".", "rater", ".", "find", "(", "'bookmarks'", ")", "except", "AttributeError", ":", "...
32.428571
0.001426
def open_download_stream(self, file_id): """Opens a Stream from which the application can read the contents of the stored file specified by file_id. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # get _id of file to read. file_id = fs...
[ "def", "open_download_stream", "(", "self", ",", "file_id", ")", ":", "gout", "=", "GridOut", "(", "self", ".", "_collection", ",", "file_id", ")", "# Raise NoFile now, instead of on first attribute access.", "gout", ".", "_ensure_file", "(", ")", "return", "gout" ]
33.96
0.002291
def post(self, key='hello', value='world'): """ This takes two parameters a key and a value and temporarily stores them on the server :param key: str of key to store the value under :param value: str of the value to store :return: Echo dict of the key value store...
[ "def", "post", "(", "self", ",", "key", "=", "'hello'", ",", "value", "=", "'world'", ")", ":", "return", "self", ".", "connection", ".", "post", "(", "'echo/key'", ",", "data", "=", "dict", "(", "key", "=", "key", ",", "value", "=", "value", ")", ...
52.125
0.009434
def load_presets(self, presets_path=None): """Load presets from disk. Read JSON formatted preset data from the specified path, or the default location at ``/var/lib/sos/presets``. :param presets_path: a directory containing JSON presets. """ presets_path = p...
[ "def", "load_presets", "(", "self", ",", "presets_path", "=", "None", ")", ":", "presets_path", "=", "presets_path", "or", "self", ".", "presets_path", "if", "not", "os", ".", "path", ".", "exists", "(", "presets_path", ")", ":", "return", "for", "preset_p...
38.064516
0.001653
def resource_to_url(resource, request=None, quote=False): """ Converts the given resource to a URL. :param request: Request object (required for the host name part of the URL). If this is not given, the current request is used. :param bool quote: If set, the URL returned will be quoted. """ ...
[ "def", "resource_to_url", "(", "resource", ",", "request", "=", "None", ",", "quote", "=", "False", ")", ":", "if", "request", "is", "None", ":", "request", "=", "get_current_request", "(", ")", "# cnv = request.registry.getAdapter(request, IResourceUrlConverter)",...
41.714286
0.001675
def concatenate(a, b=None): """ Concatenate two or more meshes. Parameters ---------- a: Trimesh object, or list of such b: Trimesh object, or list of such Returns ---------- result: Trimesh object containing concatenated mesh """ if b is None: b = [] # stack me...
[ "def", "concatenate", "(", "a", ",", "b", "=", "None", ")", ":", "if", "b", "is", "None", ":", "b", "=", "[", "]", "# stack meshes into flat list", "meshes", "=", "np", ".", "append", "(", "a", ",", "b", ")", "# extract the trimesh type to avoid a circular...
27.866667
0.00077
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs): ''' Parse a string or file through Salt's renderer system .. versionchanged:: 2018.3.0 Add support for Salt fileserver URIs. This is an open-ended function and can be used for a variety of tasks. It makes use of ...
[ "def", "renderer", "(", "path", "=", "None", ",", "string", "=", "None", ",", "default_renderer", "=", "'jinja|yaml'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "path", "and", "not", "string", ":", "raise", "salt", ".", "exceptions", ".", "SaltIn...
38.543478
0.00055
def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8', force_snake_case: bool=True, restrict: bool=True) -> TList[T]: """From csv file path to list of instance :param fpath: Csv file path :param fieldnames: Specify csv header names if no...
[ "def", "from_csvf", "(", "cls", ",", "fpath", ":", "str", ",", "fieldnames", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", "=", "None", ",", "encoding", ":", "str", "=", "'utf8'", ",", "force_snake_case", ":", "bool", "=", "True", ",", "res...
54.333333
0.016888
def _get_sts_token(self): """ Assume a role via STS and return the credentials. First connect to STS via :py:func:`boto3.client`, then assume a role using `boto3.STS.Client.assume_role <https://boto3.readthe docs.org/en/latest/reference/services/sts.html#STS.Client.assume_role>`...
[ "def", "_get_sts_token", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Connecting to STS in region %s\"", ",", "self", ".", "region", ")", "sts", "=", "boto3", ".", "client", "(", "'sts'", ",", "region_name", "=", "self", ".", "region", ")", "arn"...
43.810811
0.001811
def conf_budget(self, budget): """ Set limit on the number of conflicts. """ if self.minicard: pysolvers.minicard_cbudget(self.minicard, budget)
[ "def", "conf_budget", "(", "self", ",", "budget", ")", ":", "if", "self", ".", "minicard", ":", "pysolvers", ".", "minicard_cbudget", "(", "self", ".", "minicard", ",", "budget", ")" ]
26.714286
0.010363
def ajax_recalculate_prices(self): """Recalculate prices for all ARs """ # When the option "Include and display pricing information" in # Bika Setup Accounting tab is not selected if not self.show_recalculate_prices(): return {} # The sorted records from the ...
[ "def", "ajax_recalculate_prices", "(", "self", ")", ":", "# When the option \"Include and display pricing information\" in", "# Bika Setup Accounting tab is not selected", "if", "not", "self", ".", "show_recalculate_prices", "(", ")", ":", "return", "{", "}", "# The sorted reco...
40.089744
0.000624
def _pdf(self, x, dist, cache): """Probability density function.""" return evaluation.evaluate_density( dist, numpy.arcsinh(x), cache=cache)/numpy.sqrt(1+x*x)
[ "def", "_pdf", "(", "self", ",", "x", ",", "dist", ",", "cache", ")", ":", "return", "evaluation", ".", "evaluate_density", "(", "dist", ",", "numpy", ".", "arcsinh", "(", "x", ")", ",", "cache", "=", "cache", ")", "/", "numpy", ".", "sqrt", "(", ...
45.75
0.010753
def importRemoteSNPs(name) : """Import a SNP set available from http://pygeno.iric.ca (might work).""" try : dw = listRemoteDatawraps()["Flat"]["SNPs"] except AttributeError : raise AttributeError("There's no remote genome datawrap by the name of: '%s'" % name) finalFile = _DW(name, dw["url"]) PS.importSNPs(f...
[ "def", "importRemoteSNPs", "(", "name", ")", ":", "try", ":", "dw", "=", "listRemoteDatawraps", "(", ")", "[", "\"Flat\"", "]", "[", "\"SNPs\"", "]", "except", "AttributeError", ":", "raise", "AttributeError", "(", "\"There's no remote genome datawrap by the name of...
35.666667
0.036474
def compile(self): """Return Hip string if already compiled else compile it.""" if self.buffer is None: self.buffer = self._compile_value(self.data, 0) return self.buffer.strip()
[ "def", "compile", "(", "self", ")", ":", "if", "self", ".", "buffer", "is", "None", ":", "self", ".", "buffer", "=", "self", ".", "_compile_value", "(", "self", ".", "data", ",", "0", ")", "return", "self", ".", "buffer", ".", "strip", "(", ")" ]
35
0.009302
def simxReadStringStream(clientID, signalName, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' signalLength = ct.c_int(); signalValue = ct.POINTER(ct.c_ubyte)() if (sys.version_info[0] == 3) and (type(signalName) is str): sig...
[ "def", "simxReadStringStream", "(", "clientID", ",", "signalName", ",", "operationMode", ")", ":", "signalLength", "=", "ct", ".", "c_int", "(", ")", "signalValue", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_ubyte", ")", "(", ")", "if", "(", "sys", ...
33.526316
0.00916
def values (feature): """ Return the values of the given feature. """ assert isinstance(feature, basestring) validate_feature (feature) return __all_features[feature].values
[ "def", "values", "(", "feature", ")", ":", "assert", "isinstance", "(", "feature", ",", "basestring", ")", "validate_feature", "(", "feature", ")", "return", "__all_features", "[", "feature", "]", ".", "values" ]
31.333333
0.015544
def check(self, locator=None, allow_label_click=None, **kwargs): """ Find a check box and mark it as checked. The check box can be found via name, id, or label text. :: page.check("German") Args: locator (str, optional): Which check box to check. all...
[ "def", "check", "(", "self", ",", "locator", "=", "None", ",", "allow_label_click", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_with_label", "(", "\"checkbox\"", ",", "True", ",", "locator", "=", "locator", ",", "allow_label_click"...
43.25
0.008487
def fit(self, x_train, y_train, x_valid=None, y_valid=None, epochs=1, batch_size=32, verbose=1, callbacks=None, shuffle=True): """Fit the model for a fixed number of epochs. Args: x_train: list of training data. y_train: list of training target (label) data. ...
[ "def", "fit", "(", "self", ",", "x_train", ",", "y_train", ",", "x_valid", "=", "None", ",", "y_valid", "=", "None", ",", "epochs", "=", "1", ",", "batch_size", "=", "32", ",", "verbose", "=", "1", ",", "callbacks", "=", "None", ",", "shuffle", "="...
49.021277
0.002128
def write_config(config, config_path=CONFIG_PATH): """Write the config to the output path. Creates the necessary directories if they aren't there. Args: config (configparser.ConfigParser): A ConfigParser. """ if not os.path.exists(config_path): os.makedirs(os.path.dirname(config_pat...
[ "def", "write_config", "(", "config", ",", "config_path", "=", "CONFIG_PATH", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "config_path", ")",...
35.727273
0.002481
def name(self, src=None): """Return string representing the name of this type.""" if self._upper_bound is None and self._lower_bound is None: return "int" if self._upper_bound is None: if self._lower_bound == 1: return "int>0" return "int≥%d" % self._lower_bound i...
[ "def", "name", "(", "self", ",", "src", "=", "None", ")", ":", "if", "self", ".", "_upper_bound", "is", "None", "and", "self", ".", "_lower_bound", "is", "None", ":", "return", "\"int\"", "if", "self", ".", "_upper_bound", "is", "None", ":", "if", "s...
50.777778
0.010753
def get_item(self, tablename, key, attributes=None, consistent=False, return_capacity=None): """ Fetch a single item from a table This uses the older version of the DynamoDB API. See also: :meth:`~.get_item2`. Parameters ---------- tablename : s...
[ "def", "get_item", "(", "self", ",", "tablename", ",", "key", ",", "attributes", "=", "None", ",", "consistent", "=", "False", ",", "return_capacity", "=", "None", ")", ":", "kwargs", "=", "{", "'TableName'", ":", "tablename", ",", "'Key'", ":", "self", ...
38.514286
0.002171
def load_model(itos_filename, classifier_filename, num_classes): """Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: ...
[ "def", "load_model", "(", "itos_filename", ",", "classifier_filename", ",", "num_classes", ")", ":", "# load the int to string mapping file", "itos", "=", "pickle", ".", "load", "(", "Path", "(", "itos_filename", ")", ".", "open", "(", "'rb'", ")", ")", "# turn ...
38.939394
0.014427
def __get_libres(self): ''' Computes libpath based on whether module_name is set or not Returns-->list of str lib paths to try PEP3140: ABI version tagged .so files: https://www.python.org/dev/peps/pep-3149/ There's still one unexplained bit: pypy adds '-' + sys._mu...
[ "def", "__get_libres", "(", "self", ")", ":", "if", "self", ".", "_module_name", "is", "None", ":", "return", "[", "]", "ending", "=", "'.so'", "base", "=", "self", ".", "_libpath", ".", "rsplit", "(", "ending", ",", "1", ")", "[", "0", "]", "abi",...
34.218182
0.001033
def analyzeWeightPruning(args): """ Multiprocess function used to analyze the impact of nonzeros and accuracy after pruning low weights and units with low dutycycle of a pre-trained model. :param args: tuple with the following arguments: - experiment path: The experiment results path ...
[ "def", "analyzeWeightPruning", "(", "args", ")", ":", "path", ",", "params", ",", "minWeight", ",", "minDutycycle", ",", "position", "=", "args", "device", "=", "torch", ".", "device", "(", "\"cuda\"", "if", "torch", ".", "cuda", ".", "is_available", "(", ...
37.283951
0.011935
def from_b32key(b32_key, state=None): '''Some phone app directly accept a partial b32 encoding, we try to emulate that''' try: lenient_b32decode(b32_key) except TypeError: raise ValueError('invalid base32 value') return GoogleAuthenticator('otpauth://totp/xxx?%s' % urlencode(...
[ "def", "from_b32key", "(", "b32_key", ",", "state", "=", "None", ")", ":", "try", ":", "lenient_b32decode", "(", "b32_key", ")", "except", "TypeError", ":", "raise", "ValueError", "(", "'invalid base32 value'", ")", "return", "GoogleAuthenticator", "(", "'otpaut...
43.375
0.008475
def is_valid_sse_object(sse): """ Validate the SSE object and type :param sse: SSE object defined. """ if sse and sse.type() != "SSE-C" and sse.type() != "SSE-KMS" and sse.type() != "SSE-S3": raise InvalidArgumentError("unsuported type of sse argument in put_object")
[ "def", "is_valid_sse_object", "(", "sse", ")", ":", "if", "sse", "and", "sse", ".", "type", "(", ")", "!=", "\"SSE-C\"", "and", "sse", ".", "type", "(", ")", "!=", "\"SSE-KMS\"", "and", "sse", ".", "type", "(", ")", "!=", "\"SSE-S3\"", ":", "raise", ...
36.125
0.010135
def timesince(d, now): """ Taken from django.utils.timesince and modified to simpler requirements. Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, month...
[ "def", "timesince", "(", "d", ",", "now", ")", ":", "def", "pluralize", "(", "a", ",", "b", ")", ":", "def", "inner", "(", "n", ")", ":", "if", "n", "==", "1", ":", "return", "a", "%", "n", "return", "b", "%", "n", "return", "inner", "def", ...
34.2
0.000406
def decode_all(data, codec_options=DEFAULT_CODEC_OPTIONS): """Decode BSON data to multiple documents. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `data`: BSON data - `codec_options` (optional): An instance of :class:`~bson.codec_options.Co...
[ "def", "decode_all", "(", "data", ",", "codec_options", "=", "DEFAULT_CODEC_OPTIONS", ")", ":", "if", "not", "isinstance", "(", "codec_options", ",", "CodecOptions", ")", ":", "raise", "_CODEC_OPTIONS_TYPE_ERROR", "docs", "=", "[", "]", "position", "=", "0", "...
39.131148
0.000409
def subdivide(vertices, faces, face_index=None): """ Subdivide a mesh into smaller triangles. Note that if `face_index` is passed, only those faces will be subdivided and their neighbors won't be modified making the mesh no longer "watertight." Parameters ------...
[ "def", "subdivide", "(", "vertices", ",", "faces", ",", "face_index", "=", "None", ")", ":", "if", "face_index", "is", "None", ":", "face_index", "=", "np", ".", "arange", "(", "len", "(", "faces", ")", ")", "else", ":", "face_index", "=", "np", ".",...
32.507042
0.000421
def transform(self, X): ''' Turns distances into RBF values. Parameters ---------- X : array The raw pairwise distances. Returns ------- X_rbf : array of same shape as X The distances in X passed through the RBF kernel. ''...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "check_array", "(", "X", ")", "X_rbf", "=", "np", ".", "empty_like", "(", "X", ")", "if", "self", ".", "copy", "else", "X", "X_in", "=", "X", "if", "not", "self", ".", "squared", ":...
24.967742
0.002488
def _set_WorkingDir(self, path): """Sets the working directory """ self._curr_working_dir = path try: mkdir(self.WorkingDir) except OSError: # Directory already exists pass
[ "def", "_set_WorkingDir", "(", "self", ",", "path", ")", ":", "self", ".", "_curr_working_dir", "=", "path", "try", ":", "mkdir", "(", "self", ".", "WorkingDir", ")", "except", "OSError", ":", "# Directory already exists", "pass" ]
26.666667
0.008065