content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pearson_correlation_terms(co_elements, first_set, second_set, first_set_avg, second_set_avg): """ Description A function which returns the pearson correlation terms between two elements. Arguments :param co_elements: Number of co-elements. :...
9c7e723e0717e39e8dd295c2ed3e4998740cc6c8
3,625,695
import torch def train(clf, onehot_encoder, params): """ Trains the model given training data. Arguments: clf (class) : lstm model params (dict) : contains model, dimension, and batch parameters Returns: clf (class) : the trained model """ num_epochs = params['num_epoch...
a0f4da082403ab402dd9ea44cf25dc935e940893
3,625,696
def get_sorted_qlist_wstats(course_id, topic_id, user_id=None): """ Return a list of questions, sorted by position. With some statistics (may be expensive to calculate). """ def cmp_question_position(a, b): """Order questions by the absolute value of their positions since we use -...
95418a585dc73bda35a3bc5a132781d5942fbe03
3,625,697
def get_telem_values(tstop, msids, days=7): """ Fetch last ``days`` of available ``msids`` telemetry values before time ``tstop``. :param tstop: start time for telemetry (secs) :param msids: fetch msids list :param days: length of telemetry request before ``tstop`` :returns: astropy Table ...
3d11b30be1842cc9736df27a2b79c8ac62fd3ce4
3,625,698
def ConvertListToCSVString(csv_list): """Helper to convert a list to a csv string.""" return ','.join(str(s) for s in csv_list)
547311ceac094211d47d0cc667d54b2a3e697f4e
3,625,700
def random_scale(img, min_size): """ min_size default: 640 正因为调用了这个函数,初始化成归一化的坐标就不用维护了 """ h, w = img.shape[: 2] if max(h, w) > 1280: scale = 1280.0 / max(h, w) img = cv2.resize(img, dsize=None, fx=scale, fy=scale) h, w = img.shape[: 2] random_scale = np.array([0.5, 1.0,...
7a33d60f03c254c087c47d82ec8f12999037a5e4
3,625,702
def get_learn_performance(model): """ For acquiring the sum total performance of a strategy""" # get the list of agent strategy = [a.strategy for a in model.schedule.agents] # get the list of agent performances scores = [a.score for a in model.schedule.agents] # for each in that list, when stra...
9515c1c9b11461dc8b26ffa627c7cd0e4e4e539c
3,625,703
def min_distance_bottom_up(word1: str, word2: str) -> int: """ >>> min_distance_bottom_up("intention", "execution") 5 >>> min_distance_bottom_up("intention", "") 9 >>> min_distance_bottom_up("", "") 0 """ m = len(word1) n = len(word2) dp = [[0 for _ in range(n + 1)] for _ in ...
8cd87ffe877aa24d5b1fa36ce1d3b96efb7b4e1e
3,625,704
def adjust_cell_formula(value, k): """ Cell formula, i.e., if i=5, val=?(A11)+?(B12) -> val=A16+B17 """ if isinstance(value, str): for i in range(value.count('?(')): if value and '?(' in value and ')' in value: i = value.index('?(') j = value.index(')', i) ...
c95cd7a3e4667749c3aec502c33977ef93530a9e
3,625,705
def insert_data(id: str, og: str, value: int): """ Insert data in db Params: id: short url(primary key) og: original url value: number of visit returns: True if successful else False """ query = f'''INSERT INTO URLS (ID, ORIGINAL, VISITS) VALUES ("{str(id)}", "{st...
0fe1ff2679bee1353066f9c372a89e87193036ef
3,625,706
def main(df): """ main function returs a clean data frame Returns ------- df_new : pandas data frame clean data. """ df_new = data_cleaning(df) return df_new
ce4bf4c8b184da27c801a29d32acdd9160b5c9c9
3,625,707
def lCQgCPevBZXs(): """Package link to operation.""" pkg = Package("pkg") return pkg.circles.long_operation.Bar
7e204094d51a4344264ef22d0a22edf8da0dcccf
3,625,708
def isExtended(lut): """ Returns True if the lookup table has been extended with isExtended. I.e. returns True if the last and second to last LUT entries are the same """ assertIsLut(lut) return np.array_equal(lut[-1, :], lut[-2, :])
ee00813f8b07697b3eb77935dc41c674deb102b3
3,625,709
import re def exclude_regexps(regexps, suite): """Returns the tests whose id does not match with any of the regexps.""" if not regexps: # No regexpes, no filtering return suite def matches_none_of(test): # A test is kept if its id matches none of the 'excludes' regexps tid...
44e93679ef1ea40b7333794e284b8c9bef117ba4
3,625,710
import joblib def _load_fcn(path, extension): """Actual loading function, which handles the cases specified in `load()`.""" if extension == "pt": obj = to.load(path) elif extension == "npy": obj = np.load(path) elif extension == "pkl": obj = joblib.load(path) else: ...
faddd58753fc3ed6c13fbe793223ec37c9531448
3,625,711
def tasks_mult_per_owner(): """Several owners with several tasks each.""" return ( Task('Make a cookie', 'Raphael'), Task('Use an emoji', 'Raphael'), Task('Move to Berlin', 'Raphael'), Task('Create', 'Michelle'), Task('Inspire', 'Michelle'), Task('Encourage', 'Mi...
fccf075a8b69301672ed9abfeb85a53254309ee9
3,625,712
def generate_systemd_scion_config(host, archive, with_sig_dummy_entry=False): """ Generate the configuration archive for the :host: in the given archive-writer :param host: Host object :param scionlab.util.archive.BaseArchiveWriter archive: output archive-writer :returns: list of systemd units that ...
90b8453d83fb93a03f17973febf1b633924be8c2
3,625,713
import json def lascoverage(inputfile): """ Provide a file name with extension: - las - laz ...extract a tight polygon around the XY points in the file and return a GeoJSON polygon """ # define a pipeline metapipeline = { "pipeline": [ { "type":...
08a2c2f85060552f0b181c6db20fcbbb06a39016
3,625,714
def get_renovations(ids, cache_time=5): """ Get stadium renovation by ID Args: ids: renovation ID(s). Can be a single string ID, comma separated string, or list. cache_time: response cache lifetime in seconds, or `None` for infinite cache """ if isinstance(ids, list): ids = ...
0bbff09433a6e74f728960e7d9796ccfcfacbb47
3,625,715
def _simulate_delta_rule_2A(task_design, alpha, initial_value_learning, alpha_pos=None, alpha_neg=None): """Q learning (delta learning rule) for two alternative...
cb3fa709bea70d396cde0369bc70a68b8121c469
3,625,716
def get_sha3_calculator(input_bytes): """ Returns object that can be used to calculate sha3 hash :param input_bytes: input bytes :return: object that can calculate sha3 256 hash """ if input_bytes is None: raise ValueError("Input is required") return keccak.new(digest_bits=eth_comm...
3fa938d02f988f6d7903fffea833a4634ca60d9e
3,625,717
import ast def Exec(content, global_scope, local_scope, filename='<unknown>'): """Safely execs a set of assignments. Mutates |local_scope|.""" node_or_string = ast.parse(content, filename=filename, mode='exec') if isinstance(node_or_string, ast.Expression): node_or_string = node_or_string.body def _visit...
4a7839072d31cba7326427b92471a5bd144a0028
3,625,718
def alerts(): """ Endpoint to return and alerts we have :returns result: dict with array of dicts containing alert data """ result = dict() result['alerts'] = [] alert_list = Alert.query.all() for alert in alert_list: result['alerts'].append(alert.message) return jsonify(re...
eede001e5b7a9d1898bb4ce476288c2bdf4cb531
3,625,719
def ff_multiplicative_inverse(a, modulus=0x11b): """ Based on extended Euclidean algorithm >>> hex(ff_multiplicative_inverse(0x53)) '0xca' """ b = modulus x0, x1 = 0, 1 while a: (q, a), b = ff_divmod(b, a), a x0, x1 = x1, x0 ^ ff_multiply(q, x1, modulus) _, r = ff_divmod(x0, modulus) return r
b6b863082ed9f341df7cbc099abda2d4c7e0f653
3,625,720
def list_own_groups(cm_id, caller_id): """ Method returns list of the groups caller is leader of. @clmview_user @response{list(dict)} dicts describing groups led by caller """ user = User.get(caller_id) # returns all the groups where the user is the leader return [g.dict for g in user...
3bee791cc7f2dbd9cce72acfcd5d00afe5b7ba3b
3,625,721
import copy def _oned_intFunc(x,twodfunc,gfun,hfun,tol,args): """Internal function for bovy_dblquad""" thisargs= copy.deepcopy(args) thisargs.insert(0,x) return integrate.romberg(twodfunc,gfun(x),hfun(x),args=thisargs,tol=tol)
748fa35dbb2364b2c9cd8324356ac6f19f6ba320
3,625,722
def get_category(category_string, model=Category): """ Convert a string, including a path, and return the Category object """ model_class = get_cat_model(model) category = str(category_string).strip("'\"") category = category.strip('/') cat_list = category.split('/') if len(cat_list) ==...
738be2115cd4b3cc7c3ad9aabbeda0ead9eab66a
3,625,723
def genselect(arr, inds): """Select some elements along the inds.ndim-th axis of arr. Takes arr of shape shape (a1, a2, …, am), and inds of shape (a1, a2, …, a(k-1), bk), where k <= m. The elements of inds index into the kth axis of a, allowing you to keep only a subset of "supercolumns" along a given a...
e763ab5981da44476807603082decdb494b268e4
3,625,724
def info(_: Request) -> Response: """ Definition of the /info endpoint, in accordance with SEP-0038. See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0038.md#response """ info_data = {"assets": []} for asset in Asset.objects.filter(sep38_enabled=True): info_data...
75314803d5b6b2d40f17a420efb4ae1a94cc0d68
3,625,725
def remove_nan(*args): """ *args: 1d arrays of the same length """ # Check input arrays have the same wavelegth # ... # Find bad pixels: nan, null or negative wavelengths mask = [] mask = np.ones_like(args[0], dtype=bool) for a in args: for i in np.arange(len(a)): ...
415f172ded154e12c9e0e0f5c6e282e98833ce07
3,625,726
def periodize_filter_fourier(h_f, nperiods=1, aggregation='sum'): """ Computes a periodization of a filter provided in the Fourier domain. Parameters ---------- h_f : array_like complex numpy array of shape (N*n_periods,) n_periods: int, optional Number of periods which should be...
f9a2845dcf40eedce9d46faba506f1c1358ce6a5
3,625,727
def bounding_box_crop(x, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100): """Generates cropped_image using a one of the bboxes randomly distorted.""" ...
d646e4fea765acecb29bed216b639d59b32209ba
3,625,728
from sfepy.fem.probes import LineProbe def gen_lines(problem): """ Define three line probes in axial directions. Parameters ---------- problem : ProblemDefinition instance The current ProblemDefinition instance. Returns ------- probes : list The list of the probes...
5b8ce8e3a39c99e9d0d357f4ae3dbaff86ee2f45
3,625,729
def authenticated_http_request(service_account, *args, **kwargs): """Sends an OAuth2-authenticated HTTP request. Args: service_account: Service account to use. For GCE, the name of the service account, otherwise the path to the service account JSON file. Raises: AuthenticatedHttpRequestFailure "...
c06637978dc23dd6e69bcf5cd087d4423d2726df
3,625,730
def add_extra_columns(df, datatype='sim'): """ Function to add to new columns to DataFrame that are commonly used Parameters ---------- df : pandas.DataFrame Input DataFrame datatype : str, optional Specify whether this is a DataFrame based on simulation or data (default is ...
ee8fdd74132ed2d471b8393f61e26c51b18440d3
3,625,732
def _search(json_, query): """Search for matching packages. :param json_: output json if True :type json_: bool :param query: The search term :type query: str :returns: Process status :rtype: int """ if not query: query = '' config = util.get_config() results = [ind...
45e4fa71a5b5c77b40b89eff631491e0e369cf15
3,625,733
import base64 def decode_image(uri: str) -> np.array: """ Translates image from base64 string to numpy array. """ data = uri.split(",")[1] data = BytesIO(base64.b64decode(data)) image = Image.open(data).convert("RGB") return np.array(image)
9a46dff14a7b6392cbe2b98f6658cbb759affd7f
3,625,734
def solve_for_map(ds, m0, obs_mean, obs_std, m_packer, obs_packer, mask3D, mds, n_small=None,xdalike=None,dsim=None,dirs=None): """Solve for m_MAP $m_{MAP} = m_0 + H^{-1}F^T R^{-1}(d - F m_0)$ Parameters ---------- ds : xarray Dataset containing the EVD ...
887f98d41c05bd64c906790c138b3e005c1ea26a
3,625,735
def str_q2b(ustring, skip_cn_punc=False): """ 全角转半角 """ return ''.join([q2b(uchar, skip_cn_punc) for uchar in ustring])
f5db8276689fb62a434506f9f4fe4555d48c1173
3,625,736
def quick_sort(data): """To sort data as an increase order by divide and conquer method.""" def q_sort(left_index, right_index): """Do quicksort recursively.""" if right_index <= left_index: return # Sort sub partition. part = partition(left_index, right_index) ...
e8c530b6da3f705b08279eb213d03bd54820f4a4
3,625,737
from datetime import datetime import json def monitor(event, context): """ This method looks for security groups and reports any found groups to a json file in s3. """ groups = getAllSecurityGroups() if len(groups) is 0: logger.warning("no security groups found") return #...
648c8bd478eae48677c1126f75c6fab3588375e7
3,625,738
def load_8_color_data(shot, frames=range(5,12), remove_edges=True, data=False, start_n = 13, end_n = 46, ignore=[22]): """ This function automatically loads data from the tree and passes it on to the load_8_color function. When loading data this is generally the preferred method. """ MST_data = load...
207b1516e8141a7f96af067157e8eb7a37a0fb82
3,625,739
import traceback def error(mixed): """Show error page for HTTP and form errors. :param mixed: String or actual catched exception. """ status = 400 trace = None if isinstance(mixed, string_types): page, error = mixed.split(':') message = ERRORS[page][error] else: m...
ee4692fe362af93f68098192ff70bd838d5e7cb2
3,625,740
def get_connection_params(config): """ Creates instances of DatasetParams, SystemParams, DatasetToSystemParams, and CollectionParams for connection generation from config. """ dataset_params = DatasetParams( dataset_count=config["dataset"]["dataset_count"], dataset_env_count_map=proc...
400369514000838af61eb8c5dc7040f2509ec761
3,625,742
def slope_id(csv_name): """ Extract an integer slope parameter from the filename. :param csv_name: The name of a csv file of the form NWS-<SLP>-0.5.csv :return: int(<SLP>) """ return int(csv_name.split("-")[1])
1ae34f1e5cc91fdc3aaff9a78e1ba26962475625
3,625,743
def full_path_to_points(path): """ Find the corners of the path :param path: a list containing, a list of the x coordinates and a list of the y coordinates of the path :return:a list containing, a list of the x coordinates and a list of the y coordinates of the corners of the path """ points_x =...
7b740b136b232ab98fd7fe7d0f3ff129c69a14a7
3,625,744
import requests def check_parent_login(username, dob): """Checks if user input for their credentials is correct for parent's portal. :param username: student's PID (format: XXXNameXXXX) where X - integers :type username: str :param dob: User's Date of Birth :type do...
8817cd24a767f2a4deb71a7e0f5a122c7504146c
3,625,745
import calendar def within_duration(date: dt, start: dt, end: dt, is_break: bool, term: int) -> bool: """ Check if the date is within the current duration If it is, print out the date as what week of the term or break it is and return True """ if not start <= date <= end: return False ...
c8198da050629d51ccc4c0b3e6d8f991105116c2
3,625,746
from joblib import delayed, Parallel def joblib(function, argument_list, num_cores=None): """Apply a univariate function to a list of arguments in a parallel fashion. Uses Joblib's delayed() function with a parallel executor that starts multiple processes. Args: function: A callable object t...
4a81738bf8dca1c570e34d2c39827bd052e746d7
3,625,747
def read_input(filename): """read input file and return list of raw intcodes.""" with open(args.input, "r") as infile: raw_intcodes = infile.readlines()[0].strip().split(",") return raw_intcodes
3ff908d5552ff64e4d43b5a6454696ce1aa94b21
3,625,748
def marketYesterday(token="", version="stable", filter="", format="json"): """This returns previous day adjusted price data for whole market https://iexcloud.io/docs/api/#previous-day-prices Available after 4am ET Tue-Sat Args: token (str): Access token version (str): API version ...
701b9d9a6ab29dab7c61cf4f55e164b6b46d4651
3,625,749
def r2_glmnet(cv_out, y): """calculate r2 using the lambda_1se. This value is for the most regularized model whose mean squared error is within one standard error of the minimal.""" # https://stackoverflow.com/questions/50610895/how-to-calculate-r-squared-value-for-lasso-regression-using-glmnet-in-r be...
affc0b08207f7d8d14036953192687c17cfa8441
3,625,750
def shift_x(x, shift_amt): """ Shifts (registers) the raster plot x by shift_amt """ shifted = np.zeros_like(x) for t in range(x.shape[1]): col = x[:,t] sh = shift_amt[t] shifted[:,t] = shift(col, sh) return shifted
61acf0496b52bb34f3041e4ee1750eaa3eaebe9b
3,625,751
def get_start_sig(line: dict, sched_line: m_sched.LineSchedule, i_stop): """select start signal from branching data and target signals of last stop""" i_prev = (i_stop - 1) % len(line["stops"]) target_signals = list(line["routing"][i_prev].values())[0]["next"] start_signal_str: str = target_signals[sch...
ddac473aef1b9f9b62434a9b1577519f4be6f784
3,625,752
def minbox(points): """Returns the minimal bounding box necessary to contain points Args: points (tuple, list, set): ((0,0), (40, 55), (66, 22)) Returns: dict: {ulx, uly, lrx, lry} Example: >>> minbox((0, 0), (40, 55), (66,22)) {'ulx': 0, 'uly': 55, 'lrx': 66, 'lry': 0...
d8b11d40b52886f290d28f3434b17d2b9641c4fb
3,625,753
def resolve_cname(hostname): """Resolve a CNAME record to the original hostname. This is required for AWS where the hostname of the RDS instance is part of the signing request. """ try: answers = dns.resolver.query(hostname, "CNAME") for answer in answers: if answer.rdt...
f7c090517531c18d103502600cb7c86c4869a494
3,625,755
from .nn import stack import numpy def eye(num_rows, num_columns=None, batch_shape=None, dtype='float32'): """ :alias_main: paddle.eye :alias: paddle.eye,paddle.tensor.eye,paddle.tensor.creation.eye :old_api: paddle.fluid.layers.eye **eye** This function constructs an identity tensor, or a batch of t...
6254ee8fc44c3af847a15d02306482826a299e2c
3,625,756
from typing import Tuple def _IsRetriableHTTPError(ret_value: Tuple[httplib2.Response, Text]) -> bool: """Determines whether the given HTTP exception is retriable. Args: ret_value: The return Tuple returned from the request method. Returns: Whether the exception can be retried. """ retriable_http_...
f96364c741a9035029bc94dc681ffd4e869ba44f
3,625,757
import csv def write_csv(history, filename): """ Write Letterboxd format CSV """ if history: with open(filename, 'w', encoding='utf8') as fil: writer = csv.DictWriter(fil, list(history[0].keys())) writer.writeheader() writer.writerows(history) return True ...
66ab2c9734c5d50b59d1aaff2dd62a4fffcfe0ec
3,625,758
def apply_regression(df, w): """ Apply regression for different classifiers. @param df pandas dataframe; @param w dict[classifier: list of weights]; @return df with appended result. """ # get input if 'state' in df.columns: x = df.drop('state', axis=1).to_numpy(dtype='float64') ...
1fb5fd9f4b297cd024e405dc5d9209213d28ff0d
3,625,759
async def asset(request): """ Browse a particular asset for which we have recorded readings and return a readings with timestamps for the asset. The number of readings return is defaulted to a small number (20), this may be changed by supplying the query parameter ?limit=xx&skip=xx and it will not respe...
2a42cc3f23259b57a51c170920fe998d4a7b7712
3,625,760
def get_geopandas_df(path): """ Creates geopandas dataframe from geeojson file at "path" filepath """ open_json = open_geojson(path) gdf = gpd.GeoDataFrame.from_features((open_json)) return gdf
d21d0285e9333385cd5b71b7c02702d3f41b49db
3,625,761
from typing import Optional def fabs(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray: """ Calculate the absolute value element-wise and return floating-point class:`~heat.core.dndarray.DNDarray`. This function exists besides ``abs==absolute`` since it will be needed in case complex numbers will b...
0e063ad4d691958b90dd877c138fed580b6a0e09
3,625,762
def _parse_meme_motif(motif_line, f): """ Parse the next meme motif from the file. Parameters ---------- motif_line: string the motif name line f: file the open file, which should be pointing to the line immediately after the motif name line Returns ------- mot...
79fccbbf07ef31277b8a2e6ecf5da1ea74a81e72
3,625,764
def get_lambda_cloud_watch_func_name(stackname, asg_name, instanceId): """ Generate the name of the cloud watch metrics as a function of the ASG name and the instance id. :param stackname: :param asg_name: :param instanceId: :return: str """ name = asg_name + '-cwm-' + str(instan...
893abaf60684cbf9d72774d6f5bb2c4351744290
3,625,765
def secondary_training_status_changed(current_job_description, prev_job_description): """Returns true if training job's secondary status message has changed. Args: current_job_description: Current job description, returned from DescribeTrainingJob call. prev_job_description: Previous job descri...
b1d1a83cccb8cf84fa678345bcf7b3f6531aa2c5
3,625,766
import requests def request_movie_info(movie): """ Request movie information. :param movie: A movie object in Model. :return: Request json or None :type movie: Movie """ url = 'https://api.themoviedb.org/3/movie/' + str(movie.tmdb_id) query = { 'api_key': TMDB_APIKEY, ...
1957a09479150d064e3cfc38e402fe6ae4dec16b
3,625,767
from typing import Callable from typing import Any from typing import Dict from typing import Type def event_source( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, data_class: Type[DictWrapper], ): """Middleware to create an instance of the passed in e...
ddd4f4ab7445f9553b0bb744f3b8d569ebf2b17a
3,625,768
import re def get_placeholders(arg, check_duplicates=False): """ Get all the placeholders' names in order. Use the regex below to locate all the opening ({{) and closing brackets (}}). After that, extract "stuff" inside the brackets. Args: arg: The word which this function performs search...
11364e0d897b87d79b588e5ffafe76d429f37f08
3,625,769
def string_concat(str1, str2): """Concatenates two strings.""" return str1 + str2
5b6d842fca2d3623d33341d9bba4e4a76ec29e15
3,625,770
from typing import Optional def _determine_upstream_ids( fid: str, df: pd.DataFrame, basin_field: str = None, downstream_field: str = None, basin_family: Optional[str] = None, ) -> pd.Series: """Return a list of upstream features by evaluating the downstream networks. Parameters -----...
6be87a2a838842f8d7e54c8b686084824ef47f62
3,625,771
def remove_spaces(input_text, main_rnd_generator=None, settings=None): """Removes spaces. main_rnd_generator argument is listed only for compatibility purposes. >>> remove_spaces("I love carrots") 'Ilovecarrots' """ return input_text.replace(" ", "")
a9ba3bcca4a4ff1610d52271562e053f25815618
3,625,773
def length_vector(vector): """ Calculates the norm of a vector. """ return np.linalg.norm(vector)
029732f7bff27fcda65649378d6b7fc669aea410
3,625,774
def init_calendar(): """ init calendar. The calendar initialization function is called to generate the calendar id when the system starts. :return: calendar id """ calendar_id = create_calendar() if calendar_id is None: raise Exception("init calendar failed.") return calenda...
0d4fb9c8a1211fb53bc26fa28e0f474a99795232
3,625,776
def get_db(): """Opens a new database connection if there is none yet for the current application context. """ #if not hasattr(g, 'sqlite_db'): #g.sqlite_db = connect_db() con = connect_db() #return g.sqlite_db return con
1b09d2734a3c62bf6f17f2136924d2fbfb3d7d2c
3,625,777
from typing import List from typing import Counter import heapq def top_k_frequent_pq(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using priority queue approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2]...
4d30bd7e11a087be1a23f9db5c8af7f78c083a5f
3,625,778
from typing import Optional def get_db_instance(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDBInstanceResult: """ Resource Type definition for AWS::Neptune::DBInstance """ __args__ = dict() __args__['id'] = id if opts is None: ...
8267374486c3381fb4fee7fdf7531e0c96799820
3,625,779
def add(x, y): """Add 2 numbers together""" return x+y
bdf809dee5716058a3df4c56d76ec6d9d2ec97c1
3,625,780
def splitData(X, Y=None, train_fraction=0.80): """ Split data into training and test data. Parameters ---------- X : MxN numpy array of data to split Y : Mx1 numpy array of associated target values train_fraction : float, fraction of data used for training (default 80%) Returns ---...
d5ce36bb663f138b924b9ce0173d464a067b2747
3,625,783
def monthFormat(month: int) -> str: """Formats a (zero-based) month number as a full month name, according to the current locale. For example: monthFormat(0) -> "January".""" months = [ "January", "February", "March", "April", "May", "June", "July", ...
cb675f547d9beec0751d8252e99b5c025b8fd291
3,625,785
def test_postponed_resolution_error(): """ This test checks that an unresolvable scopre provider induces an exception. This is checked by using a scope provider which always returns a postponed object. """ ################################# # META MODEL DEF ###############################...
c17d67364f3da6b0892cf2fe04c24e329f3d1732
3,625,786
from datetime import datetime import decimal def _jsonEncoder(obj): """ Encodes C{decimal.Decimal} and C{datetime.datetime} objects. """ if isinstance(obj, datetime.datetime): obj = datetime_util.convertToIso8601(obj) elif isinstance(obj, decimal.Decimal): decimalTuple = obj.as_tuple(...
5b74cf4edc6a1a9eb30ec9c766329c1050d8b467
3,625,787
import torch def optimization_step(A, Y, Z, beta, apply_cg, mode='prox_cg1'): """ Optimization step for several different modes: - 'prox_exact' takes an exact proximal step - 'prox_cgN' takes an approximate proximal step, generated by N conjugate gradient steps - 'gradient' performs a ...
0452c05dcdf2b5c61dc1a721e2b1365eb58acc41
3,625,788
def get_city_country_continent(city, country, continent): """Get id of city, country, and continent from database.""" if city is not None: if City.objects.filter(name=city).count() == 0: # Create new city object if not already in database city = City(name=city) city.s...
e5a3a3d0a68ba42f945f845f3a91d675bf3f84a6
3,625,790
import pyfits def wcscopy( donor, recipient, dext=1, rext=1, verbose=False ): """ Copy the WCS header keywords from the donor fits file into the header of the recipient fits file. dext and rext specify the fits extensions to use for the donor and recipient, respectively. """ donfits = pyfits...
82fd9eae1038f1e01ca51de6a8354f796d61ab9b
3,625,791
def distance2line(line_start, line_end, point): """ Calculate distance from a line between the start and end to an arbitary point in space :param line_start: array, position of the start of the line :param line_end: array, position of the end of the line :param point: array, arbitary position in sp...
e3bc1c318ae14f9d4af2db2622cd765217aec469
3,625,793
def create_linking_info(ctx, user_link_flags, files): """ Creates CcLinkingInfo for the passed user link options and libraries. Args: ctx - rule context user_link_flags - (list of strings) link optins, provided by user files - (LibrariesToLink) provider with the library files """ ...
fa536637dbfe81187f420f6ede32c13ad271521e
3,625,794
def build_fnln_contact(individual_contact): """ Expected parameter format for individual_contact ('My Name', 'myname@gmail.com') Sample output: {'email': 'myname@gmail.com', 'name': 'My Name'} """ return { "email": individual_contact[-1], "name": individual_...
54080191320cfeb425de0f765f10e29726405d0d
3,625,795
def add_usdan_day(day_item): """ Unique ID for each day item is the time attr. Assumes a day_item is in the form: { 'time': <time>, 'breakfast':<meal_items>, 'lunch':<meal_items>, 'dinner':<meal_items>, 'brunch'... }y where <meal_items...
d162ed11accab4beae37db584fd0dbbf4bd7ac45
3,625,796
import numpy as np def shortcut( sn ) : """ For a given snana.SuperNova object sn, quickly convert the posterior probabilities computed using the 'mid' class fractions prior into the posterior probabilities you get when adopting the 'galsnid' prior. NOTE: we do not account for redshift...
adca461ca14c941e8f6a69193f796b78f5dc25dd
3,625,797
def _create_device_profile(device, pv_type, iprofile_id): """Create a profile disk or partition, depending on the physical volume type.""" device_profile = None if pv_type == constants.PV_TYPE_DISK: device_profile = _create_disk_profile(device, iprofile_id) elif pv_type == constants.PV_T...
a4650905935b30aa1ca454f23eb4b0b4d1eb8b8d
3,625,798
def initialize_with_zeros(dim): """ 此函数为w创建一个维度为(dim,1)的0向量,并将b初始化为0。 参数: dim - 我们想要的w矢量的大小(或者这种情况下的参数数量) 返回: w - 维度为(dim,1)的初始化向量。 b - 初始化的标量(对应于偏差) """ w = np.zeros(shape = (dim,1)) b = 0 #使用断言来确保我要的数据是正确的 assert(w.shape == (dim,...
7fb5dad91abab2f29066fffac8c2640f670c45fc
3,625,799
def _process_tce(tce): """Processes the light curve for a Kepler TCE and returns an Example proto. Args: tce: Row of the input TCE table. Returns: A tensorflow.train.Example proto containing TCE features. """ all_time, all_flux = preprocess.read_light_curve(tce.kepid, ...
56fdd0ee3762093398a07d608277a46df9c5e0f9
3,625,801
def extract_img(size, in_tensor): """ Args: size (int): size of crop in_tensor (tensor): tensor to be cropped """ dim1, dim2 = in_tensor.size()[2:] in_tensor = in_tensor[:, :, int((dim1-size)/2):int((dim1+size)/2), int((dim2-size)/2):int((dim2+size)/2)] return in_tensor
5c167c88aa7c65ca06f46d2795dbcd2af38db71e
3,625,802
def generate_plot_filename(pair, ticker_interval) -> str: """ Generate filenames per pair/ticker_interval to be used for storing plots """ pair_name = pair.replace("/", "_") file_name = 'freqtrade-plot-' + pair_name + '-' + ticker_interval + '.html' logger.info('Generate plot file for %s', pair...
a964a90f441ab8c5a41f96a3e6b23f2e5ff4a535
3,625,803
def pdm_prepare_weights_vggs(nets, device="cpu"): """ Note that we only handle the FC parts and leave the conv layers as is """ weights = [] for net_i, net in enumerate(nets): layer_i = 0 statedict = net.state_dict() net_weights = [] for i, (k,v) in enumerate(stated...
5452976b68fb006f154c762e8f29a7dc776b191a
3,625,804
def fmod2p(x): """ Floating point modulo 2 pi """ rval = fmod(x, twopi) if(rval < 0): rval += 2*pi return(rval)
e482cc7bc38c7e73471fe71072bd1923cb6f634e
3,625,805
import math import copy def plan_cartesian_path_lin(move_arm, wpose, length, alpha, z_start, cs): """ :type move_arm: class 'moveit_commander.move_group.MoveGroupCommander' :type length: float :type alpha: float """ move_arm.set_start_state(cs) waypoints = [] wpose.position.x += length*math.cos(alpha...
e064ff6239fd7bb6b29d4c210ef94956219b5165
3,625,806
def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0, GroupCipherKeyNumber_presence=0, GprsResumption_presence=0, BaListPref_presence=0): """CHANNEL RELEASE Section 9.1.7""" a = TpPd(pd=0x6) b = MessageType(mesType=0xD) # 00001101 c = RrCause(...
df61fa49197211af871a08ed93e9d5a5e99ff04b
3,625,807
def gemm_quantized_impl(M, N, K, unroll, interleave, data_type="uint8"): """Assembly implementation of a blocked gemv. Given a block a of shape (4, k) and a block b' of shape (4, k) produces the output block c = a*b of shape (4,4)""" stepA = min(4, M) stepB = min(4, N) assert data_type in ["uin...
f688886a9c7e70b2408376b5e00521ac3b8522ff
3,625,808