code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
cos_a = np.cos(angle) sin_a = np.sin(angle) rot_mat = np.identity(3) if form=='c': rot_mat[1, 1] = cos_a rot_mat[1, 2] = -sin_a rot_mat[2, 1] = sin_a rot_mat[2, 2] = cos_a elif form=='r': rot_mat[1, 1] = cos_a rot_mat[1, 2] = sin_a rot_ma...
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 Vectors : a = rot1(angle, 'c').dot(...
1.7492
1.765451
0.990795
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 dcm2body313(dcm)
Convert DCM to body Euler 3-1-3 angles
1.755879
1.677363
1.04681
vec = np.squeeze(vec) skew = np.array([ [0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]]) return skew
def hat_map(vec)
Return that hat map of a vector Inputs: vec - 3 element vector Outputs: skew - 3,3 skew symmetric matrix
2.21759
2.480529
0.893999
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 vee_map(skew)
Return the vee map of a vector
2.553988
2.553613
1.000147
quat = np.zeros(4) quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1) quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T) return quat
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 Returns: -------- ...
5.738056
6.751573
0.849884
dcm = (quat[-1]**2-np.inner(quat[0:3], quat[0:3]))*np.eye(3,3) + 2*np.outer(quat[0:3],quat[0:3]) + 2*quat[-1]*hat_map(quat[0:3]) return dcm
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 vector and a scalar part. The ve...
3.724056
4.339107
0.858254
w = vee_map(Rdot.dot(R.T)) Omega = vee_map(R.T.dot(Rdot)) return (w, Omega)
def dcmdottoang_vel(R,Rdot)
Convert a rotation matrix to angular velocity w - angular velocity in inertial frame Omega - angular velocity in body frame
5.697379
6.550896
0.86971
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 ang_veltoaxisangledot(angle, axis, Omega)
Compute kinematics for axis angle representation
4.342937
4.483061
0.968744
Omega = angle_dot*axis + np.sin(angle)*axis_dot - (1-np.cos(angle))*hat_map(axis).dot(axis_dot) return Omega
def axisangledottoang_vel(angle,axis, angle_dot,axis_dot)
Convert axis angle represetnation to angular velocity in body frame
5.55634
5.273678
1.053599
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 methods into one. repos_list = client.repos_list_with_http_info if owner ...
def list_repos(owner=None, **kwargs)
List repositories in a namespace.
3.804502
3.725577
1.021185
owner, source, slug = owner_repo_package click.echo( "Copying %(slug)s package from %(source)s to %(dest)s ... " % { "slug": click.style(slug, bold=True), "source": click.style(source, bold=True), "dest": click.style(destination, bold=True), }, ...
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. - 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 pac...
2.526004
2.892042
0.873433
if os.path.exists(path): if os.path.isdir(path): if os.path.islink(path): os.unlink(path) else: shutil.rmtree(path, ignore_errors=ignore_errors) else: if os.path.islink(path): os.unlink(path) else: ...
def rm_file_or_dir(path, ignore_errors=True)
Helper function to clean a certain filepath Parameters ---------- path Returns -------
1.440854
1.612833
0.893369
cache_valid = False if self.rootdir: col_org_file_check = self[col].rootdir + '/__attrs__' col_values_file_check = self[col].rootdir + '.values/__attrs__' cache_valid = os.path.exists(col_org_file_check) and os.path.exists(col_values_file_check) ret...
def cache_valid(self, col)
Checks whether the column has a factorization that exists and is not older than the source :param col: :return:
4.539181
5.019565
0.904298
cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \ '.values/__attrs__' exists_group_index = os.path.exists(col_values_file_check) missing_col...
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:
4.990074
5.42198
0.920342
if not self.rootdir: raise TypeError('Only out-of-core ctables can have ' 'factorization caching at the moment') if not isinstance(col_list, list): col_list = [col_list] if refresh: kill_list = [x for x in os.listdir(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 therefore) But the (unique) values carray is not as long (as long a...
2.847664
2.808465
1.013957
if isinstance(col_or_col_list, list): col_is_list = True col_list = col_or_col_list else: col_is_list = False col_list = [col_or_col_list] output = [] for col in col_list: if self.auto_cache or self.cache_valid(col)...
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:
3.73178
3.806206
0.980446
'''Perform aggregation and place the result in the given ctable. Args: ct_agg (ctable): the table to hold the aggregation nr_groups (int): the number of groups (number of rows in output table) skip_key (int): index of the output row to remove from results (used for f...
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 aggregation nr_groups (int): the number of groups (number of rows in output table) skip_key (int): index of the output row to remove from results (used for filtering) ...
2.383287
1.614377
1.476289
# first check if the factorized arrays already exist # unless we need to refresh the cache factor_list = [] values_list = [] # factorize the groupby columns for col in groupby_cols: if self.auto_cache or self.cache_valid(col): # crea...
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
3.213507
2.908671
1.104802
list_len = len(input_list) arr_len = len(input_list[0]) mult_arr = np.full(arr_len, 1000003, dtype=np.long) value_arr = np.full(arr_len, 0x345678, dtype=np.long) for i, current_arr in enumerate(input_list): index = list_len - i - 1 value_arr ^= ...
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 -------
3.95515
4.071321
0.971466
if not self.rootdir: # in-memory scenario input_rootdir = None col_rootdir = None col_factor_rootdir = None col_values_rootdir = None col_factor_rootdir_tmp = None col_values_rootdir_tmp = None else: ...
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 -------
2.762523
2.780026
0.993704
'''Create unique groups for groupby loop Args: factor_list: values_list: groupby_cols: bool_arr: Returns: carray: (carray_factor) int: (nr_groups) the number of resulting groups ...
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_groups) the number of resulting groups int: (s...
4.807908
4.118916
1.167275
if self.rootdir: tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-') self._dir_clean_list.append(tmp_rootdir) else: tmp_rootdir = None return tmp_rootdir
def create_tmp_rootdir(self)
create a rootdir that we can destroy later again Returns -------
3.671504
3.921566
0.936234
for tmp_rootdir in list(self._dir_clean_list): rm_file_or_dir(tmp_rootdir) self._dir_clean_list.remove(tmp_rootdir)
def clean_tmp_rootdir(self)
clean up all used temporary rootdirs Returns -------
3.778135
3.977336
0.949916
'''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 to groupby over agg_list (list): the aggregation operations (s...
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 to groupby over agg_list (list): the aggregation operations (see groupby ...
3.498963
2.429856
1.439988
if type(term_list) not in [list, set, tuple]: raise ValueError("Only term lists are supported") col_list = [] op_list = [] value_list = [] for term in term_list: # get terms filter_col = term[0] filter_operator = term[1]...
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 limit: :param skip: :return: :raise ValueError:
2.87635
2.784749
1.032894
if type(term_list) not in [list, set, tuple]: raise ValueError("Only term lists are supported") valid = True for term in term_list: # get terms filter_col = term[0] filter_operator = term[1].lower().strip(' ') filter_value =...
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'])] :param term_list: :param outcols: :param limit: :pa...
2.356455
2.331417
1.010739
assert basket_col is not None if bool_arr is None: return None if self.auto_cache and bool_arr.rootdir is not None: rootdir = self.create_tmp_rootdir() else: rootdir = None return \ ctable_ext.is_in_ordered_subgroups( ...
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 -------
3.721304
4.280848
0.869291
def _clone_with_metaclass(Class): attrs = dict((key, value) for key, value in items(vars(Class)) if key not in skip_attrs) return Type(Class.__name__, Class.__bases__, attrs) return _clone_with_metaclass
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).
2.766832
2.999906
0.922306
for elem in tuples: # Handle non-tuples and non-lists as a single repeated element. if not isinstance(elem, (tuple, list)): yield (elem, ) * length continue l = len(elem) # If we have the correct length already, yield it. if l == length: yield elem # If we're too long, truncate. eli...
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.
3.252512
2.90589
1.119283
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_api_version(), bold=True)} )
def print_version()
Print the environment versions.
3.022378
2.703736
1.117852
# pylint: disable=unused-argument if version: print_version() elif ctx.invoked_subcommand is None: click.echo(ctx.get_help())
def main(ctx, opts, version)
Handle entrypoint to CLI.
3.10644
2.808207
1.1062
filename = click.format_filename(filepath) basename = os.path.basename(filename) click.echo( "Checking %(filename)s file upload parameters ... " % {"filename": click.style(basename, bold=True)}, nl=False, ) context_msg = "Failed to validate upload parameters!" with...
def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors)
Validate parameters for requesting a file upload.
4.05152
3.872151
1.046323
filename = click.format_filename(filepath) basename = os.path.basename(filename) click.echo( "Requesting file upload for %(filename)s ... " % {"filename": click.style(basename, bold=True)}, nl=False, ) context_msg = "Failed to request file upload!" with handle_api_...
def upload_file(ctx, opts, owner, repo, filepath, skip_errors, md5_checksum)
Upload a package file via the API.
2.596343
2.555389
1.016026
click.echo( "Checking %(package_type)s package upload parameters ... " % {"package_type": click.style(package_type, bold=True)}, nl=False, ) context_msg = "Failed to validate upload parameters!" with handle_api_exceptions( ctx, opts=opts, context_msg=context_msg, re...
def validate_create_package( ctx, opts, owner, repo, package_type, skip_errors, **kwargs )
Check new package parameters via the API.
3.861851
3.611989
1.069176
click.echo( "Creating a new %(package_type)s package ... " % {"package_type": click.style(package_type, bold=True)}, nl=False, ) context_msg = "Failed to create package!" with handle_api_exceptions( ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_erro...
def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs)
Create a new package via the API.
2.639616
2.579813
1.023181
# pylint: disable=too-many-locals attempts -= 1 click.echo() label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")} status_str = "Waiting" stage_str = None def display_status(current): # pylint: disable=unused-argument if not stage_s...
def wait_for_package_sync( ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3 )
Wait for a package to synchronise (or fail).
2.897025
2.85819
1.013587
# pylint: disable=unused-argument owner, repo = owner_repo # 1. Validate package create parameters validate_create_package( ctx=ctx, opts=opts, owner=owner, repo=repo, package_type=package_type, skip_errors=skip_errors, **kwargs ) # ...
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.
2.040199
1.996664
1.021804
# 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.handlers = {} context = create_push_handlers.context = get_package_formats() ...
def create_push_handlers()
Create a handler for upload per package format.
3.049444
2.996668
1.017612
func._result_cache = {} # pylint: disable-msg=W0212 @wraps(func) def _memoized_func(*args, **kwargs): key = (args, tuple(sorted(kwargs.items()))) if key in func._result_cache: # pylint: disable-msg=W0212 return func._result_cache[key] # pylint: disable-msg=W0212 ...
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 with', x) ... return x+3 ...
2.059065
1.973839
1.043178
@wraps(method) def _wrapper(self, *args, **kwargs): # NOTE: a __dict__ check is performed here rather than using the # built-in hasattr function because hasattr will look up to an object's # class if the attr is not directly found in the object's dict. That's # bad for th...
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 foo(self, x, y=0): ... prin...
4.712286
4.459532
1.056677
for key in list(getattr(obj, '_memoized_results', {}).keys()): # key[0] is the method name if key[0] in method_names: del obj._memoized_results[key] try: property_dict = obj._cache_ except AttributeError: property_dict = obj._cache_ = {} for prop in met...
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 foo(self): ... return inc() ... @me...
3.371264
4.085891
0.825099
inner_attname = '__%s' % func.__name__ def new_fget(self): if not hasattr(self, '_cache_'): self._cache_ = dict() cache = self._cache_ if inner_attname not in cache: cache[inner_attname] = func(self) return cache[inner_attname] return property(n...
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 ... @memoizedproperty ... def foo(self): ...
2.47363
3.851374
0.642272
if isinstance(data, text_type): data = data.encode("UTF-8") aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data = _pad(data) iv_bytes = os.urandom(AES_BLOCK_SIZE) cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes) data = iv_bytes + cipher.encrypt(d...
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 string containing the data to be encrypted Retur...
2.332885
2.410351
0.967861
data = from_base64(base64_data) aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key) data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:] if hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_signature: raise AuthenticationError("HMAC authenticati...
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 byte string containing the data decrypted with an HMAC signin...
2.226926
2.329113
0.956126
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 maybe_spinner(opts): is_auth, username, email, name = get_user_br...
def whoami(ctx, opts)
Retrieve your current authentication status.
3.57361
3.345501
1.068184
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 _clean(self, value)
Perform a standardized pipline of operations across an iterable.
2.812196
2.490341
1.129241
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, 'split'): value = value.split(separator) value = self._clean(value) try: return s...
def native(self, value, context=None)
Convert the given string into a list of substrings.
4.289553
4.329002
0.990887
if self.separator is None: separator = ' ' else: separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator value = self._clean(value) try: value = separator.join(value) except Exception as e: raise Concern("{0} caught, failed to convert t...
def foreign(self, value, context=None)
Construct a string-like representation for an iterable of string-like objects.
4.123206
3.983276
1.035129
ret = bytearray(4) ret[0] = (val>>24)&M8 ret[1] = (val>>16)&M8 ret[2] = (val>>8)&M8 ret[3] = val&M8 return ret
def tob32(val)
Return provided 32 bit value as a string of four bytes.
2.157281
2.173559
0.992511
c = 0 olen = len(buf) ret = "" # 16 byte lines while (c+0x10) <= olen: adr = c + spos l = ':10{0:04X}00'.format(adr) sum = 0x10+((adr>>8)&M8)+(adr&M8) for j in range(0,0x10): nb = buf[c+j] l += '{0:02X}'.format(nb) sum = (sum +...
def bintoihex(buf, spos=0x0000)
Convert binary buffer to ihex and return as string.
2.672181
2.637602
1.01311
gen = op_tbl[mcode[0]] ret = gen[0] # opcode nargs = len(gen) i = 1 while i < nargs: if i < len(mcode): # or assume they are same len ret |= (mcode[i]&gen[i][0]) << gen[i][1] i += 1 return ret
def op_gen(mcode)
Generate a machine instruction using the op gen table.
6.042751
5.702271
1.059709
error('scan error: ' + msg + ' on line {}'.format(self.sline)) sys.exit(-1)
def scanerror(self, msg)
Emit scan error and abort assembly.
8.382463
6.831395
1.22705
if line is None: line = self.sline self.dowarn('warning: ' + msg + ' on line {}'.format(line))
def parsewarn(self, msg, line=None)
Emit parse warning.
6.055599
5.880549
1.029768
if line is None: line = self.sline error('parse error: ' + msg + ' on line {}'.format(line)) sys.exit(-2)
def parseerror(self, msg, line=None)
Emit parse error and abort assembly.
5.795409
4.675416
1.239549
self.__next__() while self.sym['type'] != 'EOF': if self.sym['type'] == 'LABEL': self.__label__() elif self.sym['type'] == 'MNEMONIC': self.__instruction__() elif self.sym['type'] == 'NAME' or self.sym['type'] == 'ASSEMBLER': ...
def parse(self)
Parse input.
4.555527
4.477866
1.017343
owner, source, slug = owner_repo_package resync_package( ctx=ctx, opts=opts, owner=owner, repo=source, slug=slug, skip_errors=skip_errors ) if no_wait_for_sync: return wait_for_package_sync( ctx=ctx, opts=opts, owner=owner, repo=source, ...
def resync( ctx, opts, owner_repo_package, skip_errors, wait_interval, no_wait_for_sync, sync_attempts, )
Resynchronise a package in a repository. This requires appropriate permissions for 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: 'you...
2.153526
3.014199
0.71446
click.echo( "Resynchonising the %(slug)s package ... " % {"slug": click.style(slug, bold=True)}, nl=False, ) context_msg = "Failed to resynchronise package!" with handle_api_exceptions( ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors ): ...
def resync_package(ctx, opts, owner, repo, slug, skip_errors)
Resynchronise a package.
4.163295
3.932281
1.058748
payload = {} # Add non-empty arguments for k, v in six.iteritems(kwargs): if v is not None: payload[k] = v return payload
def make_create_payload(**kwargs)
Create payload for upload/check-upload operations.
3.71897
3.336321
1.114692
client = get_packages_api() with catch_raise_api_exception(): upload = getattr(client, "packages_upload_%s_with_http_info" % package_format) data, _, headers = upload( owner=owner, repo=repo, data=make_create_payload(**kwargs) ) ratelimits.maybe_rate_limit(client,...
def create_package(package_format, owner, repo, **kwargs)
Create a new package in a repository.
8.001436
7.943685
1.00727
client = get_packages_api() with catch_raise_api_exception(): check = getattr( client, "packages_validate_upload_%s_with_http_info" % package_format ) _, _, headers = check( owner=owner, repo=repo, data=make_create_payload(**kwargs) ) ratelimit...
def validate_create_package(package_format, owner, repo, **kwargs)
Validate parameters for creating a package.
6.820731
6.582399
1.036207
client = get_packages_api() with catch_raise_api_exception(): data, _, headers = client.packages_copy_with_http_info( owner=owner, repo=repo, identifier=identifier, data={"destination": destination}, ) ratelimits.maybe_rate_limit(client,...
def copy_package(owner, repo, identifier, destination)
Copy a package to another repository.
7.202471
7.072008
1.018448
client = get_packages_api() with catch_raise_api_exception(): data, _, headers = client.packages_move_with_http_info( owner=owner, repo=repo, identifier=identifier, data={"destination": destination}, ) ratelimits.maybe_rate_limit(client,...
def move_package(owner, repo, identifier, destination)
Move a package to another repository.
6.98166
7.04457
0.99107
client = get_packages_api() with catch_raise_api_exception(): _, _, headers = client.packages_delete_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratelimits.maybe_rate_limit(client, headers) return True
def delete_package(owner, repo, identifier)
Delete a package in a repository.
6.277989
5.832567
1.076368
client = get_packages_api() with catch_raise_api_exception(): data, _, headers = client.packages_resync_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratelimits.maybe_rate_limit(client, headers) return data.slug_perm, data.slug
def resync_package(owner, repo, identifier)
Resync a package in a repository.
8.836617
8.260198
1.069783
client = get_packages_api() with catch_raise_api_exception(): data, _, headers = client.packages_status_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratelimits.maybe_rate_limit(client, headers) # pylint: disable=no-member # Pylint detects the re...
def get_package_status(owner, repo, identifier)
Get the status for a package in a repository.
5.636733
5.365779
1.050497
client = get_packages_api() api_kwargs = {} api_kwargs.update(utils.get_page_kwargs(**kwargs)) api_kwargs.update(utils.get_query_kwargs(**kwargs)) with catch_raise_api_exception(): data, _, headers = client.packages_list_with_http_info( owner=owner, repo=repo, **api_kwargs...
def list_packages(owner, repo, **kwargs)
List packages for a repository.
3.834971
3.69654
1.037449
# pylint: disable=fixme # HACK: This obviously isn't great, and it is subject to change as # the API changes, but it'll do for now as a interim method of # introspection to get the parameters we need. def get_parameters(cls): params = {} # Create a dummy instance so we...
def get_package_formats()
Get the list of available package formats and parameters.
4.733402
4.806771
0.984736
return [ k for k, v in six.iteritems(get_package_formats()) if not predicate or predicate(k, v) ]
def get_package_format_names(predicate=None)
Get names for available package formats.
3.80227
3.499499
1.086518
name = opts['--name'] now = datetime.datetime.now() bot.timers[name] = now return bot.start_fmt.format(now)
def start(opts, bot, event)
Usage: start [--name=<name>] Start a timer. Without _name_, start the default timer. To run more than one timer at once, pass _name_ to start and stop.
9.963852
11.191223
0.890327
name = opts['--name'] slack_username = opts['--notify'] now = datetime.datetime.now() delta = now - bot.timers.pop(name) response = bot.stop_fmt.format(delta) if slack_username: mention = '' # The slack api (provided by https://github.com/os/slacker) is available on all...
def stop(opts, bot, event)
Usage: stop [--name=<name>] [--notify=<slack_username>] Stop a timer. _name_ works the same as for `start`. If given _slack_username_, reply with an at-mention to the given user.
5.165053
4.171835
1.238077
client = get_user_api() # Never use API key for the token endpoint config = cloudsmith_api.Configuration() set_api_key(config, None) with catch_raise_api_exception(): data, _, headers = client.user_token_create_with_http_info( data={"email": login, "password": password} ...
def get_user_token(login, password)
Retrieve user token from the API (via authentication).
7.706392
7.660864
1.005943
client = get_user_api() with catch_raise_api_exception(): data, _, headers = client.user_self_with_http_info() ratelimits.maybe_rate_limit(client, headers) return data.authenticated, data.slug, data.email, data.name
def get_user_brief()
Retrieve brief for current user (if any).
9.757306
10.049986
0.970878
try: yield except _ApiException as exc: detail = None fields = None if exc.body: try: # pylint: disable=no-member data = json.loads(exc.body) detail = data.get("detail", None) fields = data.get("fie...
def catch_raise_api_exception()
Context manager that translates upstream API exceptions.
2.764662
2.576881
1.072872
if not cls.config_files: return None if not cls.config_searchpath: return None filename = cls.config_files[0] filepath = cls.config_searchpath[0] return os.path.join(filepath, filename)
def get_default_filepath(cls)
Get the default filepath for the configuratin file.
3.162548
2.791871
1.13277
filepath = cls.get_default_filepath() if not filepath: return False filename = os.path.basename(filepath) config = read_file(get_data_path(), filename) # Find and replace data in default config data = data or {} for k, v in six.iteritems(dat...
def create_default_file(cls, data=None, mode=None)
Create a config file and override data if specified.
2.662666
2.567288
1.037151
for filename in cls.config_files: for searchpath in cls.config_searchpath: path = os.path.join(searchpath, filename) if os.path.exists(path): return True return False
def has_default_file(cls)
Check if a configuration file exists.
3.168504
2.591779
1.222521
if path and os.path.exists(path): if os.path.isdir(path): cls.config_searchpath.insert(0, path) else: cls.config_files.insert(0, path) config = cls.read_config() values = config.get("default", {}) cls._load_values_into_opt...
def load_config(cls, opts, path=None, profile=None)
Load a configuration file into an options object.
3.053046
2.97998
1.024519
config_cls = self.get_config_reader() return config_cls.load_config(self, path, profile=profile)
def load_config_file(self, path, profile=None)
Load the standard config file.
5.587413
5.080256
1.099829
config_cls = self.get_creds_reader() return config_cls.load_config(self, path, profile=profile)
def load_creds_file(self, path, profile=None)
Load the credentials config file.
7.078548
6.166843
1.14784
value = validators.validate_api_headers("api_headers", value) self._set_option("api_headers", value)
def api_headers(self, value)
Set value for API headers.
5.862163
5.175814
1.132607
if isinstance(value, six.string_types): value = [int(x) for x in value.split(",")] self._set_option("error_retry_codes", value)
def error_retry_codes(self, value)
Set value for error_retry_codes.
2.486992
2.680481
0.927816
if not allow_clear: # Prevent clears if value was set try: current_value = self._get_option(name) if value is None and current_value is not None: return except AttributeError: pass self.opts...
def _set_option(self, name, value, allow_clear=False)
Set value for an option.
4.06642
3.882058
1.047491
client = get_rates_api() with catch_raise_api_exception(): data, _, headers = client.rates_limits_list_with_http_info() ratelimits.maybe_rate_limit(client, headers) return { k: RateLimitsInfo.from_dict(v) for k, v in six.iteritems(data.to_dict().get("resources", {})) ...
def get_rate_limits()
Retrieve status (and optionally) version from the API.
6.178626
5.863736
1.053701
if value == '' or (hasattr(value, 'strip') and value.strip() == ''): return None return self.native(value)
def loads(self, value, context=None)
Attempt to load a string-based value into the native representation. Empty strings are treated as ``None`` values.
4.517814
3.374467
1.338823
value = self.dumps(value) fh.write(value) return len(value)
def dump(self, fh, value, context=None)
Attempt to transform and write a string-based foreign value to the given file-like object. Returns the length written.
4.400816
3.589473
1.226034
if self.strip and hasattr(value, 'strip'): value = value.strip() if self.none and value == '': return None if self.encoding and isinstance(value, bytes): return value.decode(self.encoding) return value
def native(self, value, context=None)
Convert a value from a foriegn type (i.e. web-safe) to Python-native.
2.858221
2.737211
1.044209
value = super().native(value, context) if value is None: return try: return self.ingress(value) except Exception as e: raise Concern("Unable to transform incoming value: {0}", str(e))
def native(self, value, context=None)
Convert a value from a foriegn type (i.e. web-safe) to Python-native.
5.76577
5.672861
1.016378
click.echo("Retrieving rate limits ... ", nl=False) context_msg = "Failed to retrieve status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): resources_limits = get_rate_limits() click.secho("OK", fg="green") headers = ["Res...
def rates(ctx, opts)
Check current API rate limits.
2.698696
2.648348
1.019011
click.echo("Retrieving service status ... ", nl=False) context_msg = "Failed to retrieve status!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): status, version = get_status(with_version=True) click.secho("OK", fg="green") c...
def service(ctx, opts)
Check the status of the Cloudsmith service.
2.890346
2.746027
1.052556
client = get_distros_api() # pylint: disable=fixme # TODO(ls): Add package format param on the server-side to filter distros # instead of doing it here. with catch_raise_api_exception(): distros, _, headers = client.distros_list_with_http_info() ratelimits.maybe_rate_limit(client,...
def list_distros(package_format=None)
List available distributions.
5.89382
5.785307
1.018757
a_milli = 1000000.0 td_ds = td.seconds + (td.days * 86400) # 24 * 60 * 60 td_micro = td.microseconds + (td_ds * a_milli) return td_micro / a_milli
def total_seconds(td)
For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(days=4, seconds=33) >>> to...
3.450625
4.511086
0.764921
if dt.tzinfo: td = dt - EPOCH_AWARE else: td = dt - EPOCH_NAIVE return total_seconds(td)
def dt_to_timestamp(dt)
Converts from a :class:`~datetime.datetime` object to an integer timestamp, suitable interoperation with :func:`time.time` and other `Epoch-based timestamps`. .. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time >>> abs(round(time.time() - dt_to_timestamp(datetime.utcnow()), 2)) 0.0...
4.560202
5.762758
0.791323
dt_args = [int(p) for p in _NONDIGIT_RE.split(iso_str)] return datetime(*dt_args)
def isoparse(iso_str)
Parses the limited subset of `ISO8601-formatted time`_ strings as returned by :meth:`datetime.datetime.isoformat`. >>> epoch_dt = datetime.utcfromtimestamp(0) >>> iso_str = epoch_dt.isoformat() >>> print(iso_str) 1970-01-01T00:00:00 >>> isoparse(iso_str) datetime.datetime(1970, 1, 1, 0, 0) ...
7.427789
9.806047
0.75747
td_kwargs = {} for match in _PARSE_TD_RE.finditer(text): value, unit = match.group('value'), match.group('unit') try: unit_key = _PARSE_TD_KW_MAP[unit] except KeyError: raise ValueError('invalid time unit %r, expected one of %r' %...
def parse_timedelta(text)
Robustly parses a short text description of a time period into a :class:`datetime.timedelta`. Supports weeks, days, hours, minutes, and seconds, with or without decimal points: Args: text (str): Text to parse. Returns: datetime.timedelta Raises: ValueError: on parse failure....
2.265573
2.574377
0.880047
if other is None: other = datetime.utcnow() diff = other - d diff_seconds = total_seconds(diff) abs_diff = abs(diff) b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1 bbound, bunit, bname = _BOUNDS[b_idx] f_diff = diff_seconds / total_seconds(bunit) rounded_diff = round(f_d...
def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True)
Get a tuple representing the relative time difference between two :class:`~datetime.datetime` objects or one :class:`~datetime.datetime` and now. Args: d (datetime): The first datetime object. other (datetime): An optional second datetime object. If unset, defaults to the curren...
4.006782
4.293771
0.933161
drt, unit = decimal_relative_time(d, other, ndigits, cardinalize=True) phrase = 'ago' if drt < 0: phrase = 'from now' return '%g %s %s' % (abs(drt), unit, phrase)
def relative_time(d, other=None, ndigits=0)
Get a string representation of the difference between two :class:`~datetime.datetime` objects or one :class:`~datetime.datetime` and the current time. Handles past and future times. Args: d (datetime): The first datetime object. other (datetime): An optional second datetime object. If ...
5.333785
7.267095
0.733964
whence = datetime.strptime(string, format) return whence.date()
def strpdate(string, format)
Parse the date string according to the format in `format`. Returns a :class:`date` object. Internally, :meth:`datetime.strptime` is used to parse the string and thus conversion specifiers for time fields (e.g. `%H`) may be provided; these will be parsed but ignored. Args: string (str): The d...
8.275453
15.23961
0.543023
if not isinstance(start, date): raise TypeError("start expected datetime.date instance") if stop and not isinstance(stop, date): raise TypeError("stop expected datetime.date instance or None") try: y_step, m_step, d_step = step except TypeError: y_step, m_step, d_ste...
def daterange(start, stop, step=1, inclusive=False)
In the spirit of :func:`range` and :func:`xrange`, the `daterange` generator that yields a sequence of :class:`~datetime.date` objects, starting at *start*, incrementing by *step*, until *stop* is reached. When *inclusive* is True, the final date may be *stop*, **if** *step* falls evenly on it. By ...
2.578193
2.597812
0.992448
# Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo("Getting list of distributions ... ", nl=False, err=use_stderr) context_msg = "Failed to get list of distributions!" with handle_api_exceptions(ctx, opts=opts, context_msg=...
def distros(ctx, opts, package_format)
List available distributions.
3.130877
3.151537
0.993444
owner, repo = owner_repo # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.echo("Getting list of packages ... ", nl=False, err=use_stderr) context_msg = "Failed to get list of packages!" with handle_api_exceptions(ctx, opt...
def packages(ctx, opts, owner_repo, page, page_size, query)
List packages for a repository. OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name to list packages for that namespace and repository. All separated by a slash. You can use the search query (-q|--query) to filter packages: - By name: 'my-package' (implicit) or 'name:m...
2.969707
3.229885
0.919447