text
stringlengths
18
773k
def create_config_files(ctx, opts, api_key): """Create default config files.""" # pylint: disable=unused-argument config_reader = opts.get_config_reader() creds_reader = opts.get_creds_reader() has_config = config_reader.has_default_file() has_creds = creds_reader.has_default_file() if has_...
def token(ctx, opts, login, password): """Retrieve your API authentication token/key.""" click.echo( "Retrieving API token for %(login)s ... " % {"login": click.style(login, bold=True)}, nl=False, ) context_msg = "Failed to retrieve the API token!" with handle_api_exceptions...
def status(ctx, opts, owner_repo_package): """ Get the synchronisation status for a package. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'y...
def _process_arguments(self, args, kw): """Map positional to keyword arguments, identify invalid assignments, and return the result. This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of effort to ensure raised exceptions are as Python-like as possible. """...
def import_and_wrap_deprecated(module_name, module_dict, warn_import=True): """ Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__ """ if warn_import: deprecated_import(module_name) from importlib import import_...
def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None): """ Usage: deprecate_module_with_proxy(__name__, locals()) # at bottom of module """ def _ModuleProxy(module, depr): """Return a wrapped object that warns about deprecated accesses""" # http:/...
def native(self, value, context=None): """Convert a foreign value to a native boolean.""" value = super().native(value, context) if self.none and (value is None): return None try: value = value.lower() except AttributeError: return bool(value) if value in self.truthy: return True ...
def foreign(self, value, context=None): """Convert a native value to a textual boolean.""" if self.none and value is None: return '' try: value = self.native(value, context) except Concern: # The value might not be in the lists; bool() evaluate it instead. value = bool(value.strip() if self.st...
def get_root_path(): """Get the root path for the application.""" root_path = __file__ return os.path.dirname(os.path.realpath(root_path))
def read(path, root_path=None): """Read the specific file into a string in its entirety.""" try: root_path = root_path or get_root_path() real_path = os.path.realpath(os.path.join(root_path, path)) with open(real_path) as fp: return fp.read().strip() except IOError: ...
def get_long_description(): """Grok the readme, turn it into whine (rst).""" root_path = get_root_path() readme_path = os.path.join(root_path, "README.md") try: import pypandoc return pypandoc.convert(readme_path, "rst").strip() except ImportError: return "Cloudsmith CLI"
def rand(n, **kwargs): """Random vector from the n-Sphere This function will return a random vector which is an element of the n-Sphere. The n-Sphere is defined as a vector in R^n+1 with a norm of one. Basically, we'll find a random vector in R^n+1 and normalize it. This uses the method of Marsa...
def tan_rand(q, seed=9): """Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere ...
def perturb_vec(q, cone_half_angle=2): r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed...
def common_package_action_options(f): """Add common options for package actions.""" @click.option( "-s", "--skip-errors", default=False, is_flag=True, help="Skip/ignore errors when copying packages.", ) @click.option( "-W", "--no-wait-for-sync", ...
def common_cli_config_options(f): """Add common CLI config options to commands.""" @click.option( "-C", "--config-file", envvar="CLOUDSMITH_CONFIG_FILE", type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True), help="The path to your config.ini fil...
def common_cli_output_options(f): """Add common CLI output options to commands.""" @click.option( "-d", "--debug", default=False, is_flag=True, help="Produce debug output during processing.", ) @click.option( "-F", "--output-format", defau...
def common_cli_list_options(f): """Add common list options to commands.""" @click.option( "-p", "--page", default=1, type=int, help="The page to view for lists, where 1 is the first page", callback=validators.validate_page, ) @click.option( "-l", ...
def common_api_auth_options(f): """Add common API authentication options to commands.""" @click.option( "-k", "--api-key", hide_input=True, envvar="CLOUDSMITH_API_KEY", help="The API key for authenticating with the API.", ) @click.pass_context @functools.wrap...
def initialise_api(f): """Initialise the Cloudsmith API for use.""" @click.option( "--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to." ) @click.option( "--api-proxy", envvar="CLOUDSMITH_API_PROXY", help="The API proxy to connect through.", ...
def list_entitlements(owner, repo, page, page_size, show_tokens): """Get a list of entitlements on a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, ...
def create_entitlement(owner, repo, name, token, show_tokens): """Create an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception(): ...
def delete_entitlement(owner, repo, identifier): """Delete an entitlement from a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): _, _, headers = client.entitlements_delete_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratel...
def update_entitlement(owner, repo, identifier, name, token, show_tokens): """Update an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception...
def refresh_entitlement(owner, repo, identifier, show_tokens): """Refresh an entitlement in a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_refresh_with_http_info( owner=owner, repo=repo, identifier=identifier, sh...
def sync_entitlements(owner, repo, source, show_tokens): """Sync entitlements from another repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_sync_with_http_info( owner=owner, repo=repo, data={"source": source}, show_t...
def initialise_api( debug=False, host=None, key=None, proxy=None, user_agent=None, headers=None, rate_limit=True, rate_limit_callback=None, error_retry_max=None, error_retry_backoff=None, error_retry_codes=None, ): """Initialise the API.""" config = cloudsmith_api.Con...
def get_api_client(cls): """Get an API client (with configuration).""" config = cloudsmith_api.Configuration() client = cls() client.config = config client.api_client.rest_client = RestClient() user_agent = getattr(config, "user_agent", None) if user_agent: client.api_client.user_ag...
def set_api_key(config, key): """Configure a new API key.""" if not key and "X-Api-Key" in config.api_key: del config.api_key["X-Api-Key"] else: config.api_key["X-Api-Key"] = key
def validate_request_file_upload(owner, repo, filepath, md5_checksum=None): """Validate parameters for requesting a file upload.""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): _, _, headers = client.files_validate_with_h...
def request_file_upload(owner, repo, filepath, md5_checksum=None): """Request a new package file upload (for creating packages).""" client = get_files_api() md5_checksum = md5_checksum or calculate_file_md5(filepath) with catch_raise_api_exception(): data, _, headers = client.files_create_with_...
def upload_file(upload_url, upload_fields, filepath, callback=None): """Upload a pre-signed file to Cloudsmith.""" upload_fields = list(six.iteritems(upload_fields)) upload_fields.append( ("file", (os.path.basename(filepath), click.open_file(filepath, "rb"))) ) encoder = MultipartEncoder(upl...
def handle_api_exceptions( ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False ): """Context manager that handles API exceptions.""" # flake8: ignore=C901 # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" ...
def get_details(exc): """Get the details from the exception.""" detail = None fields = collections.OrderedDict() if exc.detail: detail = exc.detail if exc.fields: for k, v in six.iteritems(exc.fields): try: field_detail = v["detail"] except (...
def get_error_hint(ctx, opts, exc): """Get a hint to show to the user (if any).""" module = sys.modules[__name__] get_specific_error_hint = getattr(module, "get_%s_error_hint" % exc.status, None) if get_specific_error_hint: return get_specific_error_hint(ctx, opts, exc) return None
def make_env_key(app_name, key): """Creates an environment key-equivalent for the given key""" key = key.replace('-', '_').replace(' ', '_') return str("_".join((x.upper() for x in (app_name, key))))
def set_env(self, key, value): """Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`. """ os.environ[make_env_key(self.appname, key)] = str(value) # ...
def unset_env(self, key): """Removes an environment variable using the prepended app_name convention with `key`.""" os.environ.pop(make_env_key(self.appname, key), None) self._registered_env_keys.discard(key) self._clear_memoization()
def _reload(self, force=False): """Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally. """ self._config_map = dict() self._r...
def move( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, yes, ): """ Move (promote) a package to another repo. This requires appropriate permissions for both the source repository/package and the destination r...
def create_requests_session( retries=None, backoff_factor=None, status_forcelist=None, pools_size=4, maxsize=4, ssl_verify=None, ssl_cert=None, proxy=None, session=None, ): """Create a requests session that retries some errors.""" # pylint: disable=too-many-branches confi...
def data(self): """ Get the content for the response (lazily decoded). """ if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
def getheader(self, name, default=None): """ Return a given response header. """ return self.response.headers.get(name, default)
def request( self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None, ): """ :param method: http request method :param url: http request url :...
def get_root_path(): """Get the root directory for the application.""" return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
def read_file(*path): """Read the specific file into a string in its entirety.""" real_path = os.path.realpath(os.path.join(*path)) with click.open_file(real_path, "r") as fp: return fp.read()
def calculate_file_md5(filepath, blocksize=2 ** 20): """Calculate an MD5 hash for a file.""" checksum = hashlib.md5() with click.open_file(filepath, "rb") as f: def update_chunk(): """Add chunk to checksum.""" buf = f.read(blocksize) if buf: chec...
def get_page_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" page_kwargs = {} page = kwargs.get("page") if page is not None and page > 0: page_kwargs["page"] = page page_size = kwargs.get("page_size") if page_size is not None and page_size > 0: page_kw...
def get_query_kwargs(**kwargs): """Construct page and page size kwargs (if present).""" query_kwargs = {} query = kwargs.pop("query") if query: query_kwargs["query"] = query return query_kwargs
def _get_version_from_git_tag(path): """Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash. """ m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '') if m is None: return None version, post_commit, hash = m.groups...
def get_version(dunder_file): """Returns a version string for the current package, derived either from git or from a .version file. This function is expected to run in two contexts. In a development context, where .git/ exists, the version is pulled from git tags. Using the BuildPyCommand and SDist...
def ctime(message=None): "Counts the time spent in some context" global t_elapsed t_elapsed = 0.0 print('\n') t = time.time() yield if message: print(message + ": ", end='') t_elapsed = time.time() - t print(round(t_elapsed, 4), "sec")
def rot1(angle, form='c'): """Euler rotation about first axis This computes the rotation matrix associated with a rotation about the first axis. It will output matrices assuming column or row format vectors. For example, to transform a vector from reference frame b to reference frame a: Column V...
def dcm2body313(dcm): """Convert DCM to body Euler 3-1-3 angles """ theta = np.zeros(3) theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1]) theta[1] = np.arccos(dcm[2, 2]) theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2]) return theta
def hat_map(vec): """Return that hat map of a vector Inputs: vec - 3 element vector Outputs: skew - 3,3 skew symmetric matrix """ vec = np.squeeze(vec) skew = np.array([ [0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], ...
def vee_map(skew): """Return the vee map of a vector """ vec = 1/2 * np.array([skew[2,1] - skew[1,2], skew[0,2] - skew[2,0], skew[1,0] - skew[0,1]]) return vec
def dcmtoquat(dcm): """Convert DCM to quaternion This function will convert a rotation matrix, also called a direction cosine matrix into the equivalent quaternion. Parameters: ---------- dcm - (3,3) numpy array Numpy rotation matrix which defines a rotation from the b to a frame ...
def quattodcm(quat): """Convert quaternion to DCM This function will convert a quaternion to the equivalent rotation matrix, or direction cosine matrix. Parameters: ---------- quat - (4,) numpy array Array defining a quaterion where the quaternion is defined in terms of a vecto...
def dcmdottoang_vel(R,Rdot): """Convert a rotation matrix to angular velocity w - angular velocity in inertial frame Omega - angular velocity in body frame """ w = vee_map(Rdot.dot(R.T)) Omega = vee_map(R.T.dot(Rdot)) return (w, Omega)
def ang_veltoaxisangledot(angle, axis, Omega): """Compute kinematics for axis angle representation """ angle_dot = axis.dot(Omega) axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega) return angle_dot, axis_dot
def axisangledottoang_vel(angle,axis, angle_dot,axis_dot): """Convert axis angle represetnation to angular velocity in body frame """ Omega = angle_dot*axis + np.sin(angle)*axis_dot - (1-np.cos(angle))*hat_map(axis).dot(axis_dot) return Omega
def normalize(num_in, lower=0, upper=360, b=False): """Normalize number to range [lower, upper) or [lower, upper]. Parameters ---------- num : float The number to be normalized. lower : int Lower limit of range. Default is 0. upper : int Upper limit of range. Default is ...
def list_repos(owner=None, **kwargs): """List repositories in a namespace.""" client = get_repos_api() api_kwargs = {} api_kwargs.update(utils.get_page_kwargs(**kwargs)) # pylint: disable=fixme # FIXME: Compatibility code until we work out how to conflate # the overlapping repos_list metho...
def copy( ctx, opts, owner_repo_package, destination, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, ): """ Copy a package to another repository. This requires appropriate permissions for both the source repository/package and the destination repository. ...
def rm_file_or_dir(path, ignore_errors=True): """ Helper function to clean a certain filepath Parameters ---------- path Returns ------- """ if os.path.exists(path): if os.path.isdir(path): if os.path.islink(path): os.unlink(path) el...
def cache_valid(self, col): """ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: """ cache_valid = False if self.rootdir: col_org_file_check = self[col].rootdir + '/__attrs__' ...
def group_cache_valid(self, col_list): """ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: """ cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, sel...
def cache_factor(self, col_list, refresh=False): """ Existing todos here are: these should be hidden helper carrays As in: not normal columns that you would normally see as a user The factor (label index) carray is as long as the original carray (and the rest of the table theref...
def unique(self, col_or_col_list): """ Return a list of unique values of a column or a list of lists of column list :param col_or_col_list: a column or a list of columns :return: """ if isinstance(col_or_col_list, list): col_is_list = True col_li...
def aggregate_groups(self, ct_agg, nr_groups, skip_key, carray_factor, groupby_cols, agg_ops, dtype_dict, bool_arr=None): '''Perform aggregation and place the result in the given ctable. Args: ct_agg (ctable): the table to hold the aggregati...
def factorize_groupby_cols(self, groupby_cols): """ factorizes all columns that are used in the groupby it will use cache carrays if available if not yet auto_cache is valid, it will create cache carrays """ # first check if the factorized arrays already exist # ...
def _int_array_hash(input_list): """ A function to calculate a hash value of multiple integer values, not used at the moment Parameters ---------- input_list Returns ------- """ list_len = len(input_list) arr_len = len(input_list[0]) ...
def create_group_column_factor(self, factor_list, groupby_cols, cache=False): """ Create a unique, factorized column out of several individual columns Parameters ---------- factor_list groupby_cols cache Returns ------- """ if no...
def make_group_index(self, groupby_cols, bool_arr): '''Create unique groups for groupby loop Args: factor_list: values_list: groupby_cols: bool_arr: Returns: carray: (carray_factor) int: (nr...
def create_tmp_rootdir(self): """ create a rootdir that we can destroy later again Returns ------- """ if self.rootdir: tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-') self._dir_clean_list.append(tmp_rootdir) else: tmp_rootdir...
def clean_tmp_rootdir(self): """ clean up all used temporary rootdirs Returns ------- """ for tmp_rootdir in list(self._dir_clean_list): rm_file_or_dir(tmp_rootdir) self._dir_clean_list.remove(tmp_rootdir)
def create_agg_ctable(self, groupby_cols, agg_list, expectedlen, rootdir): '''Create a container for the output table, a dictionary describing it's columns and a list of tuples describing aggregation operations to perform. Args: groupby_cols (list): a list of columns...
def where_terms(self, term_list, cache=False): """ Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :param term_list: :param outcols: :param limi...
def where_terms_factorization_check(self, term_list): """ check for where terms if they are applicable Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :...
def is_in_ordered_subgroups(self, basket_col=None, bool_arr=None, _max_len_subgroup=1000): """ Expands the filter using a specified column Parameters ---------- basket_col bool_arr _max_len_subgroup Returns -------...
def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))): """Class decorator to set metaclass. Works with both Python 2 and Python 3 and it does not add an extra class in the lookup order like ``six.with_metaclass`` does (that is -- it copies the original class instead of using inheritance...
def ensure_tuple(length, tuples): """Yield `length`-sized tuples from the given collection. Will truncate longer tuples to the desired length, and pad using the leading element if shorter. """ for elem in tuples: # Handle non-tuples and non-lists as a single repeated element. if not isinstance(elem, (tuple,...
def print_version(): """Print the environment versions.""" click.echo("Versions:") click.secho( "CLI Package Version: %(version)s" % {"version": click.style(get_cli_version(), bold=True)} ) click.secho( "API Package Version: %(version)s" % {"version": click.style(get_...
def main(ctx, opts, version): """Handle entrypoint to CLI.""" # pylint: disable=unused-argument if version: print_version() elif ctx.invoked_subcommand is None: click.echo(ctx.get_help())
def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors): """Validate parameters for requesting a file upload.""" filename = click.format_filename(filepath) basename = os.path.basename(filename) click.echo( "Checking %(filename)s file upload parameters ... " % {"filename"...
def upload_file(ctx, opts, owner, repo, filepath, skip_errors, md5_checksum): """Upload a package file via the API.""" filename = click.format_filename(filepath) basename = os.path.basename(filename) click.echo( "Requesting file upload for %(filename)s ... " % {"filename": click.style(b...
def validate_create_package( ctx, opts, owner, repo, package_type, skip_errors, **kwargs ): """Check new package parameters via the API.""" click.echo( "Checking %(package_type)s package upload parameters ... " % {"package_type": click.style(package_type, bold=True)}, nl=False, )...
def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs): """Create a new package via the API.""" click.echo( "Creating a new %(package_type)s package ... " % {"package_type": click.style(package_type, bold=True)}, nl=False, ) context_msg = "Failed to crea...
def wait_for_package_sync( ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3 ): """Wait for a package to synchronise (or fail).""" # pylint: disable=too-many-locals attempts -= 1 click.echo() label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")} ...
def upload_files_and_create_package( ctx, opts, package_type, owner_repo, dry_run, no_wait_for_sync, wait_interval, skip_errors, sync_attempts, **kwargs ): """Upload package files and create a new package.""" # pylint: disable=unused-argument owner, repo = owner_repo ...
def create_push_handlers(): """Create a handler for upload per package format.""" # pylint: disable=fixme # HACK: hacky territory - Dynamically generate a handler for each of the # package formats, until we have slightly more clever 'guess type' # handling. :-) handlers = create_push_handlers.ha...
def memoize(func): """ Decorator to cause a function to cache it's results for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> @memoize ... def foo(x): ... print('running function wit...
def memoizemethod(method): """ Decorator to cause a method to cache it's results in self for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> class Foo (object): ... @memoizemethod ... ...
def clear_memoized_methods(obj, *method_names): """ Clear the memoized method or @memoizedproperty results for the given method names from the given object. >>> v = [0] >>> def inc(): ... v[0] += 1 ... return v[0] ... >>> class Foo(object): ... @memoizemethod ... ...
def memoizedproperty(func): """ Decorator to cause a method to cache it's results in self for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> class Foo (object): ... _x = 1 ... @memoiz...
def aes_encrypt(base64_encryption_key, data): """Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte ...
def aes_decrypt(base64_encryption_key, base64_data): """Verify HMAC-SHA256 signature and decrypt data with AES-CBC Arguments: encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a b...
def whoami(ctx, opts): """Retrieve your current authentication status.""" click.echo("Retrieving your authentication status from the API ... ", nl=False) context_msg = "Failed to retrieve your authentication status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with mayb...
def _clean(self, value): """Perform a standardized pipline of operations across an iterable.""" value = (str(v) for v in value) if self.strip: value = (v.strip() for v in value) if not self.empty: value = (v for v in value if v) return value
def native(self, value, context=None): """Convert the given string into a list of substrings.""" separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator value = super().native(value, context) if value is None: return self.cast() if hasattr(value, '...