content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def processPostMessage(post_message, status_type): """ Check if the message is >500 characters If it is, shorten it to 500 characters Ouput: a tuple of strings: read_more (empty if not shortened), post text """ if len(post_message) > 500: post_message = post_message[:500] last_sp...
2d21ec04ef863b57f95bb4b8256f2195559e6f8e
3,608,957
def linkHasRel(link_attrs, target_rel): """Does this link have target_rel as a relationship?""" # XXX: TESTME rel_attr = link_attrs.get('rel') return rel_attr and relMatches(rel_attr, target_rel)
f2a264dbb922d7c2c5318e9564744334f994454e
3,608,958
def _focus_measurement_3d(image, neighborhood_size): """Helmli and Scherer’s mean method used as a focus metric. Parameters ---------- image : np.ndarray, np.uint8 A 3-d tensor with shape (z, y, x). neighborhood_size : int The size of the square used to define the neighborhood of ea...
f830fc867177fdc4232938da03e433a2a5aa9d0a
3,608,959
from mmdet.models import SSDHead def get_ssd_head_model(): """SSDHead Config.""" test_cfg = mmcv.Config( dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.45), min_bbox_size=0, score_thr=0.02, max_per_img=200)) model = SSDHead( ...
d46ea93f0245be1636f0f10497154724c9564f3c
3,608,960
def save_gan_images(generator, epoch, examples=100, dim=(10, 10), figsize=(10, 10)): """ Generate a sample of examples. """ noise = get_noise(examples) generated_images = generator.predict(noise) generated_images = generated_images.reshape(examples, 28, 28) plt.figure(figsize=figsize) f...
2ad954a072e85247990204061566f9bbf6238094
3,608,961
import datasets def load(dataset_info: datasets.DatasetInfo) -> testbed_base.TestbedProblem: """Load a regression problem from a real dataset specified by config.""" num_enn_samples = 1000 # We set it to the number we use for our testbed train_data, test_data = load_dataset(name=dataset_info.dataset_name) d...
de7700759da4aa8b18fc87f8d663720fd3fc4962
3,608,962
def calc_blue(historys): """ { 1: [0.16, 0.16, 0.15, ...], 2: [0.16, 0.16, 0.22, ...], ... 12: [0.16, 0.16, 0.3, ...], } """ blues = [history['result']['blue'] for history in historys] result = dict() for num in range(1,13): #12选2 # result.setdefault(n...
44e391adc8db7c85ecd45c533ce0e12485866113
3,608,963
def get_transition_analysis_matrices(odf_order, angle_max, angle_weight="flat", angle_weighting_power=1.): """ Convenience function that creates and returns all the necessary matrices for iodf1 and iodf2 Parameters: ----------- odf_order: "odf4", "odf6", "odf8" or "odf1...
aab9fa68b11e2f47acb32507e3e72422fdaea1b0
3,608,964
def expected_wait_time_random_arrival(xdata,wdata,headway, nsims = 5000000, ntrips=3, q_half=None): """ Given R-Vector xdata representing instances and R-Vector wdata representing weighted probabilities of those instances (need not add ...
ee1369516d3ee13e48c1b185fdab5b0b4278e6fc
3,608,966
def main(global_config, **settings): """ Returns a Pyramid WSGI application. Apart from the clld boilerplate, it orders the home sub-navigation and registers the get_map_marker hook. """ config = Configurator(settings=settings) config.include('clld.web.app') config.registry.settings['home_c...
71c845c2b6d190cfc7ac1845ddc7f3152c838ebd
3,608,967
import yaml def open_yaml(yfile): """ This function opens file with YAML configuration. :param yfile: Name of file. :return: Python object ( nested lists / dicts ). """ with open(yfile, 'r') as stream: yamlobj = yaml.load(stream) return yamlobj
0a76866a8430cd917518fe620fa7c346cdca7edb
3,608,968
def get_instance_path(index_instance): """ Return a platform formated filesytem path corresponding to an index instance """ names = [] for ancestor in index_instance.get_ancestors(): names.append(ancestor.value) names.append(index_instance.value) return assemble_path_from_list(...
5144a9f6bf9b88b36bec6d6c556448a2450b788c
3,608,969
def download_media_suite(request, domain, app_id): """ See Application.create_media_suite """ if not request.app.copy_of: request.app.set_media_versions(None) return HttpResponse( request.app.create_media_suite() )
bbbefb1eb20a404811baf70d42b389b74301e869
3,608,970
def current_token() -> object: """Return a backend specific token object that can be used to get back to the event loop.""" return get_asynclib().current_token()
d456fef0117d64ce51050171dfb4ae82f8dba45c
3,608,971
import base64 def _derive_sha256_key(passwd): """Derive a base64 encoded urlsafe digest from password. Using the given password, an irreversible hash is derived using cryptography algorithm. To make use of this for Fernet encryption, it is transformed to base64 encoded urlsafe digest. :param str...
4e92a76dca0f99ee0f38d5ba922762396da51d91
3,608,972
def runAllTces(tceFile,sector,outfile): """ Run for all TCEs """ df=p.read_csv(tceFile,comment='#') for index,row in df[37:38].iterrows(): clip = runOneDv(sector,row.ticid,row.planetNumber) text,header = outputInfo(clip) #Write out decision with open(ou...
c1474d79041b904d36fc4a4c2e2b3c90258a00fc
3,608,973
def data_for_keys(data_dict, data_keys): """ Return a dict with data for requested keys, or empty strings if missing. """ return {x: data_dict[x] if x in data_dict else '' for x in data_keys}
b844ae2dba804e179e7e8dd08166f392a90e7f7a
3,608,974
def new_uniformly_random_array_list(low, high, shapes): """ This function returns a list whose kth entry is an array with shape= shapes[k] and with entries selected uniformly at random from the interval [low, high]. Parameters ---------- low : float high : float shapes : list[tuples...
5e4d1a9d2ed1a5e367ef14a6b6941a5429bd6edf
3,608,975
def distinct_values_bt(bin_tree): """Find distinct values in a binary tree.""" distinct = {} result = [] def _walk(node=None): if node is None: return if node.left is not None: _walk(node.left) if distinct.get(node.val): distinct[node.val] =...
8d84d57559a0c813e7ac12199680172a9b591be9
3,608,976
def create_filename_template(request): """creates a new FilenameTemplate """ logged_in_user = get_logged_in_user(request) # get parameters name = request.params.get('name') target_entity_type = request.params.get('target_entity_type') path = request.params.get('path') filename = request...
5cdf50e32ce3b26c86735c8e93aafea880f6ab91
3,608,978
def custom_slugify(data, suffix=True, offset=15): """ Using django util methods create a slug. Append a random string at the end of the slug if necessary for making it unique """ # slugify the source_field passed to the function new_slug = slugify(data)[:offset] if suffix: # get a ...
f4119e3fd6c3e2089376a93cc8dc360983b428f6
3,608,979
def filter_output(filter_callbacks, kwargs, obj, missing_ok=False): """Filter ouput. For each key in filter_callbacks, if it exists in kwargs, kwargs[key] tells what we need to filter. If the call of filter_callbacks[key] returns False, it tells the obj should be filtered out of output. """ ...
cd9f6b1b68b0155a8f00986ae4619ffd4119dabf
3,608,980
def fix_iobtag(iob, DESC_DECISION): """ This is specific to the BBN Corpus; the reason some of the entity labels are being modified: 1) Errors in the original labeling, or 2) Not enough labels of the given category The parameter DESC_DECISION can be 'keep', 'merge' or 'remove', which determine...
2743e7d36c7d8153a7cf6694a69e9a212219ae8f
3,608,981
from typing import List def get_answered_questions(question_list: List[List[bytes]]) -> list: """Dont let the type hint confuse you, problem of not using classes. It takes the result of get_question_list(file_list) Returns a list of questions that are answered. """ t = [] for q in quest...
d485b374721f445ab62853eaa67de65bd2a893e2
3,608,982
import gettext def profile_update(): """ 用户信息更新 :return: """ gender = request.argget.all('gender', 'secret') birthday = request.argget.all('birthday') homepage = request.argget.all('homepage') address = json_to_pyseq(request.argget.all('address', {})) info = request.argget.all('inf...
e7fa3fe06c2fd7f76cf4f39f71001af3630dc308
3,608,983
def keywords_volume_query_id(request, keywd, query_id, format=None): """ Retrieve related queries """ ip_address = request.META['REMOTE_ADDR'] if valid_ip(ip_address) is False: return Response("Not authorised client IP", status=status.HTTP_401_UNAUTHORIZED) print "in view:" + str(keywd...
e94514c5cf58ff31c22205ad4c96f5caeb943212
3,608,984
def drafts(request): """ The function is used to get all the files created by user(employee). It gets all files created by user by filtering file(table) object by user i.e, uploader. It displays user and file details of a file(table) of filetracking(model) in the template of 'Saved f...
d9993ba1c69c5abfc52e14096759bad0a51868b4
3,608,985
from typing import Union def _data_period(index) -> Union[pd.Timedelta, Number]: """Return data index period as pd.Timedelta""" values = pd.Series(index[-100:]) return values.diff().dropna().median()
87d00003072dd364efee89c3f1b6d4a3843211b0
3,608,986
def chain_callbacks(f): """Decorate to mimic the promise pattern via an yield expression. Decorator function to make a wrapper which executes functions yielded by the given generator in order. """ @wraps(f) def wrapper(*args, **kwargs): chain = f(*args, **kwargs) try: ...
616914636a806c5e92ffbc5b79b3b97f20d03490
3,608,987
import json def well_known_did (mode) : """ did:web https://w3c-ccg.github.io/did-method-web/ https://identity.foundation/.well-known/resources/did-configuration/#LinkedDomains """ address = mode.owner_talao # secp256k pvk = privatekey.get_key(address, 'private_key', mode) key = helpe...
15610de05d529b4721790c8e2dd89c93cb64d8ce
3,608,988
def generate_blobimage(shape, blobs): """function to generate blob images from an image shape and blob coordinates and sigmas :param shape:shape of image to generate :param blobs: array with blob coordinates and sigma in last column""" img = np.zeros(shape, dtype=np.float) if blobs is None: ...
2e046e53163058dbda3cb2df490cbe1ef1a7433e
3,608,989
def split_data_list(list_data, num_split): """ list_data: list of data items returning: list with num_split elements, each as a list of data items """ num_data_all = len(list_data) num_per_worker = num_data_all // num_split print("num_data_all: %d" % num_data_all...
7282d1ae89f830d5b48fa73ea3d355cd63344f5c
3,608,991
import re def _find_breakpoint(line, break_pattern=', ', nmax=80): """ determine where to break the line """ line = _remove_comment(line) locs = [m.start() for m in re.finditer(break_pattern, line)] if len(locs) > 0: break_loc = locs[np.where( np.asarray(locs) < (nmax - len(break_p...
553dfe3a088fb16b5abb52ace1078b18917904ae
3,608,992
def patch_set_approved(patch_set): """Return True if the patchset has been approved. :param dict patch_set: De-serialized dict of a gerrit change :return: True if one of the patchset reviews approved it. :rtype: bool """ approvals = patch_set.get('approvals', []) for review in approvals: ...
af7e56be45e537be9308f0031fe3923425afd48c
3,608,994
def _load_one_df(date): """Helper function for load_merged_summary in multiproc pool.""" # print(f'({date}) ', end='', flush=True) print('.', end='', flush=True) return load_casus_summary(date).reset_index()
8ad388d312359a6e77439d90d1189d5a47f424cd
3,608,995
import torch def mean_tour_len_edges(x_edges_values, y_pred_edges): """ Computes mean tour length for given batch prediction as edge adjacency matrices (for PyTorch tensors). Args: x_edges_values: Edge values (distance) matrix (batch_size, num_nodes, num_nodes) y_pred_edges: Edge predicti...
dc15b22fb6625ef7c8fcf4e518a617dd0a109c55
3,608,996
import requests import time import re def nrel_bcl_api_request(data): """Send a request to the Building Component Library API via HTTP GET and return the JSON response. Args: data (dict or OrderedDict): key-value pairs of parameters to post to the API Returns: dict: the j...
e0a32ce733f97dda0302a14b160af2eefb5f565d
3,608,998
import shutil def install( kernel_spec_manager=None, user=False, kernel_name=KERNEL_NAME, display_name=None, prefix=None, ): """Install the Picky kernelspec for Jupyter Parameters ---------- kernel_spec_manager: KernelSpecManager [optional] A KernelSpecManager to ...
7360f8b23f4b2ee8b005b3e3bb6e5de1fd88fb9d
3,608,999
def run_MLKWayPartMgr(H: Netlist, K: int): """[summary] Args: H (Netlist): [description] K (int): [description] Returns: [type]: [description] """ partMgr = MLKWayPartMgr(0.4, K) # partMgr.limitsize = 2000 randseq = [randint(0, K - 1) for _ in H] if isinstance(...
30c09c7889960ff83da1f1f37f5cf1ca3b22a506
3,609,000
import math def compute_difference(bbox, x, y, w, h): """ Helper function for calculating shortest distance between two bounding boxes, using the center coordinates """ boxX, boxY = getBboxMidPoint(bbox) inX, inY = getMidpoint(x, y, w, h) difX = abs(boxX - inX) difY = abs(boxY - inY) d...
c61c0019773ae8d274358f13e779f3183db85597
3,609,001
def ODP_methods(CASRN): """Return all methods available to obtain ODP for the desired chemical. Parameters ---------- CASRN : str CASRN, [-] Returns ------- methods : list[str] Methods which can be used to obtain ODP with the given inputs. See Also -------- ODP...
186ee39db26923c4fc94a80bbe751ef910265062
3,609,002
def PySet_Pop(space, w_set): """Return a new reference to an arbitrary object in the set, and removes the object from the set. Return NULL on failure. Raise KeyError if the set is empty. Raise a SystemError if set is an not an instance of set or its subtype.""" return space.call_method(space.w_set...
5303f9b7afd4d4cfdb6ee065e860720af5b88b8e
3,609,003
def pad_portraits_to_same_size(B1, B2): """ Make sure that two matrices are padded with zeros and/or trimmed of zeros to be the same dimensions. Parameters ---------- B1, B2 (np.ndarray): Portrait matrices of a graph (k x N) Returns ------- BigB1, BigB2 (np.ndarray): ...
d4fbee5187066c440e03922961a143fb610c9aa0
3,609,004
def rss_func(mean, ground_truth): """ Compute the Residual Sum of Squares between the GP predictions and the ground truth values of the simulated lightcurves. :param mean: GP predictive mean :param ground_truth: ground truth values of the simulated lightcurve :return: residual sum of squares ...
7ad2dcf372baf3b2ca5455e175fa6adcf13a8aad
3,609,005
import json def adminUsersEdit(): """ Admin - edit user """ if current_user.is_admin: body = json.loads(request.data) id = body["id"] user = User.query.filter_by(id=id).first() if user is None: user = User.query.filter_by(username=body["username"]).first() ...
93a18439d41ff47d69d6a514a4cb0f822bb04293
3,609,006
def get_hwmi_(kde, inv, ax_t, c_hwmi, c_wsdi, minL): """ ... get hwmi/cwmi and wsdi/csdi over nD cube ... Parsed arguments: kde: dictionary keys: 'cdf', 'x' - cdf: cdf values of KernelDistributionEstimate object - x: support values of KernelDistributionEstimate ...
1fd03168cf00fc23a1ee7f77b97c61ef22b9f723
3,609,007
import random def random_mac_address(local=True): """ Generate random MAC address """ vendor = random.SystemRandom().choice( ( (0x00, 0x05, 0x69), # VMware MACs (0x00, 0x50, 0x56), # VMware MACs (0x00, 0x0C, 0x29), # VMware MACs (0x00, 0x16, 0...
eb89ab223d0e8ae9f011277d92f3cd01d27627e8
3,609,008
def logpolar(src, r0, r1, center=None): """Log-Polar transform The area radii [r0:r1] of radius N/2 mapsto the same size of src image cf. cv2.logPolar(src, (nx,ny), M, cv2.INTER_CUBIC) """ h, w = src.shape if center is None: xc, yc = w//2, h//2 else: xc, yc = center ...
762df3fb22d9f0734334b69c9b160bb6663bcab8
3,609,009
def check_win(game, players): """ -1: ongoing 0: tie > 0: id of winner """ # print(status) # print(status) for player in players: if len(player.destination_cards) == 0: return player.id, 1 if game.card_index >= len(game.cards) or player.trains == 0: ...
0127de10c9b6b9b08dbf07b3747d92a2a9b4115c
3,609,010
from datetime import datetime def now(): """ Return the current UTC time as a datetime object unless the test suites have overriden this value. """ # If the value of now has been frozen, use that, otherwise use the wallclock. if _now_override: n = _now_override else: n = datetime.u...
90d2d1caf2830349136864ef1cc6dbf73d752255
3,609,011
def extract_gs1_data(filepath): """Filepath is absolute filepath to the file "GPC Schema 2018-12 EN.xml" It can be downloaded from https://www.gs1.org/sites/default/files/docs/gpc/en_2018-12.zip. """ root = objectify.parse(open(filepath, encoding="utf-8")).getroot() schema = root["{urn:ean.ucc:2}m...
8b6cd1e5dde6abfeee56b29e2e82aacae00bb65b
3,609,012
def message_has_label(message, label): """Tests whether a message has a label Args: message: message to consider. label: label to check. Returns: True/False. """ return label['id'] in message.get('labelIds', [])
634808b2533469daa42779a3563f127d06ce1b14
3,609,014
def indent_func_def(func_def): """Ensures max columns in a function signature follows style guide""" if len(func_def) < 80: return func_def parts = func_def.split(',') idx = func_def.index('(') params = parts[0] for x in parts[1:]: params += ',\n{}{}'.format(idx * ' ', x) ret...
371bde9c8580982894759d6716a9be6d4f8521a5
3,609,015
def load_img(path): """Returns the numpy array after loading image Input ---------- path: str Output ---------- image: numpy.ndarray """ img = Image.open(path) image = np.array(img) return image
8f8a1e1e9b5c0c2783a423cdfbe7aa111846d568
3,609,017
from typing import Tuple def project_lidarpcs_to_camera(pc: LidarPointCloud, transform: npt.NDArray[np.float64], camera_intrinsic: npt.NDArray[np.float64], width: int, height: int) -> Tuple[npt....
9348adc47ab41179991a0bb01229b7f3e3ac8433
3,609,018
import unicodedata import re def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. Borrowed from https://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename """ value = str(unicodedata.normalize('NFKD'...
88683c3e4c91f909c584f946ac887f1431df1f83
3,609,019
def buildValue(value): """Builds a positioning value record. Value records are used to specify coordinates and adjustments for positioning and attaching glyphs. Many of the positioning functions in this library take ``otTables.ValueRecord`` objects as arguments. This function builds value records f...
8d8d05079a9b4e92fcbfed5a477898b39520d847
3,609,020
def line_colors(streamlines, cmap='rgb_standard'): """ Create colors for streamlines to be used in fvtk.line Parameters ---------- streamlines : sequence of ndarrays cmap : ('rgb_standard', 'boys_standard') Returns ------- colors : ndarray """ if cmap=='rgb_standard': ...
a89fa0384e632f3faa2eac709d722c727b37a3dc
3,609,021
def transform_case(input_string): """ Lowercase string fields """ return input_string.lower()
4d15f33781c1b58d3a04a52fcc8e5f5042e33bdf
3,609,022
from re import S def linear_expand(expr): """ If a sympy 'Expr' is of the form: expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n where all the a_j are noncommuting symbols in basis then (expr_0, ..., expr_n) and (1, a_1, ..., a_n) are returned. Note that expr_j*a_j does not have to be of that...
bbbf7329f14ddadf14fc26d65f0358f71b923a18
3,609,023
from typing import Union def format_numbers_consistently(number: Union[int, float]) -> Union[int, float]: """ Formats numeric values in a consistent way. Prevents inconsistencies with how numbers are formatted (e.g. '12.0' as '12') :type number: float or int :param number: numeric value to forma...
ebf7acdca53ac331ac7a5e1e8ba2ee416cc7112b
3,609,024
import re def extract_date_from_date_time(date_time: str) -> str: """ Given a date in format YYYY-MM-DDTHH:MM:SS, extract the date part (i.e. YYYY-MM-DD) :param date_time : str (DATETIME_FORMAT) :return str a date in DATE_FORMAT """ assert type(date_time) == str, "date_time must ...
4727273615fa38a48eace841c4ff8760ab10d08e
3,609,025
def _join_tokens_to_string(tokens): """Join a list of string tokens into a single string.""" token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_is_alnum[i]: ret.append(u" ") ret.append(token) ...
ea5ba745650ba7f9f6cca205152387aa4b95f500
3,609,026
def make_divisible(value, divisor, min_value=None, min_ratio=0.9): """Make divisible function. This function rounds the channel number down to the nearest value that can be divisible by the divisor. Args: value (int): The original channel number. divisor (int): The divisor to fully div...
950aeb4d48ca8749b8da55c9359798c8127f318e
3,609,027
def cli(ctx, role_name, description, user_ids="", group_ids=""): """Create a new role. Output: Details of the newly created role. For example:: {'description': 'desc', 'url': '/api/roles/ebfb8f50c6abde6d', 'model_class': 'Role', 'type': 'admin', ...
7b9b9f0d72dd2312448eee96dc9743b2b9657271
3,609,028
def train(features, labels, type='cnn', num_classes=None, print_summary=True, save_model=True, lr=0.01, loss_type=None, epochs=100, optimizer='Adam', verbose=True): """Trains model based on provided feature & target data Options: - epochs: The number of iterations. Default is 50. - lr: Learning rate...
c9f96787f384cbb281bfb661d3268da30acf1936
3,609,029
def get_train_test(folder_path, train_size): """返回训练集和测试集的 pcap 的路径, 这里返回的数据格式如下, { 'Chat': ['./data/preprocess_data\\Chat\\AIMchat1\\AIMchat1.pcap.UDP_131-202-240-87_137_131-202-243-255_137.pcap', ...], 'Email': [...], ... } Args: folder_path (str): 包含 pcap 文件的根目录 ...
b67381ba3414236f4128c6aaf1ab45642402578d
3,609,030
def plot_inter_train_results(results, figure_title, pretrain_res=None, key='val_accuracy'): """Plot training progress of pretraining models. :param results: list of subjects inter training results :type results: list of lists of dicts :param figure_title: saving location for created plot :type ...
9bb679aec3daa1ea6accb428110c2e48525f9f5c
3,609,032
def user_point_timestamps(date_start, date_end, outfile=None): """display the timestamps for user points.""" output = _output('=== point timestamps from %s to %s ===\n' % ( date_start, date_end), outfile) if not date_start: output += _output("must specify date_start parameter.", outfile) ...
f7020ae3192e5a1482d8f4bb0b2597b6b01fe157
3,609,033
def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points ...
d93dcb63911f361bd294a11ce2423e90cd4cc131
3,609,034
def eq_entropy(drva,drvt,drvd,airf,temp,dhum,chkbnd=False): """Calculate humid air entropy with derivatives. Calculate the specific entropy of humid air or its derivatives with respect to dry air mass fraction, temperature, and humid air density. :arg int drva: Number of dry fraction deriv...
f5ef09936df64d4db66740921a69fb55063c74f1
3,609,035
import aiohttp import asyncio async def async_check_can_reach_url( hass: HomeAssistant, url: str, more_info: str | None = None ) -> str: """Test if the url can be reached.""" session = aiohttp_client.async_get_clientsession(hass) try: await session.get(url, timeout=5) return "ok" ...
967cc2aa722f35b172138d95dbfad8345c73c69a
3,609,036
def is_licence_accepted(licence_expression: str) -> bool: """Determines whether the licence expressed is valid with regards to project's accepted licences.""" authorised_licences = [licence.identifier for licence in get_allowed_opensource_licences()] is_or = _is_expression_or(licence_expression) if bool...
0cf230a5350a50cb1849945e2d3608d0ece7f589
3,609,038
import numpy def sentence_to_weight_matrix(sentence): """ Converts the dependency graph of a sentence of tokens into a weight matrix. weight[u, v] = 0 iff u == v weight[u, v] = 1 iff u != v and are_bidirectionaly_directly_connected(u, v) == True weight[u, v] = 0 else """ V = len(sentence)...
e413de859ce825b8fc0c00b4241d74746d26b0b0
3,609,040
import csv def find_by_column(filename, column, value): """ This method discovers interactions registered in the DLT looking at one specific value""" list = [] with open(filename) as f: reader = csv.DictReader(f) for item in reader: if item[column] == value: lis...
928f53e72c7b5e3e63316748545a530c20559f8b
3,609,041
def restore(context, backup_info, restore_location): """ Main entry point for restoring a backup based on the given backup id. This will transfer backup data to this instance an will carry out the appropriate restore procedure (eg. mysqldump) :param context: the context token which contains th...
907eba4fa280ca00c911d8f9602f1b950af3ee61
3,609,042
def end_match(s, t, k, direction='sp'): """ Compares the first or last k-1 bases of strings s,t for a match. The direction argument is a two character string whose characters are 'p' or 's', where the first character indicates whether to use the prefix or suffix of s for comparison and the second ch...
d5b912cbcbc33d21c5cba60dd85897fcf73feee4
3,609,043
def hilbert_space_kron(op, indx, dims): """ Extend an operator op to the full product hilbert space given by dimensions in dims. Parameters ---------- op : np.array Operator to be extended. indx : int Position of which subspace to extend. dims : list New dimensio...
2ce100ddfecd1acb6088ebabed00d7578f7aab9a
3,609,044
def genSpecSines_p(ipfreq, ipmag, ipphase, N, fs): """ Generate a spectrum from a series of sine values iploc, ipmag, ipphase: sine peaks locations, magnitudes and phases N: size of the complex spectrum to generate; fs: sampling rate returns Y: generated complex spectrum of sines """ Y = np.zeros(N, dtype = com...
bc3f2a195f190d02513bf14b98816c6a4d8e74fc
3,609,045
from datetime import datetime def dt_to_dec(dt): """Convert a datetime to decimal year.""" year_start = datetime(dt.year, 1, 1) year_end = year_start.replace(year=dt.year+1) return dt.year + ((dt - year_start).total_seconds() / # seconds so far float((year_end - year_start).total_seconds()))
0841f21c245b0f3a2a1404c7c8c5bff9a26aae21
3,609,046
def check_pypi_update(dist_name): """Just check for updates and return a json with the attribute "has_update". :param dist_name: distribution name :rtype: json :return: json with the attribute "has_update" """ pkg_res = get_pkg_res() try: pkg_dist_version = pkg_res.get_distribut...
cc8e3600ebf1d0a07ab8960337249170e2899490
3,609,047
import requests import json def city_coordinate(ip): """ 将ip地址定位:返回城市左下和右上两个点经纬度 :param ip: ip地址 :return: dot_ls 左下,右上经纬度坐标,[(lng1,lat1),(lng2,lat2)] """ url = "https://restapi.amap.com/v3/ip?parameters" parameters = { "ip": ip, "key": user_config.LBS_WEB_KEY } res...
10020d1636f6f055c37aacbce7ba4d2208d7d3c4
3,609,050
def get_fit1(): """ Returns fit file for unit tests, uses data with larger uncertainties. """ info_path = InfoPath( path='temp_data', dir_name="a02_gaussian_mixture1", sub_dir_name=InfoPath.DO_NOT_CREATE ) return run(info_...
e5c0cc9165fbe876553ef033ee06bfd4540daca2
3,609,051
def get_brain_file(file_id): """ :param file_id: :return: """ try: response = get(file_id) except ValueError: response = None return response
915b2ce819cf27b6512ba947d520699c630a92b4
3,609,052
from typing import Optional from typing import Union def normalize_ip_address( v: Optional[Union[str, IPv4Address, IPv6Address]] ) -> Optional[str]: """Pydantic validator for IP address fields. Convert the PostgreSQL INET type to `str` to support reading entries from a PostgreSQL database. Param...
3decda34f8c1265d5a374b0571cc3c1982357be5
3,609,053
def elements_to_stress_array(element_list, timestep=0) -> np.array: """Extract a numpy array containing element stress from a list of nodes at a given timestep""" points = [] for element in element_list: points.append(element.get_stress()) return np.array(points)[:, timestep, :]
20317c23cce42470a64aabbce1c01c6f18d5a075
3,609,054
def enhanceEntries(entriesList, feedId, feedName): """ Add Id of feed to each entry so that we only need the item, which then contains all information that we need Parameters ---------- entriesList : list A List of RSSEntries (FeedParserDicts) feedId : string The URL of th...
db4bf6a82ca4fe41ee0797d361b962126836a7b8
3,609,055
def get_topic_attributes(TopicArn, region=None, key=None, keyid=None, profile=None): """ Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user. CLI example:: salt myminion boto3_sns.get_topic_attributes someTopic region=us-west...
18dba2cdd4b55070c6f37d64073fc9ab85fd7f6b
3,609,056
def check_type(val, predicate, k, name): """Returns VAL. Raises a SchemeError if not PREDICATE(VAL) using "argument K of NAME" to describe the offending value.""" if not predicate(val): bad_type(val, k, name) return val
d0944a6d384ebfe8161cebffe6da001b8e3b49ae
3,609,057
def CalculateMediationPEEffect(PointEstimate2, PointEstimate3, ia = 0, ib = 1): """Calculate derived effects from simple mediation model. Given parameter estimates from a simple mediation model, calculate the indirect effect, the total effect and the indirect effects Parameters ----------...
d2a80db944715a02dd267147087076b14db939a2
3,609,058
def filterColorBias( bmp, bias, savefile = '' ): """ """ for h in range(bmp.height): for w in range(bmp.width): if( abs(bmp.pixels[h][w][0]-bmp.pixels[h][w][1]) > bias or abs(bmp.pixels[h][w][0]-bmp.pixels[h][w][2]) > bias or abs(bmp.pixels[h][w][1]-bmp...
1813c85a638fc0bd7523430eb54b9ceb88d379dc
3,609,059
async def delete_page_route( current_user: UserIn = Depends(get_validated_user), page_id: str = Form(None, title="page_id")): """Remove a page for a given user, provided they own it""" if (page := await page_verify(current_user, page_id)): # Delete metadata return await page_dele...
099c9f8f024a5dfca1154071d0904e754f41a057
3,609,060
def get_keywords(search_term): """ get the scored keywords for the search term's page, then just return the top words without their scores """ keywords_and_scores = keywords_with_scores(search_term) return [keyword for keyword, score in keywords_and_scores]
e968b5ff594e201f946be17b164cac927db53cb2
3,609,061
import json def get_employees_by_current_project(term): """ Method to return an array of employees by project as json response. """ print("-" * 50) print("Term: " + term + "\n") results = es.search( index="projects", body={ "query": { "match_phrase...
42d9cdc3a7850d06ce5e6444b37c73c4704803ba
3,609,062
def tf_out(): """Static equilibrium results from threebar funicular.""" output = {} output["xyz"] = {0: [0.29289321881345254, -0.7071067811865475, 0.0], 1: [1.0, 0.0, 0.0], 2: [2.5, 0.0, 0.0], 3: [3.207106, -0.7071067, 0.0]} output["force"]...
1f60894de3cb14b147baa552e4485aed0544a2b0
3,609,063
from bs4 import BeautifulSoup def get_text_from_XML_without_saving(path): """ :param path: path to the XML file :return: Text extracted from the path """ tree = open(path, 'r', encoding='utf8') soup = BeautifulSoup(tree) for script in soup(["script", "style"]): script.extract() ...
f6fd435ae75ca6cc7743e8d0b7da6afca24b0719
3,609,064
def _parse_color_input(number_of_elements, color_spec, cmap=None, vmin=None, vmax=None, alpha=1.): """ Handle the mess that is matplotlib color specifications. Return an RGBA array with specified number of elements. Arguments --------- number_of_elements: int Numb...
5752f06475786d02f7f897c52191f02be4e646cb
3,609,066
def Histogram(dfs, measurement, configs, analysisType, bins=50, iqr=None, **addConfigs): """Generates a Points Plot with a corresponding Histogram""" newConfigs = addConfigs log.info("Generating histograms for measurement {}...".format(measurement)) finalplots = None try: for key in dfs["key...
d205966633505270ff60a08348ee8536527c9f21
3,609,067
import json def user_profile(username): """Renders the user profile page given their username.""" user = User.query(User.username_lower == username.lower()).get() if not user: user = User.query(User.username == username).get() if not user: return render_template("blank_profile.html", username=username...
199456fb57c23cb7cd795864d14c4e141d050f7d
3,609,068
import hashlib def _insert_object_resp(bucket=None, name=None, data=None): """Fake GCS object metadata""" assert type(data) is bytes hasher = hashlib.md5() hasher.update(data) md5_hex_hash = hasher.hexdigest() return { u'bucket': bucket, u'name': name, u'md5Hash': _he...
7bad1a7ecab042e60cb7a34d2e92679581226a18
3,609,069