code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def is_canonical_address(address: Any) -> bool: if not is_bytes(address) or len(address) != 20: return False return address == to_canonical_address(address)
Returns `True` if the `value` is an address in its canonical form.
def irfftn(a, s=None, axes=None, norm=None): output = mkl_fft.irfftn_numpy(a, s, axes) if _unitary(norm): output *= sqrt(_tot_size(output, axes)) return output
Compute the inverse of the N-dimensional FFT of real input. This function computes the inverse of the N-dimensional discrete Fourier Transform for real input over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``irfftn(rfftn(a), a.shape) == a...
def get_examples(examples_dir="examples/"): all_files = os.listdir(examples_dir) python_files = [f for f in all_files if is_python_file(f)] basenames = [remove_suffix(f) for f in python_files] modules = [import_module(module) for module in pathify(basenames)] return [ module for module in mo...
All example modules
def gdbgui(): interpreter = "lldb" if app.config["LLDB"] else "gdb" gdbpid = request.args.get("gdbpid", 0) initial_gdb_user_command = request.args.get("initial_gdb_user_command", "") add_csrf_token_to_session() THEMES = ["monokai", "light"] initial_data = { "csrf_token": session["csrf_to...
Render the main gdbgui interface
def anchored_pairs(self, anchor): pairs = OrderedDict() for term in self.keys: score = self.get_pair(anchor, term) if score: pairs[term] = score return utils.sort_dict(pairs)
Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The distances, in descending order.
def zscore(self, key, member): fut = self.execute(b'ZSCORE', key, member) return wait_convert(fut, optional_int_or_float)
Get the score associated with the given member in a sorted set.
def output(self, result): if self.returns: errors = None try: return self._adapt_result(result) except AdaptErrors as e: errors = e.errors except AdaptError as e: errors = [e] raise AnticipateErrors( ...
Adapts the result of a function based on the returns definition.
def stop_patching(name=None): global _patchers, _mocks if not _patchers: warnings.warn('stop_patching() called again, already stopped') if name is not None: items = [(name, _patchers[name])] else: items = list(_patchers.items()) for name, patcher in items: patcher.sto...
Finish the mocking initiated by `start_patching` Kwargs: name (Optional[str]): if given, only unpatch the specified path, else all defined default mocks
def lists_submissions(self, date, course_id, grader_id, assignment_id): path = {} data = {} params = {} path["course_id"] = course_id path["date"] = date path["grader_id"] = grader_id path["assignment_id"] = assignment_id self.logger.debug("GET /ap...
Lists submissions. Gives a nested list of submission versions
def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs): return _random_helper(_internal._random_poisson, _internal._sample_poisson, [lam], shape, dtype, kwargs)
Draw random samples from a Poisson distribution. Samples are distributed according to a Poisson distribution parametrized by *lambda* (rate). Samples will always be returned as a floating point data type. Parameters ---------- lam : float or Symbol, optional Expectation of interval, should...
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
Set the values and labels, and select the first option if we aren't initializing
def list_append(self, key, value, create=False, **kwargs): op = SD.array_append('', value) sdres = self.mutate_in(key, op, **kwargs) return self._wrap_dsop(sdres)
Add an item to the end of a list. :param str key: The document ID of the list :param value: The value to append :param create: Whether the list should be created if it does not exist. Note that this option only works on servers >= 4.6 :param kwargs: Additional arguments t...
def buildCliString(self): config = self.navbar.getActiveConfig() group = self.buildSpec['widgets'][self.navbar.getSelectedGroup()] positional = config.getPositionalArgs() optional = config.getOptionalArgs() print(cli.buildCliString( self.buildSpec['target'], ...
Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program
def set_template(path, template, context, defaults, saltenv='base', **kwargs): path = __salt__['cp.get_template']( path=path, dest=None, template=template, saltenv=saltenv, context=context, defaults=defaults, **kwargs) return set_file(path, saltenv, **kwar...
Set answers to debconf questions from a template. path location of the file containing the package selections template template format context variables to add to the template environment default default values for the template environment CLI Example: .. co...
def Validate(self, type_names): errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)] if errs: raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
Filtered types need to be RDFValues.
def get_view_url(self, view_name, user, url_kwargs=None, context_kwargs=None, follow_parent=True, check_permissions=True): view, url_name = self.get_initialized_view_and_name(view_name, follow_parent=follow_parent) if ...
Returns the url for a given view_name. If the view isn't found or the user does not have permission None is returned. A NoReverseMatch error may be raised if the view was unable to find the correct keyword arguments for the reverse function from the given url_kwargs and context_kwargs. ...
def construct_formatdb_cmd(filename, outdir, blastdb_exe=pyani_config.FORMATDB_DEFAULT): title = os.path.splitext(os.path.split(filename)[-1])[0] newfilename = os.path.join(outdir, os.path.split(filename)[-1]) shutil.copy(filename, newfilename) return ( "{0} -p F -i {1} -t {2}".format(blastdb_ex...
Returns a single formatdb command. - filename - input filename - blastdb_exe - path to the formatdb executable
def output_deployment_status(awsclient, deployment_id, iterations=100): counter = 0 steady_states = ['Succeeded', 'Failed', 'Stopped'] client_codedeploy = awsclient.get_client('codedeploy') while counter <= iterations: response = client_codedeploy.get_deployment(deploymentId=deployment_id) ...
Wait until an deployment is in an steady state and output information. :param deployment_id: :param iterations: :return: exit_code
def compile(self, **kwargs): code = compile(str(self), "<string>", "exec") global_dict = dict(self._deps) global_dict.update(kwargs) _compat.exec_(code, global_dict) return global_dict
Execute the python code and returns the global dict. kwargs can contain extra dependencies that get only used at compile time.
def add_gripper(self, arm_name, gripper): if arm_name in self.grippers: raise ValueError("Attempts to add multiple grippers to one body") arm_subtree = self.worldbody.find(".//body[@name='{}']".format(arm_name)) for actuator in gripper.actuator: if actuator.get("name") is...
Mounts gripper to arm. Throws error if robot already has a gripper or gripper type is incorrect. Args: arm_name (str): name of arm mount gripper (MujocoGripper instance): gripper MJCF model
def run_parser_plugins(self, url_data, pagetype): run_plugins(self.parser_plugins, url_data, stop_after_match=True, pagetype=pagetype)
Run parser plugins for given pagetype.
def executemany(self, sql, *params): fut = self._run_operation(self._impl.executemany, sql, *params) return fut
Prepare a database query or command and then execute it against all parameter sequences found in the sequence seq_of_params. :param sql: the SQL statement to execute with optional ? parameters :param params: sequence parameters for the markers in the SQL.
def pack_and_batch(dataset, batch_size, length, pack=True): if pack: dataset = pack_dataset(dataset, length=length) dataset = dataset.map( functools.partial(trim_and_pad_all_features, length=length), num_parallel_calls=tf.data.experimental.AUTOTUNE ) dataset = dataset.batch(batch_size, drop_rema...
Create a tf.data.Dataset which emits training batches. The input dataset emits feature-dictionaries where each feature is a vector of integers ending in EOS=1 The tensors in the returned tf.data.Dataset have shape [batch_size, length]. Zeros indicate padding. length indicates the length of the emitted exa...
def flo(string): callers_locals = {} frame = inspect.currentframe() try: outerframe = frame.f_back callers_locals = outerframe.f_locals finally: del frame return string.format(**callers_locals)
Return the string given by param formatted with the callers locals.
def as_set(self, decode=False): items = self.database.smembers(self.key) return set(_decode(item) for item in items) if decode else items
Return a Python set containing all the items in the collection.
def SvcStop(self) -> None: self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.h_stop_event)
Called when the service is being shut down.
def cub200_iterator(data_path, batch_k, batch_size, data_shape): return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True), CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False))
Return training and testing iterator for the CUB200-2011 dataset.
def save(self): d = dict(self) old_dict = d.copy() _id = self.collection.save(d) self._id = _id self.on_save(old_dict) return self._id
Save model object to database.
def assert_numbers_almost_equal(self, actual_val, expected_val, allowed_delta=0.0001, failure_message='Expected numbers to be within {} of each other: "{}" and "{}"'): assertion = lambda: abs(expected_val - actual_val) <= allowed_delta self.webdriver_assert(assertion,...
Asserts that two numbers are within an allowed delta of each other
def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): if regex: if not case: flags |= re.IGNORECASE regex = re.compile(pat, flags=flags) if regex.groups > 0: warnings.warn("This pattern has match groups. To actually get the" ...
Test if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ---------- pat : str Character sequence or regular expression. case : bool,...
def disconnect_async(self, conn_id, callback): future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
Asynchronously disconnect from a device.
def digest_chunks(chunks, algorithms=(hashlib.md5, hashlib.sha1)): hashes = [algorithm() for algorithm in algorithms] for chunk in chunks: for h in hashes: h.update(chunk) return [_b64encode_to_str(h.digest()) for h in hashes]
returns a base64 rep of the given digest algorithms from the chunks of data
def getCompleteFile(self, basepath): dirname = getDirname(self.getName()) return os.path.join(basepath, dirname, "complete.txt")
Get filename indicating all comics are downloaded.
def update_url(url, params): if not isinstance(url, bytes): url = url.encode('utf-8') for key, value in list(params.items()): if not isinstance(key, bytes): del params[key] key = key.encode('utf-8') if not isinstance(value, bytes): value = value.encode...
update parameters using ``params`` in the ``url`` query string :param url: An URL possibily with a querystring :type url: :obj:`unicode` or :obj:`str` :param dict params: A dictionary of parameters for updating the url querystring :return: The URL with an updated querystring :rt...
def set_names(self, names, level=None, inplace=False): if level is not None and not isinstance(self, ABCMultiIndex): raise ValueError('Level must be None for non-MultiIndex') if level is not None and not is_list_like(level) and is_list_like( names): msg = "Names m...
Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, optional If the index is a MultiIndex, level(s) to set (None for ...
def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None): action = "get nic information" with zvmutils.log_and_reraise_sdkbase_error(action): return self._networkops.get_nic_info(userid=userid, nic_id=nic_id, vswitch=vswitch)
Retrieve nic information in the network database according to the requirements, the nic information will include the guest name, nic device number, vswitch name that the nic is coupled to, nic identifier and the comments. :param str userid: the user id of the vm :par...
def info_string(self, size=None, message='', frame=-1): info = [] if size is not None: info.append('Size: {1}x{0}'.format(*size)) elif self.size is not None: info.append('Size: {1}x{0}'.format(*self.size)) if frame >= 0: info.append('Frame: {}'.format(...
Returns information about the stream. Generates a string containing size, frame number, and info messages. Omits unnecessary information (e.g. empty messages and frame -1). This method is primarily used to update the suptitle of the plot figure. Returns: An info st...
def _factory(importname, base_class_type, path=None, *args, **kargs): def is_base_class(item): return isclass(item) and item.__module__ == importname if path: sys.path.append(path) absolute_path = os.path.join(path, importname) + '.py' module = imp.load_source(importname, absolut...
Load a module of a given base class type Parameter -------- importname: string Name of the module, etc. converter base_class_type: class type E.g converter path: Absoulte path of the module Neede for extensions. If not given module is in onlin...
def _clone(self): instance = super(Bungiesearch, self)._clone() instance._raw_results_only = self._raw_results_only return instance
Must clone additional fields to those cloned by elasticsearch-dsl-py.
def _update_label(self, label, array): maximum = float(numpy.max(array)) mean = float(numpy.mean(array)) median = float(numpy.median(array)) minimum = float(numpy.min(array)) stdev = float(numpy.std(array, ddof=1)) encoder = pvl.encoder.PDSLabelEncoder serial_labe...
Update PDS3 label for NumPy Array. It is called by '_create_label' to update label values such as, - ^IMAGE, RECORD_BYTES - STANDARD_DEVIATION - MAXIMUM, MINIMUM - MEDIAN, MEAN Returns ------- Update label module for the NumPy array. Usag...
def gen_opt_str(ser_rec: pd.Series)->str: name = ser_rec.name indent = r' ' str_opt = f'.. option:: {name}'+'\n\n' for spec in ser_rec.sort_index().index: str_opt += indent+f':{spec}:'+'\n' spec_content = ser_rec[spec] str_opt += indent+indent+f'{spec_content}'+'\n' return...
generate rst option string Parameters ---------- ser_rec : pd.Series record for specifications Returns ------- str rst string
def get(self, name, default=_MISSING): name = self._convert_name(name) if name not in self._fields: if default is _MISSING: default = self._default_value(name) return default if name in _UNICODEFIELDS: value = self._fields[name] ret...
Get a metadata field.
def detect_port(port): socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: socket_test.connect(('127.0.0.1', int(port))) socket_test.close() return True except: return False
Detect if the port is used
def contribute_to_class(self, cls, name, virtual_only=False): super(RegexField, self).contribute_to_class(cls, name, virtual_only) setattr(cls, name, CastOnAssignDescriptor(self))
Cast to the correct value every
def get_data(self): url = self.build_url() self.locationApiData = requests.get(url) if not self.locationApiData.status_code == 200: raise self.locationApiData.raise_for_status()
Gets data from the built url
def migrateProvPre010(self, newslab): did_migrate = self._migrate_db_pre010('prov', newslab) if not did_migrate: return self._migrate_db_pre010('provs', newslab)
Check for any pre-010 provstacks and migrate those to the new slab.
def parse(source, remove_comments=True, **kw): return ElementTree.parse(source, SourceLineParser(), **kw)
Thin wrapper around ElementTree.parse
def _set_cell_attr(self, selection, table, attr): post_command_event(self.main_window, self.ContentChangedMsg) if selection is not None: self.code_array.cell_attributes.append((selection, table, attr))
Sets cell attr for key cell and mark grid content as changed Parameters ---------- attr: dict \tContains cell attribute keys \tkeys in ["borderwidth_bottom", "borderwidth_right", \t"bordercolor_bottom", "bordercolor_right", \t"bgcolor", "textfont", \t"po...
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offset=self._offset + offset, shap...
Return numpy.memmap of data stored in file.
def _piecewise_learning_rate(step, boundaries, values): values = [1.0] + values boundaries = [float(x) for x in boundaries] return tf.train.piecewise_constant( step, boundaries, values, name="piecewise_lr")
Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value for the learning rate.
def parse_pgurl(self, url): parsed = urlsplit(url) return { 'user': parsed.username, 'password': parsed.password, 'database': parsed.path.lstrip('/'), 'host': parsed.hostname, 'port': parsed.port or 5432, }
Given a Postgres url, return a dict with keys for user, password, host, port, and database.
def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.): r return 2.*pi*L/acosh((D2**2 + D1**2 - 4.*Z**2)/(2.*D1*D2))
r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D1` which is `Z` distance from the center of another pipe of outer diameter`D2`. Length `L` must be provided, but can be set to 1 to obtain a dimensionless shape factor used in some sources. .. math:: ...
def parse(cls, s, **kwargs): pb2_obj = cls._get_cmsg() pb2_obj.ParseFromString(s) return cls.parse_from_cmessage(pb2_obj, **kwargs)
Parse a bytes object and create a class object. :param bytes s: A bytes object. :return: A class object. :rtype: cls
def mac_address(ip): mac = '' for line in os.popen('/sbin/ifconfig'): s = line.split() if len(s) > 3: if s[3] == 'HWaddr': mac = s[4] elif s[2] == ip: break return {'MAC': mac}
Get the MAC address
def usage(text): def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.usage = text return func return decorator
Decorator used to specify a usage string for the console script help message. :param text: The text to use for the usage.
def project_drawn(cb, msg): stream = cb.streams[0] old_data = stream.data stream.update(data=msg['data']) element = stream.element stream.update(data=old_data) proj = cb.plot.projection if not isinstance(element, _Element) or element.crs == proj: return None crs = element.crs ...
Projects a drawn element to the declared coordinate system
def start_external_service(self, service_name, conf=None): if service_name in self._external_services: ser = self._external_services[service_name] service = ser(service_name, conf=conf, bench=self.bench) try: service.start() except PluginException:...
Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing
def remove_channel(self, channel, *, verbose=True): channel_index = wt_kit.get_index(self.channel_names, channel) new = list(self.channel_names) name = new.pop(channel_index) del self[name] self.channel_names = new if verbose: print("channel {0} removed".forma...
Remove channel from data. Parameters ---------- channel : int or str Channel index or name to remove. verbose : boolean (optional) Toggle talkback. Default is True.
def log(self, ctx='all'): path = '%s/%s.log' % (self.path, ctx) if os.path.exists(path) is True: with open(path, 'r') as f: print(f.read()) return validate_path = '%s/validate.log' % self.path build_path = '%s/build.log' % self.path out = [] with open(validate_path) as valida...
Gets the build log output. :param ctx: specifies which log message to show, it can be 'validate', 'build' or 'all'.
def read_config(): if not os.path.isfile(CONFIG): with open(CONFIG, "w"): pass parser = ConfigParser() parser.read(CONFIG) return parser
Read the configuration file and parse the different environments. Returns: ConfigParser object
def _parse_optional_params(self, oauth_params, req_kwargs): params = req_kwargs.get('params', {}) data = req_kwargs.get('data') or {} for oauth_param in OPTIONAL_OAUTH_PARAMS: if oauth_param in params: oauth_params[oauth_param] = params.pop(oauth_param) if...
Parses and sets optional OAuth parameters on a request. :param oauth_param: The OAuth parameter to parse. :type oauth_param: str :param req_kwargs: The keyworded arguments passed to the request method. :type req_kwargs: dict
def include_library(libname): if exclude_list: if exclude_list.search(libname) and not include_list.search(libname): return False else: return True else: return True
Check if a dynamic library should be included with application or not.
def mod(x, y, context=None): return _apply_function_in_current_context( BigFloat, mpfr_mod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return the remainder of x divided by y, with sign matching that of y.
def runSearchContinuousSets(self, request): return self.runSearchRequest( request, protocol.SearchContinuousSetsRequest, protocol.SearchContinuousSetsResponse, self.continuousSetsGenerator)
Returns a SearchContinuousSetsResponse for the specified SearchContinuousSetsRequest object.
def add(self, child): if isinstance(child, Run): self.add_run(child) elif isinstance(child, Record): self.add_record(child) elif isinstance(child, EventRecord): self.add_event_record(child) elif isinstance(child, DataDisplay): self.add_data...
Adds a typed child object to the simulation spec. @param child: Child object to be added.
def between(self, start, end): if hasattr(start, 'strftime') and hasattr(end, 'strftime'): dt_between = ( 'javascript:gs.dateGenerate("%(start)s")' "@" 'javascript:gs.dateGenerate("%(end)s")' ) % { 'start': start.strftime('%Y-%m-%d ...
Adds new `BETWEEN` condition :param start: int or datetime compatible object (in SNOW user's timezone) :param end: int or datetime compatible object (in SNOW user's timezone) :raise: - QueryTypeError: if start or end arguments is of an invalid type
def enable_global_typechecked_decorator(flag = True, retrospective = True): global global_typechecked_decorator global_typechecked_decorator = flag if import_hook_enabled: _install_import_hook() if global_typechecked_decorator and retrospective: _catch_up_global_typechecked_decorator() ...
Enables or disables global typechecking mode via decorators. See flag global_typechecked_decorator. In contrast to setting the flag directly, this function provides a retrospective option. If retrospective is true, this will also affect already imported modules, not only future imports. Does not wor...
def create_query_engine(config, clazz): try: qe = clazz(**config.settings) except Exception as err: raise CreateQueryEngineError(clazz, config.settings, err) return qe
Create and return new query engine object from the given `DBConfig` object. :param config: Database configuration :type config: dbconfig.DBConfig :param clazz: Class to use for creating query engine. Should act like query_engine.QueryEngine. :type clazz: class :return: New que...
def send(self, data): log.debug('Sending %s' % data) if not self._socket: log.warn('No connection') return self._socket.send_bytes(data.encode('utf-8'))
Send data through websocket
def parse_command_line() -> Namespace: import tornado.options parser.parse_known_args(namespace=config) set_loglevel() for k, v in vars(config).items(): if k.startswith('log'): tornado.options.options.__setattr__(k, v) return config
Parse command line options and set them to ``config``. This function skips unknown command line options. After parsing options, set log level and set options in ``tornado.options``.
def unpack(cls, msg): flags, first_payload_type, first_payload_size = cls.UNPACK_FROM(msg) if flags != 0: raise ProtocolError("Unsupported OP_MSG flags (%r)" % (flags,)) if first_payload_type != 0: raise ProtocolError( "Unsupported OP_MSG payload type (%r)...
Construct an _OpMsg from raw bytes.
def makeSocket(self, timeout=1): plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(plain_socket, 'settimeout'): plain_socket.settimeout(timeout) wrapped_socket = ssl.wrap_socket( plain_socket, ca_certs=self.ca_certs, cert_...
Override SocketHandler.makeSocket, to allow creating wrapped TLS sockets
def enable_receiving(self, loop=None): self.receive_task = asyncio.ensure_future(self._receive_loop(), loop=loop) def do_if_done(fut): try: fut.result() except asyncio.CancelledError: pass except Exception as ex: self.re...
Schedules the receive loop to run on the given loop.
def main(model_folder): model_description_file = os.path.join(model_folder, "info.yml") with open(model_description_file, 'r') as ymlfile: model_description = yaml.load(ymlfile) logging.info(model_description['model']) data = {} data['training'] = os.path.join(model_folder, "traindata.hdf5")...
Main part of the training script.
def clean_series_name(seriesname): if not seriesname: return seriesname seriesname = re.sub(r'(\D)[.](\D)', '\\1 \\2', seriesname) seriesname = re.sub(r'(\D)[.]', '\\1 ', seriesname) seriesname = re.sub(r'[.](\D)', ' \\1', seriesname) seriesname = seriesname.replace('_', ' ') seriesname ...
Cleans up series name. By removing any . and _ characters, along with any trailing hyphens. Is basically equivalent to replacing all _ and . with a space, but handles decimal numbers in string, for example: >>> _clean_series_name("an.example.1.0.test") 'an example 1.0 test' >>> _clean_series_...
def set_options(self, option_type, option_dict, force_options=False): if force_options: self.options[option_type].update(option_dict) elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list): self.options[option_type] = MultiAxis(option_type) ...
set plot options
def ffill_across_cols(df, columns, name_map): df.ffill(inplace=True) for column in columns: column_name = name_map[column.name] if column.dtype == categorical_dtype: df[column_name] = df[ column.name ].where(pd.notnull(df[column_name]), ...
Forward fill values in a DataFrame with special logic to handle cases that pd.DataFrame.ffill cannot and cast columns to appropriate types. Parameters ---------- df : pd.DataFrame The DataFrame to do forward-filling on. columns : list of BoundColumn The BoundColumns that correspond ...
def get_vip_request(self, vip_request_id): uri = 'api/v3/vip-request/%s/' % vip_request_id return super(ApiVipRequest, self).get(uri)
Method to get vip request param vip_request_id: vip_request id
def iter(self, pages=None): i = self._pages() if pages is not None: i = itertools.islice(i, pages) return i
Get an iterator of pages. :param int pages: optional limit to number of pages :return: iter of this and subsequent pages
def get_token(): token = os.environ.get("GH_TOKEN", None) if not token: token = "GH_TOKEN environment variable not set" token = token.encode('utf-8') return token
Get the encrypted GitHub token in Travis. Make sure the contents this variable do not leak. The ``run()`` function will remove this from the output, so always use it.
def install(directory, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='...
Install composer dependencies for a directory. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. directory Directory location of the composer...
def get_rel_sciobj_file_path(pid): hash_str = hashlib.sha1(pid.encode('utf-8')).hexdigest() return os.path.join(hash_str[:2], hash_str[2:4], hash_str)
Get the relative local path to the file holding an object's bytes. - The path is relative to settings.OBJECT_STORE_PATH - There is a one-to-one mapping between pid and path - The path is based on a SHA1 hash. It's now possible to craft SHA1 collisions, but it's so unlikely that we ignore it for now ...
def hybrid_forward(self, F, inputs): outputs = self.ffn_1(inputs) if self.activation: outputs = self.activation(outputs) outputs = self.ffn_2(outputs) if self._dropout: outputs = self.dropout_layer(outputs) if self._use_residual: outputs = outp...
Position-wise encoding of the inputs. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) Returns ------- outputs : Symbol or NDArray Shape (batch_size, length, C_out)
def load(filename): try: with open(filename, 'rb') as f: return pickle.load(f) except Exception as e1: try: return jl_load(filename) except Exception as e2: raise IOError( "Unable to load {} using the pickle or joblib protocol.\n" ...
Load an object that has been saved with dump. We try to open it using the pickle protocol. As a fallback, we use joblib.load. Joblib was the default prior to msmbuilder v3.2 Parameters ---------- filename : string The name of the file to load.
def variablename(var): s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())] s=s[0].upper() return s
Returns the string of a variable name.
def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'): try: body_data = data[body_subtree] except KeyError: raise EvaluationError('Data dictionary has no subtree %r' % body_subtree) tokens_body = [] template.execute(body_data, tokens_body.append) data[bo...
OBSOLETE old API.
def bk_blue(cls): "Make the text background color blue." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_BLUE cls._set_text_attributes(wAttributes)
Make the text background color blue.
def default_spec(self, manager): specstr = "" stable_families = manager.stable_families if manager.config.releases_unstable_prehistory and stable_families: specstr = ">={}".format(min(stable_families)) if self.is_featurelike: if True: specstr = ">=...
Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">=2")``. * When ``releases_always_forward...
def _get_id(self): return ''.join(map(str, filter(is_not_None, [self.Prefix, self.Name])))
Construct and return the identifier
def send_pgrp(cls, sock, pgrp): assert(isinstance(pgrp, IntegerForPid) and pgrp < 0) encoded_int = cls.encode_int(pgrp) cls.write_chunk(sock, ChunkType.PGRP, encoded_int)
Send the PGRP chunk over the specified socket.
def get_current_key(self, resource_name): url = ENCRYPTION_CURRENT_KEY_URL.format(resource_name) return self._key_from_json(self._get_resource(url))
Returns a restclients.Key object for the given resource. If the resource isn't found, or if there is an error communicating with the KWS, a DataFailureException will be thrown.
def headers(self): return { "Content-Type": ("multipart/form-data; boundary={}".format(self.boundary)), "Content-Length": str(self.len), "Content-Encoding": self.encoding, }
All headers needed to make a request
def _guessunit(self): if not self.days % 1: return 'd' elif not self.hours % 1: return 'h' elif not self.minutes % 1: return 'm' elif not self.seconds % 1: return 's' else: raise ValueError( 'The stepsize...
Guess the unit of the period as the largest one, which results in an integer duration.
def from_response(response): http_response = response.raw._original_response status_line = "HTTP/1.1 %d %s" % (http_response.status, http_response.reason) headers = str(http_response.msg) body = http_response.read() response.raw._fp = StringIO(body) payload = status_line ...
Creates a WARCRecord from given response object. This must be called before reading the response. The response can be read after this method is called. :param response: An instance of :class:`requests.models.Response`.
def getlist(self, section, option): value = self.get(section, option) if value: return value.split(',') else: return None
returns the named option as a list, splitting the original value by ','
def setKeySequenceCounter(self, iKeySequenceValue): print '%s call setKeySequenceCounter' % self.port print iKeySequenceValue try: cmd = WPANCTL_CMD + 'setprop Network:KeyIndex %s' % str(iKeySequenceValue) if self.__sendCommand(cmd)[0] != 'Fail': time.slee...
set the Key sequence counter corresponding to Thread Network master key Args: iKeySequenceValue: key sequence value Returns: True: successful to set the key sequence False: fail to set the key sequence
def vertical_velocity(omega, pressure, temperature, mixing=0): r rho = density(pressure, temperature, mixing) return (omega / (- mpconsts.g * rho)).to('m/s')
r"""Calculate w from omega assuming hydrostatic conditions. This function converts vertical velocity with respect to pressure :math:`\left(\omega = \frac{Dp}{Dt}\right)` to that with respect to height :math:`\left(w = \frac{Dz}{Dt}\right)` assuming hydrostatic conditions on the synoptic scale. By Equat...
def _reconnect_handler(self): for channel_name, channel in self.channels.items(): data = {'channel': channel_name} if channel.auth: data['auth'] = channel.auth self.connection.send_event('pusher:subscribe', data)
Handle a reconnect.
def get(self, preview_id): return self.request.get('get', params=dict(id=preview_id))
Retrieve a Historics preview job. Warning: previews expire after 24 hours. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewget :param preview_id: historics preview job hash of the job to retrieve :type preview_id: str :retu...
def _logger(self): level = logging.INFO self.log.setLevel(level) self.log.handlers = [] if self.default_args.logging is not None: level = self._logger_levels[self.default_args.logging] elif self.default_args.tc_log_level is not None: level = self._logger_l...
Create TcEx app logger instance. The logger is accessible via the ``tc.log.<level>`` call. **Logging examples** .. code-block:: python :linenos: :lineno-start: 1 tcex.log.debug('logging debug') tcex.log.info('logging info') tcex.log...