content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def originProblem(): """ Logic grid puzzle: 'origin' in CPpy Based on... to check originally, currently part of ZebraTutor Probably part of Jens Claes' master thesis, from a 'Byron...' booklet """ person = ['Mattie', 'Ernesto', 'Roxanne', 'Zachary', 'John'] age = ['109', '110', '111', '112'...
634517806e5c7087c27dfceaf89c978a49668d39
49,968
import multiprocessing def do_fiteach(save_cube=None, save_pars=None, show_plot=False): """Fits a cube with a gaussian for later use""" if save_cube is None: save_cube = 'test.fits' test_sigma = 10 # in pixel values, each pixel is CDELT3 thick make_test_cube((100,10,10), save_cube, ...
d9fa03e9340040bf5bbdd458a6ea291cab924331
49,969
def prev(y): """Reverses next() function from super_cipher.py. next() generates the next keystream according to the following bit mapping: current triplet -> next possible triplet : current bit -> next possible bit 0 000 --> (0 000, 4 100) : 0 --> (0, 1) 1 001 --> (0 000, 4 100) : 1 --> (0, 1) ...
bc1b50ebb016b76327c93ba7f6aef2f6cd63b453
49,970
def is_runtime_path_valid(path): """ Returns True if the given path is a valid runtime path, False otherwise. """ try: _parse_from_path(path) return True except InvalidMetadata: return False
d32b5b49dc800ae68644ed7f6c8ee5dc5830a82c
49,971
def list_role_privileges(role, web_session=None): """Lists all privileges of a role. Args: role (str): The name of the role. web_session (object): The webserver session object, optional. Will be passed in by the webserver automatically Returns: The generated shell reque...
ab6170b1c9bf048013932b2e9408836c4809ca38
49,972
def replaceShapes(path, controls=None, remove=True): """ Replaces all the the given control shapes with controls of the same name in the given path file. If no controls given, will use selected. If none selected, will use all controls in the scene. Args: path (string): Path to Maya file to refe...
10f6e3d40f96493487b27815017a153f511abec3
49,974
from typing import Dict from typing import Any def generator_run_to_dict(generator_run: GeneratorRun) -> Dict[str, Any]: """Convert Ax generator run to a dictionary.""" return { "__type": generator_run.__class__.__name__, "arms": generator_run.arms, "weights": generator_run.weights, ...
83805a3458d5db740019af7e907c96ca69430068
49,975
import six def preprocess_data_for_dqn(data, reward_model="sparse"): """ Creates n_students traces of (s,a,r,s') tuples which can be loaded into the experience replay buffer. Each student yields one trace :param data: :param reward_model: "dense", "sparse" or "semisparse". If "sparse", then re...
bb1e6ada6bc6e7d3228b73e1fb1e1b3158daf4bc
49,976
def find_layer_of_feature(feature, layer_notation='conv'): """ This function find the layer correspondent to the given feature in a certain embedding. It returns the layer name of the feature. There are two different notations: - The used by the FNE: vgg16_model/relux_y - The used by the vgg16 ...
2c07811c667f795511b32bf914e9810f4e5ae77b
49,977
def connect(): """Page for connecting to the pi.""" return(str(connect_to_pi.delay({'r': ['VS1_GT1']})))
ab2c10bb83393cc49582f3c62573cb603a7aa1f6
49,979
from typing import Tuple def _vector_sample_perturbations( theta: ArrayTree, key: PRNGKey, std: float, num_samples: int) -> Tuple[ArrayTree, ArrayTree, ArrayTree]: """Sample a perturbation with positive and negative pair.""" def _fn(key: PRNGKey) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: pos =...
368d10e14dd3069f193c89e9b287216c690dc5ee
49,981
def solution_detail(request, solution_id): """ :param request: :param solution_id: :return: """ solution_id = solution_id solution_item = Solution.objects.get_solution_by_id(solution_id) if not solution_item: raise Http404 # 获取关键词 solution_keywords = solution_item.keyword...
e17bf56ec9567ea63d25a886737c9f7bb104a022
49,982
def _execute_query(sql_raw, params, qry_type): """ Handles executing queries based on the `qry_type` passed in. Returns False if there are errors during connection or execution. if results == False: print('Database error') else: print(results) You cannot use `if no...
80c0a76ecbc4b01b2b9f31923a3356de19ad4251
49,983
def index(page=None): """ preview_data = Preview.query.all() # print(preview_data) # [<Preview 17>] first_preview_id = Preview.query.order_by(Preview.id.asc()).first().id # <Preview 17> # first_preview_id = Preview.query.order_by(Preview.id.asc()) # sql # print(first_preview_id.id) return...
f509ce04b2e6aba3b4bfca5b3dba42ceb80aaa36
49,984
def conv2d_w(x, W): """conv2d returns a 2d convolution layer with full stride.""" # return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return wavecomp_ops_module.wave_conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
cce0312dad3d684af6ef202941aca0b36f40b001
49,985
def interpolate_colors(colors, flat=False, num_colors=256): """ given a list of colors, create a larger list of colors interpolating the first one. If flatten is True a list of numers will be returned. If False, a list of (r,g,b) tuples. num_colors is the number of colors wanted in the final list """ ...
cbcd22544623019d268e2f2b887cfcfbee1821b0
49,986
def vcv_cart2local(vcv_cart, lat, lon): """Transforms a VCV from the Cartesian to the local reference frame. If only a column vector of variances is supplied then they are assumed to be uncorrelated and only the column vector of variances is returned. See Section 4.4.1 of the DynAdjust User's Guide v1....
22d9b0fded345c1758fc84c53d28ef6a29607ebb
49,987
def create_instance(test_id, config, args): """ Invoked by TestExecutor class to create a test instance @test_id - test index number @config - test parameters from, config @args - command line args """ return TestSessions(test_id, config, args)
34053bc31d6592ae58341fa8350f6e01bca27b1c
49,988
def process_decoded_keypoints_2d(decoded_tensors, keypoint_names_2d, include_keypoint_scores_2d, common_module=common): """Processes decoded 2D keypoint tensors. Args: decoded_tensors: A dictionary for decoded te...
f9aa19913c89ebe1f18c5378849cb39238623236
49,989
def compute_propagation(w, phi): """ Propagation term """ # Compute derivatives x and y wx = compute_derivative(w, np.array([[-1, 1]])) wy = compute_derivative(w, np.array([[-1], [1]])) # Get max and min of wx wx_max = np.maximum(wx, 0) wx_min = np.minimum(wx, 0) # Get max ...
73ae5d3733af4f23576c18986a630214595df0de
49,990
import tqdm def dict2PCA(fit_dict, test_dict=None, dim=2, pca=None): """ Dimensionality Reduction by PCA with dict data example of dict data is below: fit_dict = {"aa": [[ndarray with shape (Na, D)]], "bb": [[ndarray with shape (Nb, D)]],...} Args: ...
049a28f8bfec27dd00c9390e83b2a7b301ca0b86
49,991
def totree(expr): """Simplifies ``expr`` (:py:class:`Expr <histbook.expr.Expr>`) to contain only constants (:py:class:`Const <histbook.expr.Const>`), names (:py:class:`Name <histbook.expr.Name>` and :py:class:`Predicate <histbook.expr.Predicate>`), and function calls (:py:class:`Call <histbook.expr.Call>`).""" ...
f24e224994398819d417d52a6f0974329f30898f
49,992
def decimal_to_short(code): """ Convert an ICD9 code from decimal format to short format. """ parts = code.split(".") parts[0] = _zero_pad(parts[0]) return "".join(parts)
9c5eb5391ffeae52c474ea807eb2c22af633d05a
49,993
def total() -> int: """ :return: int: Return sum of number of grains in each of the 64 squares, i.e. 2^64 - 1 """ # The sum of the geometric series 1 + 2 + 4 + 8... 64 terms is 2^64 - 1 return 2**64 - 1
4322456aaff1417354d4b5224594dab9b3c05508
49,994
import hashlib def normalize_property_ref(value: rdltypes.PropertyReference, owner_node: node.Node) -> str: """ Hash of relative path from owner of the property to the target component's property """ path = "%s->%s" % (value.node.get_rel_path(owner_node), value.name) md5 = hashlib.md5(path.enc...
0455d48baef30088259839a746010261d7d6d0b8
49,995
def needs_db(function): """ A function wrapper that provides access to the database. """ @wraps(function) def wrapper(*args, **kwargs): db_session = Session() output = function(db_session, *args, **kwargs) db_session.close() return output return wrapper
a9c535639e0ddab56d487d956de15be5fcfe08e1
49,996
def deluser(name, username, **kwargs): """ Remove a user from a group Args: name (str): The name of the group to modify username (str): The name of the user to remove from the group Returns: bool: ``True`` if successful, otherwise ``False`` CLI Ex...
863dcc1848372c1dbeac712b6c5b2b8d3219035b
49,997
def show_cmaps(*args, **kwargs): """ Generate a table of the registered colormaps or the input colormaps categorized by source. Adapted from `this example \ <http://matplotlib.org/stable/gallery/color/colormap_reference.html>`__. Parameters ---------- *args : colormap-spec, optional Col...
c5b8fa3fa3cbb131250be5b813e10c4ff45e0752
50,000
import logging def Run(benchmark_spec): """Measure the boot time for all VMs. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects with individual machine boot times. """ vm = benchmark_spec.vms...
97176dc9e27d9f1f756769bef3966efa5c4e627c
50,001
def ansi_render_approx(s, width = 80, height = 2000): """ Does an approximated render of how a string would look on a vt100 terminal The string can contain ANSI escape sequences, which the :module:`pyte` engine can render so a string such as >>> s = '\x1b[23;08Hi\x1b[23;09H\x1b[23;09Hf\x1b[23;...
c6db54b85780137e75dcc04e43c04ef1f4abe873
50,003
def ycbcr2rgb(ycbcr, *, channel_axis=-1): """YCbCr to RGB color space conversion. Parameters ---------- ycbcr : (..., 3, ...) array_like The image in YCbCr format. By default, the final dimension denotes channels. channel_axis : int, optional This parameter indicates which a...
d5a27283f257c76c683426f5bb307c300756a464
50,004
import requests def confirm_licenses_package(access_token, resource_server, pickup_number): # type: (str, str, str) -> int """ Sends the confirmation to the server that the license package was retrieved. Returns the response code in case of success. """ response = requests.post( resour...
575e524efebcf4e89141362102488b087ca48fbf
50,005
def loss(logits, labels): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ # Convert from sparse integer labels in the range [0, NUM_CL...
5e034179193ebb7343264a837f3dd3aeee151729
50,006
def get_douban_url(detail_soup): """-""" detail_soup = detail_soup.find('a', title='豆瓣链接') if detail_soup: return detail_soup['href'] return ''
3f4cb56876da722883e3386d7af7ce41726456ac
50,008
def truncate_out_cert_raw(origin_raw_str: str): """truncate the original ssl certificate raw str like:\n -----BEGIN CERTIFICATE----- raw_str_data... -----END CERTIFICATE-----\n and split out the raw_str_data""" if not isinstance(origin_raw_str, str) or origin_raw_str == "": raise Excepti...
0513a927ab74ac8d6df4e379319eb3516c2f0c14
50,011
from datetime import datetime def addNewUser(db: Connection, userID: int) -> bool: """ Add new user to database :param db: database object instance :param userID: User ID :return: Boolean True if no error """ if db is None: return False now: datetime = datetime.utcnow() cur...
13ac827c703a30a96d416850b5380c2e89592a96
50,012
def dv_dlogdp(dp, n, gm, gsd): """The volume weighted PDF of a lognormal distribution as calculated using equation 8.20 from Seinfeld and Pandis. .. math:: n_V^o(log D_p)=log(10)*D_p n_V(D_p) Parameters ---------- dp : float or array of floats Particle diameter in microns. ...
88617ab744e86ef8a6d2b3b589c8620e87b80e61
50,013
def cmp_char(a, b): """Returns '<', '=', '>' depending on whether a < b, a = b, or a > b Examples -------- >>> from misc_utils import cmp_char >>> cmp_char(1, 2) '<' >>> print('%d %s %d' % (1, cmp_char(1,2), 2)) 1 < 2 Parameters ---------- a Value to be compare...
7e8183564f888df3cce65f2bbbeb659aec43928c
50,014
def retrieve_context_topology_node_owned_node_edge_point_available_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid, node_uuid, owned_node_edge_point_uuid): # noqa: E501 """Retrieve committed-burst-size Retrieve operation of resource: committed-burst-size # noqa: E501 :param uuid...
f299772ba3cab3ca0d508971d45d1ba0a5272b6e
50,015
def get_command_name(cmd, default=''): """Extracts command name.""" # Check if command object exists. # Return the expected name property or replace with default. if cmd: return cmd.name return default
f77a73d1ff24ec74b1c7cf10f89c45fab41fed20
50,016
def _getText(node): """ Obtains the text from the node provided. @param node Node to obtain the text from. @retval Text from the node provided. """ return " ".join(child.data.strip() for child in node.childNodes if child.nodeType == child.TEXT_NODE)
ebd23a28073104e81cd7a1d38323ac2a1c49355b
50,018
from typing import Union import sqlite3 def make_connection_plus_from(conn: Union[sqlite3.Connection, ConnectionPlus] ) -> ConnectionPlus: """ Makes a ConnectionPlus connection object out of a given argument. If the given connection is already a ConnectionPlus, then it is re...
b66ce558d9515d57ecfee066900a5b3150d90c81
50,019
from ._fine_cal import read_fine_calibration def _update_sensor_geometry(info, fine_cal, ignore_ref): """Replace sensor geometry information and reorder cal_chs.""" logger.info(' Using fine calibration %s' % op.basename(fine_cal)) fine_cal = read_fine_calibration(fine_cal) # filename -> dict ch_na...
7b22f9b42adff0f73a2a8b5fa71a9edbcf260eb2
50,020
def polygonOffsetWithMinimumDistanceToPoint(point, polygon, perpendicular=False): """Return the offset from the polygon start where the distance to the point is minimal""" return polygonOffsetAndDistanceToPoint(point, polygon, perpendicular)[0]
b84ca6bf40563c5663490d3c28806ee3b3226500
50,021
def get_package_versions(sha1, os_type, package_versions=None): """ Will retrieve the package versions for the given sha1 and os_type from gitbuilder. Optionally, a package_versions dict can be provided from previous calls to this function to avoid calling gitbuilder for information we've alrea...
24cdcf0641fd0a0bd16c39e7a79c0d2c69f6692f
50,022
def get_arrdepth(arr): """ USAGE ----- arr_depths = get_arrdepth(arr) Determine number of nested levels in each element of an array of arrays of arrays... (or other array-like objects). """ arr = np.array(arr) # Make sure first level is an array. all_nlevs = [] for i in ran...
4d06fdf10f6b3bfb590da86c6627b546db29dbea
50,024
def get_ocid(prefix, tenderID): """greates unique contracting identifier""" return "{}-{}".format(prefix, tenderID)
309e8a07dcdf787fd2dd6a41abb4f4d26f1baa63
50,025
import hashlib def md5(fileName): """Compute md5 hash of the specified file""" m = hashlib.md5() try: fd = open(fileName,"rb") except IOError: print("Reading file has problem:", filename) return x = fd.read() fd.close() m.update(x) return m.hexdigest()
a502ada56c934e7b66155b261a23a283e9b65bf7
50,026
def Kernel(x,f,theta): """ build square kernel matrix for inputs x with kernel function f and parameters theta Inputs ------- x : vector values to evaluate the kenrel function at, pairwise f: kernel function function that accepts inputs as (x1,x2,theta) theta: vector ...
e0bb80f2c90e72bdbf2405f4d96dfaa0f6d3f03c
50,027
from typing import Union def drop_duplicated_indices(df: Union[pd.Series, pd.DataFrame]) -> Union[pd.Series, pd.DataFrame]: """If one concatenates dataframes there might be duplicated indices. This can lead to problems, e.g., in interpolation steps. One easy solution can be to just drop the duplicated row...
5f14965e5cbb7fa859db74588b5880d1b24e8bf3
50,028
import json def report_response(params, runner=None, cache=DEFAULT_CACHE): """ This frontend helper function is meant to be used in your request-processing code to handle all AJAX responses to the Blingalytics JavaScript frontend. In its most basic usage, you just pass in the request's GET parame...
7568ff0e80afcea319ceace1c9f10f807903ce3e
50,029
def median( y, mask): """Return the median of the array y, ignoring masked elements. Parameters ----------- y : ndarray array of values mask : ndarray array of (int32) ones or zeros (0 indicates a good value) Returns -------- med...
e5ff3c249f7246caa94b61aa3586c1e79b01f8fa
50,030
import torch import copy def train_model(x_train, y_train_e, x_val, y_val_e, num_epochs, learning_rate): """ Train the model using the data given, along with the parameters given. @param x_train is the training dataset. @param y_train_e is an np.array of the training labels. @param x_va...
96c8675816178362100082d5911b977ae192d14e
50,031
def polynomial(a0,a1,a2,a3,a4,x): """ Up to x4 """ return a0 + x*(a1+x*(a2+x*(a3+x*a4)))
81ad200df9b6e9d7cd00e1ced8bae8dacec303b1
50,032
def time_round(time, delta, epoch=None): """From https://stackoverflow.com/a/57877961/13775459""" mod = time_mod(time, delta, epoch) if mod < (delta / 2): return time - mod return time + (delta - mod)
a6d6a7e8beb60013c01d0512f5dc0ccf7c2fa0b2
50,033
def resnet(info, depth=28, width=1): """Resnets of varying width and depth.""" N = (depth - 4) // 6 inputs = Input(shape=info.features['image'].shape) x = Conv2D(16, (3, 3), padding='same')(inputs) x = BatchNormalization()(x) x = Activation('relu')(x) for _ in range(N): x = _residu...
7d8e0fc707549d39010db3f9cad2e92496b52d2e
50,034
import hashlib def get_str_md5(content): """ Calculate the MD5 for the str file :param content: :return: """ m = hashlib.md5(content) # 创建md5对象 return m.hexdigest()
c0e864288d8d6af2fe31b5cb5afe54bfe83e2fb3
50,035
def cv_personal_info(request): """Add information about person to CV requests""" return {'cv_personal_info': CV_PERSONAL_INFO}
8f7aa458747dcffc20247926b01ac36f536e6bd9
50,036
def make_test(row): """ Generate a test method """ def row_test(self): actual = row.get("_actual") if actual in ("P", "F"): if actual == "P": self.assertMeansTest("eligible", row) else: self.assertMeansTest("ineligible", row) ...
083117f44687c56a7a33cfa74776baea6b40048c
50,037
def replace_german_umlaute(unicode_string): """.""" utf8_string = unicode_string.encode("utf-8") print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") print("{}".format(utf8_string)) print(u"{}".format(utf8_string)) print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") for k in umlaute_dict.keys(): utf8_string ...
f1d88056b3166443a6cc4989d3b4f4106573cd65
50,038
import posixpath def populate(contents_mgr): """ Populate a test directory with a ContentsManager. """ dirs_nbs = [ ('', 'inroot.ipynb'), ('Directory with spaces in', 'inspace.ipynb'), ('unicodé', 'innonascii.ipynb'), ('foo', 'a.ipynb'), ('foo', 'name with space...
d2d3479e36c102d8d7d98819d2aeb5b40d1cca4c
50,040
def running_mean(clazz=None, batch_size=50, step_size=10, dim=None): """The :func:`running_mean` decorator is used to add a :class:`.RunningMean` to the :class:`.MetricTree`. If the inner class is not a :class:`.MetricTree` then one will be created. The :class:`.RunningMean` will be wrapped in a :class:`.To...
1dd99ce8a33bc66e3b69da5611bb6e405cb4b360
50,041
def min_value(state, depth, max_depth, alpha, beta, transposition_table): """ Acting as the minimizer for the min_max search with alpha beta """ state.depth = depth # checking entry in transposition table table_check = transposition_table.table_lookup(state) if(len(table_check) > 0): ...
ee28fcb8a18cf2aff60fdea3f963ce8a3404f9a0
50,042
def api_client(cluster_name: str, api_class: str) -> k8s.client.apis: """ Creates and returns a python k8s api client of the specified class and pointing to the specified cluster. Usage: Use this function whenever you want a python k8s api client. Python k8s api documentation: https://github.com/kubernetes-clie...
c9c857093dad701fa9a3a745da2c403137191e2d
50,043
def plot_intensity(tc, ax=None, figsize=(10,5), fontsize=15): """ Plot the intensity of the given TC. Parameters ---------- tc: TC A single TC. ax: Axe Axe for plotting figsize: tuple Figure size of (12, 6) fontsize: int Size of the font (title, label and...
6a76018f29de6e08b0715fe67bd94c30ee10e28e
50,044
import PIL.Image as Image def fig_2_Image(fig): """ Ref: https://panjinquan.blog.csdn.net/article/details/104179723 fig = plt.figure() image = fig2data(fig) @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a...
6dda76db1c976005bca0814fd512d747790ff45d
50,045
import math def binary_sigmoid(n: float, lmbda: float = 1.0) -> float: """ Binary Sigmoidal (Unipolar Continuous) Activation Function """ return 1 / (1 + (math.exp(-lmbda * n)))
dec3380311c5bb1130e8455254d55b44ab416d21
50,046
from .collections import store def user_is_valid(data): """user error handling""" resp = "The username you provided already exists" body = store.get_by_field(key='username', value=data.get('username')) is not None errors = {} if store.get_by_field(key='email', value=data.get('email')) is not None...
185e290afe74492d190c4adb336629a38c06c377
50,047
def create_new_ap_hostname(country_code, ap_macs: list(), mgmt_subnet: str) -> dict: """ "WAP<COUNTRY_CODE><2nd_OCTET>3rd_OCTET>_<ascending index starting from 001>" start index will be the lowest management IP address Args: mgmt_subnet: IP network portion (without prefix) ap_macs: list...
ad10091981a3f404d1e5805049e3bcf6e6d18899
50,048
def ldns_tsig_keydata_clone(*args): """LDNS buffer.""" return _ldns.ldns_tsig_keydata_clone(*args)
ccda3684f6611333fe0db77c4eacb325f6c6fa0a
50,049
def log_variance(locations): """ Compute location variance feature from location data. Logarithm of combined variance of latitude and longitude values. :param locations: dataframe of location data with columns latitude and longitude. :return: location variance. """ if len(locations) < 2: ...
d0fbf61ad8154d2ebf4f992682ebfcb1cc77472c
50,050
def client(app): """ Fixture to emulate client""" return app.test_client()
555e43501347e257ea9b0eeb95ba80e99e1a6ce9
50,051
def first_discoverable(targets, cat, kwargs): """A target chooser: the first target for which discover() succeeds This may be useful where some drivers are not importable, or some sources can be available only sometimes. """ for t in targets: try: if cat: s = cat...
592d738d943578929d69d4d98ca98cdda16f96b9
50,052
def _centralize(shape): """Create a shape which is just like the input, but aligned to origin. The origin is (0; 0) in 2D case. The input shape stays unchanged. It's expected to be a numpy.array. """ centroid = shape.mean(0) return shape - centroid
0c65ac55d3dbad9d540d73e2480c0d71ad703302
50,053
import torch import random def evaluate_model(Net, seeds, mini_batch_size=100, optimizer = optim.Adam, criterion = nn.CrossEntropyLoss(), n_epochs=40, eta = 1e-3, lambda_l2 = 0, alpha=0.5, beta=0.5, plot=True,statistics = True ,rotate = False,translate=False,swap_channel = False, ...
7a7e4438eaf81337894cd10454254e368060fb27
50,054
def factory(_context, request): """Return a AuthCookieService instance for the passed context and request.""" cookie = SignedCookieProfile( # This value is set in `h.auth` at the moment secret=request.registry.settings["h_auth_cookie_secret"], salt="authsanity", cookie_name="aut...
1d8191a1202c9493af47d947b5f95c7fc471624d
50,055
def get_fcn_resnet50_model_instance(num_classes): """ This method gets an instance of FCN-Resnet-50 model given num_classes. 0 < num_classes <= 21 :param num_classes: number of classes :return: instance of FCN-Resnet-50 model. """ # Checks constraint on num_classes if num_classes <= 0 ...
594c1f34822ba648a35392bcb4fe8e07bb7bb514
50,056
def projC(gamma,q): """return the KL projection on the column constrints """ return np.multiply(gamma,q/np.maximum(np.sum(gamma,axis=0),1e-10))
9199a9d746a4d1cb1cfb9c074f333289ac9365b1
50,057
def read_file(file_name, package_level=True): """Get file content given file path. :param: [package_level] - Wheather the file is in/out side the `gmail_api_wrapper` package """ file_path = get_absolute_path(file_name, package_level=package_level) with open(file_path) as file_descriptor: ...
2feac46a49acb7a804b7527512e1dfd9d7b98c04
50,058
def fit_vfa_nonlinear(s, fa_rad, tr): """Return T1 based on VFA signals using NLLS fitting. Parameters ---------- s: ndarray 1D array of signals. fa_rad: ndarray 1D array of flip angles (rad). tr: float Repetition time (s). Returns ---...
f8fccfd1e1e61a2da1c8be93eef6f241e8370a7f
50,059
import random def GenerateRandomName(): """Generates a random string. Returns: The returned string will be 12 characters long and will begin with a lowercase letter followed by 10 characters drawn from the set [-a-z0-9] and finally a character drawn from the set [a-z0-9]. """ buf = cStringIO.Stri...
96810577d5c12f97bf3854baee1ff66484b71782
50,060
def _check_fit_params(x_data, fit_params, indices=None): """Check and validate the parameters passed during ``fit``.""" fit_params_validated = {} for param_key, param_value in fit_params.items(): if (not _is_arraylike(param_value) or _num_samples(param_value) != _num_samples(x_data))...
bcf7535af55662130b559b04970fabaa5b7e1ccf
50,062
def is_html_needed(user_agent): """ Basing on `user_agent`, return whether it needs HTML or ANSI """ plaintext_clients = ['curl', 'wget', 'fetch', 'httpie', 'lwp-request', 'python-requests'] if any([x in user_agent for x in plaintext_clients]): return False return True
67a75c34dca4672534058729875dc5ee98696590
50,065
def open_hansen_biomass_tile(tile_id, version): """ Open single tile from the Hansen 2020 dataset and then massage it into a format for use by the rest of the routines. Parameters ---------- tile_id : str The latitude/longitude of the northwest corner of the tile (e.g. 50N_130W) ver...
5f6bb87a90f9506af9e90d29ec11fda2f7c6b8c3
50,066
def process_entry(base_url, i, entry): """ Given a base URL, an index, and an entry dictionary, ensure that the entry is valid, and return an Apache RedirectMatch directive string. """ source = '' replacement = '' # Check entry data type if type(entry) is not dict: raise ValueError('Entry %d is n...
1dd3074fbca9d7c1f646ae348ceb992c027bb1fb
50,067
import unicodedata def _normalize(string_to_convert, normalize=False): """ a utility method for normalizing string """ try: return unicodedata.normalize('NFC', string_to_convert) if normalize else string_to_convert except TypeError: return string_to_convert
2c4edc31741d8b87165996339c8b9231f5ed6aa5
50,068
def pipe(*args, **kwargs): """An aggregator that eagerly sums fields of items in a stream. Note that this pipe is not lazy if `group_key` is specified. Args: items (Iter[dict]): The source. kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe...
dd0b6433793d40c1710cdf2ce72ff627af623279
50,069
def __xor_bytes(bytes1, bytes2): """xor of a list of bytes""" assert len(bytes1) == len(bytes2) return [bytes1[i] ^ bytes2[i] for i in range(len(bytes1))]
0b576cd877839cd2191fee57f6b5f270a37726de
50,070
def plugins_help() -> str: """ Gets the help text for the 'plugins' sub-command. """ return PluginsOptions.get_configured_parser(prog="wai-annotations plugins").format_help()
7d88e2e397fe6d1ddf6298901f7d7fece9a1e91b
50,071
def report_issue() -> str: # pragma: no cover """Used when errors are really f*cked up""" return ('Report an issue please? ' '( https://github.com/agamm/comeback/issues )')
9b6015a12f252341f63bb988d2bb5b46c3c66318
50,072
def get_distro(): """ factory to return the right Distro object """ return distro_instance
bd188dcb27c8f541988a3209453a92cfca34b59d
50,073
def compute_coefficients(temperature_resistance_pairs): """Computes Steinhart-Hart model coefficients. Equations taken from https://www.dataloggerinc.com/wp-content/uploads/2016/10/self-calibrate-thermistors.pdf. Args: temperature_resistance_pairs: sequence of three (temperature, resistance) tuples....
15e7a68281eb5a9b879c1bdd82522630b2d25846
50,074
from datetime import datetime import functools def timed_cache(**timed_cache_kwargs): """LRU cache decorator with timeout. Parameters ---------- days: int seconds: int microseconds: int milliseconds: int minutes: int hours: int weeks: int maxsise: int [default: 128] ty...
0cdad8fcb7f76303b73e883d71e0c055c136f453
50,075
def _get_orthologous_imodulons(M1, M2, method, cutoff): """ Given two M matrices, returns the dot graph and name links of the various connected ICA components Parameters ---------- M1 : ~pandas.DataFrame M matrix from the first organism M2 : ~pandas.DataFrame M matrix from t...
85aa4ba43b74b6b102f062a6aa131e7596ef9b69
50,076
def cont6(): """ 1 cluster (2 shared contours) with 2 subclusters (those from <cont4>). Contains 3 minima (subclusters contain 1 and 2, resp.). """ cont_min = [ cncc(5, (6.00, 3.00), 0.2, (1, 1)), cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15), cncc(2, (6.25, 3.25), 0.3, (6, 1...
4ce2406b6bb6eb26341b64e853b3451003410a53
50,077
def _get_raw_parts_helper(response, http_response_type): """Helper for _get_raw_parts Assuming this body is multipart, return the iterator or parts. If parts are application/http use http_response_type or HttpClientTransportResponse as enveloppe. """ body_as_bytes = response.body() # In or...
755b33a9141e9ec62170f50e278f72fa20c7de2b
50,078
def mom2mag_nm(mom): """Converts moment to magnitude - newtonmetre""" return (np.log10(mom) - 9.05) / 1.5
83da75adb534f6e3e7ed6afa067c111f0688344b
50,079
def mergeWindows(data, dimOrder, maxWindowSize, overlapPercent, batchSize, transform, progressCallback=None): """ Generates sliding windows for the specified dataset and applies the specified transformation function to each window. Where multiple overlapping windows include an element of the input datas...
3775c7c4e5a49921af8ac8cd8a2b7cb37c5e3385
50,080
def UDPOS(*args, **kwargs): """ Universal Dependencies English Web Treebank Separately returns the training and test dataset Arguments: root: Directory where the datasets are saved. Default: ".data" Examples: >>> from torchtext.datasets.raw import UDPOS >>> train_dataset, vali...
cea4db2bba5e97fd6ecb34c4ceda89ee899e0c71
50,081
def _load_global_signal(confounds_raw, global_signal): """Load the regressors derived from the global signal.""" global_params = _add_suffix(["global_signal"], global_signal) _check_params(confounds_raw, global_params) return confounds_raw[global_params]
e904077af687083f0e2135744172a36b4ae38a41
50,082