content
stringlengths
22
815k
id
int64
0
4.91M
def test_bst_balance_method_on_really_left_balanced_tree(empty_tree): """Test balance method returns correct balance on really left tree.""" for i in range(21, 1, -1): empty_tree.insert(i) assert empty_tree.balance() == 19
5,297,100
def _next_tick(): """ Proceed to the next tick, publicizing data of the new tick via the api (the new states). """ # save the new general info global _MATRX_info, _next_tick_info, __states _MATRX_info = copy.copy(_next_tick_info) _next_tick_info = {} # print("Next ticK:", _MATRX_info); ...
5,297,101
def main(args): """Run the command line program.""" word_counts = Counter() for fname in args.infiles: with open(fname, 'r') as reader: update_counts(reader, word_counts) util.collection_to_csv(word_counts, num=args.num)
5,297,102
def dump_files_for_page(volume_barcode, redacted, alto_xml_output, original_alto, page, unredacted_storage, redacted_storage): """ For debugging when an alto file fails to match during assert_reversability. """ path = page['path'][:-3] dump_text(path, unredacted_storage.contents(path)) if re...
5,297,103
def xmlvalue(self, value): """Patch for xmlvalue""" if value.startswith(FILETAG): return value return b64encode(value)
5,297,104
def can_write(path): """Test ability to write a file in 'path'. Assume the path is a temporary directory, so don't bother cleaning up. """ if not path.exists(): _log.debug(f"can_write: Creating parent directory '{path}'") try: path.mkdir() except Exception as err: ...
5,297,105
def test_sigma_dut_sae_password(dev, apdev): """sigma_dut controlled SAE association and long password""" if "SAE" not in dev[0].get_capability("auth_alg"): raise HwsimSkip("SAE not supported") ifname = dev[0].ifname sigma = start_sigma_dut(ifname) try: ssid = "test-sae" pa...
5,297,106
def loop_2_f_twice(n): """Run loop calling empty function twice per loop, n times.""" for i in range(n): f() f()
5,297,107
def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, ...
5,297,108
def print_device_info(nodemap): """ This function prints the device information of the camera from the transport layer; please see NodeMapInfo example for more in-depth comments on printing device information from the nodemap. :param nodemap: Transport layer device nodemap. :type nodemap: INode...
5,297,109
def compute_roc_from_sparse_glm_smpls(data, x_smpls): """ Compute the ROC curve given samples from a sparse weighted model We can estimate p(A_{k,k'} | data) from our samples """ # Compute the inferred connectivity matrix p_A = np.zeros_like(x_smpls[0]['net']['graph']['A']) for smpl in x_smp...
5,297,110
def submit_number(number): """Add a number or decimal to the display""" # Insert the number or decimal pressed to the end of the display display.insert(END, number) # If decimal was pressed, disable the decimal button so it cannot be pressed twice if "." in display.get(): decimal_button.con...
5,297,111
def column_check(lst): """ Function check's whether columns have right numbers, according to the given rows >>> column_check(['***', ' * 1', '123', '111']) False """ var1 = rebuilding(lst) var2 = number_row_check(var1) if var2 is True: return True return False
5,297,112
def accuracy(W, x, t): """computes the accuracy of the model with the weights W (shape (dim_phi, N_classes)) for a test set x (shape (N_examples, dim_x)) and t (shape (N_examples, K_classes)). """ phi = features(x) y = activity(W, phi) correct = np.equal(np.argmax(y, axis=1), np.argmax(t, axis=...
5,297,113
def group2(): """group 2""" pass
5,297,114
def plot_gottselig(n, datatype='calcs'): """ plot gottselig normalization for all channels Parameters ---------- datatype: str (default: 'calcs') which data to plot [options: 'calcs', 'normed_pwr'] """ exclude = ['EKG', 'EOG_L', 'EOG_R'] eeg_chans = [x for ...
5,297,115
def find_val_in_lid_shotlog(shotno): """ seigyo.lid_shotlog から対応するショット番号のlidデータを取得する。 LID計算機とのファイル共有の問題が解決されないままとなっているため、現状ではデータを取得できない。 しばらく舟場データを使用する)2013.10.21 Parameters ---------- shotno : int shot number Returns ------- dict """ vals = {} db = get_conn...
5,297,116
def init(specfile: str = "configs/dlrs.yaml") -> None: """initializer, read in specification file and assign to variable spec. >>> init() >>> print(spec["version"]) 0.6.0 """ global spec yaml = YAML() specfile = os.path.join(os.path.dirname(os.path.realpath(__file__)),specfile) with ...
5,297,117
def _add_outgoing_edges( graph: Graph[V], u: V, mst: Graph[V], heap: FibonacciHeap[V] ) -> None: """ Given a node, updates the priorities of adjacent nodes by following its edges. """ for v, e in graph[u].items(): if v in mst: continue if v not in heap: heap.e...
5,297,118
def SB_oxy_eq(coef,oxyvolts,pressure,temp,dvdt,os,cc=[1.92634e-4,-4.64803e-2]): """ Oxygen (ml/l) = Soc * (V + Voffset) * (1.0 + A * T + B * T^2 + C * T^3 ) * OxSol(T,S) * exp(E * P / K) Original equation from calib sheet dated 2014: coef[0] = Soc coef[1] = Voffset coef[2] = A coef[3] = B ...
5,297,119
def make_pipeline_short(pipeline_type): """Make a short pipeline.""" pipeline = pipeline_type( ChunkedStreamLink(), EventLink(), ) assert isinstance(pipeline.bottom, ChunkedStreamLink) assert isinstance(pipeline.top, EventLink) return pipeline
5,297,120
def mixIn (base, addition): """ Mixes in place, i.e. the base class is modified. Tags the class with a list of names of mixed members. @param base : the base class @param addition : additional classes """ assert not hasattr(base, '_mixed_') mixed = [] for item, val in addition.__dict__.items(): i...
5,297,121
def find_best_weight(w_path: str, best: str = "min", ext: str = ".hdf5", epoch_identifier: int = None): """Given weights in w_path, find the best weight. if epoch_identifier is given, it will be given priority to find best_weights The file_names are supposed in following format FileName_Epoch_Error.ext ...
5,297,122
def monkeyed_consul_boom(full_path, json): """boom on monkeypatch for the put to consul""" raise requests.ConnectionError("monkey-boom")
5,297,123
def get_task_by_user_id(): """ { "page": "Long", "size": "Long", "user_id": "Long" } """ domain = request.args.to_dict() return task_service.get_task_by_user_id(domain)
5,297,124
def unescape_html(chatbot, statement): """ Convert escaped html characters into unescaped html characters. For example: "&lt;b&gt;" becomes "<b>". """ import sys # Replace HTML escape characters if sys.version_info[0] < 3: from HTMLParser import HTMLParser html = HTMLParser(...
5,297,125
def return_suffix(kind=kind,index=index,dimkeys=dimkeys,copula_string=None,marginal_string = None,marginal_data=None,segment_marginal=None): """ :return: a coherent string that permits to give a suffix in the name of our files. """ if kind == 'diagonal': diago = diag(len(dimkeys)) res =...
5,297,126
def collect_metrics(manager: 'TxMiningManager') -> MetricData: """Collect data from TxMiningManager.""" return MetricData( miners_count=len(manager.miners), total_hashrate_ghs=manager.get_total_hashrate_ghs(), txs_solved=manager.txs_solved, txs_timeout=manager.txs_timeout, ...
5,297,127
def normalize_response(response, request=None): """ Given a response, normalize it to the internal Response class. This also involves normalizing the associated request object. """ if isinstance(response, Response): return response if request is not None and not isinstance(request, Requ...
5,297,128
def _get_user(): """Get the user object or create it based on the token in the session If there is no access token abort with 401 message """ if 'Access-Token' not in request.headers: abort(401, message='Access Denied!') token = request.headers['Access-Token'] user_data = github.get('u...
5,297,129
def get_notifications_by_type(user_id: int, notification_type: NotificationType, unread_only: bool = False) -> typing.List[Notification]: """ Get all (unread) notifications of a given type for a given user. :param user_id: the ID of an existing user :param notification_type: the type of notification to...
5,297,130
def test_model(args): """ main function for testing param args: global arguments return: None """ print(args) if args.cuda: print("=====> use gpu id: '{}'".format(args.gpus)) os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus if not torch.cuda.is_available(): ...
5,297,131
def get_processing_unit_config(unit_config): """Returns the :class:`.ProcessingUnitConfig` corresponding to *unit_config*""" if isinstance(unit_config, ProcessingUnitConfig): return unit_config elif isinstance(unit_config, dict): unit_name = unit_config["unit_name"] processin...
5,297,132
def partscore_pairs(part,score=S): """Scores the partition for student groupings accoring to the provided score class, by performing the groupscore function for every group in the partition returns: a number (lower scores mean the partition is more novel) """ ss = 0 for group in part: s...
5,297,133
def get_gedi02_b_beam_as_gdf(input_file, gedi_beam_name, valid_only=True, out_epsg_code=4326): """ A function which gets a geopandas dataframe for a beam. Note the parameters with multiple values in the z axis are not included in the dataframe. :param input_file: input file path. :param gedi_beam_n...
5,297,134
def save_tag(n_clicks_timestamp, input_values): """Saves the corresponding tag from the input field to the tag list. Ideally, we would like to use the MATCH function to determine which button was clicked. However, since we only have one save tag toast for all the tags, we can't use MATCH in the Output fiel...
5,297,135
def upgrade(options=None, fatal=False, dist=False): """Upgrade all packages.""" if options is None: options = ['--option=Dpkg::Options::=--force-confold'] cmd = ['apt-get', '--assume-yes'] cmd.extend(options) if dist: cmd.append('dist-upgrade') else: cmd.append('upgrade'...
5,297,136
def test_create_unique_asset_type() -> None: """Create unique asset type wih desired ID.""" asset_type = AssetType(asset_type_id="12345") assert asset_type.asset_type_id == "12345" assert asset_type.type == "Unique"
5,297,137
def maybe_print_as_json(opts, data, page_info=None): """Maybe print data as JSON.""" if opts.output not in ("json", "pretty_json"): return False root = {"data": data} if page_info is not None and page_info.is_valid: meta = root["meta"] = {} meta["pagination"] = page_info.as_dic...
5,297,138
def float_like(x, /) -> bool: """ Tests if an object could be converted to a float. Args: x (Any): object to test Returns: bool: Whether the object can be converted to a float. """ try: float(x) return True except ValueError: return False
5,297,139
def open_file(path): """ Opens a given file. Returns an error if the current file type is not supported. """ try: file = mediafile.MediaFile(path) return { 'success': True, 'file': file } except mediafile.UnreadableFileError: return { 'error': 'the given file could not be rea...
5,297,140
def schur_comp(M,idx_set): """ computes the schur complement/the pieces of the schur complement for a matrix M """ comp_idx = [i for i in range(len(M)) if i not in idx_set] A = M[np.ix_(idx_set,idx_set)] B = M[np.ix_(idx_set,comp_idx)] C = M[np.ix_(comp_idx,idx_set)] D = M[np.ix_(comp_id...
5,297,141
def noise_db(a, snr): """ Takes an array of seismic amplitudes and SNR in dB. Args: a (ndarray): seismic amplitude array. snr (int): signal to noise ratio. Returns: Noise array, the same shape as the input. Note: it does *not* return the input array with the noise added. ...
5,297,142
def get_structure_numbers(structure, momenta_dict): """Return the number of the parent and children of a given structure according to some momenta dictionary. """ legs = structure.get_all_legs() children = frozenset((leg.n for leg in legs)) if structure.name() == "S": return None, child...
5,297,143
def purchase_number(request): """Purchases a new phone number using the Twilio API""" form = PurchaseNumberForm(request.POST) if form.is_valid(): # Purchase the phone number phone_number = form.cleaned_data['phone_number'] twilio_number = purchase_phone_number(phone_number.as_e164) ...
5,297,144
def oneshot_behavior(behaviour, name=None): """ This is taken from py_trees.idiom.oneshot. However, we use a different clearing policy to work around some issues for setting up StartConditions of OpenSCENARIO """ if not name: name = behaviour.name variable_name = get_py_tree_path(beh...
5,297,145
def font_render_multiline(font, text, antialias, color, background=None, justify='left', line_spacing=0): """ Returns a Surface containing the text in the given font. The first five parameters are the ones used to render single line text. justify can be 'left', 'right', or 'center'. line_spacing is how...
5,297,146
def get_artella_project_url(project_id, files_url=True): """ Returns Artella project URL :param project_id: str, Unique ID for the Artella project :param files_url: bool, Whether to return root project URL of project files URL :return: str """ raise RuntimeError('get_artella_project_url fun...
5,297,147
def user_conversion(): """ Best pipeline: GaussianNB(ExtraTreesClassifier(XGBClassifier(input_matrix, learning_rate=0.001, max_depth=10, min_child_weight=10, n_estimators=100, n_jobs=1, subsample=0.7500000000000001, verbosity=0), bootstrap=True, criterion=entropy, max_features=0.55, min_samples_leaf=10, min_sam...
5,297,148
def get_files_names_from_dir(directory: str, ext: str) -> List[str]: """Return list of file's names with extension `ext` from `directory`.""" files_names = [ file_name for file_name in listdir(directory) if file_name.endswith(ext) ] files_names.sort() return files_names
5,297,149
def cache(ctx, directory, verbosity): """Cache a local copy of catalogue""" click.echo('Caching WIS 1.0 Catalogue') _ = cache_catalogue(directory) click.echo('Done')
5,297,150
def check_bin(number, index): """ 用于某些二进制标志位的场景 返回一个 int 类型变量的某一二进制位的值,index 从 1 开始,即 >>> check_bin(2, 1) 0 >>> check_bin(2, 2) 1 """ try: return int(bin(number)[2:][-index]) except IndexError: return 0
5,297,151
def init(state): """Init app.""" app = state.app # Register services - cannot be done in extension because # Invenio-Records-Resources might not have been initialized. registry = app.extensions["invenio-records-resources"].registry ext = app.extensions["invenio-records-marc21"] registry.regi...
5,297,152
def run_command(cmd): """Run a command in a sub-process. Returns the exit status code and the combined stdout and stderr. """ if env.PY2 and isinstance(cmd, unicode): cmd = cmd.encode(sys.getfilesystemencoding()) # In some strange cases (PyPy3 in a virtualenv!?) the stdout encoding of ...
5,297,153
def parse_exclusion_file(exclusion_file, exclusion_column): """ Reads in the specified column of the specified file into a set. """ exclusion_list = set() with open(exclusion_file) as infile: for line in infile: to_exclude = line.split('\t')[exclusion_column] exclus...
5,297,154
def __parse_config__(config_file_path): """ Parses the config file and sets the globals. """ global ENVIRONMENT_VARIABLES global DEPLOYMENT_PATHS global DEPLOYMENT_STRUCTURES global BUILD_FOLDER_REGEX global IGNORE_JOBS global SPLIT_TOKEN global PREPEND_STRING global APPEND_S...
5,297,155
def unstack(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/unstack . """ return tensorflow.unstack(*args, **kwargs)
5,297,156
def test_trim_eviction(cache_mode, cache_line_size, filesystem, cleaning): """ title: Test verifying if trim requests do not cause eviction on CAS device. description: | When trim requests enabled and files are being added and removed from CAS device, there is no eviction (no rea...
5,297,157
def map_operations_and_unroll( circuit: CIRCUIT_TYPE, map_func: Callable[[ops.Operation, int], ops.OP_TREE], *, deep: bool = False, raise_if_add_qubits=True, tags_to_ignore: Sequence[Hashable] = (), ) -> CIRCUIT_TYPE: """Applies local transformations via `cirq.map_operations` & unrolls inter...
5,297,158
def main(project_dir): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('Downloading nltk resources') nltk.download('punkt') nltk.download('averaged_percep...
5,297,159
def min_sum_space_improved(arr): """ A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array. Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0 Correct problem descri...
5,297,160
def full_extraction(url): """ Runs a complete end-to-end extraction using all other functions. :param url: The url to extract the HTML from :return: An object that contain the HTML from the article """ full_html = get_html(url) pattern_extraction = pattern_article_extraction(url) retur...
5,297,161
def auth_enabled(controller): """Decorator for if an auth plugin is enabled""" @wraps(controller) def wrapper(request, *args, **kwargs): if not mgg.app.auth: messages.add_message( request, messages.WARNING, _('Sorry, authentication is disab...
5,297,162
def encode_token_tx(token_tx: Dict) -> bytes: """ Creates bytes representation of token transaction data. args: token_tx: Dictionary containing the token transaction data. returns: Bytes to be saved as token value in DB. """ token_tx_str = '' token_tx_str += token_tx['token...
5,297,163
def from_base32(number): """Convert a BASE32 representation of an AIC to a BASE10 one.""" number = compact(number) if not all(x in _base32_alphabet for x in number): raise InvalidFormat() s = sum(_base32_alphabet.index(n) * 32 ** i for i, n in enumerate(reversed(number))) return ...
5,297,164
def fatal(msg): """ Print a fatal error @param msg: The message """ print("FATAL:", msg)
5,297,165
def distance(strand_a, strand_b): """ Compare two strings and count the differences. :param strand_a string - String representing a strand of DNA. :param strand_b string - String representing a different strand of DNA. :return int - number of differences between 2 strands. """ if len(stran...
5,297,166
def unzscore(im_norm, zscore_median, zscore_iqr): """ Revert z-score normalization applied during preprocessing. Necessary before computing SSIM :param im_norm: Normalized image for un-zscore :param zscore_median: Image median :param zscore_iqr: Image interquartile range :return im: image a...
5,297,167
def republish(producer, message, exchange=None, routing_key=None, remove_props=['application_headers', 'content_type', 'content_encoding', 'headers']): """Republish message.""" body = ensure_bytes(message.bod...
5,297,168
def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array ...
5,297,169
def parse_command_line(): """ Parse command line. It uses argparse to parse thoraxe' command line arguments and returns the argparse parser. """ parser = argparse.ArgumentParser( prog="thoraxe", description=""" thoraxe is a tool to identify orthologous exonic regions (s-...
5,297,170
def set_artist(track_title, track_genre, track_location, track_artist,language): """ Function to set only artist details Returns boolean True if set else False gets invoked in the get song function """ try: if(Check_artist(track_artist)): pass else: collection = db.collection(u'artist').document(track_...
5,297,171
def get_latest_status_from_database(session: Session) -> Status: """Get latest status from database""" latest_status = get_latest_status(session) # convert to PyDantic object latest_status = Status.from_orm(latest_status) return latest_status
5,297,172
def values_to_rgb(ranges, values): """ Converts a three dimensional tuple to a RGB map @param ranges The mininum and maximum of each dimension @param values The value to transform """ r_color = (float(values[0]) - float(ranges[0][0])) / float(ranges[0][1]) g_color = (float(values[1]) - float(ran...
5,297,173
def requires_auth(f): """ Decoretorn to check user auth """ @wraps(f) def decorated(*args, **kwargs): """ Check user auth """ auth = request.authorization if not auth or not check_auth(auth.username, auth.password): raise Unauthorized('Could not verify your access level f...
5,297,174
def test_hypercontractivity_coefficient_tensorization(dist1, dist2): """ Test tensorization: hc(X X' : Y Y') = max(hc(X:Y), hc(X', Y')) """ import dit dit.ditParams['repr.print'] = True mixed = dist1.__matmul__(dist2) hc_mixed = hypercontractivity_coefficient(mixed, [[0, 2], [1, 3]])...
5,297,175
def algorithm_m_clean(n): """ Knuth's Algorithm M for permutation generation, cleaned up to remove duplicate rotations. This generates the rotations: constructs a map of each sequence to its captain. """ sequence_to_captain = {} captains = set() for perm in algorithm_m(n): ...
5,297,176
def alfred_data_prep(root_path, info_prefix, out_dir, workers): """Prepare the info file for alfred dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): N...
5,297,177
def test_get_private_fields(mongo_client): """Return the private fields for the class""" assert Dragon.get_private_fields() == {'breed'}
5,297,178
def _archive_url_parser( header, url, latest_version=__version__, instance=None, response=None ): """Returns the archive after parsing it from the response header. Parameters ---------- header : str The response header of WayBack Machine's Save API url : str The input url, the ...
5,297,179
def fasta_records(filepath): """Count the number of records in a FASTA file.""" count = 0 next_pos = 0 angle_bracket = bytes(">", "utf-8") memory_map = TrimmableMemoryMap(filepath, access=mmap.ACCESS_READ) with memory_map.map() as mem_map: size = memory_map.size next_pos = mem_ma...
5,297,180
def cifar_iid(dataset, num_users): """ Sample I.I.D. client data from CIFAR10 dataset :param dataset: :param num_users: :return: dict of image index """ num_items = int(len(dataset) / num_users) dict_users, all_idxs = {}, [i for i in range(len(dataset))] for i in range(num_users): dict_users[i] = ...
5,297,181
def get_area_filter(point_cloud, extents): """ Args: point_cloud: (3, N) point cloud extents: 3D area in the form [[min_x, max_x], [min_y, max_y], [min_z, max_z]] Returns: """ if not isinstance(point_cloud, np.ndarray) and isinstance(extents, np.ndarray): raise TypeError('...
5,297,182
def meat2segment(meat): """Convert into a list of points.""" asos = load_geodf("sfstns") tokens = meat.split() sz = len(tokens) i = 0 pts = [] gc = "geometry" while i < sz: token = tokens[i] if token.isdigit() and (i + 2) < sz: miles = float(token) ...
5,297,183
def ensure_shape(x, y): """Util to broadcast on var to another but only when shape is different. This way we don't convert scalar into array type unnecessarily. """ shape_y = np.shape(y) if np.shape(x) == shape_y: return x return np.broadcast_to(x, shape_y)
5,297,184
def sweepTeamQorCL(team, ccteambr, stream, options=None): """ Takes all task branches in the holding bin for a team and sweep them to the QOR bin. Create bin if it doesn't yet exist. """ sfb = SFTeamBranchTool() origteam = team team = sfb.devTeamToScmTeam(team) if team is None: ...
5,297,185
def get_property(name,*args): """Convenience function to quickly retrieve any stellar property/properties for a given KepID/KOI numbers Parameters ---------- name : int, float or str, or array_like KOI or KIC name (or array of names) *args : string, properties to return (must...
5,297,186
def print_helptext(): """ print helptext for command-line interface """ pout("usage: %s [flags] [tasks]\n" " Execute tasks in order. if no tasks are specified, tries to\n" " execute task 'default'\n" " flags:\n" " -w / --watch watch files/folders for change...
5,297,187
def property_immutable_cache(f): """ This cache should only be used on properties that return an immutable object """ @wraps(f) def inner(self): if f.__name__ not in self.cache: self.cache[f.__name__] = f(self) return self.cache[f.__name__] return property(inner)
5,297,188
def normalize(vec): """normalizes an Nd list of vectors or a single vector to unit length. The vector is **not** changed in place. For zero-length vectors, the result will be np.nan. :param numpy.array vec: an Nd array with the final dimension being vectors :: numpy.array...
5,297,189
def lam(m, f, w): """Compute lambda""" s = 0 for i in range(len(f)): s += f[i] * w[i] return float(m)/float(s)
5,297,190
def is_old_file(filename, max_days=0, max_seconds=3600, verbose=True): """Returns true if the file modification date > max_days / max_seconds ago or if the file does not exist""" if os.path.isfile(filename) is not True: return True st = os.stat(filename) mtime = st.st_mtime now = datetim...
5,297,191
def _get_binary_xentropy(target_values, forecast_probabilities): """Computes binary cross-entropy. This function satisfies the requirements for `cost_function` in the input to `run_permutation_test`. E = number of examples :param: target_values: length-E numpy array of target values (integer clas...
5,297,192
def delete(program, project, submission_client, types=DEFAULT_TYPES, batch_size=DEFAULT_BATCH_SIZE, drop_project=DEFAULT_DROP_PROJECT): """Delete all content from project.""" delete_all(submission_client, program, project, types=types, batch_size=batch_size) try: if drop_project: print(s...
5,297,193
def _check_for_collision(sprite1: Sprite, sprite2: Sprite) -> bool: """ Check for collision between two sprites. :param Sprite sprite1: Sprite 1 :param Sprite sprite2: Sprite 2 :returns: Boolean """ collision_radius_sum = sprite1.collision_radius + sprite2.collision_radius diff_x = sp...
5,297,194
def get_value(lst, row_name, idx): """ :param lst: data list, each entry is another list with whitespace separated data :param row_name: name of the row to find data :param idx: numeric index of desired value :return: value """ val = None for l in lst: if not l: conti...
5,297,195
def in_domain(X, a_array, c_array): """ Check is a given point is inside or outside the design domain """ flag = 1 for n in range(numpy.shape(a_array)[0]): a = a_array[n] c = c_array[n] dist = numpy.dot(X-c,a) if(dist > 0.7): flag = 0 if(abs(dist)<0.7): flag = 2 return flag
5,297,196
def generate_script(job): """ Generates a script from a job. """ work_dir = job.path json_data = hjson.loads(job.json_text) # The base url to the site. url_base = f'{settings.PROTOCOL}://{settings.SITE_DOMAIN}{settings.HTTP_PORT}' # Extra context added to the script. runtime = dict...
5,297,197
def test_query_label_4(): """Test query with more than one --label""" import json import os import os.path import osxphotos from osxphotos.cli import query runner = CliRunner() cwd = os.getcwd() result = runner.invoke( query, [ "--json", "--d...
5,297,198
def metadata(ts, capture_block_id, report_path, run, st=None): """Create a dictionary with required metadata. Parameters ---------- ts : : class:`katsdptelstate.TelescopeState` telescope state capture_block_id : int capture_block_id report_path : string path where report...
5,297,199