content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_matching_s3_keys_as_set(bucketname, suffix="") -> set: """ Generate the keys in an S3 bucket as set. :param bucket: Name of the S3 bucket. :param prefix: Only fetch keys that start with this prefix (optional). """ result = set() for obj in get_matching_s3_objects(bucketname): ...
8b1c3ece7cecee91fad170663e3963b4909fbcf4
41,438
def scaled_up_roi(roi, scale: int, shape=None): """ Compute ROI for a scaled up image. Given a crop region in the original image compute equivalent crop in the upsampled image. :param roi: ROI in the original image :param scale: integer scale to get scaled up image :return: ROI in the scaled u...
24f160bde7f995861aee3f0c20001ce4093aa58a
41,441
def get_rotation(tracker: TrackerComponent): """Returns the Euler rotation of the tracker.""" # Data is [0]=side-side [1]=flat [2]=forward-back if tracker.is_hardware: torso_state = tracker.get_state('torso') return torso_state.rot_euler return (0, 0, 0)
c352c51513abccdbc716cd02d2d04a057a164cfd
41,442
import torch def lowpass_filtering_in_frequency_domain( image_grad: torch.Tensor, lowpass: torch.Tensor ) -> torch.Tensor: """Applies lowpass filtering in the frequency domain as descibed in Walker et al. 2019. Args: grad (torch.Tensor): gradient lowpass (torch.Tensor): losspass tenso...
847d89f9f0078838b594b61df9dd4544cb2bd062
41,443
def review_detection_html(ibs, image_uuid, result_list, callback_url, callback_method='POST', include_jquery=False): """ Returns the detection review interface for a particular image UUID and a list of results for that image. Args: image_uuid (UUID): the UUID of the image you want to review det...
c155f48e2ebc930f9ee9181107ac65ba0b2ea637
41,444
def mask_label_image(labels: np.ndarray, bg_mask: np.ndarray, bg_label: int = 0): """ Mask an input label image and rearrange the label numbers so that they form the continuous range [0, numlabel]. Note that there is not relabelling of the components, just a renumbering. Args: :param labe...
3bcc9fb1e65884856105048d42756e03f5062237
41,445
import torch def compute_accuracy( x: Tensor, y: Tensor, m: int, nx: int, c1: int, w: Tensor, b: Tensor ) -> float: """Compute accuracy using the given parameters and data. Args: x (Tensor): The input tensor (MNIST images) y (Tensor): The output tensor (a column vector of zeros and ones) ...
eededcbedbf4b0137e16428ab0ed566cb5e6e102
41,446
def modal(item_id): """ Return the information of the specified 'item_id'. This is so that users can open the correct modal item through AJAX """ return jsonify({ "id": item_id, "name": mysqlcommands.get_item(item_id)[1] })
2f7edf7a7ed61b7ad2e6223b4dc8e267bc2fa8a0
41,447
import warnings def get_download_url(data_product_uri): """(Deprecated) Get URL for downloading data product identified by data_product_uri.""" warnings.warn("Use user_storage.get_download_url instead.", DeprecationWarning) return (reverse("django_airavata_api:download_file") + "?" + urlencode...
c095a2dfe43ffb984d3eb6bbecc64106dd29c5fe
41,448
import re def get_remote_version_string(): """ Get the current cvd string from the clamav DNS TXT entry """ resolver = Resolver() resolver.timeout = 5 nameserver = CVDUPDATE_NAMESERVER record = str(resolver.resolve(CVDUPDATE_NAMESERVER, "TXT").response.answer[0]) versions = re.searc...
c58415d26378a804d0b536d7218f14744a673d93
41,449
def lit(val): """Accept a single item and return the given value.""" return lambda seq: ([val], seq[1:], Status.succeed(where='lit'))
3cf40630a20ef53e25e67ffe1e0279e9bfafa24e
41,450
def average(data, axis, n): """ Averages data along the given axis by combining n adjacent values. :param data: Data to average along a given axis. :type data: numpy array :param axis: Axis along which to average. :type axis: int :param n: Factor by which to average. :type n: int ...
2f958f48dbf4e14cdcce4c0c06904b7c48007a25
41,452
def _left_operator(func): """Function decorator to treat a method as the left operator.""" def inner(self, other): """Decorator wrapper.""" left = self.value if isinstance(other, NumericType): right = other.value else: right = other return to_aiid...
252cd5b7e9031f0598c998b69cc7157dcd747661
41,453
from typing import Any def normalize_data_values(type_string: TypeStr, data_value: Any) -> Any: """Decodes utf-8 bytes to strings for abi string values. eth-abi v1 returns utf-8 bytes for string values. This can be removed once eth-abi v2 is required. """ _type = parse_type_string(type_string) ...
17e4c3342a8d7dbc5a1274b5368357cb66a9b8e0
41,454
def update_bpt(*args): """update_bpt(bpt_t bpt) -> bool""" return _idaapi.update_bpt(*args)
e02507ec02b11a3fb30fe10d6da584bf9535a65d
41,456
def generate_test_data(): """ 生成测试样本数据,来自函数y=sin(2 * pi * x) :return: 生成的测试数据集的X向量和Y向量 """ test_X = np.linspace(0, 1, 4 * data_number) test_Y = np.sin(2 * np.pi * test_X) return test_X, test_Y
9b8e0abbb5b0a68b3fa20105e0e96e9bf40fee6a
41,457
def usaf_station_to_lat_lng(station): """Return the latitude and longitude coordinates of the given USAF station. Parameters ---------- station : str String representing a USAF Weather station ID Returns ------- lat_lng : tuple of float Latitude and longitude coordinates. ...
591615783f859be3efe36bb754e8142430d69069
41,459
def generate_kwargs(gt, m_vir_thresh, SSPs_in=None, SSP_kwargs={}, **extra_kwargs): """ Generate kwargs for a GAMMA run. Example usage: ## Generate tree and SSP input to GAMMA gt = caga.gamma_tree.load("my_gamma_tree.npy") mvir_thresh = 1e7 SSPs_in = caga.precompute_ssps...
c9b03fb003d778890f8183b2bf4dd7e5ccfb4dca
41,460
def increase_vectors(vectors): """accelerate so that pieces move faster in earlier frames""" new_vecs = [] for vec in vectors: new_vecs.append((vec[0]*VEC_GROWTH, vec[1]*VEC_GROWTH)) return new_vecs
0eaeaa193722b7a135fa7f0d37605d7bf3a7db9e
41,461
def Validate(ciffile,dic = "", diclist=[],mergemode="replace",isdic=False): """Validate the `ciffile` conforms to the definitions in `CifDic` object `dic`, or if `dic` is missing, to the results of merging the `CifDic` objects in `diclist` according to `mergemode`. Flag `isdic` indicates that `ciffile` is ...
d3828279f9cdfae69690122c82ab50cb40fb9662
41,462
def tapis_client(x_tapis_token: str = Depends(tapis_token)) -> Tapis: """Returns a user Tapis client for the provided token""" try: client = _client(x_tapis_token) except BaseTapyException as exc: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="...
cf9b7a70819c8b1f19da9ae4a40e07417032e0ef
41,463
def default_exchange(): """Return a default :class:`kombu.Exchange` created from configuration. Scope: function This fixture offers a default :class:`kombu.Exchange`. """ return Exchange("test-exchange", type="direct")
efff24cd68f6b5bcd2d7628a2bfc399969b64a10
41,464
from ._array import GeoArray def to_geo(values): """Convert values to GeoArray Parameters ---------- values : WKT, GeoJSON or Esri JSON in a list Returns ------- addresses : GeoArray Examples -------- Parse strings >>> to_geo(['{"x" : -118.15, "y" : 33.80, "spatialRefere...
f0eaa16589489c998109fb9d38df96d82435ac32
41,465
def build(name, ask=True, **kwargs): """ Build the malicious mote to its target hardware. :param name: experiment name (or absolute path to experiment) :param ask: ask confirmation :param path: expanded path of the experiment (dynamically filled in through 'command' decorator with 'expand') :pa...
3d1e82946779f298aecb2e90f481588172bbf051
41,466
def cor(y, z): """Compute Pearson's correlation coefficient.""" return np.corrcoef(y, z)[0, 1]
bb7dac07c5070430a2160c85a87fba1a657e0785
41,467
import torch def ldot(u, v, keepdim=False): """Lorentzian scalar product""" uv = u * v uv.narrow(-1, 0, 1).mul_(-1) return torch.sum(uv, dim=-1, keepdim=keepdim)
59c26e622ef5ffe94d92a2e8c0fc40d316b58f5b
41,468
def print_qa(questions, answers_gt, answers_gt_original, answers_pred, era, similarity=dirac, path=''): """ In: questions - list of questions answers_gt - list of answers (after modifications like truncation) answers_gt_original - list of answers (before modifications) answers_pr...
b1379067f4677626522989ea5c2888678b50e8dc
41,469
def thumbiconurl(public_path): """Get the URL of an icon for filename. """ return mimetypeurl(mimetype(public_path))
590f1d75f5bb27aed0f0a81dc2b70b940ad9a677
41,470
def test_depends(func): """Decorator to prevent a test being executed in individual mode""" def invalid(self, test): if self.test_individual: test.description = "Invalid" return test.DISABLED("This test cannot be performed individually") else: return func(self...
4b2db29fc8c0a30ec3a4ec6c3fb93ed958f0094e
41,471
def load( phono3py_yaml=None, # phono3py.yaml-like must be the first argument. supercell_matrix=None, primitive_matrix=None, phonon_supercell_matrix=None, is_nac=True, calculator=None, unitcell=None, supercell=None, nac_params=None, unitcell_filename=None, supercell_filename...
ed2c4b2eceb0a7979ab864b8ff357663086dbc5e
41,472
def pluralize( *, with_quantity: bool = True, with_indicative: bool = False, **word ) -> str: """Pluralize a single kwarg's name depending on the value. ``with_indicative`` must be used with ``with_quantity``. Example ------- >>> pluralize(object=2) "2 objects" >>> pluralize(object=1)...
9dc4fbe280f4794599f57e7af645d9cac51d655e
41,473
def move_bounds(box, ovl_box, padding=0, axis=None): """ given two boxes, return the x and y deltas needed to move the first box to avoid the second. for simplicity, we chose only one axis, whichever is shorter. Also, only allow positive moves. can choose axis with axis='y' or axis='x' ""...
4b3275d97987a95f9962e975ead5f03af3964348
41,474
def ensure_f(func: Function) -> F: """wrap the given function into a F instance""" if not isinstance(func, F): return F(func) return func
7ea54909bac42c2ade1d1a82ec00c9aff3af7cb6
41,475
import re def compiler_call(executable): """ A predicate to decide the entry is a compiler call or not. """ compilers = [ re.compile(r'^([^/]*/)*([^-]*-)*c(c|\+\+)$'), re.compile(r'^([^/]*/)*([^-]*-)*g(cc|\+\+)(-\d+(\.\d+){0,2})?$'), re.compile(r'^([^/]*/)*([^-]*-)*clang(\+\+)?(-\d+(\....
d8fa6fa22f13b13154579e19a4ab18e016a56caf
41,476
def month_and_year(m=None, y=None): """Creates a string from month and year data, if available.""" if y is None: return "present" if m is None: return str(y) m = month_to_int(m) return "{0} {1}".format(SHORT_MONTH_NAMES[m], y)
6c09800c7b7649c983462b0f1d09829d897c4e1b
41,478
def to_bool(a): """ a: a str or bool object if a is string 'true', 't', 'yes', 'y', '1', 'ok' ==> True 'false', 'f', 'no', 'n', '0' ==> False """ if isinstance(a, bool): return a elif a is None: return False elif isinstance(a, (int, float)): return b...
00cb99d07ba6dc2b149f52930e9916cabb7fb872
41,479
import six def find_nova_host(address, config): """See if a nova instance has the supplied address.""" nova = client.Client(config['username'], config['password'], config['tenant_id'], config['authurl'], region...
11dc70d022996f8134d57a4507f8b495a7b23402
41,480
from typing import Iterable def camera_matrix(fov=const.CAMERA_FOV, resolution=const.CAMERA_RESOLUTION, alpha=0): """Returns camera matrix [1] from Field-of-View, skew, and offset. Parameters ---------- fov : float, Iterable Field-of-View angle (degrees), if type is Iterable it will be interp...
3817ea4f890b423757fb4c29715697f9df5decf4
41,481
import random def LoadUserAgents(uafile): """ uafile : string path to text file of user agents, one per line """ uas = [] with open(uafile, 'rb') as uaf: for ua in uaf.readlines(): if ua: uas.append(ua.strip()[1:-1-1]) random.shuffle(uas) return ...
3942f92c11e16ff979c1ef80552a1340bc149c16
41,482
def comment_threads_list(key, part, allThreadsRelatedToChannelId=None, channelId=None, id=None, videoId=None, maxResults=None, moderationStatus=None, order=None, pageToken=None, searchTerms=None, textFormat=None): """Returns a list of commen...
74ca3da4aee410ed38916ed4193860715ea01614
41,483
def gaussianBlur(img): """Applies gaussian filter to a grayscale image""" return cv2.GaussianBlur(img, (5, 5), 0)
e0a28f50c792ec09a6660beedc2d9e6e1df0d59b
41,484
def fix_month(bib_str: str) -> str: """Fixes the string formatting in a bibtex entry""" return ( bib_str.replace("{Jan}", "jan") .replace("{jan}", "jan") .replace("{Feb}", "feb") .replace("{feb}", "feb") .replace("{Mar}", "mar") .replace("{mar}", "mar") .r...
9bdcb06dc43a6d6748af20d5279ca38ec6aa1d0a
41,485
def multipart_form_message(media, form_data={}): """Return a MIMEMultipart message to upload encoded media via an HTTP form POST request. Args: media: a list of (encoded_data, filename) tuples. form_data: dict of name, value form fields. """ message = MIMEMultipart('form-data', None) if form_data: ...
e8c27c3baf0e0692a017de2bfb3a08755cecfb4a
41,486
def make_well2file_dict(data): """Create a dictionary mapping wells to image files. Parameters ---------- data : pandas data frame A data frame from feature computation. Returns ------- well2file : dictionary, {(int, string): string} A dictionary keyed by a (plate, well) tu...
0baaed068a9b84596749a89bc37cae10f8e3950d
41,487
from typing import Optional def create_balloon( x: units.Distance = units.Distance(m=0.0), y: units.Distance = units.Distance(m=0.0), center_lat: float = 0.0, center_lng: float = 0.0, pressure: float = 7_000.0, power_percent: float = 0.95, date_time: Optional[dt.datetime] = None, time_...
e776684b8aa648acfd18f1e026aec296e4c39329
41,488
def calculate_reference_sample(experiment: FCSExperiment, exclude_samples: list) -> str: """ Given an FCS Experiment with multiple FCS files, calculate the optimal reference file. This is performed as described in Li et al paper (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5...
0058d26f7331b5fc1075af1a3a394bc6c64ba2b2
41,490
def get_visibles(photos, user): """ get only photos visible for user """ return photos.filter( Q(owner=user) | Q(shared=user) )
657c336244d2d34b76c12f8964389be4a8d1a300
41,491
import asyncio async def changeTeam(team, member): """enleve tous les rôles d'un utilisateur sauf '@everyone' et '@modo' puis place le member dans la team appropriée return 1 si le changement est effectif 0 sinon""" team = teamName(team) assert team assert isinstance(member, discord.Member) f...
a6accb214e1e09bae59fc4b495f95d019444ac01
41,492
def dataqc_spiketest(dat, acc, N=5, L=5, strict_validation=False): """ Description: Data quality control algorithm testing a time series for spikes. Returns 1 for presumably good data and 0 for data presumed bad. The time series is divided into windows of len L (an odd integer ...
c2c496c6260095b8887b5105ec4305af74959c17
41,493
def pad(text: str, width: int, align: str = '<', fill: str = ' '): """ pad the string with `fill` to length of `width` :param text: text to pad :param width: expected length :param align: left: <, center: ^, right: > :param fill: char to fill the padding :return: """ assert align in ...
74befd22927438961b85e370ed16239d7df52707
41,494
def coins_to_numpy(game): """Game coins info to numpy array Parameters ---------- game : camel up game Camel up game class Returns ------- array Numpy array """ return np.array( [(key[0], key[1]["coins"]) for key in [*game.player_dict.items()]], dty...
2c0614d008f43bbb33e66e6cad169e4e512a6cd9
41,495
import select def edit_mode(obj): """ Select the object and change to edit mode :param obj: string, name of object :return: bpy data object """ bpy.ops.object.mode_set(mode='EDIT') o = select(obj) bpy.ops.object.mode_set(mode='EDIT') bpy.ops.object.mode_set(mode='EDIT') return ...
046c65e6b2beda097776cecb35e25fa8b64314e5
41,496
async def test_cli( aiohttp_client, otupdate_config, monkeypatch, version_file_path, mock_name_synchronizer, ): """ Build an app using dummy versions, then build a test client and return it """ app = buildroot.get_app( name_synchronizer=mock_name_synchronizer, system_...
616c900b2f122ec04cfd3586d9de2937bf9c0d6d
41,497
def check_xform(path_to_xform): """ Returns an array of warnings if the form is valid. Throws an exception if it is not """ # provide useful error message if java is not installed if not _java_installed(): raise EnvironmentError("pyxform odk validate dependency: java not found") #re...
ac31946110fefc462ebc0e9bc9763840f19a77bb
41,498
import torch def slerp(val, low, high): """ val, low, high: bs x frames x coordinates if val == 0 then low if val == 1 then high """ assert low.dim() == 3, low.dim() assert val.dim() == 3, val.dim() assert high.dim() == 3, high.dim() low_norm = low / torch.norm(low, dim=2, keepdim=...
96a74c366139f3f617676e5e011884f698569b97
41,499
def canonical_version(versionstr, release_type='python-service'): """Given a version string verify it is in the canonical form.""" errors = list(validate_version(versionstr, release_type)) if errors: raise ValueError(errors[-1]) return versionstr
caa578f41b7046e88a9a174221d9d1af9b378955
41,500
def CircAperture(Fin, R, x_shift = 0.0, y_shift = 0.0): """ *Inserts a circular aperture in the field.* :param R: radius of the aperture :type R: int, float :param x_shift: shift in x direction (default = 0.0) :param y_shift: shift in y direction (default = 0.0) :type x_shift: int, floa...
bad700cd1e1c8f8767ab52b1444d4088ca30f6b2
41,501
import re def extract_access_token(request): """ Get the access token using Authorization Request Header Field method. Or try getting via GET. See: http://tools.ietf.org/html/rfc6750#section-2.1 Return a string. """ auth_header = request.META.get('HTTP_AUTHORIZATION', '') if re.compi...
6c6d36bdd4965796bacdca7d13a2fc6ef2189299
41,502
def param_is_numeric_and_simple(p): """ Test whether a parameter is numeric and, if it is a string, that it doesn't contain scientific or uncommon notation. :param p: An input parameter :return: """ if isinstance(p, str): return str_is_numeric(p) else: return param_is_num...
3e85671d84d865767c306199c98f1c1c2b151a29
41,503
def DefineNor(height, width): """ Generate Nor module I0 : Array(width, Bit), I1 : Array(n, Bit) -> O : Array(n, Bit) """ T = Array(width, Bit) class _Nor(Circuit): assert height > 1 and height <= 4 name = 'Nor%dx%d' % (height, width) if height == 2: IO ...
b7de2c1f5af67d96aed3e840f20bcce9d3ac4023
41,504
def HMA(data, period=16): """ Hell's Moving Average HMA indicator is a common abbreviation of Hull Moving Average. The average was developed by Allan Hull and is used mainly to identify the current market trend. Unlike SMA (simple moving average) the curve of Hull moving average is considerably s...
604bc4da85d3cb5220db6460caf84f90ff8cc401
41,505
import torch def create_input(shape): """Create a random input tensor.""" return torch.rand(shape).float()
88a907bae19882a4a7c1a0b819eb0deccb065752
41,506
def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input('物品名称,价格,重量: ').split() return name_str, int(price_str), int(weight_str)
d48452a942263ae522e93474c6cc4a5cdd9e097c
41,507
def perpendicular_vector(R, max_alt): """ Generates a viewing and tangent vectors perpendicular to a sphere of radius R """ return np.array([0, R+max_alt*2, 0]).reshape(3, 1), \ np.array([0.0, 0, 0]).reshape(3, 1)
5a08c9d935d05ccee99666627a359ee5c6163147
41,508
import base64 import time def enroll(video): """ Params: video: base64 encoded data """ try: setup_directories() content = base64.b64decode(video) filename = frappe.session.user+".mp4" OUTPUT_VIDEO_PATH = frappe.utils.cstr(frappe.local.site)+"/private/files/user/"+filename with open(OUTPUT_VIDEO_PATH,...
6bc989f656f123613b85d61f3217f39a0a5d993f
41,509
def nonzero_maximum_box(input: Image, flag_dst: Image, destination: Image = None) -> Image: """Apply a maximum filter (box shape) to the input image. The radius is fixed to 1 and pixels with value 0 are ignored. Note: Pixels with 0 value in the input image will not be overwritten in the output im...
a28e2fe91e712ca95ed66670465e72033d756a7e
41,510
def linear_layer(input_tensor, classes, train, summary=False, rf=1, data_format="NCHW"): """Builds a logit layer that we apply the softmax to, with variables Args: input_tensor: input tensor classes: Number of classes to classify in the output train: If we want to train this layer or no...
d297314d5af49065f19fda689939d6216fe34734
41,511
def get_information(key): """ Obtains a variety of runtime information about CMSElemental. """ key = key.lower() if key not in __info: raise KeyError(f"Information key '{key}' not understood.") return __info[key]
bfe75ac86a9231629fbf3472cbdddfd1e4015787
41,513
import string import random def gene_text(number=6): """生成随机字符""" source = string.ascii_letters+string.digits return ''.join(random.sample(source,number))
40970c8b938797243d7626ebad48e78116df657a
41,514
def gen_snippet(snippet, config): """Renders a config snippet. "config" represents the portion of the YAML file applicable to this snippet""" template = ENV.get_template(snippet + ".j2") return template.render(config=config)
cb740b483204b7c49647414ae24145475a0d9b6f
41,516
import requests from bs4 import BeautifulSoup from datetime import datetime def get_info_from_notice(notice): """ # 글 제목, 글 작성자 if(str(notice).find('font')!=-1): print('정상작동') title = notice.find('font').text else: print('에러') writer = notice.find('td', attrs={'class'...
a063bc6cbbcc18dc49c5141d235373e65deed810
41,517
def thead(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transl...
aa288162d200733761d3b84f81234fb1b05dfe7d
41,519
from typing import Union from typing import Type def get_msf_session_id(session_name: str, plan_execution_id: Union[Type[int], int]) -> str: """ Get a Metasploit session ID by the defined session name :param str session_name: Session name provided in input file :param int plan_execution_id: ID of the...
27ba07da3c7330cf752a02b9737f153e258d3a25
41,520
def compute_margin( input_fn, root_dir, model_config, sess=None, batchsize=50, dataset_size=50000): """Compute the margins of a model on all input data. Loads a given model from given directory and load the parameters in the given scope. Iterates over the entire training dataset and computes the upper bo...
717e9a3cf03ab4f7594a4f082a7cc2699b0bd75b
41,521
def in_notebook(): """Determine whether code is running in a Jupyter Notebook shell. Returns ------- ip : bool True if running in a notebook shell, False otherwise """ try: # See https://stackoverflow.com/questions/15411967 shell = get_ipython().__class__.__name__ ...
f3b77ecb41c40b8bc8f558441374fc35949c331d
41,522
import tokenize from operator import getitem import math def groupby_agg( ddf, gb_cols, aggs_in, split_every=None, split_out=None, dropna=True, sep="___", sort=False, as_index=True, ): """ Optimized groupby aggregation for Dask-CuDF. This aggregation algorithm only sup...
67635be47d6495f75e57649ca565dd454143853a
41,523
def put_op(form): """Annotation for a callable function specifying that it is a PUT :class:`Op`.""" return op.Put(form)
c90562f01a64bed25a576ea503f65e93feb0f7aa
41,524
def str_to_tstamp(time_value): """ Convert date string to timestamp Args: time_value (Union[str, int]): date string in any format supported by dateutils.parser.parse Returns: int: timestamp """ if type(time_value) is int: # If we got int - consider it being timestamp already ...
758216ec302d87adff5be5673c89476f164c053f
41,525
def merge_UserInput_with_SourceDF(user_df: pd.DataFrame, source_df: pd.DataFrame): """ Reads the user feature dataset and merges that to the end of the source dataset. Removes the duplicates found in the source with the users dataset. It returns a tuple. first element is the merged dataset and the secon...
a5c16112a43985ae9c56ff017a825ea126e2ad52
41,526
from datetime import datetime def get_effective_data_length(user_code, span_min=10, best_effort=False, exclude_capped=False, start_time=None, end_time=None, min_num_samples=100): """ To compute the length of the data by the user, based on `ActionLog`. Our system establishes a connection (from app ...
9307e0b142775430f088249f9ae37ef3b549c875
41,527
def lorenz_curve(data: pd.Series) -> pd.Series: """ Calculates the values for the lorenz curve of the data. For more information see online `lorenz curve <https://en.wikipedia.org/wiki/Lorenz_curve>`_. Args: data: sorted series to calculate the lorenz curve for Returns: the va...
0a430c60f61addb286d0d29c9358906d810bae12
41,528
from typing import Iterable def cut_solid(solid, cutter): """ Performs a boolean cut of a solid with another solid or iterable of solids. Args: solid Shape: the Shape that you want to cut from cutter Shape: the Shape(s) that you want to be the cutting object Returns: Shape: the...
44f2f039a4bbeba986f4195f9294369f11f59531
41,529
def _find_stub_degree(branch, bus_id): """Find degree of stubbiness, and stub branches. :param pandas.DataFrame branch: branch DataFrame from Grid object. :param int bus_id: index of bus to find subbiness of. :return: (*tuple*) -- tuple containing: stub_degree (*int*) -- How stubby (non-negativ...
4036fb131674401441ac5387923a78a37378ace2
41,531
def add_data_to_list(twitter_return): """ Extract the data from the twitter_return dictionary and place in a list """ twitter_dict = twitter_return ['response_dict'] # Grab the twitter data twitter_data_list=twitter_dict['data'] return twitter_data_list
9e2a2a5e22926b604856c1ec1ae20ebf765b8610
41,532
def get_issue_by_url_seg(url_seg, url_seg_issue): """ Retorna um número considerando os parâmetros ``iid`` e ``kwargs``. - ``url_seg``: string, contém o seguimento da URL do Journal; - ``url_seg_issue``: string, contém o seguimento da URL do Issue,. """ journal = get_journal_by_url_seg(url_seg...
8b7f167a0bebf7cd4484a4da24df142e70c60cad
41,533
def negentropy(p): """ Entropy which operates on vectors of length N. """ # This works fine even if p is a n-by-1 cvxopt.matrix. return np.nansum(p * np.log2(p))
90b271589ba25d86420ad8413cd83fa304d75d24
41,534
def check_n_files(subject, collector, keep, n_file=1): """ Organise download path per subject for the two sessions. If the number of total file is not the same as expected, drop the subject. Parameters ---------- subject: str Subject ID. collecter: dict Dictionary collecti...
56e9ec830d573b8fc8f5c50c1b6bc126a44653a7
41,535
def create_resource_id_tag(**kwargs): """ create tag via resource id """ session = kwargs.get('session', {}) resource_id = kwargs.get('resource_id', {}) tag_name = kwargs.get('tag_name', {}) tag_value = kwargs.get('tag_value', {}) try: tag_session = session.get_client_session(service='ec...
2eef38417ce22520267f31b1b24297f914e2392a
41,538
def ErrorReset(*args): """ErrorReset()""" return _gdal.ErrorReset(*args)
ea013beb93eed6f2d7f91f1a9d1cab5e6692769f
41,539
from typing import Dict def get_noise_range_pcts(db_range_exps: dict, length: float) -> Dict[int, float]: """Calculates percentages of aggregated exposures to different noise levels of total length. Note: Noise levels exceeding 70 dB are aggregated and as well as noise levels lower than 50 dB. Re...
723c7e45a24c149df6f5f19b3f8aabb1f8d5b184
41,540
def update_info(): """ 用户信息更新 """ username = request.get_json()['username'] email = request.get_json()['email'] password = request.get_json()['password'] words_book = request.get_json()['words_book'] words_num = request.get_json()['words_num'] words_num = int(words_num) if words_num ...
d997cf23ec0320b4b583f35431df11877116ecd2
41,541
def read_terminals(terminals_file=DEFAULT_TERMINALS_FILE): """Returns all terminals in order that they are coded in file_train. """ terminals = read_json(terminals_file)[:50000 - 1] return [EMPTY_TOKEN] + terminals + [UNKNOWN_TOKEN]
6514a760f4ed2a49be97230ce6315c0d8bc27d8c
41,542
def _sync_engagement_db_dataset_to_coda(engagement_db, coda, coda_config, dataset_config, cache, dry_run=False): """ Syncs messages from one engagement database dataset to Coda. :param engagement_db: Engagement database to sync from. :type engagement_db: engagement_database.EngagementDatabase :para...
e56e967a96348760119e9194909fdbd2ae65d6fb
41,543
def group_by_first(pairs): """Return a list of pairs that relates each unique key in the [key, value] pairs to a list of all values that appear paired with that key. this documentation should state why this should normally be used; what should this func normally be used for? Arguments: pairs -- a se...
430f6cb9c8c3fc0b6f6b5078f383c5bbb7420dfe
41,544
def accepts_environment(func): """Allows defining an action function that accepts only theTrailEnvironment and doesn't accept a context. Example: @accepts_environment def action_function_taking_only_environment(trail_env): # Do something with trail_env pass """ @wraps(func) ...
8d6ce250e6bd22e6ec110aded195dfd63e4fe286
41,545
def film_layer(incoming, gamma, beta, name='film'): """ FiLM layer :param incoming: incoming tensor :param gamma: incoming gamma :param beta: incoming beta :param name: (string) name scope :return: """ with tf.name_scope(name): # get shape of incoming tensors: in_shap...
0617da38dabe08cdbde762b20f2f1d9f75d9256c
41,546
def _score_lcs(target_tokens, prediction_tokens): """Computes LCS (Longest Common Subsequence) rouge scores. Args: target_tokens: Tokens from the target text. prediction_tokens: Tokens from the predicted text. Returns: A Score object containing computed scores. """ if not target_tokens or not pr...
666cc0761d0bbd221ccd09106d16073c323d42d1
41,547
def reshape_t(x, shape): """Work around fact that x.reshape(()) doesn't work""" if shape != (): return x.reshape(shape) else: return x[0]
579a63afd05ff86093903e160db16266e2bb2125
41,548
import ctypes def make_shared_array(np_array: np.ndarray) -> mp.Array: """ shared array""" flat_shape = int(np.prod(np_array.shape)) shared_array_base = mp.Array(ctypes.c_float, flat_shape) shared_array = np.ctypeslib.as_array(shared_array_base.get_obj()) shared_array = shared_array.reshape(np_arr...
4b1f7ff98c82506c5f04631f4d2211d4e8ca990c
41,549
def _create_core_state_space(optim_paras, options): """Create the core state space. The state space of the model are all feasible combinations of the period, experiences, lagged choices and types. Creating the state space involves two steps. First, the core state space is created which abstracts f...
6f33032212e61d69e11a616f132961f6f70ae373
41,550