_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q40400
ExpCM_empirical_phi._compute_empirical_phi
train
def _compute_empirical_phi(self, beta): """Returns empirical `phi` at the given value of `beta`. Does **not** set `phi` attribute, simply returns what should be value of `phi` given the current `g` and `pi_codon` attributes, plus the passed value of `beta`. Note that it uses the...
python
{ "resource": "" }
q40401
ExpCM_empirical_phi._update_dPrxy
train
def _update_dPrxy(self): """Update `dPrxy`, accounting for dependence of `phi` on `beta`.""" super(ExpCM_empirical_phi, self)._update_dPrxy() if 'beta' in self.freeparams: self.dQxy_dbeta = scipy.zeros((N_CODON, N_CODON), dtype='float') for w in range(N_NT): ...
python
{ "resource": "" }
q40402
ExpCM_empirical_phi._update_dprx
train
def _update_dprx(self): """Update `dprx`, accounting for dependence of `phi` on `beta`.""" super(ExpCM_empirical_phi, self)._update_dprx() if 'beta' in self.freeparams: dphi_over_phi = scipy.zeros(N_CODON, dtype='float') for j in range(3): dphi_over_phi +=...
python
{ "resource": "" }
q40403
ExpCM_empirical_phi_divpressure._update_dPrxy
train
def _update_dPrxy(self): """Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`.""" super(ExpCM_empirical_phi_divpressure, self)._update_dPrxy() if 'omega2' in self.freeparams: with scipy.errstate(divide='raise', under='raise', over='raise', in...
python
{ "resource": "" }
q40404
ExpCM_empirical_phi_divpressure._update_Frxy
train
def _update_Frxy(self): """Update `Frxy` from `piAx_piAy_beta`, `omega`, `omega2`, and `beta`.""" self.Frxy.fill(1.0) self.Frxy_no_omega.fill(1.0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.Frxy_no_ome...
python
{ "resource": "" }
q40405
YNGKP_M0._calculate_correctedF3X4
train
def _calculate_correctedF3X4(self): '''Calculate `phi` based on the empirical `e_pw` values''' def F(phi): phi_reshape = phi.reshape((3, N_NT)) functionList = [] stop_frequency = [] for x in range(N_STOP): codonFrequency = STOP_CODON_TO_NT...
python
{ "resource": "" }
q40406
YNGKP_M0._update_Pxy
train
def _update_Pxy(self): """Update `Pxy` using current `omega`, `kappa`, and `Phi_x`.""" scipy.copyto(self.Pxy_no_omega, self.Phi_x.transpose(), where=CODON_SINGLEMUT) self.Pxy_no_omega[0][CODON_TRANSITION] *= self.kappa self.Pxy = self.Pxy_no_omega.copy() self.Pxy[...
python
{ "resource": "" }
q40407
YNGKP_M0._update_dPxy
train
def _update_dPxy(self): """Update `dPxy`.""" if 'kappa' in self.freeparams: scipy.copyto(self.dPxy['kappa'], self.Pxy / self.kappa, where=CODON_TRANSITION) _fill_diagonals(self.dPxy['kappa'], self._diag_indices) if 'omega' in self.freeparams: ...
python
{ "resource": "" }
q40408
YNGKP_M0._update_Pxy_diag
train
def _update_Pxy_diag(self): """Update `D`, `A`, `Ainv` from `Pxy`, `Phi_x`.""" for r in range(1): Phi_x_half = self.Phi_x**0.5 Phi_x_neghalf = self.Phi_x**-0.5 #symm_p = scipy.dot(scipy.diag(Phi_x_half), scipy.dot(self.Pxy[r], scipy.diag(Phi_x_neghalf))) s...
python
{ "resource": "" }
q40409
GammaDistributedModel.dlogprior
train
def dlogprior(self, param): """Equal to value of `basemodel.dlogprior`.""" assert param in self.freeparams, "Invalid param: {0}".format(param) if param in self.distributionparams: return 0.0 else: return self._models[0].dlogprior(param)
python
{ "resource": "" }
q40410
step_impl04
train
def step_impl04(context): """Compare behavior of singleton vs. non-singleton. :param context: test context. """ single = context.singleStore general = context.generalStore key = 13 item = 42 assert single.request(key) == general.request(key) single.add_item(key, item) general.ad...
python
{ "resource": "" }
q40411
step_impl06
train
def step_impl06(context): """Prepare test for singleton property. :param context: test context. """ store = context.SingleStore context.st_1 = store() context.st_2 = store() context.st_3 = store()
python
{ "resource": "" }
q40412
step_impl07
train
def step_impl07(context): """Test for singleton property. :param context: test context. """ assert context.st_1 is context.st_2 assert context.st_2 is context.st_3
python
{ "resource": "" }
q40413
Dbf.open
train
def open(cls, dbfile, encoding=None, fieldnames_lower=True, case_sensitive=True): """Context manager. Allows opening a .dbf file. .. code-block:: with Dbf.open('some.dbf') as dbf: ... :param str|unicode|file dbfile: .dbf filepath or a file-like object. :pa...
python
{ "resource": "" }
q40414
Dbf.open_zip
train
def open_zip(cls, dbname, zipped, encoding=None, fieldnames_lower=True, case_sensitive=True): """Context manager. Allows opening a .dbf file from zip archive. .. code-block:: with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf: ... :param str|unicode dbname: .dbf fi...
python
{ "resource": "" }
q40415
Dbf.iter_rows
train
def iter_rows(self): """Generator reading .dbf row one by one. Yields named tuple Row object. :rtype: Row """ fileobj = self._fileobj cls_row = self.cls_row fields = self.fields for idx in range(self.prolog.records_count): data = fileobj.rea...
python
{ "resource": "" }
q40416
FigColorbar.setup_colorbars
train
def setup_colorbars(self, plot_call_sign): """Setup colorbars for each type of plot. Take all of the optional performed during ``__init__`` method and makes the colorbar. Args: plot_call_sign (obj): Plot instance of ax.contourf with colormapping to add as a colorbar...
python
{ "resource": "" }
q40417
setup_environ
train
def setup_environ(manage_file, settings=None, more_pythonic=False): """Sets up a Django app within a manage.py file. Keyword Arguments **settings** An imported settings module. Without this, playdoh tries to import these modules (in order): DJANGO_SETTINGS_MODULE, settings **more_pyth...
python
{ "resource": "" }
q40418
validate_settings
train
def validate_settings(settings): """ Raise an error in prod if we see any insecure settings. This used to warn during development but that was changed in 71718bec324c2561da6cc3990c927ee87362f0f7 """ from django.core.exceptions import ImproperlyConfigured if settings.SECRET_KEY == '': ...
python
{ "resource": "" }
q40419
incremental_neighbor_graph
train
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None, weighting='none'): '''See neighbor_graph.''' assert ((k is not None) or (epsilon is not None) ), "Must provide `k` or `epsilon`" assert (_issequence(k) ^ _issequence(epsilon) ), "Exactly o...
python
{ "resource": "" }
q40420
Versions
train
def Versions(): """Returns a string with version information. You would call this function if you want a string giving detailed information on the version of ``phydms`` and the associated packages that it uses. """ s = [\ 'Version information:', '\tTime and date: %s' % time....
python
{ "resource": "" }
q40421
readDivPressure
train
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...
python
{ "resource": "" }
q40422
load_configuration
train
def load_configuration(conf_path): """Load and validate test configuration. :param conf_path: path to YAML configuration file. :return: configuration as dict. """ with open(conf_path) as f: conf_dict = yaml.load(f) validate_config(conf_dict) return conf_dict
python
{ "resource": "" }
q40423
main
train
def main(): """Read configuration and execute test runs.""" 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) ...
python
{ "resource": "" }
q40424
ctox
train
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. """ if arguments is None: argumen...
python
{ "resource": "" }
q40425
positional_args
train
def positional_args(arguments): """"Generator for position arguments. Example ------- >>> list(positional_args(["arg1", "arg2", "--kwarg"])) ["arg1", "arg2"] >>> list(positional_args(["--", "arg1", "--kwarg"])) ["arg1", "kwarg"] """ # TODO this behaviour probably isn't quite right....
python
{ "resource": "" }
q40426
Env.ctox
train
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...
python
{ "resource": "" }
q40427
Tokenizer.is_blankspace
train
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. """ if...
python
{ "resource": "" }
q40428
Tokenizer.is_separator
train
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. """ if le...
python
{ "resource": "" }
q40429
jitChol
train
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...
python
{ "resource": "" }
q40430
jitEigh
train
def jitEigh(A,maxTries=10,warning=True): """ Do a Eigenvalue Decomposition with Jitter, works as jitChol """ 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: ...
python
{ "resource": "" }
q40431
modelComparisonDataFrame
train
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 ...
python
{ "resource": "" }
q40432
BenjaminiHochbergCorrection
train
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 ...
python
{ "resource": "" }
q40433
param_dict_to_list
train
def param_dict_to_list(dict,skeys=None): """convert from param dictionary to list""" #sort keys RV = SP.concatenate([dict[key].flatten() for key in skeys]) return RV pass
python
{ "resource": "" }
q40434
checkgrad
train
def checkgrad(f, fprime, x, *args,**kw_args): """ Analytical gradient calculation using a 3-point method """ 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 b...
python
{ "resource": "" }
q40435
Atom.chival
train
def chival(self, bonds): """compute the chiral value around an atom given a list of bonds""" # XXX I'm not sure how this works? order = [bond.xatom(self) for bond in bonds] return self._chirality(order)
python
{ "resource": "" }
q40436
Atom.setchival
train
def setchival(self, bondorder, rotation): """compute chiral ordering of surrounding atoms""" 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:...
python
{ "resource": "" }
q40437
FreedDisambiguate.disambiguate
train
def disambiguate(self, symclasses): """Use the connection to the atoms around a given vertex as a multiplication function to disambiguate a vertex""" offsets = self.offsets result = symclasses[:] for index in self.range: try: val = 1 for offset, bondtype in offsets[index]: ...
python
{ "resource": "" }
q40438
FreedDisambiguate.breakRankTies
train
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 i...
python
{ "resource": "" }
q40439
FreedDisambiguate.findLowest
train
def findLowest(self, symorders): """Find the position of the first lowest tie in a symorder or -1 if there are no ties""" _range = range(len(symorders)) stableSymorders = map(None, symorders, _range) # XXX FIX ME # Do I need to sort? stableSymorders.sort() ...
python
{ "resource": "" }
q40440
FreedDisambiguate.findInvariantPartitioning
train
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 ...
python
{ "resource": "" }
q40441
LowRankCov.setCovariance
train
def setCovariance(self, cov): """ makes lowrank approximation of cov """ 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
python
{ "resource": "" }
q40442
mountain_car_trajectories
train
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) ''' domain = MountainCar() slopes = np.random.normal(0, 0.01, size=num_traj) v0s = np.random.normal(0, 0.005, size=nu...
python
{ "resource": "" }
q40443
before_all
train
def before_all(context): """Setup before all tests. Initialize the logger framework. :param context: test context. """ lf = LoggerFactory(config_file='../features/resources/test_config.yaml') lf.initialize() ll = lf.get_instance('environment') ll.info('Logger initialized: {}'.format(lf...
python
{ "resource": "" }
q40444
shell_escape
train
def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$")): """Escape given string according to shell rules.""" if not text or _safe.match(text): return text squote = type(text)("'") return squote + text.replace(squote, type(text)(r"'\''")) + squote
python
{ "resource": "" }
q40445
get_pattern_mat
train
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. """ pattern_mat = np.zeros((len(pattern)...
python
{ "resource": "" }
q40446
cache_image_data
train
def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs): """ Call uploader and cache its results. """ 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(...
python
{ "resource": "" }
q40447
copy_image_from_url
train
def copy_image_from_url(url, cache_dir=None, use_cache=True): """ Copy image from given URL and return upload metadata. """ return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache)
python
{ "resource": "" }
q40448
_parse_fmt
train
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles', marker_key='marker'): '''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: # Eithe...
python
{ "resource": "" }
q40449
VizMixin.plot
train
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 ...
python
{ "resource": "" }
q40450
normalize_mapping_line
train
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. """ if not mapping_line: retu...
python
{ "resource": "" }
q40451
write
train
def write( stream_fragments, stream, normalize=True, book=None, sources=None, names=None, mappings=None): """ Given an iterable of stream fragments, write it to the stream object by using its write method. Returns a 3-tuple, where the first element is the mapping, second element is the ...
python
{ "resource": "" }
q40452
encode_sourcemap
train
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...
python
{ "resource": "" }
q40453
repr_compat
train
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. """ if unicode and isinstance(s, unicode): return repr(s)[1:] else: return repr(s)
python
{ "resource": "" }
q40454
normrelpath
train
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. """ if not all(map(isabs, [base, target])): return target return relpath(normpath(tar...
python
{ "resource": "" }
q40455
laplacian_reordering
train
def laplacian_reordering(G): '''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,...
python
{ "resource": "" }
q40456
node_centroid_hill_climbing
train
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.''' # Initialize order with BFS from a random start node. order = _breadth_first_order(G) for it in range(num_centerings): B ...
python
{ "resource": "" }
q40457
XSDGenerator.add_column_property_xsd
train
def add_column_property_xsd(self, tb, column_property): """ Add the XSD for a column property to the ``TreeBuilder``. """ if len(column_property.columns) != 1: raise NotImplementedError # pragma: no cover column = column_property.columns[0] if column.primary_key and not self...
python
{ "resource": "" }
q40458
XSDGenerator.add_class_properties_xsd
train
def add_class_properties_xsd(self, tb, cls): """ Add the XSD for the class properties to the ``TreeBuilder``. And call the user ``sequence_callback``. """ for p in class_mapper(cls).iterate_properties: if isinstance(p, ColumnProperty): self.add_column_property_xsd(tb,...
python
{ "resource": "" }
q40459
XSDGenerator.get_class_xsd
train
def get_class_xsd(self, io, cls): """ Returns the XSD for a mapped class. """ 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 ...
python
{ "resource": "" }
q40460
load_db_from_url
train
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 me...
python
{ "resource": "" }
q40461
OECDatabase.searchPlanet
train
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 """ searchNam...
python
{ "resource": "" }
q40462
OECDatabase.transitingPlanets
train
def transitingPlanets(self): """ Returns a list of transiting planet objects """ transitingPlanets = [] for planet in self.planets: try: if planet.isTransiting: transitingPlanets.append(planet) except KeyError: # No 'discover...
python
{ "resource": "" }
q40463
OECDatabase._loadDatabase
train
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 """ # Initialise Database...
python
{ "resource": "" }
q40464
RandomSlugField.generate_slug
train
def generate_slug(self, model_instance): """Returns a unique slug.""" 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:...
python
{ "resource": "" }
q40465
BaseApi.create
train
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_...
python
{ "resource": "" }
q40466
BaseApi.get
train
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 ...
python
{ "resource": "" }
q40467
BaseApi.list
train
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, optio...
python
{ "resource": "" }
q40468
BaseApi.search
train
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 wil...
python
{ "resource": "" }
q40469
simple_integrate
train
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. """ peaks = [] for hints in peak_list: t0, t1 = hints['t0'], hints['t1'] hints['in...
python
{ "resource": "" }
q40470
drop_integrate
train
def drop_integrate(ts, peak_list): """ Resolves overlap by breaking at the minimum value. """ 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...
python
{ "resource": "" }
q40471
_integrate_mpwrap
train
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. """ ts, tpks = ts_and_pks pks = integrate(ts, tpks, **fopts) # for p in pks: # p.info['mz'] = str(ts.na...
python
{ "resource": "" }
q40472
get_bytes
train
def get_bytes(num_bytes): """ Returns a random string of num_bytes length. """ # 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 ...
python
{ "resource": "" }
q40473
get_long
train
def get_long(): """ Generates a random long. The length of said long varies by platform. """ # 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. ...
python
{ "resource": "" }
q40474
auto_instantiate
train
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 v...
python
{ "resource": "" }
q40475
SNRPlanet
train
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_\t...
python
{ "resource": "" }
q40476
transitDurationCircular
train
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 p...
python
{ "resource": "" }
q40477
estimateAbsoluteMagnitude
train
def estimateAbsoluteMagnitude(spectralType): """Uses the spectral type to lookup an approximate absolute magnitude for the star. """ from .astroclasses import SpectralType specType = SpectralType(spectralType) if specType.classLetter == '': return np.nan elif specType.classNumber ...
python
{ "resource": "" }
q40478
is_remote_allowed
train
def is_remote_allowed(remote): """ Check if `remote` is allowed to make a CORS request. """ 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
python
{ "resource": "" }
q40479
OneHash.generate_challenges
train
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. """ # Generate a series of seeds seed...
python
{ "resource": "" }
q40480
OneHash.meet_challenge
train
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...
python
{ "resource": "" }
q40481
OneHash.generate_seeds
train
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 """ # Generate a starting see...
python
{ "resource": "" }
q40482
OneHash.pick_blocks
train
def pick_blocks(self, num, root_seed): """ Pick a set of positions to start reading blocks from the file that challenges are created for. This is a deterministic operation. Positions are guaranteed to be within the bounds of the file. :param num: Number of blocks to pick ...
python
{ "resource": "" }
q40483
OneHash.check_answer
train
def check_answer(self, hash_answer): """ Check if the returned hash is in our challenges list. :param hash_answer: Hash that we compare to our list of challenges :return: boolean indicating if answer is correct, True, or not, False """ for challenge in self.challenges: ...
python
{ "resource": "" }
q40484
HelpScout._load_apis
train
def _load_apis(self): """Find available APIs and set instances property auth proxies.""" helpscout = __import__('helpscout.apis') for class_name in helpscout.apis.__all__: if not class_name.startswith('_'): cls = getattr(helpscout.apis, class_name) api...
python
{ "resource": "" }
q40485
make_response
train
def make_response(response): """Make response tuple Potential features to be added - Parameters validation """ if isinstance(response, unicode) or \ isinstance(response, str): response = (response, 'text/html') return response
python
{ "resource": "" }
q40486
fft
train
def fft(ts): """ Perform a fast-fourier transform on a Trace """ t_step = ts.index[1] - ts.index[0] oc = np.abs(np.fft.fftshift(np.fft.fft(ts.values))) / len(ts.values) t = np.fft.fftshift(np.fft.fftfreq(len(oc), d=t_step)) return Trace(oc, t)
python
{ "resource": "" }
q40487
loads
train
def loads(ast_str): """ Create a Trace from a suitably compressed string. """ data = zlib.decompress(ast_str) li = struct.unpack('<L', data[0:4])[0] lt = struct.unpack('<L', data[4:8])[0] n = data[8:8 + li].decode('utf-8') t = np.fromstring(data[8 + li:8 + li + lt]) d = np.fromstring...
python
{ "resource": "" }
q40488
dumps
train
def dumps(asts): """ Create a compressed string from an Trace. """ d = asts.values.tostring() t = asts.index.values.astype(float).tostring() lt = struct.pack('<L', len(t)) i = asts.name.encode('utf-8') li = struct.pack('<L', len(i)) try: # python 2 return buffer(zlib.compres...
python
{ "resource": "" }
q40489
ts_func
train
def ts_func(f): """ This wraps a function that would normally only accept an array and allows it to operate on a DataFrame. Useful for applying numpy functions to DataFrames. """ def wrap_func(df, *args): # TODO: should vectorize to apply over all columns? return Chromatogram(f(d...
python
{ "resource": "" }
q40490
desaturate
train
def desaturate(c, k=0): """ Utility function to desaturate a color c by an amount k. """ from matplotlib.colors import ColorConverter c = ColorConverter().to_rgb(c) intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] return [intensity * k + i * (1 - k) for i in c]
python
{ "resource": "" }
q40491
find_spectrum_match
train
def find_spectrum_match(spec, spec_lib, method='euclidian'): """ Find spectrum in spec_lib most similar to spec. """ # filter out any points with abundance below 1 % # spec[spec / np.sum(spec) < 0.01] = 0 # normalize everything to sum to 1 spec = spec / np.max(spec) if method == 'dot': ...
python
{ "resource": "" }
q40492
DaemonCLI.get_command
train
def get_command(self, ctx, name): """Get a callable command object.""" if name not in self.daemon_class.list_actions(): return None # The context object is a Daemon object daemon = ctx.obj def subcommand(debug=False): """Call a daemonocle action.""" ...
python
{ "resource": "" }
q40493
ConfigurationLoader.cli_help_message
train
def cli_help_message(self, description): ''' Get a user friendly help message that can be dropped in a `click.Command`\ 's epilog. Parameters ---------- description : str Description of the configuration file to include in the message. Returns ...
python
{ "resource": "" }
q40494
Application.start
train
def start(self): """ Start the application, initializing your components. """ current_pedalboard = self.controller(CurrentController).pedalboard if current_pedalboard is None: self.log('Not exists any current pedalboard.') self.log('Use CurrentController t...
python
{ "resource": "" }
q40495
Application.stop
train
def stop(self): """ Stop the application, closing your components. """ for component in self.components: component.close() self.log('Stopping component - {}', component.__class__.__name__) for controller in self.controllers.values(): controlle...
python
{ "resource": "" }
q40496
get_seconds
train
def get_seconds(value, scale): """Convert time scale dict to seconds Given a dictionary with keys for scale and value, convert value into seconds based on scale. """ scales = { 'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 *...
python
{ "resource": "" }
q40497
_get_col_epsg
train
def _get_col_epsg(mapped_class, geom_attr): """Get the EPSG code associated with a geometry attribute. Arguments: geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of the geometry attribute as defined i...
python
{ "resource": "" }
q40498
create_geom_filter
train
def create_geom_filter(request, mapped_class, geom_attr): """Create MapFish geometry filter based on the request params. Either a box or within or geometry filter, depending on the request params. Additional named arguments are passed to the spatial filter. Arguments: request the request. ...
python
{ "resource": "" }
q40499
create_filter
train
def create_filter(request, mapped_class, geom_attr, **kwargs): """ Create MapFish default filter based on the request params. Arguments: request the request. mapped_class the SQLAlchemy mapped class. geom_attr the key of the geometry property as defined in the SQLAlchemy ...
python
{ "resource": "" }