code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: df = pandas.read_csv(fileName, sep=None, engine='python') pandasformat = True except ValueError: pandasformat = False df.columns = ['site', 'divPressureValue'] scaleFactor = max(df["divPressureValue"].abs()) if scaleFactor > 0: df["divPressureValue"] = [x / ...
def readDivPressure(fileName)
Reads in diversifying pressures from some file. Scale diversifying pressure values so absolute value of the max value is 1, unless all values are zero. Args: `fileName` (string or readable file-like object) File holding diversifying pressure values. Can be comma-, space-, o...
3.664713
3.051314
1.201028
with open(conf_path) as f: conf_dict = yaml.load(f) validate_config(conf_dict) return conf_dict
def load_configuration(conf_path)
Load and validate test configuration. :param conf_path: path to YAML configuration file. :return: configuration as dict.
2.706362
2.998341
0.90262
# TASK improve validation if APPLICATIONS not in conf_dict.keys(): raise InvalidConfigurationError('Missing application configuration.') if SEED_FILES not in conf_dict.keys(): raise InvalidConfigurationError('Missing seed file configuration.') if RUNS not in conf_dict.keys(): ...
def validate_config(conf_dict)
Validate configuration. :param conf_dict: test configuration. :type conf_dict: {} :raise InvalidConfigurationError:
2.951188
2.909933
1.014177
parser = argparse.ArgumentParser(description='Stress test applications.') parser.add_argument('config_path', help='Path to configuration file.') args = parser.parse_args() try: configuration = load_configuration(args.config_path) except InvalidConfigurationError: print("\nConfig...
def main()
Read configuration and execute test runs.
3.614331
3.402082
1.062388
"ctox: tox with conda." try: # pragma: no cover # Exit on broken pipe. import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: import sys sys.exit(cto...
def main(arguments, toxinidir=None)
ctox: tox with conda.
5.132113
4.299324
1.193702
if arguments is None: arguments = [] if toxinidir is None: toxinidir = os.getcwd() args, options = parse_args(arguments) if args.version: print(version) return 0 # if no conda trigger OSError try: with open(os.devnull, "w") as fnull: ch...
def ctox(arguments, toxinidir)
Sets up conda environments, and sets up and runs each environment based on the project's tox.ini configuration file. Returns 1 if either the build or running the commands failed or 0 if all commmands ran successfully.
4.073234
4.052824
1.005036
# TODO this behaviour probably isn't quite right. if arguments and arguments[0] == '--': for a in arguments[1:]: yield a else: for a in arguments: if a.startswith('-'): break yield a
def positional_args(arguments)
Generator for position arguments. Example ------- >>> list(positional_args(["arg1", "arg2", "--kwarg"])) ["arg1", "arg2"] >>> list(positional_args(["--", "arg1", "--kwarg"])) ["arg1", "kwarg"]
4.563073
5.096465
0.895341
"ctox: tox with conda" from sys import argv arguments = argv[1:] toxinidir = os.getcwd() return main(arguments, toxinidir)
def _main()
ctox: tox with conda
19.946808
9.348649
2.133657
# TODO make this less of a hack e.g. using basepython from config # if it exists (and use an attribute directly). if self.name[:4] not in SUPPORTED_ENVS: from colorama import Style cprint(Style.BRIGHT + "Skipping unsupported python version %s\n...
def ctox(self)
Main method for the environment. Parse the tox.ini config, install the dependancies and run the commands. The output of the commands is printed. Returns 0 if they ran successfully, 1 if there was an error (either in setup or whilst running the commands), 2 if the build was skip...
9.25566
8.750134
1.057773
'''Read tokens strings into (is_flag, value) tuples: For this value of `tokens`: ['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack'] `flatten(tokens)` yields an iterable: [ (True, 'f'), (False, 'pets.txt'), (True, ...
def parse_tokens(tokens)
Read tokens strings into (is_flag, value) tuples: For this value of `tokens`: ['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack'] `flatten(tokens)` yields an iterable: [ (True, 'f'), (False, 'pets.txt'), (True, 'v'), ...
8.112108
2.944988
2.754547
if len(char) > 1: raise TypeError("Expected a char.") if char in self.blankspaces: return True return False
def is_blankspace(self, char)
Test if a character is a blankspace. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a blankspace, False otherwise.
5.118761
6.125621
0.835631
if len(char) > 1: raise TypeError("Expected a char.") if char in self.separators: return True return False
def is_separator(self, char)
Test if a character is a separator. Parameters ---------- char : str The character to test. Returns ------- ret : bool True if character is a separator, False otherwise.
4.989153
5.88801
0.847341
# X = linalg.solve(A,linalg.solve(A.transpose(),B)) # much faster version X = linalg.cho_solve((A, True), B) return X
def solve_chol(A,B)
Solve cholesky decomposition:: return A\(A'\B)
4.13073
5.971319
0.691762
jitter = 0 i = 0 while(True): try: # Try --- need to check A is positive definite if jitter == 0: jitter = abs(SP.trace(A))/A.shape[0]*1e-6 LC = linalg.cholesky(A, lower=True) return LC.T, 0.0 else: ...
def jitChol(A, maxTries=10, warning=True)
Do a Cholesky decomposition with jitter. Description: U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky decomposition on the given matrix, if matrix isn't positive definite the function adds 'jitter' and tries again. Thereafter the amount of jitter is multiplied by 10 each time it ...
3.744469
3.859605
0.970169
warning = True jitter = 0 i = 0 while(True): if jitter == 0: jitter = abs(SP.trace(A))/A.shape[0]*1e-6 S,U = linalg.eigh(A) else: if warning: # pdb.set_trace() # plt.figure() # plt.imshow(A, interpolation="nearest") # plt.c...
def jitEigh(A,maxTries=10,warning=True)
Do a Eigenvalue Decomposition with Jitter, works as jitChol
4.015855
4.082204
0.983747
if self.entry_point_group: eps = sorted(pkg_resources.iter_entry_points( self.entry_point_group), key=attrgetter('name')) for ep in eps: app.logger.debug("Loading config for entry point {}".format( ep)) app.conf...
def init_app(self, app)
Initialize Flask application.
4.041618
3.920182
1.030977
df = (pandas.read_csv(modelcomparisonfile, sep='|', skiprows=[1]) .select(lambda x: 'Unnamed' not in x, axis=1) ) # strip whitespace df.columns = df.columns.str.strip() for col in df.columns: if pandas.api.types.is_string_dtype(df[col]): df[col] = df[col...
def modelComparisonDataFrame(modelcomparisonfile, splitparams)
Converts ``modelcomparison.md`` file to `pandas` DataFrame. Running ``phydms_comprehensive`` creates a file with the suffix ``modelcomparison.md``. This function converts that file into a DataFrame that is easy to handle for downstream analysis. Args: `modelcomparisonfile` (str) Th...
2.731112
2.829188
0.965334
num_tests = len(pvals) # sort by p-value sorted_tests = sorted(pvals, key=lambda tup: tup[1]) # find maximum rank for which p <= (rank/num_tests)*FDR max_rank = 0 pcutoff = None for (rank, (label, p)) in enumerate(sorted_tests): rank = rank + 1 # rank beginning with 1 for smal...
def BenjaminiHochbergCorrection(pvals, fdr)
Benjamini-Hochberg procedure to control false discovery rate. Calling arguments: *pvals* : a list of tuples of *(label, p)* where *label* is some label assigned to each data point, and *p* is the corresponding *P-value*. *fdr* : the desired false discovery rate The return value is the 2-tuple ...
4.473949
3.930641
1.138224
#sort keys RV = SP.concatenate([dict[key].flatten() for key in skeys]) return RV pass
def param_dict_to_list(dict,skeys=None)
convert from param dictionary to list
13.011314
13.999975
0.929381
RV = [] i0= 0 for key in skeys: val = param_struct[key] shape = SP.array(val) np = shape.prod() i1 = i0+np params = list[i0:i1].reshape(shape) RV.append((key,params)) i0 = i1 return dict(RV)
def param_list_to_dict(list,param_struct,skeys)
convert from param dictionary to list param_struct: structure of parameter array
3.930096
4.214735
0.932466
LG.debug("Checking gradient ...") import numpy as np # using machine precision to choose h eps = np.finfo(float).eps step = np.sqrt(eps)*(x.min()) # shake things up a bit by taking random steps for each x dimension h = step*np.sign(np.random.uniform(-1, 1, x.size)) f_ph = f(x+h, ...
def checkgrad(f, fprime, x, *args,**kw_args)
Analytical gradient calculation using a 3-point method
2.743641
2.696984
1.0173
if 'gradcheck' in opts: gradcheck = opts['gradcheck'] else: gradcheck = False if 'max_iter_opt' in opts: max_iter = opts['max_iter_opt'] else: max_iter = 5000 if 'pgtol' in opts: pgtol = opts['pgtol'] else: pgtol = 1e-10 params0 = gpr.get...
def opt_hyper(gpr,Ifilter=None,bounds=None,opts={},*args,**kw_args)
optimize params Input: gpr: GP regression class params0: dictionary filled with starting hyperparameters opts: options for optimizer
3.423943
3.448306
0.992935
# XXX I'm not sure how this works? order = [bond.xatom(self) for bond in bonds] return self._chirality(order)
def chival(self, bonds)
compute the chiral value around an atom given a list of bonds
12.824594
12.275593
1.044723
rotation = [None, "@", "@@"][(rotation % 2)] # check to see if the bonds are attached if not bondorder: # use the default xatoms if len(self.oatoms) < 3 and self.explicit_hcount != 1: raise PinkyError("Need to have an explicit hydrogen when specifying "\ ...
def setchival(self, bondorder, rotation)
compute chiral ordering of surrounding atoms
7.547869
7.262942
1.03923
offsets = self.offsets result = symclasses[:] for index in self.range: try: val = 1 for offset, bondtype in offsets[index]: val *= symclasses[offset] * bondtype except OverflowError: # Hmm, how often does this occur? val = 1L for offset, bondtype in offs...
def disambiguate(self, symclasses)
Use the connection to the atoms around a given vertex as a multiplication function to disambiguate a vertex
5.091745
4.990021
1.020386
# XXX FIX ME, should the lowest value be 1 or 0? symclasses = self.symclasses stableSort = map(None, symclasses, range(len(symclasses))) stableSort.sort() last = None x = -1 for order, i in stableSort: if order != last: x += 1...
def rank(self)
convert a list of integers so that the lowest integer is 0, the next lowest is 1 ... note: modifies list in place
7.096336
6.442238
1.101533
stableSort = map(None, oldsym, newsym, range(len(oldsym))) stableSort.sort() lastOld, lastNew = None, None x = -1 for old, new, index in stableSort: if old != lastOld: x += 1 # the last old value was changed, so update both ...
def breakRankTies(self, oldsym, newsym)
break Ties to form a new list with the same integer ordering from high to low Example old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4) new = [60, 2 61,90,99] res = [ 4, 0, 3, 1, 2] * * This tie is broken in this case
4.710307
4.871825
0.966846
_range = range(len(symorders)) stableSymorders = map(None, symorders, _range) # XXX FIX ME # Do I need to sort? stableSymorders.sort() lowest = None for index in _range: if stableSymorders[index][0] == lowest: return stableSym...
def findLowest(self, symorders)
Find the position of the first lowest tie in a symorder or -1 if there are no ties
4.712435
4.615003
1.021112
get = primes.primes.get disambiguate = self.disambiguate breakRankTies = self.breakRankTies while 1: newSyms = map(get, symclasses) newSyms = disambiguate(newSyms) breakRankTies(symclasses, newSyms) if symclasses == newSyms: ...
def findInvariant(self, symclasses)
(symclasses) -> converge the disambiguity function until we have an invariant
3.884797
3.725653
1.042716
symorders = self.symorders[:] _range = range(len(symorders)) while 1: pos = self.findLowest(symorders) if pos == -1: self.symorders = symorders return for i in _range: symorders[i] = symorders[i...
def findInvariantPartitioning(self)
Keep the initial ordering of the symmetry orders but make all values unique. For example, if there are two symmetry orders equal to 0, convert them to 0 and 1 and add 1 to the remaining orders [0, 1, 0, 1] should become [0, 2, 1, 3]
4.093291
3.225803
1.268921
self.refresh_oauth_credential() request = Request( auth_session=self.session, api_host=self.api_host, method=method, path=target, args=args, ) return request.execute()
def _api_call(self, method, target, args=None)
Create a Request object and execute the call to the API Server. Parameters method (str) HTTP request (e.g. 'POST'). target (str) The target URL with leading slash (e.g. '/v1/products'). args (dict) Optional dictionary of argumen...
5.034862
4.960596
1.014971
args = OrderedDict([ ('lat', latitude), ('lng', longitude), ('ride_type', ride_type), ]) return self._api_call('GET', 'v1/ridetypes', args=args)
def get_ride_types(self, latitude, longitude, ride_type=None)
Get information about the Ride Types offered by Lyft at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. ride_type (str) Optional specif...
3.197936
3.760578
0.850384
args = OrderedDict([ ('lat', latitude), ('lng', longitude), ('ride_type', ride_type), ]) return self._api_call('GET', 'v1/eta', args=args)
def get_pickup_time_estimates(self, latitude, longitude, ride_type=None)
Get pickup time estimates (ETA) for products at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. ride_type (str) Optional specific ride ...
3.771128
4.330386
0.870853
args = OrderedDict([ ('start_lat', start_latitude), ('start_lng', start_longitude), ('end_lat', end_latitude), ('end_lng', end_longitude), ('ride_type', ride_type), ]) return self._api_call('GET', 'v1/cost', args=args)
def get_cost_estimates( self, start_latitude, start_longitude, end_latitude=None, end_longitude=None, ride_type=None, )
Get cost estimates (in cents) for rides at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) ...
2.25297
2.535488
0.888575
args = OrderedDict([ ('lat', latitude), ('lng', longitude), ]) return self._api_call('GET', 'v1/drivers', args=args)
def get_drivers(self, latitude, longitude)
Get information about the location of drivers available near a location. A list of 5 locations for a sample of drivers for each ride type will be provided. Parameters latitude (float) The latitude component of a location. longitude (float) The long...
4.724529
5.811606
0.812947
args = { 'ride_type': ride_type, 'origin': { 'lat': start_latitude, 'lng': start_longitude, 'address': start_address, }, 'destination': { 'lat': end_latitude, 'lng': end_longi...
def request_ride( self, ride_type=None, start_latitude=None, start_longitude=None, start_address=None, end_latitude=None, end_longitude=None, end_address=None, primetime_confirmation_token=None, )
Request a ride on behalf of an Lyft user. Parameters ride_type (str) Name of the type of ride you're requesting. E.g., lyft, lyft_plus start_latitude (float) Latitude component of a start location. start_longitude (float) ...
1.698043
1.857589
0.914111
args = { "cancel_confirmation_token": cancel_confirmation_token } endpoint = 'v1/rides/{}/cancel'.format(ride_id) return self._api_call('POST', endpoint, args=args)
def cancel_ride(self, ride_id, cancel_confirmation_token=None)
Cancel an ongoing ride on behalf of a user. Params ride_id (str) The unique ID of the Ride Request. cancel_confirmation_token (str) Optional string containing the cancellation confirmation token. Returns (Response) A Res...
2.833363
3.456573
0.819703
args = { "rating": rating, "tip.amount": tip_amount, "tip.currency": tip_currency, "feedback": feedback, } endpoint = 'v1/rides/{}/rating'.format(ride_id) return self._api_call('PUT', endpoint, args=args)
def rate_tip_ride(self, ride_id, rating, tip_amount=None, tip_currency=None, feedback=None )
Provide a rating, tip or feedback for the specified ride. Params ride_id (str) The unique ID of the Ride Request. rating (int) An integer between 1 and 5 tip_amount Optional integer amount greater than 0 in minor currency units ...
2.678136
3.160881
0.847275
args = { 'start_time': start_time, 'end_time': end_time, 'limit': limit, } return self._api_call('GET', 'v1/rides', args=args)
def get_user_ride_history(self, start_time, end_time, limit=None)
Get activity about the user's lifetime activity with Lyft. Parameters start_time (datetime) Restrict to rides starting after this point in time. The earliest supported date is 2015-01-01T00:00:00Z end_time (datetime) Optional Restrict to ri...
2.576847
3.173489
0.811992
credential = self.session.oauth2credential if credential.is_stale(): refresh_session = refresh_access_token(credential) self.session = refresh_session
def refresh_oauth_credential(self)
Refresh session's OAuth 2.0 credentials if they are stale.
6.45296
4.554248
1.41691
self.setParams(sp.log(sp.diagonal(cov)))
def setCovariance(self,cov)
set hyperparameters from given covariance
18.008911
17.483217
1.030068
assert cov.shape[0]==self.dim, 'Dimension mismatch.' S, U = la.eigh(cov) U = U[:,::-1] S = S[::-1] _X = U[:, :self.rank] * sp.sqrt(S[:self.rank]) self.X = _X
def setCovariance(self, cov)
makes lowrank approximation of cov
4.081329
3.77977
1.079782
'''Collect data using random hard-coded policies on MountainCar. num_traj : int, number of trajectories to collect Returns (trajectories, traces) ''' domain = MountainCar() slopes = np.random.normal(0, 0.01, size=num_traj) v0s = np.random.normal(0, 0.005, size=num_traj) trajectories = [] traces = []...
def mountain_car_trajectories(num_traj)
Collect data using random hard-coded policies on MountainCar. num_traj : int, number of trajectories to collect Returns (trajectories, traces)
3.604511
2.986196
1.207058
lf = LoggerFactory(config_file='../features/resources/test_config.yaml') lf.initialize() ll = lf.get_instance('environment') ll.info('Logger initialized: {}'.format(lf.config)) ll.info('Initial test context: {}'.format(context))
def before_all(context)
Setup before all tests. Initialize the logger framework. :param context: test context.
11.040648
9.932438
1.111575
if not text or _safe.match(text): return text squote = type(text)("'") return squote + text.replace(squote, type(text)(r"'\''")) + squote
def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$"))
Escape given string according to shell rules.
5.598797
4.63359
1.208307
pattern_mat = np.zeros((len(pattern), oracle.n_states-1)) for i,p in enumerate(pattern): length = p[1] for s in p[0]: pattern_mat[i][s-length:s-1] = 1 return pattern_mat
def get_pattern_mat(oracle, pattern)
Output a matrix containing patterns in rows from a vmo. :param oracle: input vmo object :param pattern: pattern extracted from oracle :return: a numpy matrix that could be used to visualize the pattern extracted.
3.461802
3.738023
0.926105
return parts.Bunch( image=parts.Bunch( animated='false', bandwidth=0, caption=None, views=0, deletehash=None, hash=None, name=(url.rsplit('/', 1) + [url])[1], title=None, type='image/*', width=0, height=0, size=0, datetime=int(time.time()), # XXX was fmt.iso_datetime...
def fake_upload_from_url(url)
Return a 'fake' upload data record, so that upload errors can be mitigated by using an original / alternative URL, especially when cross-loading from the web.
8.527974
8.702895
0.979901
use_cache = True if "use_cache" in kwargs: use_cache = kwargs["use_cache"] del kwargs["use_cache"] json_path = None if cache_dir: json_path = os.path.join(cache_dir, "cached-img-%s.json" % cache_key) if use_cache and os.path.exists(json_path): LOG.info("...
def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs)
Call uploader and cache its results.
2.892337
2.834878
1.020269
return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache)
def copy_image_from_url(url, cache_dir=None, use_cache=True)
Copy image from given URL and return upload metadata.
6.780552
6.949017
0.975757
import pprint import tempfile try: image = sys.argv[1] except IndexError: print("Usage: python -m pyrobase.webservice.imgur <url>") else: try: pprint.pprint(copy_image_from_url(image, cache_dir=tempfile.gettempdir())) except UploadError as exc: ...
def _main()
Command line interface for testing.
5.58587
5.518359
1.012234
assert self.client_id, "imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable..." assert self.client_secret, "imgur client secret is not set! Export the IMGUR_CLIENT_SECRET environment variable..." # Prepare image try: image_data = (image + '')...
def upload(self, image, name=None)
Upload the given image, which can be a http[s] URL, a path to an existing file, binary image data, or an open file handle.
4.247796
4.179173
1.01642
'''Modified from matplotlib's _process_plot_format function.''' try: # Is fmt just a colorspec? color = mcolors.colorConverter.to_rgb(fmt) except ValueError: pass # No, not just a color. else: # Either a color or a numeric marker style if fmt not in mlines.lineMarkers: return {color_key:...
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles', marker_key='marker')
Modified from matplotlib's _process_plot_format function.
3.043304
2.760849
1.102307
'''Plot the graph using matplotlib in 2 or 3 dimensions. coordinates : (n,2) or (n,3) array of vertex coordinates directed : if True, edges have arrows indicating direction. weighted : if True, edges are colored by their weight. fig : a matplotlib Figure to use, or one of {'new','current'}. Default...
def plot(self, coordinates, directed=False, weighted=False, fig='current', ax=None, edge_style=None, vertex_style=None, title=None, cmap=None)
Plot the graph using matplotlib in 2 or 3 dimensions. coordinates : (n,2) or (n,3) array of vertex coordinates directed : if True, edges have arrows indicating direction. weighted : if True, edges are colored by their weight. fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to ...
2.572264
1.734858
1.482695
if not mapping_line: return [], previous_source_column # Note that while the local record here is also done as a 4-tuple, # element 1 and 2 are never used since they are always provided by # the segments in the mapping line; they are defined for consistency # reasons. def regener...
def normalize_mapping_line(mapping_line, previous_source_column=0)
Often times the position will remain stable, such that the naive process will end up with many redundant values; this function will iterate through the line and remove all extra values.
8.770515
8.625304
1.016835
return { "version": 3, "sources": sources, "names": names, "mappings": encode_mappings(mappings), "file": filename, }
def encode_sourcemap(filename, mappings, sources, names=[])
Take a filename, mappings and names produced from the write function and sources. As the write function currently does not handle the tracking of source filenames, the sources should be a list of one element with the original filename. Arguments filename The target filename that the strea...
2.205049
3.175251
0.694449
encode_sourcemap_args, output_js_map = verify_write_sourcemap_args( mappings, sources, names, output_stream, sourcemap_stream, normalize_paths ) encoded_sourcemap = json.dumps( encode_sourcemap(*encode_sourcemap_args), sort_keys=True, ensure_ascii=False, ) if ...
def write_sourcemap( mappings, sources, names, output_stream, sourcemap_stream, normalize_paths=True, source_mapping_url=NotImplemented)
Write out the mappings, sources and names (generally produced by the write function) to the provided sourcemap_stream, and write the sourceMappingURL to the output_stream. Arguments mappings, sources, names These should be values produced by write function from this module. output_...
3.136256
3.145278
0.997132
if name is None: return if name not in self._names: # add the name if it isn't already tracked self._names[name] = len(self._names) result = self._names[name] - self._current self._current = self._names[name] return result
def update(self, name)
Query a name for the relative index value to be added into the source map name field (optional 5th element).
3.644486
3.369445
1.081628
if unicode and isinstance(s, unicode): return repr(s)[1:] else: return repr(s)
def repr_compat(s)
Since Python 2 is annoying with unicode literals, and that we are enforcing the usage of unicode, this ensures the repr doesn't spew out the unicode literal prefix.
5.353157
3.538796
1.512706
package_name, module_name = name.rsplit('.', 1) version = ply_dist.version.replace( '.', '_') if ply_dist is not None else 'unknown' data = (package_name, module_name, py_major, version) lextab = '%s.lextab_%s_py%d_ply%s' % data yacctab = '%s.yacctab_%s_py%d_ply%s' % data return l...
def generate_tab_names(name)
Return the names to lextab and yacctab modules for the given module name. Typical usage should be like so:: >>> lextab, yacctab = generate_tab_names(__name__)
4.564363
3.952236
1.154881
if not all(map(isabs, [base, target])): return target return relpath(normpath(target), dirname(normpath(base)))
def normrelpath(base, target)
This function takes the base and target arguments as paths, and returns an equivalent relative path from base to the target, if both provided paths are absolute.
4.387355
4.546539
0.964988
'''Reorder the graph's vertices, returning a copy of the input graph. order : integer array-like, some permutation of range(G.num_vertices()). ''' adj = G.matrix('dense') adj = adj[np.ix_(order, order)] return Graph.from_adj_matrix(adj)
def permute_graph(G, order)
Reorder the graph's vertices, returning a copy of the input graph. order : integer array-like, some permutation of range(G.num_vertices()).
6.579969
2.675195
2.459622
'''Reorder vertices using the eigenvector of the graph Laplacian corresponding to the first positive eigenvalue.''' L = G.laplacian() vals, vecs = np.linalg.eigh(L) min_positive_idx = np.argmax(vals == vals[vals>0].min()) vec = vecs[:, min_positive_idx] return permute_graph(G, np.argsort(vec))
def laplacian_reordering(G)
Reorder vertices using the eigenvector of the graph Laplacian corresponding to the first positive eigenvalue.
4.933233
3.149254
1.566477
'''Iterative reordering method based on alternating rounds of node-centering and hill-climbing search.''' # Initialize order with BFS from a random start node. order = _breadth_first_order(G) for it in range(num_centerings): B = permute_graph(G, order).bandwidth() nc_order = _node_center(G, order, rel...
def node_centroid_hill_climbing(G, relax=1, num_centerings=20, verbose=False)
Iterative reordering method based on alternating rounds of node-centering and hill-climbing search.
4.740393
3.350909
1.414659
if column.nullable: attrs['minOccurs'] = str(0) attrs['nillable'] = 'true' for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES): if isinstance(column.type, cls): attrs['type'] = xsd_type with tag(tb, 'xsd:element', attrs) ...
def add_column_xsd(self, tb, column, attrs)
Add the XSD for a column to tb (a TreeBuilder)
1.506707
1.504227
1.001648
if len(column_property.columns) != 1: raise NotImplementedError # pragma: no cover column = column_property.columns[0] if column.primary_key and not self.include_primary_keys: return if column.foreign_keys and not self.include_foreign_keys: i...
def add_column_property_xsd(self, tb, column_property)
Add the XSD for a column property to the ``TreeBuilder``.
3.351038
3.211862
1.043332
for p in class_mapper(cls).iterate_properties: if isinstance(p, ColumnProperty): self.add_column_property_xsd(tb, p) if self.sequence_callback: self.sequence_callback(tb, cls)
def add_class_properties_xsd(self, tb, cls)
Add the XSD for the class properties to the ``TreeBuilder``. And call the user ``sequence_callback``.
3.868827
2.65897
1.45501
attrs = {} attrs['xmlns:gml'] = 'http://www.opengis.net/gml' attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema' tb = TreeBuilder() with tag(tb, 'xsd:schema', attrs) as tb: with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb: wit...
def get_class_xsd(self, io, cls)
Returns the XSD for a mapped class.
2.301713
2.196893
1.047713
catalogue = gzip.GzipFile(fileobj=io.BytesIO(requests.get(url).content)) database = OECDatabase(catalogue, stream=True) return database
def load_db_from_url(url="https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz")
Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo in the OpenExoplanetCatalogue GitHub group. The database is loaded from the url in memory :param url: url to load (must be gzipped version of systems folder) :return: OECDatabase objected in...
4.576088
5.598105
0.817435
searchName = compactString(name) returnDict = {} for altname, planetObj in self._planetSearchDict.iteritems(): if re.search(searchName, altname): returnDict[planetObj.name] = planetObj if returnDict: if len(returnDict) == 1: ...
def searchPlanet(self, name)
Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even just 1214. :param name: the name of the planet to search :return: dictionary of results as planetname -> planet object
3.566606
3.6553
0.975735
transitingPlanets = [] for planet in self.planets: try: if planet.isTransiting: transitingPlanets.append(planet) except KeyError: # No 'discoverymethod' tag - this also filters Solar System planets pass retu...
def transitingPlanets(self)
Returns a list of transiting planet objects
6.733785
6.151334
1.094687
planetNameDict = {} for planet in self.planets: name = planet.name altnames = planet.params['altnames'] altnames.append(name) # as we also want the default name to be searchable for altname in altnames: reducedname = compactStr...
def _generatePlanetSearchDict(self)
Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form (lowercase, no spaces and dashes)
6.001624
5.391103
1.113246
# Initialise Database self.systems = [] self.binaries = [] self.stars = [] self.planets = [] if stream: tree = ET.parse(databaseLocation) for system in tree.findall(".//system"): self._loadSystem(system) else: ...
def _loadDatabase(self, databaseLocation, stream=False)
Loads the database from a given file path in the class :param databaseLocation: the location on disk or the stream object :param stream: if true treats the databaseLocation as a stream object
4.548897
4.69639
0.968594
queryset = model_instance.__class__._default_manager.all() # Only count slugs that match current length to prevent issues # when pre-existing slugs are a different length. lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length} if queryset.filter(**lookup).count...
def generate_slug(self, model_instance)
Returns a unique slug.
3.670617
3.58261
1.024565
# We'll just introspect the _actual_ field. from south.modelsinspector import introspector field_class = '%s.%s' % (self.__module__, self.__class__.__name__) args, kwargs = introspector(self) kwargs.update({ 'length': repr(self.length), 'exclude_u...
def south_field_triple(self)
Returns a suitable description of this field for South.
2.723574
2.547278
1.06921
cls._check_implements('create') data = record.to_api() params = { 'reload': True, } params.update(**add_params) data.update(params) return cls( endpoint_override or '/%s.json' % cls.__endpoint__, data=data, ...
def create(cls, session, record, endpoint_override=None, out_type=None, **add_params)
Create an object on HelpScout. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be created. endpoint_override (str, optional): Override the default endpoint using this. out_type (helpsco...
5.434434
7.039919
0.771946
cls._check_implements('delete') return cls( endpoint_override or '/%s/%s.json' % ( cls.__endpoint__, record.id, ), request_type=RequestPaginator.DELETE, singleton=True, session=session, out_type=out_type, ...
def delete(cls, session, record, endpoint_override=None, out_type=None)
Delete a record. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be deleted. endpoint_override (str, optional): Override the default endpoint using this. out_type (helpscout.BaseModel, ...
6.676804
7.351788
0.908188
cls._check_implements('get') try: return cls( endpoint_override or '/%s/%d.json' % ( cls.__endpoint__, record_id, ), singleton=True, session=session, ) except HelpScoutRemoteExcep...
def get(cls, session, record_id, endpoint_override=None)
Return a specific record. Args: session (requests.sessions.Session): Authenticated session. record_id (int): The ID of the record to get. endpoint_override (str, optional): Override the default endpoint using this. Returns: helpscout.Base...
5.181933
4.613122
1.123303
cls._check_implements('list') return cls( endpoint_override or '/%s.json' % cls.__endpoint__, data=data, session=session, )
def list(cls, session, endpoint_override=None, data=None)
Return records in a mailbox. Args: session (requests.sessions.Session): Authenticated session. endpoint_override (str, optional): Override the default endpoint using this. data (dict, optional): Data to provide as request parameters. Returns: ...
8.827516
9.786797
0.901982
cls._check_implements('search') domain = cls.get_search_domain(queries) return cls( '/search/%s.json' % cls.__endpoint__, data={'query': str(domain)}, session=session, out_type=out_type, )
def search(cls, session, queries, out_type)
Search for a record given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Dom...
5.6116
6.109271
0.918539
cls._check_implements('update') data = record.to_api() del data['id'] data['reload'] = True return cls( '/%s/%s.json' % (cls.__endpoint__, record.id), data=data, request_type=RequestPaginator.PUT, singleton=True, ...
def update(cls, session, record)
Update a record. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be updated. Returns: helpscout.BaseModel: Freshly updated record.
6.663633
7.510657
0.887224
peaks = [] for hints in peak_list: t0, t1 = hints['t0'], hints['t1'] hints['int'] = intname pk_ts = ts.twin((t0, t1)) if base_ts is None: # make a two point baseline base = Trace([hints.get('y0', pk_ts[0]), hints.get('y1', pk...
def simple_integrate(ts, peak_list, base_ts=None, intname='simple')
Integrate each peak naively; without regard to overlap. This is used as the terminal step by most of the other integrators.
3.871543
4.057673
0.954129
peaks = [] for _, pks in _get_windows(peak_list): temp_pks = [] pks = sorted(pks, key=lambda p: p['t0']) if 'y0' in pks[0] and 'y1' in pks[-1]: y0, y1 = pks[0]['y0'], pks[-1]['y1'] else: y0 = ts.get_point(pks[0]['t0']) y1 = ts.get_point(pk...
def drop_integrate(ts, peak_list)
Resolves overlap by breaking at the minimum value.
2.988161
2.992435
0.998572
ts, tpks = ts_and_pks pks = integrate(ts, tpks, **fopts) # for p in pks: # p.info['mz'] = str(ts.name) return pks
def _integrate_mpwrap(ts_and_pks, integrate, fopts)
Take a zipped timeseries and peaks found in it and integrate it to return peaks. Used to allow multiprocessing support.
5.018451
4.385599
1.144302
# Is this the way to do it? #s = c_ubyte() # Or this? s = create_string_buffer(num_bytes) # Used to keep track of status. 1 = success, 0 = error. ok = c_int() # Provider? hProv = c_ulong() ok = windll.Advapi32.CryptAcquireContextA(byref(hProv), None, None, PROV_RSA_FULL, 0) ...
def get_bytes(num_bytes)
Returns a random string of num_bytes length.
5.57021
5.440019
1.023932
# The C long type to populate. pbRandomData = c_ulong() # Determine the byte size of this machine's long type. size_of_long = wintypes.DWORD(sizeof(pbRandomData)) # Used to keep track of status. 1 = success, 0 = error. ok = c_int() # Provider? hProv = c_ulong() ok = windll.Adva...
def get_long()
Generates a random long. The length of said long varies by platform.
6.524404
6.387865
1.021375
def decorator(f): if not hasattr(f, '__annotations__'): f.__annotations__ = kwargs.copy() else: f.__annotations__.update(kwargs) if args: if len(args) != 1: raise ValueError('annotate supports only a single argument.') f._...
def annotate(*args, **kwargs)
Set function annotations (on Python2 and 3).
2.766484
2.513959
1.100449
def decorator(f): # collect our argspec sig = signature(f) @wraps(f) def _(*args, **kwargs): bvals = sig.bind(*args, **kwargs) # replace with instance if desired for varname, val in bvals.arguments.items(): anno = sig.paramet...
def auto_instantiate(*classes)
Creates a decorator that will instantiate objects based on function parameter annotations. The decorator will check every argument passed into ``f``. If ``f`` has an annotation for the specified parameter and the annotation is found in ``classes``, the parameter value passed in will be used to construc...
5.516138
5.503881
1.002227
# make it work if given only one argument (for Python3) if len(argnames) == 1 and callable(argnames[0]): return data()(argnames[0]) def decorator(f): f = annotate(**dict((argname, Data) for argname in argnames))(f) f = auto_instantiate(Data)(f) return f return decor...
def data(*argnames)
Designate an argument as a :class:`~data.Data` argument. Works by combining calls to :func:`~data.decorators.auto_instantiate` and :func:~data.decorators.annotate` on the named arguments. Example: .. code-block:: python class Foo(object): @data('bar') def meth(self, foo,...
4.721998
4.399352
1.073339
def ratioTerminatorToStar(H_p, R_p, R_s): # TODO add into planet class r deltaF = ((10 * H_p * R_p) + (25 * H_p**2)) / (R_s**2) return deltaF.simplified
r"""Calculates the ratio of the terminator to the star assuming 5 scale heights large. If you dont know all of the input try :py:func:`calcRatioTerminatorToStar` .. math:: \Delta F = \frac{10 H R_p + 25 H^2}{R_\star^2} Where :math:`\Delta F` is the ration of the terminator to the star, H s...
null
null
null
r SNRplanet = SNRStar * starPlanetFlux * \ sqrt(Nobs) * sqrt(pixPerbin) * sqrt(NVisits) return SNRplanet
def SNRPlanet(SNRStar, starPlanetFlux, Nobs, pixPerbin, NVisits=1)
r""" Calculate the Signal to Noise Ratio of the planet atmosphere .. math:: \text{SNR}_\text{planet} = \text{SNR}_\text{star} \times \Delta F \times \sqrt{N_\text{obs}} \times \sqrt{N_\text{pixPerbin}} \times \sqrt{N_\text{visits}} Where :math:`\text{SNR}_\star` SNR of the star detecti...
4.794689
4.27582
1.12135
r if i is nan: i = 90 * aq.deg i = i.rescale(aq.rad) k = R_p / R_s # lit reference for eclipsing binaries b = (a * cos(i)) / R_s duration = (P / pi) * arcsin(((R_s * sqrt((1 + k) ** 2 - b ** 2)) / (a * sin(i))).simplified) return dur...
def transitDurationCircular(P, R_s, R_p, a, i)
r"""Estimation of the primary transit time. Assumes a circular orbit. .. math:: T_\text{dur} = \frac{P}{\pi}\sin^{-1} \left[\frac{R_\star}{a}\frac{\sqrt{(1+k)^2 + b^2}}{\sin{a}} \right] Where :math:`T_\text{dur}` transit duration, P orbital period, :math:`R_\star` radius of the star, a is ...
9.335192
8.981534
1.039376
# TODO improve with more x and k values from Cox 2000 try: temp = (5800 * aq.K * float(M_s.rescale(aq.M_s) ** 0.65)).rescale(aq.K) except AttributeError: temp = np.nan return temp
def estimateStellarTemperature(M_s)
Estimates stellar temperature using the main sequence relationship T ~ 5800*M^0.65 (Cox 2000).
12.005426
7.760149
1.547061
try: m = float(m) # basic value checking as there is no units M = float(M) Av = float(Av) except TypeError: return np.nan d = 10 ** ((m - M + 5 - Av) / 5) if math.isnan(d): return np.nan else: return d * aq.pc
def estimateDistance(m, M, Av=0.0)
estimate the distance to star based on the absolute magnitude, apparent magnitude and the absorption / extinction. :param m: apparent magnitude :param M: absolute magnitude :param Av: absorbtion / extinction :return: d (distance to object) in parsecs
5.613843
4.762331
1.178802
magnitude_estimation_filepath = resource_filename( __name__, 'data/magnitude_estimation.dat') raw_table = np.loadtxt(magnitude_estimation_filepath, '|S5') absMagDict = { 'O': {}, 'B': {}, 'A': {}, 'F': {}, 'G': {}, 'K': {}, 'M': {}} f...
def _createAbsMagEstimationDict()
loads magnitude_estimation.dat which is from http://xoomer.virgilio.it/hrtrace/Sk.htm on 24/01/2014 and based on Schmid-Kaler (1982) creates a dict in the form [Classletter][ClassNumber][List of values for each L Class]
4.35199
4.026404
1.080863
from .astroclasses import SpectralType specType = SpectralType(spectralType) if specType.classLetter == '': return np.nan elif specType.classNumber == '': specType.classNumber = 5 # approximation using mid magnitude value if specType.lumType == '': specType.lumType ...
def estimateAbsoluteMagnitude(spectralType)
Uses the spectral type to lookup an approximate absolute magnitude for the star.
7.456282
7.05206
1.05732
if settings.debug: return True if not remote: return False for domain_pattern in settings.node['cors_whitelist_domains']: if domain_pattern.match(remote): return True return False
def is_remote_allowed(remote)
Check if `remote` is allowed to make a CORS request.
5.946238
4.823699
1.232713
def decorator(function, methods=methods): # Always allow OPTIONS since CORS requests will need it. methods = set(methods) methods.add('OPTIONS') @wraps(function) def wrapper(environment, start_response): try: start_time = time.time() if function.func_name not in (_servin...
def endpoint(url, methods=['GET'])
Returns a decorator which when applied a function, causes that function to serve `url` and only allows the HTTP methods in `methods`
2.606425
2.655742
0.98143
# Generate a series of seeds seeds = self.generate_seeds(num, root_seed, self.secret) blocks = self.pick_blocks(num, root_seed) # List of 2-tuples (seed, hash_response) self.challenges = [] # Generate the corresponding hash for each seed for i in range...
def generate_challenges(self, num, root_seed)
Generate the specified number of hash challenges. :param num: The number of hash challenges we want to generate. :param root_seed: Some value that we use to generate our seeds from.
4.537326
4.563726
0.994215
chunk_size = min(1024, self.file_size // 10) seed = challenge.seed h = hashlib.sha256() self.file_object.seek(challenge.block) if challenge.block > (self.file_size - chunk_size): end_slice = ( challenge.block - (self.file_size - chunk_size) ...
def meet_challenge(self, challenge)
Get the SHA256 hash of a specific file block plus the provided seed. The default block size is one tenth of the file. If the file is larger than 10KB, 1KB is used as the block size. :param challenge: challenge as a `Challenge <heartbeat.Challenge>` object
2.745443
2.479061
1.107453
# Generate a starting seed from the root if num < 0: raise HeartbeatError('%s is not greater than 0' % num) if secret is None: raise HeartbeatError('secret can not be of type NoneType') seeds = [] try: tmp_seed = hashlib.sha256(root_...
def generate_seeds(num, root_seed, secret)
Deterministically generate list of seeds from a root seed. :param num: Numbers of seeds to generate as int :param root_seed: Seed to start off with. :return: seed values as a list of length num
3.211173
3.180398
1.009677