content
stringlengths
22
815k
id
int64
0
4.91M
def _name_to_agent_class(name: str): """ Convert agent name to class. This adds "Agent" to the end of the name and uppercases the first letter and the first letter appearing after each underscore (underscores are removed). :param name: name of agent, e.g. local_human :return: ...
65,200
def bin_search_recursive(array, what_to_find, left=0, right=None): """ Finds element in a sorted array using recursion. :param list array: A sorted list of values. :param what_to_find: An item to find. :returns: Index of the searchable item or -1 if not found. """ right = right if right is...
65,201
def extensions_to_glob_patterns(extensions: List) -> List[str]: """Generate a list of glob patterns from a list of extensions. """ patterns: List[str] = [] for ext in extensions: pattern = ext.replace(".", "*.") patterns.append(pattern) return patterns
65,202
def is_classvar(t): """ >>> is_classvar(typing.ClassVar[int]) True >>> is_classvar(int) False """ return is_from_typing_module(t) and str(t).startswith("typing.ClassVar[")
65,203
def get_reduced_powers(values: Tuple, power: int) -> Tuple[Expr, Symbol]: """ For a variable v only taking finitely many values v**n can be written as linear combinations of powers < |values|. This function computes this linear combination. The values ought be passed as a sorted tuple to enable caching ...
65,204
def detect_cross_pnt(arr, thr, way='up', gap=1): """ detect the data rise/down point, returns the index of the point right above the threshold. arguments: - arr: data array (1d) - thr: threshold (scale) key arguments: - way: either be "up" or "down", for data rise/ data down respective...
65,205
def check_resource(drink_ingredients): """Checks whether the ingredients in the machine enough to make the drink""" for items in resources: if drink_ingredients[items] > resources[items]: print(f"Sorry there's not enough {items}!") return False return True
65,206
def _as_pairs( x: Union[ Tuple[Union[Tuple[int, int], int], ...], int, List[Tuple[Union[int, numpy.int64], Union[int, numpy.int64]]], ], ndim: int, as_index: bool, ): """ usage.skimage: 6 """ ...
65,207
def handler(event, context): """ https://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html """ print(event, context) publisher.handle(event, context) return {}
65,208
def extract_image( inputs: Union[jnp.ndarray, Mapping[str, jnp.ndarray]] ) -> jnp.ndarray: """Extracts a tensor with key `image` or `x_image` if it is a dict, otherwise returns the inputs.""" if isinstance(inputs, dict): if "image" in inputs: return inputs["image"] else: return inputs["x_ima...
65,209
def drop_duplicate_cols(df: pd.DataFrame) -> pd.DataFrame: """Remove duplicated colulms from a df # https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns/40435354#40435354 Args: df (pd.DataFrame): df with duplicated column names Returns: pd.DataFrame: df ...
65,210
def find_sources(indegrees: dict) -> deque: """Find sources (nodes that have 0 inbound edges). Args: indegrees (dict): A dictionary where the key is a graph node \ and the value is the number of inbound edges. Returns: deque: A deque containing source nodes. """ sources = d...
65,211
def stretch_audio(x, rate, window_size=512): """Stretch the audio speech using spectrogram. Args: x (numpy.ndarray): Input waveform. rate (float): Rate of stretching. window_size (int, optional): Window size for stft. Defaults to 512. Returns: numpy.ndarray: The stretched a...
65,212
async def email_subscribe_confirm(token, hood=Depends(get_hood_unauthorized)): """Confirm a new subscriber and add them to the database. :param token: encrypted JSON token, holds the email of the subscriber. :param hood: Hood the Email bot belongs to. :return: Returns status code 200 after adding the s...
65,213
def main(): """Co-plot the same variable from multiple files, save as file or display the figure.""" parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument('-p', '--pattern', type=str, required=True, help='Pattern, passed to glob.glob that would match the desi...
65,214
def test_duplicate_ipv6_prefix_records_are_from_same_region(deduplicated_ipv6_prefixes): """Verify duplicate records for a prefix are from the same Region. A single prefix should not be advertised from multiple Regions. """ test = True for prefix, records in deduplicated_ipv6_prefixes.items(): ...
65,215
def pairing_gen(email_addresses): """This function generates the final pairings and outputs an alphabetically sorted pandas dataframe with all elements in both columns """ pairing_1 = [] pairing_2 = [] for first_member, second_member in grouper(email_addresses, 2, SUBSTITUTE): pairing_...
65,216
def test_render_response_header_minimal(testrenderer): """Path response's 'header' minimal definition is rendered.""" markup = textify( testrenderer.render_response( 200, {"description": "An evidence.", "headers": {"X-Request-Id": {}}}, ) ) assert markup == textwrap.dedent( ...
65,217
def plot_all_modes(pastis_modes, out_dir, design, fname_suffix='', save=False): """ Plot all PATIS modes onto a grid. :param pastis_modes: array, PASTIS modes [seg, mode] in nm :param out_dir: str, output path to save the figure to if save=True :param design: str, "small", "medium", or "large" LUVOI...
65,218
def get_joint_loss(data_dict, device, config, weights, detection=True, caption=True, reference=True, use_lang_classifier=True, num_ground_epoch=50): """ Loss functions Args: data_dict: dict config: dataset config instance reference: flag (False/True) Returns: loss: pytor...
65,219
def specr_model(fn, a,b,c1,c2,d,e): """ Description: ------------ Theoretical model for spectral ratio. Preferred model is determined by the values of d & e and they are user-defined. Input: ----------------- fn --> freqeuncy bins a --> fc main event b --> fc egf ...
65,220
def get_operation_id_groups(expression): """Takes an operator expression from an .mmcif transformation dict, and works out what transformation IDs it is referring to. For example, (1,2,3) becomes [[1, 2, 3]], (1-3)(8-11,17) becomes [[1, 2, 3], [8, 9, 10, 11, 17]], and so on. :param str expression: ...
65,221
def is_plus(char: Optional[str]) -> bool: """Check if character is a plus symbol.""" return char == PLUS
65,222
def mrt_alert_msg(mrt_line, direction, stations, public_bus, mrt_shuttle, mrt_shuttle_dir): """ Message that will be sent if there is an MRT alert/breakdown/delay :param mrt_line: "DTL/NSL/EWL..." :param direction: "Both"/specific MRT station name("Jurong East") :param stations: "NS17, NS16, NS15, N...
65,223
def _check_nco_binaries(config): """Check to see if necessary NCO binaries are available.""" ncodir = config["s2smetric"]["ncodir"] nco_bins = ["ncks", "ncrename"] for nco_bin in nco_bins: path = f"{ncodir}/{nco_bin}" if not os.path.exists(path): print(f"[ERR] Cannot find {pa...
65,224
def oncall_now_print(oc_users, now_user): """Print user doing the on-call now.""" user_name = oc_users[now_user['user']]['name'] user_phone = oc_users[now_user['user']]['phone'] print("On-call now:") print("{}, {}.".format(user_name, user_phone)) print("From {}, until {}".format( now_us...
65,225
def normalize(contentData): """ The primary normalization and de-obfuscation function. Runs various checks and changes as necessary. Args: contentData: Script content Returns: contentData: Normalized / De-Obfuscated content """ # Passes modificationFlag to each function to det...
65,226
def testParseResults_always_yieldsValidVulnerabilities(): """Test proper parsing of Zap JSON output.""" with (pathlib.Path(__file__).parent / 'zap-test-output.json').open('r', encoding='utf-8') as o: results = json.load(o) vulnz = list(result_parser.parse_results(results)) assert len(vul...
65,227
def convert_to_progressive_jpeg(image_field): """Swap an image_field content in memory before hitting file system. TODO: Finish implementing this; currently not working """ img = PIL.Image.open(BytesIO(image_field.read())) output = BytesIO() # New memory buffer try: img.save(output,...
65,228
def clusters_tournament(ptree, labels): """A cluster 'wins' if some node inside the cluster is the ascendant of another node in the other cluster""" L = np.max(labels) + 1 T = np.zeros((L, L), dtype=int) for i, m in enumerate(ptree.match): li = labels[i] if li != -1: for ...
65,229
def _load_quebec(start_date=datetime(2020, 1, 1), end_date=datetime.today(), verbose=True): """ Parameters: - `start_date` datetime object, the date of the earliest news release to be retrieved. By default, only the releases published before Jan 1 2020 are retrieved - `end_date` ...
65,230
def batch_to_model_inputs(batch, aux, prog, diag, forcing, constants): """Prepare batch for input into model This function reshapes the inputs from (batch, time, feat) to (time, z, x, y) and includes the constants """ batch = merge(batch, constants) def redim(val, num): if num == 1: ...
65,231
def is_envvar(buff, pos): """:return: start, end, pos or None, None, None tuple.""" try: while buff[pos] in ' \t': pos += 1 start = pos while True: if buff[pos] in '\0"\'()- \t\n': return None, None, None if buff[pos] == '=': ...
65,232
def application(): """Create an application.""" return flaked.Application()
65,233
def urlscraper(url: str, pattern: str, regex:bool=False) -> list: """urlscraper is a simple method to scrape information from a url based on a given string pattern :param url: the url to run pattern against :param pattern: the string representation of the pattern :param regex: flag for using a pattern ...
65,234
def load_model(filename): """ Return a model stored within a file. This routine is for specialized model descriptions not defined by script. If the filename does not contain a model of the appropriate type (e.g., because the extension is incorrect), then return None. No need to load pickles o...
65,235
def climb_stairs(stairs): # """You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example: Input: 2 Output: 2 3 1 1 1 1 2 2 1 """ ...
65,236
def measure_nearest_neighbor_performance(accuracy_label, encoder, family_accessions, batch_size, train_samples, shuffle_seed, sample_random_state): """Measures nearest neighbor classification p...
65,237
def make_safe(s): """Replaces all spaces with '\\ '""" return replaceAll(s, " ", "\\ ")
65,238
def gradient_descent(w0, optimizer, regularizer=None, opts=dict()): """ Mini-Batch Stochastic Gradient descent algorithm. w0: is the initial guess loss_function: is the loss function you want to optimize. It should have the gradient and loss method. opts: a dictionary with the algorithm parameters ...
65,239
def parse_xml_file(filename): """Returns a dictionary with the class_id, genus, species, bg_species.""" def strip_tag(s): return s.split('>', 1)[1].split('<', 1)[0] mapping = {"ClassId": "class_id", "Genus": "genus", "Species": "species", "BackgroundSpec...
65,240
def remove(event, dest): """Enleve le destinataire d'un évènement""" assert isinstance(event, (str, unicode)) assert event[:5] == "event" global events if event in events.keys(): if dest in events[event]: events[event].remove(dest) if not events[event]: ...
65,241
def _validate_timestamp_keys(input_json): """Ensure the timestamp_format_key values in input_json's log_configs entries are valid.""" valid_keys = set() for config in (input_json, _read_log_configs()): valid_keys |= set(config.get("timestamp_formats").keys()) for log_config in input_json.get("lo...
65,242
def autodetect_version(libdirs): """ Detect the current version of HDF5, and return X.Y.Z version string. Intended for Unix-ish platforms (Linux, OS X, BSD). Does not support Windows. Raises an exception if anything goes wrong. config: configuration for the build (configure command) """ im...
65,243
def compute_aggregation_axes(dims, axes=None, keepdims=False): """Computes parameters for an aggregation-over-axes operation. Args: dims ([int or Value]): The dimensions of the value being aggregated. axes ([int], optional): Defaults to None. The indices of the axes to aggregate over. k...
65,244
def dataNormalize(data, maxAudio_total ,maxVisual_total ): """ :param data: the avData, size is (*,288,360) :return: the normalized avData, size is (*,288,360) normalize method: (x-min_local)/(max_total-min_local) """ data_nor = np.zeros(data.shape) for i in range(6): audiodata = dat...
65,245
def run_ip_traffic_monitor(db_connection, net_interfaces, device_id, agent_ip): """ Function monitors IP traffic in real time using Scapy's sniff function. If an exception occurres it will run again in 5 seconds. Arguments: - db_connection: sqlite3 database connection. - net_interfaces: A list of provided ...
65,246
def test_interpreter(): """ Basic set of visiting nodes """ interpreter = Interpreter() cmd = next(Parser(Lexer(Scanner("1 + 2\n")))) assert interpreter.visit(cmd) == 3 cmd = next(Parser(Lexer(Scanner("1 * 2\n")))) assert interpreter.visit(cmd) == 2 cmd = next(Parser(Lexer(Scanner...
65,247
def is_rfc1918(ip_str): """Returns True if the IP is private. If the IP isn't a valid IPv4 address this function will raise a :class:`ValidationError`. """ private_networks = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"] try: ip_str_network = ipaddr.IPv4Network(ip_str) except ipaddr....
65,248
def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=1000, ...
65,249
def call_ellipse(onegal, galaxy, galaxydir, pixscale=0.262, nproc=1, filesuffix='custom', bands=['g', 'r', 'z'], refband='r', input_ellipse=None, sky_tests=False, unwise=False, verbose=False, clobber=False, debug=False, logfile=None): """Wrapper on...
65,250
def start_the_sink_communications_process(): """ Creates a Sink object for a sink process (i.e. initialises the worker_exec process and keeps the zmq communication between the worker_exec and the forwarder) :return: The SinkCom object """ push_port, receiving_topics, _, parameters_top...
65,251
def optionsSymbols( symbol="", expiration="", includeExpired=None, token="", version="stable", filter="", format="json", ): """This call returns an object keyed by symbol with the value of each symbol being an array of available contract dates. https://iexcloud.io/docs/api/#options-...
65,252
def text_word_wrap(text, width): """ Word-wrap a string to width `width`. """ return textwrap.wrap(text, width)
65,253
def test_create(): """Test getting a created test role""" role, user, keypair = helper.role.create() assert isinstance(role, protobuf.role_state_pb2.RoleAttributes) assert isinstance(user, protobuf.user_state_pb2.User) assert isinstance(role.role_id, str) assert isinstance(role.name, str) as...
65,254
def aggregate_metrics(parent_dir, metrics): """Aggregate the metrics of all experiments in folder `parent_dir`. Assumes that `parent_dir` contains multiple experiments, with their results stored in `parent_dir/subdir/metrics_dev.json` Args: parent_dir: (string) path to directory containing ...
65,255
def acceptStdin(in_f, out_f, addr=None): """ Create a command source with the given fds as input and output. """ # Force new versions to be loaded. # # deep_reload(Hub) nubID = g.nubIDs.gimme() otherIP, otherPort = in_f.getpeername() try: otherFQDN = socket.getfqdn(otherIP) ex...
65,256
def inspect_coefs(lm, X) -> Union[pd.Series, pd.DataFrame]: """ View a summary of a linear model's coefficients. Works for both linear and logistic regression models. >>> import pydataset >>> iris = pydataset.data('iris') >>> X, y = iris[['Sepal.Length', 'Sepal.Width']], iris.Species >>> l...
65,257
def clean_census_data(df): """ Clean up the census data results from the API. By default, the census data often includes non-numeric characters as annotations or missing values. # see https://www.census.gov/data/developers/data-sets/acs-5year/data-notes.html # for estimate and annotation values ...
65,258
def move(): """ Called when the Battlesnake Engine needs to know your next my_move. The data parameter will contain information about the board. Your response must include your my_move of up, down, left, or right. """ start = timer() # my_moves delta = [[-1, 0], # go up [0...
65,259
def find_detection_probability(Mc, eta, redshifts, distances, n_redshifts_detection, n_binaries, snr_grid_at_1Mpc, detection_probability_from_snr, Mc_step=0.1, eta_step=0.01, snr_step=0.1): """ Compute the detection probability given a grid of SNRs and detection probabilities...
65,260
def maybe_value(tree: dict, *path_components: str): """ Get the value corresponding to last key in the key path ``[k1, k2, ..]`` on the input dictionary tree. The key sequence may match an actual key path or match it up to a point or not match any path at all. If a key ``k[n]`` in the input sequence...
65,261
def load_datasets(arg_space, use_embds, batchSize, kmer_len=None, embd_size=None, embd_window=None): """ Loads and processes the data. """ input_prefix = arg_space.inputprefix output_dir = 'results/'+arg_space.directory if not os.path.exists(output_dir): os.makedirs(output_dir) #save...
65,262
def CompoundIsDrugCheck(db,cids_data=None,fin=None,fout=sys.stdout,verbose=0): """ Determine whether input CIDs link to any SIDs which are flagged is_drug. Output in_db, is_drug and drug SID[s]. """ if fin: cids_data={} while True: line=fin.readline() if not line: break cid=int(line) ...
65,263
def add_all_EM_inferred_labels(dbcon): """Expectation-Maximization based method for ground truth inference from multi-observer datasets, as proposed by Dawid and Skene in 1979. Maximum Likelihood Estimation of Observer Error-Rates Using the EM Algorithm # noqa Author(s): A. P. Dawid and A. M. Skene ...
65,264
def response_json_ok(json): """Creates a tuple representing the HTTP package to respond the requisition with the given JSON on its body and status code 200 :param json: object to be sent on HTTP body :return response: tuple representing the HTTP response package """ return _make_json_respons...
65,265
def build_k_indices(y, k_fold, seed=1): """build k indices for k-fold.""" num_row = y.shape[0] interval = int(num_row / k_fold) np.random.seed(seed) indices = np.random.permutation(num_row) k_indices = [indices[k * interval: (k + 1) * interval] for k in range(k_fold)] return...
65,266
def init_model(args, num_classes): """Initialise model""" architecture = getattr(models, args.model) if args.curve is None: model = architecture.base(num_classes=num_classes, **architecture.kwargs) else: curve = getattr(curves, args.curve) model...
65,267
def get_LoiterType_str(str): """ Returns a numerical value from a string """ if str == "VehicleDefault": return LoiterType.VehicleDefault if str == "Circular": return LoiterType.Circular if str == "Racetrack": return LoiterType.Racetrack if str == "FigureEight": return LoiterType.FigureEight...
65,268
def load_tour(fname): """ Reads a tour from a JSON file. Input: - fname : filename Output: - tour : loaded tour """ with open(fname, 'r') as fp: return json.load(fp)
65,269
def get_lhn_accordion(driver, object_name): """Select relevant section in LHN and return relevant section accordion.""" selenium_utils.open_url(url.Urls().dashboard) lhn_menu = dashboard.Header(driver).open_lhn_menu() # if object button not visible, open this section first if object_name in cache.LHN_SECTION_...
65,270
def modular_sqrt_composite(c, factors): """ Calculates modular square root of composite value for given all modulus factors For a = b^2 mod p*q*r*m... calculates b :param c: residue :param factors: list of modulus prime factors :return: all potential root values """ n = multiply(factors)...
65,271
def trim_zeros(x): """It's common to have tensors larger than the available data and pad with zeros. This function removes rows that are all zeros. x: [rows, columns]. """ pre_shape = x.shape assert len(x.shape) == 2, x.shape new_x = x[~np.all(x == 0, axis=1)] post_shape = new_x.shape ...
65,272
def save_project(context): """Save project with path from *context*.""" import hiero.core project = hiero.core.newProject() try: project.saveAs(context.path) except RuntimeError: # thrown if operation is cancelled by user. return
65,273
def build_opener(apiurl, user, password, cookie_path, debuglevel=0, capath=None, cafile=None, headers=()): """build urllib opener for given name/password it creates * HTTPSHandler with proper ssl context * HTTPCookieProcessor with a link to cookiejar * HTTPBasicAuthHandler with user/passw...
65,274
def show_user(username): """Some Comment""" return 'Welcome: %s' % username
65,275
def unfold_rep_seq(rep_seq: str) -> str: """Unfold the rep_seq string.""" unfolded = "" matches = rep_seq_pat.findall(rep_seq) for m in matches: unfolded += m[0] * int(m[1]) + m[2] return unfolded
65,276
def main(): """ Main function for creating gdb """ try: # Prints message to screen arcpy.AddMessage("....Creating HTML index") create_index.create_index(GDB_DATABASE_OUTPUT_PATH, adm.ADM_DIC_LIST, cad.CAD_DIC_LIST, cli.CLI_DIC_LIST, ...
65,277
def get_cost(ss, a, dist_mat, C, n): """Determines the cost of an airline route network from a sampleset. Args: - ss: Sampleset dictionary. One solution returned from the hybrid solver. - a: Float in [0.0, 1.0]. Discount allowed for hub-hub legs. - dist_mat: Numpy matrix providing dista...
65,278
def get_python_code(paths): """ Returns all Python code, as a list of tuples, each one being: (filename, list of lines) """ retval = [] for p in paths: if not os.path.isdir(p): raise Exception("'%s' is not a directory." % p) for (dirpath, dirnames, filenames) in os.w...
65,279
def get_epsilon_interpolator( eps, t_break, eps2=-1, t_delta_phases=-1, transition_time=14, t_break_final=None, eps_final=None ): """ Return an interpolator that produces an epsilon when called with a time (relative to the model start). The solution has at least 3 steps (4 if t_break_final and eps_final...
65,280
async def test_last_scheduled_write_wins_array(dut): """ Test that the last scheduled write for an *arrayed* signal handle is the value that is written. """ dut.array_7_downto_4.value = [1, 2, 3, 4] dut.array_7_downto_4[7].value = 10 await ReadOnly() assert dut.array_7_downto_4.value == [1...
65,281
def get_cqt_index(pitch, hparams): """Get row closest to this pitch in a CQT spectrogram""" frequencies = librosa.cqt_frequencies(constants.TIMBRE_SPEC_BANDS, fmin=librosa.midi_to_hz(constants.MIN_TIMBRE_PITCH), bins_per_octave=...
65,282
def save_file_in_minio(csv_file, shop_key): """ creates a file in the minio stores 'productstore' bucket :param shop_key: A string that is used to specify a shop :param csv_file: A object that is an instance of CsvFile :return: """ with Span(span_name='save_file_in_minio', trace_context=trac...
65,283
def mdtf_copy_banner(mdtf_path,wk_dir): """Copy the banner image.""" banner_src = Path(mdtf_path)/"src"/"html"/"mdtf_diag_banner.png" banner_dst = wk_dir.parents[0]/"mdtf_diag_banner.png" if not banner_dst.exists(): print("Copying MDTF banner image.") shutil.copy2(str(banner_src),str(ban...
65,284
def add_comments() -> None: """Add text to every line of every file in directory tree""" root = Path(".") for path_object in root.glob('**/*'): if path_object.is_file(): if str(path_object).endswith(".py") and not str(path_object).startswith("dev"): with open(path_object,...
65,285
def suite(): """Suite of test to run""" glome_tests = unittest.TestLoader().loadTestsFromModule(test.glome_test) autoglome_tests = unittest.TestLoader().loadTestsFromModule( test.autoglome_test) fuzzing_tests = unittest.TestLoader().loadTestsFromModule(test.fuzzing_test) return unittest.Tes...
65,286
def kde_2d(df, w, x, y, xmin=None, xmax=None, ymin=None, ymax=None, numx=50, numy=50): """ Calculates a 2 dimensional histogram from a Dataframe and weights. For example, a results distribution might be obtained from the history class and plotted as follows:: df, w = history.get_dis...
65,287
def test_len_gets_number_of_sources_in_filled_cache(filled_cache): """Test that len gets the number of sources in the cache.""" assert len(filled_cache) == 3
65,288
def slugify(value): """ Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. """ value = ( unicodedata.normalize('NFKD', value) .encode('ascii', 'ignore') .decode('a...
65,289
def hexpass(pwd): """Convert no alpha numeric characters in a password string to hexadecimal Args: pwd(str): The password as a string Returns: The converted string Examples >>> print(hexpass('matter')) 'matter' >>> print(hexpass('m@tt3r')) "m%40tt3r' """ ...
65,290
def _irfft2(karr, rarr, progress_callback=None): """ Inverse 2d real-to-complex FFT with callback that allows to report status of the computation to user. Parameters ---------- karr : array_like Fourier-space representation rarr : array_like Real-space representation pro...
65,291
def main(): """Make a jazz noise here""" args = get_args() sort = args.sort min_frequency = args.min files = args.positional words = [] for file in files: for char in file.read().split(): words.append(char) clean_words = [] for word in words: clean_words...
65,292
def get_best_align_elem(tensor_size, tensor_dtype): """Get the best tiling factor for alignment axis.""" basic_align_elem = int(ct_util.BLOCK_SIZE / get_bytes(tensor_dtype)) lcm = least_common_multiple(tensor_size, basic_align_elem) gcd = greatest_common_divisor(tensor_size, basic_align_elem) if gcd...
65,293
def backend_from_string(backendstring, backendopts=None): """ creates (a)sync backends from strings returns tuple (boolean,backend) where boolean specifies whether this is a syncbackend (True) or asyncbackend (False) """ backendopts = backendopts or {} ctor_kwargs = os.environ.get("PACKT...
65,294
def mock_requests(): """Return a new mock request instanse.""" yield MockedRequests()
65,295
def callAPI(verb, endpoint, body="", quiet=False): """ General purpose function for all API calls. Parameters: verb standard hypertext: GET POST etc endpoint substring to be added to base URL body the payload containing a list of dictionary objects. It is converted to JSON be...
65,296
def addFreqWeightsToCatalog(imageDict, photFilter, diagnosticsDir): """Add relative weighting by frequency for each object in the optimal catalog, extracted from the data cube saved under diagnosticsDir (this is made by makeSZMap in RealSpaceMatchedFilter). This is needed for multi-frequency cluster findin...
65,297
def new_spline(Tend, n_parts, targetvalues, tag, bv=None, use_std_approach=True): """ :param Tend: :param n_parts: :param targetvalues: pair of arrays or callable :param tag: :param bv: None or dict of boundary values (like {0: [0, 7], 1: [0, 0]}) :return: Spli...
65,298
def copy(string, **kwargs): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate( string.encode("utf-8")) except OSError as why: raise XcodeNotFound return
65,299