content
stringlengths
22
815k
id
int64
0
4.91M
def rubi_integrate(expr, var, showsteps=False): """ Rule based algorithm for integration. Integrates the expression by applying transformation rules to the expression. Returns `Integrate` if an expression cannot be integrated. Parameters ========== expr : integrand expression var : var...
19,400
def daily_price_read(sheet_name): """ 读取股票名称和股票代码 :param sheet_name: :return: """ sql = "SELECT * FROM public.%s limit 50000" % sheet_name resultdf = pd.read_sql(sql, engine_postgre) resultdf['trade_date'] = resultdf['trade_date'].apply(lambda x: x.strftime('%Y-%m-%d')) resultdf['cod...
19,401
def EWT_Boundaries_Completion(boundaries,NT): """ ====================================================================== boundaries=EWT_Boundaries_Completion(boundaries,NT) This function permits to complete the boundaries vector to get a total of NT boundaries by equally splitting the last b...
19,402
def _isfloat(string): """ Checks if a string can be converted into a float. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a float. """ try: float(string) return True except ValueError...
19,403
def get(url, **kwargs): """ get json data from API :param url: :param kwargs: :return: """ try: result = _get(url, **kwargs) except (rq.ConnectionError, rq.ReadTimeout): result = {} return result
19,404
def sample_indep(p, N, T, D): """Simulate an independent sampling mask.""" obs_ind = np.full((N, T, D), -1) for n in range(N): for t in range(T): pi = np.random.binomial(n=1, p=p, size=D) ind = np.where(pi == 1)[0] count = ind.shape[0] obs_ind[n, t, :c...
19,405
def _relabel_targets(y, s, ranks, n_relabels): """Compute relabelled targets based on predicted ranks.""" demote_ranks = set(sorted(ranks[(s == 0) & (y == 1)])[:n_relabels]) promote_ranks = set(sorted(ranks[(s == 1) & (y == 0)])[-n_relabels:]) return np.array([ _relabel(_y, _s, _r, promote_ranks...
19,406
def exp(x): """Take exponetial of input x. Parameters ---------- x : Expr Input argument. Returns ------- y : Expr The result. """ return call_pure_intrin(x.dtype, "exp", x)
19,407
def check_table(words_in_block, block_width, num_lines_in_block): """ Check if a block is a block of tables or of text.""" # average_words_per_line=24 # total_num_words = 0 ratio_threshold = 0.50 actual_num_chars = 0 all_char_ws = [] cas = [] # total_num_words += len(line) if num_li...
19,408
def upload_data( client, crypto_symbol, utc_timestamp, open_price, highest_price, lowest_price, closing_price, volume ): """composes json that will store all necessary data into a point, then writes it into database""" json_body = [ ...
19,409
def defaultSampleFunction(xy1, xy2): """ The sample function compares how similar two curves are. If they are exactly the same it will return a value of zero. The default function returns the average error between each sample point in two arrays of x/y points, xy1 and xy2. Parameters -...
19,410
def makesubs(formula,intervals,values=None,variables=None,numden=False): """Generates a new formula which satisfies this condition: for all positive variables new formula is nonnegative iff for all variables in corresponding intervals old formula is nonnegative. >>> newproof() >>> makesubs('1-x^2','[0,1]') Substi...
19,411
def generateKey(accountSwitchKey=None,keytype=None): """ Generate Key""" genKeyEndpoint = '/config-media-live/v2/msl-origin/generate-key' if accountSwitchKey: params = {'accountSwitchKey': accountSwitchKey} params["type"] = keytype key = prdHttpCaller.getResult(genKeyEndpoint, params...
19,412
def positions_count_for_one_ballot_item_doc_view(request): """ Show documentation about positionsCountForOneBallotItem """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values( url_root) templ...
19,413
def compare_maxima(input_im, gtruth_im, min_distance=10, threshold_abs=20): """Compares image maxima Compare that the maxima found in an image matches the maxima found in a ground truth image. This function is a wrapper around `skimage.feature.peak_local_max()`. It calls this function on both images th...
19,414
def atcab_sign_base(mode, key_id, signature): """ Executes the Sign command, which generates a signature using the ECDSA algorithm. Args: mode Mode determines what the source of the message to be signed (int) key_id Private key slot used to sign the message. (int) ...
19,415
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn: """ Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - Plot saved under given f...
19,416
def load_gs( gs_path: str, src_species: str = None, dst_species: str = None, to_intersect: List[str] = None, ) -> dict: """Load the gene set file (.gs file). Parameters ---------- gs_path : str Path to the gene set file with the following two columns, separated by tab: ...
19,417
def create_and_send(ip, port, address, msg): """Create a client and send a message""" osc = OSCClient(ip, port) osc.send_message(address, msg)
19,418
def sample_surface_even(mesh, count, radius=None): """ Sample the surface of a mesh, returning samples which are VERY approximately evenly spaced. This is accomplished by sampling and then rejecting pairs that are too close together. Parameters --------- mesh : trimesh.Trimesh G...
19,419
def allocate_probabilities(results, num_substations, probabilities): """ Allocate cumulative probabilities. Parameters ---------- results : list of dicts All iterations generated in the simulation function. num_substations : list The number of electricity substation nodes we wis...
19,420
def import_one_record_sv01(r, m): """Import one ODK Site Visit 0.1 record into WAStD. Arguments r The record as dict, e.g. { "instanceID": "uuid:cc7224d7-f40f-4368-a937-1eb655e0203a", "observation_start_time": "2017-03-08T07:10:43.378Z", "reporter": "florianm", "photo_s...
19,421
def assert_array_almost_equal(x: numpy.ndarray, y: List[List[float]], decimal: int): """ usage.scipy: 5 usage.sklearn: 4 """ ...
19,422
def delete_page_groups(request_ctx, group_id, url, **request_kwargs): """ Delete a wiki page :param request_ctx: The request context :type request_ctx: :class:RequestContext :param group_id: (required) ID :type group_id: string :param url: (required) ID :type url...
19,423
def envset(name): """Return True if the given environment variable is set An environment variable is considered set if it is assigned to a value other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive) """ return os.environ.get(name, 'no').lower() not in ['no', 'n', ...
19,424
def init_email_templates(): """初始化邮件模板""" from app.modules.email_templates.models import EmailTemplate template = '<p>{{ message | safe }}</p><a href="{{ url }}" target="_blank">点击访问</a>' for name in ["default", "confirm", "reset-password"]: EmailTemplate.create(name=name, template=template)
19,425
def GLM(args): """ %prog GLM GenoPrefix Pheno Outdir RUN automated GEMMA General Linear Model """ p = OptionParser(GLM.__doc__) p.set_slurm_opts(jn=True) opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) GenoPrefix, Pheno, Outdir = args ...
19,426
def solver(f, p_e, mesh, degree=1): """ Solving the Darcy flow equation on a unit square media with pressure boundary conditions. """ # Creating mesh and defining function space V = FunctionSpace(mesh, 'P', degree) # Defining Dirichlet boundary p_L = Constant(1.0) def boundary_L(x, on...
19,427
def set_stretchmatrix(coefX=1.0, coefY=1.0): """Stretching matrix Args: coefX: coefY:coefficients (float) for the matrix [coefX 0 0 coefY] Returns: strectching_matrix: matrix """ return np.array([[coefX, 0],[0, coefY]])
19,428
def double_click(self, br): """ demo: # double click on every spacer to expand column width for spc in br.select('table.ms-crm-List-Header span.ms-crm-List-Row-header-spacer'): spc.double_click(br) """ ActionChains(br).double_click(self).perform()
19,429
def _test(): """Run an example using the Crystal Maze problem.""" constraints = Constraints() domain = VariableDomain.from_range(domain_count=8, domain_start=1, domain_end=8, alpha_name...
19,430
def fixjsstyle(files=0): """ Fix js files using fixjsstyle to comply with Google coding style """ files = files.split(" ") if not files == 0 else list_js_files() for file in files: with settings(hide("warnings", "running"), warn_only=True): output = local("fixjsstyle --strict --...
19,431
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the...
19,432
def test_credentials() -> (str, str): """ Read ~/.synapseConfig and retrieve test username and password :return: endpoint, username and api_key """ config = _get_config() return config.get(DEFAULT_CONFIG_AUTH_SECTION, DEFAULT_CONFIG_USERNAME_OPT),\ config.get(DEFAULT_CONFIG_AUTH_SECT...
19,433
def BCA_formula_from_str(BCA_str): """ Get chemical formula string from BCA string Args: BCA_str: BCA ratio string (e.g. 'B3C1A1') """ if len(BCA_str)==6 and BCA_str[:3]=='BCA': # format: BCAxyz. suitable for single-digit integer x,y,z funits = BCA_str[-3:] else: ...
19,434
def get_strongly_connected_components(graph): """ Get strongly connected components for a directed graph The returned list of components is in reverse topological order, i.e., such that the nodes in the first component have no dependencies on other components. """ nodes = list(graph.keys())...
19,435
def dot(a, b): """ Computes a @ b, for a, b of the same rank (both 2 or both 3). If the rank is 2, then the innermost dimension of `a` must match the outermost dimension of `b`. If the rank is 3, the first dimension of `a` and `b` must be equal and the function computes a batch matmul. Sup...
19,436
def unreshuffle_2d(x, i0, shape): """Undo the reshuffle_2d operation.""" x_flat = unreshuffle_1d(x, i0) x_rev = np.reshape(x_flat, shape) x_rev[1::2, :] = x_rev[1::2, ::-1] # reverse all odd rows return x_rev
19,437
def findNodeJustBefore(target, nodes): """ Find the node in C{nodes} which appeared immediately before C{target} in the input document. @type target: L{twisted.web.microdom.Element} @type nodes: C{list} of L{twisted.web.microdom.Element} @return: An element from C{nodes} """ result = No...
19,438
def _format_line(submission, position, rank_change, total_hours): """ Formats info about a single post on the front page for logging/messaging. A single post will look like this: Rank Change Duration Score Flair Id User Slug 13. +1 10h 188 [Episode](gkvlja) <AutoLovepon> <...
19,439
def help_menu_message(): """Display the help menu options.""" print('\nPlease enter the number for the item you would like help on:\n') print('1: <TBC>') print('2: <TBC>') print('3: <TBC>') print('4: <TBC>') print('5: Exit Help Menu')
19,440
def train_net(network, rfcn_network, imdb, roidb, valroidb, output_dir, tb_dir, pretrained_model=None, max_iters=40000): """Train a Fast R-CNN network.""" roidb = filter_roidb(roidb) valroidb = filter_roidb(valroidb) tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gp...
19,441
def describe_import_tasks(filters=None, maxResults=None, nextToken=None): """ Returns an array of import tasks for your account, including status information, times, IDs, the Amazon S3 Object URL for the import file, and more. See also: AWS API Documentation Exceptions :example: response =...
19,442
def prime_divisors(number: int) -> Iterable[int]: """ Returns the prime divisors of the number (sorted in ascending order). E.g. prime_divisors(20) -> 2, 2, 5 """ for divisor in chain([2], count(3, step=2)): while number % divisor == 0: yield(divisor) number //= divisor ...
19,443
def run_erasure( # pylint: disable = too-many-arguments privacy_request: PrivacyRequest, policy: Policy, graph: DatasetGraph, connection_configs: List[ConnectionConfig], identity: Dict[str, Any], access_request_data: Dict[str, List[Row]], ) -> Dict[str, int]: """Run an erasure request""" ...
19,444
def write_module_scripts(folder, platform=sys.platform, blog_list=None, default_engine_paths=None, command=None): """ Writes a couple of scripts which allow a user to be faster on some tasks or to easily get information about the module. @param folder wher...
19,445
def _set_stop_area_locality(connection): """ Add locality info based on stops contained within the stop areas. """ # Find stop areas with associated locality codes with connection.begin(): query_stop_areas = connection.execute( db.select([ models.StopArea.code.label("code...
19,446
def RichTextBuffer_FindHandlerByName(*args, **kwargs): """RichTextBuffer_FindHandlerByName(String name) -> RichTextFileHandler""" return _richtext.RichTextBuffer_FindHandlerByName(*args, **kwargs)
19,447
def likelihood(tec, phase, tec_conversion, lik_sigma, K = 2): """ Get the likelihood of the tec given phase data and lik_var variance. tec: tensor B, 1 phase: tensor B, Nf tec_conversion: tensor Nf lik_sigma: tensor B, 1 (Nf) Returns: log_prob: tensor (B,1) """ mu = wrap(tec*tec_...
19,448
def angle_between(v1, v2): """Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ # https://stackoverflow.co...
19,449
def create_substrate_bulk(wf_dict_node): """ Calcfunction to create a bulk structure of a substrate. :params wf_dict: AiiDA dict node with at least keys lattice, host_symbol and latticeconstant (If they are not there, raises KeyError) Lattice key supports only fcc and bcc raises ExitCode 380, ...
19,450
def run_Net_on_multiple(patchCreator, input_to_cnn_depth=1, cnn = None, str_data_selection="all", save_file_prefix="", apply_cc_filtering = False, output_filetype = 'h5', save_prob_map = False): """ run runNetOnSlice() on neighbouring blocks of data. if opt_...
19,451
def user_to_janrain_capture_dict(user): """Translate user fields into corresponding Janrain fields""" field_map = getattr(settings, 'JANRAIN', {}).get('field_map', None) if not field_map: field_map = { 'first_name': {'name': 'givenName'}, 'last_name': {'name': 'familyName'},...
19,452
def test_promise_thread_safety(): """ Promise tasks should never be executed in a different thread from the one they are scheduled from, unless the ThreadPoolExecutor is used. Here we assert that the pending promise tasks on thread 1 are not executed on thread 2 as thread 2 resolves its own promis...
19,453
def weighted(generator: Callable, directed: bool = False, low: float = 0.0, high: float = 1.0, rng: Optional[Generator] = None) -> Callable: """ Takes as input a graph generator and returns a new generator function that outputs weighted graphs. If the generator is dense, the output will be the ...
19,454
def arg_parse(dataset, view, num_shots=2, cv_number=5): """ arguments definition method """ parser = argparse.ArgumentParser(description='Graph Classification') parser.add_argument('--mode', type=str, default='train', choices=['train', 'test']) parser.add_argument('--v', type=str,...
19,455
def generate_sampled_graph_and_labels(triplets, sample_size, split_size, num_rels, adj_list, degrees, negative_rate,tables_id, sampler="uniform"): """Get training graph and signals First perform edge neighborhood sampling on graph, then...
19,456
def write(path: str, modules: set) -> None: """Writes a distill.txt file with module names.""" with open(path, "w") as f: for module in modules: f.write(module + "\n")
19,457
def ParseArgs(): """Parses command line options. Returns: An options object as from optparse.OptionsParser.parse_args() """ parser = optparse.OptionParser() parser.add_option('--android-sdk', help='path to the Android SDK folder') parser.add_option('--android-sdk-tools', help='path ...
19,458
def write_losses_to_log(loss_list, iter_nums, logdir): """Write losses at steps in iter_nums for loss_list to log in logdir. Args: loss_list (list): a list of losses to write out. iter_nums (list): which steps to write the losses for. logdir (str): dir for log file. """ for loss in loss_list: l...
19,459
def get_interface_from_model(obj: Base) -> str: """ Transform the passed model object into an dispatcher interface name. For example, a :class:``Label`` model will result in a string with the value `labels` being returned. :param obj: the model object :return: the interface string """ ...
19,460
def main(): """Doc""" stemmer = PorterStemmer() example_words = ["python", "pythoner", "pythoning", "pythoned", "pythonly"] for word in example_words: print(stemmer.stem(word)) new_text = "It is important to by very pythonly while you are pythoning with python. All pythoners have pythone...
19,461
def get_text(string, start, end, bom=True): """This method correctly accesses slices of strings using character start/end offsets referring to UTF-16 encoded bytes. This allows for using character offsets generated by Rosette (and other softwares) that use UTF-16 native string representations under Pyt...
19,462
def train(model: Hidden, device: torch.device, hidden_config: HiDDenConfiguration, train_options: TrainingOptions, this_run_folder: str, tb_logger): """ Trains the HiDDeN model :param model: The model :param device: torch.device object, usually this is G...
19,463
def init_distance(graph: dict, s: str) -> dict: """ 初始化其他节点的距离为正无穷 防止后面字典越界 """ distance = {s: 0} for vertex in graph: if vertex != s: distance[vertex] = math.inf return distance
19,464
def read_cry_data(path): """ Read a cry file and extract the molecule's geometry. The format should be as follows:: U_xx U_xy U_xz U_yx U_yy U_yz U_zx U_zy U_zz energy (or comment, this is ignored for now) ele0 x0 y0 z0 ele1 x1 y1 z1 ... elen...
19,465
def get_camera_wireframe(scale: float = 0.3): """ Returns a wireframe of a 3D line-plot of a camera symbol. """ a = 0.5 * torch.tensor([-2, 1.5, 4]) b = 0.5 * torch.tensor([2, 1.5, 4]) c = 0.5 * torch.tensor([-2, -1.5, 4]) d = 0.5 * torch.tensor([2, -1.5, 4]) C = torch.zeros(3) F = t...
19,466
def read_input(file): """ Args: file (idx): binary input file. Returns: numpy: arrays for our dataset. """ with open(file, 'rb') as file: z, d_type, d = st.unpack('>HBB', file.read(4)) shape = tuple(st.unpack('>I', file.read(4))[0] for d in range(d)) retur...
19,467
def maximum_segment_sum(input_list: List): """ Return the maximum sum of the segments of a list Examples:: >>> from pyske.core import PList, SList >>> maximum_segment_sum(SList([-5 , 2 , 6 , -4 , 5 , -6 , -4 , 3])) 9 >>> maximum_segment_sum(PList.from_seq([-33 , 22 , 11 , -...
19,468
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. (default=None) sat_id : (string or NoneType) Specifies th...
19,469
def has_bookmark(uri): """ Returns true if the asset with given URI has been bookmarked by the currently logged in user. Returns false if there is no currently logged in user. """ if is_logged_in(): mongo.db.bookmarks.ensure_index('username') mongo.db.bookmarks.ensure_in...
19,470
def evaluate(f, K, dataiter, num_steps): """Evaluates online few-shot episodes. Args: model: Model instance. dataiter: Dataset iterator. num_steps: Number of episodes. """ if num_steps == -1: it = six.moves.xrange(len(dataiter)) else: it = six.moves.xrange(num_steps) it = tqdm(it, ncols...
19,471
def test_command_not_implemented(client, es_clear): """Tests a configured action without implemented function.""" # NOTE: recid can be dummy since it won't reach pass the resource view response = client.post( "/mocks/1234-abcd/draft/actions/command", headers=HEADERS ) assert response.status_...
19,472
def find_period_of_function(eq,slopelist,nroots): """This function finds the Period of the function. It then makes a list of x values that are that period apart. Example Input: find_period_of_function(eq1,[0.947969,1.278602]) """ global tan s1 = slopelist[0] s2 = slopelist[1] if tan == 1...
19,473
def merge_date_tags(path, k): """called when encountering only tags in an element ( no text, nor mixed tag and text) Arguments: path {list} -- path of the element containing the tags k {string} -- name of the element containing the tags Returns: whatever type you want -- th...
19,474
def pr(): """ Work with pull requests. """ pass
19,475
def ocp_play(): """Decorator for adding a method as an common play search handler.""" def real_decorator(func): # Store the flag inside the function # This will be used later to identify the method if not hasattr(func, 'is_ocp_playback_handler'): func.is_ocp_playback_handler ...
19,476
def parse_store(client, path='/tmp/damn', index='damn'): """ """ path = dirname(dirname(abspath(__file__))) if path is None else path repo_name = basename(path) create_store_index(client, index) for ok, result in streaming_bulk( client, parse_file_descriptions(path), ...
19,477
def check_encoder_decoder_args(args) -> None: """ Check possible encoder-decoder argument conflicts. :param args: Arguments as returned by argparse. """ encoder_embed_dropout, decoder_embed_dropout = args.embed_dropout encoder_rnn_dropout_inputs, decoder_rnn_dropout_inputs = args.rnn_dropout_in...
19,478
def _scatter(x_arr, y_arr, attributes, xlabel=None, xlim=None, xlog=False, ylabel=None, ylim=None, ylog=False, show=True, save=None): """Private plotting utility function.""" # initialise figure and axis settings fig = plt.figure() ...
19,479
def first_item(iterable, default=None): """ Returns the first item of given iterable. Parameters ---------- iterable : iterable Iterable default : object Default value if the iterable is empty. Returns ------- object First iterable item. """ if not ...
19,480
def init_config(): """ Init configuration """ # Load the initial config config = os.path.dirname(__file__) + \ '/colorset/config' try: data = load_config(config) for d in data: c[d] = data[d] except: pass # Load user's config rainbow_config...
19,481
def stratification(n_subjects_per_strata, n_groups, block_length=4, seed=None): """ Create a randomization list for each strata using Block Randomization. If a study has several strata, each strata is seperately randomized using block randomization. Args: n_subjects_per_strata: A list of the n...
19,482
def pytest_configure(): """ Hack the `project_template` dir into an actual project to test against. """ from mezzanine.utils.importing import path_for_import template_path = Path(path_for_import("mezzanine")) / "project_template" shutil.copytree(str(template_path), str(TMP_PATH)) proj_path ...
19,483
def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encod...
19,484
def FileDialog(prompt='ChooseFile', indir=''): """ opens a wx dialog that allows you to select a single file, and returns the full path/name of that file """ dlg = wx.FileDialog(None, message = prompt, defaultDir = indir) if dl...
19,485
def my_account(): """ Allows a user to manage their account """ user = get_user(login_session['email']) if request.method == 'GET': return render_template('myAccount.html', user=user) else: new_password1 = request.form.get('userPassword1') new_password2 = request.form.get...
19,486
def recalculate_cart(request): """ Updates an existing discount code, shipping, and tax when the cart is modified. """ from cartridge.shop import checkout from cartridge.shop.forms import DiscountForm from cartridge.shop.models import Cart # Rebind the cart to request since it's been mo...
19,487
def __pad_assertwith_0_array4D(grad: 'np.ndarray', pad_nums) -> 'np.ndarray': """ Padding arrary with 0 septally. :param grad: :param pad_nums: :return: """ gN, gC, gH, gW = grad.shape init1 = np.zeros((gN, gC, gH + (gH - 1) * pad_nums, gW), dtype = grad.dtype) init2 = np.zeros((gN,...
19,488
def islist(data): """Check if input data is a list.""" return isinstance(data, list)
19,489
def timeoutHandler(signum, frame): """ Function called when a Jodis connection hits the timeout seconds. """ raise TimeoutError('Jodis Connection Timeout')
19,490
def spatial_mean(xr_da, lon_name="longitude", lat_name="latitude"): """ Perform averaging on an `xarray.DataArray` with latitude weighting. Parameters ---------- xr_da: xarray.DataArray Data to average lon_name: str, optional Name of x-coordinate lat_name: str, optional ...
19,491
def rank(value_to_be_ranked, value_providing_rank): """ Returns the rank of ``value_to_be_ranked`` in set of values, ``values``. Works even if ``values`` is a non-orderable collection (e.g., a set). A binary search would be an optimized way of doing this if we can constrain ``values`` to be an order...
19,492
def test_more_images_than_labels(): """[summary] """ # Get images and labels images = [f"/{i}/test_{j}.png" for i in range(10) for j in range(10)] labels = [f"{i}" for i in range(10)] # Get images2labels images2labels = compute_images2labels(images, labels) ...
19,493
def Characteristics(aVector): """ Purpose: Compute certain characteristic of data in a vector Inputs: aVector an array of data Initialize: iMean mean iMed median iMin minimum iMax maximum iKurt kurt...
19,494
def loglik(alpha,gamma_list,M,k): """ Calculate $L_{[\alpha]}$ defined in A.4.2 """ psi_sum_gamma=np.array(list(map(lambda x: psi(np.sum(x)),gamma_list))).reshape((M,1)) # M*1 psi_gamma=psi(np.array(gamma_list)) # M*k matrix L=M*gammaln(np.sum(alpha)-np.sum(gammaln(alpha)))+np.sum((psi_gamma-ps...
19,495
def handle_delete(sender_content_type_pk, instance_pk): """Async task to delete a model from the index. :param instance_pk: :param sender_content_type_pk: """ from gum.indexer import indexer, NotRegistered try: sender_content_type = ContentType.objects.get(pk=sender_content_type_pk) ...
19,496
def recode_media(src, dst, start=0, length=0, width=0, height=0, fps=0, bitrate_v=0, bitrate_a=0, no_video=False, no_audio=False, copy_v=False, copy_a=False, overwrite=False, verbose=False): """Recodes media. Args: src : Path to source media file. dst ...
19,497
def get_file_hashes(directory_path): """Returns hashes of all files in directory tree, excluding files with extensions in FILE_EXTENSIONS_TO_IGNORE or files that should not be built. Args: directory_path: str. Root directory of the tree. Returns: dict(str, str). Dictionary with keys sp...
19,498
def fixedcase_word(w, truelist=None): """Returns True if w should be fixed-case, None if unsure.""" if truelist is not None and w in truelist: return True if any(c.isupper() for c in w[1:]): # tokenized word with noninitial uppercase return True if len(w) == 1 and w.isupper() and...
19,499