code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def from_ZNM(cls, Z, N, M, name=''): """ Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 ...
Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 -21.34 127 -18.00 83 130 -14.4...
def run_synthetic_SGLD(): """Run synthetic SGLD""" theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(beg...
Run synthetic SGLD
def remove_notification_listener(self, notification_id): """ Remove a previously added notification callback. Args: notification_id: The numeric id passed back from add_notification_listener Returns: The function returns boolean true if found and removed, false otherwise. """ for v in...
Remove a previously added notification callback. Args: notification_id: The numeric id passed back from add_notification_listener Returns: The function returns boolean true if found and removed, false otherwise.
def space(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True,scale=None): """ Computes adequat binning for the dimension (on the values). bins: number of bins or None units: str or None conversion_function: func...
Computes adequat binning for the dimension (on the values). bins: number of bins or None units: str or None conversion_function: function to convert units to other units resolution: step size or None end_at_end: Boolean ...
def parse(self, stream, mimetype, content_length, options=None): """Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length ...
Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length of the incoming data :param options: optional mimetype parameters (u...
def grid_expansion_costs(network, without_generator_import=False): """ Calculates grid expansion costs for each reinforced transformer and line in kEUR. Attributes ---------- network : :class:`~.grid.network.Network` without_generator_import : Boolean If True excludes lines that wer...
Calculates grid expansion costs for each reinforced transformer and line in kEUR. Attributes ---------- network : :class:`~.grid.network.Network` without_generator_import : Boolean If True excludes lines that were added in the generator import to connect new generators to the grid f...
def mangle_signature(sig, max_chars=30): """Reformat a function signature to a more compact form.""" s = re.sub(r"^\((.*)\)$", r"\1", sig).strip() # Strip strings (which can contain things that confuse the code below) s = re.sub(r"\\\\", "", s) s = re.sub(r"\\'", "", s) s = re.sub(r"'[^']*'", "...
Reformat a function signature to a more compact form.
def register_type(cls, name): """Register `name` as a type to validate as an instance of class `cls`.""" x = TypeDefinition(name, (cls,), ()) Validator.types_mapping[name] = x
Register `name` as a type to validate as an instance of class `cls`.
def VxLANTunnelState_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") VxLANTunnelState = ET.SubElement(config, "VxLANTunnelState", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ...
Auto Generated Code
def create_optimizer(name, **kwargs): """Instantiates an optimizer with a given name and kwargs. .. note:: We can use the alias `create` for ``Optimizer.create_optimizer``. Parameters ---------- name: str Name of the optimizer. Should be the name of a su...
Instantiates an optimizer with a given name and kwargs. .. note:: We can use the alias `create` for ``Optimizer.create_optimizer``. Parameters ---------- name: str Name of the optimizer. Should be the name of a subclass of Optimizer. Case insensitive. k...
def isConnected(self, fromName, toName): """ Are these two layers connected this way? """ for c in self.connections: if (c.fromLayer.name == fromName and c.toLayer.name == toName): return 1 return 0
Are these two layers connected this way?
def _submit(self, pool, args, callback): """If the caller has passed the magic 'single-threaded' flag, call the function directly instead of pool.apply_async. The single-threaded flag is intended for gathering more useful performance information about what appens beneath `call_runner`, ...
If the caller has passed the magic 'single-threaded' flag, call the function directly instead of pool.apply_async. The single-threaded flag is intended for gathering more useful performance information about what appens beneath `call_runner`, since python's default profiling tools ignor...
def comments(self): """Return the text inside the comment area of the file.""" record_numbers = range(2, self.fward) if not record_numbers: return '' data = b''.join(self.read_record(n)[0:1000] for n in record_numbers) try: return data[:data.find(b'\4')].d...
Return the text inside the comment area of the file.
def _parse_tensor(self, indices=False): '''Parse a tensor.''' if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = self.line.split() if indices: tensor[i][0] = float(tokens[1]) ...
Parse a tensor.
def downstream(self, f, n=1): """find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return """ if f.strand == -1: ret...
find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return
def from_file(path): """ Crawls articles from the urls and extracts relevant information. :param path: path to file containing urls (each line contains one URL) :return: A dict containing given URLs as keys, and extracted information as corresponding values. """ with open...
Crawls articles from the urls and extracts relevant information. :param path: path to file containing urls (each line contains one URL) :return: A dict containing given URLs as keys, and extracted information as corresponding values.
def get_active_pitch_range(self): """ Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll. """ ...
Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll.
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is pa...
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
def find_page_of_state_m(self, state_m): """Return the identifier and page of a given state model :param state_m: The state model to be searched :return: page containing the state and the state_identifier """ for state_identifier, page_info in list(self.tabs.items()): ...
Return the identifier and page of a given state model :param state_m: The state model to be searched :return: page containing the state and the state_identifier
def Rizk(mp, dp, rhog, D): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_ and many others. .. math:: \mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5} Fr_s = \frac{V_{salt}}{\sqrt{gD}} \mu = \f...
r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_ and many others. .. math:: \mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5} Fr_s = \frac{V_{salt}}{\sqrt{gD}} \mu = \frac{m_p}{\frac{\pi}{4}D^2V \rho...
def task_ref_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Process a role that references the target nodes created by the ``lsst-task`` directive. Parameters ---------- name The role name used in the document. rawtext The entire mar...
Process a role that references the target nodes created by the ``lsst-task`` directive. Parameters ---------- name The role name used in the document. rawtext The entire markup snippet, with role. text The text marked with the role. lineno The line number whe...
def predict_is(self, h): """ Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions """...
Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions
def save(self, data): """Save a document or list of documents""" if not self.is_connected: raise Exception("No database selected") if not data: return False if isinstance(data, dict): doc = couchdb.Document() doc.update(data) se...
Save a document or list of documents
def _write_color (self, text, color=None): """Print text with given color. If color is None, print text as-is.""" if color is None: self.fp.write(text) else: write_color(self.fp, text, color)
Print text with given color. If color is None, print text as-is.
def user_field_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/user_fields#create-user-fields" api_path = "/api/v2/user_fields.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/user_fields#create-user-fields
def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS): """ Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HT...
Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other structured text formats. to_lower : bool, optional If...
def end_element (self, tag): """ Print HTML end element. @param tag: tag name @type tag: string @return: None """ tag = tag.encode(self.encoding, "ignore") self.fd.write("</%s>" % tag)
Print HTML end element. @param tag: tag name @type tag: string @return: None
def hash_vector(self, v, querying=False): """ Hashes the vector and returns the bucket key as string. """ bucket_keys = [] if querying: # If we are querying, use the permuted indexes to get bucket keys for child_hash in self.child_hashes: ...
Hashes the vector and returns the bucket key as string.
def neighbours(self, word, size = 10): """ Get nearest words with KDTree, ranking by cosine distance """ word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(p...
Get nearest words with KDTree, ranking by cosine distance
def save_figure(self, event=None, transparent=False, dpi=600): """ save figure image to file""" file_choices = "PNG (*.png)|*.png|SVG (*.svg)|*.svg|PDF (*.pdf)|*.pdf" try: ofile = self.conf.title.strip() except: ofile = 'Image' if len(ofile) > 64: ...
save figure image to file
def set_num_special_tokens(self, num_special_tokens): """ Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings """ self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer...
Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings
def get_instance(self, payload): """ Build an instance of TaskQueueInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance ...
Build an instance of TaskQueueInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
def is_symbol(string): """ Return true if the string is a mathematical symbol. """ return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == '(') or (string == ')') )
Return true if the string is a mathematical symbol.
def map_trigger(library, session, trigger_source, trigger_destination, mode): """Map the specified trigger source line to the specified destination line. Corresponds to viMapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identif...
Map the specified trigger source line to the specified destination line. Corresponds to viMapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param trigger_source: Source line from which to map. (Constant...
def getAllSystemVariables(self, remote): """Get all system variables from CCU / Homegear""" variables = {} if self.remotes[remote]['username'] and self.remotes[remote]['password']: LOG.debug( "ServerThread.getAllSystemVariables: Getting all System variables via JSON-R...
Get all system variables from CCU / Homegear
def build_time(start_time): """ Calculate build time per package """ diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list...
Calculate build time per package
def interfaces_info(): """Returns interfaces data. """ def replace(value): if value == netifaces.AF_LINK: return 'link' if value == netifaces.AF_INET: return 'ipv4' if value == netifaces.AF_INET6: return 'ipv6' return value results = {...
Returns interfaces data.
def _append_array(self, value, _file): """Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _labs = ' [' _file.write(_labs) self._tctr += 1 for _item in...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise Typ...
Return string value of scalar, whatever value it was parsed as.
def kids(tup_tree): """ Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out. """ k = tup_tree[2] if k is None: return [] # pylint: disa...
Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out.
def _get_offset_day(self, other): """ Find the day in the same month as other that has the same weekday as self.weekday and is the self.week'th such day in the month. Parameters ---------- other : datetime Returns ------- day : int """ ...
Find the day in the same month as other that has the same weekday as self.weekday and is the self.week'th such day in the month. Parameters ---------- other : datetime Returns ------- day : int
def read_properties(group): """Returns properties loaded from a group""" if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
Returns properties loaded from a group
def __fork_pty(self): """This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue wit...
This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporti...
def _html(title: str, field_names: List[str]) -> str: """ Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model. """ inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field...
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model.
def fromstring(text, schema=None): """Parses a KML text string This function parses a KML text string and optionally validates it against a provided schema object""" if schema: parser = objectify.makeparser(schema = schema.schema) return objectify.fromstring(text, parser=parser) ...
Parses a KML text string This function parses a KML text string and optionally validates it against a provided schema object
def is_valid_name_error(name: str, node: Node = None) -> Optional[GraphQLError]: """Return an Error if a name is invalid.""" if not isinstance(name, str): raise TypeError("Expected string") if name.startswith("__"): return GraphQLError( f"Name {name!r} must not begin with '__'," ...
Return an Error if a name is invalid.
def start(self): """ Starts the GNS3 VM. """ vms = yield from self.list() for vm in vms: if vm["vmname"] == self.vmname: self._vmx_path = vm["vmx_path"] break # check we have a valid VMX file path if not self._vmx_path...
Starts the GNS3 VM.
def decode_union_old(self, data_type, obj): """ The data_type argument must be a Union. See json_compat_obj_decode() for argument descriptions. """ val = None if isinstance(obj, six.string_types): # Union member has no associated value tag = obj ...
The data_type argument must be a Union. See json_compat_obj_decode() for argument descriptions.
def __find_sentence_initial_proper_names(self, docs): """ Moodustame lausealguliste pรคrisnimede loendi: vaatame sรตnu, millel nii pรคrisnimeanalรผรผs(id) kui ka mittepรคrisnimeanalรผรผs(id) ning mis esinevad lause vรตi nummerdatud loendi alguses - jรครคdvustame selliste sรตnade unikaa...
Moodustame lausealguliste pรคrisnimede loendi: vaatame sรตnu, millel nii pรคrisnimeanalรผรผs(id) kui ka mittepรคrisnimeanalรผรผs(id) ning mis esinevad lause vรตi nummerdatud loendi alguses - jรครคdvustame selliste sรตnade unikaalsed lemmad;
def subscribe_multi(self, topics): """Subscribe to some topics.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", ', '.join([t for (t,q) in topics])) return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, q...
Subscribe to some topics.
def before_after_send_handling(self): """Context manager that allows to execute send wrapped in before_send() and after_send(). """ self._init_delivery_statuses_dict() self.before_send() try: yield finally: self.after_send() ...
Context manager that allows to execute send wrapped in before_send() and after_send().
def _set_nsx_controller(self, v, load=False): """ Setter method for nsx_controller, mapped from YANG variable /nsx_controller (list) If this variable is read-only (config: false) in the source YANG file, then _set_nsx_controller is considered as a private method. Backends looking to populate this va...
Setter method for nsx_controller, mapped from YANG variable /nsx_controller (list) If this variable is read-only (config: false) in the source YANG file, then _set_nsx_controller is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nsx_contr...
def _validate_geometry(self, geometry): """Validates geometry, raising error if invalid.""" if geometry is not None and geometry not in self.valid_geometries: raise InvalidParameterError("{} is not a valid geometry".format(geometry)) return geometry
Validates geometry, raising error if invalid.
def convert_conelp(c, G, h, dims, A = None, b = None, **kwargs): """ Applies the clique conversion method of Fukuda et al. to the positive semidefinite blocks of a cone LP. :param c: :py:class:`matrix` :param G: :py:class:`spmatrix` :param h: :py:clas...
Applies the clique conversion method of Fukuda et al. to the positive semidefinite blocks of a cone LP. :param c: :py:class:`matrix` :param G: :py:class:`spmatrix` :param h: :py:class:`matrix` :param dims: dictionary :param A: ...
def mode_reader(self): """MODE READER command. Instructs a mode-switching server to switch modes. See <http://tools.ietf.org/html/rfc3977#section-5.3> Returns: Boolean value indicating whether posting is allowed or not. """ code, message = self.command("MOD...
MODE READER command. Instructs a mode-switching server to switch modes. See <http://tools.ietf.org/html/rfc3977#section-5.3> Returns: Boolean value indicating whether posting is allowed or not.
def _capture_as_text(capture: Callable[..., Any]) -> str: """Convert the capture function into its text representation by parsing the source code of the decorator.""" if not icontract._represent._is_lambda(a_function=capture): signature = inspect.signature(capture) param_names = list(signature.p...
Convert the capture function into its text representation by parsing the source code of the decorator.
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == p...
Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376
def _pys2row_heights(self, line): """Updates row_heights in code_array""" # Split with maxsplit 3 split_line = self._split_tidy(line) key = row, tab = self._get_key(*split_line[:2]) height = float(split_line[2]) shape = self.code_array.shape try: if...
Updates row_heights in code_array
def generate_name(self, name=None): '''generate a Robot Name for the instance to use, if the user doesn't supply one. ''' # If no name provided, use robot name if name == None: name = self.RobotNamer.generate() self.name = name.replace('-','_')
generate a Robot Name for the instance to use, if the user doesn't supply one.
def batchccn(args): """ %prog batchccn test.csv Run CCN script in batch. Write makefile. """ p = OptionParser(batchccn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args mm = MakeManager() pf = op.basename(csvfile)....
%prog batchccn test.csv Run CCN script in batch. Write makefile.
def periodicvar_recovery(fakepfpkl, simbasedir, period_tolerance=1.0e-3): '''Recovers the periodic variable status/info for the simulated PF result. - Uses simbasedir and the lcfbasename stored in fakepfpkl to figure out where the LC for this object is. ...
Recovers the periodic variable status/info for the simulated PF result. - Uses simbasedir and the lcfbasename stored in fakepfpkl to figure out where the LC for this object is. - Gets the actual_varparams, actual_varperiod, actual_vartype, actual_varamplitude elements from the LC. - Figures out...
def to_json(self) -> dict: '''export the Deck object to json-ready format''' d = self.__dict__ d['p2th_wif'] = self.p2th_wif return d
export the Deck object to json-ready format
def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) c...
Does the actual work for file.psed, so that single lines can be passed in
async def get_soundfield(self) -> List[Setting]: """Get the current sound field settings.""" res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"}) return Setting.make(**res[0])
Get the current sound field settings.
def _numpy_index_by_percentile(self, data, percentile): """ Calculate percentile of numpy stack and return the index of the chosen pixel. numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher', 'midpoint', 'nearest'} """ d...
Calculate percentile of numpy stack and return the index of the chosen pixel. numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
def _from_dict(cls, _dict): """Initialize a QueryRelationsResponse object from a json dictionary.""" args = {} if 'relations' in _dict: args['relations'] = [ QueryRelationsRelationship._from_dict(x) for x in (_dict.get('relations')) ] ...
Initialize a QueryRelationsResponse object from a json dictionary.
def getUnitCost(self, CorpNum): """ ํŒฉ์Šค ์ „์†ก ๋‹จ๊ฐ€ ํ™•์ธ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ return ์ „์†ก ๋‹จ๊ฐ€ by float raise PopbillException """ result = self._httpget('/FAX/UnitCost', CorpNum) return int(result.unitCost)
ํŒฉ์Šค ์ „์†ก ๋‹จ๊ฐ€ ํ™•์ธ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ return ์ „์†ก ๋‹จ๊ฐ€ by float raise PopbillException
def cli(env, account_id): """List origin pull mappings.""" manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table(['id', 'media_type', 'cname', 'origin_url']) for origin in origins: table.add_row([origin['id'], ...
List origin pull mappings.
def create_temporaries(self, r=True, f=True): """Allocate and store reusable temporaries. Existing temporaries are overridden. Parameters ---------- r : bool, optional Create temporary for the real space f : bool, optional Create temporary for th...
Allocate and store reusable temporaries. Existing temporaries are overridden. Parameters ---------- r : bool, optional Create temporary for the real space f : bool, optional Create temporary for the frequency space Notes ----- To...
def process_header(self, headers): """Ignore the incomming header and replace it with the destination header""" return [c.name for c in self.source.dest_table.columns][1:]
Ignore the incomming header and replace it with the destination header
def _upload_folder_recursive(local_folder, parent_folder_id, leaf_folders_as_items=False, reuse_existing=False): """ Function to recursively upload a folder and all of its descendants. :param local_folder: full path to l...
Function to recursively upload a folder and all of its descendants. :param local_folder: full path to local folder to be uploaded :type local_folder: string :param parent_folder_id: id of parent folder on the Midas Server instance, where the new folder will be added :type parent_folder_id: int ...
async def i2c_read_request(self, address, register, number_of_bytes, read_type, cb=None, cb_type=None): """ This method requests the read of an i2c device. Results are retrieved by a call to i2c_get_read_data(). or by callback. If a callback method is prov...
This method requests the read of an i2c device. Results are retrieved by a call to i2c_get_read_data(). or by callback. If a callback method is provided, when data is received from the device it will be sent to the callback method. Some devices require that transmission be restarted ...
def write_config_file(self, params, path): """ write a config file for this single exp in the folder path. """ cfgp = ConfigParser() cfgp.add_section(params['name']) for p in params: if p == 'name': continue cfgp.set(params['name'], p, para...
write a config file for this single exp in the folder path.
def text_bounding_box(self, size_pt, text): """ Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height) """ if size_pt == 12: mul...
Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height)
def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): """Return whether all elements are True over requested axis Note: If axis=None or axis=0, this call applies df.all(axis=1) to the transpose of df. """ if axis is not None: ...
Return whether all elements are True over requested axis Note: If axis=None or axis=0, this call applies df.all(axis=1) to the transpose of df.
def get_new_broks(self): """Get new broks from our satellites :return: None """ for satellites in [self.schedulers, self.pollers, self.reactionners, self.receivers]: for satellite_link in list(satellites.values()): logger.debug("Getting broks from %s", satell...
Get new broks from our satellites :return: None
def pytwis_clt(): """The main routine of this command-line tool.""" epilog = '''After launching `pytwis_clt.py`, you will be able to use the following commands: * Register a new user: 127.0.0.1:6379> register {username} {password} * Log into a user: 127.0.0.1:6379> login {username}...
The main routine of this command-line tool.
def _get_field(self, field_name, default=None): """ Fetches a field from extras, and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page, which allow admins to specify scopes, credential pem files, etc. They get formatted as shown b...
Fetches a field from extras, and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page, which allow admins to specify scopes, credential pem files, etc. They get formatted as shown below.
def connect(self, slot): """ Connects the signal to any callable object """ if not callable(slot): raise ValueError("Connection to non-callable '%s' object failed" % slot.__class__.__name__) if (isinstance(slot, partial) or '<' in slot.__name__): # If it'...
Connects the signal to any callable object
def get_ip_interface_output_interface_vrf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface output = ET.SubElement(get_ip_interface, "output") interface = ET.SubEle...
Auto Generated Code
def entity(self): """ Returns the object this grant is for. The objects type depends on the type of object this grant is applied to, and the object returned is not populated (accessing its attributes will trigger an api request). :returns: This grant's entity :rtype: Li...
Returns the object this grant is for. The objects type depends on the type of object this grant is applied to, and the object returned is not populated (accessing its attributes will trigger an api request). :returns: This grant's entity :rtype: Linode, NodeBalancer, Domain, StackScrip...
def list_namespaced_service_account(self, namespace, **kwargs): """ list or watch objects of kind ServiceAccount This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_service_acco...
list or watch objects of kind ServiceAccount This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_service_account(namespace, async_req=True) >>> result = thread.get() :param asy...
def DeserializeMessage(self, response_type, data): """Deserialize the given data as method_config.response_type.""" try: message = encoding.JsonToMessage(response_type, data) except (exceptions.InvalidDataFromServerError, messages.ValidationError, ValueError) as e: ...
Deserialize the given data as method_config.response_type.
def _update_prx(self): """Update `prx` from `phi`, `pi_codon`, and `beta`.""" qx = scipy.ones(N_CODON, dtype='float') for j in range(3): for w in range(N_NT): qx[CODON_NT[j][w]] *= self.phi[w] frx = self.pi_codon**self.beta self.prx = frx * qx ...
Update `prx` from `phi`, `pi_codon`, and `beta`.
def _read_next_line(self): """Read next line store in self._line and return old one""" prev_line = self._line self._line = self.stream.readline() return prev_line
Read next line store in self._line and return old one
def summary(model, input_size): """ Print summary of the model """ def register_hook(module): def hook(module, input, output): class_name = str(module.__class__).split('.')[-1].split("'")[0] module_idx = len(summary) m_key = '%s-%i' % (class_name, module_idx + 1) ...
Print summary of the model
def can_group_commands(command, next_command): """ Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ...
Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ``get`` commands: - Are all arguments other than the k...
def add_handler(self, type, actions, **kwargs): """ Add an event handler to be processed by this session. type - The type of the event (pygame.QUIT, pygame.KEYUP ETC). actions - The methods which should be called when an event matching this specification is received. more than ...
Add an event handler to be processed by this session. type - The type of the event (pygame.QUIT, pygame.KEYUP ETC). actions - The methods which should be called when an event matching this specification is received. more than one action can be tied to a single event. This allows for secondary ...
def literal_struct(cls, elems): """ Construct a literal structure constant made of the given members. """ tys = [el.type for el in elems] return cls(types.LiteralStructType(tys), elems)
Construct a literal structure constant made of the given members.
def remove_repeat_coordinates(x, y, z): r"""Remove all x, y, and z where (x,y) is repeated and keep the first occurrence only. Will not destroy original values. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation val...
r"""Remove all x, y, and z where (x,y) is repeated and keep the first occurrence only. Will not destroy original values. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation value Returns ------- x, y, z ...
def compute_best_path(local_asn, path1, path2): """Compares given paths and returns best path. Parameters: -`local_asn`: asn of local bgpspeaker -`path1`: first path to compare -`path2`: second path to compare Best path processing will involve following steps: 1. Select a path...
Compares given paths and returns best path. Parameters: -`local_asn`: asn of local bgpspeaker -`path1`: first path to compare -`path2`: second path to compare Best path processing will involve following steps: 1. Select a path with a reachable next hop. 2. Select the path wit...
def getFaxStatsSessions(self): """Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictionary of fax stats. """ if not self.hasFax(): return None info_dict = {} info_dict['total'] = 0 ...
Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictionary of fax stats.
def _worker_process(self): # type: (LocalFileMd5Offload) -> None """Compute MD5 for local file :param LocalFileMd5Offload self: this """ while not self.terminated: try: key, lpath, fpath, remote_md5, pagealign, lpview = \ self._task...
Compute MD5 for local file :param LocalFileMd5Offload self: this
def create_project(self, name, **kwargs): """ Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`. """ data = s...
Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`.
def _ip_is_usable(self, current_ip): """ Check if the current Tor's IP is usable. :argument current_ip: current Tor IP :type current_ip: str :returns bool """ # Consider IP addresses only. try: ipaddress.ip_address(current_ip) except ...
Check if the current Tor's IP is usable. :argument current_ip: current Tor IP :type current_ip: str :returns bool
def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None): """Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, ...
Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size, latent_size, num_codes]. scale_weights: Tensor corresponding to lower triangular matrix used to autoregressively generate scale matrix from ...
def prt_gene_aart_details(self, geneids, prt=sys.stdout): """For each gene, print ASCII art which represents its associated GO IDs.""" _go2nt = self.sortobj.grprobj.go2nt patgene = self.datobj.kws["fmtgene2"] patgo = self.datobj.kws["fmtgo2"] itemid2name = self.datobj.kws.get("it...
For each gene, print ASCII art which represents its associated GO IDs.
def add_data(self, conf): """ Add data to the graph object. May be called several times to add additional data sets. conf should be a dictionary including 'data' and 'title' keys """ self.validate_data(conf) self.process_data(conf) self.data.append(conf)
Add data to the graph object. May be called several times to add additional data sets. conf should be a dictionary including 'data' and 'title' keys
def cleanup(self): """ Clean up children and remove the directory. Directory will only be removed if the cleanup flag is set. """ for k in self._children: self._children[k].cleanup() if self._cleanup: self.remove(True)
Clean up children and remove the directory. Directory will only be removed if the cleanup flag is set.
def color_palette(name=None, n_colors=6, desat=None): """Return a list of colors defining a color palette. Availible seaborn palette names: deep, muted, bright, pastel, dark, colorblind Other options: hls, husl, any matplotlib palette Matplotlib paletes can be specified as reversed pa...
Return a list of colors defining a color palette. Availible seaborn palette names: deep, muted, bright, pastel, dark, colorblind Other options: hls, husl, any matplotlib palette Matplotlib paletes can be specified as reversed palettes by appending "_r" to the name or as dark palettes ...