code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def handle_truncated_response(callback, params, entities): """ Handle truncated responses :param callback: :param params: :param entities: :return: """ results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False ...
Handle truncated responses :param callback: :param params: :param entities: :return:
def parse_cctop_full(infile): """Parse a CCTOP XML results file and return a list of the consensus TM domains in the format:: [(1, inside_outside_or_tm), (2, inside_outside_or_tm), ...] Where the first value of a tuple is the sequence residue number, and the second is the...
Parse a CCTOP XML results file and return a list of the consensus TM domains in the format:: [(1, inside_outside_or_tm), (2, inside_outside_or_tm), ...] Where the first value of a tuple is the sequence residue number, and the second is the predicted location with the valu...
def unsubscribe(self, tag, match_type=None): ''' Un-subscribe to events matching the passed tag. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.remove([tag, match_func]) old_events = self.pending_events ...
Un-subscribe to events matching the passed tag.
def _get_files(extension, path): """ Returns a sorted list of all of the files having the same extension under the same directory :param extension: the extension of the data files such as 'gdm' :param path: path to the folder containing the files :return: sorted list of files ...
Returns a sorted list of all of the files having the same extension under the same directory :param extension: the extension of the data files such as 'gdm' :param path: path to the folder containing the files :return: sorted list of files
def serialize_to_string( root_processor, # type: RootProcessor value, # type: Any indent=None # type: Optional[Text] ): # type: (...) -> Text """ Serialize the value to an XML string using the root processor. :return: The serialized XML string. See also :func:`declxml.se...
Serialize the value to an XML string using the root processor. :return: The serialized XML string. See also :func:`declxml.serialize_to_file`
def write_to_file(self): """ Writes the weeks with associated commits to file. """ with open('../github_stats_output/last_year_commits.csv', 'w+') as output: output.write('date,organization,repos,members,teams,' + 'unique_contributors,total_contributors,forks,...
Writes the weeks with associated commits to file.
def infer_namespace(ac): """Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one nam...
Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infe...
def get_id(self): """ get unique identifier of this container :return: str """ if self._id is None: # FIXME: provide a better error message when key is not defined self._id = self.inspect(refresh=False)["Id"] return self._id
get unique identifier of this container :return: str
def update_contents(self, contents, mime_type): """Update the contents and set the hash and modification time""" import hashlib import time new_size = len(contents) self.mime_type = mime_type if mime_type == 'text/plain': self.contents = contents.encode('ut...
Update the contents and set the hash and modification time
def gaussian_filter(self, sigma=2, order=0): """ Spatially smooth images with a gaussian filter. Filtering will be applied to every image in the collection. Parameters ---------- sigma : scalar or sequence of scalars, default = 2 Size of the filter size as s...
Spatially smooth images with a gaussian filter. Filtering will be applied to every image in the collection. Parameters ---------- sigma : scalar or sequence of scalars, default = 2 Size of the filter size as standard deviation in pixels. A sequence is interprete...
def tokens_required(scopes='', new=False): """ Decorator for views to request an ESI Token. Accepts required scopes as a space-delimited string or list of strings of scope names. Can require a new token to be retrieved by SSO. Returns a QueryDict of Tokens. """ def decorator(view_func):...
Decorator for views to request an ESI Token. Accepts required scopes as a space-delimited string or list of strings of scope names. Can require a new token to be retrieved by SSO. Returns a QueryDict of Tokens.
def _fetch_access_token(self, url, data): """ The real fetch access token """ logger.info('Fetching component access token') res = self._http.post( url=url, data=data ) try: res.raise_for_status() except requests.RequestException as req...
The real fetch access token
def xtqx(self): """get the normal matrix attribute. Create the attribute if it has not yet been created Returns ------- xtqx : pyemu.Matrix """ if self.__xtqx is None: self.log("xtqx") self.__xtqx = self.jco.T * (self.obscov ** -1) * self...
get the normal matrix attribute. Create the attribute if it has not yet been created Returns ------- xtqx : pyemu.Matrix
def positions(self, reverse=False): """returns a generator that walks the positions of this tree in DFO""" def Posgen(reverse): if reverse: lastrootsib = self.last_sibling_position(self.root) current = self.last_decendant(lastrootsib) while cur...
returns a generator that walks the positions of this tree in DFO
def add_init_files(path, zip_handler): """ adds init files to the included folder :param path: str """ paths = path.split('\\') paths = paths[:len(paths) - 1] for sub_path in paths: for root, dirs, files in os.walk(sub_path): for file_to_zip in [x for x in files if '__in...
adds init files to the included folder :param path: str
def create_volume(self, availability_zone, size=None, snapshot_id=None): """Create a new volume.""" params = {"AvailabilityZone": availability_zone} if ((snapshot_id is None and size is None) or (snapshot_id is not None and size is not None)): raise ValueError("Please pro...
Create a new volume.
def parent(self) -> Optional['CtsReference']: """ Parent of the actual URN, for example, 1.1 for 1.1.1 :rtype: CtsReference """ if self.start.depth == 1 and (self.end is None or self.end.depth <= 1): return None else: if self.start.depth > 1 and (self.end...
Parent of the actual URN, for example, 1.1 for 1.1.1 :rtype: CtsReference
def create_table( self, parent, table_id, table, initial_splits=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new table in the specified instance. ...
Creates a new table in the specified instance. The table can be created with a full set of initial column families, specified in the request. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient()...
def save(self, record_key, record_data, overwrite=True, secret_key=''): ''' a method to create a record in the collection folder :param record_key: string with name to assign to record (see NOTES below) :param record_data: byte data for record body :param overwrite:...
a method to create a record in the collection folder :param record_key: string with name to assign to record (see NOTES below) :param record_data: byte data for record body :param overwrite: [optional] boolean to overwrite records with same name :param secret_key: [optional] string...
def free_memory(cls, exclude=None): """Free global annotation memory.""" annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__ exclude = () if exclude is None else exclude for annotation_cls in list(annotations_in_memory.keys()): if issubclass(annotation_cls, exclu...
Free global annotation memory.
def load_generated_checkers(cls, args): """ Load checker classes from generator plugins """ for gen in cls._get_generator_plugins(): checkers = gen.get_checkers(args) cls.checkers.update(checkers)
Load checker classes from generator plugins
def logistic_map(x, steps, r=4): r""" Generates a time series of the logistic map. Characteristics and Background: The logistic map is among the simplest examples for a time series that can exhibit chaotic behavior depending on the parameter r. For r between 2 and 3, the series quickly becomes stati...
r""" Generates a time series of the logistic map. Characteristics and Background: The logistic map is among the simplest examples for a time series that can exhibit chaotic behavior depending on the parameter r. For r between 2 and 3, the series quickly becomes static. At r=3 the first bifurcation poi...
def main(): '''Main routine.''' # process arguments if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss = sys.argv[2] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFound...
Main routine.
def run(juttle, deployment_name, program_name=None, persist=False, token_manager=None, app_url=defaults.APP_URL): """ run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: ...
run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: * Initial job status details including information to associate multiple flowgraphs with their individual outputs (sinks): { "status":...
def RdatasetsBM(database,host=rbiomart_host): """ Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") ensemblMart=bi...
Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing
def ls(self): """Return a list of *all* files & dirs in the repo. Think of this as a recursive `ls` command from the root of the repo. """ tree = self.ls_tree() return [t.get('file') for t in tree if t.get('file')]
Return a list of *all* files & dirs in the repo. Think of this as a recursive `ls` command from the root of the repo.
def get_lonlatalt(self, utc_time): """Calculate sublon, sublat and altitude of satellite. http://celestrak.com/columns/v02n03/ """ (pos_x, pos_y, pos_z), (vel_x, vel_y, vel_z) = self.get_position( utc_time, normalize=True) lon = ((np.arctan2(pos_y * XKMPER, pos_x * X...
Calculate sublon, sublat and altitude of satellite. http://celestrak.com/columns/v02n03/
def visible_object_groups(self): """Return iterator of object group indexes that are set 'visible' :rtype: Iterator """ return (i for (i, l) in enumerate(self.layers) if l.visible and isinstance(l, TiledObjectGroup))
Return iterator of object group indexes that are set 'visible' :rtype: Iterator
def list_joined_groups(self, user_alias=None): """ 已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表 """ xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias)) xml_results = xml.xpath('//div[@class="group-list group-ca...
已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表
def log(self, string): """ appends input string to log file and sends it to log function (self.log_function) Returns: """ self.log_data.append(string) if self.log_function is None: print(string) else: self.log_function(string)
appends input string to log file and sends it to log function (self.log_function) Returns:
def get_name(obj, setting_name='LONG_NAME_FORMAT'): """ Returns the correct order of the name according to the current language. """ nickname = obj.get_nickname() romanized_first_name = obj.get_romanized_first_name() romanized_last_name = obj.get_romanized_last_name() non_romanized_first_na...
Returns the correct order of the name according to the current language.
def serialize_dict(self, attr, dict_type, **kwargs): """Serialize a dictionary of objects. :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. :param bool required: Whether the objects in the dictionary must not be None or empty. ...
Serialize a dictionary of objects. :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. :param bool required: Whether the objects in the dictionary must not be None or empty. :rtype: dict
def _build_layers(self, inputs, num_outputs, options): """Process the flattened inputs. Note that dict inputs will be flattened into a vector. To define a model that processes the components separately, use _build_layers_v2(). """ hiddens = options.get("fcnet_hiddens") ...
Process the flattened inputs. Note that dict inputs will be flattened into a vector. To define a model that processes the components separately, use _build_layers_v2().
def isID(self, elem, attr): """Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically. """ if elem is None...
Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically.
def _get_encoder_data_shapes(self, bucket_key: int, batch_size: int) -> List[mx.io.DataDesc]: """ Returns data shapes of the encoder module. :param bucket_key: Maximum input length. :param batch_size: Batch size. :return: List of data descriptions. """ return [mx...
Returns data shapes of the encoder module. :param bucket_key: Maximum input length. :param batch_size: Batch size. :return: List of data descriptions.
def check_auth(email, password): """Check if a username/password combination is valid. """ try: user = User.get(User.email == email) except User.DoesNotExist: return False return password == user.password
Check if a username/password combination is valid.
def _pip_search(stdout, stderr): """Callback for pip search.""" result = {} lines = to_text_string(stdout).split('\n') while '' in lines: lines.remove('') for line in lines: if ' - ' in line: parts = line.split(' - ') name ...
Callback for pip search.
def parse_request(self): """Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back...
Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.
def get_lsf_status(): """Count and print the number of jobs in various LSF states """ status_count = {'RUN': 0, 'PEND': 0, 'SUSP': 0, 'USUSP': 0, 'NJOB': 0, 'UNKNWN': 0} try: subproc = subprocess...
Count and print the number of jobs in various LSF states
def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementation.createDocument(None, "sv...
Create default SVG document
def dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.""" for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit']['url']) return parse_timestamp(commit['commit']['committer']['date']) retu...
Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.
def register_parser(self, type, parser, **meta): """Registers a parser of a format. :param type: The unique name of the format :param parser: The method to parse data as the format :param meta: The extra information associated with the format """ try: self.re...
Registers a parser of a format. :param type: The unique name of the format :param parser: The method to parse data as the format :param meta: The extra information associated with the format
def home_mode_status(self, **kwargs): """Returns the status of Home Mode""" api = self._api_info['home_mode'] payload = dict({ 'api': api['name'], 'method': 'GetInfo', 'version': api['version'], '_sid': self._sid }, **kwargs) respon...
Returns the status of Home Mode
def all(cls, client, **kwargs): """ fetch all option positions """ max_date = kwargs['max_date'] if 'max_date' in kwargs else None max_fetches = \ kwargs['max_fetches'] if 'max_fetches' in kwargs else None url = 'https://api.robinhood.com/options/positions/' ...
fetch all option positions
def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT): """ Create an object instance of the given class from the given module. Args and kwargs are passed to the constructor. This mimics the following code: .. code-block:: python from m...
Create an object instance of the given class from the given module. Args and kwargs are passed to the constructor. This mimics the following code: .. code-block:: python from module import class return class(*args, **kwargs) :param module_name: module name :param class_name: clas...
def pivot(self,binned=True): """Calculate :ref:`pivot wavelength <pysynphot-formula-pivwv>` of the observation. .. note:: This is the calculation performed when ETC invokes ``calcphot``. Parameters ---------- binned : bool Use binned dataset for...
Calculate :ref:`pivot wavelength <pysynphot-formula-pivwv>` of the observation. .. note:: This is the calculation performed when ETC invokes ``calcphot``. Parameters ---------- binned : bool Use binned dataset for calculations. Otherwise, use native dat...
def main(): """Given an input whl file and target version, create a copy of the whl with that version. This is accomplished via string replacement in files matching a list of globs. Pass the optional `--glob` argument to add additional globs: ie `--glob='thing-to-match*.txt'`. """ parser = argparse.Argument...
Given an input whl file and target version, create a copy of the whl with that version. This is accomplished via string replacement in files matching a list of globs. Pass the optional `--glob` argument to add additional globs: ie `--glob='thing-to-match*.txt'`.
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getp...
Main code
def activate_status_output_overall_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") activate_status = ET.Element("activate_status") config = activate_status output = ET.SubElement(activate_status, "output") overall_status = ET.SubEl...
Auto Generated Code
def parse_time(timestring): """Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() ...
Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object.
def get_list(self, url=None, callback=None, limit=100, **data): """Get a list of this github component :param url: full url :param Comp: a :class:`.Component` class :param callback: Optional callback :param limit: Optional number of items to retrieve :param data: addition...
Get a list of this github component :param url: full url :param Comp: a :class:`.Component` class :param callback: Optional callback :param limit: Optional number of items to retrieve :param data: additional query data :return: a list of ``Comp`` objects with data
def _handle_successor(self, job, successor, successors): """ Returns a new CFGJob instance for further analysis, or None if there is no immediate state to perform the analysis on. :param CFGJob job: The current job. """ state = successor all_successor_states = s...
Returns a new CFGJob instance for further analysis, or None if there is no immediate state to perform the analysis on. :param CFGJob job: The current job.
def getKwAsDict(self, kw): """ return keyword configuration as a dict Usage: rdict = getKwAsDict(kw) """ self.getKw(kw) return self.str2dict(self.confstr)
return keyword configuration as a dict Usage: rdict = getKwAsDict(kw)
def get_order_detail(self, code): """ 查询A股Level 2权限下提供的委托明细 :param code: 股票代码,例如:'HK.02318' :return: (ret, data) ret == RET_OK data为1个dict,包含以下数据 ret != RET_OK data为错误字符串 {‘code’: 股票代码 ‘Ask’:[ order_num, [order_volume1, ...
查询A股Level 2权限下提供的委托明细 :param code: 股票代码,例如:'HK.02318' :return: (ret, data) ret == RET_OK data为1个dict,包含以下数据 ret != RET_OK data为错误字符串 {‘code’: 股票代码 ‘Ask’:[ order_num, [order_volume1, order_volume2] ] ‘Bid’: [ order_num, [...
def calculate_rate(phone_number, address_country_code=None, address_exception=None): """ Calculates the VAT rate based on a telephone number :param phone_number: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as det...
Calculates the VAT rate based on a telephone number :param phone_number: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from...
def _Rforce(self, R, z, phi=0, t=0): """ NAME: _Rforce PURPOSE: evaluate the radial force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: rad...
NAME: _Rforce PURPOSE: evaluate the radial force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: radial force at (R,z, phi) HISTORY: 2016-...
def _set_attributes_on_managed_object(self, managed_object, attributes): """ Given a kmip.pie object and a dictionary of attributes, attempt to set the attribute values on the object. """ for attribute_name, attribute_value in six.iteritems(attributes): object_type = ...
Given a kmip.pie object and a dictionary of attributes, attempt to set the attribute values on the object.
def do_capture(parser, token): """ Capture the contents of a tag output. Usage: .. code-block:: html+django {% capture %}..{% endcapture %} # output in {{ capture }} {% capture silent %}..{% endcapture %} # output in {{ capture }} only {% capture ...
Capture the contents of a tag output. Usage: .. code-block:: html+django {% capture %}..{% endcapture %} # output in {{ capture }} {% capture silent %}..{% endcapture %} # output in {{ capture }} only {% capture as varname %}..{% endcapture %} # o...
def parameters_to_segments(origins, vectors, parameters): """ Convert a parametric line segment representation to a two point line segment representation Parameters ------------ origins : (n, 3) float Line origin point vectors : (n, 3) float Unit line directions parameters...
Convert a parametric line segment representation to a two point line segment representation Parameters ------------ origins : (n, 3) float Line origin point vectors : (n, 3) float Unit line directions parameters : (n, 2) float Start and end distance pairs for each line ...
def _remote_connection(server, opts, argparser_): """Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc. """ global CONN # pylint: disable=global-statement if opts.timeout is not N...
Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc.
def load_vocab(self, vocab_name, **kwargs): """ loads a vocabulary into the defintion triplestore args: vocab_name: the prefix, uri or filename of a vocabulary """ log.setLevel(kwargs.get("log_level", self.log_level)) vocab = self.get_vocab(vocab_name , **kwargs) ...
loads a vocabulary into the defintion triplestore args: vocab_name: the prefix, uri or filename of a vocabulary
def average_precision(truth, recommend): """Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP. """ if len(truth) == 0: if len(recommend) == 0: r...
Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP.
def CaptureFrameLocals(self, frame): """Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple. """ # Capture all local variables (including method arguments). variables = {n: self.Captur...
Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple.
def __json_strnum_to_bignum(json_object): """ Converts json string numerals to native python bignums. """ for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'): if (key in json_object and isinstance(json_object[key], six....
Converts json string numerals to native python bignums.
def example_lab_to_ipt(): """ This function shows a simple conversion of an XYZ color to an IPT color. """ print("=== Simple Example: XYZ->IPT ===") # Instantiate an XYZ color object with the given values. xyz = XYZColor(0.5, 0.5, 0.5, illuminant='d65') # Show a string representation. p...
This function shows a simple conversion of an XYZ color to an IPT color.
def render_tile(cells, ti, tj, render, params, metadata, layout, summary): """ Render each cell in the tile and stitch it into a single image """ image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_size), (255,255,255)) keys = cells.keys() for i,key in enumerat...
Render each cell in the tile and stitch it into a single image
def get_bins_by_query(self, bin_query): """Gets a list of ``Bins`` matching the given bin query. arg: bin_query (osid.resource.BinQuery): the bin query return: (osid.resource.BinList) - the returned ``BinList`` raise: NullArgument - ``bin_query`` is ``null`` raise: Operatio...
Gets a list of ``Bins`` matching the given bin query. arg: bin_query (osid.resource.BinQuery): the bin query return: (osid.resource.BinList) - the returned ``BinList`` raise: NullArgument - ``bin_query`` is ``null`` raise: OperationFailed - unable to complete request raise:...
def flattennd(d, levels=0, key_as_tuple=True, delim='.', list_of_dicts=None): """ get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tu...
get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys delim...
def display_notes(self): """Display information about scores and raters. """ if self.annot is not None: short_xml_file = short_strings(basename(self.annot.xml_file)) self.idx_annotations.setText(short_xml_file) # if annotations were loaded without dataset ...
Display information about scores and raters.
def set_primary_key_auto(self, table): """ Analysis a table and set a primary key. Determine primary key by identifying a column with unique values or creating a new column. :param table: Table to alter :return: Primary Key column """ # Confirm no primar...
Analysis a table and set a primary key. Determine primary key by identifying a column with unique values or creating a new column. :param table: Table to alter :return: Primary Key column
def copy_folder_content(src, dst): """ Copy all content in src directory to dst directory. The src and dst must exist. """ for file in os.listdir(src): file_path = os.path.join(src, file) dst_file_path = os.path.join(dst, file) if os.path.isdir(file_path): shutil....
Copy all content in src directory to dst directory. The src and dst must exist.
def cdsthreads(self): """ Determines which core genes from a pre-calculated database are present in each strain """ # Create and start threads for i in range(self.cpus): # Send the threads to the appropriate destination function threads = Thread(target=sel...
Determines which core genes from a pre-calculated database are present in each strain
def get_email_context(self, activation_key): """ Build the template context used for the activation email. """ scheme = 'https' if self.request.is_secure() else 'http' return { 'scheme': scheme, 'activation_key': activation_key, 'expiration_da...
Build the template context used for the activation email.
def get_middle_point(self): """ Return the middle point of the mesh. :returns: An instance of :class:`~openquake.hazardlib.geo.point.Point`. The middle point is taken from the middle row and a middle column of the mesh if there are odd number of both. Otherwise the ...
Return the middle point of the mesh. :returns: An instance of :class:`~openquake.hazardlib.geo.point.Point`. The middle point is taken from the middle row and a middle column of the mesh if there are odd number of both. Otherwise the geometric mean point of two or four midd...
def get_suppressions(relative_filepaths, root, messages): """ Given every message which was emitted by the tools, and the list of files to inspect, create a list of files to ignore, and a map of filepath -> line-number -> codes to ignore """ paths_to_ignore = set() lines_to_ignore = defaultd...
Given every message which was emitted by the tools, and the list of files to inspect, create a list of files to ignore, and a map of filepath -> line-number -> codes to ignore
def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None, network_type='walk', timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): """ Download OSM ways and nodes within a bounding box from the ...
Download OSM ways and nodes within a bounding box from the Overpass API. Parameters ---------- lat_min : float southern latitude of bounding box lng_min : float eastern longitude of bounding box lat_max : float northern latitude of bounding box lng_max : float we...
def compute_before_after(self): """Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code. """ if not self.parsed: self._parse() list_from = self.input_lines list_...
Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code.
def _get_node_column(cls, node, column_name): """Given a ParsedNode, add some fields that might be missing. Return a reference to the dict that refers to the given column, creating it if it doesn't yet exist. """ if not hasattr(node, 'columns'): node.set('columns', {}...
Given a ParsedNode, add some fields that might be missing. Return a reference to the dict that refers to the given column, creating it if it doesn't yet exist.
def get_active_project_path(self): """Get path of the active project""" active_project_path = None if self.current_active_project: active_project_path = self.current_active_project.root_path return active_project_path
Get path of the active project
def child_allocation(self): """ The sum of all child asset classes' allocations """ sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: # This is not a branch but a leaf. Return own allocation. ...
The sum of all child asset classes' allocations
def get_index_by_alias(self, alias): """Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name """ try: info = self.es.indices.get_alias(name=alias) return next(iter(info.keys())) except elasticsearch....
Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name
def strings(self, otherchar=None): ''' Each time next() is called on this iterator, a new string is returned which will the present lego piece can match. StopIteration is raised once all such strings have been returned, although a regex with a * in may match infinitely many strings. ''' # In the case...
Each time next() is called on this iterator, a new string is returned which will the present lego piece can match. StopIteration is raised once all such strings have been returned, although a regex with a * in may match infinitely many strings.
def get_element_name(parent, ns): # type: (_Element, str) -> str """Get element short name.""" name = parent.find('./' + ns + 'SHORT-NAME') if name is not None and name.text is not None: return name.text return ""
Get element short name.
def get_config_groups(self, groups_conf, groups_pillar_name): ''' get info from groups in config, and from the named pillar todo: add specification for the minion to use to recover pillar ''' # Get groups # Default to returning something that'll never match ret_g...
get info from groups in config, and from the named pillar todo: add specification for the minion to use to recover pillar
def _clean(self, rmConnetions=True, lockNonExternal=True): """ Remove all signals from this interface (used after unit is synthesized and its parent is connecting its interface to this unit) """ if self._interfaces: for i in self._interfaces: i._clean...
Remove all signals from this interface (used after unit is synthesized and its parent is connecting its interface to this unit)
def getMetricDetails(self, metricLabel): """ Gets detailed info about a given metric, in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. :param metricLabel: (string) label of the given metric (see :class:`~nupic.frameworks...
Gets detailed info about a given metric, in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. :param metricLabel: (string) label of the given metric (see :class:`~nupic.frameworks.opf.metrics.MetricSpec`) :returns: (dict) of met...
def _parse_group(self, group_name, group): """ Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'. """ if type(group) == dict: # Example: # { # "mgmt": { # "...
Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'.
def frets_to_NoteContainer(self, fingering): """Convert a list such as returned by find_fret to a NoteContainer.""" res = [] for (string, fret) in enumerate(fingering): if fret is not None: res.append(self.get_Note(string, fret)) return NoteContainer(res)
Convert a list such as returned by find_fret to a NoteContainer.
def _assemble_active_form(self, stmt): """Example: p(HGNC:ELK1, pmod(Ph)) => act(p(HGNC:ELK1), ma(tscript))""" act_agent = Agent(stmt.agent.name, db_refs=stmt.agent.db_refs) act_agent.activity = ActivityCondition(stmt.activity, True) activates = stmt.is_active relation = get_caus...
Example: p(HGNC:ELK1, pmod(Ph)) => act(p(HGNC:ELK1), ma(tscript))
def connectQ2Q(self, fromAddress, toAddress, protocolName, protocolFactory, usePrivateCertificate=None, fakeFromDomain=None, chooser=None): """ Connect a named protocol factory from a resource@domain to a resource@domain. This is analagous to someth...
Connect a named protocol factory from a resource@domain to a resource@domain. This is analagous to something like connectTCP, in that it creates a connection-oriented transport for each connection, except instead of specifying your credentials with an application-level (username, ...
def get(self): 'Retrieve the most recent value generated' # If you attempt to use a generator comprehension below, it will # consume the StopIteration exception and just return an empty tuple, # instead of stopping iteration normally return tuple([(x.name(), x.get()) for x in sel...
Retrieve the most recent value generated
def report(self, event, metadata=None, block=None): """ Reports an event to Alooma by formatting it properly and placing it in the buffer to be sent by the Sender instance :param event: A dict / string representing an event :param metadata: (Optional) A dict with extra metadat...
Reports an event to Alooma by formatting it properly and placing it in the buffer to be sent by the Sender instance :param event: A dict / string representing an event :param metadata: (Optional) A dict with extra metadata to be attached to the event :param bl...
def network_security_group_delete(name, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Delete a network security group within a resource group. :param name: The name of the network security group to delete. :param resource_group: The resource group name assigned to the network ...
.. versionadded:: 2019.2.0 Delete a network security group within a resource group. :param name: The name of the network security group to delete. :param resource_group: The resource group name assigned to the network security group. CLI Example: .. code-block:: bash salt-call ...
def _delete(self, state=None): """Helper for :meth:`delete` Adds a delete mutation (for the entire row) to the accumulated mutations. ``state`` is unused by :class:`DirectRow` but is used by subclasses. :type state: bool :param state: (Optional) The state that ...
Helper for :meth:`delete` Adds a delete mutation (for the entire row) to the accumulated mutations. ``state`` is unused by :class:`DirectRow` but is used by subclasses. :type state: bool :param state: (Optional) The state that is passed along to :...
def p(self, value, event): """Return the conditional probability P(X=value | parents=parent_values), where parent_values are the values of parents in event. (event must assign each parent a value.) >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625}) >>> bn.p(False, {'...
Return the conditional probability P(X=value | parents=parent_values), where parent_values are the values of parents in event. (event must assign each parent a value.) >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625}) >>> bn.p(False, {'Burglary': False, 'Earthquake': True})...
def configure(self, options, conf): """ Configure plugin. """ super(LeakDetectorPlugin, self).configure(options, conf) if options.leak_detector_level: self.reporting_level = int(options.leak_detector_level) self.report_delta = options.leak_detector_report_delt...
Configure plugin.
def lock(self): # type: () -> Installer """ Prepare the installer for locking only. """ self.update() self.execute_operations(False) self._lock = True return self
Prepare the installer for locking only.
def downgrade(): """Downgrade database.""" # Remove 'created' and 'updated' columns op.drop_column('oauthclient_remoteaccount', 'created') op.drop_column('oauthclient_remoteaccount', 'updated') op.drop_column('oauthclient_remotetoken', 'created') op.drop_column('oauthclient_remotetoken', 'updat...
Downgrade database.
def solve_gamlasso(self, lam): '''Solves the Graph-fused gamma lasso via POSE (Taddy, 2013)''' weights = lam / (1 + self.gamma * np.abs(self.beta[self.trails[::2]] - self.beta[self.trails[1::2]])) s = self.solve_gfl(u) self.steps.append(s) return self.beta
Solves the Graph-fused gamma lasso via POSE (Taddy, 2013)
def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)): """Compute cartesian coordinates of the pixels in instrument scan.""" if isinstance(orb, (list, tuple)): tle1, tle2 = orb orb = Orbital("mysatellite", line1=tle1, line2=tle2) # get position and velocity for each time of each pixel ...
Compute cartesian coordinates of the pixels in instrument scan.