content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import Type from typing import Optional def unwrap_vec_wrapper(env: Union["GymEnv", VecEnv], vec_wrapper_class: Type[VecEnvWrapper]) -> Optional[VecEnvWrapper]: """ Retrieve a ``VecEnvWrapper`` object by recursively searching. :param env: :param vec_wrapper_class:...
9d544e9789499e63303407ebfb472001b218b304
40,157
import re def parseLintignoreText(lintignoreText): """ *lintignoreText* should be the text of a 'lintignore' file. Return the corresponding list of regexes to match against file paths. """ lintignoreLines = joinLists([parseLintignoreLine(x) for x in lintignoreText....
633268d4816b544a917320a7a21862b480c64ae8
40,158
import json from typing import Counter def statistics(uid): """Return url statistics Arguments: - `uid`: The hashed id of the url """ if not DB.exists(uid): abort(404) else: entry = DB.get(uid) entry = json.loads(entry) short_link = uid full_link = ent...
d223a59e5d72e7f3aed9ef9247c45636adcab599
40,159
def ProfileMatrix(kmer_list, k, t, mode, pseudo_count=1): # nrow = t, ncol = k """Input a list of kmers and output a entropy score or profile probilities. It can be switched to hamming distance score by setting mode. """ matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list. f...
dc474d0a8dd210be1234763b0d5f141e6c3fa7e4
40,160
import re def you_to_yall(text: str) -> str: """Convert all you's to y'all.""" pattern = r'\b(y)(ou)\b' return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE)
1a3ee7ebf2394f84ad296e18da789dff8ca50a12
40,161
def svn_client_list4(*args): """svn_client_list4(char const * path_or_url, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, apr_array_header_t patterns, svn_depth_t depth, apr_uint32_t dirent_fields, svn_boolean_t fetch_locks, svn_boolean_t include_externals, svn_client_list_func2_t list_func, void * b...
5a1496f09209da8e42c199518a53e3cf4e655f91
40,162
from typing import List def trivial_max_gcd_sum(arr_a: List[int], arr_b: List[int]) -> int: """Calculate max gcd sum. Complexity: O(n^2). """ max_gcd = 0 max_sum = 0 for num_a in arr_a: for num_b in arr_b: cur_gdc = gcd(num_a, num_b) if cur_gdc > max_gcd: ...
857bf53f77e71e0aff8774641054c35927cdb8d4
40,163
import re def get_displays(): """ Return the list of displays. """ # get dispays names conns = ["xrandr", "--query"] res = Popen(conns, stdout=PIPE).communicate()[0].decode(ENC) regex = r"\n([^\s]*) (connected|disconnected).*" names = [res[0] for res in re.findall(regex, res)] # cr...
a03e10e780e6e6e91917a1d63532fd4ad522089f
40,164
def tjur_r2(y_true, y_score): """ Tjur Pseudo R-squared Parameters ---------- y_true : numpy array True values (observed response). y_score : numpy array Predicted probabilities. Returns ------- t_r2 : float Tjur Pseudo R-squared. """ y_mu1 = y_scor...
0be5ec44a8f6973219c044f7f2378eba3a6aecfb
40,165
def get_full_std_lib(indent=0): """ Get the code for the full PyScript standard library. The given indent specifies how many sets of 4 spaces to prepend. If the full stdlib is made available in JavaScript, multiple snippets of code can be transpiled without inlined stdlib parts by using ``py2js...
9349d3f565cb6a615e7e421e2f460b4ce38aae22
40,166
def unit(aClass, value): """ Calls the 'unit' method of 'aClass' with 'value'. """ return aClass.unit(value)
58c69898fc024a4ed31e4f7fd10f7fd287af565b
40,167
from typing import Optional def list_location_consortiums(location_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListLocationConsortiumsResult: """ Collection of the consortium payload. :param str location_name: Location Name. """ ...
bb6e37971495e46911bde0f698239447e50edcec
40,168
from typing import Tuple def typeshed_py_version(options: Options) -> Tuple[int, int]: """Return Python version used for checking whether module supports typeshed.""" # Typeshed no longer covers Python 3.x versions before 3.6, so 3.6 is # the earliest we can support. if options.python_version[0] >= 3:...
73d059966e50b8443c4ab93183556818ac49f619
40,169
def pcr(adata, covariate, embed=None, n_comps=50, recompute_pca=True, verbose=False): """ PCR for Adata object Checks whether to + compute PCA on embedding or expression data (set `embed` to name of embedding matrix e.g. `embed='X_emb'`) + use existing PCA (only if PCA entry exists) ...
9d44321d244f2ad945d8307c2157f73870a20e12
40,170
from pydantic import BaseModel # noqa: E0611 async def update_one(model: DeclarativeMeta, obj: BaseModel, pk_param: int, pk_attr: str = 'id'): """ Update one """ query = update(model).where(pk_param == getattr(model, pk_attr)).values(obj.dict()) await database.execute(query) return {**obj.dict(), pk_...
efdbce5605803a10737af67807af91f144ace9ea
40,171
def yellow_mask(original): """ Create a mask from the yellowish pixels of the frame, combining RGB mask and HSV mask """ hsv = yellow_mask_hsv(original) rgb = yellow_mask_rgb(original) mask = np.zeros_like(rgb) mask[(hsv == 1) | (rgb == 1)] = 1 return mask
1236614531748d8682f3d2676675186bfd914ca3
40,173
def getClass(): """ Takes in a JSON of the form {'_id' : String} Returns all the information for a class including _id stringified {'result' : None/JSON, 'success' : Boolean} """ if request.json is None or '_id' not in request.json: abort(400) if not dbworker.validateAccessList([...
1946ee40a934fcf7e861782b571ce1db435dc341
40,174
def isstrictlyascending(lam): """This determines whether the index string is a strictly ascending sequence Parameters ---------- lam : an indexable object of things that are comparable. Usually an array of integers Returns ------- bool : true if the sequence is strictly ascending, else fal...
fce99e5ae20d987102eeea441b95777f0b775eba
40,175
def collections_endpoint(url): """ Resource endpoint handler :param url: the url that led here .. versionchanged:: 0.0.7 Using 'utils.request_method' helper function now. .. versionchanged:: 0.0.6 Support for HEAD requests .. versionchanged:: 0.0.2 Support for DELETE resour...
e3230c8e98bf7f6a0b628c9eceec0170ca70e1f3
40,176
def to_aws_tags(tags): """ When you assign tags to an AWS resource, you have to use the form [{"key": "KEY1", "value": "VALUE1"}, {"key": "KEY2", "value": "VALUE2"}, ...] This function converts a Python-style dict() into these tags. """ return [ {"key": key, "valu...
d1e18ea1e4de08fcae59febbe97ab3eb5bc2a2f1
40,178
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5): """ Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID. Arguments: X -- input dataset, of shape (2, number of examples) parameters -- python dictionary containing...
5cd9a9fe9b66b26ac79f4bf1657b24797dadca2d
40,179
def compose_postprocessing(postprocessing): """ Compose a postprocessing transform to be performed. Params ------ postprocessing : dict - dictionary defining all preprocessing steps to be taken with their values e.g. {"Name" : "RescaleIntensity"} ...
2533202fa34f4101fbae0e1403b1df3fce6b2ef0
40,180
def run_ksp(graph, cfg, k, thresh=10, algorithm=KSP.find_ksp): """ Build the shortest path trees and compute k diverse shortest paths """ # construct sp trees _ = graph.sp_trees(**cfg) # compute k shortest paths ksp_processor = KSP(graph) ksp_out = algorithm(ksp_processor, k, thresh=thre...
9bcc8f3ac6ea34dbbdd55f9abd067c661c448633
40,181
def handler(event, context): """ api entry function """ output = process_api_request(event, put_schedule_tags, logger) logger.info(output) return output
32d902f814df51b7dd86bbddefd22f3d47a56af7
40,182
def check_for_winner(players) -> bool: """Checks all players for a single winner. Returns True if there is a winner. Keyword arguments: players -- list of player objects """ return sum(map(lambda x: not x.is_bankrupt(), players)) == 1
17d39e92a38a9474f080ddebfac1d4813f464a1e
40,183
def random(num_points, span): """ This function generates a set of random x and y coordinates using the numpy uniform random number generator 'numpy.random.uniform()'. Parameters ---------- num_points : int The number of points to generate span : World class The world defin...
d4425619b29782bc926fac925d896345cdf2f410
40,185
def get_game_player(game_state): """Get the game player whose turn it is to play.""" num_players = len(game_state.game_players) for game_player in game_state.game_players: if game_state.turn_number % num_players == game_player.turn_order: return game_player return None
a75a0b1b7f1ce4da8c944ad40208fba6f9a50f5a
40,186
def details(location_slug: str): """View: Location Details""" slug = slugify(location_slug) if location_slug and location_slug != slug: return redirect_url(url_for("locations.details", location_slug=slug)) database_connection = mysql.connector.connect(**current_app.config["database"]) locat...
df830ac6d746f8d82806537c66dc12172a90eeb3
40,187
def get_widget_config(id_): """Get a widget :param id: The ID of the widget :type id: str :rtype: Report """ widget_config = WidgetConfig.query.get(id_) return widget_config.to_dict()
3b4b92491a2ddae0674ecb8a9b8578a795849cbb
40,188
import ast def extract_info_attributes(round_datum): """Extract information attributes for current round using NLU annotations. Args: round_datum: Current round information Returns: get_attribute_matches: Information attributes """ user_annotation = ast.literal_eval(round_datum["...
95e60ea10a7888b3f04619fc882279ebffaf189a
40,189
import re def get_headers_pairs_list(filename, verbose=False): """ Read data for clustering from a given file. Data format: <email_number> <header>. Clusters are separated with a blank line. :param filename: file with input data for clustering. :param verbose: Whether to be verbose. Default ...
d6b457652e1025475075fb601ba81b6a7fe346fc
40,190
def maintainer_menu(request): """ View for maintainer menu page. This page can only access by superuser and maintainer. :param request: WSGI request from user. :return: Render the maintainer menu page and pass the value from context to the template (maintainer.html) """ hero_image = 'img/m...
fe87e96c1a8cda2618ceaf0f24fa58ece1bac690
40,191
def declaration_path(decl, with_defaults=True): """ returns a list of parent declarations names :param decl: declaration for which declaration path should be calculated :type decl: :class:`declaration_t` :rtype: [names], where first item contains top parent name and last item contains...
a17ef5c192b4fd75b51216eecc717dbf1e09740f
40,193
def fit_largest_peak(xs, ys, num): """ Algorithm to "fit" the largest peak :param xs: numpy array of floats, time series data :param ys: numpy array of floats, power data :param num: integer, number of peaks to fit :return: """ sort = np.argsort(xs) xs, ys = xs[sort], ys[sort] #...
acf7587c081cc427c78dd88dc3b5d33f1dc6f8cf
40,194
import torch def direction_neuron(layer, direction, x=None, y=None, batch=None): """Visualize a single (x, y) position along the given direction Similar to the neuron objective, defaults to the center neuron. InceptionV1...
7becd4e60fd4810f364c36d7aca165a92060e0bf
40,195
from pathlib import Path def _run_jlab_string(talktorials_dst_dir): """ Print command for starting JupyterLab from workspace folder. Parameters ---------- talktorials_dst_dir : str or pathlib.Path Path to directory containing the talktorial folders. """ talktorials_dst_dir = Path...
76c45f77f419b6a302d63d92e51cd0ea1bb92ebb
40,196
def moment2d(grid): """ >>> moment2d([[5, 6, 7, 2, 4]]) [[0, 6, 14, 6, 16]] """ return list(map(moment, grid))
d02bf3a21ccf20566c5e2b93ace82579559eef8f
40,197
import requests def get_onprem_cost_efficiency_handler(request): """ Queries the OneSphere metrics API and returns the private cloud cost efficiency. """ # Get KMS secured environment variables api_base = request.metadata.get('api_base', None) token = request.metadata.get('token', None) # G...
a271165c30ea5855be07906b89357c7700796806
40,199
from pesummary.core.plots.bounded_1d_kde import bounded_1d_kde def _setup_triangle_plot(parameters, kwargs): """Modify a dictionary of kwargs for bounded KDEs Parameters ---------- parameters: list list of parameters being plotted kwargs: dict kwargs to be passed to pesummary.gw.p...
b3be4c1d402a1defafb779274970d7a4983d396d
40,200
def pack(*v): """Packs value to fit into a word""" w = 0 for i, x in enumerate(v): w += INST_SZ**(len(v) - i - 1) * x return w
e9dcbab2655033077d14060da33656734a580d3c
40,203
def print_card(card): """ Makes a card string from a card object :param card: The card object :return: The card string """ if card.layout() == 'normal': return make_card_string(card) elif card.layout() == 'split': return make_split_card_string(card) elif card.layout() == ...
e866afa374bc7d3664387262a5d9bf201087cc7f
40,205
def component_declaration1(): # type: ignore """ component_declaration1 = declaration comment """ return syntax.declaration, syntax.comment
48125c163fd8a6c12159f8d68d7786caf6acf42f
40,206
def BackupConfiguration(sql_messages, instance=None, backup_enabled=None, backup_location=None, backup_start_time=None, enable_bin_log=None, enable_point_in_time_recovery=None,...
18750b852fda215252c1211d41cf5f1ad1f6e887
40,207
def artifact_patch_request(user_id, req_op, req_path, req_value=None, req_from=None): """Modifies an attribute of the artifact Parameters ---------- user_id : str The id of the user performing the patch operation req_op : str The operation to perform on th...
96d69c1c5a12a53238565ca032c49861d2f73c17
40,208
def topo_2_property(topology, property): """ Returns properties of a topology for a given topology name. Properties: 'stk_func' - gives the stk topology function for building cages 'stoich' - gives the stoichiometries of both building blocks assuming that the first building bloc...
984e87ece3ad0fadf78a380807288995da873398
40,209
def get_full_names(pdb_dict): """Creates a mapping of het names to full English names. :param pdb_dict: the .pdb dict to read. :rtype: ``dict``""" full_names = {} for line in pdb_dict.get("HETNAM", []): try: full_names[line[11:14].strip()] += line[15:].strip() except: f...
be31bb2c8e59e7b2ef4b51aba45f3cbafcb23a63
40,210
import urllib import json def create_package(base_url, data=None, api_key=None): """Post a data dict to one of the actions of the CKAN action API. See the documentation of the action API, including each of the available actions and the data dicts they accept, here: http://docs.ckan.org/en/ckan-1.8/api...
24e58d050c7c7cc26d03f659e789143da722c77c
40,211
def getDiffError(a, b): """ (Deprecated)Calculate the distance square between a and b. Parameters ---------- a, b : ndarray of float, in the same shape The two matrices to be compared Returns ------- float The sum of element-wise distance square between a and b. ...
f31a785907c949b4f4230fc7e35a2b396dc40cdc
40,212
from scipy import linalg import warnings def _fit_corrs(x_xt, x_y, n_ch_x, reg_type, alpha, n_ch_in): """Fit the model using correlation matrices.""" known_types = ('ridge', 'laplacian') if isinstance(reg_type, string_types): reg_type = (reg_type,) * 2 if len(reg_type) != 2: raise Valu...
9033ab134f89183afb7e850f7d61b6793103b42d
40,213
def symbol(a=None): """ Return a variable from the symbolic ring with the given name. If an expression is given, it is returned unchanged. """ if isinstance(a, Expression): return a return SR.symbol(a)
48728d7775fa8013499e8070f557efe4bda63218
40,214
import glob def get_files(base_dir, ref_dir): """ get_files: get all the asdf files in base_dir. """ allfiles = sorted(glob(join(base_dir, "*h5"))) # we should use the head of ref_dir and the base of the globbed files result = [] for each_file in allfiles: result.append(join(ref_di...
5244e313193c9d77829f07e5400287953b89749e
40,215
def load_image(filename): """Loads a PNG image file.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
414ead568ecbbe61b90a155c50cdf83ee7783ec9
40,216
import abc def _actor_in_relationship(actor, relationship): """Test whether the given actor is present in the given attribute""" if actor == relationship: return True if isinstance(relationship, (AppenderMixin, Query, abc.Container)): return actor in relationship return False
7c9ab9c17552e4156dd0341a8244f9ef13e8aaa9
40,217
import math def gamma_correct(cs, c): """ Transform linear RGB values to nonlinear RGB values. Rec. 709 is ITU-R Recommendation BT. 709 (1990) ``Basic Parameter Values for the HDTV Standard for the Studio and for International Programme Exchange'', formerly CCIR Rec. 709. For details see ...
ebdc970f9e2e82e372bb4f83c162c9d9c2df0f44
40,218
def get_flat_pos_array(img_arr): """Converts grayscale image numpy array into flat array with cube positions for blender. """ WIDTH = 160 HEIGHT = 120 THRESH = 127 res_arr = np.zeros(WIDTH*HEIGHT*3) white_indexes = np.argwhere(img_arr > THRESH) for row in white_indexes: y, x...
7053be7d2cdfee76ca1e347a0982fa08589e99d5
40,219
import re def extract_last_reg_status_change(strValue): """处理show onu last-reg-status-change命令得到的数据。其中,时间若为0000-00-00 00:00:00,将会转换为None。 Args: strValue (str): show onu last-reg-status-change命令得到的数据 Returns: list: 字典列表。 """ # SLOT PON ONU LAST_OFF_TIME LAST_ON_TIME # 4 ...
8661b1b01cc0a8d9c01cad892c2b9560fcbc5406
40,220
def slurp(filename): """Return the contents of a file as a single string.""" fh = open(filename, 'r') try: contents = fh.read() finally: fh.close() return contents
f3e4a943dfe64dbc02e887a2f5f18e39597c8094
40,221
def refsoot_imag(wavelengths, enhancement_param=1): """imaginary part ot the refractive index for soot :param wavelengths: wavelength(s) in meter. :param enhancement_param: This parameter enhances the mass absoprtion efficiency of BC. It makes it possible to scale BC absorption. Values of this param...
bbd7a9ad7f14088739c8eeaef926dbc63f5a2385
40,222
def calculate_all_metrics(obs: DataArray, sim: DataArray) -> dict: """Calculate all metrics with default values.""" results = { "NSE": nse(obs, sim), "MSE": mse(obs, sim), "RMSE": rmse(obs, sim), "KGE": kge(obs, sim), "Alpha-NSE": alpha_nse(obs, sim), "Beta-NSE": ...
6649642ad06152646a82f6c8c68a09599d89cb36
40,223
from typing import Pattern def transform(pattern: Pattern) -> "Either": """Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a) """ result = [] groups = [[pattern]] ...
d2ed8b04de376f6994d123cf8942eb8efb78068a
40,225
def create_placeholders(n_x, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288) n_y -- scalar, number of classes (from 0 to 5, so -> 6) Returns: X -- placeholder for the data input, of sha...
e0140f18fd71fec61228f55384588faa0e9bf23e
40,226
import requests import html from datetime import datetime import time def checkIfUpdateAvailable(updateDateFileAddress): """Checks the Jyväskylä open data website for wheter there is an update for the linkkidata-package Returns true if there is, false if there is not""" try: lastUpdatedDate ...
6d7ce02adf4a2bb8e6944abfcc15dac791fa178b
40,227
import torch def nmse(outputs, targets): """ Normalized mean square error :param outputs: Module's output :param targets: Target signal to be learned :return: Normalized mean square deviation """ # Flatten tensors outputs = outputs.view(outputs.nelement()) targets = targets.view(ta...
97d801fa520e4eda214300bf2915d43dc2ec948d
40,228
async def get_schema_template( db: AsyncSession, tenant_id: UUID, wallet_id: UUID, schema_template_id: UUID, deleted: bool | None = False, ) -> SchemaTemplateItem: """Get Schema Template. Find and return a Traction Schema Template by ID. Args: db: database session tenant_i...
ae5da1b26eb74ba206c6b343ad7de95d3ea9081a
40,229
from typing import Callable def get_random_box(shape: AxesLike, box_shape: AxesLike, axes: AxesLike = None, distribution: Callable = uniform): """Get a random box of shape ``box_shape`` that fits in the ``shape`` along the given ``axes``.""" start = distribution(shape_after_full_convolution(shape, box_shape, ...
f75e86c96905cd98853dc83f1832481daa0fc7ea
40,230
def _optimize_font_size(font, text, max_font_size, min_font_size, max_text_len): """Calculate the optimal font size to fit text in a given size.""" # Check size when using smallest single line font size fontobj = ImageFont.truetype(font, min_font_size) text_size = fontobj.getsiz...
e19784e78e484ab6effe9d57ed6e2be89799bc2f
40,231
from redis import StrictRedis as Redis, RedisError def redis_exists(): """ Test that redis-py is installed and redis-server is running locally. """ try: except ImportError: return False try: Redis(db=15).ping() return True except RedisError: return False
181836efd149c4657a384628a0fe842d771d344a
40,232
def get_table_type(filename): """ Accepted filenames: device-<device_id>.csv, user.csv, session-<time_iso>.csv, trials-<time_iso>-Block_<n>.csv :param filename: name of uploaded file. :type filename: str :return: Name of table type. :rtype: str|None """ basename, ext = f...
bc4f39e4c9138168cec44c492b5d1965de711a7e
40,233
def get_paradigm(dataset_name): """ Return the paradigm of a dataset ('domain_generalization' or 'subpopulation_shift') Args: dataset_name (str): Name of the dataset to get the paradigm of. (Must be part of the DATASETS list) Return: str: The paradigm of the dataset """ ...
c2f28b6b8d4ac4fdacbc26d04862406bc15ff240
40,235
def fix_cropBox_rot(img, bbox, input_size, rot): """Crop bbox from image by Affinetransform. Parameters ---------- img: torch.Tensor A tensor with shape: `(3, H, W)`. bbox: list or tuple [xmin, ymin, xmax, ymax]. input_size: tuple Resulting image size, as (height, width)....
a181821bf6f58e1356116b06d33c6fca58a24003
40,236
def find_locations(text): """ Find normalized location mentions in text, with natasha library """ locations = [] try: doc = Doc(text) doc.segment(segmenter) doc.tag_morph(morph_tagger) doc.parse_syntax(syntax_parser) doc.tag_ner(ner_tagger) for token i...
121478937e469687d482bce2454fc0fff8946a4e
40,237
def length_of_longest_substring(s: str) -> int: """ The most obvious way to do this would be to go through all possible substrings of the string which would result in an algorithm with an overall O(n^2) complexity. But we can solve this problem using a more subtle method that does it with one linear tr...
3844c6fd1c62025b704284e76da25f7c63aa0fc9
40,238
def loads(s): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a NeXTSTEP property list document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified....
6d6a36091b8278865370fa35cae5c3aa5c57cbb2
40,239
def make_download_filename(genome, args, response_format): """ Make filename that will explain to the user what the predictions are for :param genome: str: which version of the genome we are pulling data from :param args: SearchArgs: argument used for search :param response_format: str file extensio...
4645e3175de0db81e940d0e64740e937bce7afc3
40,240
def ranges_means(data): """ Return ranges, means of cycles counted using Downing's method 1. """ turns = data_rearranged_for_rainflow_counting(data) values = [] # of the current turns being processed ranges = [] means = [] for turn in turns: values.append(turn) while ...
6d5510709596773570ba5074cb561c66299f86f7
40,241
def window_to_bounds(window, affine): """Convert pixels to coordinates in a window""" minx = ((window[1][0], window[1][1]) * affine)[0] maxx = ((window[1][1], window[0][0]) * affine)[0] miny = ((window[1][1], window[0][1]) * affine)[1] maxy = ((window[1][1], window[0][0]) * affine)[1] return min...
6377d792271a86175349daa277b8eb937dd740f5
40,243
def matches_version_constraint(constraint, target, version): """ See http://wiki.opscode.com/display/chef/Version+Constraints Do not pad the target to 3 (it would change the meaning of ~>) """ version = pad_to_3(version) # just in case if constraint == '~>': high = pad_to_3(target[:-2] + [(...
38acd10494032c8fd9a6764b308ab6388363bd40
40,244
def forge_buy(oc_user,params): """购买打造的装备 """ data = {} user_forge_obj = UserForge.get_instance(oc_user.uid) user_property_obj = UserProperty.get(oc_user.uid) cost_smelting = user_forge_obj.cost_smelting user_smelting = user_property_obj.property_info.get("smelting",0) if cost_smelting >...
35312b9a82754c2854f9cb58266d97ebdd4d0bbe
40,246
from typing import Optional from typing import List def tm_path(name: str) -> str: """Returns the path of the settings file for name ('9o', 'doc', 'go', 'gohtml') Note: This is used to locate syntax files, and appears to break when GoSublime is not located in the ST Package directory. """ pkg...
6d711dd5eac524617e77bddbea5e8fde71ef7168
40,247
import json def get_javascript_value(value): """ Get javascript value for python value. >>> get_javascript_value(True) true >>> get_javascript_value(10) 10 """ if isinstance(value, bool): if value: return 'true' else: return 'false' else: ...
d8a20ebf1ad17e6e25d676f30cb57278b6b22589
40,248
import torch def sort_by_seq_lens(args, batch, sequences_lengths, descending=True): """ Sort a batch of padded variable length sequences by their length. Args: batch: A batch of padded variable length sequences. The batch should have the dimensions (batch_size x max_sequence_length x ...
224af4c3c687f95444aa661eb45d37bb46983a30
40,249
def Bootstrap(data1, data2, M = 1e4, paired = False, direction = None, verbose = False): """ Bootstrap difference in means between two groups. M = float64 # Number of iterations paired = {True, False} direction = {"greater", "lesser", None} if verbose = True, returns distribution and p_value, shows...
9c5773786600c073b40fd394f0f3a3636e576f23
40,252
def read_station_coordinates(file, group=None, var_x='Xs', var_y='Ys'): """ Read the x and y coordinates from an NetCDF file. :param file: Input NetCDF file :param group: The group of the NetCDF file to read. See xarray.open_mfdataset for details. :param var_x: Variable name for x coordinates ...
11cf18e18c01958a6365a137682dd4bc283d6e5c
40,253
def is_ctrl_z(e: InputEvent, keyboard: InputDevice) -> bool: """ Check whether event invokes ^z or not. """ return e.code == ecodes.KEY_Z and ecodes.KEY_LEFTCTRL in keyboard.active_keys()
97fb9da93b30be1b84aabaa0ee6a389d397d65df
40,254
import importlib def import_module_from_path(filepath): """ Import a module from given path. https://stackoverflow.com/a/67692/5159551 """ spec = importlib.util.spec_from_file_location('person', filepath) person_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(person_...
4bc6d2dfeaef811ceb234931e114781ecdae0e57
40,255
import numpy import random def time_mask(spec, T=40, n_mask=2, replace_with_zero=True, inplace=False): """freq mask for spec agument :param numpy.ndarray spec: (time, freq) :param int n_mask: the number of masks :param bool inplace: overwrite :param bool replace_with_zero: pad zero on mask if tru...
f69364510c78f2fc3e96fb4f028737c6c415d5df
40,256
def change(csq): """ >>> change("missense|TMEM240|ENST00000378733|protein_coding|-|170P>170L|1470752G>A") ('170P', '170L', True) >>> change('synonymous|AGRN|ENST00000379370|protein_coding|+|268A|976629C>T') ('268A', '268A', False) """ parts = csq.split("|") if len(parts) < 7: ret...
da43c6bd45e641b885469d07c2e6befff334d8a3
40,257
from typing import Dict from typing import List from typing import Tuple def update_params( workload: spec.Workload, current_param_container: spec.ParameterContainer, current_params_types: spec.ParameterTypeTree, model_state: spec.ModelAuxiliaryState, hyperparameters: spec.Hyperparameters, bat...
464aef19fd9e8eeb894f972daad57ced56701bb8
40,259
def with_coordinates(pw_in_path, positions_type, atom_symbols, atom_positions): """Return a string giving a new input file, which is the same as the one at `pw_in_path` except that the ATOMIC_POSITIONS block is replaced by the one specified by the other parameters of this function. `positions_type`, `a...
11dc207a4f17a6521a1aa6299d455f0548c50566
40,261
def find_nearest(array, value): """ Returns the index of "array" whose data best matches "value". https://tinyurl.com/yc7twjx8 """ array = np.asarray(array) idxs = np.argsort(np.abs(array - value))[0] return idxs
7d8b0cba75d6077a6a35b351754546bb345d8090
40,263
def TDVGGNetV1(output_units, input_shape, num_conv_blocks=5, num_block_layers=2*[2]+3*[3], num_fc_layers=3, conv_filters=64, conv_filters_factor=2, max_conv_filters=512, dilation_rate=1, dilation_rate_factor=0, hidden_fc_units=4096, kernel_size=...
a410fe1dce21075f658d340f75f667f9902bf544
40,264
def countby(seq, key): """ Description ---------- Create a dictionary with keys composed of the return value of the funcion/key\n applied to each item in the sequence. The value for each key is the number of times\n each key was returned. Parameters ---------- seq : (list or tuple o...
45ce59f9fd5c837eefbb04ac31d662a10974598d
40,265
import re def datefmt_to_regex(datefmt): """ Convert a strftime format string to a regex. :param datefmt: strftime format string :type datefmt: ``str`` :returns: Equivalent regex :rtype: ``re.compite`` """ new_string = datefmt for pat, reg in PATTERN_MATCHNG: new_string =...
9daeeada904bdd1ca4b71a6e389e9f1ae1ac6ead
40,266
def hsv_decomposition(image, channel='H'): """Decomposes the image into HSV and only returns the channel specified. Args: image: numpy array of shape(image_height, image_width, 3). channel: str specifying the channel. Can be either "H", "S" or "V". Returns: out: numpy array of shap...
c7a853d8c3c4dac4748db262b992235786e91382
40,267
def resize_images(X, y): """ This method resizes the images to height=66, widht=200 No. of Output Images = No. of Input Images """ images = [] steering_angles = [] for i in range(len(X)): resized = cv2.resize(X[i], (200, 66)) images.append(resized) steering_angles.app...
c5356e2f3e6504f99901c6308a901b3e03047919
40,268
def spline_area(s_tuple, N=None): """Compute area of spline s discretized in N segments.""" # to get a good approx. take 3 x the number of knots if N is None: N = 3 * len(s_tuple[0]) c = splev(np.linspace(0, 1, N, endpoint=False), s_tuple) cprm = splev(np.linspace(0, 1, N, endpoint=False),...
0379ad15d86e5715ce142fdae5c038f4e01e5e72
40,269
def kgtk_date_hour(x): """Return the hour component of a KGTK date literal as an int. """ if isinstance(x, str): m = KgtkValue.lax_date_and_times_re.match(x) if m: return int(m.group('hour'))
50cd9029ce956f719b5618b2f7523ec876f6f2ce
40,270
def conv3d_blk(x, shape, stride, phase): """conv3d block with ReLu""" W = tf.get_variable("W", shape=shape, initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable("b", shape=shape[4], initializer=tf.constant_initializer(0.1)) return conv3d(tf.nn.relu(tf.contrib.layers.batch_norm(x, is_t...
aec3a1f5de5db5f519499cf0ed32ae553f53d6b1
40,271
def check_bias(bias: TensorParams): """This function checks whether the bias values fit in 40 bits""" if bias and bias.dtype == np.dtype("int64"): valid = all(len(bin(bias_value)[2:]) <= 40 for bias_value in bias.values) return valid return True
666fa565611fc5496a2adb4d6319bd72c4e9ecb4
40,272
def l2normalize(v, eps=1e-12): """l2 normalize the input vector. Args: v: tensor to be normalized eps: epsilon (Default value = 1e-12) Returns: A normalized tensor """ return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)
9e3ecce736672a74e5239a3855b696dba8d0ec7c
40,274