content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import calendar def animated_doubletimeseries(ds1, ds2, output_path, width_pixels=1000, interval=200, bands1=['red', 'green', 'blue'], bands2=['red', 'green', 'blue'], percentile_stretch1 = (0.02...
743dc48299ec6c98ac6f6ed0de91e29543315f35
80,408
def calc_stats(data): """ Calculate statistics for use in violin plot. """ x = np.asarray(data, np.float) vals_min = np.min(x) vals_max = np.max(x) q2 = np.percentile(x, 50, interpolation="linear") q1 = np.percentile(x, 25, interpolation="lower") q3 = np.percentile(x, 75, interpolati...
2a17d4b8ef0a31ce61fdaddd621c5501933a1c06
80,409
def get_disease_auc(dis_embeddings, dis_path, plot=False): """ Calculate disease similarity AUC metrics :param dis_sim: disease embeddings matrix :param plot: whether to draw ROC :return: AUROC, AP score """ dmap, _ = load_dmap(dis_path+"/dis2id.txt") pos_data = load_xlsx(path_pos, dmap)...
f5e6177029f26d0af7b5df2b2412f456259da5d4
80,410
def rle_encode(mask): """ Convert mask to EncodedPixels in run-length encoding from https://www.kaggle.com/stainsby/fast-tested-rle-and-input-routines Args: mask(np.array): mask to be converted """ pixels = mask.T.flatten() # We need to allow for cases where there is a '1' at either...
049fc399d74e5f0d0277bb2726a81b283cc6cb72
80,411
def get_authorization_key(request): """ Get the Authorization Key from the request """ auth = request.headers.get('Authorization') if auth: auth = auth.split() if len(auth) == 2: if auth[0].lower() == 'key': return auth[1] return None
5cba14bdebb4b203c773c1e0832373114e554c78
80,412
def text_to_set(text): """ take a text and return a set of all contained words """ s = sets.Set(text.split(' ')) s.discard('') return s
f7073f68cf203d1862a45601c41484af7e0acbaa
80,413
def reactor_efficiency(voltage, current, theoretical_max_power): """Assess reactor efficiency zone. :param voltage: voltage value (integer or float) :param current: current value (integer or float) :param theoretical_max_power: power that corresponds to a 100% efficiency (integer or float) :return:...
b58fe806da2bcfdabc12bd3f5b36a0b296ce7142
80,414
def process_search_results(results): """ Transform result representation from the output of the widget to the test framework comparison representation. """ matches = {} for result in results.values(): file, line, col, __ = result filename = osp.basename(file) if filename ...
429243e0ef06b709bc7bc26cddbc91eda632d2f0
80,415
def read_data_csv(path): """Read the csv data from the specified path. Args: path (string): path to the csv file Returns: DataFrame (df): DataFrame Object """ df = pd.read_csv(path) df.drop(["Unnamed: 0"], axis=1, inplace=True) return df
e65ca93401a7e2d59e5e31bec599ab26be07d620
80,417
def _bubbled_up_groups_from_units(group_access_from_units): """ Return {user_partition_id: [group_ids]} to bubble up from Units to Sequence. This is to handle a special case: If *all* of the Units in a sequence have the exact same group for a given user partition, bubble that value up to the Sequen...
a4e3c5ee563d65bc3b8c787512efe356abfdfbd6
80,418
def make_settings(write_config_file): """Return a factory function for settings.Settings with defaults.""" default_config = """ [pypi] username:foo password:bar """ def _settings(config=default_config, **settings_kwargs): config_file = write_config_file(config) ...
654668b8d6e0b047d54c9c2e673bbbe7457eb77d
80,419
from typing import Dict def get_agent_details(agent_key: str) -> Dict: """Sends an API request with the agent key, and retrieve the agent information. Args: agent_key: the agent key in the form : agent/org/name Returns: dictionary of the agent information like : name, dockerLocation.. ...
0021fef435bef7111ded00c239c11c95b20be20c
80,420
def armed_forces_per_year_by_country(country): """Returns the armed forces personnel (total) per year of the given country.""" cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="MS.MIL.TOTL.P1"'.format(country)) armed_forces = cur.fetchall() cur.close() ...
8e6256b8e6b9a1dd4f2501fe60c69debf365c6e7
80,421
def is_list_with_max_len(value, length): """ Is the list of given length or less? :param value: The value being checked :type value: Any :param length: The length being checked :type length: Nat :return: True if the list is of the length or less, False otherwise :rtype: bool """ retu...
fd5016617d264b79ee4e4a0dae7782776d997fc5
80,422
def dhdP_h(P, h): """ Derivative of equilibrium specific enthalpy [kJ m^3 / kg kJ] w.r.t. pressure @ a given equilibrium enthalpy""" x = x_h(P, h) return x * dhgdP(P) + (1 - x) * dhfdP(P) + dxdP_h(P, h) * dhfgdP(P)
2d749cf13bbc81090f584acdaf633227a288bbe4
80,423
import numpy def layer_localized_inverse(self, x, y, y_prime, verbose=False): """Computes a localized inverse around the point x for a given layer as the concatenation of the localized inverses of each node contained in the layer This is a slightly modified version of mdp.hinet.Layer.inverse """ ...
7dbbcd73117f3944fe34ebdfbee270b0d88e4fe7
80,424
def exists_transcript_id(db, transcript_id): """ Search bar MongoDB: db.transcripts.find({'transcript_id': 'ENST00000450546'}, fields={'_id': False}) SciDB: aggregate( filter(transcript_index, transcript_id = 'ENST00000450546'), count(*)); Sci...
3a9588040e6e3fb7c2c0a78c0038aa873c1670b6
80,426
def _guess_label_from_rule(rule): """Guess pod, xar, or image label from build rule. For example, //pod/foo:bar/build becomes //foo:bar. """ name_parts = rule.name.parts ASSERT( len(name_parts) == 2 and name_parts[1] == 'build', 'expect pod, xar, or image build rule: {}', ru...
5699fc74e26044f37c66b7b7fd777fce3f7941ff
80,427
def macro(name): """Decorator to define a macro called `name`. This stores the macro `name` in the namespace for the module where it is defined. If the module where it is defined is in `hy.core`, then the macro is stored in the default `None` namespace. This function is called from the `defma...
2bcacd7120f1a09e5b39dd688f145d20b337429e
80,428
def search(*args, **kwargs): """(Public) Filters and list tags Use this method to get a list of tags based on a general search of terms. For example, calling this method with terms=v1&terms=0 returns all tags with 'v1' and '0' on the 'name' or 'description' fields. The response returns a pagination...
c0d5188bd0f053ee7c5f14bf9c436fc89c3cdbd5
80,429
def split_data_to_chunks(data: list, max_chunk_size: int, overlapping_size: int): """ Because GP can take very long to finish, we split data into smaller chunks and train/predict these chunks separately :param data: :param max_chunk_size: :param overlapping_size: :return: list of split data ...
370e9fe9a17c58d7dca202bb4c822f9b8b662fae
80,431
def read_moves(file_name): """Read moves from file. Move features are pipe-separated. Returns moves and keys as lists (every move is a dict at this point).""" moves = [] with open(file_name, encoding='utf-8') as f: first_line = f.readline() first_line = first_line[1:] # remove '#' at th...
a87b73feaf7d49b3ece716fe5732f5647e5dcd25
80,432
from typing import Dict def get_user_auth_alias(user_id: int, exchange_name: str) -> Dict[str, str]: """Fetches user exchange auth data and returns the catalyst auth alias Args: user_id (int): strategy's user ID exchange_name (str): name of exchange to to authenticate Returns: st...
c62408357b2787dce510b6d410a09778a8eb76fa
80,433
def knight_moves(start): """ Allowable knight moves based on position """ places = [] for dx in range(8): for dy in range(8): checkx, checky = [abs(n - start[ind]) for ind, n in enumerate([dx, dy])] ...
a3ddcf8d8b10b120a8fb3b1d12e026b4acaef259
80,434
def _get_request_ip(request, default=''): """Helper method to get IP from a request's META dict, if present.""" if request is not None and hasattr(request, 'META'): return get_client_ip(request)[0] else: return default
7d64f7767db33c54281636169e32713f2859197b
80,436
def hoppingy(site0, site1, p): """ Nearest-neighbor hopping term in Hamiltonian, y-direction : """ return -p.ty*tau_z - 1j*p.alphahbar/(2*p.ay)*sigma_xtau_z
f2d2fbd39b218906f1c23bd60f4ed6cb6c8664e1
80,437
def number_of_constituents(bc_class): """ Calculates the number of constituents Args: bc_class: The ADH simulation class that holds all simulation information Returns: The number of transport constituents """ num_trn = 0 cn = bc_class.constituent_properties if cn.salin...
b290bc6ef6f4b02889dcc82d91120f44bff5f650
80,438
import array def getNeighbours(image,i,j): """ Return an array of <=9 neighbour pixel of an image with a center at (i,j) """ nbg = [] for k in arange(i-1, i+2): for l in arange(j-1, j+2): try: nbg.append(image[k,l]) except BaseException as e: ...
1b43cce518020b701046fb7c66ee12577f42500c
80,439
def xsd_append_nofilter(annotation_el): """Returns Boomi XML Schema no filter annotation appended to the given parent element.""" child_el = append_child(annotation_el, XSD_APPINFO_NAME) filter_el = append_child(child_el, XSD_FILTER_NAME) filter_el.attributes[XSD_ATTR_FILTER_XMLNS] = XSD_FILTER_NS ...
1bb58d5b89ed7e91ca9c14705f3bd990a8ea022e
80,440
def login(user_name, password): """ Function to login """ verified_user = Credentials.verify_user(user_name, password) return verified_user
4891777962f9be7779bca7f321fa2043abd1cc57
80,441
def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: person = Person.objects.get(pk=pk) except Person.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PersonSerializer(person) return JsonRe...
11d83869499745946a7b14a577f1b495c19193a1
80,442
def print_single_vs_multi_performance( mstr_bepoch_list, base_dir, features, template, event_independent, metric_type="micro", data_type="test", span_type="pred_span", part="overall", ): """ Args: part: classification, entity, combination, rawCombination, overall ...
4319de2c70a31c14590f4005cb50a06ffedba218
80,443
from typing import Optional def gen_game_weighted( numbers: np.ndarray, stars: np.ndarray, numbers_prob: Optional[np.ndarray] = None, stars_prob: Optional[np.ndarray] = None ) -> np.ndarray: """Generate a game based on probabilities. Parameters ---------- numbers : np.ndarray ...
8cab194dbd49f143f1f873b56b5b84e4ae54e209
80,444
def nmf_adisdi(cube, angle_list,scale_list=None, cube_ref=None, ncomp=1, scaling=None, max_iter=100, random_state=None, mask_center_px=None, imlib='opencv', interpolation='lanczos4', collapse='median', full_output=False, verbose=True, **kwargs): """ Non Negative Matrix Factorization for ADI ...
ed402ab011fb570c2dc89130a11db8a830277eb0
80,445
def is_hydrophilic(atom): """ Checks whether an atom belongs to hydrophilic residue :param atom: atom :return: True if the atom belongs to hydrophobic residue, otherwise false """ hydrophilic_atoms = ['H', 'N', 'S', 'O'] hydrophilic_residues = ['GLU', 'ASP', 'ASN', 'QLN', 'HIS', 'GLN', 'SER...
ac366f13934ce859eb9822855481fa7c2a49d21c
80,447
def infectious_rate_tweets(t, p0=0.001, r0=0.424, phi0=0.125, taum=2., t0=0, tm=24, bounds=None): """ Alternative form of infectious rate from paper. Supports bounds for r0 and taum. Bounds should be passed as an array in the form of [(lower r0, lower taum), (upper r0, upper taum)]. Converted to hours. ...
28b2db80d18cd31b362b41bb8d98c8685aebc871
80,448
from typing import Optional def from_utf(buffer: 'Optional[bytes]') -> str: """ Превращаем буфер ctypes в обычную строку. :param buffer: буфер :return: декодированная строка """ if buffer: return buffer.rstrip(b'0').decode(UTF) return ''
b37eb2c9623cfd90abb65fff6c3e66ce7394fa01
80,449
import ctypes import locale def getWindowsLanguage(): """ Fetches the locale name of the user's configured language in Windows. """ windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage() try: localeName=locale.windows_locale[windowsLCID] except KeyError: # #4203: some locale identifiers from Windows ...
9e74ff2fbbdeb9d21451a808f92034eb6ffe051e
80,450
def text_recognize(_image_info, _box_info): """ 文本识别 Args: _image_info: 待识别的完整图像 _box_info: 图像中文本区域的位置 Returns: 文本区域位置的识别结果 """ to_return_result = {'text': ''} oss_handler = get_oss_handler() img = oss_handler.download_image_file( _image_info['bucket...
db62c7af453cdec773fd0ece90504d3dfd15c5fe
80,452
def is_supported_str_dtype(data): """Return True if data type is a string type supported by preview""" return data.dtype.name.startswith("string") or is_single_str_array(data)
9b861ea9035db1156e4ee9de7b5d444b75ea9e06
80,453
import math def propagate_plane_to_curved_flat_arbitrary(k, rs_support, Eri, z, xo, yo, qs_center=(0, 0), kz_mode='local_xy'): """Propagate from uniformly sampled plane to arbitrarily sampled curved surface. Args: k (scalar): Wavenumber. rs_support (scalar or pair of): Input aperture along x ...
9e880f9ce4d271583e1f26f3497cb378ff4521c1
80,455
import types def optimize(objective_function, domain, stopping_condition, parameters=None, position_update=functions.std_position, velocity_update=functions.std_velocity, parameter_update=functions.std_parameter_update, measurements=(), mea...
3fb28f1f471cc3e0dd911c3a717d2992dfabcb80
80,456
def after_folder_option(location): """location: folder full path""" return True
a2cdb5de2a6852964ecc7e71acbcd0ee2c6b92a8
80,457
def sidebar(parent_region="BR", where=st.sidebar): """ Collect input parameters for the app to run. Returns: Dictionary with the following keys: parent_region, regions, columns, targets, days """ st = where kind = st.selectbox(_("Select scenario"), list(REGIONS_TYPES[parent_...
e76966acacb91d0a398e4a002768b26686938d36
80,458
import pycountry def language_name(value): """Jinja2 filter to get language object from language code.""" return pycountry.languages.get(alpha_2=value)
78cc9a1f13a6faf63cad75738a2e56813fbfe2a4
80,459
def validate_seed(seed): """Validate a NANO seed and raise an exception on failure :param str seed: Seed as a 64-character hex string :raises InvalidSeed: If the seed is invalid :return: The seed :rtype: str """ if len(seed) != 64 or not is_hex(seed): raise InvalidSeed("Seed must be...
4edf286a332a6ca5d4e88cda98374b8de03974df
80,460
def calc_mutual_information(x, y, bins): """ Calculate the mutual information between two continuous random variables Parameters -------------- x : An array of floats y : An array of floats bins : An int, the number of bins for performing a 2D histogram on (x,y) Returns -----------...
c8e5c329eec5e6c2fe72ecad3eefe3c0c782c67b
80,461
def circle_distance_circle(circle, other): """ Give the distance between two circles. The circles must have members 'center', 'r', where the latest is the radius. """ d = abs(circle.center - other.center) - circle.r - other.r if d < 0.0: d = 0.0 return d
c76146d1ec9003be5345b14b12563dfb8bac7798
80,462
import functools import jinja2 def _RenderTemplate(template_subdir, template_name, **context): """Loads a template file and renders it to unicode. Args: template_subdir: The subdirectory in gae/templates containing the template file. template_name: The name of the template file. **context: Op...
946e3e015713832893ae8f4a37f4ec3e168a33de
80,463
def get_zip_data(zip_code): """ Get the county code based on the zip passed """ # if it isn't a valid zip format or someone passed None, just toss back nothing if not zip_code or not valid_zip(zip_code): return None zip_data = None # if the 5-digit zip is in our list at all, then check deta...
d34c7eeb66dead6680c569fa762eaaf8680d4879
80,464
def _info(): """ :returns: process return code :rtype: int """ emitter.publish(default_command_info("help")) return 0
ca964eeaaa803d8b37061a081ceb927d537083fb
80,465
def next_batch(): """ Modify this function to ingest your data and returns it. :return: (inputs, targets). Could be a python generator. """ x = np.expand_dims(uniform(size=32), axis=1) y = np.expand_dims(np.expand_dims(np.mean(x), axis=0), axis=0) # should be close to 0.5 return x, y
a642b086add86562fcae091312b929e8f9778418
80,466
def make_salt(password: bytes, iterations: int = DEF_ITS_SALT) -> (bytes, int): """make_salt: Takes password bytes and hashes iterations times to produce a salt sha256(password) -> sha256(result) -> sha256(result) until iterations Returns (salt bytes, seconds (zero if less than DEF_VERBOSE_TIME)) """ ...
f590237c72db404cfdc9075908ded08f0efb2ca0
80,467
import logging def get_logger(name: str) -> logging.Logger: """Returns a logger with the proper logging level set. See :class:`.LoggerProvider`. :param name: Logger name, e.g. `__name__` of the caller. """ return LoggerProvider().get_logger(name=name)
de44260c9076f4d7a17e5e9741b915d7f6be1f5e
80,468
def generate_qe_params(structure, settings, pressure=0.0, type=None): """ Generate the input parameters needed to run a calculation for PW (Quantum Espresso) :param structure: StructureData object containing the crystal structure :param machine: ParametersData object containing a dictionary with the...
ddbe9cd792b38e27942f90069061e7e47d1b990c
80,469
def class_to_json(obj): """ eturns the dictionary description with simple data structure (list, dictionary, string, integer and boolean) for JSON serialization of an object """ return(obj.__dict__)
8bac6f68d8fc18b1a80800943bede4106f618e6c
80,470
def create_people_profile_acl(conn, profile_id, ac_role_id): """Create new people_profile_acl""" sql = """ INSERT INTO access_control_list( object_id, object_type, ac_role_id, created_at, updated_at ) VALUES ( :object_id, :object_type, :ac_role_id, NOW(), NOW() ) """ conn.execute( text...
66f8297135e1a85ecfec544e006cc807f29de8e1
80,472
from typing import Dict def piecewise_constant_schedule( init_value: float, boundaries_and_scales: Dict[int, float] = None): """Returns a function which implements a piecewise constant schedule. Args: init_value: An initial value `init_v`. boundaries_and_scales: A map from boundaries `b_i` to non...
10a050d4c0b9075c81394b181489084b0d29a176
80,473
def Sound_Stop(*args): """Sound_Stop()""" return _misc_.Sound_Stop(*args)
fbcb606d2d6640f1d58617530de165b2c43375c4
80,474
def ocr(image_file, text_file): """Run.""" img = Image.open(image_file) text = pytesseract.image_to_string(img) with open(text_file, 'w') as fout: fout.write(text) fout.close() return text
cc6b154853980c42cbca6541a4ae55c38333944a
80,475
def parse_configs(input_configs): """Parse configuration values set via command line. Parameters ---------- input_configs: list of str list of configurations provided via command line. Returns ------- pass_context_configs: dict a dict containing key-value configs to be used...
8de5ed214ae83729210951856a8ab7b72da7ac83
80,476
def GaussianBlur(frame: np.array): """Computes GaussianBlur on input frame. GaussianBlur is used to filter out small variations from frame to frame in the order of a few pixels, we apply Gaussian smoothing to average pixel intensities across a 21 x 21 region. This helps to smooth out (and hopefully rem...
0791789ee9ce4384b1900574a69cbd2f549af10f
80,477
def identity(payload): """Find user from its id.""" user_id = payload["identity"] return UserModel.find_by_id(user_id)
57f1a18925201b5ddce7cd33adf98679e02fba51
80,478
from analyser.common.targetstatecontroller import TargetState def loadTargetState(targetStateConfig, existingTargetState=None): """ extracts a new TargetState object from the specified configuration :param targetStateConfig: the config dict. :param existingTargetState: the existing state :return: ...
c3f3f832fcd70138eda767833f018fe694578331
80,479
def rankdata(da, dims=None, method=None, **kwargs): """Wrap and extend :func:`scipy.stats.rankdata`. Usage examples available at :ref:`stats_tutorial` See Also -------- xarray.DataArray.rank : Similar function but without a ``method`` argument available. """ rank_kwargs = {"axis": -1} ...
1d53d34e9d48842dd3ecf9c2e55c9e1fd434ab9a
80,480
import pandas import numpy def forecast_NL(df: pandas.DataFrame): """ Applies testcount interpolation/extrapolation. Currently this assumes the OWID data, which only has an "all" region. In the future, this should be replaced with more fine graned data loading! """ # only weekly total_tests are a...
ec5daf8859d61ac65082e655b4b8949582d46d56
80,481
from typing import Dict import json def get_class_probabilities( probas: np.ndarray, out_path: str, cls_file: str, top_k: int, save_as_json: bool, ) -> Dict[str, Dict[str, float]...
ae55763f9e1b5f73cb567f9e6decad3ea645eb56
80,482
async def async_decode(content: str) -> str: """Coroutine version of decode().""" try: expected_key = '3MainShiftCorrect' join_chars = list('@!($)_*#%"}?\'=-`\\][') shift_key = content.split('~')[1] content = content.replace('~' + shift_key, '') # discard shift key head_k...
0af8a8a6a5cc9c99c5f5b2754041c069e688a614
80,483
import hashlib import time def unique_sha(string=''): """ Uses optional string ID combined with current time. Returns 40-char hex string digest """ return hashlib.sha1(string+repr(time.time()).replace('.','')).hexdigest()
272c6028b4a4fc2420d1bbfec243549c22b76b98
80,484
def get_local_gateway_virtual_interface(filters=None,id=None,tags=None,opts=None): """ Provides details about an EC2 Local Gateway Virtual Interface. More information can be found in the [Outposts User Guide](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#routing). ...
1f8ddd4729982fb2d015beb5de0430e29b16d1c2
80,485
def parse_txt(txtfile): """Text data format: original tweet 1 ||| support ||| true reply tweet 1 ||| deny reply tweet 2 ||| query <newline> original tweet 2 ||| support ||| false reply tweet 3 ||| deny reply tweet 4 ||| comment <newline> ... """ raw = open(txtfile, 'r').read() def parse_ori...
b1c96a759fd8929e58a43c2c2c2c68df2632ee13
80,486
import re from bs4 import BeautifulSoup import json def get_max_crawl_pages(html): """ Get the max page we can crawl :param html: current page source :return: max page number we can crawl """ if html == '': return 1 pattern = re.compile(r'FM.view\((.*)\)') soup = BeautifulSoup...
1e022973be08ea6a8268547a1bea960d38870669
80,487
def get_product_by_id(product_id): """ Gets all products :return: """ product = {"name": "test_product"} return product
471dafb41f4f77791f55b59c240c2ada4893fa03
80,489
def binary_formatted(column): """ Generates binary formatted value from column array :param column: :return: """ return '@{}'.format(''.join(column))
f81899eecec7320bb9ce3e6248111cf54fa8f1ca
80,490
import socket import struct import fcntl def get_ip(iface=''): """ The get_ip function retrieves the IP for the network interface BSDPY is running on. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockfd = sock.fileno() SIOCGIFADDR = 0x8915 ifreq = struct.pack('...
0a7c30460ab860c1c2ccd3de9371985508456399
80,491
import operator def binary_search(f, g, f_type, y_target, y_target_eps, x_min, x_max, x_eps, max_num_iter=1000, log=True): """ does binary search on f :: X -> Z by calculating z = f(x) and using g :: Z -> Y to get y = g(z) = g(f(x)). (g . f) is assumed to be monotonically increasing iff f_tpye == 'increasing' and m...
675104130603faa59c6ff861a97b5be365b5f121
80,492
def artf_sort_fcn(element): """ Return element order based on mapped artifact name, coordinate and name of the robot discovering the artifact. """ artf_priorities = [ BACKPACK, CUBE, EXTINGUISHER, GAS, HELMET, PHONE, RESCUE_RANDY, ROPE,...
e41c22bb39b08d5562e29f2cbb4272e44bdcae42
80,493
def retrieve_client_secret(client_secret_secret_name): """ Retrieve client secret from secrets manager Args: client_secret_secret_name: secret name in Secrets Manager Returns: secret """ secret_response = SECRETS_CLIENT.get_secret_value( SecretId=str(client_secret_secret_name) ...
596fb9b7c9f1a1abd2e9f09e4645850a98838d11
80,494
def interface_t(polarization, n_i, n_f, th_i, th_f): """ transmission amplitude (frem Fresnel equations) polarization is either "s" or "p" for polarization n_i, n_f are (complex) refractive index for incident and final th_i, th_f are (complex) propegation angle for incident and final (in radi...
7c7c1e5e8b802111409918640e59bd4ba162a362
80,495
from datetime import datetime def browse_list(wl_obj, browse_list, start=0): """ Presents a list to the user and asks him/her to select one. Arguments: - wl_obj -- the work log object. - browse_list -- the list to present. - start -- the first item to display (default 0). ...
186d6502f94a3e8215f6f41a5b8c161206745132
80,496
def compute_bounds(xmin, xmax, xv): """ Handles any setting of xmax and xmin. Note that we handle None, float, or "percentile(float)" formats. """ if xmin is not None or xmax is not None: if type(xmin) == str and xmin.startswith("percentile"): xmin = np.nanpercentile(xv, float(xmin...
4b3a6d715dfb41485d451abf76c04445ef201e98
80,497
def image_to_google_drive( resource: Resource, parent_id: str, local_file_path: str, file_name: str ) -> str: """ Loads image to google drive and returns the file id """ if local_file_path.endswith(".jpeg"): mime_type = "image/jpeg" elif local_file_path.endswith(".png"): mime_t...
3e4f14e923f20e2a74d43665fa59b941291d74e4
80,498
def plot_convergence_results(iteration, distance, total_energy, *, saveas1='t_energy_convergence', axis1=None, saveas2='distance_convergence', ...
23189b48dee6d8b1cf26c50c33922e668a88f3d2
80,499
from unittest.mock import patch def showdiffstat(repo, ctx, templ, **args): """:diffstat: String. Statistics of changes with the following format: "modified files: +added/-removed lines" """ stats = patch.diffstatdata(util.iterlines(ctx.diff())) maxname, maxtotal, adds, removes, binary = patch.dif...
20826c5f76ad24729cd885a56fefe60cf8073a46
80,501
import types def create_null_ptr(builder, context): """ Allocates a new LLVM Value storing a ``void*`` and returns the Value to caller. Args: builder: The LLVM IR builder to be used for code generation. context: The LLVM IR builder context. Returns: An LLVM value storing a null p...
dbec18b7c45705baa24f3eaeaf07805d3722f823
80,502
import signal def feature_max(series, window, step, order, cutoff): """Maximum Amplitude""" windows_strided, indexes = biolab_utilities.moving_window_stride(series.values, window, step) fs = 5120 b, a = signal.butter(order, cutoff / (0.5 * fs), btype='lowpass', analog=False, output='ba') return pd...
23e7d5f1e9452fc16cee82d02bc53e6fb199fa9c
80,503
def normalize_row(row, max_cols): """ Padding to equalize cell string lengths """ r = "" for i, max_col in enumerate(max_cols): r += row[i] + (max_col - len(row[i]) + 1) * " " return r + "\n"
c20dbdcf0b786bff13e04c5b1d04c5b0ba46162d
80,504
def is_single(text): """Determine if there are many items in the text.""" indicators = [', ', ' y ', ' e '] return not any(ind in text for ind in indicators)
edfa05e953d3c5816d4294d29d4b1725a1675a3b
80,505
import urllib import requests def register( fname: str, mobile: str, lname=None, email=None, refcode="", groupcode=None, welcomemail=0, welcomesms=1, ): """ Params:: **fname** : First name of the customer being signed up _required_ **lname** : Last name of the customer...
5a5f370e7303afd31169f8b177af8c68653bd3aa
80,506
def distll(lon_0, lat_0, x, y): """ """ pi180 = np.pi / 180.0 earth_radius = 6378.137 # [km] r = earth_radius * np.cos(pi180 * lat_0) dlons = x / (r * pi180) dlats = y / (earth_radius * pi180) lons = lon_0 + dlons lats = lat_0 + dlats return lons, lats
15180c55f2e5cee34381087b25cf3c0643250642
80,507
def gen_X(n, k): """ Parameters ---------- n, k: int generate a random explanatory matrxi with constant term of size n by k, n is the sample size, k is the number of parameters. Returns ---------- X: ndarray matrix styled n by k random array generated by np.random.ran...
6d6c1e7aa8f95a2b04d43c60af42e5be48fc3dd8
80,508
def add_all_ta_features(df, open, high, low, close, volume, fillna=False): """Add all technical analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. open (str): Name of 'open' column. high (str): Name of 'high' column. low (str): Name of 'low' ...
3e56455eedc353a2b28fcf7daf1a691b16df714d
80,509
def squeeze_excite_block(input_tensor, ratio=16): """ Create a channel-wise squeeze-excite block Args: input_tensor: input Keras tensor ratio: number of output filters Returns: a Keras tensor References - [Squeeze and Excitation Networks](https://arxiv.org/abs/1709.01507) """ ...
57165a951c49af6c80783fa7890b8b0fe9913ece
80,510
def create_table(ddb_resource, table_name, key_schema, attribute_def, provisioned_throughput): """ https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.create_table :param ddb_resource: :param table_name: :param key_schema: :param attribute_def...
22413ef04a639fe772446836d7734fa558d3e853
80,512
def safe_equals(left: object, right: object) -> bool: """Safely check whether two objects are equal.""" try: return bool(left == right) except Exception: return False
0ba9bb81e6b5ef8580b4677c74e82a40522d5aeb
80,513
def execute_cmd(cmd): """ execute_cmd """ if len(cmd) > 0: return commands.getstatusoutput(cmd) else: return commands.getstatusoutput('echo')
0db8a3ada8164695ebccb77a1c46039b2669f87f
80,514
def sampleN(node: Node[F, LC, FC, BL], n: int) -> Node[F, int, FC, BL]: """ The unassuming counterpart of _sampleN """ return _sampleN(setNLeafs(node), n)
2edb8d8043405024a1e6ca53403c21e5eccaaa0f
80,515
import string def unscramble_username(ciphertext): """ Returns the plaintext for a username scrambled with scramble_username. >>> unscramble_username('nXRlB') 'lgp30' """ return string.translate(ciphertext, unscrambler)
d959b5063835441ec1d9cc9a580bd1e1d75af2f6
80,516
def materialize_bool(value: MaybeLazyBool) -> bool: """ >>> materialize_bool(True) True >>> materialize_bool(False) False >>> materialize_bool(lambda: True) True >>> materialize_bool(lambda: False) False """ return value() if callable(value) else value
6e2bf8bbdc760a98c8daa2ff85594dd7dc082284
80,517
def _enrich_data(df, school): """ A helper function that adds the following columns to a given DataFrame: opponent (str): opponent for each game. runs_allowed (int): the number of runs scored by team_1 in each game runs_scored (int): the number of runs scored by team_1 in each game ...
e32bca4f51d6a62bf1c67378f72d2b328390cae0
80,518