content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def domain_delete(domainName): # noqa: E501 """domain_delete Remove the domain # noqa: E501 :param domainName: :type domainName: str :rtype: DefaultMessage """ return 'do some magic!'
a0865aa2ff4902ac5cf8a8c0ea9eb62e792af56b
24,691
from datetime import datetime def ParseDate(s): """ ParseDate(s) -> datetime This function converts a string containing the subset of ISO8601 that can be represented with xs:dateTime into a datetime object. As such it's suitable for parsing Collada's <created> and <modified> elements. The date must b...
d65e4bb51487d9cb22b910e3dc44e299882600b5
24,692
def kinetic_energy(atoms): """ Returns the kinetic energy (Da*angs/ps^2) of the atoms. """ en = 0.0 for a in atoms: vel = v3.mag(a.vel) en += 0.5 * a.mass * vel * vel return en
8615d61f30f5ded029d1c230346682a040d05e87
24,693
def boxes_intersect(boxes, box): """Determine whether a box intersects with any of the boxes listed""" x1, y1, x2, y2 = box if in_box(boxes, x1, y1) \ or in_box(boxes, x1, y2) \ or in_box(boxes, x2, y1) \ or in_box(boxes, x2, y2): return True return False
b2201e1501a7827b6db8ef63ebf468b3e1839800
24,694
def cumulative_mean_normalized_difference_function(df, n): """ Compute cumulative mean normalized difference function (CMND). :param df: Difference function :param n: length of data :return: cumulative mean normalized difference function :rtype: list """ # scipy method cmn_df = df[...
974c0bdaab0e8872ef746839c8d973604eab6929
24,695
def minimal_subject_transformer(index, minimal_subject, attributes, subject_types, subject_type_is, center, radius): """Construct the JSON object for a MinimalSubject.""" subdomain, type = minimal_subject.subdomain, minimal_subject.type # Gather all the attributes values...
3babc222c508850b8b5bdea551efa8c9e9bc0aa4
24,697
def beta_avg_inv_cdf(y, parameters, res=0.001): """ Compute the inverse cdf of the average of the k beta distributions. Parameters ---------- y : float A float between 0 and 1 (the range of the cdf) parameters : array of tuples Each tuple (alpha_i, beta_i) i...
01c266e21401f6f7ad624151aa40d195c9196453
24,698
def _aprime(pHI,pFA): """recursive private function for calculating A'""" pCR = 1 - pFA # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _aprime(1-pHI ,1-pFA) # Pollack and Norman's (1964) A' measure # formula from Grier 1971 i...
3694dcdbc5da2c12bece51e85988245a60ebe811
24,699
def requires_testing_data(func): """Skip testing data test.""" return _pytest_mark()(func)
a3f5116bc3ac1639de13355795f2bd1da67521aa
24,700
def mfcc_derivative_loss(y, y_hat, derivative_op=None): """ Expects y/y_hat to be of shape batch_size x features_dim x time_steps (default=128) """ if derivative_op is None: derivative_op = delta_matrix() y_derivative = tf.matmul(y, derivative_op) y_hat_derivative = tf.matmul(y_hat, deri...
8d2b05d65ae3efb10d00f0b30d75ca45abf92064
24,701
from typing import List def get_mprocess_names_type1() -> List[str]: """returns the list of valid MProcess names of type1. Returns ------- List[str] the list of valid MProcess names of type1. """ names = ( get_mprocess_names_type1_set_pure_state_vectors() + get_mproces...
e02b8e5ccc6153899fd999d669a34f14f2258170
24,704
def LoadAI(FileName): """LoadSC: This loads an IGOR binary file saved by LabView. Loads LabView Scope data from igor and extracts a bunch of interesting information (inf) from the data header""" IBWData = igor.LoadIBW(FileName); # I am going to store the experimental information in a dictionary ...
d1d434c72e1d50bd857bddba1c4e750f74ea901b
24,705
def accept_message_request(request, user_id): """ Ajax call to accept a message request. """ sender = get_object_or_404(User, id=user_id) acceptor = request.user if sender in acceptor.profile.pending_list.all(): acceptor.profile.pending_list.remove(sender) acceptor.profile.conta...
52a7701433a3ff4acbc6adf6cea3ee64303eee02
24,706
import pytz def pytz_timezones_from_utc_offset(tz_offset, common_only=True): """ Determine timezone strings corresponding to the given timezone (UTC) offset Parameters ---------- tz_offset : int, or float Hours of offset from UTC common_only : bool Whether to only return ...
4890acae850530b4b7809afb1c09a5cf4795b443
24,707
from sage.arith.all import rising_factorial def _sympysage_rf(self): """ EXAMPLES:: sage: from sympy import Symbol, rf sage: _ = var('x, y') sage: rfxy = rf(Symbol('x'), Symbol('y')) sage: assert rising_factorial(x,y)._sympy_() == rfxy.rewrite('gamma') sage: assert ris...
c3f55efdcca393cb795f35160131eb781721202a
24,708
def run_sax_on_sequences(rdd_sequences_data, paa, alphabet_size): """ Perform the Symbolic Aggregate Approximation (SAX) on the data provided in **ts_data** :param rdd_sequences_data: rdd containing all sequences: returned by function *sliding_windows()*: *sequences_data* contain a list of all seq : tu...
4f23894355abfa29094c0b8974e2a7a2e50b6789
24,710
from typing import Union def attack_speed(game: FireEmblemGame, unit: ActiveUnit, weapon: Union[ActiveWeapon, None]) -> int: """ Calculates and returns the unit's Attack Speed, based on the AS calculation method of the current game, the unit's stats, the given weapon's Weight. If the weapon is None, a...
268af7ee65e6bab291818a5fece35006b1209c90
24,711
def set_pow_ref_by_upstream_turbines_in_radius( df, df_upstream, turb_no, x_turbs, y_turbs, max_radius, include_itself=False): """Add a column called 'pow_ref' to your dataframe, which is the mean of the columns pow_%03d for turbines that are upstream and also within radius [max_radius] of the turbi...
10ee016f3dbd86bd047dc75a10fa13701cf64fca
24,712
def load_block_production(config: ValidatorConfig, identity_account_pubkey: str): """ loads block production https://docs.solana.com/developing/clients/jsonrpc-api#getblockproduction """ params = [ { 'identity': identity_account_pubkey } ] return smart_rpc_call(co...
3af5bc21772699fa10102147fb4a3d90569d8cff
24,713
def remove_metatlas_objects_by_list(object_list, field, filter_list): """ inputs: object_list: iterable to be filtered by its attribute values field: name of attribute to filter on filter_list: strings that are tested to see if they are substrings of the attribute value returns filte...
8885a355fcf79696ef84d13242c28943999693b5
24,715
def resnet_encoder(inputs, input_depth=16, block_type='wide', activation_fn=tf.nn.relu, is_training=True, reuse=None, outputs_collections=None, scope=None): """Defines an encoder network based on resnet...
80a136a2d6a4047a92a9c924e92523136017354b
24,716
def execute_stored_proc(cursor, sql): """Execute a stored-procedure. Parameters ---------- cursor: `OracleCursor` sql: `str` stored-proc sql statement. """ stored_proc_name, stored_proc_args = _sql_to_stored_proc_cursor_args(sql) status = cursor.callproc(stored_proc_name, pa...
528a5b19c208695db0eff8efdb18c1e30cb484b4
24,717
def no_order_func_nb(c: OrderContext, *args) -> Order: """Placeholder order function that returns no order.""" return NoOrder
8bfb6c93930acdf03b83e90271e6904ce5a8e689
24,718
def get_queued(): """ Returns a list of notifications that should be sent: - Status is queued - Has scheduled_time lower than the current time or None """ return PushNotification.objects.filter(status=STATUS.queued) \ .select_related('template') \ .filter(Q(scheduled_time__lte=...
4fa14ad21a2954e1f55df562ccd10edf356b3d02
24,719
def hue_of_color(color): """ Gets the hue of a color. :param color: The RGB color tuple. :return: The hue of the color (0.0-1.0). """ return rgb_to_hsv(*[x / 255 for x in color])[0]
06fd67639f707d149c1b0b21ffc0f337faf1fbe0
24,720
import requests def recent_tracks(user, api_key, page): """Get the most recent tracks from `user` using `api_key`. Start at page `page` and limit results to `limit`.""" return requests.get( api_url % (user, api_key, page, LastfmStats.plays_per_page)).json()
f0814fca86dfdcb434527ebbefcea867045359fe
24,721
def extract_hdf5_frames(hdf5_frames): """ Extract frames from HDF5 dataset. This converts the frames to a list. :param hdf5_frames: original video frames :return [frame] list of frames """ frames = [] for i in range(len(hdf5_frames)): hdf5_frame = hdf5_frames[str(i)] assert l...
f22b8ef61a86de45c0801ab3ff8cba679549387b
24,722
def st_oid(draw, max_value=2**512, max_size=50): """ Hypothesis strategy that returns valid OBJECT IDENTIFIERs as tuples :param max_value: maximum value of any single sub-identifier :param max_size: maximum length of the generated OID """ first = draw(st.integers(min_value=0, max_value=2)) ...
e43daccf3b123a1d35e1c1cc9c313b580161971a
24,723
import torchvision def predict(model, image_pth=None, dataset=None): """ Args: model : model image (str): path of the image >>> ".../image.png" dataset [Dataset.Tensor]: Returns: -------- predicted class """ transform = transforms.Compose([ transforms...
16a0a429b0fb42ac2c58df94b25d52478d5288a7
24,724
def to_centers(sids): """ Converts a (collection of) sid(s) into a (collection of) trixel center longitude, latitude pairs. Parameters ---------- sids: int or collection of ints sids to covert to vertices Returns -------- Centers: (list of) tuple(s) List of centers. A cente...
795e6f60d21997b425d60a2859a34ca56f94c7fb
24,725
def get_atlas_by_id(atlas_id: str, request: Request): """ Get more information for a specific atlas with links to further objects. """ for atlas in siibra.atlases: if atlas.id == atlas_id.replace('%2F', '/'): return __atlas_to_result_object(atlas, request) raise HTTPException( ...
f37079c16c6bbcf17295e7e14be21cbc3c38bd1e
24,726
def load_etod(event): """Called at startup or when the Reload Ephemeris Time of Day rule is triggered, deletes and recreates the Ephemeris Time of Day rule. Should be called at startup and when the metadata is added to or removed from Items. """ # Remove the existing rule if it exists. if not d...
74f9b1d4644417263eb2bfe56543baa9ebf0d0a1
24,727
def extract_title(html): """Return the article title from the article HTML""" # List of xpaths for HTML tags that could contain a title # Tuple scores reflect confidence in these xpaths and the preference # used for extraction xpaths = [ ('//header[@class="entry-header"]/h1[@class="entry-ti...
c9a26c6e54e0e4d26c9f807499103bce51b3a1b3
24,728
def re_send_mail(request, user_id): """ re-send the email verification email """ user = User.objects.get(pk=user_id) try: verify = EmailVerify.objects.filter(user = user).get() verify.delete() except EmailVerify.DoesNotExist: pass email_verify = EmailVerify(user=...
f07c7f55e8bd5b4b1282d314bf96250a031937db
24,729
def add_map_widget( width: int, height: int, center: tuple[float, float], zoom_level: int, tile_server: TileServer, ) -> int | str: """Add map widget Args: width (int): Widget width height (int): Widget height center (tuple[float, float]): Center point coordinates: ...
b6a9bd455f8394485a48f6ba45d0084baa1b24b1
24,732
from typing import List def _index_within_range(query: List[int], source: List[int]) -> bool: """Check if query is within range of source index. :param query: List of query int :param source: List of soure int """ dim_num = len(query) for i in range(dim_num): if query[i] > source[i]: ...
34c595a3c498fbe1cce24eea5d5dc1866bbbcfac
24,733
from typing import List def test_transactions() -> List[TransactionObject]: """ Load some example transactions """ transaction_dict_1 = { "amount": 1.0, "asset_id": 23043, "category_id": 229134, "currency": "usd", "date": "2021-09-19", "external_id": Non...
8aa52fdbf719793e9f93a276097498f70b4973a6
24,735
def modified(mctx, x): """``modified()`` File that is modified according to status. """ # i18n: "modified" is a keyword getargs(x, 0, 0, _("modified takes no arguments")) s = mctx.status()[0] return [f for f in mctx.subset if f in s]
ec647f7478c587b35e9a1d7b219754fabf3940a8
24,736
def parse_declarations(lang, state, code_only=False, keep_tokens=True): """ Return the comments or code of state.line. Unlike parse_line, this function assumes the parser is *not* in the context of a multi-line comment. Args: lang (Language): Syntax description for the language being...
48b1ea0259795ef3f7acd783b704be5e4be8a79b
24,737
import math def rads_to_degs(rad): """Helper radians to degrees""" return rad * 180.0 / math.pi
1be742aa4010e2fc5678e6f911dcb21b0b4d1b59
24,738
def get_employer_jobpost(profile): """ """ jobs = None if profile.is_employer: jobs = JobPost.objects.filter(user=profile.user).order_by('title', 'employment_option', 'is_active') return jobs
d1be49c5381aedfd21d6dbceb07eeb98f1ef3dc4
24,739
def _paginate_issues_with_cursor(page_url, request, query, cursor, limit, template, extra_nav_parameters=None, ...
a315163a9d0e53473ce77e262edf3b7f6e663802
24,740
def overlapping(startAttribute, # X endAttribute, # Y startValue, # A endValue, # B ): """ Return an L{axiom.iaxiom.IComparison} (an object that can be passed as the 'comparison' argument to Store.query/.sum/.count) which will const...
66e56c9a7c66cbc385e4b7bbea4aa6c08212993e
24,741
def _aligned_series(*many_series): """ Return a new list of series containing the data in the input series, but with their indices aligned. NaNs will be filled in for missing values. Parameters ---------- many_series : list[pd.Series] Returns ------- aligned_series : list[pd.Series...
6598dff7814ef20dd0f4904b6c140b6883f9283b
24,742
def structConfMat(confmat, index=0, multiple=False): """ Creates a pandas dataframe from the confusion matrix. It distinguishes between binary and multi-class classification. Parameters ---------- confmat : numpy.ndarray Array with n rows, each of one being a flattened confusion matrix...
25b458a81a96c8d38d990cd43d3fab5c6526dabd
24,743
from . import data import datasets import pkg_resources def get_img(ds): """Get a standard image file as a Niimg Parameters ---------- ds : str Name of image to get.\n Volume Masks:\n "MNI152_T1_2mm_brain"\n "MNI152_T1_2mm_brain_mask"\n "MNI152_T1_2mm_brain_mas...
0df5bbd1d5188a8d67a7078625734f4b186ca2e9
24,744
from typing import Tuple from typing import Optional def check_for_missing_kmers(is_fastq: bool, subtype_result: str, scheme: str, df: pd.DataFrame, exp: int, obs: int, ...
add7449112c7720bb56a8d682030c7220991ff7b
24,746
import torch import itertools def splat_feat_nd(init_grid, feat, coords): """ Args: init_grid: B X nF X W X H X D X .. feat: B X nF X nPt coords: B X nDims X nPt in [-1, 1] Returns: grid: B X nF X W X H X D X .. """ wts_dim = [] pos_dim = [] grid_dims = init...
24e798dd9cdaf51988c5229442bef4ebed14c4be
24,747
from typing import Any from typing import Optional import torch def q_nstep_td_error_ngu( data: namedtuple, gamma: Any, # float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(reduction='no...
eac618bddf77252e6be77f8254fa14f8e00e2c68
24,748
import time import hashlib def generate_activation_code(email : str) -> str: """ Takes email address and combines it with a timestamp before encrypting everything with the ACTIVATION_LINK_SECRET No database storage required for this action :param email: email :type email: unicode :return: act...
d2770bf9e2d15e361fa5dcf145fba978f40cb06f
24,749
def fmin_sgd(*args, **kwargs): """ See FMinSGD for documentation. This function creates that object, exhausts the iterator, and then returns the final self.current_args values. """ print_interval = kwargs.pop('print_interval', sys.maxint) obj = FMinSGD(*args, **kwargs) while True: t ...
91173eb8c2b4732c217be4ff170d5821eb1e9e5f
24,750
def scan(this, accumulator, seed=None): """Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. For aggregation behavior with no intermediate results, see OutputThing.aggregate. 1 - scanne...
4d69686f41c93549208b2e0721e14d95c7c52321
24,753
def get_efficient_pin_order_scramble(): """ Gets an efficient pin order scramble for a Rubik's Clock. """ return _UTIL_SCRAMBLER.call("util_scramble.getClockEfficientPinOrderScramble")
edf20cd55f9e2c8e7e3aa0f73f08c34958336a44
24,754
def fixed_padding(inputs, kernel_size): """Pad the input along the spatial dimensions independently of input size. This function is copied/modified from original repo: https://github.com/tensorflow/tpu/blob/acb331c8878ce5a4124d4d7687df5fe0fadcd43b/models/official/resnet/resnet_model.py#L357 Args: ...
ac20d85fff8abd1ea6b160294f1f0a3118e09527
24,755
def _is_si_object(storage_instance): """ Helper method for determining if a storage instance is object. Args: storage_instance: Returns: (Bool) True if object, False if not. """ si_type = storage_instance.get("service_configuration", None) if si_type is None: # object not su...
3cc2591bb0391e6d9d62197d0bb593f5006215c8
24,756
def wgs84_to_bd09(lng, lat): """WGS84 -> BD09""" lng, lat = wgs84_to_gcj02(lng, lat) lng, lat = gcj02_to_bd09(lng, lat) return lng, lat
e0d0b7dfa70b8e260b8fb061b50e838463ccec08
24,757
import math def spin_images(pc1, pc2, opt = spin_image_options()): """Compute spin image descriptors for a point cloud Parameters ---------- pc1 : pcloud The function computes a spin image descriptor for each point in the point cloud pc1 pc2 : pcloud The points in the poi...
2011d2c1d610655dd752f30c4efa3abe9c7d4d29
24,758
def clone_file_info(input, output): """clone_file_info(FileConstHandle input, FileHandle output)""" return _RMF.clone_file_info(input, output)
226ee2a0a2547f4bf57754187517301e649cd919
24,759
def queries_to_retract_from_dataset(client, project_id, dataset_id, person_id_query, retraction_type=None): """ Get list of queries to remove all records in all tables ...
b0e2512da10bf1d4742995d8b5a7ed0ec15bca6a
24,760
def calc_moments(imcube, rmscube, mask=None): """ Calculate moments of a masked cube and their errors Parameters ---------- imcube : SpectralCube The image cube for which to calculate the moments and their errors. rmscube : SpectralCube A cube representing the noise estimate at ...
00c43af169f650efe155dca87b3755f128a13f7f
24,761
import types import array def value(*, source: str, current_location: types.Location) -> types.TSourceMapEntries: """ Calculate the source map of any value. Args: source: The JSON document. current_location: The current location in the source. Returns: A list of JSON pointers...
093b2df66c3577c7f24ec1cc1da3cd71bf3cdd4f
24,762
def get_class_cnts_by_feature_null(df, class_col, feature, normalize=True): """ Break out class fequencies (in `df[class_col]`) by whether or not `df[feature]` is null. Parameters ---------- df : pandas.DataFrame DataFrame on which this function will operate. class_col : str ...
9ac2ae717c2aca90ca988ad0f960365e8475a555
24,764
import gc def systemic_vel_est(z,param_dict,burn_in,run_dir,plot_param_hist=True): """ Estimates the systemic (stellar) velocity of the galaxy and corrects the SDSS redshift (which is based on emission lines). """ c = 299792.458 # Get measured stellar velocity stel_vel = np.array(param_dict['stel_vel']['c...
3d5c957147ad7f16cd664d08326ad40196f46d5e
24,765
def set_model_weights(model, weights): """Set the given weights to keras model Args: model : Keras model instance weights (dict): Dictionary of weights Return: Keras model instance with weights set """ for key in weights.keys(): model.get_layer(key).set_weights(wei...
0adb7294348af379df0d2a7ce2101a6dc3a43be4
24,767
import re def extract_manage_vlan(strValue): """处理show manage-vlan得到的信息 Args: strValue(str): show manage-vlan得到的信息 Returns: list: 包含管理Vlan字典的列表 """ # ------------------------------------ # Manage name : xx # ------------------------------------ # Svlan ...
83ff7d5af37c9caf9bf557caa9e1d845e96706fb
24,769
from typing import List def generate_sample_space_plot_detailed( run_directory: str, step: int = 0, agent_ids: List[int] = [0], contour_z: str = "action_value", circle_size: str = "action_visits", ) -> List[dcc.Graph]: """Generates detailed sample space plots for the given agents. Paramet...
544e3bebcb2ecb6d62f4228b13527e392a3dc51a
24,770
import ntpath def raw_path_basename(path): """Returns basename from raw path string""" path = raw(path) return ntpath.basename(path)
d1282ead5a8d5bf9705302347b2769421ece409b
24,771
from typing import Dict from typing import Tuple from typing import Optional def prepare_request( url: str, access_token: str = None, user_agent: str = None, ids: MultiInt = None, params: RequestParams = None, headers: Dict = None, json: Dict = None, ) -> Tuple[str, RequestParams, Dict, Op...
f1ab81d32146a102c2ac7518228c4f880d988214
24,772
def require_permission(permission): """Pyramid decorator to check permissions for a request.""" def handler(f, *args, **kwargs): request = args[0] if check_permission(request, request.current_user, permission): return f(*args, **kwargs) elif request.current_user: ...
e9321d6eaf84b80bd41d253ebd26aabecd6660ee
24,773
import _uuid def _collapse_subgraph(graph_def, inputs, outputs, op_definition): """Substitute a custom op for the subgraph delimited by inputs and outputs.""" name = _uuid.uuid1().hex # We need a default type, but it can be changed using 'op_definition'. default_type = types_pb2.DT_FLOAT new_graph = fuse_op...
f0f562c7d26876761a3d251d41a64aac5c432db0
24,774
def downsample_filter_simple(data_in, n_iter=1, offset=0): """ Do nearest-neighbor remixing to downsample data_in (..., nsamps) by a power of 2. """ if n_iter <= 0: return None ns_in = data_in.shape[-1] ns_out = ns_in // 2 dims = data_in.shape[:-1] + (ns_out,) data_out = np.e...
f3b247e552ed95f28bd9f68ac00ff39db6741d77
24,775
from datetime import datetime def _session_setup(calling_function_name='[FUNCTION NAME NOT GIVEN]'): """ Typically called at the top of lightcurve workflow functions, to collect commonly required data. :return: tuple of data elements: context [tuple], defaults_dict [py dict], log_file [file object]. """ ...
95dd3cada63e8970b3f39ff2b3f3d14797f86cd8
24,776
def find_center(image, center_guess, cutout_size=30, max_iters=10): """ Find the centroid of a star from an initial guess of its position. Originally written to find star from a mouse click. Parameters ---------- image : numpy array or CCDData Image containing the star. center_gue...
9357b6655ec094b058af0710eb6f410b49019b9b
24,777
def zGetTraceArray(numRays, hx=None, hy=None, px=None, py=None, intensity=None, waveNum=None, mode=0, surf=-1, want_opd=0, timeout=5000): """Trace large number of rays defined by their normalized field and pupil coordinates on lens file in the LDE of main Zemax application (not in the DDE ser...
986d69d3adae09841fb1b276e9b182a93f4c7fd7
24,778
def bin2bytes(binvalue): """Convert binary string to bytes. Sould be BYTE aligned""" hexvalue = bin2hex(binvalue) bytevalue = unhexlify(hexvalue) return bytevalue
ecc90282e7b247f0e87f8349e382d2b2a194cf77
24,779
from typing import Optional def _report_maker( *, tback: str, func_name: Optional[str] = None, header: Optional[str] = None, as_attached: bool = False, ) -> Report: """ Make report from Args: tback(str): traceback for report. func_name(str, optional)...
a4ff80557944d774b162ac0671dd6997243ff49f
24,781
def moments(data,x0=None,y0=None): """Returns (height, x, y, width_x, width_y) the gaussian parameters of a 2D distribution by calculating its moments """ total = data.sum() X, Y = np.indices(data.shape) x = (X*data).sum()/total y = (Y*data).sum()/total col = data[:, int(y)] width_x ...
d88f8aa9938d397c205135bd1174be64bdf32d5f
24,782
def VecStack(vector_list, axis=0): """ This is a helper function to stack vectors """ # Determine output size single_vector_shape = [max([shape(vector)[0] for vector in vector_list]), max([shape(vector)[1] for vector in vector_list])] vector_shape = dcopy(single_vector_shape) vector_shape[axis] *= ...
5a2b00ec25fc34dc7a24a493b7e72edb13fbf1b9
24,784
def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ...
556af462015429173464574de0103a6f661355f7
24,785
def get_full_path(path, nx_list_subgraph): """Creates a numpy array of the line result. Args: path (str): Result of ``nx.shortest_path`` nx_list_subgraph (list): See ``create_shortest path`` function Returns: ndarray: Coordinate pairs along a path. """ p_list = [] curp ...
1849341431bf24d0dbe0920ca1ae955a6280415f
24,786
def get_compliance_site_case_notifications(data, request): """ returns the count of notification for a compliance site case and all visit cases under it. """ ids = [item["id"] for item in data] notifications = ( ExporterNotification.objects.filter( user_id=request.user.pk, organ...
639b4ef0425573e3f7806b18c7d03221d5db3932
24,787
def compare_two_data_lists(data1, data2): """ Gets two lists and returns set difference of the two lists. But if one of them is None (file loading error) then the return value is None """ set_difference = None if data1 is None or data2 is None: set_difference = None else: set...
6e926d3958544d0d8ce1cbcb54c13535c74ab66b
24,789
from typing import Any from datetime import datetime def get_on_request(field: Any, default_value: Any) -> Any: """ Функция получения значений Args: field: поле default_value: если пустое то подставим это значение Return: значение поля или дефолтное """ if isinstance(fi...
598f47d996618cfcf3790fe7497c6d51508efc48
24,790
def aptamer(ligand, piece='whole', liu=False): """ Construct aptamer sequences. Parameters ---------- ligand: 'theo' Specify the aptamer to generate. Right now only the theophylline aptamer is known. piece: 'whole', '5', '3', or 'splitter' Specify which part of the ap...
1d3b3803022d0529ff9fa393779aec5fd36cb94b
24,791
def bootstrap_ci(dataframe, kind='basic'): """Generate confidence intervals on the 1-sigma level for bootstrapped data given in a DataFrame. Parameters ---------- dataframe: DataFrame DataFrame with the results of each bootstrap fit on a row. If the t-method is to be used, a Panel i...
073276c5cf28b384716352ec386091ed252de72c
24,792
import re def get_Trinity_gene_name(transcript_name): """ extracts the gene name from the Trinity identifier as the prefix """ (gene_name, count) = re.subn("_i\d+$", "", transcript_name) if count != 1: errmsg = "Error, couldn't extract gene_id from transcript_id: {}".format(transcript_nam...
4c1ab87285dbb9cdd6a94c050e6dbed27f9f39bf
24,793
import regex def exclude_block_notation(pattern: str, text: str) -> str: """ 行を表現するテキストから、ブロック要素の記法を除外\n 除外した結果をInline Parserへ渡すことで、Block/Inlineの処理を分離することができる :param pattern: 記法パターン :param text: 行テキスト :return: 行テキストからブロック要素の記法を除外した文字列 """ return regex.extract_from_group(pattern, text,...
803d084a383b454da6d1c69a5d99ad0b4777eea7
24,794
def envfile_to_params(data): """ Converts environment file content into a dictionary with all the parameters. If your input looks like: # comment NUMBER=123 KEY="value" Then the generated dictionary will be the following: { "NUMBER": "123", "KEY": "value" } """ params = filter(lambda x: len(x) == 2,...
03d3b4eb7ea5552938e6d42dcfd4554a1fe89422
24,795
import tokenize def greedy_decode(input_sentence, model, next_symbol=next_symbol, tokenize=tokenize, detokenize=detokenize): """Greedy decode function. Args: input_sentence (string): a sentence or article. model (trax.layers.combinators.Serial): Transformer model. Returns: string...
416d61827ecb54c5ef85e2669c9905d5b20ecbf3
24,796
def get_browser_errors(driver): """ Checks browser for errors, returns a list of errors :param driver: :return: """ try: browserlogs = driver.get_log('browser') except (ValueError, WebDriverException) as e: # Some browsers does not support getting logs print(f"Could n...
fda6953703053fa16280b8a99aa91165625f6aa9
24,797
def get_user(request, user_id): """ Endpoint for profile given a user id. :param request: session request. :param user_id: id of user. :return: 200 - user profile. 401 - login required. 404 - user not found. """ try: get_user = User.objects.get(id=user_id) ...
cd790d93ed9f5f974fe4b6868f10cf2f4470f93c
24,798
def get_file_ext(url): """ Returns extension of filename of the url or path """ return get_filename(url).split('.')[-1]
419f8b1e8caac13aed500563e94cc28e40669156
24,799
def check_records(msg: dict) -> int: """ Returns the number of records sent in the SQS message """ records = 0 if msg is not None: records = len(msg[0]) if records != 1: raise ValueError("Not expected single record") return records
7036f943b733ca34adaaa5ff917b3eb246075422
24,800
def get_processes_from_tags(test): """Extract process slugs from tags.""" tags = getattr(test, 'tags', set()) slugs = set() for tag_name in tags: if not tag_name.startswith('{}.'.format(TAG_PROCESS)): continue slugs.add(tag_name[len(TAG_PROCESS) + 1:]) return slugs
16d333d1371ab533aa5ed7a26c4bdd968233edf9
24,801
import random def eight_ball(): """ Magic eight ball. :return: A random answer. :rtype: str """ answers = [ 'It is certain', 'It is decidedly so', 'Not a fucking chance!', 'without a doubt', 'Yes definitely', 'I suppose so', 'Maybe', ' No fucking way!', 'Sure :D', ...
728aea44a111a25d878ec7686038d993fe49f71c
24,803
def head(line, n: int): """returns the first `n` lines""" global counter counter += 1 if counter > n: raise cbox.Stop() # can also raise StopIteration() return line
221f8c6ac5a64b5f844202622e284053738147aa
24,804
def onehot(x, numclasses=None): """ Convert integer encoding for class-labels (starting with 0 !) to one-hot encoding. If numclasses (the number of classes) is not provided, it is assumed to be equal to the largest class index occuring in the labels-array + 1. The output is an array...
6595ef4fc837296f6ba31c78a4b3047aaca7ee49
24,805
import numpy def draw_graph(image, graph): """ Draw the graph on the image by traversing the graph structure. Args: | *image* : the image where the graph needs to be drawn | *graph* : the *.txt file containing the graph information Returns: """ tmp = draw_edges(image, graph)...
2454e654969d766af60546686d9c305c67199c8a
24,806
def valid_octet (oct): """ Validates a single IP address octet. Args: oct (int): The octet to validate Returns: bool: True if the octet is valid, otherwise false """ return oct >= 0 and oct <= 255
9dd2346bb5df5bc00bb360013abe40b8039bdc45
24,807
def load_clean_dictionaries(): """ is loading the combilex data into two dictionaries word2phone and phone2word :return: g2p_dict, p2g_dict """ grapheme_dict = {} phonetic_dict = {} with open(COMBILEX_PATH, encoding='utf-8') as combilex_file: for line in combilex_file: ...
ab7257c78ec8ba0786a0112362ba318468e69e02
24,808