content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_weights(matrix): """ This function is used to find the weights of attributes as we get from the comparison matrices """ weight_vector = [[0] for k in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): weight_vector[i][0]+=matrix[i][j] weight_vector[i][0]=weight_vec...
1fbbe8a1b8be184f05484b6d3f9d9c71f9688c0f
76,798
def index_json_route(): """datatable data endpoint""" return jsonify({'data': dynamo.tables[TABLE_NAME].scan()['Items']})
2afde13bc553635064323e33ac0019a3dbcb0c54
76,800
def rdict(x): """ recursive conversion to dictionary converts objects in list members to dictionary recursively attributes beginning with '_' is converted to fields excluding the '_' """ if isinstance(x, list): l = [rdict(y) for y in x] return l elif isinstance(x, dict): ...
5da3d680b9ec191e5962ac4ce4469cbfef608ed4
76,801
def prepare_refs(refscheme, spcdct, spc_queue): """ add refs to species list as necessary """ if isinstance(refscheme, str): msg = 'Determining {} reference molecules for: \n'.format(refscheme) if is_scheme(refscheme): refs, newmsg = get_refs(spc_queue, spcdct, refscheme) ...
5ca590c0677617bd7540771bc7fd209c558bcf8e
76,802
def row_id_exists(cursor, table_name, row_id): """ :param cursor: the cursor to the database's connection :type cursor: Cursor :param table_name: the name of the table searching for :type table_name: str :param row_id: the integer value of the row in the table :type row_id: int :retu...
102ae1d011aa93d8ebada5321b45cb1aa7b7d452
76,803
def score_roll(roll): """Determines the numerical score for the given roll.""" if is_triple(roll): return roll[0] + 10 sorted_roll = sorted(roll) if sorted_roll[0] == sorted_roll[1]: return sorted_roll[2] if sorted_roll[1] == sorted_roll[2]: return sorted_roll[0] if s...
3f2b0e252b01bd9379cbdf5bac483250631208bb
76,804
import base64 def diff_kubernetes_secret(secret, desired_fields): """Computes a set of changed fields (either added, removed, or modified) between the given existing secret and the set of desired fields. :param secret: an existing secret as a KubernetesAPIResponse containing encoded se...
eb3d219a40bc68ba00d3d876aade936f8b062e75
76,805
def hydrate_datetime(seconds, nanoseconds, tz=None): """ Hydrator for `DateTime` and `LocalDateTime` values. :param seconds: :param nanoseconds: :param tz: :return: datetime """ minutes, seconds = map(int, divmod(seconds, 60)) hours, minutes = map(int, divmod(minutes, 60)) days, hou...
cc024c226253b82ea6c6a93fe39bec0c5e3bcd90
76,806
def find_indexes_where_lists_differ(list1: list, list2: list) -> list: """This function returns the indexes where the two input lists differ. THe input lists are expected to have same length Args: list1 (list): first input list list2 (list): second input list Returns: out_list (list)...
888d850b692a1920058f53a4617dcd08d5ed31cc
76,807
def get_squad_loss(labels, model_outputs, loss_factor=1.0): """Calculate loss for SQuAD task. Args: labels: one-hot label of (start_positions, end_positions) model_outputs: output of the squad model as (start_logits, end_logits) loss_factor: factor applied to loss calculation Returns: total_loss...
d5bef589ff1d94adad160fd63d2ec9d3aace610a
76,808
def UnfoldLabel(Dic: dict, Name: str) -> str: """ Unfold Patch label (e.g. "C1" -> "Inner Core Top") Parameters ---------- Dic : dict Dictionnary containing description of acronym characters Name : str patch label Returns ------- str Unfolded patch label. ...
5f2fb0613a7ce03a0e4a0b09752ed9f3d7635861
76,809
def for_each_chunk(regiondir, consumer, nbt_data=False): """ Calls consumer with each chunk stored in the regiondir (all region files). Parameters ---------- regiondir Directory (Path) containing the region files to read (will only look for files with the .mca suffix) consumer T...
2419054cecc81b26bf0941a3b7e56f3fe05e981f
76,810
from typing import Iterable from typing import Hashable from typing import cast def get_variables(ds: xr.Dataset, variables: Iterable[Hashable]) -> xr.Dataset: """ds[...] is very confusing function from a typing perspective and should be avoided in long-running pipeline codes. This function introduces a type-...
48b1c7a931b3083f03b6200c800e1ad30f4cc044
76,811
from typing import Dict def extract_core_electrons(cp2k_remote_folder): """Read from the cp2k.out the number of core electrons (included in the pseudopotential) and print them as a Dict """ with cp2k_remote_folder.creator.outputs.retrieved.open('aiida.out') as handle: content = handle.readline...
c7212909a34a717ce4ee93aa83f4b1fe424036c1
76,813
def _doub_hyb_dft_energy(output_str): """ Read the energy from double-hybdrid density functional theory methods from the output file string. Return the energy in Hartrees. :param output_str: string of the program's output file :type output_str: str :rtype: float """ e_patte...
3257fc2a6c853a6f92919818c342cae148d776af
76,814
def removeprefix(self: str, prefix: str) -> str: """ Backport of `removeprefix` from PEP-616 (Python 3.9+) """ if self.startswith(prefix): return self[len(prefix):] else: return self
109770b8467a3c1e86156e40f9735ade8f2d08aa
76,816
def S_to_T(S_list): """Converts S-parameters into a T Matrix. Input form should be in frequency, np.matrix([[S11,S12],[S21,S22]]) format. Returns a list in [frequency, np.matrix] format """ t_complex_list=[] t_matrix=[] for row in S_list: frequency=row[0] m=row[1] T11=-np.lin...
7a6121c0cea8f98815ae28368281b71b7efff7de
76,817
def object_location_Wears(x, world) : """Gets the location of an object by what currently wears it.""" locs = world.query_relation(Wears(Y, x), var=Y) if locs : return locs[0] else : raise NotHandled()
9046ed515d9359a6d35c835b179e54e7f6b4e45d
76,818
def error(string: str) -> F: """ Shows a formatted error message. --- Arguments --- string (str) Some string for the error message. --- Returns --- Formatter The formatted string. """ # Returns the formatted string. return F().bold().red(string)
5c6c6540d3521490cd5c076fcc13a0e6d89fc215
76,820
def Not(i: Bit) -> Bit: """ Not gate out = not in ``` +--------+ i +--+ | | NAND +--+ out i +--+ | +--------+ ``` """ return nirvana.nand(i, i)
379577c5bdf26093a2db9dd0e4f947305d7ed593
76,821
def get_ap(y_true, y_predict, interpolate=True, point_11=False): """ Average precision in different formats: (non-) interpolated and/or 11-point approximated point_11=True and interpolate=True corresponds to the 11-point interpolated AP used in the PASCAL VOC challenge up to the 2008 edition and has bee...
44aacf80c8eaa15497490d5be4f1aa1c6f526024
76,822
def lorentzian(x, area, center, sigma): """1 dimensional lorentzian Parameters ---------- x : array independent variable area : float area of lorentzian peak, If area is set as 1, the integral is unity. center : float center position sigma : float sta...
a11bbc4c692004b3111a56301da0f7eff7b45a09
76,823
def make_postback_action(data, label=None, i18n_labels=None, display_text=None, i18n_display_texts=None): """ make post back action. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/1005050?lang=en>`_ :param data: post back strin...
a31ae7870275be70faf885eb780121788aa35cf2
76,824
def get_language_with_alpha2_fallback(language_code): """ Lookup language code `language_code` (string) in the internal language codes, and if that fails, try to map map `language_code` to the internal represention using the `getlang_by_alpha2` helper method. Returns either a le-utils Language objec...
6a410fcefe96491d5d48d9c3091ab221e30b7531
76,825
import hashlib def hash_string(string): """ returns hash of bytes """ return hashlib.sha1(string.encode(encoding="utf-8")).hexdigest()
87b31dbf655077234eafcf98b7acbe573e7c0bf8
76,826
import logging def max_diff_centroids(old_centroids, new_centroids): """ Computes the difference from the old centroids for clusters and the new ones. Returns the max difference. """ max_dist = 0 for key in old_centroids: if key in new_centroids: sim = logic.similarity(old...
d06adb5cf1991f17b8bf80aefcb751eb6e376ae4
76,827
def apply_dehomogenization(pts): """Computes the dehomogeneous points, i.e. dividing by the last dimension. :param pts: DxN points :returns: (D-1)xN dehomogeneous points This will issue a RuntimeWarning if the last dimension is 0. The corresponding division result will be set to nan. If you're ...
e3389a60a54decb0ab9c620b72b40c88429720c5
76,828
async def upload_file(some_file: UploadFile = File(...), keep_alive: bool = Header(None)): """ Upload a file """ data = await some_file.read() return (some_file.filename, some_file.content_type, data)
cf5686dfc83179fc15ad2ea664bdc1b746ce2578
76,829
import math def LogicalAnd(x, y, target=utils.CUDA): """LogicalAnd.""" return math.LogicalAnd(x, y, target)
243d3844ee02c4d11598497dd75814e59d6b94f7
76,830
def point_in_circle(pnt, crc): """ Returns true if and only if the point is in the circle pnt: a Point crc: a Circle returns: True or False, when the point is in or out. """ dist_from_cent = distance_bw_points(pnt, crc.centre) if dist_from_cent <= crc.radius: return True else: ...
1220e136ae82603822a175da7482b95b8e371275
76,831
def oh_stretch_harm_loadtxt(cds): """Will try to load random.txt. Part of testing that Potential_NoMP works the way it is intended""" mass = Constants.reduced_mass('O-H', to_AU=True) omega = Constants.convert(3700., 'wavenumbers', to_AU=True) a = np.loadtxt('random.txt') return np.squeeze(0.5 * mass...
b37b9816903b36753bf62a3c48d732f2c000f935
76,832
def values_of(choices): """ Returns a tuple of values from choices options represented as a tuple of tuples (value, label). For example: .. sourcecode:: python >>> values_of(( ... ('1', 'One'), ... ('2', 'Two'),)) ('1', '2') :rtype: tuple """ ...
1b152cfab229d2eddd5bf0ff3cbf53954b1934e5
76,833
import urllib def create_authentication_path(username, datestring, token): """Returns path to Docebo SSO endpoint, with all necessary params. Args: USER_KEYS['domain']: Current user's email username: Email of current user datestring: Timestamp generated by create_datestring token: Valid h...
3ea4a50386072f0a435703dc3ead771c415d4442
76,834
def get_minio_notification_response( minio_client, bucket_name: str, prefix: str, suffix: str, events: list[str] ): """Start listening to minio events. Copied from minio-py.""" query = {"prefix": prefix, "suffix": suffix, "events": events} # pylint: disable=protected-access return minio_client._url_...
d28bf1bb40a7702a7174972b300c44701c0e45d6
76,835
def combine_testcases(log_url): """ This function combines the failed and passed testcases names """ pass_test_cases_names = get_pass_tests_name(log_url) fail_test_cases_names = get_fail_tests_name(log_url) return pass_test_cases_names + fail_test_cases_names
95372b67b6fc585b948b69654681d63842759d2b
76,836
def _has_opt_convergence_message(output_str): """ Assess whether the output file string contains the message signaling successful convergence of the geometry optimization. :param output_str: string of the program's output file :type output_str: str :rtype: bool """ pattern ...
7896f56b93b71ce07181e2e8f056feda29e8c221
76,837
import logging def shop_create(request): """ responds to the item create template if 'add multiple items' is selected on the submit button the same submission form will return else the list view will be returned """ logging.getLogger("info_logger").info(f"view entered | user = {request.user.us...
b8c47f934ce84db8762b1db09b5e0e2db248936c
76,838
def get_subscription(request): """Get the subscription status of the given page This is called to update the Subscribed? link in the top menu of the view page lazily. The POST data consists of 'trunk_id'; the service is expected to return the subscription status as 'status' in the JSON object it returns (1 ...
3a69bcf2dd97f4be23a7b8f5edf4e29b0ceb4418
76,839
def key_diff_something(first_data, second_data, format='long', key_sep=KEY_SEP): """ Determine key diff-set :param first_data: dict :param second_data: dict :param format: str ('short', 'long') :param key_sep: str :return: dict """ diffs = {'missing_keys': [], 'ex...
cbc252b8c94d3e1969a365eecd606c3a5097aa5b
76,840
def listparams(dms=[0], sizes=[50], windows=[5], mincounts=[2], workers=4, epochs=100): """ return: a list of parameter combinations """ return [{ 'dm': dm, 'size': size, 'window': window, 'min_count': mincount, 'workers': workers, 'it...
9b22c25b1ff71c048870585746e44e37226aea08
76,841
def applyxfm(src, ref, mat, out, interp='spline', **kwargs): """Convenience function which runs ``flirt -applyxfm ...``.""" return flirt(src, ref, out=out, applyxfm=True, init=mat, interp=interp, **kwargs)
72e4aafb1b02741503f132f3cb482e0b1d6fdfbd
76,842
import math def Tm_staluc(s,dnac=50,saltc=50,rna=0): """Returns DNA/DNA tm using nearest neighbor thermodynamics. dnac is DNA concentration [nM] saltc is salt concentration [mM]. rna=0 is for DNA/DNA (default), for RNA, rna should be 1. Sebastian Bassi <sbassi@genesdigitales.com>""" ...
7a40d1b9327f139e5bb1acba0fe612b29d0c66a1
76,843
def remove_stopwords(tokens): """ remove stopwords from tokens """ try: stopwords = nltk.corpus.stopwords.words('english') except LookupError: nltk.download('stopwords') stopwords = nltk.corpus.stopwords.words('english') return [t for t in tokens if t.lower() not in stopw...
e0945299a8e4b43a9327abc7b05e4f731ca95bbc
76,844
def generate_tasklocation_occurrences( # pylint: disable=bad-continuation task_location, OccurrenceModelClass=TaskOccurrence ): """ Generates TaskOccurrence objects using the TaskLocation timing_rule field It works this way: - gets the start_time from the timing_rule - only generates a...
f4628ae77900776b588138c86e86a7df9cd40f4c
76,845
def reconstruct_video_g(amp_video, original_video, levels=3): """ Function: reconstruct_video_g ----------------------------- reconstructs a video from a gaussian pyramid and the original Args: ----- amp_video: the amplified gaussian video original_video: the original video levels: the levels in the gauss...
0a80b07654528c5b39d4d1ca92a425f39eaca8e4
76,846
import sqlite3 def delete_all_person_comments(person_id): """Delete all comments for the specified person identifier. :param person_id: Person identifier (row identifier) :return: Boolean indicating success of database action. """ try: conn = sqlite3.connect(settings.database_name) ...
9567658278388bd0b44dc4b73067deb027fbf16f
76,847
from jwst.lib.set_telescope_pointing import compute_local_roll def change_header_pointing(header, ra_ref=0., dec_ref=0., pa_v3=0.): """ Update a FITS header for a new pointing (center + roll). Parameters ---------- header : `~astropy.io.fits.Header` Parent header (must contain `V2_R...
7ec1a73b2451cf3694a9dc681ba48794ef2bc80e
76,848
def parse(): """Parse input and return list of files. :return: list of input files """ description = "Generate typical sas plots with matplotlib" epilog = """freesas is an open-source implementation of a bunch of small angle scattering algorithms. """ parser = SASParser( prog="freesa...
5867af13221de08e5e42925faa6ac7368b3753ac
76,849
def create_contact() -> Response: """ API endpoint for contacts/create. Creates new contact by given username. :return: New contact serialized to JSON """ body = request.get_json() emails = body.get('email') if not isinstance(emails, list): email_list = list(body.get('email')) ...
b88889819467b5d85a07cc16ba20467603837367
76,851
import base64 def wrap(asset): """ Wraps the encrypted malicious code with its decrpytion key in base64 format, namely creates the executable part of virus. First exec() decodes the key and decrypts the code, second one executes the code with the provided globals """ encrpyted_asset, key = encrpyt_it(asse...
46ff73071c17775c90c1c5f906f806bc07f04e7e
76,852
def check_columns(board: list): """ Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa). Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns. >>> check_columns(['***21**', '412...
2dd4898c5cf3df63ff6174e8cfa1676e37a0c767
76,853
import torch import math def MI_matching(latent_stats, generative_factors, sensitive_latent_idx, latent_factors, storage=None): """ Supervised loss to match latent factors z with known generative factors v. Parameters ---------- latent_stats: torch.Tensor Mean, log-variance of latent ...
e77f0d633096ee0a8e0754f442e8fc38e3e7a30a
76,854
import importlib def get_version_string(module_str): """Returns the version string found in the top-level module. ``module_str`` should be a valid Python module name. __version__ will be extracted from the top-level module and returned. For example, if ``module_str`` is 'foo.bar.baz', ``foo.__versio...
2e584848d92fa08e88e185019d5c8b3d80ae66e1
76,855
import warnings def check_primer_seq(seq_list, primer, position): """ Check if primer is in every given sequence and at the right position. Parameters ---------- seq_list : list List of sequences primer : string position : position of the primer in the sequence Returns -...
112338810aff7a61c1eb600e111a313b5cc407a6
76,856
import re def estimate_investment_net_worth(results): """Currently only using investment table to calculate net worth""" key_codes = { "A": [1, 1000], "B": [1001, 2500], "C": [2501, 5000], "D": [5001, 15000], "E": [15001, 50000], "F": [50001, 100000], "G...
a5b0134ab428f0b0f3f3f3ba0d2391325fff87b1
76,858
def user(username): """View function for the user profile page. May become deprecated as there isn't much use for it, except for listing specific posts.""" user = User.query.filter_by(username=username).first_or_404() posts = find_users_post(user) for post in posts: post.set_age() r...
3b33e09169ad498b66954e2160b7a353da02d6ae
76,859
def units(lang="en_US"): """ Cached unit object """ return Units(lang)
0d90a0b6f30775162c850a29812c2dedfc2c040a
76,860
from re import X def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the variance of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.var` for full documentation. ...
a285e51a9f4372d252162c9a248616a09a2f321e
76,861
def get_reserves(web3, token0_name, token1_name): """get the reserves, in tokens, of a particular uniswap v2 pool""" exchange_address, first_token_name, second_token_name = getExchangeAddressForTokenPair(token0_name, token1_name) exchange = web3.eth.contract(address=exchange_address, abi=exchange_abi) r...
691c51b82ff8d27c170362b0309e3b5c72fed461
76,862
import requests def distance_address(): """ This function is use for calculating the distance between points and seeing whether the destination point is inside or outside the MKAD (Moscow ring road) """ if not request.is_json: msg = "You have to send data in json format" app.lo...
7b0186d747f4b3a7b71c6b9aa646bdb3905befd4
76,863
def build_custom_cnn(n_freq_cnn=128, n_frames_cnn=50, n_filters_cnn=64, filter_size_cnn=(5, 5), pool_size_cnn=(2,2), n_classes=10, large_cnn=False, n_dense_cnn=64): """ Function that returns the S-CNN [1] model. [1] J. Salamon, D. MacConnell, M. Cartwright, P....
43c98dbafddc07c265759a296053106c57caee0e
76,864
def objc_provider_framework_name(path): """Returns the name of the framework from an `objc` provider path. Args: path: A path that came from an `objc` provider. Returns: A string containing the name of the framework (e.g., `Foo` for `Foo.framework`). """ return path.rpartition("/")...
cafb53a64cc8654a992d325faa34721a19d5a38a
76,865
def binary_search_iteratively(ls: list, item: object) -> bool: """Iteratively binary-searches for item in the ls, which is assumed to be sorted in increasing order. It returns the index such that ls[index] == item, if item is in the list ls, otherwise it returns -1. Time complexity: O(log(n)).""" ...
bc86aba22ed83ca6a8f224b463788c91a2ab8918
76,866
def logout(): """ handles logic for user logout calls flask_login logout_user() once call is complete message is flashed and the user is redirected to the index @return: response obj @rtype: werkzeug.wrappers.Response """ logout_user() flash('You have been logged out', category=...
338a5602fe096b1ff8aad3a59a707f0e208d31c5
76,867
def hexWithoutQuotes(l): """ Return a string listing hex without all the single quotes. >>> l = range(10) >>> print hexWithoutQuotes(l) [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9] """ return str([hex (i) for i in l]).replace("'", "")
2700a4c2e3a4981f1cac241d774d0a9b3534189c
76,868
import math def build_inf_graph_2_groups_disconnected(num_agents: int, influence_value : np.float64, diagonal_value : np.float64 = 0) -> np.ndarray: """Returns the influence graph for for "disconnected" scenario.""" inf_graph = np.zeros((num_agents, num_agents)) middle = math.ceil(num_agents/2) inf_gr...
d060bafa9b09afeb6bf7e1388ca551a96f509b63
76,869
def load_png_qImg(pngPath, width): """ load the Obie logo """ # load the logo and read all channels (including alpha transparency) logo = cv2.imread(pngPath, cv2.IMREAD_UNCHANGED) # swap color channels for Qt logo = cv2.cvtColor(logo, cv2.COLOR_BGRA2RGBA) # resize to a known width main...
3d689fdf3a092e3532b60f06fd3d6cb81eb94843
76,870
from typing import Iterable from typing import List def merge_crosslistings(courses: Iterable[Course]) -> List[MergedCourse]: """Merge cross-listings of the same course in a collection of courses""" course_groups = defaultdict(list) for course in courses: course_groups[(course.year, course.course_...
35d0462c23fb8e6941eb939e972112f35be32285
76,871
def mask_covering_gaussians(means, fwhms, n_channels, remove_intervals=None, range_slices=False, pad_channels=10, min_channels=100): """Define mask around fitted Gaussians for goodness of fit calculations. This is currently not in use in GaussPy+. Parameters ---------- ...
03e6f73dbb84db225329352941c2513c290ed217
76,872
import pickle def trainModel(model, df_x, df_y): """It splits the data into test and train. It only trains the model in the train data. Input: model: (str) key of one of the implemented models at runLearningModel(). df_x: (pd.DataFrame) feature matrix. df_y: (pd.DataFrame) label ma...
6a86770dedcaa60d659b664d36b7e76dc91446c5
76,873
import copy def merge_channels(spectrum_list): """Merges spectra""" intensity_arrays = [] mz_arrays = [] for index, spectrum in enumerate(spectrum_list): intensity = np.array(spectrum.parameters['intensity array']) mz = np.array(spectrum.parameters['m/z array']) mz_arrays.appen...
3ffa09c073b43dfe607816fc453905878a643dd2
76,874
def get_subreddits(): """ Fetch user subreddits otherwise fetch a list of defaults """ if g.get('user'): subreddit_subs = g.user.subreddit_subs.get('subs') subreddits = Subreddit.query.filter(Subreddit.name.in_(subreddit_subs)) else: # Default set of subreddits subred...
dd070e54a0eba0f683215eaa8abca5819df2ad49
76,875
import logging def get_local_frames_iter(video_path, max_number=None): """ This function returns a iterator of frames of test videos. It is used for local test of participating algorithms. Each iteration provides a tuple of (video_id, frames), each frame will be in RGB color format with array shape of...
460564f038e6823f7a9ccb15c3a04f0f712990ca
76,876
import re def clean_server_response(d): """cleans the server reponse by replacing: '-' -> None '1,000' -> 1000 :param resp_dict: """ for key, value in d.items(): if type(value) is str or isinstance(value, str): if re.match('-', value): value = No...
55a3a02e1be3502ebc8a7a7b5511e57ab3ec24f5
76,878
import re def is_jenkins_command(comment): """ Returns True if the comment consists solely of Jenkins commands. This is heuristic-based; it's easy to identify the presence of Jenkins commands, but trickier to also match surrounding context that's part of the command, such as "Jenkins, ...". S...
13d289493f33b325ef01d8c03be2442a6bd1c256
76,880
from multiprocessing import Process def run_in_subprocess(func, *args, **kwargs): """ 多进程工具函数,不涉及返回值等细节处理时使用 :param func: 被进程委托的函数 :return: 返回multiprocessing进程对象 """ process = Process(target=func, args=args, kwargs=kwargs) process.daemon = True process.start() return process
a2a3586ab8975102b38f6caf2b07984287cc4f7c
76,882
def guess_2D_gauss(data): """Gives an initial guess for the parameters of a 2D Gaussian. Paramters ----------- data : nd array the data to guess paramters for Returns --------- parameters : list contains amplitude, xCenter, yCenter, xWidth, yWidth, offset, rotat...
79d7c089d8be94c25e5431eae00dc1f7bb2dfe31
76,883
from datetime import datetime def plotImageMap(fig,m,ax, xgrid,ygrid,z,time=0,clim=[],cmap='jet', save_dir='', totality=False, raw_image=False, euv_mask=False, moon=False, euv_gradient=False): """ Plot the image on the basemap """ title = datetime.datetime.utcfromtime...
793e11b0d0b1aec305d66727f370879798624c64
76,884
from typing import Optional def censor(text: Optional[str]) -> str: """ Replaces characters in a str by the asteriks text: The text to censure. """ char = "*" text = text if text else "" return text[0] + (len(text) - 1) * char if text else text
fa93653065611e6842e3162bf1fb245d81651418
76,885
def model_from_slug(product_line, model=None): """ Returns product description for model slug or models dict for the specified product line """ if not cache.get("slugmap"): slugmap = {} # Map model slug to corresponding product description product_lines = gsxws.products.models() ...
05eae45733b36bd87901f46dca153110a0ab5379
76,886
def _tf_lcs(x, y, m, n): """ Computes the LCS between two truncated seqs. The implementation below uses a DP programming algorithm and runs in O(mn) time where m = len(x) and n = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: first seq y: s...
6ad0b75b01a33121991490303baff58ad5480951
76,887
def getMaximum3DRegion(binary): """ Get the Maximum 3D region from 3D multiple bindary Regions""" all_labels = measure.label(binary, background = 0) props = measure.regionprops(all_labels) areas = [prop.area for prop in props] maxArea_label = 1+np.argmax(areas) max_binar...
908e37f0b199735ea5b6c870286904c55a943a78
76,889
def _check_deps(module, validate): """Check app:endpoint dependencies.""" deps = set() errors = [] for (appname, app) in module.apps.iteritems(): for epname in app.endpoints: endpt = app.endpoints[epname] for (_, call) in syslalgo.enumerate_calls(endpt.stmt): ...
654272aa32b4253ca20efa2b1297d97d4036ba00
76,890
import six def normalize_params(params): """ Return copy of params with strings listified and unicode strings utf-8 encoded. """ # urllib cannot handle unicode strings properly. quote() excepts, # and urlencode() replaces them with '?'. def encode(value): if isinstance(value, six.t...
952b101a674077d213217a449f2aeb7e5100c004
76,891
import json def extract_session_parameters(response_json: str): """Extracts session parameters from the json response of a Dialogflow webhook.""" response = json.loads(response_json) return response["session_info"]["parameters"]
45cde22d7271512e4f90fc3078c327c9ccbd86b0
76,892
def _keypoint_camera_to_world(keypoints, camera_params, image_name=None, dataset='Body3DH36MDataset'): """Project 3D keypoints from the camera space to the world space. Args: keypoints (np.ndarray): 3D keypoints i...
c0b6fce4a42096711474d037f2c5df64c05fbc6f
76,893
def _get_mapping_from_secret_type_to_class_name(): """Returns secret_type => plugin classname""" mapping = {} for key, value in globals().items(): try: if issubclass(value, BasePlugin) and value != BasePlugin: mapping[value.secret_type] = key except TypeError: ...
89c42673b72941e99cdfe854ea9dd8e50bb746eb
76,894
def scalar_multiply(c, u): """ return the vector u scaled by the scalar c """ return tuple((c * a for a in u));
9ace577e852179893e90544754b8010d3476f3ae
76,895
def open_cam_usb(dev, width, height): """Open a USB webcam.""" return cv2.VideoCapture(dev)
2fe74fd35996439c78cb88118eb494012f700f66
76,896
from typing import Sequence def make_surfaces_lattice(self:trains.Train, lattice: mathx.Lattice, boundary: _boundaries.Boundary = None, names: Sequence[str] = None): """Make optical surface for each interface with lattice surface profiles. The surfaces are placed along the z axis. Args: lattice:...
0862ad8471c80ff369f73c3cc467393d66e319af
76,897
import inspect from typing import Dict from typing import Any def _build_float_option(parameter: inspect.Parameter) -> Dict[str, Any]: """Provide the argparse options for a float option.""" params = { "type": float, "default": None if parameter.default == parameter.empty else parameter.default...
24d52b19f298a14484b62ba7ebf7a6436ead0394
76,898
def fibonacci(n): """Return the nth number of the fibonacci series.""" if n is 1 or n is 2: return 1 return fibonacci(n - 1) + fibonacci(n - 2)
904bce9c8a23a0ae8c8f7c8cf9262de8b9b55a48
76,899
from google.cloud import bigquery def get_bigquery_client(credentials: dict = None, project: str = None): """ Utility function for instantiating a Google BigQuery Client from a given set of credentials. Args: - credentials (dict, optional): a dictionary of Google credentials used to initialize ...
29d49ab7faf9021ea94f774bba47306e178fbbee
76,900
def sslcan_del(request): """ :param request: :return: """ if request.method == 'POST': scan_id = request.POST.get('scan_id') scan_item = str(scan_id) value = scan_item.replace(" ", "") value_split = value.split(',') split_length = value_split.__len__() ...
96236e5a8108ff35e6468dbf21070471ce849fe5
76,901
def train(target_network, optimizer, states, actions, next_states, rewards, terminals, kappa, num_atoms, cumulative_gamma, double_dqn): """Run a training step.""" def loss_fn(model, target, mean_loss=True): logits = jax.vmap(model)(states).logits logits = jnp.squeeze(logits) # Fetch the logits...
a8d37bd63e53da921e3f9f87a6c23ae9147d6966
76,902
from typing import Optional def init_statistics_router(stats: Optional[OpalStatistics] = None): """initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what topics are they registered. If the OPAL server does not hav...
fbd0eb2f308326e20a9a66a598b15d9bc5f62337
76,904
def grouper_orig(cc): """grouper based on gaps in timestamps""" diffs = cc.timestamps().diff() grpr_orig = (diffs>cc.timedelta).cumsum() grpr_orig.name = 'g_orig' return grpr_orig
ecc755be0d107a3ac86c35069546ac920c4d42ce
76,905
def find_value1_value2(liste, value): """ finds the next smaller and larger value in a list for a passed value. :param liste: list to be searched :param value: value :return: lower value, upper value and index """ tmp_array = np.array(liste) index = np.where(tmp_array > value)[0][0] ...
8f6d9af8c39a00f3dfa71f963a1a2743153aaa4b
76,906
def event_file(): """ Create filepath including file name for Twitch Toolkit Events file Returns: str: complete path to StoreIncidents.json """ path = settings.get_toolkit_path() if path[-1] == '\\': path = path + 'StoreIncidents.json' else: path = path + '\\StoreIn...
05c41f86b416340db56dc8b299863360128ff1db
76,907
def try_build_plain_route(pattern, finishing=True, kwargs=None, name=None): """If the plain route regular expression match the pattern than create a PlainRoute instance. """ if isinstance(pattern, PlainRoute): return pattern if pattern == "" or RE_PLAIN_ROUTE.match(pattern): return P...
edd327b7e888eb49702ff51e8cecffe3c97f8ed9
76,909