text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def make_path_conditional(self, path, condition): """ Wrap entire API path definition in a CloudFormation if condition. """ self.paths[path] = make_conditional(condition, self.paths[path])
[ "def", "make_path_conditional", "(", "self", ",", "path", ",", "condition", ")", ":", "self", ".", "paths", "[", "path", "]", "=", "make_conditional", "(", "condition", ",", "self", ".", "paths", "[", "path", "]", ")" ]
43.2
0.009091
def LE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): '''32-bit field, Little endian encoded''' return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range)
[ "def", "LE32", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ",", "full_range", "=", "False", ")", ":", "return", "UInt32", "(", "value", ",", "min_value", "=", "mi...
92
0.010791
def app_url_defaults(self, f): """Same as :meth:`url_defaults` but application wide. """ self.record_once(lambda s: s.app.url_default_functions .setdefault(None, []).append(f)) return f
[ "def", "app_url_defaults", "(", "self", ",", "f", ")", ":", "self", ".", "record_once", "(", "lambda", "s", ":", "s", ".", "app", ".", "url_default_functions", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", ")", "...
37.333333
0.0131
def get_qpimage(self, index): """Return a single QPImage of the series Parameters ---------- index: int or str Index or identifier of the QPImage Notes ----- Instead of ``qps.get_qpimage(index)``, it is possible to use the short-hand ``qps[in...
[ "def", "get_qpimage", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "str", ")", ":", "# search for the identifier", "for", "ii", "in", "range", "(", "len", "(", "self", ")", ")", ":", "qpi", "=", "self", "[", "ii", "]", ...
34.410256
0.001449
def predict_from_cfg(cls, df, cfgname): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which describes the hedonic model. Returns ...
[ "def", "predict_from_cfg", "(", "cls", ",", "df", ",", "cfgname", ")", ":", "logger", ".", "debug", "(", "'start: predict from configuration {}'", ".", "format", "(", "cfgname", ")", ")", "hm", "=", "cls", ".", "from_yaml", "(", "str_or_buffer", "=", "cfgnam...
35.8
0.002176
def save(hdf5_filename, array): """ Export a numpy array to a HDF5 file. Arguments: hdf5_filename (str): A filename to which to save the HDF5 data array (numpy.ndarray): The numpy array to save to HDF5 Returns: String. The expanded filename that now holds the HDF5 data """ ...
[ "def", "save", "(", "hdf5_filename", ",", "array", ")", ":", "# Expand filename to be absolute", "hdf5_filename", "=", "os", ".", "path", ".", "expanduser", "(", "hdf5_filename", ")", "try", ":", "h", "=", "h5py", ".", "File", "(", "hdf5_filename", ",", "\"w...
29.045455
0.001515
def parse_port(port_obj, owner): '''Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. ...
[ "def", "parse_port", "(", "port_obj", ",", "owner", ")", ":", "profile", "=", "port_obj", ".", "get_port_profile", "(", ")", "props", "=", "utils", ".", "nvlist_to_dict", "(", "profile", ".", "properties", ")", "if", "props", "[", "'port.port_type'", "]", ...
36.285714
0.001279
def on_batch_begin(self, last_input, last_target, **kwargs): "Clamp the weights with `self.clip` if it's not None, return the correct input." if self.clip is not None: for p in self.critic.parameters(): p.data.clamp_(-self.clip, self.clip) return {'last_input':last_input,'last_target...
[ "def", "on_batch_begin", "(", "self", ",", "last_input", ",", "last_target", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "clip", "is", "not", "None", ":", "for", "p", "in", "self", ".", "critic", ".", "parameters", "(", ")", ":", "p", "."...
80.8
0.029412
def compile_file(filename, compiler_class=Compiler, **kwargs): """Compile a single file (provided as a :class:`pathlib.Path`), and return a string of CSS. Keyword arguments are passed along to the underlying `Compiler`. Note that the search path is set to the file's containing directory by default...
[ "def", "compile_file", "(", "filename", ",", "compiler_class", "=", "Compiler", ",", "*", "*", "kwargs", ")", ":", "filename", "=", "Path", "(", "filename", ")", "if", "'search_path'", "not", "in", "kwargs", ":", "kwargs", "[", "'search_path'", "]", "=", ...
37.611111
0.001441
def parse_euro_date(self, date_string: str): """ Parses dd/MM/yyyy dates """ self.date = datetime.strptime(date_string, "%d/%m/%Y") return self.date
[ "def", "parse_euro_date", "(", "self", ",", "date_string", ":", "str", ")", ":", "self", ".", "date", "=", "datetime", ".", "strptime", "(", "date_string", ",", "\"%d/%m/%Y\"", ")", "return", "self", ".", "date" ]
42.25
0.011628
def mkbrowseto(self, url): """Create the urwid callback function to open the web browser or call another function with the URL. """ # Try-except block to work around webbrowser module bug # https://bugs.python.org/issue31014 try: browser = os.environ['BROWSER...
[ "def", "mkbrowseto", "(", "self", ",", "url", ")", ":", "# Try-except block to work around webbrowser module bug", "# https://bugs.python.org/issue31014", "try", ":", "browser", "=", "os", ".", "environ", "[", "'BROWSER'", "]", "except", "KeyError", ":", "pass", "else...
41.277778
0.001972
def make_gpfs_path(path): """Make a gpfs version of a file path. This just puts /gpfs at the beginning instead of /nfs""" if os.path.isabs(path): fullpath = os.path.abspath(path) else: fullpath = os.path.abspath(path) if len(fullpath) < 5: return fullpath if fullpath[0:5]...
[ "def", "make_gpfs_path", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "fullpath", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "else", ":", "fullpath", "=", "os", ".", "path", ".", "abspath", "...
33
0.002457
def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' adapters = _parse_interfaces() if iface in adapters: try: if iface == 'source': template = JINJA.get_t...
[ "def", "get_interface", "(", "iface", ")", ":", "adapters", "=", "_parse_interfaces", "(", ")", "if", "iface", "in", "adapters", ":", "try", ":", "if", "iface", "==", "'source'", ":", "template", "=", "JINJA", ".", "get_template", "(", "'debian_source.jinja'...
27.678571
0.001247
def bingham_mean(dec=None, inc=None, di_block=None): """ Calculates the Bingham mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with t...
[ "def", "bingham_mean", "(", "dec", "=", "None", ",", "inc", "=", "None", ",", "di_block", "=", "None", ")", ":", "if", "di_block", "is", "None", ":", "di_block", "=", "make_di_block", "(", "dec", ",", "inc", ")", "return", "pmag", ".", "dobingham", "...
31.729167
0.001911
def points(self, include_hidden=False): """Return the number of points awarded to this submission.""" return sum(x.points for x in self.testable_results if include_hidden or not x.testable.is_hidden)
[ "def", "points", "(", "self", ",", "include_hidden", "=", "False", ")", ":", "return", "sum", "(", "x", ".", "points", "for", "x", "in", "self", ".", "testable_results", "if", "include_hidden", "or", "not", "x", ".", "testable", ".", "is_hidden", ")" ]
57.75
0.008547
def delete_servers(*servers, **options): ''' Removes NTP servers configured on the device. :param servers: list of IP Addresses/Domain Names to be removed as NTP servers :param test (bool): discard loaded config. By default ``test`` is False (will not dicard the changes) :param com...
[ "def", "delete_servers", "(", "*", "servers", ",", "*", "*", "options", ")", ":", "test", "=", "options", ".", "pop", "(", "'test'", ",", "False", ")", "commit", "=", "options", ".", "pop", "(", "'commit'", ",", "True", ")", "return", "__salt__", "["...
39.441176
0.002183
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None): """compute problem size, thread block and grid dimensions for this kernel""" threads = get_thread_block_dimensions(params, block_size_names) current_problem_size = get_problem_size(problem_size, params) grid = get_grid_dime...
[ "def", "setup_block_and_grid", "(", "problem_size", ",", "grid_div", ",", "params", ",", "block_size_names", "=", "None", ")", ":", "threads", "=", "get_thread_block_dimensions", "(", "params", ",", "block_size_names", ")", "current_problem_size", "=", "get_problem_si...
67.333333
0.00978
def lines(start=None, end=None, reverse=False, selection=False): """Iterate lines in range. Args: start: Starting address, start of IDB if `None`. end: End address, end of IDB if `None`. reverse: Set to true to iterate in reverse order. selection: If set to True, replaces start ...
[ "def", "lines", "(", "start", "=", "None", ",", "end", "=", "None", ",", "reverse", "=", "False", ",", "selection", "=", "False", ")", ":", "if", "selection", ":", "start", ",", "end", "=", "get_selection", "(", ")", "else", ":", "start", ",", "end...
28.931034
0.002307
def initialize(spark_home_path: str = None): """ Registers and initializes the PySpark library dependencies so that the pyspark package can be imported and used within the notebook. If you specify the path to the spark home folder, the PySpark libraries from that location will be loaded. If a value...
[ "def", "initialize", "(", "spark_home_path", ":", "str", "=", "None", ")", ":", "if", "not", "spark_home_path", ":", "spark_home_path", "=", "os", ".", "environ", ".", "get", "(", "'SPARK_HOME'", ")", "spark_home_path", "=", "environ", ".", "paths", ".", "...
29.786885
0.000533
def get_historical_data(fsym, tsym, freq, info='full', e='all', try_conversion=True, aggregate=1, limit=1440, to_ts=False): """Get minute-by-minute historical price and volume information for the requested currency pair. Available data is limited to the last 7 da...
[ "def", "get_historical_data", "(", "fsym", ",", "tsym", ",", "freq", ",", "info", "=", "'full'", ",", "e", "=", "'all'", ",", "try_conversion", "=", "True", ",", "aggregate", "=", "1", ",", "limit", "=", "1440", ",", "to_ts", "=", "False", ")", ":", ...
34.013889
0.034127
def setup_logging(cli_options): """Setup logging with cli options defined by the user.""" if cli_options.debug_info or get_debug_level() > 0: levels = {2: logging.INFO, 3: logging.DEBUG} log_level = levels[get_debug_level()] log_format = '%(asctime)s [%(levelname)s] [%(name)s] -> %(...
[ "def", "setup_logging", "(", "cli_options", ")", ":", "if", "cli_options", ".", "debug_info", "or", "get_debug_level", "(", ")", ">", "0", ":", "levels", "=", "{", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "DEBUG", "}", "log_leve...
40
0.001527
def cat(self, others=None, sep=None, na_rep=None, join=None): """ Concatenate strings in the Series/Index with given separator. If `others` is specified, this function concatenates the Series/Index and elements of `others` element-wise. If `others` is not passed, then all values...
[ "def", "cat", "(", "self", ",", "others", "=", "None", ",", "sep", "=", "None", ",", "na_rep", "=", "None", ",", "join", "=", "None", ")", ":", "from", "pandas", "import", "Index", ",", "Series", ",", "concat", "if", "isinstance", "(", "others", ",...
39.165919
0.000223
def _run_apt_command(cmd, fatal=False): """Run an apt command with optional retries. :param: cmd: str: The apt command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ # Provide DEBIAN_FRONTEND=noninteractive if not present in the environment. ...
[ "def", "_run_apt_command", "(", "cmd", ",", "fatal", "=", "False", ")", ":", "# Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.", "cmd_env", "=", "{", "'DEBIAN_FRONTEND'", ":", "os", ".", "environ", ".", "get", "(", "'DEBIAN_FRONTEND'", ",", ...
35.210526
0.001456
def interaction( self, frame, tb=None, exception='Wdb', exception_description='Stepping', init=None, shell=False, shell_vars=None, source=None, iframe_mode=False, timeout=None, ...
[ "def", "interaction", "(", "self", ",", "frame", ",", "tb", "=", "None", ",", "exception", "=", "'Wdb'", ",", "exception_description", "=", "'Stepping'", ",", "init", "=", "None", ",", "shell", "=", "False", ",", "shell_vars", "=", "None", ",", "source",...
25.703125
0.001756
def rate_limits(self): """Returns a list of rate limit details.""" if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self.response) return self._rate_limits
[ "def", "rate_limits", "(", "self", ")", ":", "if", "not", "self", ".", "_rate_limits", ":", "self", ".", "_rate_limits", "=", "utilities", ".", "get_rate_limits", "(", "self", ".", "response", ")", "return", "self", ".", "_rate_limits" ]
35
0.009302
async def run(self): """Run the main listener run loop. Doesn't return until :meth:`terminate` is called. """ logger.info(__( "Starting Resolwe listener on channel '{}'.", state.MANAGER_EXECUTOR_CHANNELS.queue )) while not self._should_stop: ...
[ "async", "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "__", "(", "\"Starting Resolwe listener on channel '{}'.\"", ",", "state", ".", "MANAGER_EXECUTOR_CHANNELS", ".", "queue", ")", ")", "while", "not", "self", ".", "_should_stop", ":", "aw...
39.311475
0.001627
def newline(self): """Write eol, then start new line.""" self.write_str(self.eol) self.room = self.maxlinelen
[ "def", "newline", "(", "self", ")", ":", "self", ".", "write_str", "(", "self", ".", "eol", ")", "self", ".", "room", "=", "self", ".", "maxlinelen" ]
32.5
0.015038
def _filter_unscheduled_routers(self, plugin, context, routers): """Filter from list of routers the ones that are not scheduled. Only for release < pike. """ if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]: context, plugin = plugin, context unsc...
[ "def", "_filter_unscheduled_routers", "(", "self", ",", "plugin", ",", "context", ",", "routers", ")", ":", "if", "NEUTRON_VERSION", ".", "version", "[", "0", "]", "<=", "NEUTRON_NEWTON_VERSION", ".", "version", "[", "0", "]", ":", "context", ",", "plugin", ...
43.956522
0.001936
def scale(self): """The absolute scale of a pinch gesture, the scale is the division of the current distance between the fingers and the distance at the start of the gesture. The scale begins at 1.0, and if e.g. the fingers moved together by 50% then the scale will become 0.5, if they move twice as far apart...
[ "def", "scale", "(", "self", ")", ":", "if", "self", ".", "type", "not", "in", "{", "EventType", ".", "GESTURE_PINCH_BEGIN", ",", "EventType", ".", "GESTURE_PINCH_UPDATE", ",", "EventType", ".", "GESTURE_PINCH_END", "}", ":", "raise", "AttributeError", "(", ...
36.193548
0.023438
def shapeRecords(self): """Returns a list of combination geometry/attribute records for all records in a shapefile.""" return ShapeRecords([ShapeRecord(shape=rec[0], record=rec[1]) \ for rec in zip(self.shapes(), self.records())])
[ "def", "shapeRecords", "(", "self", ")", ":", "return", "ShapeRecords", "(", "[", "ShapeRecord", "(", "shape", "=", "rec", "[", "0", "]", ",", "record", "=", "rec", "[", "1", "]", ")", "for", "rec", "in", "zip", "(", "self", ".", "shapes", "(", "...
57.2
0.013793
def parse(s): """ Parses a string into a Tag """ try: m = _regex.match(s) t = Tag(int(m.group('major')), int(m.group('minor')), int(m.group('patch'))) return t \ if m.group('label') is None \ ...
[ "def", "parse", "(", "s", ")", ":", "try", ":", "m", "=", "_regex", ".", "match", "(", "s", ")", "t", "=", "Tag", "(", "int", "(", "m", ".", "group", "(", "'major'", ")", ")", ",", "int", "(", "m", ".", "group", "(", "'minor'", ")", ")", ...
31.714286
0.010941
def make_auth_headers(self, content_type): """Add authorization header.""" headers = self.make_headers(content_type) headers['Authorization'] = 'Basic {}'.format(self.get_auth_string()) return headers
[ "def", "make_auth_headers", "(", "self", ",", "content_type", ")", ":", "headers", "=", "self", ".", "make_headers", "(", "content_type", ")", "headers", "[", "'Authorization'", "]", "=", "'Basic {}'", ".", "format", "(", "self", ".", "get_auth_string", "(", ...
45.6
0.008621
def shell_split(text): """ Split the string `text` using shell-like syntax This avoids breaking single/double-quoted strings (e.g. containing strings with spaces). This function is almost equivalent to the shlex.split function (see standard library `shlex`) except that it is supporting u...
[ "def", "shell_split", "(", "text", ")", ":", "assert", "is_text_string", "(", "text", ")", "# in case a QString is passed...\r", "pattern", "=", "r'(\\s+|(?<!\\\\)\".*?(?<!\\\\)\"|(?<!\\\\)\\'.*?(?<!\\\\)\\')'", "out", "=", "[", "]", "for", "token", "in", "re", ".", "...
41.6875
0.001466
def run(self): has_npm = npm_installation_check() if has_npm: run_npm_install() else: print("Warning: npm not installed using prebuilded js files!", file=sys.stderr) """ Download npm packages required by package.json and extract required ...
[ "def", "run", "(", "self", ")", ":", "has_npm", "=", "npm_installation_check", "(", ")", "if", "has_npm", ":", "run_npm_install", "(", ")", "else", ":", "print", "(", "\"Warning: npm not installed using prebuilded js files!\"", ",", "file", "=", "sys", ".", "std...
45.923077
0.002461
def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[], fields_hidden=[], fields_readonly=[], checkbox_checked_name=b"Yes"): """Generates fdf string from fields specified * pdf_form_url (default: None): just the url for the form. * fdf_data_strings (default: [])...
[ "def", "forge_fdf", "(", "pdf_form_url", "=", "None", ",", "fdf_data_strings", "=", "[", "]", ",", "fdf_data_names", "=", "[", "]", ",", "fields_hidden", "=", "[", "]", ",", "fields_readonly", "=", "[", "]", ",", "checkbox_checked_name", "=", "b\"Yes\"", "...
49.333333
0.00051
def clear(self, objtype=[]): r""" Clears objects from the project entirely or selectively, depdening on the received arguments. Parameters ---------- objtype : list of strings A list containing the object type(s) to be removed. If no types are sp...
[ "def", "clear", "(", "self", ",", "objtype", "=", "[", "]", ")", ":", "if", "len", "(", "objtype", ")", "==", "0", ":", "super", "(", ")", ".", "clear", "(", ")", "else", ":", "names", "=", "[", "obj", ".", "name", "for", "obj", "in", "self",...
35.148148
0.002051
def classical(vulnerability_function, hazard_imls, hazard_poes, loss_ratios): """ :param vulnerability_function: an instance of :py:class:`openquake.risklib.scientific.VulnerabilityFunction` representing the vulnerability function used to compute the curve. :param hazard_imls: ...
[ "def", "classical", "(", "vulnerability_function", ",", "hazard_imls", ",", "hazard_poes", ",", "loss_ratios", ")", ":", "assert", "len", "(", "hazard_imls", ")", "==", "len", "(", "hazard_poes", ")", ",", "(", "len", "(", "hazard_imls", ")", ",", "len", "...
35.285714
0.000788
async def pair_with_device(loop): """Make it possible to pair with device.""" my_zeroconf = Zeroconf() details = conf.AppleTV('127.0.0.1', 'Apple TV') details.add_service(conf.DmapService('login_id')) atv = pyatv.connect_to_apple_tv(details, loop) atv.pairing.pin(PIN_CODE) await atv.pairing...
[ "async", "def", "pair_with_device", "(", "loop", ")", ":", "my_zeroconf", "=", "Zeroconf", "(", ")", "details", "=", "conf", ".", "AppleTV", "(", "'127.0.0.1'", ",", "'Apple TV'", ")", "details", ".", "add_service", "(", "conf", ".", "DmapService", "(", "'...
30.833333
0.001311
def run_instance_jmap(cluster, environ, topology, instance, role=None): ''' :param cluster: :param environ: :param topology: :param instance: :param role: :return: ''' params = dict( cluster=cluster, environ=environ, topology=topology, instance=instance) if role is not None:...
[ "def", "run_instance_jmap", "(", "cluster", ",", "environ", ",", "topology", ",", "instance", ",", "role", "=", "None", ")", ":", "params", "=", "dict", "(", "cluster", "=", "cluster", ",", "environ", "=", "environ", ",", "topology", "=", "topology", ","...
23.04
0.011667
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). ...
[ "def", "probes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Warn user about unhandled parameters", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "[", "'limit'", ",", "'offset'", ",", "'onlyactive'", ",", "'includedeleted'", "]", ":", ...
33.25
0.001328
def vmotion_configured(name, enabled, device='vmk0'): ''' Configures a host's VMotion properties such as enabling VMotion and setting the device VirtualNic that VMotion will use. name Name of the state. enabled Ensures whether or not VMotion should be enabled on a host as a boolean...
[ "def", "vmotion_configured", "(", "name", ",", "enabled", ",", "device", "=", "'vmk0'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "esxi_cmd", "=...
33.542857
0.002069
def get_context_data(self, **kwargs): """Inject STRIPE_PUBLIC_KEY and plans into context_data.""" context = super().get_context_data(**kwargs) context.update( { "STRIPE_PUBLIC_KEY": djstripe_settings.STRIPE_PUBLIC_KEY, "plans": Plan.objects.all(), } ) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "\"STRIPE_PUBLIC_KEY\"", ":", "djstripe_settings", ".",...
28.1
0.037931
def _build_data(self, amplification_group): """ Creates the numpy array tables from the hdf5 tables """ # Determine shape of the tables n_levels = len(amplification_group) # Checks the first group in the amplification group and returns the # shape of the SA array ...
[ "def", "_build_data", "(", "self", ",", "amplification_group", ")", ":", "# Determine shape of the tables", "n_levels", "=", "len", "(", "amplification_group", ")", "# Checks the first group in the amplification group and returns the", "# shape of the SA array - implicitly assumes th...
51.230769
0.000982
def get_res_stats(ds_list, t_srs=None): """Return resolution stats for an input dataset list """ if t_srs is None: t_srs = get_ds_srs(ds_list[0]) res = np.array([get_res(ds, t_srs=t_srs) for ds in ds_list]) #Check that all projections are identical #gt_array = np.array([ds.GetGeoTransfo...
[ "def", "get_res_stats", "(", "ds_list", ",", "t_srs", "=", "None", ")", ":", "if", "t_srs", "is", "None", ":", "t_srs", "=", "get_ds_srs", "(", "ds_list", "[", "0", "]", ")", "res", "=", "np", ".", "array", "(", "[", "get_res", "(", "ds", ",", "t...
33.294118
0.013746
def export_curves_stats(self, aids, key): """ :returns: a dictionary rlzi -> record of dtype loss_curve_dt """ oq = self.dstore['oqparam'] stats = oq.hazard_stats().items() # pair (name, func) stat2idx = {stat[0]: s for s, stat in enumerate(stats)} if 'loss_curve...
[ "def", "export_curves_stats", "(", "self", ",", "aids", ",", "key", ")", ":", "oq", "=", "self", ".", "dstore", "[", "'oqparam'", "]", "stats", "=", "oq", ".", "hazard_stats", "(", ")", ".", "items", "(", ")", "# pair (name, func)", "stat2idx", "=", "{...
46.347826
0.001838
def _GetEntries(self, paths, max_entries, iterator_from_file, is_sequence=False): """Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number...
[ "def", "_GetEntries", "(", "self", ",", "paths", ",", "max_entries", ",", "iterator_from_file", ",", "is_sequence", "=", "False", ")", ":", "entries", "=", "{", "}", "index", "=", "0", "for", "filepath", "in", "paths", ":", "reader", "=", "iterator_from_fi...
36.846154
0.008136
def pos(string, substr, start): """ Find the first occurrence in a string of a substring, starting at a specified location, searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pos_c.html :param string: Any character string. :type string: str :param substr: Substring ...
[ "def", "pos", "(", "string", ",", "substr", ",", "start", ")", ":", "string", "=", "stypes", ".", "stringToCharP", "(", "string", ")", "substr", "=", "stypes", ".", "stringToCharP", "(", "substr", ")", "start", "=", "ctypes", ".", "c_int", "(", "start"...
34.136364
0.001295
def get_vec_tb(self): """Returns vector from top to bottom""" return self.height * self.sin_a(), self.height * self.cos_a()
[ "def", "get_vec_tb", "(", "self", ")", ":", "return", "self", ".", "height", "*", "self", ".", "sin_a", "(", ")", ",", "self", ".", "height", "*", "self", ".", "cos_a", "(", ")" ]
34.25
0.014286
def subscribed(self, build_root, handlers): """Bulk subscribe generator for StreamableWatchmanClient. :param str build_root: the build_root for all subscriptions. :param iterable handlers: a sequence of Watchman.EventHandler namedtuple objects. :yields: a stream of tuples in the form (subscription_name...
[ "def", "subscribed", "(", "self", ",", "build_root", ",", "handlers", ")", ":", "command_list", "=", "[", "[", "'subscribe'", ",", "build_root", ",", "handler", ".", "name", ",", "handler", ".", "metadata", "]", "for", "handler", "in", "handlers", "]", "...
41.037037
0.010582
def show_formats(): """ Print a list of all the file formats that are supported for writing. The file formats are determined by their extensions. Returns ------- None """ fmts = { "ann": "Kvis annotation", "reg": "DS9 regions file", "fits": "FITS Binary Table", ...
[ "def", "show_formats", "(", ")", ":", "fmts", "=", "{", "\"ann\"", ":", "\"Kvis annotation\"", ",", "\"reg\"", ":", "\"DS9 regions file\"", ",", "\"fits\"", ":", "\"FITS Binary Table\"", ",", "\"csv\"", ":", "\"Comma separated values\"", ",", "\"tab\"", ":", "\"ta...
30
0.001242
def get_room_config(self, mucjid): """ Query and return the room configuration form for the given MUC. :param mucjid: JID of the room to query :type mucjid: bare :class:`~.JID` :return: data form template for the room configuration :rtype: :class:`aioxmpp.forms.Data` ...
[ "def", "get_room_config", "(", "self", ",", "mucjid", ")", ":", "if", "mucjid", "is", "None", "or", "not", "mucjid", ".", "is_bare", ":", "raise", "ValueError", "(", "\"mucjid must be bare JID\"", ")", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", ...
28.740741
0.002494
def to_dict(self): """ Return the user as a dict. """ public_keys = [public_key.b64encoded for public_key in self.public_keys] return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos, home_dir=self.home_dir, shell=self.shell, public_keys=p...
[ "def", "to_dict", "(", "self", ")", ":", "public_keys", "=", "[", "public_key", ".", "b64encoded", "for", "public_key", "in", "self", ".", "public_keys", "]", "return", "dict", "(", "name", "=", "self", ".", "name", ",", "passwd", "=", "self", ".", "pa...
65.4
0.015106
def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" f...
[ "def", "do_init", "(", "dev", "=", "False", ",", "requirements", "=", "False", ",", "allow_global", "=", "False", ",", "ignore_pipfile", "=", "False", ",", "skip_lock", "=", "False", ",", "system", "=", "False", ",", "concurrent", "=", "True", ",", "depl...
37.209677
0.002111
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) ...
[ "def", "cached_request", "(", "self", ",", "request", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "logger", ".", "debug", "(", "'Looking up \"%s\" in the cache'", ",", "cache_url", ")", "cc", "=", "self", ".", "pa...
40.418182
0.001537
def cmd_vehicle(self, args): '''handle vehicle commands''' if len(args) < 1: print("Usage: vehicle SYSID[:COMPID]") return a = args[0].split(':') self.mpstate.settings.target_system = int(a[0]) if len(a) > 1: self.mpstate.settings.target_compon...
[ "def", "cmd_vehicle", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "print", "(", "\"Usage: vehicle SYSID[:COMPID]\"", ")", "return", "a", "=", "args", "[", "0", "]", ".", "split", "(", "':'", ")", "self", ".", "...
42.6
0.001837
def get_campus_permissions(calendar_id, campus_code): """ :return: a list of sorted trumba.Permission objects corresponding to the given campus calendar. None if error, [] if not exists raise DataFailureException if the request failed. """ if is_bot(campus_code): re...
[ "def", "get_campus_permissions", "(", "calendar_id", ",", "campus_code", ")", ":", "if", "is_bot", "(", "campus_code", ")", ":", "return", "get_bot_permissions", "(", "calendar_id", ")", "elif", "is_sea", "(", "campus_code", ")", ":", "return", "get_sea_permission...
36
0.001504
def get(object_ids): """Get a remote object or a list of remote objects from the object store. This method blocks until the object corresponding to the object ID is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that has it ...
[ "def", "get", "(", "object_ids", ")", ":", "worker", "=", "global_worker", "worker", ".", "check_connected", "(", ")", "with", "profiling", ".", "profile", "(", "\"ray.get\"", ")", ":", "if", "worker", ".", "mode", "==", "LOCAL_MODE", ":", "# In LOCAL_MODE, ...
41
0.000541
def cli(env): """List all zones.""" manager = SoftLayer.DNSManager(env.client) zones = manager.list_zones() table = formatting.Table(['id', 'zone', 'serial', 'updated']) table.align['serial'] = 'c' table.align['updated'] = 'c' for zone in zones: table.add_row([ zone['id...
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "SoftLayer", ".", "DNSManager", "(", "env", ".", "client", ")", "zones", "=", "manager", ".", "list_zones", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'zone'", ",", ...
23.555556
0.002268
def __vCmdConnectCameras(self, args): '''ToDo: Validate the argument as a valid port''' if len(args) >= 1: self.WirelessPort = args[0] print ("Connecting to Cameras on %s" % self.WirelessPort) self.__vRegisterCameras()
[ "def", "__vCmdConnectCameras", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", ">=", "1", ":", "self", ".", "WirelessPort", "=", "args", "[", "0", "]", "print", "(", "\"Connecting to Cameras on %s\"", "%", "self", ".", "WirelessPort", ...
42.833333
0.01145
def get_graph(self, parse_direction=False): """ Return the networkx directed graph of received data """ g = nx.DiGraph() for way_id, (tags, nodes) in self.ways.items(): # If oneway is '-1', reverse the way and treat as a normal oneway if tags.get('oneway') == '-1': ...
[ "def", "get_graph", "(", "self", ",", "parse_direction", "=", "False", ")", ":", "g", "=", "nx", ".", "DiGraph", "(", ")", "for", "way_id", ",", "(", "tags", ",", "nodes", ")", "in", "self", ".", "ways", ".", "items", "(", ")", ":", "# If oneway is...
39
0.002086
def get_or_add_group(self, nested_names, name_attr='id'): """Get a group from the tree, or add a new one with the given name structure. `nested_names` is a list of strings which represent group names. Each group name will be nested inside of the previous group name. `name_attr`...
[ "def", "get_or_add_group", "(", "self", ",", "nested_names", ",", "name_attr", "=", "'id'", ")", ":", "group", "=", "self", ".", "tree", ".", "getroot", "(", ")", "# Drill down through the names until we find the desired group", "while", "len", "(", "nested_names", ...
41.710526
0.001233
def connect(self, timeout_sec=TIMEOUT_SEC): """Connect to the device. If not connected within the specified timeout then an exception is thrown. """ self._central_manager.connectPeripheral_options_(self._peripheral, None) if not self._connected.wait(timeout_sec): rai...
[ "def", "connect", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_central_manager", ".", "connectPeripheral_options_", "(", "self", ".", "_peripheral", ",", "None", ")", "if", "not", "self", ".", "_connected", ".", "wait", "(", ...
54.714286
0.012853
def _pfp__snapshot(self, recurse=True): """Save off the current value of the field """ if hasattr(self, "_pfp__value"): self._pfp__snapshot_value = self._pfp__value
[ "def", "_pfp__snapshot", "(", "self", ",", "recurse", "=", "True", ")", ":", "if", "hasattr", "(", "self", ",", "\"_pfp__value\"", ")", ":", "self", ".", "_pfp__snapshot_value", "=", "self", ".", "_pfp__value" ]
39.2
0.01
def set_scroll_offset(editor, value): """ Set scroll offset. """ if value is None: editor.show_message('scrolloff=%i' % editor.scroll_offset) else: try: value = int(value) if value >= 0: editor.scroll_offset = value else: ...
[ "def", "set_scroll_offset", "(", "editor", ",", "value", ")", ":", "if", "value", "is", "None", ":", "editor", ".", "show_message", "(", "'scrolloff=%i'", "%", "editor", ".", "scroll_offset", ")", "else", ":", "try", ":", "value", "=", "int", "(", "value...
29.733333
0.002174
def operations(*operations): '''Decorator for marking Resource methods as HTTP operations. This decorator does a number of different things: - It transfer onto itself docstring and annotations from the decorated method, so as to be "transparent" with regards to introspection. - It tra...
[ "def", "operations", "(", "*", "operations", ")", ":", "def", "decorator", "(", "method", ")", ":", "def", "wrapper", "(", "cls", ",", "request", ",", "start_response", ",", "*", "*", "kwargs", ")", ":", "result_cache", "=", "[", "]", "try", ":", "yi...
48.052632
0.000537
def relaxNGValidatePushCData(self, data, len): """check the CData parsed for validation in the current stack """ ret = libxml2mod.xmlRelaxNGValidatePushCData(self._o, data, len) return ret
[ "def", "relaxNGValidatePushCData", "(", "self", ",", "data", ",", "len", ")", ":", "ret", "=", "libxml2mod", ".", "xmlRelaxNGValidatePushCData", "(", "self", ".", "_o", ",", "data", ",", "len", ")", "return", "ret" ]
52.25
0.009434
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
[ "def", "setup", "(", "self", ")", ":", "self", ".", "allow", "=", "self", ".", "config", "[", "'allow'", "]", "self", ".", "halt", "=", "self", ".", "config", "[", "'halt'", "]", "self", ".", "skip", "=", "self", ".", "config", "[", "'skip'", "]"...
29.166667
0.011111
def automatic_parser(result, dtypes={}, converters={}): """ Try and automatically convert strings formatted as tables into nested list structures. Under the hood, this function essentially applies the genfromtxt function to all files in the output, and passes it the additional kwargs. Args: ...
[ "def", "automatic_parser", "(", "result", ",", "dtypes", "=", "{", "}", ",", "converters", "=", "{", "}", ")", ":", "np", ".", "seterr", "(", "all", "=", "'raise'", ")", "parsed", "=", "{", "}", "for", "filename", ",", "contents", "in", "result", "...
38.258065
0.000822
def set_api_version(self, major, minor): """Set the API version this module was designed for. Each module must declare the mib12 API version it was compiled with as a 2 byte major.minor number. This information is used by the pic12_executive to decide whether the application is compati...
[ "def", "set_api_version", "(", "self", ",", "major", ",", "minor", ")", ":", "if", "not", "self", ".", "_is_byte", "(", "major", ")", "or", "not", "self", ".", "_is_byte", "(", "minor", ")", ":", "raise", "ArgumentError", "(", "\"Invalid API version number...
45.846154
0.008224
def detach(self): """ Detaches this Volume if it is attached """ self._client.post('{}/detach'.format(Volume.api_endpoint), model=self) return True
[ "def", "detach", "(", "self", ")", ":", "self", ".", "_client", ".", "post", "(", "'{}/detach'", ".", "format", "(", "Volume", ".", "api_endpoint", ")", ",", "model", "=", "self", ")", "return", "True" ]
26
0.010638
def hideEvent(self, event): """Override hide event to stop waiting spinner.""" QWidget.hideEvent(self, event) self.spinner.stop()
[ "def", "hideEvent", "(", "self", ",", "event", ")", ":", "QWidget", ".", "hideEvent", "(", "self", ",", "event", ")", "self", ".", "spinner", ".", "stop", "(", ")" ]
38.25
0.012821
def _submit(self, client, config, osutil, request_executor, transfer_future): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer ma...
[ "def", "_submit", "(", "self", ",", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "transfer_future", ")", ":", "# Determine the size if it was not provided", "if", "transfer_future", ".", "meta", ".", "size", "is", "None", ":", "# If a size...
45.792453
0.00121
async def get_counts(self): """ see :class:`datasketch.MinHashLSH`. """ fs = (hashtable.itemcounts() for hashtable in self.hashtables) return await asyncio.gather(*fs)
[ "async", "def", "get_counts", "(", "self", ")", ":", "fs", "=", "(", "hashtable", ".", "itemcounts", "(", ")", "for", "hashtable", "in", "self", ".", "hashtables", ")", "return", "await", "asyncio", ".", "gather", "(", "*", "fs", ")" ]
33.666667
0.009662
def features(self): """ The set of features supported by this MUC. This may vary depending on features exported by the MUC service, so be sure to check this for each individual MUC. """ return { aioxmpp.im.conversation.ConversationFeature.BAN, aio...
[ "def", "features", "(", "self", ")", ":", "return", "{", "aioxmpp", ".", "im", ".", "conversation", ".", "ConversationFeature", ".", "BAN", ",", "aioxmpp", ".", "im", ".", "conversation", ".", "ConversationFeature", ".", "BAN_WITH_KICK", ",", "aioxmpp", ".",...
47
0.002317
def _parse_data(self, data, charset): """ Parse the data :param data: the data (may be None) """ return self._decode_data(data, charset) if data else u''
[ "def", "_parse_data", "(", "self", ",", "data", ",", "charset", ")", ":", "return", "self", ".", "_decode_data", "(", "data", ",", "charset", ")", "if", "data", "else", "u''" ]
25.857143
0.010695
def load_embedding(path): ''' return embedding for a specific file by given file path. ''' EMBEDDING_DIM = 300 embedding_dict = {} with open(path, 'r', encoding='utf-8') as file: pairs = [line.strip('\r\n').split() for line in file.readlines()] for pair in pairs: if l...
[ "def", "load_embedding", "(", "path", ")", ":", "EMBEDDING_DIM", "=", "300", "embedding_dict", "=", "{", "}", "with", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "file", ":", "pairs", "=", "[", "line", ".", "strip", "...
38.461538
0.001953
def map_regions(self, map_col, agg=None, copy_col=None, fname=None, region_col=None, remove_duplicates=False, inplace=False): """Plot regional data for a single model, scenario, variable, and year see pyam.plotting.region_plot() for all available options Parameters ...
[ "def", "map_regions", "(", "self", ",", "map_col", ",", "agg", "=", "None", ",", "copy_col", "=", "None", ",", "fname", "=", "None", ",", "region_col", "=", "None", ",", "remove_duplicates", "=", "False", ",", "inplace", "=", "False", ")", ":", "models...
42.056818
0.000792
def delimited_file( self, hdfs_dir, schema, name=None, database=None, delimiter=',', na_rep=None, escapechar=None, lineterminator=None, external=True, persist=False, ): """ Interpret delimited text files (CSV / T...
[ "def", "delimited_file", "(", "self", ",", "hdfs_dir", ",", "schema", ",", "name", "=", "None", ",", "database", "=", "None", ",", "delimiter", "=", "','", ",", "na_rep", "=", "None", ",", "escapechar", "=", "None", ",", "lineterminator", "=", "None", ...
31.629032
0.001484
def str_cmd(cmd, cwd, env): """ Runs the command and returns its stdout and stderr. """ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env) stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process) process.wait() s...
[ "def", "str_cmd", "(", "cmd", ",", "cwd", ",", "env", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "cwd", "=", "cwd", ",", "env"...
44.7
0.015351
def forward(self, x): """Returns a list of outputs for tasks 0,...t-1 Args: x: a [batch_size, ...] batch from X """ head_outputs = [None] * self.t # Execute input layer if isinstance(self.input_layer, list): # One input_module per task input_out...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "head_outputs", "=", "[", "None", "]", "*", "self", ".", "t", "# Execute input layer", "if", "isinstance", "(", "self", ".", "input_layer", ",", "list", ")", ":", "# One input_module per task", "input_output...
39.357143
0.001771
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None): """Private method to delete a specified state from the LRS :param activity: Activity object of state to be deleted :type activity: :class:`tincan.activity.Activity` :param agent: Agent object of state...
[ "def", "_delete_state", "(", "self", ",", "activity", ",", "agent", ",", "state_id", "=", "None", ",", "registration", "=", "None", ",", "etag", "=", "None", ")", ":", "if", "not", "isinstance", "(", "activity", ",", "Activity", ")", ":", "activity", "...
35.302326
0.001923
def plot_masks(mask_1, mask_2, mask_3): """Plots three masks""" fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5)) for ax in [ax1, ax2, ax3]: ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax1.set_title("Type 1") ax1.imshow(mask_1, cmap='viridis') ax2.set_ti...
[ "def", "plot_masks", "(", "mask_1", ",", "mask_2", ",", "mask_3", ")", ":", "fig", ",", "(", "(", "ax1", ",", "ax2", ",", "ax3", ")", ")", "=", "plt", ".", "subplots", "(", "1", ",", "3", ",", "figsize", "=", "(", "12", ",", "5", ")", ")", ...
32.214286
0.002155
def main(): """ Start the GUI :return: """ app = QApplication(sys.argv) rlbot_icon = QtGui.QIcon(os.path.join(get_rlbot_directory(), 'img', 'rlbot_icon.png')) app.setWindowIcon(rlbot_icon) window = RLBotQTGui() window.show() app.exec_()
[ "def", "main", "(", ")", ":", "app", "=", "QApplication", "(", "sys", ".", "argv", ")", "rlbot_icon", "=", "QtGui", ".", "QIcon", "(", "os", ".", "path", ".", "join", "(", "get_rlbot_directory", "(", ")", ",", "'img'", ",", "'rlbot_icon.png'", ")", "...
27.818182
0.009494
def _read_info(info_path): """Returns info dict or None.""" if not tf.io.gfile.exists(info_path): return None with tf.io.gfile.GFile(info_path) as info_f: return json.load(info_f)
[ "def", "_read_info", "(", "info_path", ")", ":", "if", "not", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "info_path", ")", ":", "return", "None", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "info_path", ")", "as", "info_f", ":...
31.333333
0.020725
def chunk(self, chunks=None, name=None, lock=False): """Coerce this array's data into a dask arrays with the given chunks. If this variable is a non-dask array, it will be converted to dask array. If it's a dask array, it will be rechunked to the given chunk sizes. If neither c...
[ "def", "chunk", "(", "self", ",", "chunks", "=", "None", ",", "name", "=", "None", ",", "lock", "=", "False", ")", ":", "import", "dask", ".", "array", "as", "da", "if", "utils", ".", "is_dict_like", "(", "chunks", ")", ":", "chunks", "=", "dict", ...
40.188679
0.000917
def fillRectangle(self, x, y, width, height, color): """fill the area with the color. the color is a string in the pixel format set up earlier""" #fallback variant, use update recatngle #override with specialized function for better performance self.updateRectangle(x, y, width...
[ "def", "fillRectangle", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ")", ":", "#fallback variant, use update recatngle", "#override with specialized function for better performance", "self", ".", "updateRectangle", "(", "x", ",", "y", ...
57.333333
0.011461
def addColumn(self, column): """ Adds the inputted column to this table schema. :param column | <orb.Column> """ column.setSchema(self) self.__columns[column.name()] = column
[ "def", "addColumn", "(", "self", ",", "column", ")", ":", "column", ".", "setSchema", "(", "self", ")", "self", ".", "__columns", "[", "column", ".", "name", "(", ")", "]", "=", "column" ]
27.75
0.008734
def set_org(self, value, lineno): """ Sets a new ORG value """ if value < 0 or value > MAX_MEM: error(lineno, "Memory ORG out of range [0 .. 65535]. Current value: %i" % value) self.index = self.ORG = value
[ "def", "set_org", "(", "self", ",", "value", ",", "lineno", ")", ":", "if", "value", "<", "0", "or", "value", ">", "MAX_MEM", ":", "error", "(", "lineno", ",", "\"Memory ORG out of range [0 .. 65535]. Current value: %i\"", "%", "value", ")", "self", ".", "in...
35
0.011952
def _do_unzip(zipped_file, output_directory): """Perform the actual uncompression.""" z = zipfile.ZipFile(zipped_file) for path in z.namelist(): relative_path = os.path.join(output_directory, path) dirname, dummy = os.path.split(relative_path) try: if relative_path.endswi...
[ "def", "_do_unzip", "(", "zipped_file", ",", "output_directory", ")", ":", "z", "=", "zipfile", ".", "ZipFile", "(", "zipped_file", ")", "for", "path", "in", "z", ".", "namelist", "(", ")", ":", "relative_path", "=", "os", ".", "path", ".", "join", "("...
43.263158
0.00119
def shepp_logan(space, modified=False, min_pt=None, max_pt=None): """Standard Shepp-Logan phantom in 2 or 3 dimensions. Parameters ---------- space : `DiscreteLp` Space in which the phantom is created, must be 2- or 3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding slic...
[ "def", "shepp_logan", "(", "space", ",", "modified", "=", "False", ",", "min_pt", "=", "None", ",", "max_pt", "=", "None", ")", ":", "ellipsoids", "=", "shepp_logan_ellipsoids", "(", "space", ".", "ndim", ",", "modified", ")", "return", "ellipsoid_phantom", ...
41.219512
0.000578
def RandomStandardNormal(shape, dtype, seed): """ Standard (mu=0, sigma=1) gaussian op. """ if seed: np.random.seed(seed) return np.random.normal(size=reduce(mul, shape)).reshape(shape).astype(dtype_map[dtype]),
[ "def", "RandomStandardNormal", "(", "shape", ",", "dtype", ",", "seed", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "return", "np", ".", "random", ".", "normal", "(", "size", "=", "reduce", "(", "mul", ",", "sha...
33.285714
0.008368
def get_services(self): """Get all services.""" self.request(EP_GET_SERVICES) return {} if self.last_response is None else self.last_response.get('payload').get('services')
[ "def", "get_services", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_SERVICES", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", ...
48.25
0.015306
def pad_add(av, size=None, stlen=10): """ Perform linear padding for complex array The input array `av` is padded with a linear ramp starting at the edges and going outwards to an average value computed from a band of thickness `stlen` at the outer boundary of the array. Pads will only be appended...
[ "def", "pad_add", "(", "av", ",", "size", "=", "None", ",", "stlen", "=", "10", ")", ":", "if", "size", "is", "None", ":", "size", "=", "list", "(", ")", "for", "s", "in", "av", ".", "shape", ":", "size", ".", "append", "(", "int", "(", "2", ...
32.659091
0.000676
def connect(url='https://gitlab.com', token=None): """ Return a connected GitLab session ``token`` should be a ``private_token`` from Gitlab """ if token is None: token = os.environ.get('GITLAB_API_TOKEN', None) gl_session = gitlab.Gitlab(url, token) try: gl_session.versi...
[ "def", "connect", "(", "url", "=", "'https://gitlab.com'", ",", "token", "=", "None", ")", ":", "if", "token", "is", "None", ":", "token", "=", "os", ".", "environ", ".", "get", "(", "'GITLAB_API_TOKEN'", ",", "None", ")", "gl_session", "=", "gitlab", ...
24.75
0.001946
def get_stores(self): """Return a list with number of stored cache lines per memory hierarchy level.""" return [self.stats[cache_level]['STORE_count']/self.first_dim_factor for cache_level in range(len(self.machine['memory hierarchy']))]
[ "def", "get_stores", "(", "self", ")", ":", "return", "[", "self", ".", "stats", "[", "cache_level", "]", "[", "'STORE_count'", "]", "/", "self", ".", "first_dim_factor", "for", "cache_level", "in", "range", "(", "len", "(", "self", ".", "machine", "[", ...
66.5
0.01487
def find_jar(jar_name, root_path=None): """ Look for the named jar in: #. ``root_path``, if specified #. working directory -- ``PWD`` #. ``${PWD}/build`` #. ``/usr/share/java`` Return the full path of the jar if found; else return :obj:`None`. """ jar_name = os.path.basename(jar_na...
[ "def", "find_jar", "(", "jar_name", ",", "root_path", "=", "None", ")", ":", "jar_name", "=", "os", ".", "path", ".", "basename", "(", "jar_name", ")", "root", "=", "root_path", "or", "os", ".", "getcwd", "(", ")", "paths", "=", "(", "root", ",", "...
28.052632
0.001815
def element(cls, name, parent=None, interleave=None, occur=0): """Create an element node.""" node = cls("element", parent, interleave=interleave) node.attr["name"] = name node.occur = occur return node
[ "def", "element", "(", "cls", ",", "name", ",", "parent", "=", "None", ",", "interleave", "=", "None", ",", "occur", "=", "0", ")", ":", "node", "=", "cls", "(", "\"element\"", ",", "parent", ",", "interleave", "=", "interleave", ")", "node", ".", ...
39.333333
0.008299
def _strip_marker_elem(elem_name, elements): """Remove the supplied element from the marker. This is not a comprehensive implementation, but relies on an important characteristic of metadata generation: The element's operand is always associated with an "and" operator. This means that we can simply rem...
[ "def", "_strip_marker_elem", "(", "elem_name", ",", "elements", ")", ":", "extra_indexes", "=", "[", "]", "preceding_operators", "=", "[", "\"and\"", "]", "if", "elem_name", "==", "\"extra\"", "else", "[", "\"and\"", ",", "\"or\"", "]", "for", "i", ",", "e...
42.862069
0.000787
def save(self, location=None): """ Saves the current status of the metadata This saves the metadata at the location of the previously loaded metadata or at the file/path given in location. Specify a location if the metadata should be stored in a different location or was never ...
[ "def", "save", "(", "self", ",", "location", "=", "None", ")", ":", "if", "location", ":", "location", "=", "Path", "(", "location", ")", "if", "os", ".", "path", ".", "splitext", "(", "str", "(", "location", ")", ")", "[", "1", "]", "==", "''", ...
39.129032
0.001609
def to_delete(datetimes, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, firstweekday=SATURDAY, now=None): """ Return a set of datetimes that should be deleted, out of ``datetimes``. See ``to_keep`` for a description of arguments. """ dat...
[ "def", "to_delete", "(", "datetimes", ",", "years", "=", "0", ",", "months", "=", "0", ",", "weeks", "=", "0", ",", "days", "=", "0", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ",", "firstweekday", "=", "SATURDAY"...
42
0.001553