content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def determine_all_layers_for_elev(std_atmos, layers, values, elevation): """Determine all of the layers to use for the elevation Args: std_atmos [StdAtmosInfo]: The standard atmosphere layers [<str>]: All the pressure layers values [<LayerInfo>]: All the interpolated layers information ...
c3e23670437efa7caa03f1027b2a59d0bd62361a
26,500
from typing import List def remove_redundant( text: str, list_redundant_words: List[str] = S_GRAM_REDUNDANT, ) -> str: """To remove phrases that appear frequently and that can not be used to infere skills. Parameters ---------- text : str The text to clean. list_redundant_words : ...
07a3dfca84acb57b0786e17879d2ac17693c8eba
26,501
import asyncio def position_controller_mock(): """ Position controller mock. """ mock = MagicMock(spec=PositionController) future = asyncio.Future() future.set_result(None) mock.update_odometry = MagicMock(return_value=future) return mock
71e7c4a5894eb56ab99aaec03e9e569291e12e6c
26,502
import sys def trim(docstring): """PEP257 docstring indentation trim function.""" if not docstring: return "" # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (firs...
0035c5af5718e9d26949439a4178ee1958d99ac7
26,503
def forest_overview(): """ The remove forest URL handler. :return: The remove_forest.html page """ all_sensors = mysql_manager.get_all_sensors() for sensor_module in all_sensors: sensor_module['latest_measurements'] = mysql_manager.get_latest_measurements_from_sensor(sensor_module['id...
05ffdd24a08ab6553ac175bd2dfc690bfbf1876e
26,504
def task_dev(): """Run the main task for the project""" return { 'actions': ["docker run --volume %s/:/app %s" % (CONFIG["project_root"], IMAGE)] }
7a8f3dab41076d56717312c01a6144dfd7fac43b
26,505
import struct from datetime import datetime def header_parse(header, ts_resolution): """ parses the header of a TOB3 frame. Parameters ---------- header: string of binary encoded dat with length of 12-Bytes ts_resolution: frame time resolution. multiplier for sub-second part ...
7615064961e44167a3efbca888522fc9433e4598
26,506
def shuff_par_str(shuffle=True, str_type="file"): """ shuff_par_str() Returns string from shuffle parameter to print or for a filename. Optional args: - shuffle (bool): default: True - str_type (str): "print" for a printable string and "file" for a string usab...
956fd86c4ce458d73ebfd425e8b9430dbd027705
26,507
def fft_imaginary(x: np.ndarray) -> np.ndarray: """ Imaginary values of FFT transform :param x: a numeric sequence :return: a numeric sequence """ x_fft = np.fft.fft(x) xt = np.imag(x_fft) return xt
6c9a60a160475f687fba8f624b8e06e4f63d5125
26,508
def prodtype_to_platform(prods): """ Converts one or more prodtypes into a string with one or more <platform> elements. """ if isinstance(prods, str): return name_to_platform(prodtype_to_name(prods)) return "\n".join(map(prodtype_to_platform, prods))
f23d14001ac9afdf3215b5ecbbc23759708c27fd
26,509
import pickle def train_config_setting(config, dataset): """ Configuring parameter for training process :param config: type dict: config parameter :param dataset: type str: dataset name :return: config: type dict: config parameter """ # Load max shape & channels of images and labels. ...
ecb9fde6cf19220f4503c42345fdfaf690f2783a
26,510
def parse_bool(value): """Parses a boolean value from a string.""" return _parse_value(value, BooleanField())
0291ca0a68abe2f2a0e9b92f6c931e3d5a06a69a
26,511
def load_dataset_X_y(dirname, opt): """ load training data :param : dirname : str, loading target directory :param : opt : str, option data format "pandas" or "numpy" :return : data_X : numpy, training data :return : data_y : numpy, true data """ # X input_filename = di...
602008cb3c03ec64861646a9f8a1a8647b01d59a
26,512
def connect_to_es(host, port, use_auth=False): """ Return client that's connected to an Elasticsearch cluster. Unless running from authorized IP, set use_auth to True so that credentials are based on role. """ if use_auth: http_auth = _aws_auth() else: http_auth = None es = ...
db29aef8d08c46c375c68e4da6100164321495a5
26,513
import select from typing import cast def task_5(): """Задание 5""" s = select([ student.c.name, student.c.surname, cast((student.c.stipend * 100), Integer) ]) print(str(s)) rp = connection.execute(s) return rp.fetchall()
3932bb3da4a443154805e708a58924d07f1d5221
26,514
def sentinelCloudScore(img): """ Compute a custom cloud likelihood score for Sentinel-2 imagery Parameters: img (ee.Image): Sentinel-2 image Returns: ee.Image: original image with added ['cloudScore'] band """ im = sentinel2toa(img) # Compute several indicators of cloudyness ...
672fca54fb0e43d9cae51de95149a44b0ed731bc
26,515
import re def safe_filename(name: str, file_ending: str = ".json") -> str: """Return a safe version of name + file_type.""" filename = re.sub(r"\s+", "_", name) filename = re.sub(r"\W+", "-", filename) return filename.lower().strip() + file_ending
98a887788046124354676a60b1cf7d990dbbc02f
26,516
def group(): """ RESTful CRUD controller """ if auth.is_logged_in() or auth.basic(): pass else: redirect(URL(c="default", f="user", args="login", vars={"_next":URL(c="msg", f="group")})) module = "pr" tablename = "%s_%s" % (module, resourcename) table = s3db[tablename]...
df532b93901b7c709ac21c2da4fffe1e06159f0c
26,517
def _tracking_cost(time: int = 0, state: np.ndarray = None) -> float: """Tracking cost function. The goal is to minimize the distance of the x/y position of the vehicle to the 'state' of the target trajectory at each time step. Args: time : Time of the simulation. Used for time-dependent cost ...
cd4f39c78687d3975e2e4d1bc0e3b8d8f8fc4b2c
26,518
def fixture_repo(repo_owner: str, repo_name: str) -> Repository: """Return a GitHub repository.""" return Repository(repo_owner, repo_name)
4a2cae78bfcb0158ae8751305c7a187b368f5d5d
26,519
def get_clean(source_file): """Generate a clean data frame from source file""" print('Reading from source...') df = pd.read_csv(source_file) print('Cleaning up source csv...') # Drop rows with too much NA data df.drop(['Meter Id', 'Marked Time', 'VIN'], axis=1, inplace=True) # Drop rows miss...
f565dcd75faf3464b540f42cc76aafdc59f0c2d8
26,520
def populate_db(): """Populate the db with the common pop/rock songs file""" songs = dm.parse_file('static/common_songs.txt') freq_matrix = dm.get_frequency_matrix(songs) model, clusters = clustering.clusterize(freq_matrix) clustering.save(model, MODEL_FILENAME) clusters_for_db = {} try: ...
87ff8fdebd398e0cff006f40ad9a69f658991eda
26,521
def magenta_on_red(string, *funcs, **additional): """Text color - magenta on background color - red. (see sgr_combiner()).""" return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_RED,))
3b6062a6ae326766a8d44d34e2c3a4e47c232430
26,522
import os def enabled(flag: str) -> bool: """ Returns whether an environment flag is enabled. """ return os.getenv(flag, "").lower() in ENABLED_SYMBOLS
36be493e28f0bc97fedbb47c9a7dd5df5dd192fa
26,523
def create_entry(entry: Entry) -> int: """ Create an entry in the database and return an int of it's ID """ return create_entry(entry.title, entry.text)
6aa2832a9bf7b81460e792c96b06a599cc512e7b
26,524
def process_document_bytes( project_id: str, location: str, processor_id: str, file_content: bytes, mime_type: str = DEFAULT_MIME_TYPE, ) -> documentai.Document: """ Processes a document using the Document AI API. Takes in bytes from file reading, instead of a file path """ # Th...
92ae70d0e3754b76f7cc8b6b0370d53e9031b319
26,525
import numpy as np def merge_imgs(imgs, cols=6, rows=6, is_h=True): """ 合并图像 :param imgs: 图像序列 :param cols: 行数 :param rows: 列数 :param is_h: 是否水平排列 :param sk: 间隔,当sk=2时,即0, 2, 4, 6 :return: 大图 """ if not imgs: raise Exception('[Exception] 合并图像的输入为空!') img_shape = i...
c591c450e54aea76ea237263b3169ef4af306a96
26,526
import nose import os.path def get_nose_runner(report_folder, parallel=True, process_timeout=600, process_restart=True): """Create a nose execution method""" def _run_nose(test_folders): if not report_folder or not os.path.exists(report_folder) or not os.path.isdir(report_folder): raise ...
a8ba0471f6e64b3c4f61bd58b44a6d42d621fc0f
26,527
def text_editor(): """Solution to exercise R-2.3. Describe a component from a text-editor GUI and the methods that it encapsulates. -------------------------------------------------------------------------- Solution: -------------------------------------------------------------------------- ...
39fd3f41cbc28d333dd5d39fc8d1967164bd7bc4
26,528
def generate_imm5(value): """Returns the 5-bit two's complement representation of the number.""" if value < 0: # the sign bit needs to be bit number 5. return 0x1 << 4 | (0b1111 & value) else: return value
72be8225d364ec9328e1bb3a6e0c94e8d8b95fb0
26,529
def CalculateChiv6p(mol): """ ################################################################# Calculation of valence molecular connectivity chi index for path order 6 ---->Chiv6 Usage: result=CalculateChiv6p(mol) Input: mol is a molecule object....
332a5fab80beaa115366ed3a5967a7c433aa8981
26,530
def _cart2sph(x,y,z): """A function that should operate equally well on floats and arrays, and involves trignometry...a good test function for the types of functions in geospacepy-lite""" r = x**2+y**2+z**2 th = np.arctan2(y,x) ph = np.arctan2(x**2+y**2,z) return r,th,ph
fb0184c315c9b4206b4ffc5b019264162b9641d4
26,531
from typing import Optional def get_existing_key_pair(ec2: EC2Client, keypair_name: str) -> Optional[KeyPairInfo]: """Get existing keypair.""" resp = ec2.describe_key_pairs() keypair = next( (kp for kp in resp.get("KeyPairs", {}) if kp.get("KeyName") == keypair_name), None, ) if k...
d066431f784e108e0b27a7c73f833b716cf6e879
26,532
import jinja2 def render_template(template: str, context: dict, trim_blocks=True, lstrip_blocks=True, **env_kwargs): """ One-time-use jinja environment + template rendering helper. """ env = jinja2.Environment( loader=jinja2.DictLoader({'template': templ...
26ec504d694682d96fce0240145549f0f62c0695
26,533
def _func_to_user(uid, func): """ Internal function for doing actions against a user. Gets the user from the database, calls the provided function, and then updates the user back in the database. Args: uid (string) -- The user's key func (function) -- activity to perform on the use...
f3f9af52410a15f61492adbb88cb9706de2e7042
26,534
import torch def breg_sim_divergence(K, p, q, symmetric=False): # NOTE: if you make changes in this function, do them in *_stable function under this as well. """ Compute similarity sensitive Bregman divergence of between a pair of (batches of) distribution(s) p and q over an alphabet of n elements. ...
f668b4af511c1689ec66a34f386c756b7b0fdb0e
26,535
def manage_pages(request): """Dispatches to the first page or to the form to add a page (if there is no page yet). """ try: page = Page.objects.all()[0] url = reverse("lfs_manage_page", kwargs={"id": page.id}) except IndexError: url = reverse("lfs_add_page") return HttpR...
5b50821c516cd450dde5dba9f83c27687e63c8ef
26,536
def get_network_info(): """ Sends a NETWORK_INTERFACES_INFO command to the server. Returns a dict with: - boolean status - list of str ifs (network interfaces detected by RaSCSI) """ command = proto.PbCommand() command.operation = proto.PbOperation.NETWORK_INTERFACES_INFO data = sen...
0d0517eeee5260faa2b12de365f08b8d962eb0c8
26,537
from typing import Optional def basis(asset: Asset, termination_tenor: str, *, source: str = None, real_time: bool = False, request_id: Optional[str] = None) -> Series: """ GS end-of-day cross-currency basis swap spread. :param asset: asset object loaded from security master :param terminat...
92c613e8522dab1bfcf3da5ffd4c9dd8e89fb175
26,538
import os def env_path_contains(path_to_look_for, env_path=None): """Check if the specified path is listed in OS environment path. :param path_to_look_for: The path the search for. :param env_path: The environment path str. :return: True if the find_path exists in the env_path. :rtype: bool "...
75d650ed6ef21c479404def73edca5cdee4a4bb4
26,539
def jp_clean_year(string, format): """Parse the date and return the year.""" return getYearFromISODate(iso8601date(string,format))
33b1a9121485abaff93c4ec979c3c3f63d7d1252
26,540
def _epsilon(e_nr, atomic_number_z): """For lindhard factor""" return 11.5 * e_nr * (atomic_number_z ** (-7 / 3))
8c6115b77ce3fb4956e5596c400c347e68382502
26,541
def compute_heatmap(cnn_model, image, pred_index, last_conv_layer): """ construct our gradient model by supplying (1) the inputs to our pre-trained model, (2) the output of the (presumably) final 4D layer in the network, and (3) the output of the softmax activations from the model """ gradM...
2ee24d643de319588307913eb5f15edbb4a8e386
26,542
def did_git_push_succeed(push_info: git.remote.PushInfo) -> bool: """Check whether a git push succeeded A git push succeeded if it was not "rejected" or "remote rejected", and if there was not a "remote failure" or an "error". Args: push_info: push info """ return push_info.flags & GIT...
ff9ea6856767cda79ed6a6a82b5cadacb1318370
26,543
import six def find_only(element, tag): """Return the only subelement with tag(s).""" if isinstance(tag, six.string_types): tag = [tag] found = [] for t in tag: found.extend(element.findall(t)) assert len(found) == 1, 'expected one <%s>, got %d' % (tag, len(found)) return found...
fd4ec56ba3e175945072caec27d0438569d01ef9
26,544
async def mongoengine_invalid_document_exception_handler(request, exc): """ Error handler for InvalidDocumentError. Logs the InvalidDocumentError detected and returns the appropriate message and details of the error. """ logger.exception(exc) return JSONResponse( Response(succes...
cb9722a6619dfcdaeebcc55a02ae091e54b26207
26,545
def gen_2Dsersic(size,parameters,normalize=False,show2Dsersic=False,savefits=False,verbose=True): """ Generating a 2D sersic with specified parameters using astropy's generator --- INPUT --- size The dimensions of the array to return. Expects [ysize,xsize]. The 2D gauss will ...
8202ef9d79cc7ccb42899a135645244ecd4fc541
26,546
import torch def dqn(agent, env, brain_name, n_episodes=2500, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.999, train=True): """Deep Q-Learning. Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode ...
a1c1715451c8613866871c5e51e423d3a67e6928
26,547
from datetime import datetime def get_activity_stats_subprocess( data_full: list[ActivitiesUsers], data_cp: list[ActivitiesUsers] ) -> DestinyActivityOutputModel: """Run in anyio subprocess on another thread since this might be slow""" result = DestinyActivityOutputModel( full_completions=0, ...
c7ef7f93e0aeefe659676bac98944fbf88eaabe7
26,548
def ma_cache_nb(close: tp.Array2d, windows: tp.List[int], ewms: tp.List[bool], adjust: bool) -> tp.Dict[int, tp.Array2d]: """Caching function for `vectorbt.indicators.basic.MA`.""" cache_dict = dict() for i in range(len(windows)): h = hash((windows[i], ewms[i])) if h not in c...
ae2547ba2c300386cc9d7a9262c643a305ca987f
26,549
def get_AllVolumes(controller, secondary=None): """Run smcli command 'show AllVolumes' on the controller, the output is returned to the calling function. The primary controller (a) is mandatory, but the secondary controller (b) is optional.""" # Check which controller is reachable. ...
32125adec4811d1813e3e804c05c647e1de1e011
26,550
def fetch_slot_freq_num(timestamp, slot, freq_nums): """Find GLONASS frequency number in glo_freq_nums and return it. Parameters ---------- timestamp : datetime.datetime slot : int GLONASS satellite number freq_nums : dict { slot_1: { datetime_1: freq-num, ... } } Returns ...
835a71def86478cbc7327b3873c203ad6936276d
26,551
def _apply_function(x, fname, **kwargs): """Apply `fname` function to x element-wise. # Arguments x: Functional object. # Returns A new functional object. """ validate_functional(x) fun = get_activation(fname) lmbd = [] for i in range(len(x.outputs)): lmbd.appe...
a968dcea7ac95f154c605ba34737c13198b62d77
26,552
import os def GetFilesSplitByOwners(files): """Returns a map of files split by OWNERS file. Returns: A map where keys are paths to directories containing an OWNERS file and values are lists of files sharing an OWNERS file. """ files_split_by_owners = {} for action, path in files: dir_with_owner...
a7c61be189b628a025bb6cff3e67430dfab122b8
26,553
def get_url(city): """ Gets the full url of the place you want to its weather You need to obtain your api key from open weather, then give my_api_key the value of your key below """ my_api_key = 'fda7542e1133fa0b1b312db624464cf5' unit = 'metric' # To get temperature in Celsius weat...
9454a9ad4a2baacb7988216c486c497a0253056c
26,554
def login() -> ApiResponse: """Login a member""" member_json = request.get_json() email = member_json["email"] password = member_json["password"] member = MemberModel.find_by_email(email) if member and member.verify_password(password) and member.is_active: identity = member_schema.dump...
73122e8a52a420ed20c7f11eb63be1317a818c1d
26,555
from typing import Sequence from typing import Union from typing import Iterator def rhythmic_diminution(seq: Sequence, factor: Union[int, float]) -> Iterator[Event]: """Return a new stream of events in which all the durations of the source sequence have been reduced by a given factor. """ return (Eve...
a2ce2982f487e228594ecf992b8d5ed01799f9e2
26,556
def get_line_offset(): """Return number of characters cursor is offset from margin. """ user_pos = emacs.point() emacs.beginning_of_line() line_start = emacs.point() emacs.goto_char(user_pos) return user_pos - line_start
6c2144699eec32f7f22991e8f12c4304024ca93f
26,557
def test_scheduler_task(scheduler: Scheduler) -> None: """ scheduler_task decorator should allow custom evaluation. """ @scheduler_task("task1", "redun") def task1( scheduler: Scheduler, parent_job: Job, sexpr: SchedulerExpression, x: int ) -> Promise: return scheduler.evaluate(...
4b129d25a719019323905888649d8cec0e40513e
26,558
def verse(day): """Produce the verse for the given day""" ordinal = [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', ] gifts = [ ...
027cedf0b1c2108e77e99610b298e1019629c880
26,559
def create_todo(business, ar_year, ar_min_date, ar_max_date, order, enabled): # pylint: disable=too-many-arguments """Return a to-do JSON object.""" todo = { 'task': { 'todo': { 'business': business.json(), 'header': { 'name': 'annualRepor...
2b52e4e2d101422c7fa9941ba0a06b898e3e0ba5
26,560
import uuid async def invite_accept_handler( invite_id: uuid.UUID = Form(...), current_user: models.User = Depends(get_current_user), db_session=Depends(yield_db_session_from_env), ) -> data.GroupUserResponse: """ Accept invite request. If the user is verified, adds user to desired group and m...
4faf22d3f3f9c59d040961b25b1f1660a002f9bd
26,561
def read_current_labels(project_id, label_history=None): """Function to combine label history with prior labels. Function that combines the label info in the dataset and the label history in the project file. """ # read the asreview data as_data = read_data(project_id) # use label history ...
5676be04acc8dd2ab5490ec1223585707d65d834
26,562
import collections def get_mindiff(d1, d2, d3): """ This function determines the minimum difference from checkboxes 3, 5, and 7, and counts the number of repetitions. """ min_diff = [] for i, _ in enumerate(d1): diffs_list = [d1[i], d2[i], d3[i]] md = min(diffs_list) if md == ...
d2bf03b31712a15dbee45dbd44f3f937a3fd4a1a
26,563
def mode(lyst): """Returns the mode of a list of numbers.""" # Obtain the set of unique numbers and their # frequencies, saving these associations in # a dictionary theDictionary = {} for number in lyst: freq = theDictionary.get(number, None) if freq == None: # number...
bccf7955741ad4258dea7686559b9cb0bf934ab4
26,564
import os def download(dataset, path='./', quiet=False, sub_dir='', debug=False, use_cache=True): """Download scripts for retriever.""" args = { 'dataset': dataset, 'command': 'download', 'path': path, 'sub_dir': sub_dir, 'quiet': quiet } engine = choose_engine(...
3ccc22ee65c9d1749575c57634904a476cd44284
26,565
def project_permissions(project_id): """View and modify a project's permissions. """ # does user have access to the project? project = helpers.get_object_or_exception(Project, Project.id == project_id, exceptions...
45fda8e95394e8271ee03e9cc65bdbe03dc18f8b
26,566
import pandas as pd def fetch_community_crime_data(dpath=None): """Downloads community crime data. This function removes missing values, extracts features, and returns numpy arrays Parameters ---------- dpath: str | None specifies path to which the data files should be downloaded. ...
c85e74c647d70497479fabb43d78887bb55751f0
26,567
def linear_forward(A, W, b): """ Implement the linear part of a layer's forward propagation. Arguments: A -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (size of current layer, size of previous layer) b ...
db9120f983b20ea67e9806c71b32463f47fe2839
26,568
def get_task_reviews_count(request): """RESTful version of getting all reviews of a task """ logger.debug('get_task_reviews_count is running') task_id = request.matchdict.get('id', -1) task = Task.query.filter(Task.id == task_id).first() if not task: transaction.abort() return ...
9c9e114f4ef7ee9cf33e3c85331de21e317d50e7
26,569
from typing import Sequence from typing import Match import glob async def mp_force(p: 'Player', m: 'Match', msg: Sequence[str]) -> str: """Force a player into the current match by name.""" if len(msg) != 1: return 'Invalid syntax: !mp force <name>' if not (t := await glob.players.get(name=' '.jo...
58f8d0c8ad0e623973b49792253344cba430b8d5
26,570
def draw_concat(Gs, Zs, reals, NoiseAmp, in_s, mode, opt): """get image at previous scale""" G_z = in_s if Gs: if mode == 'rand': count = 0 for G, Z_opt, real_curr, real_next, noise_amp in zip(Gs, Zs, reals, reals[1:], NoiseAmp): if count == 0: ...
a52db339e6e657148dcf74ef815dd265929f545f
26,571
import tqdm import os def generate_spline_window_chips(*, image_paths, output_dir): """Interpolates all images using a squared spline window""" if not image_paths: return [] first_image = image_paths[0] with rasterio.open(first_image) as src: chip_size = src.width n_channels =...
d3db8803644e7eca3bf68396e4ff3f6110402148
26,572
def read(filename): """ Read TOUGHREACT chemical input file. Parameters ---------- filename : str Input file name. """ with open_file(filename, "r") as f: out = read_buffer(f) return out
acf88a707048bed3f0c59aab3c1f328a5f0d8bf5
26,573
def visit_bottomup(f, d): """Visits and rewrites a nested-dict ``d`` from the bottom to the top, using the ``f`` predicate.""" if isinstance(d, dict): return f({k: visit_bottomup(f, v) for (k, v) in d.items()}) else: return f(d)
9fb4884f1280afe06a1819a44e3055c1173284b1
26,574
import os def watson_transcribe(recording): """ Send Recorded Audio to IBM Watson for Transcription and return the transcription as formated word per line. """ print(10 * "*" + "Watson Transcribe" + 10 * "*") watson_username = os.environ.get('WATSON_USERNAME') watson_password = os.environ.get('WATSON_PAS...
80e6a6d5f85dccda2bc6cd9b08bbf61b35951125
26,575
def processNonTerminal(nt): """ Finds the rule expansion for a nonterminal and returns its expansion. """ return processRHS(grammar.getRHS(nt))
c938ee877e8b66d9ed9aad6cf3708b5d2241279d
26,576
def get_attributes_as_highlighted_html(rid): """Get column descriptions for a given CSV file. The columns are described in EML attribute elements. """ return { k: dex.util.get_etree_as_highlighted_html(v) for k, v in get_attributes_as_etree(rid).items() }
0e19ccca6d09b6cdaac9361a02c5e38e84ae9190
26,577
import timeit import multiprocessing import itertools def bound_update(unary,X,kernel,bound_lambda,bound_iteration =20, batch = False, manual_parallel =False): """ Here in this code, Q refers to Z in our paper. """ start_time = timeit.default_timer() print("Inside Bound Update . . .") N,K...
c5b1be8fb881d2b2bb8596843747441c5e6ca99a
26,578
from typing import List def get_walkable_field_names(model: Model, field_types: List[Field] = None) -> List[str]: """Get a list with names of all fields that can be walked""" if field_types is None: field_types = [ManyToManyField, ManyToOneRel] fields_to_walk = [] fields = getattr(model, '_met...
0ef53ce31072913861e6e78a22eb387b2e185ca8
26,579
def normalize(email): """ Returns a NormalizedEmail with the appropriate contents """ try: v = validate_email(email) return NormalizedEmail(v['email']) except EmailNotValidError as e: return NormalizedEmail(str(e), error=True)
4379966f68810b22c06b81597b706454f46a8247
26,580
def valid_flavor_list(): """ this includes at least 'BIAS', 'LIGHT' based on forDK.tar.gz samples capitalization inconsistent in forDK.tar.gz samples need to keep an eye out for additional valid flavors to add """ # not sure how to deal with reduced image flavors that I've invented: # R...
b12451ff4725f5fcea3592373ef6e53cbe04b23c
26,581
import os import array def loadfits(filename, dir="", index=0): """READS in the data of a .fits file (filename)""" filename = capfile(filename, '.fits') filename = dirfile(filename, dir) if os.path.exists(filename): # CAN'T RETURN data WHEN USING memmap # THE POINTER GETS MESSED UP OR ...
e59287b4ae2e458367d77f1e764e71e299d94682
26,582
from pathlib import Path async def show_tile_with_body( request: Request, response: Response, body: TileRequest, path: Path = Depends(imagepath_parameter), extension: OutputExtension = Depends(extension_path_parameter), headers: ImageRequestHeaders = Depends(), config: Settings = Depends(get_s...
6f6767f4831496796e2cf622a0362fab11dee844
26,583
def create_mesh(ob_name, coords, edges=[], faces=[]): """Create point cloud object based on given coordinates and name. Keyword arguments: ob_name -- new object name coords -- float triplets eg: [(-1.0, 1.0, 0.0), (-1.0, -1.0, 0.0)] """ # Create new mesh and a new object me = bpy.data.mesh...
b57baf08c2a2b07516e36e741b2aa55054883bf8
26,584
def get_time_from_datetime(data): """ Returns a timedelta64 series the form "hh:mm:ss" from data, being a datetime64 series """ time = data.apply(lambda x: np.timedelta64(x.hour, 'h') + np.timedelta64(x.minute, 'm') + np.timedelta64(x.second, 's')) return time
d7af50beadbb426d7b1d0671cabf16546707a1b6
26,585
import math def mms_feeps_pitch_angles(trange=None, probe='1', level='l2', data_rate='srvy', datatype='electron', suffix=''): """ Generates a tplot variable containing the FEEPS pitch angles for each telescope from magnetic field data. Parameters: trange : list of str time range of in...
c74bd2f717dcae231d1071013b04c58879efdb3e
26,586
def tokenize(text): """Converts text to tokens. Case-folds, removes stop words, lemmatises text. This is the same tokenization as is done on the training data for the model. """ # Set up dict for lemmatisation tag_map = defaultdict(lambda : "n") # by default, assume nouns tag_map['J'] = "a" #...
d7c6a124d13bd2d0360a22edc24a4d079bb9d93b
26,587
def do_command(client, command, indices, params=None): """ Do the command. """ if command == "alias": return alias( client, indices, alias=params['name'], remove=params['remove'] ) if command == "allocation": return allocation(client, indices, rule=para...
e33325a941ee4ed7e50c90cc8fb1067abe377d52
26,588
def filetostr(filename): """ filetostr """ try: with open(filename, "rb") as stream: return stream.read() except: return None
52683ada0008fb22e1c48301adf3fd7c48c21d06
26,589
def valid_for(days): """Return a text saying for how many days the certificate is valid for or years if it spans over years.""" delta = timedelta(days=days) value = '' if delta.days / 365 > 1: value += '%d years' % (delta.days / 365) else: value += '%d days' % delta.days retu...
fe26213d17477602a8c9dc60ed3fe62297df5390
26,590
import re def redditor_info(bot, trigger, match=None): """Show information about the given Redditor""" commanded = re.match(bot.config.core.prefix + 'redditor', trigger) r = praw.Reddit( user_agent=USER_AGENT, client_id='6EiphT6SSQq7FQ', client_secret=None, ) match = match ...
85086299162b28fefb5273b458f8de8927c05d94
26,591
def vcr_config() -> dict: """VCR config that adds a custom before_record_request callback.""" nessie_test_config.cleanup = False return { "before_record_request": before_record_cb, }
8b61e1c825e1470571445e60da8880fa8dbaa14b
26,592
import mimetypes import binascii def main(): # pylint: disable=R0914,R0912,R0915 """The main method""" images = {} materials = {} meshes = {} objects = {} groups = {} texts = {} # Set up our FileDescription fileid = FileId(filename = bpy.path.abspath(bpy.data.filepath)) file_d...
66494f7904c956f67614cb159c346ad3b0e5283b
26,593
import random def get_best(get_fitness, optimalFitness, geneSet, display, show_ion, target, parent_candidates, seed=None, hull=None, simplex=None, verbose=0, hull_bounds=[0, 1], inner_search=True, parent_cap=25, mutation_cap=1000): """ the primary public function of the ...
5ebc9757b4518eabf2968bda9dc6cabd10e5cdb1
26,594
from datetime import datetime def generate_info_endpoint_reply(request): """ This just returns a hardcoded introspection string. """ available_api_versions = {} for ver in optimade_supported_versions: available_api_versions[optimade_supported_versions[ver]] = request['baseurl'] + ver ...
93e0b818c95742d0b7db679e0b3d3ade034cc0e8
26,595
def M(s,o): """ M - s - array of predictions (or simulated) o - array of observations (or targets) """ s,o = np.array(s),np.array(o) return np.nansum( np.abs( np.divide(s-o,o) ))/len(o)
5c53c8b02c88a37204f478d71fb74f2536848af0
26,596
def check_link_exist(destination: str): """Check if link already exists and return otherwise return None""" session: Session = db_session.create_session() result = session.execute( f"SELECT short_link FROM links WHERE destination = '{destination}'", ) # fix possible SQL injection for row i...
57f27da14c4ee551f6eb1e9424cd2b446658ae2f
26,597
from communities.models import Community def smart_404(request): """Returns a 404 message that tries to help the user.""" base_url = settings.HOST_URL not_found = { 'type': None, 'redirect_url': base_url } path_arguments = request.path.split('/')[1:] if path_arguments and ...
62252efb658054b88933109ce7b162cd43962186
26,598
def get_basemap(): """ Use cached copy of basemap from the script's parent folder otherwise download basemap from imgur """ url = "https://i.imgur.com/yIVogZH.png" image = "basemap.png" location = PATH + image print(location) try: basemap = cbook.get_sample_data(location) ...
b1d8267da582206c60006268b5a576cabbe30d28
26,599