content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_user_role_table(table_name='user', id_column_name='id'): """ Create the user-role association table so that it correctly references your own UserMixin subclass. """ return db.Table('fp_user_role', db.Column( 'user_id', db.Integer, ...
8e7570590686e78d2bf7f91ba3b16f14f4c42620
3,638,572
import re def _remove_comments_inline(text): """Removes the comments from the string 'text'.""" if 'auto-ignore' in text: return text if text.lstrip(' ').lstrip('\t').startswith('%'): return '' match = re.search(r'(?<!\\)%', text) if match: return text[:match.end()] + '\n' else: return tex...
463e29e1237a88e91c13a58ffea1b2ccdafd4a1d
3,638,573
def wide_to_tall(df: pd.DataFrame) -> pd.DataFrame: """Convert a wide table to a tall table Args: df (pd.DataFrame): wide table Returns: pd.DataFrame: tall table """ return df.unstack().dropna().reset_index()
50ab71d18f5fb1e4dba9207b71030c7f8ffdbcde
3,638,574
def is_pj_player_plus(value): """ :param value: The value to be checked :type value: Any :return: whether or not the value is a PJ Player+ :rtype: bool """ return isinstance(value, list) and len(value) == 4 or len(value) == 3
1c4e7a7513d746d25f6b3d7964455b0735c988fc
3,638,575
def pd_fuzz_partial_token_sort_ratio(col1, col2): """ Calculate "partial token sort" ratio (`fuzz.partial_token_sort_ratio`) between two text columns. Args: col1 (Spark Column): 1st text column col2 (Spark Column): 2nd text column Returns: Spark Column (IntegerType): result of `fuz...
d650d37d5936751f961260d98210e2d219200fe6
3,638,576
def looterCanReinforce(mine: Game) -> bool: """ Return True if, in the given game, the looter (the attack) can reinforce at this moment, regardless of whether its the first or the second time """ return getLooterReinforcementStatus(mine) != 0
e73fb193cc1c621766900c1f484db90e4e21decb
3,638,577
def _get_normed_sym_np(X_, _eps=DEFAULT_EPS): """ Compute the normalized and symmetrized probability matrix from relative probabilities X_, where X_ is a numpy array Parameters ---------- X_ : 2-d array_like (N, N) asymmetric probabilities. For instance, X_(i, j) = P(i|j) Returns ...
a6f5762a5bf41c83bd017d0661cc069f17bee618
3,638,578
def load_encoding_model(): """Model to encode image as vector of length 4096 using 2nd to last layer of VGG16""" base_model = VGG16(weights='imagenet', include_top=True) encoding_model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output) return enc...
b15f9d9b6d360a71db0fcb7fc0fa83c031f34047
3,638,579
import math def get_geohash_radius_approximation(latitude, longitude, radius, precision, georaptor_flag=False, minlevel=1, maxlevel=12): """ Get the list of geohashed that approximate a circle :param latitude: Float the longitude to get the radius approximation for :param longitude: Float the latitud...
cf8bbc4a8323b796c4f325f4f3ab9f8e3a169fa8
3,638,580
def manage_products(request, category_id, template_name="manage/category/products.html"): """ """ category = Category.objects.get(pk=category_id) inline = products_inline(request, category_id, True) # amount options amount_options = [] for value in (10, 25, 50, 100): amount_options....
4ece15c50e00198c422dbb452622dde938f2a9e6
3,638,581
def random_indices(X, size=None, p=None, sort_indices=True, **kwargs): """ Get indices for a random subset of the data. Parameters ---------- size: int * integer size to sample (required if p=None) p: float * threshold percentage to keep (required if size=None) Returns -...
680be93345ab5e3065a43fda5216a4ca8b986121
3,638,582
def get_facts(F5, uri): """ Issue a GET of the URI specified to the F5 appliance and return the result as facts. If the URI must have a slash as the first character, add it if missing In Ansible 2.2 found name clashing http://stackoverflow.com/questions/40281706/cant-read-custom-fa...
554cc7b9bf35d631c8742614142f5aa2ecaba9b4
3,638,583
from typing import Optional from typing import Sequence def parse_args(args: Optional[Sequence[str]] = None) -> Namespace: """ Parses args and validates the consistency of origin/target using the generator """ parser = ArgumentParser( prog="python -m luh3417.transfer", description...
475318fc9999b7b259a073e53b3b24d5ea46911a
3,638,584
def parse_papers_plus_json(data): """ Function which parses the papers_plus json and returns a pandas dataframe of the results. Solr Field definition shown below: <!-- Citing paper fields: papers, metadata, arxiv_metadata --> <!-- Papers --> <field name="sentencenum" type="pint" indexed="true" ...
44c7a27701e265a841e07f49741f03e4b49d4b95
3,638,585
from pathlib import Path from typing import Optional def get_credential(config_file: Path, credential_key: str = 'api_key') -> Optional[str]: """ Get a single credential from yaml file. Usual case is 'api_key' :param config_file: :param credential_key: :return: """ config = load_credential...
a3e5182c4b2e3fed777f6bd52e144a6d49e4f48f
3,638,586
import functools def authenticate_secondarily(endpoint): """Proper authentication for function views.""" @functools.wraps(endpoint) def wrapper(request: HttpRequest): if not request.user.is_authenticated: try: auth_result = PersonalAPIKeyAuthentication.authenticate(req...
ac7a5b63c2b556e1bb42986db8110a922485b96d
3,638,587
def gather_emails_GUIDs(mailbox, search, folder): """ Download GUID of messages passing search requirements """ mailbox.folder.set(folder) return (email for email in mailbox.uids(search))
d75ecdeaa4f95f9108276f2be236e33934d7de01
3,638,588
def pyrolite_meltsutil_datafolder(subfolder=None): """ Returns the path of the pyrolite-meltsutil data folder. Parameters ----------- subfolder : :class:`str` Subfolder within the pyrolite data folder. Returns ------- :class:`pathlib.Path` """ return get_module_datafold...
e1ae16fff0b2fcd247c57a40e4713eb0ee13f3e7
3,638,589
from typing import List def get_resource_record_set_cloud_formation_dict_list(hosted_zone: ResourceRecordSetList, with_soa: str, client: botocore.client.BaseClient, zone_id: str, ...
c7775a45763f733e2dc2392b5073f1bf18b7177c
3,638,590
def _prepare_line(edges, nodes): """prepare a plotly scatter3d line plot so that a set of disconnected edges can be drawn as a single line. `edges` are values associated with each edge (that get mapped to colors through a colorscale). `nodes` are pairs of (source, target) node indices for each edge...
be95f58a3938b628c89639d3311799eb359c19d2
3,638,592
import getpass def validate_password( password:str ) -> bool: """ Validates the password again a password policy. Args: password ( str, required ): password to verify. Returns: valid ( bool ): True if the password meets validity requirements....
eec09ad86d89184c4f87a8c0710e3af28f874429
3,638,593
from typing import Iterable from typing import List from typing import Dict from typing import Any def build_webhooks( handlers_: Iterable[handlers.WebhookHandler], *, resources: Iterable[references.Resource], name_suffix: str, client_config: reviews.WebhookClientConfig, ...
fc5ca5de1f09c40e08ea8918319b07186af2fe94
3,638,594
def ndo_real(data, n): """mimic of gmx_fio_ndo_real in gromacs""" return [data.unpack_real() for i in range(n)]
875edd4c78e591fcee1b3de30f0ed62a4d0b074d
3,638,595
from typing import Union from typing import Optional def get_field_type(field: Union[syntax.Field, syntax.Command], idl_file: syntax.IDLParsedSpec, idl_file_path: str) -> Optional[Union[syntax.Enum, syntax.Struct, syntax.Type]]: """Resolve and get field type of a field from the IDL file.""" ...
19445d7a142b940ff3cd0c445e716c070eeac489
3,638,596
def get_status(): """get the node status and return data""" return data({})
0314331d249cebfeb63941961793fe9a72e0c329
3,638,598
import tokenize def read_orc(path, columns=None, storage_options=None, **kwargs): """Read cudf dataframe from ORC file(s). Note that this function is mostly borrowed from upstream Dask. Parameters ---------- path: str or list(str) Location of file(s), which can be a full URL with protoco...
2f26a088cd849fc21c171767a0db276844341b11
3,638,599
import torch def get_bernoulli_sample(probs): """Conduct Bernoulli sampling according to a specific probability distribution. Args: prob: (torch.Tensor) A tensor in which each element denotes a probability of 1 in a Bernoulli distribution. Returns: A Tensor of binary samp...
14c45741d47f5eaff24893471425ddd4de7e2e4b
3,638,601
def angle_load(root, ext='.angle'): """ Load information from the :ref:`Output_angle` file previously created by :func:`.angle_save`. Args: root (str): root name for the file to be loaded ext (str, optional): default ".angle" - extension for the file to be loaded: name = root + ext Ret...
f1218dc2dc1a6c5ef1c56689111086137b04a786
3,638,602
import pickle def load_newsdata_and_labels(): """ Read newsdata, return list of documents, each line in list is one document as string. And list of labels, each line in list is one-hot-encoded class """ # read newsdata which is pickled def read_pickle_one_by_one(pickle_file): with ope...
3838cbd42e5bab898fc969ebe9b4f326c736c773
3,638,605
def CollectUniqueByOrderOfAppearance(dataset:list): """ This method collect all unique in order of appearance and return it as list. :param dataset:list: dataset list """ try: seen = set() seen_add = seen.add return [x for x in dataset if not (x in seen or seen_add(x))] ...
e252d064bf0c525ec1c1781ca6dc915dbc9d46f0
3,638,606
async def list_slot_set_actions(current_user: User = Depends(Authentication.get_current_user_and_bot)): """ Returns list of slot set actions for bot. """ actions = mongo_processor.list_slot_set_actions(current_user.get_bot()) return Response(data=actions)
f52f1e996b2be38a0e175ca6bfcbfd694dc79240
3,638,607
from PyQt5 import QtGui, QtWidgets, QtCore def openfile_dialog(file_types="All files (*)", multiple_files=False, file_path='.', caption="Select a file..."): """ Opens a File dialog which is used in open_file() function This function uses pyQt5. Parameters ---------- file_t...
b96112c5af25350b49bc086820bcea32c228d3c8
3,638,608
def getBlocks(bal: "BKAlignedLayout"): """ Finds all blocks of a given layout. :param bal The layout of which the blocks shall be found :return: The blocks of the given layout """ blocks = defaultdict(list) for layer in bal.layeredGraph.layers: for node in layer: root =...
6f40dc209b72747f6960d474d54e1ffedd2fa9a1
3,638,609
def read_mcmc(path_to_file): """ Reads mcmc chain from file Parameters ---------- path_to_file: string Path to mcmc chain file Returns --------- emcee_table: pandas dataframe Dataframe of mcmc chain values with NANs removed """ colnames = ['mhalo_c','mstellar_c'...
f8d0cdd5ea5a7274e81992722db4df29d7664e43
3,638,610
def rotzV(x, theta): """Roate a coordinate in the local z frame""" M = [[np.cos(theta), -np.sin(theta), 0], \ [np.sin(theta), np.cos(theta), 0], [0, 0, 1]] return np.dot(M, x)
43e4f7a8f93fb2b237da1f6ac3f699bf41e38e0a
3,638,611
import fcntl def has_flock(fd): """ Checks if fd has flock over it True if it is, False otherwise :param fd: :return: :rtype: bool """ try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return True else: return False
9ae997d06a12d73a659958bc2f0467ebdf0142b7
3,638,612
def ExtractCodeBySystem( codable_concept, system): """Extract code in codable_concept.""" for coding in codable_concept.coding: if (coding.HasField('system') and coding.HasField('code') and coding.system.value == system): return coding.code.value return None
e672cb3d2c1d8d65e49d00539cdecf6ee03d1143
3,638,613
def add_item(data, type): """ Add an item to the data in ranked order This function handles the process of adding an item to the list. It first requests the item from the console. Items are nothing more than a line of text typed in. Next, this kicks off a type of binary search to find the proper l...
0662fb19725e0985043d7ea75bad4c5fa55d921f
3,638,614
def get_full_test_names(testargs, machine, compiler): ############################################################################### """ Return full test names in the form: TESTCASE.GRID.COMPSET.MACHINE_COMPILER.TESTMODS Testmods are optional Testargs can be categories or test names and support th...
05fd19a412172195c2365b0c002c442ceabf7946
3,638,617
def record_or_not(record_mode, line, start_block, end_block): """ """ if not record_mode: if start_block in line: record_mode = True elif end_block in line: record_mode = False return record_mode
2b3952ab7fa3aa23ccbd712dee0aa06083b7b5f5
3,638,618
def compute_angle_stats(vec_mat, unit='deg'): """ Get mean of angles the successif vectors used in the reconstruction. return mean an variance of the angles. """ angles = [] for i in range(vec_mat.shape[1] - 1): aux = 0 dot_prod = np.dot(vec_mat[i] / np.linalg.norm(vec_mat[i]...
d1701a3eca12e41b05a38433a7561f811aceb02c
3,638,619
def id_test_data(value): """generate id""" return f"action={value.action_name} return={value.return_code}"
47649b7302ef2f3ad046fc1c7b3fc18da2687921
3,638,620
def kneeJointCenter(frame, hip_JC, delta, vsk=None): """Calculate the knee joint center and axis. Takes in a dictionary of marker names to x, y, z positions, the hip axis and pelvis axis. Calculates the knee joint axis and returns the knee origin and axis. Markers used: RTHI, LTHI, RKNE, LKNE, hip...
1f4ab38ef90c79c964587551e05ce32ccf482e53
3,638,621
def uniform(low: float = 0.0, high: float = 1.0, size: tp.Optional[SIZE_TYPE] = None): """ Draw samples from a uniform distribution. """ if high < low: raise ValueError("high must not be less than low") u = _draw_and_reshape(size, rand) return u * (high - low) +...
da79a086a9c129a88e45c11407ca0d3993104f1a
3,638,622
import math def toInt(): """This built-in function casts the current value to Int and returns the result. """ def transform_function(current_value: object, record: dict, complete_transform_schema: dict, custom_variables: dict): value_to_return = None if current...
0f58cb6c85ca4015696c7fef2d9378c0466c2422
3,638,623
import json def public_upload(request): """Public form to upload missing images :param request: current user request :type request: django.http.request :return: rendered response :rtype: HttpResponse """ upload_success = False if request.method == "POST": document = Document.o...
857b558566a52dc2b192efc3b1441a0da11a649c
3,638,624
import pathlib import re def load_classes(fstem): """Load all classes from a python file.""" all_classes = [] header = [] forward_refs = [] class_text = None done_header = False fname = pathlib.Path('trestle/oscal/tmp') / (fstem + '.py') with open(fname, 'r', encoding='utf8') as inf...
da4baaed8d849b90c51200b778bdde9a47d58cc4
3,638,625
def build_optimizer(name, lr=0.001, **kwargs): """Get an optimizer for TensorFlow high-level API Estimator. Args: name (str): Optimizer name. Note, to use 'Momentum', should specify lr (float): Learning rate. kwargs (dictionary): Optimizer arguments. Returns: tf.train.Optim...
c04c9348f26fdf25951f362a693cb70765133756
3,638,627
import yaml def generate_pruning_config(model_name, sparsity, begin_step=0, end_step=-1, schedule='ConstantSparsity', granularity='BlockSparsity', res...
42f566ce574b53d6effafcec18984c201fba7f92
3,638,628
def collect_FR_dev(stim_array,stim_dt,sim_dt,spikemon,n,return_spikes=False): """ get all firing rates for a given spikemon stim_array: array of stimulation time/strengths, e.g., [0,0,0,0,1,0,0,0,1,0,0] stim_dt: time interval of stimulation sim_dt: time interval of simulation spikemon_t: ti...
05914a68085112e0b1b4353dbd6434fb3e59c7c8
3,638,629
import json def assertDict(s): """ Assert that the input is a dictionary. """ if isinstance(s,str): try: s = json.loads(s) except: raise AssertionError('String "{}" cannot be json-decoded.'.format(s)) if not isinstance(s,dict): raise AssertionError('Variable "{}" is not a dictionary.'.forma...
302defb4e1eecc9a6171cda0401947e3251be585
3,638,630
import math def _consolidate_subdivide_geometry(geometry, max_query_area_size): """ Consolidate and subdivide some geometry. Consolidate a geometry into a convex hull, then subdivide it into smaller sub-polygons if its area exceeds max size (in geometry's units). Parameters ---------- ge...
32fbafcf3066cc73c022fc1482030d35387107c2
3,638,631
import ast from typing import Tuple from typing import List from typing import Any def get_function_args(node: ast.FunctionDef) -> Tuple[List[Any], List[Any]]: """ This functon will process function definition and will extract all arguments used by a given function and return all optional and non-optional...
a4fe9dccedd5684050a7d5e7949e384dd4021035
3,638,633
def svn_client_copy3(*args): """ svn_client_copy3(svn_commit_info_t commit_info_p, char src_path, svn_opt_revision_t src_revision, char dst_path, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_copy3, args)
336aaec7d6c2a44f22d6b1164316f16b4fd5f53f
3,638,634
import json import copy def delete(server = None, keys = None): """ Marks an entity or entities as deleted on the server. Until an entity is permanently deleted (an administrative operation, not available through the RESTful API), it can still be accessed, but will not turn up in search results. ...
b3662ba85b1aacfca6034da5d5e198a5ffada2fa
3,638,635
import collections import csv def ParseMemCsv(f): """Compute summary stats for memory. vm5_peak_kib -> max(vm_peak_kib) # over 5 second intervals. Since it uses the kernel, it's accurate except for takes that spike in their last 4 seconds. vm5_mean_kib -> mean(vm_size_kib) # over 5 second intervals "...
5d10a0d0ac5ab3d3e99ff5fd4c9ca6cd0b74656b
3,638,636
def index_containing_substring(list_str, substring): """For a given list of strings finds the index of the element that contains the substring. Parameters ---------- list_str: list of strings substring: substring Returns ------- index: containing the substring or -1 """ ...
2816899bc56f6b2c305192b23685d3e803b420df
3,638,637
import pycountry import gettext import six def _localized_country_list_inner(locale): """ Inner function supporting :func:`localized_country_list`. """ if locale == 'en': countries = [(country.name, country.alpha_2) for country in pycountry.countries] else: pycountry_locale = gette...
c67b107d10b8bc2426de39f11c30e886b5fc2894
3,638,638
def ingest_questions(questions: dict, assignment: Assignment): """ questions: [ { sequence: int questions: [ { q: str // what is 2*2 a: str // 4 }, ] }, ... ] response = { rejected: [ ... ] ignored: [ ... ...
d72370bcaa5cf1f5017eda827cca6dd011ac36d0
3,638,639
from datetime import datetime def render_book_template(book_id): """ Find a specific book in the database. Locate the associated reviews (sorted by score and date). Create the purchase url. Check whether the user has saved the book to their wishlist. """ # Find the book document in the dat...
d30b30b79b102b1c08404bc00c69b1f22ccebc6a
3,638,640
def iatan2(y,x): """One coordinate must be zero""" if x == 0: return 90 if y > 0 else -90 else: return 0 if x > 0 else 180
a0b18b61d7ffadf864a94299bc4a3a0aacd7c65a
3,638,641
import torch def fuse_bn_sequential(model): """ This function takes a sequential block and fuses the batch normalization with convolution :param model: nn.Sequential. Source resnet model :return: nn.Sequential. Converted block """ if not isinstance(model, torch.nn.Sequential): return m...
6d31cd2cd73e8dc91098b7f9cc7f70ce3b81a3b9
3,638,642
def get_baseconf_settings( baseconf_settings_filename = None ): """ Returns the basic configuration settings as a parameter structure. :param baseconf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default sett...
0b0b829f4923072431b8e73c7fd70e732f17dc30
3,638,643
def subtract_background(image, background_image): """Subtracts background image from a specified image. Returns ------- bs_image : np.ndarray of type np.int | shape = [image.shape] Background-subtracted image. """ image = image.copy().astype(np.int) background = background_image.cop...
c136f78c1f355c2031ef60ca17fb0bd6fc63c94e
3,638,645
import math def batch_genomes(genomes, num_batches, order): """ Populates 2D numpy array with len(rows)==num_batches in {order} major order. Using col is for when you know you are using X number of nodes, and want- to evenly distribute genomes across each node Use row when you want to fill each no...
00fea150ea20ae886fd72f099a1c0bd4216ba987
3,638,646
def single_gate_params(gate, params=None): """Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: a tuple of U gate parameters (theta, phi, lam) """ if gate == 'U' or gate == 'u3': ...
153459403639103cdfa9502a26797e9c536ba112
3,638,647
import time def runTests(data, targets, pipeline, parameters): """ Perform grid search with specified pipeline and parameters on data training set with targets as labels Evaluate performance based on precision and print parameters for best estimator grid search o...
122d1330444dd72aa064cd263cb7f405bf2bf9ba
3,638,650
def isMultipleTagsInput(item): """ Returns True if the argument datatype is not a column or a table, and if it allows lists and if it has no permitted value. This function is used to check whether the argument values have to be delimited by the null character (returns True) or not. :param item: Tab...
f7710902e27962fc8df55bc75be2d5d404144aeb
3,638,651
def remove_url(url: str = Form(...)): """ Remove url from the url json file :param url: api url in the format: http://ip:port/ :return: ApiResponse """ try: payload = helpers.parse_json(url_config_path) except Exception as e: return ApiResponse(success=False, ...
c7c218926c2992df19b3988987fca8cf2bbff3d1
3,638,653
def load_CSVdata(messages_filepath, categories_filepath): """ Load and merge datasets messages and categories Inputs: Path to the CSV file containing messages Path to the CSV file containing categories Output: dataframe with merged data containing messages and categories ...
e216c09ca403545fbc1152a25e966efeb4baeefc
3,638,654
def accept_invite(payload, user): """ Accepts an invite args: payload, user ret: response """ try: invite = Invites.get(payload['invite'])[0] except: return Message( Codes.NOT_FOUND, { 'message': 'There isn\'t any active invite with the given id.' } ...
bff423eeec7f7f527771934de0f32ede0f528948
3,638,655
from typing import Tuple from typing import Dict from typing import List import re def clean_status_output( input: str, ) -> Tuple[bool, Dict[str, str], List[Dict[str, str]]]: # example input """ # Health check: # - dns: rename /etc/resolv.conf /etc/resolv.pre-tailscale-backup.conf: device or ...
bbf100514373595948b0691dff857deb5772f019
3,638,656
def test_tensor_method_mul(): """test_tensor_method_mul""" class Net(Cell): def __init__(self): super(Net, self).__init__() self.sub = P.Sub() def construct(self, x, y): out = x * (-y) return out.transpose() net = Net() x = ms.Tensor(np...
89866ebd9311e0bac0e3324b01545507b986751f
3,638,657
def _get_top_artists(session: Session, limit=100): """Gets the top artists by follows of all of Audius""" top_artists = ( session.query(User) .select_from(AggregateUser) .join(User, User.user_id == AggregateUser.user_id) .filter(AggregateUser.track_count > 0, User.is_current) ...
ae6a45e7190995fc35daf62236e73c4bd5c6235f
3,638,658
def _get_other_locations(): """Returns all locations except convention venues.""" if 'all' not in location_cache.keys(): conv_venue = LocationType.objects.get(name='Convention venue') location_cache['all'] = Location.objects.exclude(loc_type=conv_venue) return location_cache['all']
a34bf432529a31bc013988c394230e55b01ac21b
3,638,660
import torch def _check_cuda_version(): """ Make sure that CUDA versions match between the pytorch install and torchvision install """ if not _HAS_OPS: return -1 _version = torch.ops.torchvision._cuda_version() if _version != -1 and torch.version.cuda is not None: tv_version = ...
d86e209d10514060f0c15bff9ea28df6b2054480
3,638,661
def largest(layer,field): """largest(layer,field) Returns the largest area significant class in the study area. """ theitems = [] rows = arcpy.SearchCursor(layer) for row in rows: theitems.append(row.getValue(field)) del rows theitems.sort() max1= theitems[-1] return ma...
ff6433a5fef48550e902317384dec746136063dc
3,638,662
import asyncio import random async def double_up(ctx): """ 「ダブルアップチャンス!」を開始します。 """ depth = 1 # 現在の階層 HOLE = "\N{HOLE}\N{VARIATION SELECTOR-16}" LEFT_ARROW = "\N{LEFTWARDS BLACK ARROW}\N{VARIATION SELECTOR-16}" RIGHT_ARROW = "\N{BLACK RIGHTWARDS ARROW}\N{VARIATION SELECTOR-16}" TOP_AR...
3ec1394d681fcb0e626e98b11bd815dddbe64254
3,638,663
def read_version(file_contents): """Read the project setting from pyproject.toml.""" data = tomlkit.loads(file_contents) details = data["tool"]["poetry"] return details["version"]
7255c199463437765d21658f792a54049bbb45ee
3,638,664
from datetime import datetime def schedule_time(check_start_time, check_end_time, time_duaration=7) -> dict: """ Returns dictionary of earliest available time within the next week """ all_busy_events = get_busy_events() for d in range(1,time_duaration): # Increment by one day throughout the week ...
858387e8d07634df7a143b3ee500e648ed54abd6
3,638,665
import array def _to_array(value): """When `value` is a plain Python sequence, return it as a NumPy array.""" if not hasattr(value, 'shape') and hasattr(value, '__len__'): return array(value) else: return value
3bf185f34c51dc2042bdb05138b0febd9e89b421
3,638,666
def dict_pix_to_deg(input_dict, changeN): """Convert pix to deg for a given dictionary format, changeN is 1 or 2, to let the function works for the first or both elements of the tuple""" dict_deg = {} for key, values in input_dict.items(): new_display = [] for display in values: ...
03c49e113c8805c4d675899f3c61e3ae00bd7681
3,638,667
def remove_container_name_from_blob_path(blob_path, container_name): """ Get the bit of the filepath after the container name. """ # container name will often be part of filepath - we want # the blob name to be the bit after that if not container_name in blob_path: return blob_path b...
e02807abebdf3a193efcabee1dda3f733a780dd5
3,638,668
from typing import Dict from typing import List def _complex_ar_from_dict(dic: Dict[str, List]) -> np.ndarray: """Construct complex array from dictionary of real and imaginary parts""" out = np.array(dic["real"], dtype=complex) out.imag = np.array(dic["imag"], dtype=float) return out
a3938619f84c2dcbec5c9ac90c0064ea380346c4
3,638,669
def endpoint(url_pattern, method="GET"): """ :param url_pattern: :param method: :param item: :return: """ def wrapped_func(f): @wraps(f) def inner_func(self, *args, **kwargs): """ :param self: :param args: :param kwargs: ...
23b68a1440e96eac27926f2a37d96cb74a568734
3,638,670
def elastic_transform( image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, random_state=None, approximate=False, ): """Elastic deformation of images as described in [Simard2003]_ (with modifications). Based on https://gist.github...
e60754cc898d83051164180b1d07ac0e4c688946
3,638,671
import re from orangecontrib.xoppy.util.xoppy_xraylib_util import f0_xop def crystal_atnum(list_AtomicName, unique_AtomicName, unique_Zatom,list_fraction, f0coeffs): """ To get the atom and fractional factor in diffierent sites list_AtomicName: list of all atoms in the crystal unique_AtomicName: lis...
f9805890971e1c2e6696084fad5f8b9071999046
3,638,672
def integrate(name, var): """ given filename and var, generate profile """ d = vtk.vtkExodusIIReader() d.SetFileName(name) d.UpdateInformation() d.SetPointResultArrayStatus(var,1) d.Update() blocks = d.GetOutput().GetNumberOfBlocks() data = d.GetOutput() # range...
116993d18c4430f6ce0e7dacba8b73ef3a03f689
3,638,673
def mediate(timer: TimerBase, decimals: int | None) -> int: """If the start function doesn't have decimals defined, then use the decimals value defined when the Timer() was initiated.""" return timer.decimals if decimals is None else validate_and_normalise(decimals)
030ec62071bc4c2bc41ae30c5eb8212b36e0359a
3,638,674
def calculate_n_inputs(inputs, config_dict): """ Calculate the number of inputs for a particular model. """ input_size = 0 for input_name in inputs: if input_name == 'action': input_size += config_dict['prior_args']['n_variables'] elif input_name == 'state': i...
78d750ff4744d872d696dcb454933c868b0ba41e
3,638,675
def coords(lat: float, lon: float, alt: float = None ) -> str: """Turn longitude, latitude into a printable string.""" txt = "%2.4f%s" % (abs(lat), "N" if lat>0 else "S") txt += " %2.4f%s" % (abs(lon), "E" if lon>0 else "W") if alt: txt += " %2.0fm" % alt return txt
c5768e03c55d5f567695056d78108812014b9ef4
3,638,678
def chromosome_to_smiles(): """Wrapper function for simplicity.""" def sc2smi(chromosome): """Generate a SMILES string from a list of SMILES characters. To be customized.""" silyl = "([Si]([C])([C])([C]))" core = chromosome[0] phosphine_1 = ( "(P(" + chromosome[1] + ...
793995484c46295977f1d312c4fa11f69bca6c84
3,638,679
def softmax_edges(graph, feat): """Apply batch-wise graph-level softmax over all the values of edge field :attr:`feat` in :attr:`graph`. Parameters ---------- graph : DGLGraph The graph. feat : str The feature field. Returns ------- tensor The tensor obtaine...
f5dafccca3c487756deeb37f534ef178cf1de75f
3,638,680
def command_result_processor_parameter_required(command_line_parameter): """ Command result message processor if a parameter stays unsatisfied. Parameters ---------- command_line_parameter : ``CommandLineParameter`` Respective command parameter. Returns ------- message ...
fed1b7af60018cb5638e021365ae754477b7a241
3,638,681
def randdirichlet(a): """ Python implementation of randdirichlet.m using randomgamma fucnction :param a: vector of weights (shape parameters to the gamma distribution) """ try: x = rand.randomgamma(a) except ValueError: a[a == 0] += 1e-16 x = rand.randomgamma(a) x /= x...
c825fb81c07337231f49437a2bea7ddd5a40234f
3,638,682
def home(request): """ This is the home page request """ return render(request, 'generator/home.html')
ad8b69871d484c16583752d029fec2970084e698
3,638,683
def print_insn_mnem(ea): """ Get instruction mnemonics @param ea: linear address of instruction @return: "" - no instruction at the specified location @note: this function may not return exactly the same mnemonics as you see on the screen. """ res = ida_ua.ua_mnem(ea) if not res:...
4c60e853356217c2fbfdd21047429c729b57f10f
3,638,684
def setdim(P, dim=None): """ Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is ...
610138c1d1a13112d35583d758cac43c1e296d18
3,638,685
def extract_file_from_zip(zipfile, filename): """ Returns the compressed file `filename` from `zipfile`. """ raise NotImplementedError() return None
dc7b1e5a196a019d1fd2274155e0404b03b09702
3,638,686
import torch def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None): """ Args: cls_scores: (N, num_class) box_preds: (N, 7 + C) nms_config: score_thresh: Returns: """ pred_scores, pred_labels, pred_boxes = [], [], [] for k in range(cls_sco...
a0451c3769b4415e7e7d184d43f6b8f121b651b1
3,638,688