code
stringlengths
1
18.2k
def XanyKXany(self): """ compute self covariance for any """ result = np.empty((self.P,self.F_any.shape[1],self.F_any.shape[1]), order='C') for p in range(self.P): X1D = self.Fstar_any * self.D[:,p:p+1] X1X2 = X1D.T.dot(self.Fstar_any) result[p] = X1X2 return result
def XanyKX(self): """ compute cross covariance for any and rest """ result = np.empty((self.P,self.F_any.shape[1],self.dof), order='C') #This is trivially parallelizable: for p in range(self.P): FanyD = self.Fstar_any * self.D[:,p:p+1] start = 0 #This is trivially parallelizable: for term in range(self.len): stop = sta...
def XKX(self): """ compute self covariance for rest """ cov_beta = np.zeros((self.dof,self.dof)) start_row = 0 #This is trivially parallelizable: for term1 in range(self.len): stop_row = start_row + self.A[term1].shape[0] * self.F[term1].shape[1] start_col = start_row #This is trivially parallelizable: for term2 in ran...
def request_access_token( grant_type, client_id=None, client_secret=None, scopes=None, code=None, refresh_token=None ): """Make an HTTP POST to request an access token. Parameters grant_type (str) Either 'client_credientials' (Client Credentials Grant) or 'authorization_code' (Authorization Code Grant). client_id (str)...
'client_id': client_id, 'client_secret': client_secret, 'scope': scopes, 'code': code, 'refresh_token': refresh_token, } auth_header = HTTPBasicAuth(client_id, client_secret) response = post(url=url, auth=auth_header, data=args) if response.status_code == codes.ok: return response message = 'Failed to request access to...
def refresh_access_token(credential): """Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credentials. Raises...
def revoke_access_token(credential): """Revoke an access token. All future requests with the access token will be invalid. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Raises ClientError (APIError) Thrown if there was an HTTP error. """ url = build_url(auth.SERVER_HOST, auth.REVO...
def _build_authorization_request_url( self, response_type, state=None ): """Form URL to request an auth code or access token. Parameters response_type (str) Only 'code' (Authorization Code Grant) supported at this time state (str) Optional CSRF State token to send to server. Returns (str) The fully constructed authoriz...
def _extract_query(self, redirect_url): """Extract query parameters from a url. Parameters redirect_url (str) The full URL that the Lyft server redirected to after the user authorized your app. Returns (dict) A dictionary of query parameters. """ qs = urlparse(redirect_url) # redirect_urls return data after query ident...
def get_session(self, redirect_url): """Complete the Authorization Code Grant process. The redirect URL received after the user has authorized your application contains an authorization code. Use this authorization code to request an access token. Parameters redirect_url (str) The full URL that the Lyft server redirect...
def get_session(self): """Create Session to store credentials. Returns (Session) A Session object with OAuth 2.0 credentials. """ response = request_access_token( grant_type=auth.CLIENT_CREDENTIAL_GRANT, client_id=self.client_id, client_secret=self.client_secret, scopes=self.scopes, ) oauth2credential = OAuth2Credentia...
def hello_user(api_client): """Use an authorized client to fetch and print profile information. Parameters api_client (LyftRidesClient) An LyftRidesClient with OAuth 2.0 credentials. """ try: response = api_client.get_user_profile() except (ClientError, ServerError) as error: fail_print(error) return else: profile = re...
def lint(): "report pylint results" # report according to file extension report_formats = { ".html": "html", ".log": "parseable", ".txt": "text", } lint_build_dir = easy.path("build/lint") lint_build_dir.exists() or lint_build_dir.makedirs() # pylint: disable=expression-not-assigned argv = [] rcfile = easy.options.lint...
& 32: # usage error (internal error in this code) sys.stderr.write("paver::lint - Usage error, bad arguments %r?!\n" % (argv,)) sys.exit(exc.returncode) else: bits = { 1: "fatal", 2: "error", 4: "warning", 8: "refactor", 16: "convention", } sys.stderr.write("paver::lint - Some %s message(s) issued.\n" % ( ", ".join([te...
def generate_contour_data(pid): """ Main function for this program. This will read in sensitivity_curves and binary parameters; calculate snrs with a matched filtering approach; and then read the contour data out to a file. Args: pid (obj or dict): GenInput class or dictionary containing all of the input information fo...
file_out.output_file_type + '_read_out')() print(time.time()-begin_time) return
def send_message(self, msg): """ Internal method used to send messages through Clementine remote network protocol. """ if self.socket is not None: msg.version = self.PROTOCOL_VERSION serialized = msg.SerializeToString() data = struct.pack(">I", len(serialized)) + serialized #print("Sending message: %s" % msg) try: self...
def _connect(self): """ Connects to the server defined in the constructor. """ self.first_data_sent_complete = False self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.host, self.port)) msg = cr.Message() msg.type = cr.CONNECT msg.request_connect.auth_code = self.auth_code or 0 ms...
def play(self): """ Sends a "play" command to the player. """ msg = cr.Message() msg.type = cr.PLAY self.send_message(msg)
def pause(self): """ Sends a "play" command to the player. """ msg = cr.Message() msg.type = cr.PAUSE self.send_message(msg)
def stop(self): """ Sends a "play" command to the player. """ msg = cr.Message() msg.type = cr.STOP self.send_message(msg)
def playpause(self): """ Sends a "playpause" command to the player. """ msg = cr.Message() msg.type = cr.PLAYPAUSE self.send_message(msg)
def next(self): """ Sends a "next" command to the player. """ msg = cr.Message() msg.type = cr.NEXT self.send_message(msg)
def previous(self): """ Sends a "previous" command to the player. """ msg = cr.Message() msg.type = cr.PREVIOUS self.send_message(msg)
def set_volume(self, volume): """ Sets player volume (note, this does not change host computer main volume). """ msg = cr.Message() msg.type = cr.SET_VOLUME msg.request_set_volume.volume = int(volume) self.send_message(msg)
def solve_t(self, Mt): """ Mt is dim_r x dim_c x d tensor """ if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt M = _Mt.transpose([0,2,1]) MLc = sp.tensordot(M, self.Lc().T, (2,0)) MLcLc = sp.tensordot(MLc, self.Lc(), (2,0)) WrMLcWc = sp.tensordot(sp.tensordot(self.Wr(), MLc, (1,0)), self.Wc().T, (2,0)) DW...
def p_commands_list(p): """commands : commands command""" p[0] = p[1] # section 3.2: REQUIRE command must come before any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands): print("REQUIRE command on line %d must come before any " "other non-RE...
def p_command(p): """command : IDENTIFIER arguments ';' | IDENTIFIER arguments block""" #print("COMMAND:", p[1], p[2], p[3]) tests = p[2].get('tests') block = None if p[3] != ';': block = p[3] handler = sifter.handler.get('command', p[1]) if handler is None: print("No handler registered for command '%s' on line %d" % (...
def p_block(p): """block : '{' commands '}' """ # section 3.2: REQUIRE command must come before any other commands, # which means it can't be in the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): print("REQUIRE command not allowed inside of a block (line %d)" % (p.li...
def p_arguments(p): """arguments : argumentlist | argumentlist test | argumentlist '(' testlist ')'""" p[0] = { 'args' : p[1], } if len(p) > 2: if p[2] == '(': p[0]['tests'] = p[3] else: p[0]['tests'] = [ p[2] ]
def init_app(self, app): """Initialize Flask application.""" if self.module: app.config.from_object(self.module)
def step_impl03(context): """Check assertions. :param context: test context. """ assert len(context.buf) == len(context.fuzzed_buf) count = number_of_modified_bytes(context.buf, context.fuzzed_buf) assert count < 3 assert count >= 0
def step_impl(context, max_modified): """Check assertions. :param max_modified: maximum expected number of modifications. :param context: test context. """ assert len(context.buf) == len(context.fuzzed_buf) count = number_of_modified_bytes(context.buf, context.fuzzed_buf) assert count >= 0 assert count <= max_modified
def step_impl06(context, count): """Execute fuzzer. :param count: number of string variants to generate. :param context: test context. """ fuzz_factor = 11 context.fuzzed_string_list = fuzz_string(context.seed, count, fuzz_factor)
def step_impl07(context, len_list): """Check assertions. :param len_list: expected number of variants. :param context: test context. """ assert len(context.fuzzed_string_list) == len_list for fuzzed_string in context.fuzzed_string_list: assert len(context.seed) == len(fuzzed_string) count = number_of_modified_bytes(con...
def step_impl08(context): """Create file list. :param context: test context. """ assert context.table, "ENSURE: table is provided." context.file_list = [row['file_path'] for row in context.table.rows]
def step_impl09(context): """Create application list. :param context: test context. """ assert context.table, "ENSURE: table is provided." context.app_list = [row['application'] for row in context.table.rows]
def step_impl10(context): """Create application list. :param context: test context. """ assert context.app_list and len( context.app_list) > 0, "ENSURE: app list is provided." assert context.file_list and len( context.file_list) > 0, "ENSURE: file list is provided." context.fuzz_executor = FuzzExecutor(context.app_list...
def step_impl11(context, runs): """Execute multiple runs. :param runs: number of test runs to perform. :param context: test context. """ executor = context.fuzz_executor executor.run_test(runs) stats = executor.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: stats available."
def step_impl12(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs."
def step_impl13(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." successful_runs = stats.cumulated_c...
def step_impl14(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." failed_runs = stats.cumulated_count...
def number_of_modified_bytes(buf, fuzzed_buf): """Determine the number of differing bytes. :param buf: original buffer. :param fuzzed_buf: fuzzed buffer. :return: number of different bytes. :rtype: int """ count = 0 for idx, b in enumerate(buf): if b != fuzzed_buf[idx]: count += 1 return count
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): '''Given a connected graph adj matrix (W), add edges to flesh it out.''' W = W.astype(bool) assert np.all(W == W.T), 'graph given to flesh_out must be symmetric' D = pairwise_distances(X, metric=...
CC_mask if verbose: # pragma: no cover print('before F:', candidate_edges.sum(), 'potentials') # calc subspaces subspaces, _ = cluster_subspaces(X, embed_dim, CC_labels.max()+1, CC_labels) # upper triangular avoids p,q <-> q,p repeats ii,jj = np.where(np.triu(candidate_edges)) # Get angles edge_dirs = X[ii] - X[jj] ssi...
def edge_cluster_angle(edge_dirs, subspaces1, subspaces2): '''edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.''' QG = edge_dirs / np.linalg.norm(edge_dirs, ord=2, axis=1)[:,None] X1 = np.einsum('...ij,...i->....
def sigma_nfw(self): """Calculate NFW surface mass density profile. Generate the surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Surface mass...
all real\n') # calculate & return centered profiles if f.ndim == 2: sigma = 2. * self._rs_dc_rcrit * f else: rs_dc_rcrit_4D = self._rs_dc_rcrit.T.reshape(1, 1, f.shape[2], f.shape[3]) sigma = 2. * rs_dc_rcrit_4D * f return sigma def _offset_sigma(self): # size of "x" arrays to integrate over numRoff = self._numRoff num...
= _centered_sigma(self) inner_integrand = sigma.value / (2. * np.pi) # INTEGRATE OVER theta sigma_of_RgivenRoff = simps(inner_integrand, x=theta_1D, axis=0, even='first') # theta is gone, now dimensions are: (numRoff,numRbins,nlens) sig_off_3D = self._sigmaoffset.value.reshape(1, 1, self._nlens) roff_v2 = roff_1D.resha...
def deltasigma_nfw(self): """Calculate NFW differential surface mass density profile. Generate the differential surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns -...
(1. + self._x[self._x_small])) secondpart[self._x_small] = np.log((1. + small_2a) / (1. - small_2a)) big_2a = self._x[self._x_big] - 1. big_2b = 1. + self._x[self._x_big] secondpart[self._x_big] = np.arctan(np.sqrt(big_2a / big_2b)) both_3a = (4. / (self._x**2)) * np.log(self._x / 2.) both_3b = 2. / (self._x**2 - 1.) g...
self._factorRouter * self._nbins r_outer = np.linspace(original_rbins.min(), original_rbins.max(), endpoint=False, num=outer_prec + 1)[1:] r_ext_unordered = np.hstack([r_inner, r_outer, original_rbins]) r_extended = np.sort(r_ext_unordered) # set temporary extended rbins, nbins, x, rs_dc_rcrit array self._rbins = r_ext...
= self._rs * self._delta_c * self._rho_crit self._rs_dc_rcrit = rs_dc_rcrit.reshape(self._nlens, 1).repeat(self._nbins, 1) self._sigma_sm = sigma_sm_rbins # reset to original sigma_sm dsigma_sm = mean_inside_sigma_sm - sigma_sm_rbins return dsigma_sm if self._sigmaoffset is None: finaldeltasigma = _centered_dsigma(self...
def from_edge_pairs(pairs, num_vertices=None, symmetric=False, weights=None): '''Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2) ''' if not symmetric: if weights is None: return EdgePairGraph(pairs, num_vertices=num_vertices) row, col = np.as...
weights return SparseAdjacencyMatrixGraph(s)
def W(self,value): """ set fixed effect design """ if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
def Wstar(self,value): """ set fixed effect design for predictions """ if value is None: self._use_to_predict = False else: assert value.shape[1]==self._K, 'Dimension mismatch' self._use_to_predict = True self._Wstar = value self.clear_cache('predict')
def obfuscate( obfuscate_globals=False, shadow_funcname=False, reserved_keywords=()): """ An example, barebone name obfuscation ruleset obfuscate_globals If true, identifier names on the global scope will also be obfuscated. Default is False. shadow_funcname If True, obfuscated function names will be shadowed. Default ...
def declared_symbols(self): """ Return all local symbols here, and also of the parents """ return self.local_declared_symbols | ( self.parent.declared_symbols if self.parent else set())
def global_symbols(self): """ These are symbols that have been referenced, but not declared within this scope or any parent scopes. """ declared_symbols = self.declared_symbols return set( s for s in self.referenced_symbols if s not in declared_symbols)
def global_symbols_in_children(self): """ This is based on all children referenced symbols that have not been declared. The intended use case is to ban the symbols from being used as remapped symbol values. """ result = set() for child in self.children: result |= ( child.global_symbols | child.global_symbols_in_childre...
def close(self): """ Mark the scope as closed, i.e. all symbols have been declared, and no further declarations should be done. """ if self._closed: raise ValueError('scope is already marked as closed') # By letting parent know which symbols this scope has leaked, it # will let them reserve all lowest identifiers first...
def _reserved_symbols(self): """ Helper property for the build_remap_symbols method. This property first resolves _all_ local references from parents, skipping all locally declared symbols as the goal is to generate a local mapping for them, but in a way not to shadow over any already declared symbols from parents, and...
purity of references made, this somewhat more involved way # is done instead. remapped_parents_symbols = { self.resolve(v) for v in self.non_local_symbols} return ( # block implicit children globals. self.global_symbols_in_children | # also not any global symbols self.global_symbols | # also all remapped parent symbols...
def build_remap_symbols(self, name_generator, children_only=True): """ This builds the replacement table for all the defined symbols for all the children, and this scope, if the children_only argument is False. """ if not children_only: replacement = name_generator(skip=(self._reserved_symbols)) for symbol, c in revers...
def nest(self, node, cls=None): """ Create a new nested scope that is within this instance, binding the provided node to it. """ if cls is None: cls = type(self) nested_scope = cls(node, self) self.children.append(nested_scope) return nested_scope
def declare(self, symbol): """ Nothing gets declared here - it's the parents problem, except for the case where the symbol is the one we have here. """ if symbol != self.catch_symbol: self.parent.declare(symbol)
def reference(self, symbol, count=1): """ However, if referenced, ensure that the counter is applied to the catch symbol. """ if symbol == self.catch_symbol: self.catch_symbol_usage += count else: self.parent.reference(symbol, count)
def build_remap_symbols(self, name_generator, children_only=None): """ The children_only flag is inapplicable, but this is included as the Scope class is defined like so. Here this simply just place the catch symbol with the next replacement available. """ replacement = name_generator(skip=(self._reserved_symbols)) sel...
def register_reference(self, dispatcher, node): """ Register this identifier to the current scope, and mark it as referenced in the current scope. """ # the identifier node itself will be mapped to the current scope # for the resolve to work # This should probably WARN about the node object being already # assigned to ...
def shadow_reference(self, dispatcher, node): """ Only simply make a reference to the value in the current scope, specifically for the FuncBase type. """ # as opposed to the previous one, only add the value of the # identifier itself to the scope so that it becomes reserved. self.current_scope.reference(node.identifier...
def resolve(self, dispatcher, node): """ For the given node, resolve it into the scope it was declared at, and if one was found, return its value. """ scope = self.identifiers.get(node) if not scope: return node.value return scope.resolve(node.value)
def walk(self, dispatcher, node): """ Walk through the node with a custom dispatcher for extraction of details that are required. """ deferrable_handlers = { Declare: self.declare, Resolve: self.register_reference, } layout_handlers = { PushScope: self.push_scope, PopScope: self.pop_scope, PushCatch: self.push_catch, #...
def finalize(self): """ Finalize the run - build the name generator and use it to build the remap symbol tables. """ self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_generator, children_only=not self.obfuscate_globals, )
def prewalk_hook(self, dispatcher, node): """ This is for the Unparser to use as a prewalk hook. """ self.walk(dispatcher, node) self.finalize() return node
def clean(): "take out the trash" src_dir = easy.options.setdefault("docs", {}).get('src_dir', None) if src_dir is None: src_dir = 'src' if easy.path('src').exists() else '.' with easy.pushd(src_dir): for pkg in set(easy.options.setup.packages) | set(("tests",)): for filename in glob.glob(pkg.replace('.', os.sep) + "/*...
def _set_grid_info(self, which, low, high, num, scale, name): """Set the grid values for x or y. Create information for the grid of x and y values. Args: which (str): `x` or `y`. low/high (float): Lowest/highest value for the axis. num (int): Number of points on axis. scale (str): Scale of the axis. Choices are 'log' o...
or log.'.format(which)) setattr(self.generate_info, which + 'scale', scale) return
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name): """Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str...
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name): """Set the grid values for x. Create information for the grid of x values. Args: num_x (int): Number of points on axis. x_low/x_high (float): Lowest/highest value for the axis. xscale (str): Scale of the axis. Choices are 'log' or 'lin'. xval_name (str...
def add_noise_curve(self, name, noise_type='ASD', is_wd_background=False): """Add a noise curve for generation. This will add a noise curve for an SNR calculation by appending to the sensitivity_curves list within the sensitivity_input dictionary. The name of the noise curve prior to the file extension will appear as i...
'sensitivity_curves' not in self.sensitivity_input.__dict__: self.sensitivity_input.sensitivity_curves = [] if 'noise_type_in' not in self.sensitivity_input.__dict__: self.sensitivity_input.noise_type_in = [] self.sensitivity_input.sensitivity_curves.append(name) self.sensitivity_input.noise_type_in.append(noise_type) ...
def set_wd_noise(self, wd_noise): """Add White Dwarf Background Noise This adds the White Dwarf (WD) Background noise. This can either do calculations with, without, or with and without WD noise. Args: wd_noise (bool or str, optional): Add or remove WD background noise. First option is to have only calculations with th...
must be yes, no, True, False, or Both.') self.sensitivity_input.add_wd_noise = wd_noise return
def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1): """Change generation type. Choose weather to generate the data in parallel or on a single processor. Args: num_processors (int or None, optional): Number of parallel processors to use. If ``num_processors==-1``, this will use multiprocessing...
def set_signal_type(self, sig_type): """Set the signal type of interest. Sets the signal type for which the SNR is calculated. This means inspiral, merger, and/or ringdown. Args: sig_type (str or list of str): Signal type desired by user. Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD...
def return_dict(self): """Output dictionary for :mod:`gwsnrcalc.generate_contour_data` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for :mod:`gwsnrcalc.generate_contour_data`. If `print_input` attribute is True, the entire dictionary...
def pretty_print(ast, indent_str=' '): """ Simple pretty print function; returns a string rendering of an input AST of an ES5 Program. arguments ast The AST to pretty print indent_str The string used for indentations. Defaults to two spaces. """ return ''.join(chunk.text for chunk in pretty_printer(indent_str)(ast))
def minify_printer( obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Construct a minimum printer. Arguments obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the...
def minify_print( ast, obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened id...
return ''.join(chunk.text for chunk in minify_printer( obfuscate, obfuscate_globals, shadow_funcname, drop_semi)(ast))
def encode_vlq(i): """ Encode integer `i` into a VLQ encoded string. """ # shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw < VLQ_MULTI_CHAR: # short-circuit simple case as it doesn't need continuation return INT_B64[raw] result = [] while raw: # assume continue result.append(r...
def decode_vlqs(s): """ Decode str `s` into a list of integers. """ ints = [] i = 0 shift = 0 for c in s: raw = B64_INT[c] cont = VLQ_CONT & raw i = ((VLQ_BASE_MASK & raw) << shift) | i shift += VLQ_SHIFT if not cont: sign = -1 if 1 & i else 1 ints.append((i >> 1) * sign) i = 0 shift = 0 return tuple(ints)
def init_app(self, app): """Initialize Flask application.""" # Ensure SECRET_KEY is set. SECRET_KEY = app.config.get('SECRET_KEY') if SECRET_KEY is None: app.config['SECRET_KEY'] = 'CHANGE_ME' warnings.warn( 'Set configuration variable SECRET_KEY with random string', UserWarning)
def require_json(): """ Load the best available json library on demand. """ # Fails when "json" is missing and "simplejson" is not installed either try: import json # pylint: disable=F0401 return json except ImportError: try: import simplejson # pylint: disable=F0401 return simplejson except ImportError as exc: raise I...
def _findNextPrime(self, N): """Generate the first N primes""" primes = self.primes nextPrime = primes[-1]+1 while(len(primes)<N): maximum = nextPrime * nextPrime prime = 1 for i in primes: if i > maximum: break if nextPrime % i == 0: prime = 0 break if prime: primes.append(nextPrime) nextPrime+=1
def venv_bin(name=None): # pylint: disable=inconsistent-return-statements """ Get the directory for virtualenv stubs, or a full executable path if C{name} is provided. """ if not hasattr(sys, "real_prefix"): easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,)) sys.exit(1) for bindir in ("bin", "Scripts"): ...
def vsh(cmd, *args, **kw): """ Execute a command installed into the active virtualenv. """ args = '" "'.join(i.replace('"', r'\"') for i in args) easy.sh('"%s" "%s"' % (venv_bin(cmd), args))
def install_tools(dependencies): """ Install a required tool before using it, if it's missing. Note that C{dependencies} can be a distutils requirement, or a simple name from the C{tools} task configuration, or a (nested) list of such requirements. """ tools = getattr(easy.options, "tools", {}) for dependency in iterut...
def task_requires(*dependencies): """ A task decorator that ensures a distutils dependency (or a list thereof) is met before that task is executed. """ def entangle(task): "Decorator wrapper." if not isinstance(task, tasks.Task): task = tasks.Task(task) def tool_task(*args, **kw): "Install requirements, then call origi...