content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import Iterable def to_np_tuple(prop: Union[int, Iterable]) -> np.ndarray: """Creates a np array of length 2 from a Conv2D property. E.g., stride=(2, 3) gets converted into np.array([2, 3]), where the height_stride = 2 and width_stride = 3. stride=2 gets converted int...
9d67cf2e608e01c41f7eeaf146b98ea61bec8dd1
3,620,913
def tetrode_identity_shuffle(multiunit): """Shuffle the correspondence between tetrodes and spike time """ n_tetrodes = len(multiunit.tetrodes) rand_tetrode_index = np.random.randint( low=0, high=n_tetrodes, size=n_tetrodes) return multiunit.isel(tetrodes=rand_tetrode_index)
e5dcb824f2081921befb9b407a561e90b3ea1317
3,620,914
def is_silent(data_chunk): """Returns 'True' if below the 'silent' threshold""" return max(data_chunk) < THRESHOLD
18e1108bab8edbc0b6f258af6ae24893795d15b6
3,620,916
def get_properties(value): """ Converts the specified value into a dict containing the NVPs (name-value pairs) :param value: :return: """ rtnval = None if isinstance(value, dict): # value is already a Python dict, so just return it rtnval = value elif '=' in value: ...
03f75e85e54a08b75b8d6e25b5d1dd65f7e987db
3,620,917
def union(llist_1, llist_2): """ Returns union of two provided LinkedLists Args: - llist_1(LinkedList): data to be written into the new block - llist_2(LinkedList) Returns: - True if the block was added. Otherwise False """ if llist_1 is Non...
503dc99cde100dd5986498d22649555e4caeae4f
3,620,918
import math def qft(qubits): """ Performs an in-place quantum fourier transform on the given register. Parameters: qubits (list[QubitPlaceholder]): The register to apply the QFT to Returns: A program containing the QFT gates. Remarks: Note that by the established convent...
6081fbe0bb1ed428a715c18db045863437024f24
3,620,919
def check_hits_in_ellipse(ellipses: np.array, hits: np.array) -> np.array: """Returns mask for specified hits, True if hit in ellipse, False otherwise """ k_hits = len(hits) / len(ellipses) duplicated_ellipses = np.repeat(ellipses, k_hits, axis=0) centers = duplicated_ellipses[:, :2] ...
2276b108b5d15fbf76c7d1ff907df029d9d9c56f
3,620,922
from typing import Dict from typing import Optional def get_optional_boolean_arg(args: Dict, argument_name: str) -> Optional[bool]: """ Extracts the argument from Demisto arguments, and in case argument exists, returns the boolean value of the argument. Args: args (Dict): Demisto arguments. ...
b4ab14557af2deb88b12c23405f4f09b53053672
3,620,923
def get_jaddr_from_comments(pp_lst, comment_lst): """ @brief reads in jump addresses wich were set by the reverse engineer @param pp_lst List of PseudoInstructions in push/pop represtentation @param comment_lst List of comments @return List of tuples (set jump address, address of jump instr...
7784c5cdab33ede4b5dbe76fe218095ce7d70bc9
3,620,924
def CalculateMeanValue(str_lengths:list): """ This function calculates the mean over all values in a list. :param str_lengths:list: lengths of all strings """ try: return int(round(sum(str_lengths)/len(str_lengths))) except Exception as ex: template = "An exception of type {0...
001acb0b9378befcd1f1ac5ed5392822fac0067d
3,620,925
import math def radangle(p0,p1): """ Radian angle between two points on a sphere in lon-lat (x,y) Parameters ---------- p0 : first point as a lon,lat tuple p1 : second point as a lon,lat tuple Returns ------- d : radian angle in radians Example ------- >>> ...
252b3be7cb41571cf26ba266b544d403f6413179
3,620,926
def annToMask(anno, height, width): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ rle = annToRLE(anno, height, width) mask = maskUtils.decode(rle) return mask
b5d8f92a2e284b9326946945af234294bfc33c96
3,620,927
def get_pdm_terms(site_index, n, adj_sites=4, shift=0): """ inputs: site_index (int): center site index n (int): number of sites in lattice (for enforcing periodic boundary conditions) adj_site (int): how many adjacent sites to collect pop and coherence values from shift (int): r...
34d7914ddd751cb75b04e855d68edb156c1defda
3,620,928
def glass(number): """ Return an array of Sellmeier coefficients for glass. The glasses all have a number. This number is used to look up the Sellmeier coefficients for glass. The number can be looked up with `ofiber.glass_name`. Use like this:: num = ofiber.glass_index("SiO2") ...
b274ec7a916aaad60e89a4b5563385a65a771acb
3,620,931
def isnan(x: _cpp.Variable) -> _cpp.Variable: """ Element-wise isnan (true if an element is nan). """ return _call_cpp_func(_cpp.isnan, x)
bedf9e3c2af9b557fa3c429d535a1a48d57d5419
3,620,932
def supply(request, page_name): """supply view_objects for user status.""" _ = page_name _ = request #todays_users = Profile.objects.filter(last_visit_date=datetime.datetime.today()) rounds_info = challenge_mgr.get_all_round_info() start = rounds_info["competition_start"] daily_status = Da...
4521dd68f5f2483932e2c4d7b40ae592fbd0eb38
3,620,934
import inspect def get_default_args(func): """ returns a dictionary of arg_name:default_values for the input function """ if not callable(func): raise TypeError("%s is not callable" % type(func)) if inspect.isfunction(func): print('a') spec = inspect.getargspec(func) el...
516cebc2f071a4f13b3784df0c3b5825b5fc21ba
3,620,935
import email def git_am_patch_split(f, encoding=None): """Parse a git-am-style patch and split it up into bits. :param f: File-like object to parse :param encoding: Encoding to use when creating Git objects :return: Tuple with commit object, diff contents and git version """ encoding = encodi...
7d7dfa1cdd6c84a5911c4cfea4d2e67026fb84ee
3,620,936
from typing import Tuple from typing import Dict def compute_retrieval_cosine(dot_product: np.ndarray) -> Tuple[Dict[str, float], np.ndarray, np.ndarray]: """ Args: dot_product: Result of computing cosine similarity between two sets of embeddings (emb1 @ emb2.T) with shape (num_datapoints,...
f18d74e015ac1ce9e1d6c095e2dc378b8a85465f
3,620,937
from io import StringIO def makeSVGedge(e): """ """ cs = StringIO.StringIO() curve = e._geomAdaptor() # adapt the edge into curve start = curve.FirstParameter() end = curve.LastParameter() points = GCPnts_QuasiUniformDeflection(curve, DISCRETIZATION_TOLERANCE, start, end) if poin...
ff08e5bebeb936f820f858a53d8cf322f07c1d3b
3,620,938
from typing import Mapping from typing import Any from typing import Optional from typing import Iterable def create_and_join_world( connection: dm_env_rpc_connection.Connection, create_world_settings: Mapping[str, Any], join_world_settings: Mapping[str, Any], requested_observations: Optional[Iterable...
4a80f24bf67475b109b5e6d5e468243384732cc7
3,620,940
from sklearn.externals import joblib from sklearn.ensemble import RandomForestRegressor def Hyperparameter_Tune_model(use_choosen_model=True, model=None, RFR_dict=None, df=None, cv=3, testset='Test set (strat. 20%)', target='Iodide', ...
181f23885a48736e0022cfabbffe33d3af50af90
3,620,942
def process_id(input_ids, vocab_table, PAD, max_len=None, min_len=None): """Converts input ids (in text string) into their indices in vocab :param input_ids Tensor Id features. Shape=[group_size] :param vocab_table TFLookupTable Vocab table for id...
a9f710d497f483a1e3aa44cdc6125086f5b224a9
3,620,943
import time def test_recurring_jobs_when_volume_detached_unexpectedly(settings_reset, set_random_backupstore, client, core_api, apps_api, pvc, make_deployment_with_pvc): # NOQA """ Test recurring jobs when volume detached unexpectedly Context: If the volume is automatically attached by the recurrin...
8e8e352f8d5954c4b86f0a593bc378fbb34707f5
3,620,944
from datetime import datetime def now_datetime(offset = 0): """ A function to return the current datetime. """ return adddays(offset, datetime.datetime.today())
6633f788e02bef6d8e0ab51ae6bffe0e2d3970f7
3,620,946
def generate_data(num_students=NUM_STUDENTS, num_items=NUM_ITEMS, num_responses=NUM_RESPONSES, prob_correct=PROB_CORRECT): """ Simulate student response data (independently of any parameters). :param int num_students: Number of unique student ids. :para...
bc81666a5e5552223a12a0f611099e2696f0481a
3,620,947
import ast def ast_name_node(**props): """ creates a name ast node with the property names and values as specified in `props` """ node = ast.Name() for name, value in props.items(): setattr(node, name, value) return node
880d9527d63c7b2c97a4bc616bf245dab6583f81
3,620,948
def _prepend_min(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` minimum values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate minim...
7a5c0c22d6358197b659b7fa1c0526f4a4a0a4aa
3,620,949
def buildX(traj_file, t, X): """ Builds the node attribute matrix for a given time step. Inputs: traj_file : string indicating the location of the ground truth trajectory data t : scalar indicating current time step X : empty node attribute matrix in shape [n_nodes, n_features] Outputs: ...
3b0d3b18d9897364e1140103d7f049d5502d302a
3,620,950
def get_answer_feedback(answer, player): """ Render the feedback text, if a review by player was given to answer """ qs = Review.objects.filter(answer=answer, reviewer=player) if not qs.count(): return '' return qs.get().feedback
6b5767740931504837fa149e57a0780d04572af6
3,620,952
def get_token_by_id(ikey, skey, host, token_id, ca=None): """ Returns a token. ikey - Admin API integration ikey skey - Admin API integration skey host - Duo host token_id - Token ID ca - Optional CA cert Returns a token object. """ url = '/admin/v1/tokens/' + token_id resp...
3f133dfe733286c55115cf8ef8c2faf56278b316
3,620,953
def frac_prop_calc(df_bin_org, prop, param_dict, catl_keys_dict): """ Computes the quenched fractions of satellites in a given mass bin. Parameters ---------- df_bin_org: pandas DataFrame Dataframe for the selected group/halo mass bin prop: string galaxy property being evaluate...
7c04878dca8f4841d445cf4ee3870ad230e5d69d
3,620,955
def move_left(board, row): """Move the given row to one position left""" board[row] = board[row][1:] + board[row][:1] return board
a0dc74f65abd5560db7c2fe602186d15b8fda3d2
3,620,956
def find_connected_continuations(continuation_arr, max_face_shape=(1152, 1152)): """ Finds the edges of a graph which describes the continuation connectivity """ sizes = continuation_arr.shape face_checked = np.zeros((6,) + continuation_arr.shape, dtype=np.bool) ...
bfc9a50dc83c9b527338c13d4f466ec9235bd7e4
3,620,957
def acp_account(): """Manage the user account of currently-logged-in users. This does NOT accept admin-specific options. """ if request.args.get('status') == 'pwdchange': alert = 'You must change your password before proceeding.' alert_status = 'danger' pwdchange_skip = True ...
d434f46e595a0579653ae045c655dcbdcd2c91fb
3,620,958
import re import torch def embed_seq(sequence, tokenizer, prottrans_model, device="cpu"): """ Embed a single sequence from the tokenizer and prottrans model. """ sequences = [sequence] sep_sequences = [] for seq in sequences: sep_sequences.append(" ".join([x for x in seq])) #print(...
2c8182e67aa2fe8fa1bf0dff332d8bd8a25a5fb2
3,620,959
from typing import Any def get_tile_from_info_dict(slide: Slide, info: Any): """ Get a tile from an info dict. Args: slide: info: info dict Returns: patch (PIL image) """ patch = slide.get_tile(info['w'], info['h'], info['mag'], info['size']) return patch
247e201cda88875d606dd7a4cdfdf56bee853d81
3,620,960
def rotate_via_numpy(xy, radians): """Use numpy to build a rotation matrix and take the dot product.""" x, y = xy c, s = np.cos(radians), np.sin(radians) j = np.array([[c, -s], [s, c]]) m = np.dot(j, np.array([x, y])) return m[0], m[1]
3567c8732a43d8a36dc92828d9d353822667b9f1
3,620,961
def get_quadrant(x, y): """ Returns the quadrant as an interger in a mathematical positive system: 1 => first quadrant 2 => second quadrant 3 => third quadrant 4 => fourth quadrant None => either one or both coordinates are zero Parameters ---------- x : float x coordina...
8650edb7a3e854eed0559f633dcf5cd0c7310db4
3,620,962
import pathlib def get_python_script_path(conn: fabric.Connection, envdir: pathlib.Path, scriptname: str = 'python') -> pathlib.Path: """Get path to specific script from Python/Anaconda environment.""" if not is_windows(conn): path = envdir / 'bin' / scriptname else: path = None p...
165e791f770999dad1df3a34767d4fdbdfdde8ab
3,620,963
import torch def get_nn_avg_dist(emb, query, knn): """ Compute the average distance of the `knn` nearest neighbors for a given set of embeddings and queries. Use Faiss if available. """ if True: # emb = emb.cpu().numpy() # query = query.cpu().numpy() if hasattr(faiss, '...
bdae7eccc624c04a766d2d905719204838efee36
3,620,964
def days_in_month(year, month): """ Inputs: year - an integer between datetime.MINYEAR and datetime.MAXYEAR representing the year month - an integer between 1 and 12 representing the month Returns: The number of days in the input month. """ leapyear=0 if(year%4 ...
b2988e9a6b1413ef0957413c10e5e4f5ef225d8b
3,620,965
def calculateUsedWater(temp_tank_before, temp_tank_after): """Calculate amount of used water based on temperature change and tank volume. :param temp_tank_before: float number :param temp_tank_after: float number :return: float used water volume in liters """ used_w = (tank_volume * (temp_tank_...
d737509368163112609e989cfe0f4f577eb4ff84
3,620,966
import requests import json def _get_token(user, password, host, port): """ Gets auth token. """ token_url = "{}:{}/api/token/".format(host, port) response = requests.post(token_url, json={ "username": user, "password": password }) if response.ok: return json.loads(response...
701bb7c1a740cfeca5c321bb6662b8f4e701cd81
3,620,968
def get_gin_confg_strs(): """ Obtain both the operative and inoperative config strs from gin. The operative configuration consists of all parameter values used by configurable functions that are actually called during execution of the current program, and inoperative configuration consists of all p...
e803bb988e7376997df0fd91febdbdd4d8353255
3,620,969
def post_queries_for_all_snapshots(network) -> Response: """Post query request for all snapshots Args: network (str): Network name Returns: Response: List[WholeQuerySummaryDict] Note: POST parameter: * query (str): Optional: target query (limit a query) """ req = ...
65c24abea9b6eeca0759a37877a8a490fd0ca9b9
3,620,970
import random def random_point(): """Returns a random point on a 100x100 grid.""" return (random.randrange(100), random.randrange(100))
6a2a2c3a4bc3f8347d538984354c2d9688989e14
3,620,971
def list_sharepoint_sites_command(client, *_): """ This function runs list tenant site command :return: human_readable, context, result """ result = client.list_sharepoint_sites() parsed_sites_items = [parse_key_to_context(item) for item in result["value"]] human_readable_content = [ ...
256928baedbeb5cbd350af40187a47a871dbf793
3,620,972
def explode_list_columns(df,explode_cols): """Own implementation of pandas explode we need an older version of pandas to run the code""" no_explode_cols = list(np.setdiff1d( df.columns , explode_cols)) df = df.set_index(no_explode_cols).apply(lambda x: x.apply(pd.Series).stack()).reset_index() return df
8a17ab140b7bd408ab0afa71b7d6ded21437620d
3,620,973
import _ctypes def _sparse_dense_vector_mult(matrix_a, vector_b, scalar=1., transpose=False, out=None, out_scalar=None, out_t=None): """ Multiply together a sparse matrix and a dense vector :param matrix_a: Left (A) matrix :type matrix_a: sp.spmatrix.csr, sp.spmatrix.csc :param vector_b: Right (B...
2dfd4ffc0d516860eb77f793cf4a5001b3880ca8
3,620,974
def get_prefix(bot, message): """ A callable prefix for the bot separeted into guilds and DM's Parameters ---------- bot commands.Bot message discord message """ prefixes = ['spektrumiter ', '!'] if not message.guild: return '!' return commands.when_me...
80f1d9b67f4bb766e5d841b1a9e0bc35e2d64e43
3,620,975
async def pergamum_login(session): """Logins the web session into the pergamum system.""" login_url = '/'.join([BIB_URL, 'pergamum/mobile/login.php']) data = { 'flag': 'renovacao.php', 'login': PERGAMUM_LOGIN, 'password': PERGAMUM_PASS, 'button': 'Acessar' } headers =...
16835cf3de7cc1dfd4964cdf75ce478d94e1f788
3,620,976
def ans(m, H, c=2, n=32): """Method of manufactured solutions test""" # setup grid d = H / n z = np.arange(n) * d + d / 2 zi = np.arange(n + 1) * d # setup solution rho = np.exp(-c * z / H) rhoi = np.exp(-c * zi / H) # rhoi = centered_to_interface(rho) w = np.sin(m * np.pi *...
41ae151b046c02128af021c07c200fd905781e42
3,620,977
def _align_for_coadd(imglist): """ Algin a group of images for coadding with astroalign. Parameters ---------- imglist : list list of images to align Returns ------- newlist : list list of new SingleImage instances with aligned images Notes ----- We wil...
d49659f0536ca3bbc4798a0f169a5edbcc0865da
3,620,978
from io import IOBase import json def create_from_json_file(filename, **kwargs): """Create a dlapp instance from JSON filename. Parameters ---------- filename (str): JSON filename. kwargs (dict): keyword arguments which would use for JSON instantiation. Returns ------- DLQuery: a DLQ...
bf2944660f704c9d2078dc44940121552ff95815
3,620,979
def control( year: int, month: int = 1, day: int = 1, hour: int = 1, minute: int = 1, half: int = 1, quarter: int = 1, week: int = 1): """Control function. Controls if the given time is possible. :param year: the year to control :param month: the month :param day: the day :param hou...
05bb25be10613fcdb0e4a7aba7a07646eb8118f5
3,620,980
def repeat(s, n): """ (str, int) -> str Return s repeated n times; if n is negative, return empty string. >>> repeat('yes', 4) 'yesyesyesyes' >>>repeat('no', 0) '' """ return (s * n)
b44b56b9e69783c7f57e99b61cc86e975c575a59
3,620,981
def convert_to_issues(statements): """Produce list of offending statements in set of files. :param statements: one item from list created by add_statement """ files = dict() for statement, path in statements: if path in files: files[path].update(statement) if statem...
681026d36b384a062c8420ad7ec8aa117d3d7097
3,620,982
from sklearn.mixture import GaussianMixture import warnings def gaussian_mixture_sm(eigvals, eigvecs, n_clusters, n_components=None, weight_by_eigval=False, keep_first=True, positive_eigs=False): """ Extends the Shi and Malik method to a GMM with no covariance constraints. * Use the eigenvectors of L_rw ...
9bef37ed06a61505ef46730aed60c3922de8fe63
3,620,983
def can_translate(user): """Checks if a user translate a product""" return user.permissions['perm_translate']
c6797346d8bd61637927af808bb9355a9220a91e
3,620,984
def read_xml_file_line_basis(xml_file, element): """ Read the xml file and capture only the elements we need. """ start_tag = f'<{element}>' # 3 end_tag = f'</{element}>' # 2 start_tag_identified = False # 3 captured_records = list() # 4 captured_line = '' with open(xml_file) as f: #...
be45d97bd3ca051f06c775b21184c158472cd824
3,620,985
def findDeque(code): """ Find the use of deque in the code Documentation: Fluent Python page 54 https://docs.python.org/2/library/collections.html#collections.deque https://pymotw.com/2/collections/deque.html """ dequeToken = (Token.Name, '^deque$') dequeIdi...
19a99c918311c3431a2499125725aaee83c99aa3
3,620,986
import html def create_footer(): """page footer""" footer = html.Footer( [ html.Div( [ html.P( [ html.Span( "{0}, version 0.1.0".format(app_name), ...
35ea610235749332fb7128afeadd9fcabde6b78d
3,620,987
def xyz_string(labels, coords): """ .xyz format string for this cartesian geometry :param labels: optional labels for the beginnings of atom lines, by index :type labels: dict """ assert len(labels) == len(coords) dxyz = '\n'.join( '{:s} {:s} {:s} {:s}'.format(asymb, *map(repr, xyz)) ...
be2d34fe41a3468c0764bbfd9d6960dc377375cc
3,620,988
def lazydict(f): """Decorator for constructing lazy dicts from a function.""" return LazyDict(f, f.__globals__, f.__name__)
633d62ac22c7253c753fbd9cc645cc6f1eb676a9
3,620,989
import pandas def Protein_translation_Amb(t, y, data, mRNAData): """ Defines ODE function Conversion of Amb_mRNA to protein p1,p2,p3....: Protein concentrations for all ODEs It will have list of all parameter values for all my ODEs, so 36 values : L, U, D for each mRNA to protein conversion equation ...
1730cf15d57566dc9ec461f3631fe0feeddd4b49
3,620,990
import logging import asyncio import inspect def allow_sync_invocation(): """ A class decorator, used to make all public async methods of the class to be invoke synchronically This action would take place only if the class has async_mode=False attribute """ def allow_sync_mode(func): def ...
7683001f7994d39b44747a0858c8663de2e202f3
3,620,991
def IssueRetryableCommand(cmd, env=None): """Tries running the provided command until it succeeds or times out. Args: cmd: A list of strings such as is given to the subprocess.Popen() constructor. env: An alternate environment to pass to the Popen command. Returns: A tuple of stdout and stde...
52cedab55d28c9f6cda2bcba7284dce5ced9afa7
3,620,992
def square(num): """ Return the square values of the input number. The input number must be integer. """ return num ** 2
e4f88e5f00de7c469d372d9ce1a7e539941b3857
3,620,994
import requests def run_ticket_validation(provider_details, key_url=None, key=None, appid=None): """ Validates Steam session ticket. 'key' is the access key for Steam API. If not set, then 'key_url' must point to it. 'appid' is the Steam App ID for this application. Returns a unique ID for this p...
99fbeb6941a07084f115dc34010c4dad92b67b56
3,620,995
import math def timestamp_to_hex(timestamp): """ # 时间戳数转化为十六进制字符串 :param timestamp: 时间戳数 :return: 时间戳对应的十六进制字符串 """ if timestamp < 0: # 如果输入的时间戳数是负值 timestamp *= -1 # 则转化为正数 timestamp_list = math.modf(timestamp) # 分割整数位和小数位成为元组,第一个位置是小数位,第二个位置是整数位 four_byte_second = hex(int...
ba5c1118e3a0a9a55157a98cf5b7693d6540b151
3,620,996
import threading import time def launch_file_toucher(f): """Launch a loop to touch the given file, and return a function to call to stop and join it.""" halt = threading.Event() def file_toucher(): while not halt.isSet(): touch(f) time.sleep(1) thread = threading.Thread(target=file_toucher) ...
4581fb5906000f1c5032e1e40b4f9666d430f65e
3,620,997
def parse_gcov_file(gcov_file): """Parses the content of .gcov file written by gcov --intermediate-format Returns: str: Source file name dict: coverage info { line_number: hits } """ count = {} with open(gcov_file) as fh: for line in fh: tag, value = line.split(':') ...
878b51b9ee2e11aa7e2364229d1fbe61b9558e0d
3,620,998
def get_default_ophys_metadata(): """Fill default metadata for optical physiology.""" metadata = get_default_nwbfile_metadata() metadata.update( Ophys=dict( Device=[dict(name="Microscope")], Fluorescence=dict( roi_response_series=[ dict( ...
f50e23117d79f0d1d0b9e5c401e8bb2f60ed996d
3,620,999
from typing import OrderedDict def apply_address_fixups(address: OrderedDict[str, str]) -> OrderedDict[str, str]: """Sometimes the usaddress parser makes mistakes. It's an imperfect world. This function applies transformations to the parsed address to correct specific known errors. """ # Fixup: At...
735f7e035b352b21b9b7998b8aa6f5ad7ac826d7
3,621,000
def get_slaves(): """Get the list of slave nodes""" slaves = range(mpi_comm.Get_size()) slaves.remove(mpi_master) return slaves
c255a0068b354ef6d385299ad581bb61999736f1
3,621,002
def _max(arr, axis = 0): """The max function. Args: arr -- The array. axis -- The axis (0 by default) Returns: The max value along the axis. """ return extrema(max, arr, axis)
fbe78449f945f22dc78cfff9ad2169e0f8029982
3,621,003
import socket def _get_results_socket(): """Instantiate the results socket for sending binary results.""" client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sock = '/_abaco_results.sock' try: client.connect(sock) except (FileNotFoundError, ConnectionError) as e: msg = "Excep...
76cea0132285d44a4bc21fcea84a75e8acf408a7
3,621,004
import torch def mask_finished_scores(score, flag): """ If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score and the rest -inf score. Args: score: A real value array with shape [batch_size * beam_size, beam_size]. flag: A bool ar...
87d5d8fb45a44c54cd690280ce0baf0c4fe8dab5
3,621,005
from typing import Dict from typing import Any def get_user(url: str, access_key: str) -> Dict[str, Any]: # pylint: disable=unused-argument """Execute the OpenAPI `GET /v1/users`. Arguments: url: The URL of the graviti website. access_key: User's access key. Returns: The respons...
7b54fb5950aa1c0d69305cd8e1a8b14b81c7bb99
3,621,006
def streamers_alter_workers(streamers): """ Alter the number of workers currently in a cluster RouteParams: """ streamers = int(streamers) account = request.form['account'] user = request.form['user'] spot = request.form.get('spot') is not None if streamers != 1 and streamers != ...
836c60e1d28a031abcdd50b4ff5c6af733e14292
3,621,007
def get_default_scaler(model_type): """ Get default values for scaler in and output for each model. Args: model_type (str): Model identifier. Returns: Dict: Scaling dictionary. """ if model_type == 'mlp_e': return EnergyStandardScaler() elif model_type == 'mlp_eg':...
da5a116db83e90687de5cf74bb346e87c7473c4a
3,621,008
import numbers def get_correlation(arg1,arg2=None): """Return correlation The input arguments may be a pair of uncertain numbers, or a single uncertain complex number. When a pair of uncertain real numbers is provided, the correlation between the arguments is returned as a real nu...
7ee642b247cf6b5daeb61f614ad503ef75c29224
3,621,010
def rotmat2d(theta: float) -> np.ndarray: """Convert angle `theta` (in radians) to a 2x2 rotation matrix.""" s = np.sin(theta) c = np.cos(theta) R = np.array([[c, -s], [s, c]]) return R
64550e94ef7c31263a0a4e453b14f6d17016dfd8
3,621,012
def Vector(size, dtype='float32', name=None): # pylint: disable=invalid-name """A block that converts its input to a vector.""" return Tensor(shape=[size], dtype=dtype, name=name).set_constructor_name( 'td.Vector')
63299f889274e68f3431fc59e451cc02c88bb7f0
3,621,013
from typing import Sequence from typing import List def render_correlation_single_heatmaps( itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str] ) -> Tabs: """ Render correlation heatmaps, but with single column """ tabs: List[Panel] = [] tooltips = [("y", "@y"), ("co...
73c3704c0c05883a0354d33ea77cc28253e066fd
3,621,014
def get_blocks(text): """ Get a traversed README doctree Args: text: Text of the example's README Returns: Returns an iterable containing the README document structure See `traverse` implementation in docutils/nodes.py for more details. """ doctree = publish_doctree(text) ...
a5e193c6b3313a0951201b66bffa41f1210b5954
3,621,015
import itertools def args_combinations(*args, **kwargs): """ Given a bunch of arguments that are all a set of types, generate all possible possible combinations of argument type args is list of type or set of types kwargs is a dict whose values are types or set of types """ def asset(v): ...
8e90ce285322bd17a97e4bdb75e230f7015f4b2d
3,621,017
import copy def coordinate_tensor(dim): """ :param dim: list of lengths for each dimension :return: a list of every possible coordinate within the dimension system """ # recurrent function def recurrent_dim_filler(dim_current, dim_higher, coordinate_higher, coordinates): # processing...
8a5e2f11b5157cb2500748ea149305a21b562b77
3,621,018
def vimeval(cmd, to_int=0): """ :to_int: 0 for original 1 for int 2 for float """ r = vim.eval(cmd) if to_int == 0: return r if to_int == 1: return int(r) return float(r)
9a4aa37c58f99261cea95e290f620885ae27d567
3,621,020
def RGBStringToList(rgb_string): """Convert string "rgb(red,green,blue)" into a list of ints. The purple air JSON returns a background color based on the air quality as a string. We want the actual values of the components. Args: rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)". Returns: ...
f94650ed977b5a8d8bb85a37487faf7b665f2e76
3,621,021
def preprocessing(df, deduplicate=False): """ Split the `sen_tok` column into sentence ID (combined with note ID) and token ID. If the `deduplicate` parameter is True, duplicate notes are removed. """ if deduplicate: df = deduplicate_notes(df) return df.assign( sen_id = lambda df...
a59dbd42d10cd7a141084b0018006f9041a5dad0
3,621,022
def get_files_involved_in_pr(repo, pr_number): """ Return a list of file names modified/added in the PR """ headers = {"Accept": "application/vnd.github.VERSION.diff"} query = f"/repos/{repo}/pulls/{pr_number}" r = utils.query_request(query, headers=headers) patch = unidiff.PatchSet(r.cont...
01a051eed32ea3fb3c566eb7167f5628d698580b
3,621,023
def csv(file_path): """Read CSV file, return DataFrame""" return pd.read_csv(file_path)
5cdeb33eae908699d1ade6e5688e171236254d95
3,621,024
import six def _metric_value(value_str, metric_type): """ Return a Python-typed metric value from a metric value string. """ if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". ...
39a3b0e5bfe2180e1897dd87872f8e08925e8847
3,621,025
def point_sample_raster(gdf, rds, win_radius=0, stat_func=np.mean, col_names=None): """ Sample all bands of a raster data set `rds`, and attribute each point of a geopandas GeoDataFrame `gdf`. A radius value can be supplied to sample the mean of a square window rather than individual pixels. Parame...
7672bf4a9937c3d1955402e3a1cdd8caa8353ead
3,621,026
def vol_spherical_cap(height: float, radius: float) -> float: """ Calculate the Volume of the spherical cap. :return 1/3 pi * height ^ 2 * (3 * radius - height) >>> vol_spherical_cap(1, 2) 5.235987755982988 """ return 1 / 3 * pi * pow(height, 2) * (3 * radius - height)
cc07575f2f98cf21ecae5b6ca9a4dd669ff83722
3,621,027
def im2col(input_data, filter_h, filter_w, stride=1, pad=0): """ Parameters ---------- input_data : (データ数, チャンネル, 高さ, 幅)の4次元配列からなる入力データ filter_h : フィルターの高さ filter_w : フィルターの幅 stride : ストライド pad : パディング Returns ------- col : 2次元配列 """ N, C, H, W = input_data.shape ...
656b7ff1875cef679ea08a04f5df7cd644a06aaf
3,621,028
def generate_g(b, d, p, q): """Compute a generator of a subgroup of Z^*_n that has order b**d mod p and order b**d mod q""" rs = PRNG() b_to_the_d = b ** d while True: x = rs.random_Zsp(p) if gmpy2.powmod(x, mpz((p-1)/b), p) != 1: gp = gmpy2.powmod(x, mpz((p-1)/b_to_the_d...
29ff505e932e46075b35ce004a752ef572742914
3,621,029
def load_runner( tag: t.Union[str, Tag], name: t.Optional[str] = None, resource_quota: t.Optional[t.Dict[str, t.Any]] = None, batch_options: t.Optional[t.Dict[str, t.Any]] = None, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "_PyFuncRunner": """ Runner represents a...
2ac4f43a9be98327995e05fbee93a71464c476bc
3,621,030