content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pick_pareto_front(points, keep_equal=False): """Returns the Pareto-optimal points from a set of points, assuming all objectives are minimisation objectives. The n points in d-dimensional objective space are given in an ndarray of shape (n,d), and the return value is of shape (m,d) where m is the ...
4dbd528bb2731dafd8a6f82cbd9dd53a83bd1c4c
29,248
import csv def get_market_conditions(filename): """ Creates the market condition table from the scenario file and risk factors """ market_conditions = [] print("Generate conditions") #open the csv file to be read with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimi...
f7876a8cf4b2d6399e1fd12f2e8a4f7614892874
29,249
def PaperSize(s): """Return a tuple (width, height) for a given paper format string. 'A4-L' will return (842, 595), the values for A4 landscape. Suffix '-P' and no suffix returns portrait.""" size = s.lower() f = "p" if size.endswith("-l"): f = "l" size = size[:-2] if size.en...
e0439e7535bba1b7f4bd5309b8f934b689f1b67f
29,250
def clean_detections(npts, on_off): """Removes spurious seismic detections that occur within a window following a detection. Parameters ---------- npts : int Length of window in data samples. on_off : array On/off indexes for detections. Returns ------- array ...
539ce2b53ee42f8038f4d1b8c35af55247e13204
29,251
def register_validator(fn): """ collect validator functions into ckanext.scheming.all_helpers dict """ all_validators[fn.__name__] = fn return fn
e1dc4c4a9294400d1916b6308192c85702d3fe69
29,252
def save_config(): """ :return: Completed save. """ global host_id_start # Save start and end to file. cfgfile = open("config.ini",'w') try: Config.add_section('Host ID') except ConfigParser.DuplicateSectionError, e: # File already exists. pass Config.set('Hos...
ba15a2d61e153fc251c5b6c9ebc6b48b5f34066e
29,253
def encode_data_image_to_16bit(data_image: np.ndarray, max_data_value: int = 120) -> np.ndarray: """ this method sets all data values above max_data_value to zero, scales it by the max_data_value and rescales the depth image to the uint16 range. :param data_image: :param max_data_value: :return...
fef90a4664ce851f2ace61c4b739c320f6cef3e8
29,254
from typing import Optional from typing import Mapping def get_database(name: Optional[str] = None, resource_group_name: Optional[str] = None, server_name: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOp...
1f4afe29ce88d1a85bdb8cee93cf731a6c37b301
29,255
import yaml def read_status_yaml(path: str, year: int = None): """Reads a yaml file containing categories and date ranges for each categories.""" with open(path, "rt") as f: data = yaml.load(f, Loader=yaml.Loader) categories = [] for category, datestrlist in data.items(): status = Sta...
51765d53264c52a3817c48b125ddad6254fca816
29,256
import numpy import math def S_inv_eulerZYX_body_deriv(euler_coordinates, omega): """ Compute dE(euler_coordinates)*omega/deuler_coordinates cfo, 2015/08/13 """ y = euler_coordinates[1] z = euler_coordinates[2] """ w1 = omega[0]; w2 = omega[1]; w3 = omega[2] ...
f7688b61084b0421288be002042b7299a7f8e867
29,257
def _mini_batch_step(X, sample_weight, x_squared_norms, centers, weight_sums, old_center_buffer, compute_squared_diff, distances, random_reassign=False, random_state=None, reassignment_ratio=.01, verbose=False): """Incremental updat...
68bd702efc61a95721d25d6fd89dd5cb54fc41fa
29,258
def get_user_ida_projects(): """ List IDA projects for current user without the prefix. Returns: list(str) -- List of projects. """ user_ida_groups = get_user_ida_groups() if user_ida_groups is None: log.error('Could not get user IDA projects.\n') return None try: ...
d94888849dd1c3c170e99d7ba57a7ec641c5ee39
29,259
def bf_get_issue_config(major, minor): # type: (str, str) -> IssueConfig """Returns the issue config for the active network.""" return IssueConfig.from_dict( restv2helper.get_issue_config(bf_session, major, minor) )
fd8b20c28cac7b8535d7f5045b7fbbaca89f6e71
29,260
import torch def normalize_rotmat(mat: torch.Tensor) -> torch.Tensor: """Normalizes rotation matrix to a valid one""" u, _, v = torch.svd(mat) s = torch.zeros_like(mat) s[..., 0, 0] = 1.0 s[..., 1, 1] = 1.0 s[..., 2, 2] = torch.det(u) * torch.det(v) return u @ s @ v.transpose(-1, -2)
1ba33c73a943392d6fe06448e81c346a5e7dc9f6
29,261
def responder(): """Responder fixture.""" return MockResponder()
097e90423a19c7d1ca231daf717afc15a1597fc1
29,262
def ortho(U, V, A, X=1, G=None, Z=0): """ U is NxL array of cell factors V is JxL array of loadings onto genes X is NxKo array of cell specific covariates A is JxKo array of coefficients of X Z is JxKf array of gene specific covariates G is NxKf array of coefficients of Z assume the data Y is of dimen...
843d895d7d88717859cf73da939266a335214518
29,263
def get_all_users_projects(is_authenticated): """Pull every assigned project for all users from Users_Projects table""" if is_authenticated and auth0.is_admin(): app.logger.info( f"Received request at {const.INTERMEDIATE_API_ALL_USERS_PROJECTS_ENDPOINT}" ) auth0_users, _ = au...
cf33a581d9dcea988af8640b98cb816b61640c3d
29,264
import requests def get_status_code(ep): """Function that gets an endpoint and returns its HTTP status code""" req = requests.get(ep) return req.status_code
bd15853ac4615e96306c2b259c6945a4c46dd17b
29,265
def process_repository(repo_dict): """ Takes a dictionary containing keys: path, branches and revisions and returns a Repository object. This method should only be called by read_yaml. """ path = repo_dict[REPOSITORY_PATH] revisions = {} if REPOSITORY_REVISIONS in repo_dict: for revisi...
3a1122edf7ce42b268a8e735bf060844b7a7fc5d
29,266
import re def hash_algorithm(alg, allow_raw=False): """Parse an hash algorithm""" # canonical name: only alphanumeric uppercase characters alg = re.sub(r'[^0-9A-Z]', '', alg.upper()) if alg in DIGEST_ASN1_PREFIXES: return alg elif allow_raw and alg == 'RAW': return alg raise Va...
dc9287d7c2be76c9b2417a367e8c4e0653c4b515
29,267
def fista(gradient_op, linear_op, prox_op, cost_op, kspace_generator=None, estimate_call_period=None, lambda_init=1.0, max_nb_of_iter=300, x_init=None, metric_call_period=5, metrics={}, verbose=0, **lambda_update_params): """FISTA sparse reconstruction. Parameters ---------- ...
b05c2e860ce3423724f9385dc6f654b98dfdafd3
29,268
def get_entry_from_args(): """ Handle finding the file entry using the user supplied arguments return the entry or quits script entirely. :rtype: object containing the entry of the found file and the entry_id or error & exit """ # Get the pcap file from arguments entry_id = None if 'pca...
5d7ea26bf17d8a8fc54ece069b05cb1918fc746f
29,269
def GetGerritFetchUrl(host): """Given a gerrit host name returns URL of a gerrit instance to fetch from.""" return 'https://%s/' % host
caf5c9015a4cd863e407fb889d473ddebd7bbabc
29,270
def deep_copy(pcollection): """Create a deep copy of a PCollection up to materialization boundaries.""" if not isinstance(pcollection, pvalue.PCollection): raise ValueError('Input to deep_copy must be a PCollection.') # AppliedPTransform.update_input_refcounts() is a vestigial method that # uses an incorre...
7cfaa902d8e4ea5ce45f779decfeaaf54da2a435
29,272
def compute_lm_accuracy(eval_preds): """Compute the accuracy given the predictions and labels, contained in `eval_preds`. It assumes the logits have been reduced with argmax(-1) by `preprocess_logits_for_accuracy`. """ preds, labels = eval_preds # preds have the same shape as the labels, after ...
fc095cf1662b9cc2e164a8d9bf5e32eb30327460
29,273
from pathlib import Path def fix_path(path): """Fix a path and convert to an absolute location. Parameters ---------- path : str Path to fix. Returns ------- str Absolute path. """ if THIS_PLATFORM == 'Windows': path = PureWindowsPath(path) return st...
a8b648f6bb9859412f347649fd93cf9c264d22b9
29,275
import numpy def partition_skymodel_by_flux(sc, model, flux_threshold=-numpy.inf): """ :param sc: :param model: :param flux_threshold: :return: """ brightsc = filter_skycomponents_by_flux(sc, flux_min=flux_threshold) weaksc = filter_skycomponents_by_flux(sc, flux_max=flux_threshol...
305b18621a3313cdf3ef1cdb14a855bbe4608276
29,276
def getNumberOfDaysBetween(d1, d2, tz_str='UTC'): """ d1 and d2 are datetime objects in UTC """ d1_date = utcInTz(d1, tz_str) d2_date = utcInTz(d2, tz_str) d1_date = deepcopy(d1_date).replace(hour = 0, minute = 0, second = 0, microsecond = 0) d2_date = deepcopy(d2_date).replace(hour = 0, minute = 0, second = 0, m...
c4cdf2febef6fe7c7bf0695c1fa0dcdc3bc6caeb
29,277
def get_language_specifics() -> BaseLanguage: """Gets the language specific actions.""" return PluginLoader().languageSpecifics
8959bce727b6c068d5fc08041d74820fd3738ef5
29,278
def add_item(): """Create a new item. This will list all login uuser created """ if 'username' not in log_session: flash("Please login in to continue.") return redirect(url_for('login')) elif request.method == 'POST': item = session.query(Item).filter_by(name=request.form['name'])....
31cc94f58a01f473731fcd689769b688bcb97f72
29,280
def SGLD(nburnin, nsample, gradU, p, batch, eta=0.0001, L=100, V=3): """ Function to get posterior samples given parameters with SGLD """ n = nburnin + nsample if type(p) != "np.array": d = 1 else: d = len(p) samples = np.zeros((n,d)) for i in range(n): ...
04d49230cb71c83561726939213e2bdc74edaf54
29,281
from typing import List def create_commands(device_ids: List[str], file_path: str) -> List[CommandRunner.Command]: """ Create a list of `Command` of the remove file command to `Cortex XDR` and `CrowdstrikeFalcon` :param device_ids: The device id's to run on :param file_path: The file_path to delete ...
2a27c69bcaaf91984c853bd37eb260cc7d27a720
29,282
from datetime import datetime def compiler(stats_set): """ Processes the API data into a clean dataframe for analysis and predictions. Parameters ---------- stats_set: list Incoming data on all previous games from the balldontlie API request. Returns ---------- final: pan...
a4edcd41cfd770e82aa368e3e6232f51d6cecec8
29,283
def generate_cpda_eligible_lists(request): """ Function retrieves the eligible user information and related unreviewed,approved and archived CPDA applications. """ active_apps = (Cpda_application.objects .select_related('applicant') .filter(applicant=request.u...
b6cda540dd94ea07d3e4a400a8dfa19c8cec1e0a
29,284
def get_points_on_sphere(n_points, r=1): """ Find n evenly spaced points on a sphere using the "How to generate equidistributed points on the surface of a sphere" by Markus Deserno, 2004. Arguments: n_points (int): number of points to generate r (float): radius of the sphere Return...
575b7aa98c08942dbe24389bf18bde36cd0f9c0e
29,285
def bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1): """ bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1) This function creates a bottleneck block layer, which is the addition of a convolution block and a batch normalized/activated block INPUTS: ...
a0a37478013feb4702fa18b5143d7f0c33506119
29,286
def list_nodelets(): """ List all nodelets in all packages. """ nodelets = [] for p in rospkg.RosPack().get_depends_on('nodelet', implicit=False): nodelets += Package(p).list_nodelets() return nodelets
367aeb784bc3282e1e37d279591ddb00aa698b0b
29,288
def predict(): """Predict route""" audio_id = request.args.get('id') db.download(audio_id) y = detector.predict("data//audio.wav") state = {"status": str(y)} return jsonify(state)
a0e7011499e6c387532172750cbaa4163c509736
29,291
def colorize(text, color, bold=False): """Colorize some text using ANSI color codes. Note that while ANSI color codes look good in a terminal they look like noise in log files unless viewed in an ANSI color capable viewer (such as 'less -R'). Args: text: The text to colorize. color: One of the color...
8231b5f7c58f940820a7f0ef0846d663ec146366
29,292
def _create_log_entry(class_, message, author, created_at=None, **kwargs): """ This method will create a new LogEntry of the given type with the given arguments. :param type type: A subclass of LogEntry which should be created. :param unicode message: the log message text :param User author: us...
ec0ad487b4aa6580555d0e58fcd3eadb8e4c3941
29,293
def avg_stimpos(band, eclipse): """ Define the mean detector stim positions. :param band: The band to return the average stim positions for, either 'FUV' or 'NUV'. :type band: str :param eclipse: The eclipse number to return the average stim positions for. :type eclipse: int :re...
59d748b99c621f6dbcbbc05ba77c54178b57533d
29,294
def multiclass_positive_predictive_value(confusion_matrix: np.ndarray, label_index: int) -> Number: """ Gets the "positive predictive value" for a multi-class confusion matrix. The positive predictive value is also known as *precision*. See the documentation of...
51822f7a75eb48301121fc52ef5e6f8fa661fe2f
29,295
def get_matching_cost_swap_bf(election_1: OrdinalElection, election_2: OrdinalElection, mapping): """ Return: Cost table """ cost_table = np.zeros([election_1.num_voters, election_1.num_voters]) for v1 in range(election_1.num_voters): for v2 in range(election_2.num_vot...
38b7857686caa60212ffdd4578097658dd9ba2e3
29,296
def auditable(event_type, msg_on_success): """ Makes the result of an endpoint audit loggable - passes an AuditLogger object to the handler so that it can set extra data to be logged. """ def decorator(f): @wraps(f) def _(self, request, *args, **kwargs): audit_logger ...
e422fcb8892da5dc26299a437238e3a815492f9e
29,297
def rec_pow(a, b): """Compute a**b recursively""" if b == 0: return 1 if b == 1: return a return (rec_pow(a,b//2)**2) * (a if b % 2 else 1)
42972acab57b3e217dbd10fa32a38125c5eab44d
29,298
def omega_d(m, bvectors, bweights, idx=None): # Eq. 36 """ Compute the diagonal contribution to the spread functional Parameters ---------- m: ndarray, shape (nkpts, nntot, nbnds, nbnds) the overlap matrix bvectors: ndarray, shape (nkpts, nntot, 3) bweights: ndarray, shape (nntot,...
30136552c53b3fd18ebb56b666cf9bafa7baf926
29,299
import json from datetime import datetime def get_github_info(packages=packages): """ Get information about subpackage releases that have been tagged on github """ no_release = [] release = {} for package in packages: url = f"https://api.github.com/repos/pysal/{package}/releases/lates...
1c13522ad816f4f4898a193bd5b7bb04febbf67a
29,300
from typing import Dict def matrix_str_to_dict(matrix_str: str) -> Dict[str, Dict[str, int]]: """Transform dictionary string to 2-d array of ints.""" scoring_matrix = {} table = [line.split() for line in matrix_str.split("\n") if line[0] != "#"] aa_tos = table[0] for row in table[1:]: aa_f...
de1d4fd581a40cb6e61bd2b13c3a89718a67736f
29,301
def restriction(model, sfield, residual, sc_dir): """Downsampling of grid, model, and fields to a coarser grid. The restriction of the residual is used as source term for the coarse grid. Corresponds to Equations 8 and 9 and surrounding text in [Muld06]_. In the case of the restriction of the residual...
b3f97cef119ae219f5bca2d56d1c6ec55bb3d5db
29,302
def check_good_not_bad(decider, good, bad): """Check if bad prof becomes GOOD by adding funcs it lacks from good prof""" bad_copy = bad.copy() for func in good: if func not in bad: bad_copy[func] = good[func] return decider.run(bad_copy) == StatusEnum.GOOD_STATUS
0464721aae2c20310eefb3e78f1b3e4c36a558ed
29,303
from typing import List def filter_by_length(data: List[list], lower_bound: int, upper_bound: int) -> List[list]: """ :param data: [[word1, word2, word3], ..., [word1, word2]] :param lower_bound: 3 :param upper_bound: 5 :return: [[word1, word2, word3, ... ], ..., None] """ for index in ra...
4b7d83a82c29622d4d26fc718b6bb5fbe959c8dd
29,304
def run_games_and_record_payoffs(game_queries, evaluate_game, ckpt_to_policy): """Simulate games according to game queries and return results. Args: game_queries: set of tuples containing indices specifying each players strat evaluate_game: callable function that takes a list of policies as argument ck...
7d03b48e076efab99353b582baf04b96503695c5
29,305
from typing import Type from typing import Tuple from typing import Any def create_namespace_handler( file_type: Type[NamespaceFile], namespace_scope: Tuple[str, ...], namespace_extension: str, ) -> Type[NamespaceFile]: """Create handler that turns yaml namespace files into json.""" class AutoYam...
a9013dfbbe48a4b6cc5b48ca3e5cb07c833e870c
29,307
def get_native_backend_config_dict(): """ Get backend_config_dict for PyTorch Native backend (fbgemm/qnnpack). """ binary_op_dtype_configs = [ weighted_op_int8_dtype_config, default_op_fp16_dtype_config, ] share_qparams_op_dtype_configs = [ default_op_quint8_dtype_config, ...
3b0332feb223b9e08724f45d6397b418a5690e0e
29,309
def dummy_content_widget(title='Dummy Content Widget', content="Dummy Content", slug="dummy_content_widget", is_published=True): """Will directly write to the database a dummy content widget for our tests. Parameters ---------- title : str Widget title. content...
e0164f5512c02abc79ddd6149c1c855fbf6b4241
29,310
def ask_note(): """Function to ask user for task notes""" task_note = input("Enter any additional task notes here >") return task_note
952010409c0430b697b899edf7c29b5fa2f9bedb
29,312
def Yt_1d_full(): """ 1d Yt fully observed """ y = np.array([[[2]], [[1.3]], [[2.5]], [[3.1]]]) return y
e44e98ab25336e16802c670361ad18359fab0957
29,315
def threshold_isodata(image, nbins=256, shift=None, max_limit=None, min_limit=None): """Return threshold value based on ISODATA method. Histogram-based threshold, known as Ridler-Calvard method or intermeans. Parameters ---------- image : array Input image. nbins : int, optional ...
7c660baac593cbd965f1b6a48a0dfc861c69b878
29,316
def populate_task_view(request): """ populate project_task view """ project_id = request.GET.get('project_id') project_name = request.GET.get('project_name') template = loader.get_template('project_management/add_project_tasks.html') project = Project.objects.get(id=int(project_id)) sta...
33f7ab5b60ef4cbc8fd0e39bf74f5a851f13659a
29,317
def cleanup_queryset(queryset): """ Remove multiple joins on the same table, if any WARNING: can alter the origin queryset order """ return queryset.model.objects.filter(pk__in=[instance.pk for instance in queryset.all()])
ecdab862fd67359fab1a5706092fe0d023d31321
29,318
def svn_diff_output_fns_invoke_output_conflict(*args): """ svn_diff_output_fns_invoke_output_conflict(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start, apr_off_t original_length, apr_off_t modified_start, apr_off_t modified_length, apr_off_t latest_start, apr_off_...
a434298342e50c2803c3ccaf69fecbe0de36b816
29,319
def capacity_factors(): """ This function generates a hard-coded dictionary containing the capacity factors for different fuels and movers. The values are defaulted to 1.0 if no capacity factor information can be found. The numbers are specific to the 2018 year and may lead to innacurate res...
b75e4a86224af565ffab919e63a1a352696e73bc
29,320
def _is_greater(list1: list, list2: list): """ return True if `list1[i] > list2[i]` for each `i` """ return all([list1[i] > list2[i] for i in range(len(list1))])
925fb214f741d6503b41b49d57a268506f05a048
29,321
def isenabled(handle): """Return True if the window is enabled""" return bool(win32functions.IsWindowEnabled(handle))
edb99831f561fd84ab0bb17bf568e200699a7aa1
29,322
def monte_carlo(d): """ Calculate Monte Carlo value for π. Arguments: d: list of unsigned byte values. Returns: Approximation of π as Decimal """ MONTEN = 6 incirc = Decimal((256.0 ** (MONTEN // 2) - 1) ** 2) d = (Decimal(j) for j in d[: len(d) // MONTEN * MONTEN]) ...
fe6fdc07c18ae35abcc3ab428f13188a0ff306c2
29,323
def verifyIfRepo(dirName): """ """ dbPath = getDbPath(dirName) print dbPath try: if verifyShelveVersionCompatibility(dbPath): return True else: return False except: return False
ecedb0569a0a1d41ad23dcef1f9155145756cb8c
29,324
def machine_setter(_latfile=None, _machine=None, _handle_name=None): """ set flame machine, prefer *_latfile* :return: FLAME machine object """ if _latfile is not None: try: with open(_latfile, 'rb') as f: m = Machine(f) except: if _machine is Non...
8fa5802d7307269d57667c84e3d832b1985dba8f
29,325
def vgg_preprocess_images(image_tensor): """ :param image_tensor: float 32 array of Batch x Height x Width x Channel immages (range 0 - 1) :return: pre-processed images (ready to input to VGG) """ vgg_mean = tf.convert_to_tensor(np.array([103.939, 116.779, 123.68], dtype=np.float32)) red, green,...
8354e3023af981b4d7f9d2c98f60a7e05943e218
29,326
def computeIntCorrections(npix,factor): """Compute `newnpix` and `newfactor` such that `npix_new` is the nearest odd-valued integer to ``npix*factor``. Parameters ---------- npix : int Odd-valued integer. factor : float Multiplicative factor. Returns ------- newn...
9b662acecd54795c50eb8ca5e4ac7af45a006c5c
29,327
def LU_factor(A,LOUD=True): """Factor in place A in L*U=A. The lower triangular parts of A are the L matrix. The L has implied ones on the diagonal. Args: A: N by N array Returns: a vector holding the order of the rows, relative to the original order Side Effects: A is fact...
aa74e20888892ba5edafd9deaf10976633319544
29,328
def get_zvals_from_grid(line,xyzgrid): """ Input: line (LineString or ARRAY with first two columns the xy coords) get z values at every point in line from xyzgrid xyzgrid: DataFrame with x,y,z columns or 3 column ARRAY returns: array of z values for each point on line """ #create dataframe if np.arra...
5eee6c46559bcf30e9d3dca30bb18ca7e3b30489
29,329
def HBIh(time, gsd = None, gh = None): """ paras gsd: optional Conductance of slow depolarizing gh : optional Return Var_t : action potential """ def HyB(Var,t,tempF): [rrho,pphi] = tempF [v,ar,asd,ca,ah]=Var ad = 1/(...
2abbf9611097e65b6a6e03e0dfdfbecd61a5bb35
29,330
import requests import json def discovery(uri="", data_format="json"): """ Method description: Deletes/Unregisters an application entity(AE) from the OneM2M framework/tree under the specified CSE Parameters: uri_cse : [str] URI of parent CSE ae_name : [str] name of the AE fmt_ex : [st...
5b09ce0f7ce533c02386cba9f4cf2ffebc85edcf
29,331
async def test_map_two_iterables_expected_result( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Look for expected results which should returned by :class:`none.collection.a.map` with two iterables given. """ async def _add(a: int, b: int) -> int: return a + b async for i, x ...
10749b3315e911e4f5c07d1adeef43e258e18092
29,332
def dijkstra_search(problem): """ Best first search that uses g(n) to evaluate cost :param problem: :return: final node """ return best_first_graph_search(problem, lambda n: n.path_cost)
e3c9dbdea4f4fc8ce99dcf4be41d4d42cfac1555
29,333
def _get_pair_nodes(root_node): """ Internal method to get "pair" nodes under root_node """ method_elem = root_node in_configs_elem_list = method_elem.getElementsByTagName("inConfigs") in_configs_elem = in_configs_elem_list[0] pair_elems_list = in_configs_elem.getElementsByTagName("pair") ...
c2b74f7a507394d2117cd6292116e62d34f3e556
29,334
def has_ao_2e_int_eri_lr(trexio_file) -> bool: """Check that ao_2e_int_eri_lr variable exists in the TREXIO file. Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function. Returns: True if the variable exists, False otherwise Raises: - Exception from tr...
3f903aa4e03ed78313b59ff0b03ddcc65c6de0ca
29,336
def corelucy(image, h): """ Make core for the LR estimation. Calculates f to produce the next iteration array that maximizes the likelihood that the entire suite satisfies the Poisson statistics. This is a simplified version of MATLAB corelucy function without damping, weights and externally def...
b376be72f3572ac06f0a401f5d768abf76d3ba00
29,337
def convert_to_bipartite(S): """ convert a standard stoichiometric matrix (in a Pandas DataFrame) to a bipartite graph with an edge between every reactant and all its reactions """ # convert the stoichiometric matrix to a sparse representation S_sparse = pd.melt(S.reset_index(), ...
cd931f92b4ef32624202ab1145236d54801ab048
29,338
def proj_l1_neg_tan_cone(u, v): """ Project u onto the negative tangent cone of l1 ball with diameter ||v||_1 at v. It's actually the tangent cone of l1 ball with bound ||v||_1 at -v. @param u: the vector to calculate projection from. @param v: the vector at whom the tangent cone forms. ...
a5a1dbf74ba3f58dc31bda50ffbc9483ab258301
29,339
def generate(prompt: str, context: str) -> str: """Generates a response for the given prompt and context. :param prompt: The prompt to generate a response for. :type prompt: str :param context: The context to generate a response for. :type context: str :return: The generated response. :rtyp...
e752c3fa10d1de40d944bfa41b88f34c2d3e4894
29,340
def fista(input_size, eval_fun, regulariser, regulariser_function=None, thresholding_function=None, initial_x=0, L0=1., eta=2., update_L=True, verbose=1, verbose_output=0): """ FISTA (Fast Iterative Shrinkage Thresholding Algorithm) is an algorithm to solve the convex minimization ...
17710174114e6b8772d3e53e49a379bc476f3c81
29,341
def __ldns_pkt_set_question(*args): """LDNS buffer.""" return _ldns.__ldns_pkt_set_question(*args)
2dfb8d0bea1aee4348d5ddc5850e36963c0f092e
29,342
import random def get_nick(infraction_id: int, member_id: int) -> str: """Randomly select a nickname from the Superstarify nickname list.""" rng = random.Random(str(infraction_id) + str(member_id)) return rng.choice(STAR_NAMES)
120ba3abcf5f68bff46672b18cbce3e18c5088d0
29,343
def find_best_path(starting): """Find the best moves using A*""" @dataclass(order=True) class PrioritizedState: """Dataclass to insert the RoomStates into the priority queue""" cost: int config: RoomState=field(compare=False) open_set = PriorityQueue() open_set.put(Priorit...
2328af1e8fbf01808c321e18b27e7c6e0e9b8f9c
29,344
def Shard(ilist, shard_index, num_shards): """Shard a given list and return the group at index |shard_index|. Args: ilist: input list shard_index: 0-based sharding index num_shards: shard count """ chunk_size = len(ilist) / num_shards chunk_start = shard_index * chunk_size if shard_index == num...
7f79ade521c1264d0ddc8c5a228679d7053d9651
29,345
from typing import Any from typing import Tuple def get_oof_pred( model: Any, X_train: pd.DataFrame, y_train: pd.Series, X_test: pd.DataFrame, n_fold: int, ) -> Tuple[np.ndarray, np.ndarray]: """ Get Out of Fold prediction for both training and testing dataset Args: model (Any)...
19871121a674ad6730db17d97930c7bd6c09f7e2
29,346
async def get_aes_key(password: str, settings: EncryptionSettings) -> bytes: """Returns the 32 byte system encryption key.""" assert isinstance(password, str) assert isinstance(settings, EncryptionSettings) return await decrypt_chunk(get_decryption_key(password, settings), settings.encrypted_key)
8f5c67d1d64c25d02c33363c572fc04c6e364e55
29,347
def nextpow2(value): """ Extracted from caiman.source_extraction.cnmf.deconvolution import axcov Find exponent such that 2^exponent is >= abs(value). Parameters: ---------- value : int Returns: ------- exponent : int """ exponent = 0 avalue = np.abs(value) while a...
4e485d9ebb8e2103dff45d777783f1f2bcdc5509
29,348
def workshopinquiry_accept_event(request, inquiry_id): """Accept workshop inquiry by creating a new event.""" wr = get_object_or_404(WorkshopInquiryRequest, state='p', pk=inquiry_id) if request.method == 'POST': form = EventCreateForm(request.POST) if form.is_valid(): event = f...
fde98bd8924ac1bc4f5c39365c90c1e53bbc7546
29,349
def load_level_data(): """Read the `level.dat` file and return the `Data` compound.""" try: level_data = nbt.load(LEVEL_DATA_PATH, gzipped=True).root['Data'] except FileNotFoundError: display_error(f'Couldn\'t find any "{LEVEL_DATA_PATH}" file. Are you ' 'sure that the ...
82039e0ba2156e0231d1403081e9cb83a140e5ce
29,350
def separation_scorer(catalogue,name_TGSS,name_NVSS): """given two names, gives separation by set-up, only gives non-zero for those in catalogue""" if (name_TGSS,name_NVSS) in catalogue.index: sep = catalogue.loc[name_TGSS,name_NVSS].separation sep *= 3600 return max(0,(40-sep)/40) ...
f70a6cf58ec12caba784ff7f51cbdbbf74f536b6
29,351
def mms_hpca_calc_anodes(fov=[0, 360], probe='1', suffix=''): """ This function will sum (or average, for flux) the HPCA data over the requested field-of-view (fov) Parameters ---------- fov : list of int field of view, in angles, from 0-360 probe : str prob...
3c6ca26f06eb65c4e2c5e3f71724d890aba5a6a9
29,352
def get_host_call_fn(model_dir): """`host_call` function for creating training summaries when using TPU.""" def host_call_fn(**kwargs): """Host_call_fn. Args: **kwargs: dict of summary name to tf.Tensor mapping. The value we see here is the tensor across all cores, concatenated along axis 0....
4dafbbed695205f97501ab44f4eeae480d562f7e
29,353
from datetime import datetime def determine_horizons_id(lines, now=None): """Attempts to determine the HORIZONS id of a target body that has multiple possibilities. The passed [lines] (from the .args attribute of the exception) are searched for the HORIZONS id (column 1) whose 'epoch year' (column 2) ...
1cbf143bfd8a7b5a3178a443b3dfc4298e02bbfd
29,354
def export_read_file(channel, start_index, end_index, bulkfile, output_dir, remove_pore=False): """Generate a read FAST5 file from channel and coordinates in a bulk FAST5 file Parameters ---------- channel : int channel number from bulk FAST5 file start_index : int start index for r...
8fc7b93492eb709d6e08d66c4089f48908d91919
29,355
def escape_html(s: str)-> str: """ Escape html :param str s: string :return: replaced html-string """ s = s.replace('&','&amp;') s = s.replace('<','&lt;') s = s.replace( '>','&gt;') s = s.replace('"','&quot;') s = s.replace("'", '&apos;') return s
d66f1af0990a108b7c6fa9ce1e5a0e51bf44f416
29,356
def CSCH(*args) -> Function: """ The CSCH function returns the hyperbolic cosecant of any real number. Learn more: https//support.google.comhttps://support.google.com/docs/answer/9116336. """ return Function("CSCH", args)
506c16e1d53a91e18e73d416f252a47f5c35fc95
29,357
def _get_valid_name(proposed_name): """Return a unique slug name for a service""" slug_name = slugify(proposed_name) name = slug_name if len(slug_name) > 40: name = slug_name[:40] return name
cce3a986fc671233c7c25029cd306c8438465618
29,358
def create_pif(headers, row): """ Creates PIFs from lists of table row :param headers: header data from the table :param row: the row of data :return: ChemicalSystem containing the data from that row """ sys_dict = {} keywords, names, units, systs = get_header_info(headers) sys_di...
25c69e69787d6abb173318d112e1fdcc7a400174
29,359