Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
359,200
def get_ipv6_neighbors_table(self): ipv6_neighbors_table = [] command = "show ipv6 neighbors" output = self._send_command(command) ipv6_neighbors = "" fields = re.split(r"^IPv6\s+Address.*Interface$", output, flags=(re.M | re.I)) if len(fields) == 2: ...
Get IPv6 neighbors table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) in seconds * state (string) For example:: [ { ...
359,201
def updateQTable( self, reward, current_state ): old_q = self.q_table[self.prev_s][self.prev_a] new_q = old_q self.q_table[self.prev_s][self.prev_a] = new_q
Change q_table to reflect what we have learnt.
359,202
def get_stack_data(self, frame, traceback, event_type): heap_data = Heap(self.options) stack_data = StackFrames(self.options) stack_frames, cur_frame_ind = self.get_stack(frame, traceback) for frame_ind, (frame, lineno) in enumerate(stack_frames): skip_this_stack = ...
Get the stack frames data at each of the hooks above (Ie. for each line of the Python code)
359,203
def _ffi_module(self): native_bin_dir = os.path.dirname(self.binary) logger.debug(, native_bin_dir) sys.path.insert(0, native_bin_dir) return importlib.import_module(NATIVE_ENGINE_MODULE)
Load the native engine as a python module and register CFFI externs.
359,204
def filter_benchmarks(benchmarks, bench_funcs, base_ver): for bm in list(benchmarks): func = bench_funcs[bm] if getattr(func, , False) and (3, 0) <= base_ver: benchmarks.discard(bm) logging.info("Skipping Python2-only benchmark %s; " "not compati...
Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The filtered set of benchmark names
359,205
def _write_config_file(items, global_vars, template, project_name, out_dir, remotes): config_dir = utils.safe_makedir(os.path.join(out_dir, "config")) out_config_file = os.path.join(config_dir, "%s.yaml" % project_name) out = {"fc_name": project_name, "upload": {"dir":...
Write configuration file, adding required top level attributes.
359,206
def write(self, path, data, offset=0, timeout=0): if not isinstance(data, (bytes, bytearray, )): raise TypeError(" argument must be binary") ret, rdata = self.sendmess(MSG_WRITE, str2bytez(path) + data, size=len(data), offset=offset, ...
write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding.
359,207
def flatFieldFromCloseDistance(imgs, bg_imgs=None): Method A img = imgAverage(imgs) bg = getBackground2(bg_imgs, img) img -= bg img = toGray(img) mx = median_filter(img[::10, ::10], 3).max() img /= mx return img
Average multiple images of a homogeneous device imaged directly in front the camera lens. if [bg_imgs] are not given, background level is extracted from 1% of the cumulative intensity distribution of the averaged [imgs] This measurement method is referred as 'Method A' in --- ...
359,208
def savez_two_column(matrix, row_offset, file_name, append=False): logging.info("Saving obj to file in two column .npz format %s.", file_name) tc = [] for u, items in enumerate(matrix): user = row_offset + u for item in items: tc.append([user, item]) np.savez_compressed(file_name, np.asarray...
Savez_compressed obj to file_name.
359,209
def DbGetPropertyHist(self, argin): self._log.debug("In DbGetPropertyHist()") object_name = argin[0] prop_name = argin[1] return self.db.get_property_hist(object_name, prop_name)
Retrieve object property history :param argin: Str[0] = Object name Str[2] = Property name :type: tango.DevVarStringArray :return: Str[0] = Property name Str[1] = date Str[2] = Property value number (array case) Str[3] = Property value 1 Str[n] = Propert...
359,210
def delete_customer(self, handle): self.request(E.deleteCustomerRequest(E.handle(handle))) return True
Delete a customer.
359,211
async def send_webmention(self, entry, url): if (entry.url, url) in self._processed_mentions: LOGGER.debug( "Skipping already processed mention %s -> %s", entry.url, url) self._processed_mentions.add((entry.url, url)) LOGGER.debug("++WAIT: webmentions.get_t...
send a webmention from an entry to a URL
359,212
def timed_cache(timeout, max_size=128): def actual_decorator(func): return _cached_func(func, caches.TimeoutCache, timeout, max_size=max_size) return actual_decorator
Time based decorator, implementing :class:`faste.caches.TimeoutCache` :param int timeout: Cache key timeout :param int max_size: (keyword) max size.
359,213
def Morsi_Alexander(Re): r if Re < 0.1: return 24./Re elif Re < 1: return 22.73/Re + 0.0903/Re**2 + 3.69 elif Re < 10: return 29.1667/Re - 3.8889/Re**2 + 1.222 elif Re < 100: return 46.5/Re - 116.67/Re**2 + 0.6167 elif Re < 1000: return 98.33/Re - 2778./Re...
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} & \mbox{if $Re < 0.1$}\\ \frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\ \frac{29.1667}{Re}-\frac{3....
359,214
def vinet_dPdV(v, v0, k0, k0p, precision=1.e-5): def f_scalar(v, v0, k0, k0p, precision=1.e-5): return derivative(vinet_p, v, args=(v0, k0, k0p), dx=v0 * precision) f_v = np.vectorize(f_scalar, excluded=[1, 2, 3, 4]) return f_v(v, v0, k0, k0p, precision=precision)
calculate dP/dV for numerical calculation of bulk modulus according to test this differs from analytical result by 1.e-5 :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at r...
359,215
def _save_and_log_checkpoint(self, actor): actor_id = self._worker.actor_id checkpoint_info = self._worker.actor_checkpoint_info[actor_id] checkpoint_info.num_tasks_since_last_checkpoint += 1 now = int(1000 * time.time()) checkpoint_context = ray.actor.CheckpointContext(...
Save an actor checkpoint if necessary and log any errors. Args: actor: The actor to checkpoint. Returns: The result of the actor's user-defined `save_checkpoint` method.
359,216
def dict(self): d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs if p.key not in ()} d[] = if self.secret_password: try: d[] = self.decrypt_secret() except AccountDecryptionError: pass if self.data: ...
A dict that holds key/values for all of the properties in the object. :return:
359,217
def _convert_series(self, metric, ts): series = monitoring_v3.types.TimeSeries() series.metric.type = self.get_metric_type(metric.descriptor) for lk, lv in self.options.default_monitoring_labels.items(): series.metric.labels[lk.key] = lv.value for key, val in zip(m...
Convert an OC timeseries to a SD series.
359,218
def get_object(cls, api_token, droplet_id): droplet = cls(token=api_token, id=droplet_id) droplet.load() return droplet
Class method that will return a Droplet object by ID. Args: api_token (str): token droplet_id (int): droplet id
359,219
def update(self): s data GET', url=self.API )._json
Update our object's data
359,220
def _process_gxd_genotype_view(self, limit=None): line_counter = 0 if self.test_mode: graph = self.testgraph else: graph = self.graph geno = Genotype(graph) model = Model(graph) raw = .join((self.rawdir, )) LOG.info("getting gen...
This table indicates the relationship between a genotype and it's background strain. It leverages the Genotype class methods to do this. Makes these triples: <MGI:genotypeid> GENO:has_reference_part <MGI:strainid> <MGI:strainid> a GENO:genomic_background If the genotyp...
359,221
def main(handwriting_datasets_file, analyze_features): logging.info("Start loading data ...", handwriting_datasets_file) loaded = pickle.load(open(handwriting_datasets_file)) raw_datasets = loaded[] logging.info("%i datasets loaded.", len(raw_datasets)) logging.info("Start analyzing...") ...
Start the creation of the wanted metric.
359,222
def connect_amqp_by_unit(self, sentry_unit, ssl=False, port=None, fatal=True, username="testuser1", password="changeme"): host = sentry_unit.info[] unit_name = sentry_unit.info[] if ssl and not port: port = ...
Establish and return a pika amqp connection to the rabbitmq service running on a rmq juju unit. :param sentry_unit: sentry unit pointer :param ssl: boolean, default to False :param port: amqp port, use defaults if None :param fatal: boolean, default to True (raises on connect er...
359,223
def compute_statistic(self, layout): data = self.data if not len(data): return type(data)() params = self.stat.setup_params(data) data = self.stat.use_defaults(data) data = self.stat.setup_data(data) data = self.stat.compute_layer(data, params, layou...
Compute & return statistics for this layer
359,224
def _get_localzone(_root=): tzenv = os.environ.get() if tzenv: try: return _tz_from_env(tzenv) except pytz.UnknownTimeZoneError: pass for configfile in (, ): tzpath = os.path.join(_root, configfile) if os.path.exists(tzpath): ...
Tries to find the local timezone configuration. This method prefers finding the timezone name and passing that to pytz, over passing in the localtime file, as in the later case the zoneinfo name is unknown. The parameter _root makes the function look for files like /etc/localtime beneath the _root...
359,225
def data_to_tfrecord(images, labels, filename): if os.path.isfile(filename): print("%s exists" % filename) return print("Converting data into %s ..." % filename) writer = tf.python_io.TFRecordWriter(filename) for index, img in enumerate(images): img_raw = img.tobytes() ...
Save data into TFRecord.
359,226
def reverse( self, query, exactly_one=DEFAULT_SENTINEL, timeout=DEFAULT_SENTINEL, feature_code=None, lang=None, find_nearby_type=, ): if exactly_one is DEFAULT_SENTINEL: warnings.warn( ...
Return an address by location point. .. versionadded:: 1.2.0 :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latit...
359,227
def ensure_json_content_type(req, app): res = req.get_response(app, catch_exc_info=True) res.content_type = return res
ErrorMiddleware returns hard-coded content-type text/html. Here we force it to be application/json.
359,228
def get_plugins(package_name, paths=None): pkg = get_latest_package(package_name, paths=paths, error=True) if not pkg.has_plugins: return [] it = iter_package_families(paths) package_names = set(x.name for x in it) bar = ProgressBar("Searching", len(package_names)) plugin_pkgs = [...
Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages that are plugins of the given package.
359,229
def get_state(self): return {"started": (True if self.background_process and self.background_process.is_alive() else False), "paused": self._pause.value, "stopped": self._end.value, "tasks": len(self.current_tasks), ...
Get general information about the state of the class
359,230
def parse_nni_variable(code): name, call = parse_annotation_function(code, ) assert len(call.args) == 1, arg = call.args[0] assert type(arg) is ast.Call, assert type(arg.func) is ast.Attribute, assert type(arg.func.value) is ast.Name, assert arg.func.value.id == , name_str = ...
Parse `nni.variable` expression. Return the name argument and AST node of annotated expression. code: annotation string
359,231
def _get_env(self, key): if self._env_key_replacer is not None: key = key.replace(*self._env_key_replacer) return os.getenv(key)
Wrapper around os.getenv() which replaces characters in the original key. This allows env vars which have different keys than the config object keys.
359,232
def _cast_to_type(self, value): if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) return value try: value = date_parser(value) ...
Convert the value to a datetime and raise error on failures
359,233
def _generate_barcode_ids(info_iter): bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode_ids
Create unique barcode IDs assigned to sequences
359,234
def safe_format_sh(s, **kwargs): to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
:type s str
359,235
def hot_questions(self): from .question import Question hot_questions_url = Topic_Hot_Questions_Url.format(self.id) params = {: 0, : self.xsrf} res = self._session.get(hot_questions_url) soup = BeautifulSoup(res.content) while True: questions_duplicat...
获取话题下热门的问题 :return: 话题下的热门动态中的问题,按热门度顺序返回生成器 :rtype: Question.Iterable
359,236
def set_release_actions(self, actions): self.release_actions = actions self.option_widget = self.release_actions.option_widget() if self.option_widget: self.option_vbox.addWidget(self.option_widget) self.option_gb.setVisible(True)
Set the widget that gives users options about the release, e.g. importing references :param actions: Release actions that define the sanity checks and cleanup actions :type actions: :class:`jukeboxcore.release.ReleaseActions` :returns: None :rtype: None :raises: None
359,237
def get_adjacent_pathways(self, pathway): vertex_id = self.pathways[pathway] adjacent = self.vertices[vertex_id].get_adjacent_vertex_ids() adjacent_pathways = [] for adjacent_id in adjacent: adjacent_pathways.append(self.get_pathway_from_vertex_id( ad...
Get the pathways adjacent to this pathway in the network Parameters ----------- pathway : str Returns ----------- list(str), a list of pathways adjacent to the input pathway
359,238
def remove_properties(self): node_prop = self.node.find() if node_prop is not None: self.node.remove(node_prop)
Removes the property layer, if exists
359,239
def QA_fetch_get_future_transaction(code, start, end, retry=4, ip=None, port=None): ip, port = get_extensionmarket_ip(ip, port) apix = TdxExHq_API() global extension_market_list extension_market_list = QA_fetch_get_extensionmarket_list( ) if extension_market_list is None else extension_market_l...
期货历史成交分笔
359,240
def ecs_idsKEGG(organism): kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read() kegg_ec=kegg_ec.split("\n") final=[] for k in kegg_ec: final.append(k.split("\t")) df=pd.DataFrame(final[0:len(final)-1])[[0,1]] df.columns=[,] return df
Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism :param organism: an organisms as listed in organismsKEGG() :returns: a Pandas dataframe of with 'ec' and 'KEGGid'.
359,241
def save_collection(png_filename_base, numpy_data, start_layers_at=1): file_ext = png_filename_base.split()[-1] if file_ext in []: file_base = .join(png_filename_base.split()[:-1]) else: output_files = [] i = start_layers_at for layer in numpy_...
Export a numpy array to a set of png files, with each Z-index 2D array as its own 2D file. Arguments: png_filename_base: A filename template, such as "my-image-*.png" which will lead to a collection of files named "my-image-0.png", "my...
359,242
def switch_to_window(self, window_name=None, title=None, url=None): if window_name: self.switch_to.window(window_name) return if url: url = self.get_url(path=url) for window_handle in self.window_handles: self.switch_to.window(window_han...
WebDriver implements switching to other window only by it's name. With wrapper there is also option to switch by title of window or URL. URL can be also relative path.
359,243
def dfa_to_dot(dfa: dict, name: str, path: str = ): g = graphviz.Digraph(format=) g.node(, style=) for state in dfa[]: if state == dfa[]: if state in dfa[]: g.node(str(state), root=, shape=) else: g.node(str(state), ...
Generates a DOT file and a relative SVG image in **path** folder of the input DFA using graphviz library. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the DOT/SVG files (default: working directory)
359,244
def flattening(Pot,R,z): return nu.sqrt(nu.fabs(z/R*evaluateRforces(Pot,R,z,use_physical=False)\ /evaluatezforces(Pot,R,z,use_physical=False)))
NAME: flattening PURPOSE: calculate the potential flattening, defined as sqrt(fabs(z/R F_R/F_z)) INPUT: Pot - Potential instance or list thereof R - Galactocentric radius (can be Quantity) z - height (can be Quantity) OUTPUT: ...
359,245
def set_error(self, error_shortmsg: str, error_longmsg: str): LOG.error(f"Update session: error in stage {self._stage.name}: " f"{error_shortmsg}: {error_longmsg}") self._error = Value(error_shortmsg, error_longmsg) self.set_stage(Stages.ERROR)
Set the stage to error and add a message
359,246
def get_points(self): return [(k, self.runtime._ring[k]) for k in self.runtime._keys]
Returns a ketama compatible list of (position, nodename) tuples.
359,247
def get_column_type(column, column_values): try: return _get_column_type_heur(column, column_values) except util.TableDefinitionError as e: logging.error("Column type couldn't be determined: {}".format(e.message)) return ColumnType.text, None, None, 1
Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the column - the concrete ColumnType is stored in the attrib...
359,248
def _notifyDone(self): if self.notified: return self.doneevent.set() for buid in self.mybldgbuids: del self.allbldgbuids[buid] self.notified = True
Allow any other editatoms waiting on me to complete to resume
359,249
def pkill(): if env(): return 1 cmd = ["ps -aux | grep fio | grep -v grep"] status, _, _ = cij.ssh.command(cmd, shell=True, echo=False) if not status: status, _, _ = cij.ssh.command(["pkill -f fio"], shell=True) if status: return 1 return 0
Kill all of FIO processes
359,250
def _read_syntax_quoted(ctx: ReaderContext) -> ReaderForm: start = ctx.reader.advance() assert start == "`" with ctx.syntax_quoted(): return _process_syntax_quoted_form(ctx, _read_next_consuming_comment(ctx))
Read a syntax-quote and set the syntax-quoting state in the reader.
359,251
def dump2sqlite(records, output_file): results_keys = list(records.results[0].keys()) pad_data = [] for key in REQUIRED_KEYS: if key not in results_keys: results_keys.append(key) pad_data.append("") conn = sqlite3.connect(os.path.expanduser(output_file), detect_typ...
Dumps tests results to database.
359,252
def land_address(self): pattern = self.random_element(self.land_address_formats) return self.generator.parse(pattern)
:example 세종특별자치시 어진동 507
359,253
def get_long_description(): here = path.abspath(path.dirname(__file__)) with open(path.join(here, )) as readme: return readme.read() return None
Read the long description.
359,254
def handle_callback_exception(self, callback): if self._error_handler: self._error_handler(callback) else: app_log.error("Exception in callback %r", callback, exc_info=True)
This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sy...
359,255
def time2isoz(t=None): if t is None: dt = datetime.datetime.utcnow() else: dt = datetime.datetime.utcfromtimestamp(t) return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
Return a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:3...
359,256
def move_if_not_on_dow(original, replacement, dow_not_orig, dow_replacement): return lambda x: ( (x.hdate.day == original and x.gdate.weekday() != dow_not_orig) or (x.hdate.day == replacement and x.gdate.weekday() == dow_replacement))
Return a lambda function. Lambda checks that either the original day does not fall on a given weekday, or that the replacement day does fall on the expected weekday.
359,257
def set_tenant(self, tenant, include_public=True): self.set_schema(tenant.schema_name, include_public) self.tenant = tenant
Main API method to current database schema, but it does not actually modify the db connection.
359,258
def cli(env): mgr = SoftLayer.ObjectStorageManager(env.client) accounts = mgr.list_accounts() table = formatting.Table([, , ]) table.sortby = api_type = None for account in accounts: if in account and account[] == : api_type = elif in account[][]: ...
List object storage accounts.
359,259
async def get_top_clans(self): url = self.BASE + data = await self.request(url) return [ClanInfo(self, c) for c in data.get()]
Get a list of top clans, info is only brief, call get_clan() on each of the ClanInfo objects to get full clan info
359,260
def get_device(self, device_id, refresh=False): if self._devices is None: self.get_devices() refresh = False device = self._devices.get(device_id) if device and refresh: device.refresh() return device
Get a single device.
359,261
def format_location(ctx, text): text = conversions.to_string(text, ctx) return text.split(">")[-1].strip()
Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary
359,262
def compute_average_regress(x, idx_chan): if x.ndim != 2: raise ValueError(f) x = moveaxis(x, idx_chan, 0) avg = mean(x, axis=0) x_o = [] for i in range(x.shape[0]): r = lstsq(avg[:, None], x[i, :][:, None], rcond=0)[0] x_o.append( x[i, :] - r[0, 0] * avg...
Take the mean across channels and regress out the mean from each channel Parameters ---------- x : ndarray 2d array with channels on one dimension idx_chan: which axis contains channels Returns ------- ndarray same as x, but with the mean being regressed out
359,263
def job(self): if self._submitter and hasattr(self._submitter, ): return self._submitter._job_access() return None
REST binding for the job associated with the submitted build. Returns: Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
359,264
def __deactivate_recipes(self, plugin, *args, **kwargs): recipes = self.get() for recipe in recipes.keys(): self.unregister(recipe)
Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated.
359,265
def other_Orange_tables(self): target_table = self.db.target_table if not self.db.orng_tables: return [self.convert_table(table, None) for table in self.db.tables if table != target_table] else: return [table for name, table in list(self.db.orng_tables.items()) i...
Returns the related tables as Orange example tables. :rtype: list
359,266
def nested_option(default=False): def decorator(method): @wraps(method) def wrapper(*args, **kwargs): option = Option.nested.value kwargs[option] = kwargs.get(option, bool(default)) return method(*args, **kwargs) return wrapper return decorator
Attaches the option ``nested`` with its *default* value to the keyword arguments when the option does not exist. All positional arguments and keyword arguments are forwarded unchanged.
359,267
def _get_guidelines(self): return tuple([self._getitem__guidelines(i) for i in range(self._len__guidelines())])
Subclasses may override this method.
359,268
def bounding_boxes(self, mode=, output=): boxes = {} if mode not in (, ): raise ValueError("Unknown mode {0}.".format(mode)) if output not in (, ): raise ValueError("Unknown output {0}.".format(output)) for row in range(1, self.rows + ...
Get the bounding boxes of the labels on a page. Parameters ---------- mode: 'fraction', 'actual' If 'fraction', the bounding boxes are expressed as a fraction of the height and width of the sheet. If 'actual', they are the actual position of the labels in mil...
359,269
def ifetch_single(iterable, key, default=EMPTY, getter=None): def _getter(item): if getter: custom_getter = partial(getter, key=key) return custom_getter(item) else: try: attrgetter = operator.attrgetter(key) return attrgetter...
getter() g(item, key):pass
359,270
def concatenate(cls, *args): nargs = len(args) if nargs == 1: return args[0] vs = [a.v for a in args if a.v is not None] vcs = [a.vc for a in args if a.vc is not None] fs = [a.f for a in args if a.f is not None] if vs and len(vs) != nargs: ...
Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces.
359,271
def app(config, src, dst, features, reload, force): config = Path(config) if reload: argv = sys.argv.copy() argv.remove() monitor(config.dirname(), src, dst, argv) else: run(config, src, dst, force)
Takes several files or directories as src and generates the code in the given dst directory.
359,272
def select(self): if not hasattr(self._gdbframe, ): print ( ) return False self._gdbframe.select() return True
If supported, select this frame and return True; return False if unsupported Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12 onwards, but absent on Ubuntu buildbot
359,273
def get_distro_info(self, loglevel=logging.DEBUG): shutit = self.shutit install_type = distro = distro_version = if shutit.build[] != : key = shutit.build[] distro = shutit.build[] install_type = package_map.INSTALL_TYPE_MAP[key] distro_version = if install_type == and shutit....
Get information about which distro we are using, placing it in the environment object. Fails if distro could not be determined. Should be called with the container is started up, and uses as core info as possible. Note: if the install type is apt, it issues the following: - apt-get update - apt-ge...
359,274
def move(self, particle, u, v, w, modelTimestep, **kwargs): if not particle.settled and not particle.dead: particle.die() temp = kwargs.get(, None) if temp is not None and math.isnan(temp): temp = None particle.temp = temp sal...
I'm dead, so no behaviors should act on me
359,275
def ifelse(self, yes, no): return H2OFrame._expr(expr=ExprNode("ifelse", self, yes, no))
Equivalent to ``[y if t else n for t,y,n in zip(self,yes,no)]``. Based on the booleans in the test vector, the output has the values of the yes and no vectors interleaved (or merged together). All Frames must have the same row count. Single column frames are broadened to match wider F...
359,276
def get_by(cls, **kwargs): user@domain.com conn = _connect(cls) model = cls._namespace _limit = kwargs.pop(, ()) if _limit and len(_limit) != 2: raise QueryError("Limit must include both and parameters") elif _limit and not all(isinstance(x, six.int...
This method offers a simple query method for fetching entities of this type via attribute numeric ranges (such columns must be ``indexed``), or via ``unique`` columns. Some examples:: user = User.get_by(email_address='user@domain.com') # gets up to 25 users created in t...
359,277
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = .format(.join(py_files)) return bash(cmd).value()
Check frosted errors in the code base.
359,278
def get_n_tail(tmax, tail_temps): t_index = 0 adj_tmax = 0 if tmax < tail_temps[0]: return 0 try: t_index = list(tail_temps).index(tmax) except: for temp in tail_temps: if temp <= tmax: adj_tmax = temp t_index = list(tail_temps)....
determines number of included tail checks in best fit segment
359,279
def value(self, progress_indicator): return interpolate.interpolate_linear_single(self.initial_value, self.final_value, progress_indicator)
Interpolate linearly between start and end
359,280
def ordinal_float(dt): try: return dt.toordinal() + ((((dt.microsecond / 1000000.) + dt.second) / 60. + dt.minute) / 60 + dt.hour) / 24. except AttributeError: try: return ordinal_float(make_datetime(dt)) except ValueError: pass dt = list(make_datetime(va...
Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all) Similar to the Microsoft Excel numerical representation of a datetime object >>> ordinal_float(datetime.datetime(1970, 1, 1)) 719163.0 >>> ordinal_float(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) # doctes...
359,281
def make_taxonomy_dict(classification, parent=False): tax_id_map = {} if parent: for row in classification.results()["table"]: if row["parent_tax_id"] is not None and row["tax_id"] is not None: tax_id_map[row["tax_id"]] = row["parent_tax_id"] else: for row ...
Takes a classification data frame returned by the API and parses it into a dictionary mapping a tax_id to its children (or parent). Restricted to tax_id's that are represented in the classification results.
359,282
def _decrypt_object(obj, **kwargs): if salt.utils.stringio.is_readable(obj): return _decrypt_object(obj.getvalue(), **kwargs) if isinstance(obj, six.string_types): if re.search(NACL_REGEX, obj) is not None: return __salt__[](re.search(NACL_REGEX, obj).group(1), **kwargs) ...
Recursively try to decrypt any object. If the object is a six.string_types (string or unicode), and it contains a valid NACLENC pretext, decrypt it, otherwise keep going until a string is found.
359,283
def portable_b64encode(thing): if is_py3(): try: some_bits = bytes(thing, ) except TypeError: some_bits = thing return polite_string(b64encode(some_bits).decode()) return polite_string(b64encode(thing))
Wrap b64encode for Python 2 & 3
359,284
def simplejson_datetime_serializer(obj): if hasattr(obj, ): return obj.isoformat() else: raise TypeError( % (type(obj), repr(obj)))
Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO strings.
359,285
def push_back(self, value): self.cache.push_back(self.value_pickler.dumps(value)) return self
Appends a copy of *value* at the end of the :class:`Sequence`.
359,286
def _getAlias(self, auth_level_uri): for (alias, existing_uri) in self.auth_level_aliases.items(): if auth_level_uri == existing_uri: return alias raise KeyError(auth_level_uri)
Return the alias for the specified auth level URI. @raises KeyError: if no alias is defined
359,287
def _view_use_legacy_sql_getter(table): view = table._properties.get("view") if view is not None: return view.get("useLegacySql", True) if table.table_type == "VIEW": return True
bool: Specifies whether to execute the view with Legacy or Standard SQL. This boolean specifies whether to execute the view with Legacy SQL (:data:`True`) or Standard SQL (:data:`False`). The client side default is :data:`False`. The server-side default is :data:`True`. If this table is not a view, :da...
359,288
def _add_gmaf(self, variant_obj, gemini_variant): max_af = gemini_variant[] if max_af: max_af = float(max_af) if max_af != -1.0: variant_obj.set_max_freq(max_af)
Add the gmaf frequency Args: variant_obj (puzzle.models.Variant) gemini_variant (GeminiQueryRow)
359,289
def _ConvertBool(value, require_str): if require_str: if value == : return True elif value == : return False else: raise ParseError(.format(value)) if not isinstance(value, bool): raise ParseError() return value
Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed.
359,290
def example_reading_spec(self): processed_reward_type = tf.float32 if self.is_processed_rewards_discrete: processed_reward_type = tf.int64 data_fields = { TIMESTEP_FIELD: tf.FixedLenFeature((1,), tf.int64), RAW_REWARD_FIELD: tf.FixedLenFeature((1,), tf.float32), PR...
Data fields to store on disk and their decoders.
359,291
def _parse_indices(self): v_name = self.prior_token v_indices = [] while self.token in (, ): v_indices.append(self._parse_index(v_name)) return v_indices
Parse a sequence of Fortran vector indices as a list of tuples.
359,292
def warning(*tokens: Token, **kwargs: Any) -> None: tokens = [brown, "Warning:"] + list(tokens) kwargs["fileobj"] = sys.stderr message(*tokens, **kwargs)
Print a warning message
359,293
def filter_by_months_per_hour(self, months_per_hour): _filt_values = [] _filt_datetimes = [] for i, d in enumerate(self.datetimes): if d in months_per_hour: _filt_datetimes.append(d) _filt_values.append(self._values[i]) return MonthlyP...
Filter the Data Collection based on a list of months per hour (as strings). Args: months_per_hour: A list of tuples representing months per hour. Each tuple should possess two values: the first is the month and the second is the hour. (eg. (12, 23) = December at 11 PM) ...
359,294
def imageurl(self): if self._imageurl is None: self._imageurl = % self.csid return self._imageurl
Return the URL of a png image of the 2D structure
359,295
def fit_deriv(x, amplitude, mean, stddev): import operator return list(map( operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev)))
GaussianAbsorption1D model function derivatives.
359,296
def set_object(self, name: str, pobj: ParameterObject) -> None: self.objects[zlib.crc32(name.encode())] = pobj
Add or update an existing object.
359,297
def flatten_dict(i): prefix= if i.get(,)!=: prefix=str(i[]) a=i[] aa={} pk=i.get(,) if pk==: pk=[] flatten_dict_internal(a, aa, prefix, pk) return {:0, : aa}
Any list item is converted to @number=value Any dict item is converted to #key=value # is always added at the beginning Input: { dict - python dictionary (prefix) - prefix (for recursion) (prune_keys) - list of keys to prune (can have wildcards) ...
359,298
def drop(self, table_name = , if_exists = False, **kwargs): return self.execute(u % ( if if_exists else , quote(table_name)), **kwargs)
Drop a table.
359,299
def main (args): if len(args) != 3: print(main.__doc__) sys.exit(1) d = libsedml.readSedML(args[1]); if ( d.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0): print (d.getErrorLog().toString()); else: libsedml.writeSedML(d, args[2]); return 0;
Usage: echo_sedml input-filename output-filename