content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import collections def fit_all_random(X_matr, rand_X_matr, Y_matr, rows, lag, fit_method, save_prefix=None, save_XY=True, verbose=False, has_reps=False, bootstrap=False, seed=None, only_array=False, **kwargs): """ X_matr: m x T (x r) of X's rand_X_matr: m x T ( x r) of X's. Same as X_matr exce...
4957dae3b60a73e4526a6cee3119a1722d2a1112
3,611,967
def check_bad_bbox(data, test_op, invalid_bbox_type, expected_error): """ :param data: de object detection pipeline :param test_op: Augmentation Op to test on image :param invalid_bbox_type: type of bad box :param expected_error: error expected to get due to bad box :return: None """ de...
fad04a018ef0b7def476f2a5491857e5de40b3d2
3,611,968
def check_patch_in_bounds(x, y, X_dim, Y_dim): """ Usage: TrueFalse = check_patch_in_bounds(x, y, X_dim, Y_dim) determine if the box is within the image Args: x: a tuple, list or array (x_start, x_end) y: a tuple, list or array (y_start, Y_end) ...
80221a95fda698f31aeed6c91987a5227a21e751
3,611,969
def _tiger_line_url(geometry, year): """ Return URL (or URLs) of zip file(s) containing shape files for a given census geography :param geometry: name of census geometry to download :param year: year of geometry to download :return: List of URLs """ base = "https://www2.census.gov/geo/t...
a6f84c9fd26ec270fd29c37a6181220cde4dabda
3,611,970
def get_coordinate_transformation(source_sr, target_sr): """This function takes a source and target spatial reference and creates a coordinate transformation from source to target, and one from target to source. source_sr - A spatial reference target_sr - A spatial reference ...
3f47cdd9886f18e4b8357f29a23fee8ac756f250
3,611,971
def d_customer_orders(): """ Real Name: b'D Customer Orders' Original Eqn: b'W Indicated Orders' Units: b'' Limits: (None, None) Type: component b'' """ return w_indicated_orders()
df26969c14f0d0929b96246926d42b1eab8345f8
3,611,972
def build_reservations_ical_file(reservations): """ Return iCalendar file containing given reservations """ cal = Calendar() cal['X-WR-CALNAME'] = vText('RESPA') cal['name'] = vText('RESPA') for reservation in reservations: event = Event() event['uid'] = 'respa_reservation_{...
c034502c3854264c3ee1ecea03c87b185519da83
3,611,973
def domain(request) -> str: """Return AWS domain""" return request.config.getoption("--domain") or "amazonaws.com"
fbf812dd28eb6aa3ff6a647a4cd1d17b739cb320
3,611,974
def sha2_384(data: bytes) -> hashes.MessageDigest: """ Convenience function to hash a message. """ return CryptographyHash.hash(hashes.sha2_384(), data)
6053054b84a37e5d99d2a7bfe4fcf34499945f25
3,611,975
def build_corpus(group): """ Function to apply to a category subset. Returns a list of LabeledSentences to train doc2vec. """ return group.apply(lambda row: LabeledSentence(row.clean_comment, [row.sentence_tag]), axis=1).values
987f7e52553eb09cc30fb3ad2665ee7a8b009c93
3,611,976
import ast def get_substitutions_from_config(config): """ Return a list of Substitution objects from the config, sorted alphabetically by pattern name. Returns an empty list if no Substitutions are specified. If there are problems parsing the values, a help message will be printed and an error wil...
45defbbe9f14a08052fd0c3cb320b8c8735a91cc
3,611,977
import base64 import hashlib def signature(text): """ This helper method normalizes text and takes the SHA1 hash of it, returning the base64 encoded result. The normalization method includes the removal of punctuation and white space as well as making the case completely lowercase. These signature...
4984094624e172d1e6666746378c7b7dfac256cf
3,611,978
def no_stderr(): """ There is no standard error """ with app.app_context(): return jsonify({'error':'stderr does not exist'}), 400
3c42b3557d7fe342cd800a127452c15d5c4ce7ee
3,611,979
import torch def compute_colors_for_labels(labels): """ Simple function that adds fixed colors depending on the class """ palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1]) colors = labels[:, None] *palette # self.palette colors = (colors % 255).numpy().astype("uint8") ...
59785d9a6f297d022ee13e9a4013cd28e7f62a10
3,611,980
def read_table(data, coerce_type, transpose=False): """ Reads in data from a simple table and forces it to be a particular type This is a helper function that allows data to be easily constained in a simple script ::return: a dictionary of with the keys being a tuple of the strings in the fi...
6701736354b30d41b4adf7c6a11406f26c21c71b
3,611,982
def load_def_omni(tint, cfg, data_path): """Loads Density Energy Flux spectrum Parameters ---------- tint : list of str Time interval cfg : dict Hash table from configuration file. Returns ------- """ ic = np.arange(1, 5) suf = "fpi_{}_{}".format(cfg["data_r...
868675a6ebaa94719346c97771e5d70547e14cb3
3,611,983
def test_constant(): """ Test a tesorflow session """ sess = tf.Session() first = tf.constant(4) second = tf.constant(5) return sess.run(first * second)
2ce039f1c07ac60c751a015c9f56575b7f2d5bb4
3,611,984
def robots(): """Robot Crawler txt for search engines.""" if current_app.config['STATIC_ROUTES'].get('robots', None): response = make_response( render_template( template_path(current_app.config['STATIC_ROUTES']['robots']) ) ) response.headers['Cont...
2dcb80dd58e86c90cc22b68ad39a09509dd52311
3,611,985
def cat_arg_and_value(arg_name, value): """Concatenate a command line argument and its value This function returns ``arg_name`` and ``value concatenated in the best possible way for a command line execution, namely: - if arg_name starts with `--` (e.g. `--arg`): `arg_name=value` is returned (...
bcd99ab465707e594646d2152ad7b10b32956f5e
3,611,987
def is_expired_dds_response(response): """ Check status_code of the response for the two values denoting expired URLs :param response: requests.Response :return: bool: True when the response is expired status """ return response.status_code == SWIFT_EXPIRED_STATUS_CODE or response.status_code ==...
47d774a0fcf22cc11d9f0ed0de0eb77dbc44185e
3,611,988
def write_session(prev_sessions, sessions, start_time, end_time, session_path, logger=structlog.get_logger()): """ Rewrite json file with new data :param prev_sessions: old sessions :param sessions: new sessions :param time: timestamp of processed flows :param session_path: path to json file ...
306ad7b84acf99bce0a4585bb31b09a297341e6d
3,611,989
def remove_formatting(input: str) -> str: """Remove color information from string.""" return input.replace(bcolors.ENDC, "")\ .replace(bcolors.OKGREEN, "")\ .replace(bcolors.OKBLUE, "")
4e459a38b925bc0fac733c7570407b9c9265ab67
3,611,990
def update_event(request, event_id): """Event update view. If the request type is POST, update the event and redirect the user to the events detail page. Otherwise, display the event creation form. Arguments: request - Django object containing request information. event_id (int) - ID of Event ...
fe164f7e17f431559ca3d6ffbdcb78aa49979c77
3,611,991
def poly_linear_constraints(p, d): """ Given p = [p1, ..., pm] in k[t]^m and d in k[t], return q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible by d if and only if (c1, ..., cm) is a solution of Mx = 0, in which case...
3fcdcaf312c8a4e95853ff21e9225d81acc9a927
3,611,992
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ step_unit = 1000.0 # 1024? results=[] for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: results.append("%3.2f %s" % (num, x)) num /= step_unit return results
41ec1d6e7a7975d1bddf22a09f840c59e3283b95
3,611,993
def comment_is_liked(comment_entity, liker): """Returns true if a given user (liker) has liked a given comment""" likes_query = CommentLike.all() likes_query.filter('liker =', liker) likes_query.filter('comment =', comment_entity) return likes_query.count() > 0
9cf3e453370a1bec19adbf182f56713b72690a70
3,611,994
def GetRenderView(connection=None): """Return the render view in use. If more than one render view is in use, return the first one.""" if not connection: connection = ActiveConnection render_module = None for aProxy in ProxyManager().NewConnectionIterator(connection): if aProxy.IsA...
4328efd8a96f7185814e4119e98c6f2ec182473c
3,611,995
def get_fuzzer_name(fuzzer_config_filename: str) -> str: """Get the fuzzer specified in fuzzer_config_filename""" fuzzer_config = yaml_utils.read(get_fuzzer_configs_dir() / fuzzer_config_filename) # Multiple configurations of the same fuzzer are differentiated by their ...
c7be73a0278262b864d246c45a5193a295af325a
3,611,996
def colorize_mask(mask, color_map=None): """ Attaches a color palette to a PIL image. So long as the image is saved as a PNG, it will render visibly using the provided color map. :param mask: PIL image whose values are only 0 to 4 inclusive :param color_map: np.ndarray or list of 3-tuples with 5 row...
45b6e6fb224711791dab843c42e93c40fbda5a28
3,611,997
import requests def langs(): """ Get list of both src and target languages """ html = requests.get(settings.site_url).content crawl_soup = bs4.BeautifulSoup(html, 'html.parser') langs = [] lang_id = 0 tags = crawl_soup.find('select').find_all('option') for tag in tags: nam...
e8128d0b629e6cb1b810dd9d91b756f6e92e9c37
3,611,998
def publisher(handler): """ Decorator that will publish messages to SNS Topics. This decorator looks for a 'messages' key in the result of the wrapper decorator. It expects result['messages'] to be a dict where key is Topic Name or ARN and value is the message to be sent. It will publish each message to ...
6f203909a36c48cb4c724141bebf98059550413c
3,612,000
import inspect def unwrap_obj(obj): """ Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap """ try: obj = obj.fget except (AttributeError, TypeError): pass try: # Cached properties if obj.func.__doc__ == obj.__do...
d158d7ed832823b66e46bea00a96c5799684bd33
3,612,001
def get_user(user_id) -> dict: """ Used only in record_to_dict and user_setting. """ user = ( db.session.query(Users.username, Users.name, Users.classnum, Users.email) .filter_by(id=user_id) .first() ) return { "username": user.username, "name": user.name,...
a25334ad1ee9abbb7f695c4e07d4cc6bcdf288cc
3,612,002
def isolines(location, **kwargs): """ :param location: an address string, or a shapely geometry the source location :param graph: NetworkX graph :param edges: geopandas GeoDataFrame :param edge_idcol: string id attribute/column name of the graph/edges GeoDataFrame (default is 'id') :para...
a809cd66e31880761f5c2c051ca9396cd037ca08
3,612,003
def delete_item(bucketlist_id, item_id): """ Deletes a bucketlist item :param bucketlist_id: :param item_id: :return: """ item = get_item(bucketlist_id, item_id) if not item or not get_bucketlist(bucketlist_id): return jsonify({ 'message': 'Bucketlist item not found....
ae30796f289fc55fae68a42b054d79703240d262
3,612,004
def predict_on_atom_efs(param): """Predict the local energy, forces, and partial stresses and predictive variances of a chemical environment.""" structure, atom, gp = param chemenv = AtomicEnvironment(structure, atom, gp.cutoffs) return gp.predict_efs(chemenv)
d16332ac72b95791e3053a450e669f6b97f0ee9f
3,612,005
def get_export_info(archive_name): """ Given a file or directory, extract it and return information that will be used in an export printout: the basename of the file, the name stripped of its extension, and our best guess (based on Slack's current naming convention) of the name of the workspace that...
7d88e13f48ee6d44d23a65abf89777d455c3d074
3,612,006
def call_var42127803hap(bamfile, cnvtag, base_db): """ Call haplotype with regard to g.42127803C>T and g.42127941G>A """ diff_haplotype = False if cnvtag == "cn2": haplotype_per_read = get_haplotypes_from_bam_single_region( bamfile, base_db, range(len(base_db.dsnp1)) ) ...
259c17e5df88e66b47f81c180499421fb97f862e
3,612,007
def closest_match(num,num_list): """ Finds the closest number to num in num_list. :num: (float) a number :num_list: (array of floats) :returns: (float) the number in num_list closest to num """ diffs = np.abs(np.subtract(num,num_list)) return num_list[np.argmin(diffs)]
37628d00de6bf1d16416a8b18c76b97e43bf0345
3,612,008
def get_workspace(repo_context): """ Construct the workspace url from the given repo context :param repo_context: Repo context from context.py :return: Workspace url for known VCS or None """ if not repo_context["repositoryUri"]: return None revision = repo_context.get("revisionId",...
ebab3b089c8267932a7a660207b8c7d4b38148f9
3,612,009
def get_wavelet(wavelet_name, dtype=tf.float32): """ Get a wavelet based on the wavelets name. Args: wavelet_name (str): Name of the wavelet ('haar', 'db1', 'db2', 'db3' or 'db4'). Returns: A wavelet object. If the wavelet name is not recognized, it returns None. """ wname = wa...
a1df3e42d0eefcde2e05fa3fa96d11185ba4088d
3,612,010
def argToBoolean(value): """ Boolean-ish arguments that are passed through demisto.args() could be type bool or type string. This command removes the guesswork and returns a value of type bool, regardless of the input value's type. It will also return True for 'yes' and False for 'no'. ...
a2b74145d98f22e6341d7b8a7a7fae6f1b1d9dd7
3,612,011
from typing import Optional def initialize_table( nrows=0, name: Optional[str] = None, subj: Optional[str] = None, set: Optional[str] = None, path: Optional[str] = None, ) -> Document: """Initializes a docx file containing the Science Bowl header row. Parameters ---------- nrows :...
04d580a9d2b2ceabb37f8abdaa89592ad09c9ddb
3,612,013
def plotlify_scatter_js(xy=None, x=None, y=None, xtag=None, ytag=None, description=""): """ Update the plot data in plotly format. :param xy: x and y in a single structure. :param description: The description of the plotly plot. :param plot_type: The type of the plotly plot. :return: A dictiona...
2ad2e33dde23ec18f162c28425380b99ae3596a6
3,612,014
from typing import Tuple from typing import Dict def get_sequence_context_to_array_index_table(motif_size: int) \ -> Tuple[Dict[str, int], Dict[str, int]]: """ Return dicts mapping sequence contexts to counter array indices Parameters ---------- motif_size: int size of motifs (e.g. 3 ...
e76116da86d07f2af3114b3337a45d32d5aa3b44
3,612,015
def make_cover_image(im): """ Make a cover image. That is, resize an image to be smaller than :py:data:`COVER_SIZE` if necessary. Parameters: im: A sanpera ``Image``. Returns: *im*, if the image is smaller than :py:data:`COVER_SIZE`. Otherwise, a new ``Image`` resized ...
64fe84f1514ecf03cb8196b94767a2b4c77ad5da
3,612,016
def uniqueCruiseIdentifier_exists(cruise_id): """ Verify cruise identifier provided does not exist. Boolean result True if exists, else False. """ try: try: # If uframe returns a value, then cruise exists, otherwise it does not. #value = uframe_get_cruise_by_subsite(cruise_id...
f1b0de22bc1ff5a3caa9bdc5263570e89042ff9e
3,612,017
def operator(openshift): """Return operator pod object.""" def select_operator(apiobject): return apiobject.get_label("app") == "apicast" and apiobject.get_label("control-plane") == "controller-manager" project_name = settings["threescale"]["gateway"]["OperatorApicast"]['openshift']['project_name'...
91e1b66086e0cd1453ff517f2be91273b4a95be8
3,612,018
def envelops(reg, target_reg): """Given a region and another target region, returns whether the region is enveloped within the target region.""" return (target_reg.start <= reg.start < target_reg.end) \ and (target_reg.start <= reg.end < target_reg.end)
716f2e905bdb852d9e0b85ff0482a70a64d325f1
3,612,020
def stats(request): """Show usage stats""" if settings.WASCH_USE_LEGACY: users_count = len(Users.select(Users.login).execute()) machines_count = len( Waschmaschinen.select(Waschmaschinen.id).execute()) appointents_count = len(Termine.select(Termine.user).execute()) else: ...
767bdb3cb4975258682b0301d99cc8b9888c7e6c
3,612,021
def get_ror_inflows(aggregation_level: str, timestamps: pd.DatetimeIndex = None) -> pd.DataFrame: """Returns ROR inflows (per unit of installed power capacity) per NUTS or country in which it exists""" return get_hydro_inflows(aggregation_level, 'ror', timestamps)
e3610b4f026b5d92d6f98826d779d14ad7f0dca4
3,612,022
def get_EI(dim, sigmas, Ampl, nE, nI, alpha, **kwargs): """ wrapper function for connectivity matrix input: dim: dimensionality, 1 or 2 sigmas: list or float of standard deviation of connectivity Ampl: list or float of standard deviation of connectivity nE: size of excitatory units nI: size of inhibitory units...
a0e327f84b5a9edf1f9d5fb222e78f3281a31712
3,612,024
from typing import MutableMapping from typing import Any def include_filter( include: MutableMapping[Any, Any], target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]: """Filters target by tree structure in include. Args: include: Dict of keys from target to include. An empty dict matches all ...
f1c10ec383a430700d8e7f58e8c9f6bc5180c844
3,612,025
def _local_pca(pca, args): """Create the local PCA object """ local_pca = PCA(pca, api=args.retrieve_api_) kwargs = {} if args.max_components: kwargs.update({"max_components": args.max_components}) if args.variance_threshold: kwargs.update({"variance_threshold": args.variance_th...
ea272dcd6b1fe4fbe2d94d9deee2244ffaeb8b42
3,612,026
def create_app(config_name): """ Creates Flask instance & initialize Came from 'Use Application Factory' : http://slides.skien.cc/flask-hacks-and-best-practices/#7 :rtype: Flask """ app_ = Flask(__name__) app_.config.from_pyfile(config_name) cors.init_app(app_) jwt.init_app(app_) ...
b5c9aed6edc675d91b60df4d094634dabb932276
3,612,027
def cv(model): """ A function to perform cross-validation on a model. """ (x_train, y_train), _ = get_metadata() cv_score = cross_validate(model, x_train, y_train, cv=5, scoring="neg_mean_squared_error", return_estimator=True, return_train...
dc63f429195c1570bf23f24f6b21fe6a6929b565
3,612,028
def analyze_data(fitsfn, observables_dir="", affine2d=None, psf_offset_find_rotation = (0.0,0.0), psf_offset_ff = None, rotsearch_d=None, set_pistons=None): """ returns: affine2d (measured or input), ...
af0d32932e5cb433c36efc5ae985057bcfb51654
3,612,029
def _get_pb_likelihood(likelihood): """Convert protobuf Likelihood integer value to Likelihood enum. :type likelihood: int :param likelihood: Protobuf integer representing ``Likelihood``. :rtype: :class:`~google.cloud.vision.likelihood.Likelihood` :returns: Enum ``Likelihood`` converted from proto...
bef00bc3dbf5e31fa0f25241bce32a8b6d61b367
3,612,030
def eval_loss(original, latent, decoder, loss_func=bce_loss): """ Example of a native Keras / Tensorflow function to be used with pca_tests """ return loss_func(original, decoder.predict(latent)).numpy()
9a476197bb20cbae933f3180134401a54a52b3de
3,612,031
from corehq.apps.locations.models import SQLLocation from corehq.apps.locations.views import EditLocationView def get_object_info(obj, cache=None): """ This function is intended to behave just like get_doc_info, only you call it with objects other than Couch docs (such as objects that use the Django O...
f1d80208cc9202f8c6db9fcd3e276c016bc213e8
3,612,033
def wave_bases(mother, k, scale, param=-1): """Computes the wavelet function as a function of Fourier frequency used for the CWT in Fourier space (Torrence and Compo, 1998) Arguments --------- mother: str equal to 'MORLET' or 'DOG' to choose the wavelet type k: vector of the Fourier...
aa4cb68e7d555cf8960e3d5db65fe31afb32977a
3,612,034
from typing import Type def _nptype_to_taco_type(ty: np.dtype) -> DType: """Returns the TACO type for the given numpy type.""" nptype_to_dtype = { np.int8: Type.INT8, np.int16: Type.INT16, np.int32: Type.INT32, np.int64: Type.INT64, np.float32: Type.FLOAT32, np.float64: Type.FL...
b77cda21c8b73edb988796cfd395e38047a30493
3,612,038
def search_images(request): """Function for Image searching/sourcing""" if 'image' in request.GET and request.GET['image']: search_term = request.GET.get('image') searched_images =Image.search_by_name(search_term) message = f'{search_term}' return render(request, 'search.html',...
01847fdc97647c5ba949fdbd8ed723c3a548da31
3,612,039
import struct def readRem(byteStream): """The rem - remark/comment type tokens""" commentLength = struct.unpack('bb', byteStream.read(2))[1] bytesRead = 2 comment = struct.unpack('%ds' % commentLength, byteStream.read(commentLength))[0].rstrip("\x00") bytesRead += commentLength return bytesRea...
31782ce3a8aa10b306066bd4dc388c62392cc11b
3,612,040
def linKK(f, Z, c=0.85, max_M=50, fit_type="real", add_cap=False): """A method for implementing the Lin-KK test for validating linearity [1] Parameters ---------- f: np.ndarray measured frequencies Z: np.ndarray of complex numbers measured impedances c: np.float cutoff f...
87b7ee6bdb2281117ced6826e6bc10455202e09d
3,612,041
def ERR_USERSDISABLED(sender, receipient, message): """ Error Code 446 """ return "ERROR from <" + sender + ">: " + message
2da8df2a4fd8cdb41840ca5d0929721af1354829
3,612,042
def get_route_name(route): """Returns route name.""" # split once, take last peice name = route.split("/", 1)[-1] return name
3d5c916711a7631d4eb90c5eff6f1f745c97a664
3,612,043
def singlecore(known_face_encodings, names, face_query): """ single core is impl to compare faces on one core """ tolerance, similarity_metric = configs.face_similarity_threshold, configs.metric if similarity_metric == 'euclidean': name= singlecore_euclidean(known_face_encodings, names, face...
0e3b6b0d6cd006a29052ce372793a485d5c29f39
3,612,045
def poisciPristanisce(pristanisce): """Vrne podatke o pristanišču na podlagi njegovega imena.""" cur.execute(""" SELECT id, pristanisce FROM Pristanisce WHERE pristanisce LIKE ?""", (pristanisce,)) return cur.fetchone()
b49399725fcff4ba382ba9784a1ff81aed1b859e
3,612,046
import scipy def showfreq(signal,fs,fc=0,db=False): """ return f,fft """ if fc==0: kc = int(len(signal)/2) else: kc = int(len(signal)/fs*fc) signal_fft = np.abs(scipy.fftpack.fft(signal)) f = np.linspace(0,fs/2,num=int(len(signal_fft)/2)) out_f = f[:kc] out_fft =...
29d423aa459ca64bbe910d549aa7a118f903ebb7
3,612,047
def make_input_split(filename, offset, length): """ Build a fake (i.e., not tied to a real file) :class:`~pydoop.pipes.InputSplit`\ . This is used for testing. :type filename: string :param filename: file name :type offset: int :param offset: byte offset of the split with respect to the beginning of ...
d7d49d23cff1d70f5870847a90c2409f0c7d5202
3,612,048
from typing import Sequence from typing import List from typing import Dict from typing import Any def get_info(devices: Sequence[custom_types.Device]) -> List[Dict[str, Any]]: """Returns persistent info and firmware version for each device.""" info = [] for device in devices: props = {} for device_prop...
4a464bc24e9e53b48091e62a73cf10e705006bdc
3,612,049
def get_policy_profile_by_uuid(db_session, profile_id): """ Retrieve policy profile by its UUID. :param db_session: database session :param profile_id: string representing the UUID of the policy profile :returns: policy profile object """ with db_session.begin(subtransactions=True): ...
665f7599182f982bbd6369d780218d26861b192c
3,612,050
from typing import Optional from typing import Union from typing import Literal def recall_score(y_true: np.ndarray, y_pred: np.ndarray, *, labels: Optional[np.ndarray] = None, pos_label: Union[str, int] = 1, average: Optional[Literal['micro', 'macro', 'samples', 'weighted', ...
9b22c84c0fd725dfc48541d45054eae05ffb6316
3,612,051
def evaluateIndcostt(individual, verbose=False): """ This function should take an individual,possibly an instance of Candidate class, and return a tuple where each element of the tuple is an objective. An example objective would be (error,circuitLen) where: error = |1 - < createdState | wantedStat...
2e98aa09acf81d3d8f83c3e189560fc5fbf62fb7
3,612,052
def weibull_cdf(): """ Generates a figure and table for the Weibull CDF data in the paper. """ exact = 2.4, 1.6, 0.8 t = np.array([ 1.202, 1.397, 1.537, 1.57, 1.768, 1.856, 1.87, 1.889, 1.918, 2.098, 2.212, 2.349, 2.453, 2.557, 2.596, 2.602, 2.678, 2.706, 3.089, 3.441 ]) F =...
df174f0b75458f31d7d6e71a1faef20d1cf4831a
3,612,053
def runFunction(func, pargs=None, kwargs=None, msg=DEFAULT_MSG): """ Runs the function, catching errors, and writing a message. :param Function func: :param list pargs: postional arguments :param dict kwargs: keyword arguments """ if pargs is None: pargs = [] if kwargs is None: kwargs = {}...
7d038ab3c20c06fa14cff4c689275b3c821c19ca
3,612,054
from sage.misc.prandom import randint from sage.homology.examples import simplicial_complexes def random_simplicial_complex(level=1, p=0.5): """ Return a random simplicial complex. :param level: measure of complexity: the larger this is, the more vertices and therefore the larger the possible dimen...
207b671d20b08f6f3bfc0bcb85b0e3426bfadd88
3,612,055
from aioredis.client import Redis def from_url(url, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ return Redis.from_url(url, **kwargs)
d7941027fd7b171fe5ab00d330df55b97e2e6205
3,612,056
import requests def get_remote_version(url: str) -> str: """Gets the remote file and returns it as a long string.""" response = requests.get(url) if response: #print("Getting remote version") s = response.text return s else: return "Url Not Found."
5d5ef45c5b74b326f9386214229529d9b71aca3d
3,612,057
def mesh_renderer(vertices, triangles, normals, diffuse_colors, camera_position, camera_lookat, camera_up, light_positions, light_intensities, image_width, ...
a1d83fe66b0f2e647c49840777a9fbb9ed6e49c7
3,612,058
from typing import Any def _is_optional(anno: Any) -> bool: """Is the supplied annotation an instance of the 'virtual' Optional type? Optional isn't really a type. It's an alias to Union[T, NoneType] """ return ( is_union(anno) and NoneType in anno.__args__ )
2e5225aadd48ab81b971b139d4984fab8985ca1f
3,612,059
def single_number_hashtable(nums: list[int]) -> int: """Returns the only element in `nums` that appears exactly once Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of integers s.t. every element appears twice, except for one Returns: the only elemen...
f15b06d4f4683b9604e8b5ab6f2fe9be588551a6
3,612,060
def mse_from_logits_bm(output_logits, target_logits): """Computes MSE between predictions associated with logits. Args: output_logits: A tensor of logits from the primary model. target_logits: A tensor of logits from the secondary model. Returns: The mean MSE """ alphas = t...
42634d83f7bea7d8525c29127b77d2982e68bebb
3,612,061
def get_data(input_path): """ Reading passage retrieval results into a dataframe. Parameters ---------- input_path : str Path to file containing passage retrieval results. Returns ------- data : DataFrame DataFrame containing passage retrieval results. ...
c9581d6259ee6d96b47736a316a5472f23dce80e
3,612,062
def metadata(datasets): """ Extract datasette metadata from a CLDF dataset. """ def iter_table_config(cldf): for table in cldf.tables: try: name = cldf.get_tabletype(table) except (KeyError, ValueError): name = None name = name ...
f4927cea1a5587a417e98453cd7df7bf2f75d507
3,612,063
def chunk_bboxes(shape, chunks, overlap): """Calculates the bounding box coordinates for each overlapped chunk Parameters ---------- shape : tuple overall shape chunks : tuple tuple containing the shape of each chunk overlap : int int indicating number of voxels to overl...
c4a526242390be6d395c02189a8641c96cb3ac4c
3,612,064
def DCT1e(x): """ This can act as a forward or backward transform. We use it simply as a transform. This is a very similar definition to wikipedia but with scaling 2. https://www.researchgate.net/publication/3343693_Convolution_Using_Discrete_Sine_and_Cosine_Transforms DCT1 of the input signal x...
a6d0e0099d38c20fdc2c1f2d3e702f4618b7cc76
3,612,065
from davitpy.models import igrf def get_igrf(lons,lats,alts,ephtimes): """ Highly visible getter method for acquiring Earth's magnetic field values for the provided ndarray of longitudes/latitudes/altitudes/times. Uses the IGRF model """ itype = 1 #Geodetic coordinates stp = 1. ifl ...
88a34f5eb531b1103999ebda8a37aedb912d0a85
3,612,066
def dcg_score_at_k(ground_truth, predictions, k=5, pos_label=1): """ Function to evaluate the Discounted Cumulative Gain @ k for a given ground truth vector and a list of predictions (between 0 and 1). Args: ground_truth : np.array consisting of multi-hot encoding of label ...
230a605daf6cce70d9ef97521485ae3cf83c9c65
3,612,067
def index(): """Show all the posts, most recent first.""" posts = HubPost.query\ .join(HubPost.post_content)\ .join(HubPost.effectivity)\ .join(HubPost.author)\ .filter(text("sat_post_effectivity.post_status = 'Active'")) return render_template("blog/index.html", posts=posts)
5ec84195039bc689b0bf2acd86bf8ed788e3b408
3,612,068
def parse_card(card: str) -> tuple: """Separates the card into value and suit. Args: card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds). Returns: tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D'). """ if le...
de9051906327dfcf01a3b2076acbed216ce43ced
3,612,070
def plot_po(one_survey): """Plot a diagram of PO (Porakonekairaus) with matplotlib. Parameters ---------- one_survey : hole object Returns ------- figure : matplotlib figure """ df = pd.DataFrame(one_survey.survey.data) if "Soil type" in df.columns: # pylint: disable=unsupport...
0c75f642c803501b617c396d0f6cc6330c40a051
3,612,073
import requests def http_get_with_headers(url, h=False): """ executes regular HTTP GET request to url returns response body and headers """ global hd if h: hd = h resp = requests.get(url, headers=hd, allow_redirects=False) return (resp.content, resp.headers)
f5d1177b4cb281b350c0843319b311e3febdec93
3,612,075
def analysis_create(): """ Renders analysis creation page """ return flask.render_template('analysis_creation.tpl')
be8d605e8d7138b000f30c7215c466e26dafb58d
3,612,076
def create_test_engine(): """ Returns an SQLAlchemy Engine, configured for testing. :return: an SQLAlchemy Engine, configured for testing. """ engine = use_database_file(":memory:") return engine
13836447262429bba539558093fb0e45d697dd05
3,612,077
def _reformat_policy(policy): """ Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name and the reformatted policy...
4eb5372e233d53e6949a90833350831542c5bd01
3,612,078
import codecs def get_line(file_path, line_rule): """ 搜索指定文件的指定行到指定行的内容 :param file_path: 指定文件 :param line_rule: 指定行规则 :return: """ s_line = int(line_rule.split(',')[0]) e_line = int(line_rule.split(',')[1]) result = [] # with open(file_path) as file: file = codecs.open(f...
fdad31f037aa4311fb46e99623a0de0496209b2c
3,612,080
def strip_all_unbalanced_parens(s): """ Return a string where unbalanced parenthesis are replaced with a space. Strips (), <>, [] and {}. """ c = strip_unbalanced_parens(s, '()') c = strip_unbalanced_parens(c, '<>') c = strip_unbalanced_parens(c, '[]') c = strip_unbalanced_parens(c, '{}'...
7d748f79ac19866650aeadc7cf34d8859707e656
3,612,081
from typing import Optional def test_module(client: Client, first_fetch_time: Optional[int]) -> str: """ Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. :type client: ``Client`` :param client: Darktrace Client :type firs...
e2c9e6acf922e765ac1da494b42ed3606da2bfe7
3,612,082