content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any from typing import List def Json(v: Any, fname: str, lazy: List[Any]): """ Default JSON encoder using ``json.dumps``. This version encodes ``None`` as json null value. """ return text_escape(dumps(v))
036252d6970802c7fea2b819184e1281469e7b08
3,626,410
def sem_id_get(obs_id): """ Retrieves all the sem_ids associated with an observer http://vm-webtools.keck.hawaii.edu:50001/v0/semesterIds/?obs_id=2003 :param obs_id: observer id :type obs_id: int :rtype: List[str] """ # authenticate, # use a master id in check_obs_id or check ==...
f1f11f827fa27f807396acd4714aa31d9c4e0de9
3,626,411
def welcome(): """Print a welome message.""" print "Python %s %s, %s" % (NAME, VERSION, BUILDDATE) print "A %s" % DESCRIPTION print return()
a3b624af86aa861b6d7d529ce8d08ad33a4a4dae
3,626,412
def _update_improper_axes( n, ax, axes, atomcoords, groups, rtol, atol, normalize=False # found axes ): """Update axes with ax and return it. Helper function for _get_improper_axes. """ if normalize: norm = np.linalg.norm(ax) if np.isclose(norm, 0.0, rtol=rtol, atol=atol): ...
ae623a8c17110ecde23391ef709be76904d76b69
3,626,413
def resolver_for(domain, mname): """Return a resolver object whose nameservers are obtained by asking the SOA MNAME (master name) for its addresses and listing the remaining NS addresses after that. Master is assumed to be most up-to-date, but may not always be reachable.""" addresses = [] maybe...
1b3dad4fec5a1c591401ff6b709bc05ce09e7411
3,626,414
def div(client, symbol, timeframe="6m", col1="open", col2="close"): """This will return a dataframe of Vector Arithmetic Div for the given symbol across the given timeframe Args: client (pyEX.Client); Client symbol (string); Ticker timeframe (string); timeframe to use, for pyEX....
68da946181e39c8b2ec03fb82ee63da1c4804512
3,626,415
import itertools def create_possible_expected_messages(message_template, expected_types): """ Some error messages contain dictionaries with error types. Dictionaries in Python are unordered so it makes testing unpredictable. This function takes in a message template and a list of types and returns ...
674dec990e0786d3e313a9b8deec72e37588d8eb
3,626,416
def chkSort(array): """Make sure sort actually did its job""" for i in range(0, len(array)-2): if array[i] > array[i+1]: print("{} is not greater than {} for indices=({},{})").format(array[i+1], array[i], i, i+1) return False return True
759c0b64fcf41121433264abbb80203534355e98
3,626,417
import json def fetch_dss_files(uuid): """ Initiate checking out a file for download from the HCA data store (DSS) parameters: - name: uuid in: path type: string description: UUID of the file to be checked out - name: fileName in: query ty...
c396b6b530a905eaa1df9f0b32289776edf334c9
3,626,418
from typing import List from typing import Optional from typing import Tuple def eval_final_hand(cards: List[Card]) -> Optional[Tuple[str, PokerHand, int]]: """ Turns a list of 7 cards into a string representation of the best hand possible with those 7 """ cards.sort(reverse=True) # Get valid five card c...
05161fb9e806dd6ab172ba4e12cbd924b8eb19f0
3,626,420
from typing import Tuple def grab_color() -> Tuple[Tuple[int, int, int], Tuple[int, int]]: """ returns a list with a tuple containing the RGB value of the most present color around the mouse and the position at the time of measurement """ pos = mouse.get_position() m = 2 rect = (pos[0] - ...
d133ff7764e64509a2da04d80d1725468c861593
3,626,421
import numpy def get_dihedral_angle1(p0,p1,p2,p3): """http://stackoverflow.com/q/20305272/1128289""" p = [p0, p1, p2, p3] b = p[:-1] - p[1:] b[0] *= -1 v = numpy.array( [ v - (v.dot(b[1])/b[1].dot(b[1])) * b[1] for v in [b[0], b[2]] ] ) # Normalize vectors v /= numpy.sqrt(np.einsum('...i,....
9762342b6e1f0f6413e20569d96aadeeb0766374
3,626,422
def calc_delta_lampams2( multipanel, constraints, delta_lampams, pdl, n_plies_to_optimise): """ calulates all ply partial lamination parameters in a multipanel structure that correspond to a specific ply drop layout INPUTS - multipanel: multipanel structure - delta_lampams: all ply par...
d3dd52bfcba94fe4f06d7c9b1aad25d827c48842
3,626,423
def merge_user_data(spark, table_type, table_num, start_num=0): """ :param table_type: 【str】 'click' or 'top' or 'play' :return: 【dataframe】 返回每种行为数据所有表的merge表 """ spark.sql("use {}".format(user_pre_db)) if start_num == 0: ret = None else: # 本来想运行完,删除掉改过名的表merge_{}_{},但在保存前删除...
48686485ea7f8e2aea790062d4cf0a5ca54142a2
3,626,424
from typing import Counter def gridToList(box): """ :summary: Reads text fields into a list for racksorter module :param QGroupBox box: group box to read the grid from :rtype: list :return: racksorter module-ready list of the permutation """ l = [] layout = box.layout() positions ...
a91dbe0316502f58d4144b22ddacdb26cdf215e7
3,626,426
def get_unavailable_agents(day): """Determine agents with no availability for a given day.""" day_number = day.weekday() unavailable = set() for handle in df_agents.index: if len(df_agents.loc[handle, "slot_ranges"][day_number]) == 0: unavailable.add(handle) print(f"\nUnavailab...
453ac16b4335201925ebad5fa48c915e8f92f2c5
3,626,427
def compare_descriptor_types(a, b): """Compare two metric types to sort them in order.""" # pylint: disable=invalid-name a_root = a['type'][len(CUSTOM_PREFIX):] b_root = b['type'][len(CUSTOM_PREFIX):] return (-1 if a_root < b_root else 0 if a_root == b_root else 1)
b34288136ce83c16671df03fd68d9694b2ee0228
3,626,428
def get_image(image) -> Image.Image: """ Gives back the given image as a PIL.Image.Image instance Args: image: the given image, it can be a filepath (str, bytes or Path), an URL (which will be downloaded), a BytesIO or a PIL.Image.Image instance Returns: A PIL.Image.Image insta...
3ac8c6606e8ea15c49860c0714bc73565d50a73f
3,626,429
def get_worksheet(ts: ThoughtSpot, connection_guid: str, worksheet_guid: str) -> Worksheet: """ :param ts: The connection to ThoughtSpot for API calls. :param connection_guid: GUID for the connection with the table to map to (not always the old connection) :param worksheet_guid: GUID for the worksheet t...
4ce5b567317f744444f6478d4365a1fd84dcd792
3,626,430
def run_grover_search(number_of_qubits, oracle, oracle_args): """ Uses Grover's quantum search to find the single answer to a problem with high probability. Parameters: number_of_qubits (int): The number of qubits that the oracle expects (the number of qubits that the answer will co...
cc47f645bbd6c9a12acf4698060fde3e76d92097
3,626,431
def compute_epsilon(target_delta, steps, noise_multiplier, batch_size, dataset_size): """Computes epsilon privacy value for given hyperparameters.""" if noise_multiplier == 0.0: return float("inf") orders = [1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64)) sampling_probability = batch...
02a52d87f36d04481efdb70c81b1bd2760c77732
3,626,432
import re def findCisIndexes(cisSplits, protSeq, overlapFlag, maxDistance): """ Called by cisOrigins(), this function returns the location data of where different pairs of cisSplits (which combine to form a given peptide) exist in a protein sequence. The output data structure is a series of embedded l...
013b1776225b6b294e9489280734730a6411d502
3,626,433
def export_selected_games_pgn_no_comments(grid, filename): """Export selected records in PGN export format excluding comments. If any records are bookmarked just the bookmarked records are exported, otherwise all records selected for display in the grid are exported. """ if filename is None: ...
74894757ac92612aaad3d14eea822e1c6717488f
3,626,434
def add_dimensions(G, naming_convension: NamingConvension = None) -> list: """ Walks graph setting all edge names and dimensions """ if naming_convension is None: naming_convension = DefaultNamingConvension(G) for edge in G.edges(): edge.params = None steps = [] indexes = {'inpu...
c369bb2b8452224b9e91b1d57315d8b2662196df
3,626,435
from datetime import datetime def add_day(date: str, format_='%Y-%m-%d', to_str=False, **kwargs) -> datetime: """一个日期加多少天或者时间 :param date: 一个正确的日期 :param format_: 日期格式化 :param to_str: 是否打印字符串 :param kwargs: 可以填写 :days=xx,seconds=xx,microseconds=xx,milliseconds=xx,minutes=xx,hours=xx,weeks=xx :...
b8810e177347fb6a0d28e454c4f4d37b98354f89
3,626,436
def fetch_swiss_exchanges(session, target_datetime, logger): """Returns the total exchanges of Switzerland with its neighboring countries.""" swiss_transmissions = {} for exchange_key in ['AT', 'DE', 'IT', 'FR']: exchanges = ENTSOE.fetch_exchange(zone_key1='CH', ...
4441215d4c4f1b9e162ef5dedec156d88783308d
3,626,437
import json def delete_volumes(repository_name, branch_name): """ Trigger lambda function that deletes EBS volumes. :param repository_name: Full repository name. :param branch_name: Branch name that is deleted. :return: Number of EBS volumes that are deleted successfully, number of EBS volumes tha...
939434708567cba4c20ac30595220c7da5299a9e
3,626,438
from albumy.models import User def load_user(user_id): """根据session中的user_id获取User对象""" user = User.query.get(int(user_id)) return user
925c573e747d5a5fa388d2368c79e81730ee396d
3,626,439
def load_saved_recipes(filename): """ Internal method for reading contens of given file. """ contents = [] try: # Read file line by line, recipe by recipe with open(filename, 'r') as recipes_file: contents = recipes_file.readlines() return contents ...
60cf9ace8cd3cbcc40aae6fa5c1d2def50bf95b9
3,626,440
def get_range(arr, refarea): """ determine plot scale range """ auto_crange: float = 99.8 refvalue = np.nanmean(arr[refarea[0]:refarea[1], refarea[2]:refarea[3]]) # reference values if str(refvalue) == 'nan': refvalue = 0 dmin_auto = np.nanpercentile((tscuml[-1, :, :]), 100 - auto_cr...
9807359eb6cf37f445a1550069e214b999a010a1
3,626,441
def label_repo( source: str = typer.Argument(CWD), input: str = typer.Option('', '-i', '--input'), output: str = typer.Option('', '-o', '--output'), template: str = typer.Option('', '-t', '--template'), ) -> int: """ Labels the local data (no template handling yet). """ repo_root = input...
e5dc00c9b5bb41e031158d37737cd3e1679e4e48
3,626,442
def get_longest_word_trie_ds(words: list[str]) -> str: """Returns the longest word character composable from other words in input array Args: words: array of strings words representing an English Dictionary Returns: the longest word in words that can be built one character at a time by ...
043b56db322c6b4eedbac0d9c237ba996cbdb03c
3,626,443
from typing import Sequence from typing import Callable from typing import Any async def async_combine_middlewares( middlewares: Sequence[Middleware], web3: 'Web3', provider_request_fn: Callable[[RPCEndpoint, Any], Any], ) -> Callable[..., RPCResponse]: """ Returns a callable function which will c...
e87eae3e97f12d2eec9a83849e7152a5b5d221bf
3,626,445
import glob def _create_image(dirs, class_info, params, count, output_dir): """Creates a dataset image at the desired directory. Returns bbox cache for creating annotations.""" # open the map and create a copy of it as a new image background_image = Image.open(choice(glob.glob(dirs['maps']+'.png'))) n...
c5a06ff125d47f931e7a82ad1a4042aa735d64ba
3,626,448
def compute_predictions_for_a_single_pipeline(p,df_X): """ This function finds predictions for a single pipeline (it is assumed that this is already the best model) Parameters ---------- p : prediction_class object df_X: DataFrame Input dataframe with possible all the original attr...
9eda59f867dffa9d559774e68d314bd7698942f1
3,626,449
from typing import Sequence from re import T from typing import Callable def min_edit_distance( source: Sequence[T], target: Sequence[T], ins_cost: Callable[..., int] = lambda _x: 1, del_cost: Callable[..., int] = lambda _x: 1, sub_cost: Callable[..., int] = lambda x, y: 0 if x == y el...
d2e36275d2de9c27a1d910371059cabed54b52a7
3,626,450
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Home Connect light.""" def get_entities(): """Get a list of entities.""" entities = [] hc_api = hass.data[DOMAIN][config_entry.entry_id] for device_dict in hc_api.devices: entity_dicts...
94c6473917ef31b2ca15ef70c2e783bd5cb2e565
3,626,451
import torch def combine(batch, i): """ Combines the vectors for a specific type of sequence and removes extra padding Args: batch: list i: int indicates the type of sequence (4, 5, 6) --> (passage, query, qa_answer) Returns: vectors: 2d long tensor [bs x max_len] """ vectors = torch.cat([exampl...
28ad3d16e89e0b3d2e3ef7cb966f577e7f1d1037
3,626,452
def GetNetworkConfig(has_external_ip, network): """Helper method to create a network config.""" network_interfaces = { 'network': network } if has_external_ip: network_interfaces['accessConfigs'] = [{ 'name': 'external-nat', 'type': 'ONE_TO_ONE_NAT' }] return network_interfaces
c0ee213c5c289fb2f6eb4b34fc18028233a1d162
3,626,453
import traceback def base_federated_role( construct, resource_name: str, federated_resource: str, assume_role_action: str, conditions: dict, actions: list, resources: list, ): """ Function that generates an IAM Federated Role with a Policy. :param construct: Custom construct th...
ea3c83d215ae5064c889f12ac3cacdef388d312d
3,626,454
from operator import inv def zeros(a): """ Return the number of cleared bits in the sequence. >>> assert zeros([0, 0]) == 2 >>> assert zeros([0, 1]) == 1 >>> assert zeros([1, 0]) == 1 >>> assert zeros([1, 1]) == 0 >>> assert zeros([1, 1, 1, 0, 1]) == 1 >>> assert zeros([0, 1, 0, 0, 0]...
76f041390dfe43bcc583e39fc7a3e3d761f87c25
3,626,455
from datetime import datetime import requests def test_commit_in_last_year_no(monkeypatch): """ 11. Has there been a commit in the last year? """ headers = {} def mock_get(*args, **kwargs): return MockResponseCommitsNo() today = datetime.now() test_date = datetime.strptime(BAD_DA...
d1145722747acc11cfdcaca8ee9066ad00572f42
3,626,456
def load_response_function(f, fstar=19.09e-3): """Load in LISA response function from file Load response function and interpolate values for a range of frequencies. Adapted from https://github.com/eXtremeGravityInstitute/LISA_Sensitivity to use binary files instead of text. See Robson+19 for more detai...
c81e1ad91cda0b3f13a826605a797f72a62fc965
3,626,457
def edit(request): """ Save profile changes. Args: request (HttpRequest): Request with user profile data passed with the `GET` method. Returns: An `HttpResponse` with search results. """ if request.method == 'POST': # Apparently, `<form> .__ call __ ()` can...
3050b80ec2ad23c8f73a84f7790541bae6199a90
3,626,458
def _make_training_input_fn(transformed_dataset): """训练数据处理""" def input_fn(): x, y = [], [] s = set() for tdt in transformed_dataset: x.append(tdt["x"].tolist()) s.add(len(tdt["x"].tolist())) y.append(tdt["y"]) print(list(s)) x, y = np...
d186c372af031224a090ac6c59b195528554a427
3,626,459
import select def _do_select_for_plugin_api(params): """A version of select_for_plugin_api which accepts indirect products.""" if not params: fail("Empty select_for_plugin_api") expanded_params = dict(**params) # Expand all indirect plugin_apis to point to their # corresponding direct pl...
83a30862c29ac88c736614102786ca2ac12c2bdd
3,626,460
def escape_special_char(string): """ Is called on all paths to remove all special characters but it's not good. Should be moved in core Should be called only in get_wrapper_path and unescape_special_char in get_entry and in script += 'menu_click... in menu_click as it's already done ...
cb3d4bd0d7370ec9c3d76543db8e3aafaf1bd8e8
3,626,461
import requests import json def search_product_with_application_id(app_id): """ Searches for Products based on application id association :param app_id: application id that is being used in products :return : True or False Indicates Success (Product Found) or Failure (Product Not Found) and ProductID ...
6047de50d7760edded8b7376a0d9e8803fd8ede8
3,626,462
def jinc(x, normalize=True): """Evaluate the jinc function in the input corodinate ``x`` Parameters ---------- x : a single point or an ndarray the input corodinate normalize : bool, optional if ``True`` (default), the normalized jinc (``jinc(0)=1``) is returned Returns...
c928569800eade81dd3cb7700daf795f7cf5c9d4
3,626,463
from pathlib import Path def fp_search_rglob(spt_root="../", st_rglob='*.py', ls_srt_subfolders=None, verbose=False, ): """Searches for files with search string in a list of folders Parameters ---------- spt_root : string...
e8fe03f9549ae77147ec96263411db9273d2c4cb
3,626,464
def decode_atbash(string, abc=None): """ Decodes a string with the classic atbash ciphering method :param string: :param abc: :return decoded string: """ if abc is None: abc = abc_en.copy() elif type(abc) == list: abc = abc.copy() elif type(abc) != tuple: retu...
8302af799509304a8a1621a6d2a3fcb1387c930e
3,626,465
def affine_subbasis(mode, dim=3, sub=None, dtype='float64'): """Generate a basis set for the algebra of some (Lie) group of matrices. The basis is returned in homogeneous coordinates, even if the group required does not require translations. To extract the linear part of the basis: lin = basis[:-1, :-1...
1496ad50c8ee30f351385477a23bed7f22bc6c1b
3,626,466
def transition_layer(x, nb_channels, dropout_rate=None, compression=1.0, weight_decay=1e-4): """ Creates a transition layer between dense blocks as transition, which do convolution and pooling. Works as downsampling. """ x = BatchNormalization(gamma_regularizer=l2(weight_decay), beta_regularize...
629094116f43bb0ffa625796b2088b167079d1cf
3,626,467
def mobilenet_v2(pretrained=False, progress=True, **kwargs): """ Constructs a MobileNetV2 architecture from `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (...
6b14de32ba6835fe72ca5784aaedfbb4abe65362
3,626,468
import math def unit_cross_product(uvec1, uvec2): """ Returns unit cross product between two unit vectors Ensures the result is itself a unit vector """ cos = np.dot(uvec1, uvec2) sin = math.sqrt(1 - cos**2) # if the number of atoms is > 3 and there are 3 colinear atoms this will fail ...
de07e29df68d744c6c9903b9664abeab899b3869
3,626,469
import warnings import uuid def new_test_image(): """ Creates an automatically generated test image. In your testing `tearDown` method make sure to delete the test image with the helper function `delete_test_image`. The recommended way of using this helper function is as follows: object_1....
b70ffbd6ddd7c41674a1dc85d8331d36fb4a1d42
3,626,470
from pathlib import Path import urllib def move_data( uid, array_uri, coverage_vector_uri, cells_vector_uri, outdir_uri, access_key, secret_key, ): """ Placeholder for moving data. Nothing fancy. Not using until more testing is done regarding tiledb.move and tiledb.consolid...
6e76633e76a022f0be29e96040ac2e2bedff7abd
3,626,471
def _(word): """Returns the translated word from the dict_lang python dict. If the word is not found, it returns the same word (in english) Arguments: word {str} -- word to translate """ global dict_lang if dict_lang == {}: load_dictionary() try: word_result = di...
1e16000ffe59454024b0825b8ebf5610adc0192a
3,626,472
def diff(f, a, b, n): """An iterative version of a forward differentiation method.""" x = np.linspace(a, b, n+1) y = np.zeros(len(x)) z = np.zeros(len(x)) h = (b-a)/float(n) for i in xrange(len(x)): y[i] = f(x[i]) for i in xrange(len(x)-1): z[i] = (y[i+1] - y[i])/h z[n] =...
1acdc675bc5c825c45550680f71a57f8d94fbb48
3,626,473
def get_minimum(feature): """Get minimum of either a single Feature or Feature group.""" if hasattr(feature, "location"): return feature.location.min() return min(f.location.min() for f in feature)
aec98f5bc065c6a97d32bc9106d67579f76f7751
3,626,474
def compute_average_top_k_loss(loss: tf.Tensor, top_k_percentage: float) -> tf.Tensor: """Computes the avaerage top-k loss per sample. Args: loss: A tf.Tensor with 2 or more dimensions of shape [batch, ...]. top_k_percentage: A float representing the % of pixel that should be...
6cbc4a720f7441f06d315a1b4ce29dfd3e33f12d
3,626,475
def isUniqueSFW(str): """ Given a string, checks if the string has unique charachters Note that this solution is inefficient as it takes O(n^2) """ l = len(str) for i in range(l): for j in range(l): if i != j and not ord(str[i]) ^ ord(str[j]): return False ...
369eddfc360a2661e063183a30c9d511a5deb3de
3,626,476
def get_3x3_homothety(x,y,z): """return a homothety 3x3 matrix""" a= [x,0,0] b= [0,y,0] c= [0,0,z] return [a,b,c]
5c6c2d8931334cc13297e787a079499753c1976c
3,626,477
def http_die_soon(req): """Disable keep-alive to make HTTP proxy act like SOCKS. By doing this wstan server can remain unchanged, but it will increase latency.""" dropped = [i for i in req.split(b'\r\n') if not _keep_alive.match(i)] end = dropped.index(b'') return b'\r\n'.join(dropped[:end] + [b'Con...
2fe5326d97bd6fa8d84ac5c50b3570a038be7749
3,626,478
def non_max_suppression(boxes, scores, threshold): """ Performs non-maximum suppression and returns indices of kept boxes. :param boxes: [N, (y1, x1, y2, x2)]. Notice (y2, x2) lays outside the box. :param scores: 1d array of box scores. :param threshold: :return: """ assert boxes.shape[0...
876b59ddf4e8955e4385873189313e8441119571
3,626,479
def extract_glimpse_numpy_like(inp, glimpse_shape, glimpse_offsets, name=None, uniform_noise=None, fill_value=None): """ Based on: https://github.com/tensorflow/tensorflow/issues/2134#issuecomment-262525617 Works like numpy with pixel coordinates starting at (0, 0), returns: inp[:, glimpse_offset[0] : g...
94404ae41532eb142b9abf3bc03b4df296d9f642
3,626,480
def readShimadzuDatafile(fn, chapter_num=-1, return_all_sections=False): """ read the ascii data from Shimadzu Lab Solutions software the file appear to be split in to multiple sections, each starts with [section name], and ends with a empty line returns the data in the sections titled ...
d9d7fca23476a303a3fa3915cd083a8c03b7129c
3,626,481
def next_not_tail(*args): """next_not_tail(ea_t ea) -> ea_t""" return _idaapi.next_not_tail(*args)
d69cc61137e96c627143217611aaaabfd293a772
3,626,482
def AddInterestedUserAndUrl(existing_url_key, bots_user_key): """Updates user models's interested_url and url model's interested_user field. This method updates url and bots_user model in trasaction to maintain the atomicity. Args: existing_url_key: Key of the url entity to update (db.Key). bots_user_...
c2652a3cd18745b65e725df69056a33124dbb217
3,626,483
def sql_to_python_type(sql_type: str) -> type: """Turn an SQL type into a dataframe dtype""" if sql_type.startswith("CHAR(") or sql_type.startswith("VARCHAR("): return pd.StringDtype() elif sql_type.startswith("INTERVAL"): return np.dtype("<m8[ns]") elif sql_type.startswith("TIMESTAMP(")...
fa668314e0a7022f8e46ead8d099cae210c7b73b
3,626,484
def scrape_to_list_value(scraped_rows, i, list_name): """insert row of rows of scraped data input i for skipping rows return value in dollars""" to_scrape = scraped_rows[i::7] list_name = [] for i in range(len(to_scrape)): num = float(to_scrape[i][0].replace(',', '.')) num_dollar...
62117d0d78a4fd691baa4163a19962c2fb1443d3
3,626,485
def _marathon(config_schema, info): """ :param config_schema: Whether to output the config schema :type config_schema: boolean :param info: Whether to output a description of this subcommand :type info: boolean :returns: process return code :rtype: int """ if config_schema: ...
f05b48c0ac6db196265f7c8840d9cee33c2769ff
3,626,486
def process_owner_me_query(): """Return features that the current user owns.""" user = users.get_current_user() if not user: return [] features = models.Feature.get_all(filterby=('owner', user.email())) feature_ids = [f['id'] for f in features] return feature_ids
e8cb698247c5eb986416013a2ad791612a4ff95a
3,626,487
def velocity_traj(arr, dt=1.0, axis=0, endpoints=True): """Calculate velocity from `arr` (usually coordinates) along time`axis` using timestep `dt`. Central differences are used (example x-coord of atom 0: ``x=coords[:,0,0]``):: v[i] = [ x[i+1] - x[i-1] ] / (2*dt) which returns nstep-2 po...
62e0de52a24e3dfc081ed5b5ed7be67b1026b409
3,626,488
def litho_ruler( height = 2 , width = 0.5, spacing = 1.2, scale = [3,1,1,1,1,2,1,1,1,1], num_marks = 21, layer = 0, ): """ Creates a ruler structure for lithographic measurement with marks of varying scales to allow for easy reading by eye. Parameters ---------- height :...
177381fdd11b322817c1353b40ff3e3edac29bc6
3,626,490
import functools def create_recurrent_model(vocab_size = 10000, num_oov_buckets = 1, embedding_size = 96, latent_size = 670, num_layers = 1, name = 'rnn', s...
dfbd4b7fe08d3a9114a82801495efe807191683e
3,626,491
def get_template(template_name): """ Returns a lxml Element containing the new terminal layout. """ template_path = path_template(template_name) new_division = ET.parse(template_path) return new_division.find("div")
0374a9b00a40d76f8d57ac35969516c58e81fa0e
3,626,492
def get_nodes_from_vpc_id(vpc_id): """ calculate node-ids from vpc_id. If not a vpc_id, then single node returned """ try: vpc_id = int(vpc_id) except ValueError as e: return ["%s" % vpc_id ] if vpc_id > 0xffff: n1 = (0xffff0000 & vpc_id) >> 16 n2 = (0x0000ffff & vpc_id) ...
5c3a6506a721f9d518579df39a91ec38118d5e75
3,626,493
from io import StringIO def format_config_vals(config_vals): """Format an iterable of config values from a config object.""" text_buffer = StringIO() for i, k, v in config_vals: val = "" if v is None else str(v) text_buffer.write( (" " * i) + colorize(pad_line(st...
1a7cd1b0f1a085c510c860ff097be010aea68997
3,626,494
from typing import List def extract_imports(node: Module) -> List[ParsedImport]: """Extract parsed imports from module.""" node_imports = [] for node_import in node.iter_imports(): from_module = '' import_data = [] for part in filter_nodes(node_import, [Name, Keyword, Operator]): ...
6bae0fc8d136758de684be0f9be543758c87e94d
3,626,495
def optimize_k_knn(X_train, y_train, X_test, y_test, min_k=3, max_k=10, score='micro'): """ Find best k neighbor number for KNN model based on scores on testing data Score is based on f1_score, for options refer to sklearn.metrics """ k_f1 = [] for k in range(min_k, max_k+1): knn = ...
0b234439f5fdee345a50a60e6835f4b62d500de0
3,626,496
from click.testing import CliRunner def run_cmd(*args): """Run the provided arguments """ runner = CliRunner() return runner.invoke(main, args)
3c0d665cebb66ac8715edee838d1feb86fb445db
3,626,497
def condor_r_step(wkspace, sys=None, job_name="rank", dag=None): """Generate a condor job for running the ranking steps. Parameters ---------- wkspace : pathlib.Path Path of the config file. sys : list(str), optional Specific ystematics to use. job_name : str Name for th...
1d0531d7a02433a9e354e736cebd7f2f7b05fd6a
3,626,498
from datetime import datetime def utc2local(utc_time): """ UTC time to local time. UTC time format: 2020-02-02T02:02:02.202002Z, formatting UTC timestamp according to "%Y-%m-%dT%H:%M:%S.%fZ". :param utc_time: UTC time :return: local time """ local_format = "%Y-%m-%d %H:%M:%S" # The for...
a2661758eb6176e7d7e4a0b6d5338b0f2c531757
3,626,499
def _custom_openapi(app: FastAPI): """Custom OpenAPI schema generator function, supporting: - Cache the schema - Set custom logo in ReDoc """ if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=settings.title, version=settings.version, ...
487418d582a17b854f77d94d89a92fde58f60625
3,626,500
import torch def get_hidden_states( model: BertModel, sent_data: np.array ) -> torch.Tensor: """ Grab the hidden state values from the model using the sentence data, and return the tensor. :param model: A BertModel object, already instantiated. :param sent_data: The sentence data ...
980b7e10d77c5b2e03a9b0ec1fd394352d34f46f
3,626,501
def search(term, category=Categories.ALL, pages=1, sort=None, order=None): """Return a search result for term in category. Can also be sorted and span multiple pages.""" s = Search() s.search(term=term, category=category, pages=pages, sort=sort, order=order) return s
6baee421c0268b69ed53989c8bd07f56c03e3c40
3,626,503
def update_self_profile(request): """ Get current session profile details """ user = get_object_or_404(User, id=request.user.id) user.first_name = request.data['first_name'] user.last_name = request.data['last_name'] user.save() return HttpResponseRest(request, {})
c85a52d8d903499d539d7505b3de1b16646a7958
3,626,505
def ex_verb_voice(sent, ex_set, be_outside_ex=True): """ Finds verb voice feature. 1. One of the tokens in the set must be partisip - VBG 2. One of the tokens in the set must be lemma 'be' 3. VBN's head has lemma 'be' If none of the tokens is verb, returns string 'None' @param sent Lis...
8891a792528af0c44865e4bbc63f269a85df4da9
3,626,506
def add_sensorgroup_filter_by_ihost(query, value): """Adds an sensorgroup-specific filter to a query. Filters results by hostid, if supplied value is an integer. Otherwise attempts to filter results by UUID. :param query: Initial query to add filter to. :param value: Value for filtering results by...
17ef948cdeed719426d8a84c302f4e8d2434ffbd
3,626,507
def compute_residuals(data, targets, weights): """ Squared error function. param list(list(float)) data: independent variable(s) param list targets: dependent variable param list weights: weight vector """ assert type(weights) == list residuals = [] for i, values in enumerate(data)...
36a40cb50e959d9ba8b557e3063d95c1dec69832
3,626,508
def _at_least_x_are_equal(a, b, x): """At least x of a and b Tensors are equal.""" match = tf.equal(a, b) match = tf.cast(match, tf.int32) return tf.greater_equal(tf.reduce_sum(match), x)
6ada1c5bde1f075268ca5cbe6b4105da7daf2599
3,626,510
def _imergeother(*args, **kwargs): """ Like :merge, but resolve all conflicts non-interactively in favor of the other `p2()` changes.""" success, status = _imergeauto(localorother='other', *args, **kwargs) return success, status, False
663589082161ad5ce16d50b8da12b64c1837d044
3,626,511
def MakeExtractor(sess, config, import_scope=None): """Creates a function to extract features from an image. Args: sess: TensorFlow session to use. config: DelfConfig proto containing the model configuration. import_scope: Optional scope to use for model. Returns: Function that receives an image...
55cc86fb13459064c64156f86ffaff24acdc1909
3,626,512
def solution(resources, args): """Problem 3 - Version 1 Find the largest prime factor with the use of this project's prime number utilities. Parameters: args.number The number whose largest prime factor to find Return: Return the largest prime factor of args.number. """ ...
5d1c72329c08a97d59cf0e977fb959332fc2e6eb
3,626,515
def get_player_actions(game, player): """ Returns player's actions for a game. :param game: game.models.Game :param player: string :rtype: set """ qs = game.action_set.filter(player=player) return set(list(qs.values_list('box', flat=True)))
9b961afbee7c3a0e8f44e78c269f37a9b6613488
3,626,516
from unittest.mock import patch def mock_library(**attributes): """ Used to replace an attribute the library that :func:`dist.load` returns. Useful for replacing part of the compiled library as part of the test. """ ffi, library = dist.load() return patch.object( dist, "load", lam...
58e5ef41da0f27f72df1880f3fe72655f41e0d94
3,626,517
def CV_IS_SPARSE_MAT_HDR(*args): """CV_IS_SPARSE_MAT_HDR(CvMat mat) -> int""" return _cv.CV_IS_SPARSE_MAT_HDR(*args)
cdb438c362383b762c750e67bf7a8abf01e3dce7
3,626,518
def parse_host_port(endpoint, default_protocol): """ parse protocol, host, port from endpoint in config :type: string :param endpoint: endpoint in config :type: baidubce.protocol.HTTP or baidubce.protocol.HTTPS :param default_protocol: if there is no scheme in endpoint, ...
fe80b1eee4a4d76fcfda1bdcb534eeef74662dcc
3,626,519
def nfvi_kube_rootca_update_generate_cert(expiry_date, subject, callback): """Kube RootCA Update - Generate Cert""" cmd_id = _infrastructure_plugin.invoke_plugin( 'kube_rootca_update_generate_cert', expiry_date=expiry_date, subject=subject, callback=callback) return cmd_id
8effed9b004901e9938c545241fbf4234a3480cd
3,626,520