Search is not available for this dataset
text
stringlengths
75
104k
def __download_from_s3(self, key, dest_dir): """Private method for downloading from S3 This private helper method takes a key and the full path to the destination directory, assumes that the args have been validated by the public caller methods, and attempts to download the spec...
def download_file_by_key(self, key, dest_dir): """Downloads a file by key from the specified S3 bucket This method takes the full 'key' as the arg, and attempts to download the file to the specified dest_dir as the destination directory. This method sets the downloaded filename to be th...
def download_file(self, regex, dest_dir): """Downloads a file by regex from the specified S3 bucket This method takes a regular expression as the arg, and attempts to download the file to the specified dest_dir as the destination directory. This method sets the downloaded filename ...
def find_key(self, regex): """Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expressi...
def find_keys(self, regex, bucket_name=None): """Finds a list of S3 keys matching the passed regex Given a regular expression, this method searches the S3 bucket for matching keys, and returns an array of strings for matched keys, an empty array if non are found. :param regex: ...
def upload_file(self, filepath, key): """Uploads a file using the passed S3 key This method uploads a file specified by the filepath to S3 using the provided S3 key. :param filepath: (str) Full path to the file to be uploaded :param key: (str) S3 key to be set for the upload ...
def delete_key(self, key_to_delete): """Deletes the specified key :param key_to_delete: :return: """ log = logging.getLogger(self.cls_logger + '.delete_key') log.info('Attempting to delete key: {k}'.format(k=key_to_delete)) try: self.s3client.delete_...
def assert_branch_type(branch_type): # type: (str) -> None """ Print error and exit if the current branch is not of a given type. Args: branch_type (str): The branch type. This assumes the branch is in the '<type>/<title>` format. """ branch = git.current_branch(refr...
def assert_on_branch(branch_name): # type: (str) -> None """ Print error and exit if *branch_name* is not the current branch. Args: branch_name (str): The supposed name of the current branch. """ branch = git.current_branch(refresh=True) if branch.name != branch_name: ...
def git_branch_delete(branch_name): # type: (str) -> None """ Delete the given branch. Args: branch_name (str): Name of the branch to delete. """ if branch_name not in git.protected_branches(): log.info("Deleting branch <33>{}", branch_name) shell.run('git branch...
def git_branch_rename(new_name): # type: (str) -> None """ Rename the current branch Args: new_name (str): New name for the current branch. """ curr_name = git.current_branch(refresh=True).name if curr_name not in git.protected_branches(): log.info("Renaming branch ...
def git_checkout(branch_name, create=False): # type: (str, bool) -> None """ Checkout or create a given branch Args: branch_name (str): The name of the branch to checkout or create. create (bool): If set to **True** it will create the branch instead of checking it ...
def git_merge(base, head, no_ff=False): # type: (str, str, bool) -> None """ Merge *head* into *base*. Args: base (str): The base branch. *head* will be merged into this branch. head (str): The branch that will be merged into *base*. no_ff (bool): ...
def get_base_branch(): # type: () -> str """ Return the base branch for the current branch. This function will first try to guess the base branch and if it can't it will let the user choose the branch from the list of all local branches. Returns: str: The name of the branch the current bra...
def choose_branch(exclude=None): # type: (List[str]) -> str """ Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]): List of branch names to exclude from the menu. By default it will exclude master and develop branches. To show all branche...
def autorun(): ''' Call the run method of the decorated class if the current file is the main file ''' def wrapper(cls): import inspect if inspect.getmodule(cls).__name__ == "__main__": cls().run() return cls return wrapper
def unique_list(seq): """ Removes duplicate elements from given @seq @seq: a #list or sequence-like object -> #list """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def flatten(*seqs): """ Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]| @seq: #tuple, #list or :class:UserList -> yields an iterator .. l = [(1, 2), (3, 4)] for x in flatten(l): print(x) .. """ for seq in seqs: ...
def randrange(seq): """ Yields random values from @seq until @seq is empty """ seq = seq.copy() choose = rng().choice remove = seq.remove for x in range(len(seq)): y = choose(seq) remove(y) yield y
def linear_least_squares(a, b, residuals=False): """ Return the least-squares solution to a linear matrix equation. Solves the equation `a x = b` by computing a vector `x` that minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may be under-, well-, or over- determined (i.e., the number...
def validate_ip_address(ip_address): """Validate the ip_address :param ip_address: (str) IP address :return: (bool) True if the ip_address is valid """ # Validate the IP address log = logging.getLogger(mod_logger + '.validate_ip_address') if not isinstance(ip_address, basestring): l...
def ip_addr(): """Uses the ip addr command to enumerate IP addresses by device :return: (dict) Containing device: ip_address """ log = logging.getLogger(mod_logger + '.ip_addr') log.debug('Running the ip addr command...') ip_addr_output = {} command = ['ip', 'addr'] try: ip_add...
def alias_ip_address(ip_address, interface, aws=False): """Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, i...
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0): """Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet...
def save_logic(self, some_object): """ Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект """ some_object.validate_model() some_object.save() self.send_success_response(data=some_object.to_dict())
def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_tty else '' return re.sub(r'<(\d{1,2})>', opcode_subst,...
def cprint(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ if len(args) or len(kw): msg = msg.format(*args, **kw) print(fmt('{}<0>'.format(msg)))
def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): # type: (str, bool, bool, Dict[str, str], bool) -> ExecResult """ Run a shell command. Args: cmd (str): The shell command to execute. shell (bool):...
def get_payload(request): """ Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-valu...
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This module...
def send_cons3rt_agent_logs(self): """Send the cons3rt agent log file :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') if self.cons3rt_agent_log_dir is None: log.warn('There is not CONS3RT agent log directory on this system') ...
def send_text_file(self, text_file, sender=None, recipient=None): """Sends an email with the contents of the provided text file :return: None """ log = logging.getLogger(self.cls_logger + '.send_text_file') if not isinstance(text_file, basestring): msg = 'arg text_f...
def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime): """ :param name: yesterday, last_month :param today: Optional current datetime. Default is now(). :param tz: Optional timezone. Default is UTC. :return: datetime (begin, end) """ if today is None: ...
def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list): """ :param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...] """ begin, end = get_date_range_by_nam...
def load_elements(self): #Set atomic data #atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits') atomicData.setDataFile('s_iii_coll_HRS12.dat') #Default: 's_iii_atom_PKW09.dat' 'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.' ...
def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30, git_cmd=None): """Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir :param branch: (str) branch to clone :par...
def encode_password(password): """Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ log = logging.getLogger(mod_logger + '.password_encoder') log.debug('Encoding password: {p}'.format(p=password)) encoded_password = '' for ...
def encode_character(char): """Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character """ if char == '!': return '%21' elif char == '"': return '%22' elif char == '#': return '%23' elif char == '$': return '%24' ...
def search_tags_as_filters(tags): """Get different tags as dicts ready to use as dropdown lists.""" # set dicts actions = {} contacts = {} formats = {} inspire = {} keywords = {} licenses = {} md_types = dict() owners = defaultdict(str) srs = {} unused = {} # 0/1 valu...
def generate(self, verified, keygen): """ :param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return: """ return Verification( verified_entity=verified, key=keygen(), verified=False )
def iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country """ v = iban_filter(v) if v[:2] == 'FI': return fi_iban_bank_info(v) else: ...
def fi_payment_reference_number(num: str): """ Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum """ assert isinstance(num, str) num = STRIP_WHITESPACE.sub('', num) num = re.sub(r'^0+', '', num) assert len(num) >...
def iso_payment_reference_validator(v: str): """ Validates ISO reference number checksum. :param v: Reference number """ num = '' v = STRIP_WHITESPACE.sub('', v) for ch in v[4:] + v[0:4]: x = ord(ch) if ord('0') <= x <= ord('9'): num += ch else: ...
def fi_iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found """ from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC v = iban_filter(v) ...
def se_clearing_code_bank_info(clearing: str) -> (str, int): """ Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found """ from jutil.bank_const_se import SE_BANK_CLEARING_LIST for name, begin, ...
def _histplot_bins(column, bins=100): """Helper to get bins for histplot.""" col_min = np.min(column) col_max = np.max(column) return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
def http_date(value): """ Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, #float, #str time-like object -> #str HTTP-style formatted date (c)2014, Marcel Hellkamp """ if isinstance(value, datetime.datetime): value = value.utctimetuple() ...
def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp """ try: method, data = header.split(None, 1) if method.lower() == 'basic': data = base64.b64decode(uniorbytes(data, b...
def image(request, data): """ Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already...
def rename(name): # type: (str) -> None """ Give the currently developed hotfix a new name. """ from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
def local_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size .. class Foo(object): def __init__(self, cache_size=5000): self._cache = OrderedDict() ...
def typed_lru(maxsize, types=None): """ :func:functools.lru_cache wrapper which allows you to prevent object types outside of @types from being cached. The main use case for this is preventing unhashable type errors when you still want to cache some results. .. from vita...
def local_expiring_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size self._cache_ttl is the expiration time in seconds .. class Foo(object): def __init__(self,...
def get(self, name, *default): # type: (str, Any) -> Any """ Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If given and the key doesn't not exist, this will be ...
def set(self, name, value): """ Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value """ curr = self.values parts = name.split('.') ...
def alias_exists(alias, keystore_path=None, keystore_password='changeit'): """Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError """ log = loggi...
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Define the filter function that every node must to implement. :param query: The sqlalchemy query. :type query: Query :param entity: The entity model. :type entity: type :return: The filtered query. ...
def _extract_relations(self, attribute: str) -> Tuple[List[str], str]: """Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attrib...
def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the ...
def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query: """Method to make the join when relation is found. :param query: The sqlalchemy query. :type query: Query :param join_models: The list of joined models get from the method `_get_relation`. ...
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in ...
def send_sms(phone: str, message: str, sender: str='', **kw): """ Sends SMS via Kajala Group SMS API. Contact [email protected] for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS ...
def _meta_get_resource_sync(md_uuid): """Just a meta func to get execution time""" isogeo.resource(id_resource=md_uuid) elapsed = default_timer() - START_TIME time_completed_at = "{:5.2f}s".format(elapsed) print("{0:<30} {1:>20}".format(md_uuid, time_completed_at)) return
def setup(self, app): ''' Setup properties from parent app on the command ''' self.logger = app.logger self.shell.logger = self.logger if not self.command_name: raise EmptyCommandNameException() self.app = app self.arguments_declaration = sel...
def process_exception(self, request, e): """ Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception """ from jutil.email import send_email assert isinstance(request, Ht...
def get_first_builder_window(builder): """Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation. """ for obj in builder.get_objects(): if isinstance(obj, Gtk.Window): #...
def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.widget) self.sl...
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file...
def show_and_run(self): """Show the main widget in a window and run the gtk loop""" if not self._ui_ready: self.prepare_ui() self.display_widget = Gtk.Window() self.display_widget.add(self.widget) self.display_widget.show() self.display_widget.connect('destroy...
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The main view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, or not a Gtk.Window, the first toplevel window found in the ...
def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
def open_file(filename, as_text=False): """Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opened in binary mode.""" if filename.lower().endswith('.gz'): if as_text: return gzip.open(filename, 'rt') else: ...
def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames, compress=True, valueClassMappings=None, datasetMetaProps=None, fieldMetaProps=None): """Create a simple writer suitable for writing flat data e.g. as BasicObject or TSV.""" if not ...
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps): """This is a temp hack to write the minimal metadata that Squonk needs. Will needs to be replaced with something that allows something more complete to be written. :param outputBase: Base name fo...
def write_metrics(baseName, values): """Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base name :param values dictionary of values to write """ m = open(baseName + '_metrics.txt', 'w') for key in values:...
def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of v...
def get_undecorated_calling_module(): """Returns the module name of the caller's calling module. If a.py makes a call to b() in b.py, b() can get the name of the calling module (i.e. a) by calling get_undecorated_calling_module(). The module also includes its full path. As the name suggests, this ...
def query_nexus(query_url, timeout_sec, basic_auth=None): """Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError """ log = logging...
def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from Nexus :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_url: (str) URL of t...
def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress print...
def main(): """Handles calling this module as a script :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.') parser.add_argument('-u', '--url', help='Nexus Server URL', required=False) ...
def get_doc(additional_doc=False, field_prefix='$', field_suffix=':', indent=4): """Return a formated string containing documentation about the audio fields. """ if additional_doc: f = fields.copy() f.update(additional_doc) else: f = fields...
def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth) return r.json()['repositories']
def list_tags(self, image_name): # type: (str) -> Iterator[str] """ List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any...
def validate_asset_structure(asset_dir_path): """Checks asset structure validity :param asset_dir_path: (str) path to the directory containing the asset :return: (str) Asset name :raises: Cons3rtAssetStructureError """ log = logging.getLogger(mod_logger + '.validate_asset_structure') log.i...
def make_asset_zip(asset_dir_path, destination_directory=None): """Given an asset directory path, creates an asset zip file in the provided destination directory :param asset_dir_path: (str) path to the directory containing the asset :param destination_directory: (str) path to the destination directory...
def validate(asset_dir): """Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) """ try: asset_name = validate_asset_structure(asset_dir_path=asset_dir) except Cons3rtAssetStructureError: _, ex, trace = sys.exc_info() ...
def create(asset_dir, dest_dir): """Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the destination directory) :return: (int) """ val = validate(asset_dir=asset_dir) if val != 0: return 1 try: asset_z...
def get_object_or_none(cls, **kwargs): """ Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None """ from django.shortcuts import _get_queryset qs = _get_queryset(cls) try: return qs.get(**kwar...
def get_model_field_label_and_value(instance, field_name) -> (str, str): """ Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple """ label = field_name value = str(getattr(instance, field_name)) fo...
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw): """ Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class na...
def get_queryset(self): """ This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "[email protected]"} A specia...
def get_queryset(self): """ This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports address_type and default params Always excludes addresses with optedout = True """ identity_id = self.kwargs...
def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool: """Test if an internet connection is operational. Src: http://stackoverflow.com/a/20913928/2556577. :param str remote_server: remote server used to check """ try: # see if we can reso...
def check_bearer_validity(self, token: dict, connect_mtd) -> dict: """Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this method checks the validity of the token with a 30 mn anticipation limit, and renews it if neces...
def check_api_response(self, response): """Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check """ # check response if response.status_code == 200: return True elif response.status_code >= 400...
def check_request_parameters(self, parameters: dict = dict): """Check parameters passed to avoid errors and help debug. :param dict response: search request parameters """ # -- SEMANTIC QUERY --------------------------------------------------- li_args = parameters.get("q").split...
def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinstance(uuid_str, str): raise TypeError("'uuid_str' expected a str value.") else: ...
def check_edit_tab(self, tab: str, md_type: str): """Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check. Must be one one of EDIT_TABS attribute :param str md_type: metadata type. Must be one one of FILTER_TYPES """ ...
def _check_filter_specific_md(self, specific_md: list): """Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check """ if isinstance(specific_md, list): if len(specific_md) > 0: # checking UUIDs and poping bad...