content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def prompt_aergo_keystore(): """Prompt user to input a new aergo private key. Returns: - name of the key - address of the key - path to keystore """ while 1: questions = [ { 'type': 'input', 'name': 'account_name', ...
4a30f53549b6faffa7097333dfcff92c28f9333d
60,100
def display_test_plot(): """ Display a test plot. Returns ------- plot_meta : plot_playground.common.d3_helper.PlotMeta An object that stores the metadata of the plot. """ df = pd.DataFrame(data=[{ 'date': '2017-11-03', 'apple': 100, 'orange': 140, }, { ...
60392d7be3470654c3b42a7876da8188df1f5b91
60,101
from typing import Optional import re def evaluate(value: str, env: Optional[dict] = None) -> any: """Parse a string containing one or multiple ``${{ }}`` blocks and ``eval`` the expressions. Simple strings are left unchanged: .. code-block:: python >>> from gada_compose import parser ...
58645568212a6ef815f47b8b52005e489ae86685
60,102
def extract_tables(sql): """Extract the table names from an SQL statment. Returns a list of (schema, table, alias) tuples """ parsed = sqlparse.parse(sql) if not parsed: return [] # INSERT statements must stop looking for tables at the sign of first # Punctuation. eg: INSERT INTO ...
61c94e037b93feb13355ee1feb79fdcd092214a2
60,103
import os import requests import io def download(module_name): """Download a zip archive for a remote module.""" metadata = fetch_from_index(module_name) url = metadata["url"] zip_url = os.path.join(url, "archive/master.zip") req = requests.get(zip_url) zipfile = io.BytesIO(req.content) r...
ae331367b8289e2825be32c308121435ac0b99b1
60,104
from typing import Tuple def euler_angles_RX(theta: float) -> Tuple[float, float, float]: """ A tuple of angles which corresponds to a ZXZXZ-decomposed ``RX`` gate. :param theta: The angle parameter for the ``RX`` gate. :return: The corresponding Euler angles for that gate. """ return (np.pi ...
7a01b853c4296abc8649e3681d86775035c979f5
60,105
def lftx(yr): """ Function reads in NCEP Reanalysis Lifted Index Surface data Parameters ---------- yr : year as integer Returns ---------- lftx : array of lifted indices latitudel : array of latitudes longitudel : array of longitudes """ directory = '/volu...
dff8f245d4c9ff7ca61a823d0f8d536546920a04
60,106
import shutil def check_java() -> bool: """ Check if Java is installed on the system.""" return shutil.which('java') is not None
44c19db5c9b72c6904e01b09797009cd8f2079b0
60,107
def data_ref_type_str(dref_enum): """ Translate an ``enum DataRefTypes`` value into a string representation. """ if dref_enum == 0x9000: return 'unknown' elif dref_enum == 0x9001: return 'integer' elif dref_enum == 0x9002: return 'fp' else: return 'INVALID'
28f3c493c1f927e8286be5d00b695ecb399210c5
60,108
def stop_stream_json(): """Define a successful response to POST /api/v1/web/equipment/stop_stream.""" return {"code": 0, "msg": "Succeed."}
0d0cb028a343ea9ac19dc8c39f75e6cfff383e06
60,109
def four_point_transform_2D(image, src_pts, tgt_pts): """Apply 4 point transformation determined by `src_pts` and `tgt_pts` on 2-D image `image`. Args: image: 2-D tensor of shape [height, width], or 3-D tensor of shape [height, width, channels] src_pts: 2-D tensor of shape [4, 2] tg...
7b82c44b46d029cc6a8803dff720ac46d2de4946
60,110
import string def mcalpine_eflaw_index(text): """ A readability score defined by Rachel McAlpine See https://strainindex.wordpress.com/2009/04/30/mcalpine-eflaw-readability-score/ EFLAW index = (#tokens + #miniwords) / #sentences :param text: A string text without punctuation :return: McAlpi...
f645d8baa7156347d0fe7edfd09d792b6b39be34
60,111
from typing import Union def _get_latest_folder( gcs_folder: str, gcp: Box, credentials: Credentials = None ) -> Union[str, None]: """Returns the latest subfolder from a "folder" in GCP[^folders]. This function assumes the folders are named with `project-id/cbs/[v3|v4]/dataset-id/YYYYMMDD`, and that ...
f074155682219d48addcac2ceca7e6274c4841f2
60,112
def is_nonCW_in_extension(G): """ Returns True if G is 'non-CW in extension', otherwise it returns False. G: directed graph of type 'networkx.DiGraph' EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> G=nx.DiGraph() e_list = [(1,2),(0,1),(0,3),(3,1),(4,2),(4,0)] G.add_edges_fr...
eb5367ec271df6339c0efaf5ed972e650163326e
60,113
def six_word_trie_with_some_overlap(): """A trie with six words that will have some overlap.""" new_trie = TrieTree() new_trie.insert('cake') new_trie.insert('car') new_trie.insert('carpet') new_trie.insert('rats') new_trie.insert('ratchet') new_trie.insert('knife') return new_trie
c18c881dcc4a7fc7e4a2e4a1e46cbdf50371eb6b
60,114
def share_group_snapshot_create(context, values): """Create a share group snapshot from the values dictionary.""" return IMPL.share_group_snapshot_create(context, values)
3345a8442db619422618c9c9e63758faf720d17d
60,115
def int_beta(Beta, radial_step=1, threshold=0.1, regions=None): """Integrate beta over a range of Newton spheres. Parameters ---------- Beta : numpy array Newton spheres radial_step : int number of pixels per Newton sphere (default 1) threshold : float threshold for norm...
3fbf32719fdadd1dc7e18bb59e633ffbf47041f3
60,116
import os def loadh5pyFile(datasetPath, dataPath): """load h5pyfile and put into a ndarray container h5pyfile size is (*,360,288), we convert it into size(*,288,360) load HDF5 object:av_data,av_dataName save the reference(index) of each frame's avdata """ au_dataPath = os.path.join(datasetPath, da...
0d07ab78aa3fa2b303f225a01470caa22a87bc1b
60,117
def runOCcmd_yaml(cmd, base_cmd='oc'): """ log commands through ocutil """ logger.info(base_cmd + " " + cmd) return ocutil.run_user_cmd_yaml(cmd, base_cmd=base_cmd, )
9690769c21f7e7933418244df112079d7fcb5180
60,118
def retry_if_buffer_error_or_retriable(exception): """Return True if BufferError or retriable KafkaError, False otherwise""" return ( isinstance(exception, KafkaException) and exception.args[0].retriable() or isinstance(exception, BufferError) )
8b016936cd6f03d432c006b01eed043d21fc07b5
60,119
def takewhile(pred, *args): """Produce a sequence with the same elements as the input sequence until pred returns false for some element; that element and all those following are discarded. The filter predicate is passed an element of the input sequence plus extra arguments, if provided. """ de...
74503e290b31d263964e532851a90a74d09f3568
60,120
def so3_to_quaternion(so3): """Converts an SO3 rotation matrix to a quaternion Args: so3: 3x3 rotation matrix Returns: numpy.ndarray: quaternion [w, x, y, z] Raises: ValueError: if so3 is not 3x3 """ if so3.shape != (3, 3): raise ValueError("SO3 matrix must be ...
d728e589f7996f2feadae907229226878491b43e
60,121
def geocode(ctx, where): """ Geocode an address. """ location = None user_data = yield ctx.bot.defer_from_thread(UserData.lookup_default, ctx.client, where) location = user_data.get("location") if where is None and location is None: return [] elif location is not None: ...
964002ff763b0f48f7e0679f850c88857e53d18b
60,122
def _sp_expm(qo): """ Sparse matrix exponential of a quantum operator. Called by the Qobj expm method. """ A = qo.data.tocsc() # extract Qobj data (sparse matrix) m_vals = np.array([3, 5, 7, 9, 13]) theta = np.array([0.01495585217958292, 0.2539398330063230, 0.950417899...
be890480357be3ff1abd005a111f215eaf2f466d
60,123
def conv_adj_list(links): """ convert a bi-direction link list to a adj_list :param links: list(int:src_dpid, int:dst_dpid, str:attr) bi-direction """ graph = dict() for link in links: src_node = link[0] dst_node = link[1] ava_bandwidth = float(link[2]) if not gr...
08d771361fa4c1614771704398004a856fe4ce29
60,124
def home(): """홈 페이지.""" return 'home'
fa5b419e66fbfa0193e9ff87b38697006fc06ae4
60,125
import os def convertSURLtoTURLUsingScope(surl, scope, computingSite, sourceSite): """ Convert SURL to TURL using the scope """ turl = "" tolog("SURL = %s" % (surl)) # Select the correct mover copycmd, setup = getCopytool(mode="get") # Get the sitemover object corresponding to the copy comm...
a0f60d8654fbada906cc04817305afe5352d0c5a
60,126
import pickle def load_solution(filepath): """Load BlitzMLSolution from disk. Parameters ---------- filepath : string Path to saved solution. Returns ------- solution : BlitzMLSolution. """ with open(filepath) as f: solution = pickle.load(f) return solution
66f2fab622baadbf0d2c8867711912e2a49099ff
60,127
def arc(t, data, rho_min=0.8, Ntrends=None, denoise=arc_emd, Nkeep=10): """Identify systematic trends in the data. Parameters ---------- t : 1D array-like The independent data, generally time. data : 2D array-like The data (e.g. lightcurves). Should have shape NxM where there are ...
a30437e8cbedebeb2d22ebd95bce85c9e52e01be
60,128
def fit(core_radius, gamma, x, y, x_real, y_real, u_data, v_data, u_advection, v_advection, i): """ Fitting of the Lamb-Oseen Vortex :param core_radius: core radius of the vortex :param gamma: circulation contained in the vortex :param x: x position :param y: y position :param x_real: x po...
2b5c62d25a7aad3f3af38f558a6bc4ba9540c0ae
60,129
import os import click import re import shutil from datetime import datetime import time def main(setup,refresh,checkmaster) -> None: # sourcery no-metrics """If a file is in original but not measured or unmeasured, copys it to unmeasured \nIf a file is in measured and in unmeasured, deletes it from unmeasured""...
d4b7baa914e3195d99475267169def10ca6556a0
60,130
def mergeSort(array): """Apply merge sort to an array. Returns a sorted array.""" if len(array) > 1: mid = len(array) // 2 left = array[:mid] right = array[mid:] mergeSort(left) mergeSort(right) i = 0 j = 0 k = 0 while i < len(left) and j <...
5f69d6697c92086adce36a054fbefaaea423c2ae
60,131
def _request_get_required(*keys): """Verify existence of request data and return values""" if request.method == 'POST': obj = request.form else: obj = request.args values = [] for k in keys: v = obj.get(k) if not v: raise Exception('Expected "%s" parameter...
ec0665886760c60ae542f9b75a81cf52371fd5c2
60,132
import numpy as np def haversine(radius, lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) All args must be of equal length. """ lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) dlon...
6c38f2657b31756a66d25d8b2d84c5e75fc2621e
60,133
import os def experiment_path(func): """ Wrapping function of user experiment, by creating inside the worker instance the experiment artifacts path """ def inner(experiment, artifacts_path, metrics): if not os.path.exists(artifacts_path): os.makedirs(artifacts_path) return...
1d29cc8a4e8363699c9bedc3fa6d070e1c71975a
60,134
def create_hdf5_data_reader( train_path, val_path, test_path, num_responses=4): """Create a data reader for CosmoFlow. Args: {train, val, test}_path (str): Path to the corresponding dataset. num_responses (int): The number of parameters to predict. """ reader_args = [ {...
5651df1e752474483db43880fd84ea3a15450799
60,135
def JS_divergence(p1, p2, weights, mode='normalized'): """Calculate JS divergence between two distributions Parameters ---------- p1 : numpy array The first distribution, 1D array p2 : numpy array The second distribution, 1D array weights: numpy array 1D array of SEM we...
d37e1b0de5e67b5a9c9fdf666112d6a3400150fd
60,136
import numpy def create_visibility(config: Configuration, times: numpy.array, freq: numpy.array, weight: float, phasecentre: SkyCoord, meta: dict = None, params={}) -> Visibility: """ Create a Visibility from Configuration, hour angles, and direction of source :param config: Configurati...
19bd80bde439083b0a4bde0d550442bff5ccf0d1
60,137
def qpt_basis_mat(As, key=None): """Vectorized unitary operator basis {As} Args: As: <list> of unitary operator based on which to compute the chi matrix for process tomography. These operators should form a 'complete' set to allow the full chi matrix to be represente...
9015da56d5a5a168644b4907b901e4c135f8b591
60,138
def format_response(event): """Determine what response to provide based upon event data. Args: event: A dictionary with the event data. """ event_type = event['type'] text = "" senderName = event['user']['displayName'] # Case 1: The bot was added to a room if event_type == 'AD...
f253b3cc60351b4cac266fc34c92732f63519605
60,139
def local_includes(path): """Returns a list of copts that act like a `local_includes` attribute. Args: path: A `string` of the directory to add to local `includes`. Returns: A `list` of copts. """ repo_name = native.repository_name()[1:] package_name = native.package_name() ...
39e498e15bf78e6b738844c3601e6605a0d9b7d8
60,140
def imageurl(value): # Only one argument. """Converts a string into all lowercase""" value.split(" ") return value.lower()
dfc1243a4286d3c0b7370c8821ed2c08e8cb4328
60,141
import html import unicodedata import re def preprocess_html(text_str, plain_text=True, remove_newlines=True, remove_tabs=True, remove_tables=False): """ Pre-process html string by cleaning anomalies and optionally removing newlines, tabs, and html tables Args: text_str (string): ...
3b22defd1c1ba8ff47e8f0c0eee1cefa09a2e58d
60,142
def load_ko_associations_by_id(id): """Retrieve a KO mutation by id""" doc = es.get('aragwas', id, doc_type='ko_associations', _source=['overPermutation','overBonferroni','maf','mac','score', 'gene', 'study'], realtime=False) if not doc['found']: raise Exception('Associations with ID %s not found' %...
bd184d26565e3d4ceeae081bc623a9a1565128b5
60,143
def find_ports(port_range, num_ports = 2): """ Find available ports in the given range Args: port_range: The range of possible ports to use. num_ports: The number of ports that must be found and returned. Returns: An integer of the first available port or False if all ports are in ...
3a6666b456714e4c30c9c7c05b498906c28192c8
60,144
import torch def warp_affine3d(src, M, dsize, mode='bilinear', padding_mode='zeros', align_corners=True): """ Applies a projective transformation a to 3d tensor. """ assert len(src.shape) == 5, src.shape assert len(M.shape) == 3 and M.shape[-2:] == (3, 4), M.shape assert len(dsize) == 3, d...
ace8ac2ff73accb4746dce0902f4076974c0c61b
60,145
def trace(layer, inputs, feed_names=None, fetch_names=None): """ Trace dygraph network into a :code:`Program`. The returned :code:`Program` can be run in static graph mode. This method would simply record all operators in the network with :code:`inputs` . Users should guarantee that the traced dygra...
56957276b239beed6c7f5f2ba9b5d973fd2a8d28
60,146
import requests def delete_sr(product_name, version_number): """ Delete Software Release :param product_name: :param version_number: :return: """ req_data = {'product_name': str(product_name), 'version_number': str(version_number)} url = SERVER_URL + '/srdelete' re...
70277aacd849540c540c4319f8bb5e8a949f855d
60,147
def get_affiliation_name(graph, id): """Given database and id returns the display name""" # Compute the paper count first query = """ MATCH (a:Affiliations) WHERE a.AffiliationId="%d" return a.NormalizedName """ % ( id, ) df = graph.run(query).data() df = df[0]['a.Norm...
31638297b0267db837424b6dde7a4f546f0f3bc9
60,148
def plot_point_grid(model, coordinates=(-1, 1, .1), show_var=False): """ Description ---------- Function to plot a point grid for a two dimensional guassian process regressor. Parameters ---------- Model: gaussian process regression model object A gaussian process regression (gp...
3714adaa22e3c9c19bdc5ae8b7d5687c6838c3ef
60,149
def one_to_one_self(model_class, fk): """ Declare a one-to-one relationship property. The property value would be an instance of the same model. You will need an associated foreign key to our own table. *This utility method should only be used during class creation.* :param model_class: class...
cd8fe9de785047eafae558e7e003298e33903204
60,150
def escape_html(message): """Escapes HTML characters in the given message.""" # Only the following characters need to be escaped # (https://wiki.ubuntu.com/NotificationDevelopmentGuidelines). message = message.replace('&', '&amp;') message = message.replace('<', '&lt;') message = message.replace...
1fdbfa9b972ad6057e97967c61644b1c2e0994d0
60,151
def check_workspace_deleted(ws_id): """ Since the DELETE_WORKSPACE event can correspond to workspace undeletion as well as deletion, we make sure that the workspace is deleted. This is done by making sure we get an excpetion with the word 'delete' in the error body. """ try: config()['ws...
576e008b14bd2768b8cd2c9a404a072e8012f33a
60,152
from datetime import datetime def psoSearch(stns, w, s_name, bam, prefs, ref_pos, manual=False, pert_num=0, override_supra=[]): """ Optimizes the paths between the detector stations and a supracenter to find the best fit for the position of the supracenter, within the given search area. The supracenter i...
83f83dd9b188b444936f1c341b9137231a724a65
60,153
def loadVtkImageXML(name): """ load a VTK Image (.vti) into a vtkImageData (vtkStructuredPoints) """ reader = vtk.vtkXMLImageDataReader() reader.SetFileName(name) reader.Update() return reader.GetOutput()
5ee82e810f607ebf86bfeac13233a367e294f155
60,154
def food(f,num): """jfehfiehfioe i fihiohghi""" tip=0.1*f f=f+tip return f/num
848e43233a0a4cbc504971437fcc6f6df1667c4b
60,155
import json import re def get_data_from_request(request): """ Because data might be in bad JSON form, might be in a string... need to return an object, always """ try: try: if len(request.POST) > 0: if '_content_type' in request.POST: data = ...
84b18fdbc79a1b8f0bc4781dadb3ea325b615327
60,156
from re import X def minimax(board): """ Returns the optimal action for the current player on the board. """ p = player(board) # If empty board is provided as input, return corner. if board == [[EMPTY]*3]*3: return (0,0) if p == X: v = float("-inf") selected_actio...
e862af9c8991e7796672857350fba983048e2806
60,157
def lyrics_language(update: Update, context: CallbackContext) -> int: """Sets lyrics language or displays options""" language = context.user_data["bot_lang"] text = context.bot_data["texts"][language]["lyrics_language"] ud = context.user_data chat_id = update.effective_chat.id # command if ...
a13d37d4de8d5cf2b9da6d955c50c1581ef9e129
60,158
import os import io def get_content(name, splitlines=False): """Return the file contents with project root as root folder.""" here = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(here, name) with io.open(path, encoding="utf-8") as fd: content = fd.read() if splitlines: ...
35334999279c076a84644a5204dd7ac6f51c10ef
60,159
def example_group_validate_enrolled_event() -> bool: """ Example validating against the enrollment group containing created in enrollment_examples.py Returns: A boolean denoting whether or not the validation was successful """ audio_service: AudioService = helpers.get_audio_service() ...
c8df59db0b5e93885eba0bc8f401e9f37c342f4d
60,160
from typing import Tuple def handle_different_values( dim: str, df_1: pd.DataFrame, df_2: pd.DataFrame ) -> Tuple[pd.DataFrame, pd.DataFrame]: """Check if the dataframes have differing values in the `columns` or the `index`, depending on the passed dimension. If so, output a warning and list the respe...
1632a14972ae6dcc66b421dcd7a971e41b2a3c70
60,161
def get_vertices_per_edge(mesh_v, mesh_f): """Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. If output of get_faces_per_edge is provided, this is used to avoid call to get_vert_connectivity()""" vc = sp.coo_matri...
878eae6b3c7755dafdfc05a77784cbaf38f63e4f
60,162
import re def read_tsp(filename): """ Read a file in .tsp format into a pandas DataFrame """ with open(filename) as file: cities = [] flag = False for line in file.readlines()[0:-1]: if line.startswith('EOF'): break if line.startswith('NO...
bf59fd6d755102b26dc0871cf44342a9fd84ad87
60,163
def qvsl(tt, pp): """saturation specific humidity over the liquid phase""" return rd / rv * esatl(tt) / (pp - (1.0 - rd / rv) * esatl(tt))
1cb4b37a60f36204443db48bca464160df694766
60,164
import time import logging import math def evaluate(mod, data_iter, epoch, log_interval): """ Run evaluation on cpu. """ start = time.time() total_L = 0.0 nbatch = 0 mod.set_states(value=0) for batch in data_iter: mod.forward(batch, is_train=False) outputs = mod.get_outputs(mer...
ecfa801c403b4d5ac5703a08d6d0733d06134639
60,165
def crop_image(img, ymin, ymax, xmin, xmax): """Crop image with given size Args: img: image as numpy array ymin: start cropping position along height in pixels ymax: end cropping position along height in pixels xmin: end cropping position along width in pixels xmax: end ...
929be89de22b5aa129f17459d53f34b335803813
60,166
def get_attributes_g(context, selector, only_visible=True): """ Return the attributes for the element that is obtained from the selector as a dictionary object. :param context: :param selector: :param only_visible: :return: """ germanium = find_germanium_object(context) if isins...
65c39263ef811fca3a730032952b42901bae3943
60,167
def charge(payment_information: PaymentData, connection_params) -> GatewayResponse: """Performs Authorize and Capture transactions in a single run.""" auth_resp = authorize(payment_information, connection_params) if not auth_resp.is_success: return auth_resp return capture(payment_information, c...
0a259ae4601fcbc4c4b57d732c7f47afe8085b45
60,168
import tqdm def get_feature_combination_df( feature_combination: list, df: pd.DataFrame, index_levels: list, column_value: str = "value", verbose: bool = False ): """ For each feature combination in ``feature_combinations``, a DataFrame is created that holds the cal...
1b4b15ff7de2485324915e9530b1c6cac371efce
60,169
def tags_to_oset(tags): """Parse a ``tags`` argument into an ordered set. """ if tags is None: return oset() elif isinstance(tags, (str, int)): return oset((tags,)) elif isinstance(tags, oset): return tags.copy() else: return oset(tags)
30cf87915aa248677d89d9ed54a0ffcfa91b57bd
60,170
def join_dtype_arrays(a1, a2, target_dtype): """ Initializes a new array with dtype target_dtype, and copies matching fields from a1 and a2 to the new array. Args: a1: a2: target_dtype: Returns: """ new_ar = np.zeros(shape=(), dtype=target_dtype) fields1 = a1 if is...
002381f066fc6f50db03fd2afcef371e49863890
60,171
import textwrap def prettyprint(annots, outlines, outfile, do_group, sections, wrapcol): """ Pretty-print the extracted annotations according to the output options. annots List of extracted annotations, in the order they appear outlines List of outlines outfile Output file handle to print to ...
db61c5434c390f058349bc01b4b7f48cce15c0f5
60,172
def create_mesh(verts, faces, name='new-mesh'): """Creates a mesh from vertices and faces. Args: verts (array_like): Local coordinates of the vertices, of shape N-by-3. faces (list(tuple)): Faces specified by ordered vertex indices. name (str, optional): Mesh name. Retu...
1dc2124d436288745a62a98b97dc8ef71e5984ae
60,173
import torch def so3_rotation_angle(R, eps: float = 1e-4): """ Calculates angles (in radians) of a batch of rotation matrices `R` with :math: `\\phi = \text{acos}\frac{\text{Trace}(R)-1}{2}`. The trace of the input matrices is checked to be in the valid range [-1-`eps`,3+`eps`]. The `eps` argument...
2786c3cd0173b3b894427d2402aef3ebf7471b4d
60,174
def eq_lvar(x, y): """Perform an equality check that considers all logic variables equal.""" return meta_diff(x, y, ne_fn=lvar_ignore_ne) is None
adfd0b18335e5b8f57f490c63eb738e6e83f9420
60,175
import bisect def binary_search(elements, value): """Returns the index of the element closest to value. Args: elements (List): A sorted list. """ if not elements: return -1 closest_index = bisect.bisect_left(elements, value, 0, len(elements) - 1) element = elements[closest_ind...
0463f69c1edc627b3b67ea0cbd646e560734703c
60,176
def mv2musig(m, v): """ Convert mean and variance of log-normal distribution into mean and stdev of underlying normal distribution Parameters ---------- m: float Mean of log-normal distribution. v: float Variance of log-normal distribution. Returns ------- mu: float ...
efd77306741fd1e8b4294402d1fdb79c4806ee5c
60,177
def smallest_prime_factor(n): """ :param n: :return: the smallest factor of n, which is in the range [2, n]. The result is always prime. """ assert n >= 2 for i in range(2, eulerlib.sqrt(n) + 1): if n % i == 0: return i return n
e56d1d26f3de6e92e2f2182c50be20ce52c809fe
60,178
def cutoff_wavenumber(a, b=None, m=1, n=0): """Calculate cutoff wavenumber of TEmn or TMmn waveguide mode. Args: a: broad dimension of waveguide, in units [m] b: narrow dimension of waveguide, in units [m] m: mode number m n: mode number n Returns: float: cutoff wav...
49b45c9c46a37a021995c0e65aaa89aaf1d830d4
60,179
def df_empty(columns, dtypes, index=None): """Creates an empty DataFrame with initial column names and types.""" assert len(columns)==len(dtypes) df = pd.DataFrame(index=index) for c, d in zip(columns, dtypes): df[c] = pd.Series(dtype=d) return df
6807aeff2b8f2195ad661779a880d03ce85becc3
60,180
def csv2pandas(data_info): """ Usage example: data_dict = { 'skinny': { 'path': '/home/sebastian/Documents/PhD/data/skinnydip/skinnyDipData_8.csv', 'read_csv_kwargs': {}, 'columns2keep': ['V2', 'V3', 'V4'], 'rename_columns': {'V2': 'f1', 'V3': 'f2', 'V...
35e6f3588fc1f19bb6d288f8c9f1e8ff1b6e9eda
60,181
from typing import List def training_size_curve(model: ModelType, x_train: np.ndarray, y_train: np.ndarray, x_val: np.ndarray, y_val: np.ndarray, sizes: List[float], title: str) -> go.Figure: """Produces a training curve with respect to train...
e6cab20822241e96e044d8d4d5cd27a8c8f9b7e0
60,182
def gs_filter(img, sigma): """ Step 1: Gaussian filter Args: img: Numpy ndarray of image sigma: Smoothing parameter Returns: Numpy ndarray of smoothed image """ if type(img) != np.ndarray: raise TypeError('input image must be of type ndarray') else: retu...
e44063895a22b4ee9a1e759126a166ce054b7b63
60,183
def make_keys_into_plays(lookup_table: dict) -> dict: """Returns a dict where all keys are Plays.""" new_table = lookup_table.copy() if any(not isinstance(key, Plays) for key in new_table): new_table = {Plays(*key): value for key, value in new_table.items()} return new_table
82e70a756312b7884a50447538d16315a147d837
60,184
import argparse def get_args(): """ get_args consolidates user inputs. :return: """ parser = argparse.ArgumentParser(description="A commandline utility to crawl on pdf files.") parser.add_argument('-d', '--debug', required=False, help='Enable debug output', dest='debug', action='store_true') ...
9b19a845f33ee0426e67c17e297359178ee1b4e4
60,185
def noto_fonts(default=''): """Local path to noto-font git repo""" return values.get('noto_fonts', default)
78c53cc18994f95d7633024c202935f1929202ed
60,186
def to_utf8(string): """ Args: string: A string que vai ser filtrada Returns: str: A string inicial apenas com caracteres utf-8 """ return ''.join(filter(lambda x: str(x) in string_lib.printable, list(str(string))))
abf0e914e13b2598a6225f67542fd6fb48b94b92
60,187
def rect_overlap(r1, r2): """Return the area of the intersection of two rectangles. Args: r1: an object with attributes left, top, width, height r2: an object with attributes left, top, width, height Returns: float """ left = float(max(r1.left, r2.left)) right = float(mi...
cba6c109fe7e9cdc3532781ebb9abbae7088754d
60,188
import math def rrange(series_key, start, stop): """Generate Renard values in a range inclusive of the start and stop values. Args: series_key: The RenardSeriesKey to use. start: The beginning of the range. The yielded values may include this value. stop: The end of the range. The yie...
50f6609a933deb6523588fd12dd69d9492f82e77
60,189
from astrometry.util.util import Tan import os def forced_phot(galaxy, survey, srcs, cat, band, log): """Perform forced photometry on a single SDSS bandpass (mosaic). """ bandfile = os.path.join(survey.output_dir, '{}-sdss-image-{}.fits.fz'.format(galaxy, band)) img, hdr = fitsio.read(bandfile, head...
9c6fd9a713a9dd63ed0271a5710688f750100007
60,190
from typing import Dict from typing import Set import itertools def get_map_of_unbound_references( comp: building_blocks.ComputationBuildingBlock ) -> Dict[building_blocks.ComputationBuildingBlock, Set[str]]: """Gets a Python `dict` of unbound references in `comp`, keyed by Python `id`. Compuations that are ...
861cd01f3c43d3de334582c350b5423bb3822106
60,191
def is_available(): """Returns a boolean to indicate the availability of a OpenCL GPU. This will initialize the driver if it hasn't been initialized. """ return driver.is_available
793b83b8c69d10e2a548c41973111de75f9e44db
60,192
def load_dset(dfile, R_cut=None, z_cut=None): """ Read saved .npz dataset, keeping only stars within specified cuts. Parameters ---------- dfile : str Path to .npz file containing dataset, e.g. files in /data directory. R_cut : float, optional Keep only stars within `R_cut` of 8...
d8786a83b871ce0fff017796b3546baea6254004
60,193
def test_for_numeric_line( d: deque, # func_deque: bool = False ) -> bool: """ Returns True if 'd' appears to be a calculation in consisting entirely of numerals, operators, and functions. In other words, the calculation has no "variables" in it, whatsoever. """ bool_acc = [] fun...
6d27968ac3f74d16e2be7bd2cba2215edc074f30
60,194
def attack(length): """ This function start with an empty string and starts to fill it (until its length it is equal to the param length) with the characters guessed by the guess_letter function. :param length: It is the guessed length of the password, generated by the function guess_length. :return...
dfae0000b0f313bbf91a731732b4b4dc06382ca3
60,195
from typing import Tuple import random def deal_card() -> Tuple[dict, dict, dict, dict]: """ """ card_string = _card_to_str(CARDS) card_list = list(card_string) random.shuffle(card_list) return ( _str_to_card("".join(card_list[:17])), _str_to_card("".join(card_list[17:3...
35bc5c5f2d0ced5dbbe1fd14121d2d0b2feb7a7b
60,196
import torch def accuracy(gt_S, pred_S): """ Get the accuracy of the model. Args: gt_S : Ground truth. pred_S : Prediction. Returns: Accuracy classification score. """ _, alp = torch.max(torch.from_numpy(pred_S), 1) return accuracy_score(gt_S, np.asarray(alp))
1b2aec51118e8006ff6d6568bcc5ab013e7ef97a
60,197
import sys import six def get_traits(prefix=None): """Returns the trait strings in the os_traits module, optionally filtered by a supplied prefix. :param prefix: Optional string prefix to filter by. e.g. 'HW_' """ prefix = prefix or "" return [ v for k, v in sys.modules[__name__].__di...
091f5a4aaafc8935991d3094cbbd0370314ded45
60,198
def upper_to_lower(upper, lower): """ return new symm matrix with upper tri copied to lower tri""" return upper, upper
ad178d0442e0242fd4818df90324e9022da96e94
60,199