content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def drop_semantic_duplicates( student_comments: pd.Series ) -> pd.Series: """Remove the duplicate comments based on the comment's semantics, e.g. "I was waiting for 1 hour." and "I waited for 1 hour." are orthographically different, but the semantically the same, so one will be removed ...
7b5ba13e96e33b041d1ef22733a4db3c8f5c6954
39,900
import os from datetime import datetime def create_summary_writer(log_dir): """Create a tensorboard summary writer. Args: log_dir: log directory. Returns: (SummaryWriter): a summary writer. Example >>> writer = create_summary_writer(os.path.join(self.basedir, 'logs')) ...
063dc5969002ffff7ddd5e4a23cc99d54ee5368c
39,901
def _clip_bounds(bbox, filename): """Clip input fiona-compatible vector file to input bounding box. :param bbox: Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds. :param filename: Input name of file containing vector data in a format compatible with fiona. :returns: Shapel...
81e79e092dcc59741f446ff44e9ba46b5967425d
39,902
import os import json import hashlib def CheckChange(input_api, message_constructor): """Checks for files with a modified contents. Some checking of validator happens on builbots, but comprehensive enumeration tests must be run locally. There are two dangers: 1. Source code for autogenerated files can b...
c92ae33b5cae1b3162f7b5ef91a7d7f13f2848c6
39,903
from registration_backend.backend import JotleafBackend def register(request): """ AJAX user registration """ backend = JotleafBackend() if request.method == 'GET': return _new_api_403() data = request.POST.copy() if not backend.registration_allowed(request): return { ...
b6e5e45eef5011ce42c4a573e9837cc25911ad71
39,904
from typing import Dict def create_mapper(df: pd.DataFrame, field_name: str) -> Dict: """指定した DataFrame の field_name を利用したカラー用マッパーを返す Args: df (pd.DataFrame): 対象とするデータフレーム field_name (str): カラーを調整するデータ列名 Returns: Dict: 調整したマッパー """ mapper = linear_cmap( field_name...
a1dec5a33c0a90d99dc63f8e4c28b5a4af30f06c
39,905
import torch def _ssim_torch(raw_tensor: torch.Tensor, dst_tensor: torch.Tensor, window_size: int, gaussian_kernel_window: np.ndarray) -> float: """PyTorch implements the SSIM (Structural Similarity) function, which only calculates single-channel data Args: ...
3fbd1e18c63a62b880f149f3548f35bf68d54a44
39,906
def create_joint_on_center(): """ Creates a new joint on center of the selected objects or components """ selection = maya.cmds.ls(sl=True) if not selection: return maya.cmds.joint(n='joint#') # if maya.cmds.objectType(selection[0]) != 'mesh': # raise NotImplementedError('Cente...
7fc402c0e97966ee8f52a526be89080d5a1e15a9
39,907
import time import subprocess import os def check_drive(possible_drives, drive_mountpoint, drive_name, log_filename): """ Full check: drive existence/name, log file existence/name, ability to write, so on returns: result,drive """ mount_tries_cnt = mount_tries while True: ...
49d2315ed4f9873f73fe88e365e2931eb982ccf1
39,908
import os def _get_credentials(): """Finds the credentials for a specific test and options. Returns: Credentials: set of credentials Raises: Exception: when the credential could not be set and they are needed for that set of options """ if os.getenv('USE_ALTERNATE_ENV...
dd111ce62086805bfa1c500eb52aae63cae98941
39,909
def filter_instances(project): """Filter EC2 instances based on Project tag""" if project: filters = [{'Name': 'tag:Project', 'Values': [project]}] ec2_instances = ec2.instances.filter(Filters=filters) else: ec2_instances = ec2.instances.all() return ec2_instances
9f9eb69a3e80b446074b16db1a018bf067cdda15
39,910
import json def plugin_poll(handle): """ Poll readings from the modbus device and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a reading in a JSON document, as a Python d...
e60fd3e01fb2c23a06e1f261795c9afa2054168c
39,911
from typing import List from typing import Any def validate_unity(unity_permutation: List[Any]) -> bool: """Checks that the input permutation is the unity permutation, i.e., an object s of type List[List[int], float, bool] such that * s[0][0] > -1, * s[0][i] < s[0][j] for i < j, * s[1] = 1.0, and...
6ee49a342c058c2122f58dae715881e7a4228091
39,912
def gf_TC(f, K): """Returns trailing coefficient of `f`. """ if not f: return K.zero else: return f[-1]
d09c0bb3a29cce379a598055e7ea781ff6f6f673
39,913
import sys def readinput(filename, target_col=None, exclude_features=None, make_shadows=False): """ Read a dataset and return an input and a target features subset Parameters ---------- filename : str The file path of the dataset to be read target_col : str...
40529da559af0fbaed7ced4667cb8b90a6625842
39,914
def shared_podcast_episode_query(user): """ Shared query set for PodcastEpisodesViewSet and RecentPodcastEpisodesViewSet """ return ( PodcastEpisode.objects.filter(published=True, podcast__published=True) .prefetch_related( Prefetch("offered_by", queryset=LearningResourceOff...
dd42159e36f94186bc9ed033c6e01356ab0967a7
39,915
import os def generate_tclloader_radfilt(radin, rads): """ Filter non-existent radio variants. :param radin: Directory containing files to copy. :type radin: str :param rads: List of radio variants. :type rads: list(str) """ rfiles, infiles = generate_tclloader_radset(radin, rads) ...
6d38adfa710351f216df767d7ddc68c053b66eb7
39,916
import base64 def convert_image( png_image_base64: str, jpeg_image_quality: int = IMAGE_QUALITY_JPEG ) -> str: """ Convert an image from PNG to JPEG, encoded in Base64. (Semi-)transparent pixels are replaced with (semi-)white pixels in the output JPEG image. Args: png_image_base64: P...
8133da5aee63b35b016bde5c09e44aeb05be1a09
39,917
def merge(*args): """ Merge multiple frame states together """ if not args: return create() s = {arg['identifier'] for arg in args} if len(s) != 1: raise ValueError("Expected identifiers, got %s" % str(s)) children = defaultdict(list) for arg in args: for child in arg['ch...
cf1f4bc54583769f621cc8fdb98aaffe64d75cb7
39,918
def int64_counter(urn, metric, ptransform=None, pcollection=None, labels=None): # type: (...) -> metrics_pb2.MonitoringInfo """Return the counter monitoring info for the specifed URN, metric and labels. Args: urn: The URN of the monitoring info/metric. metric: The payload field to use in the monitoring ...
0f9d05861e923239d25af837aa8d33e8be31fec4
39,919
import six def _to_binary_string_py3(text): """ Converts a string to a binary string if it is not already one. Returns a str in Python 2 and a bytes in Python3. Do not use directly, use to_binary_string instead. """ if isinstance(text, six.binary_type): return text elif isinstance...
393962a4a8e1c0def3a402122be59363572ed6cc
39,920
def get_log_info(prefix='', rconn=None): """Return info log as a list of log strings, newest first. On failure, returns empty list""" if rconn is None: return [] # get data from redis try: logset = rconn.lrange(prefix+"log_info", 0, -1) except: return [] if logset: ...
d333fbeaff754e352a0b84c10f4d28e148badfa0
39,921
def get_hidden_status(data): """ 使用Gaussian HMM对数据进行建模,并得到预测值 """ cols = ["r_5", "r_20", "a_5", "a_20"] model = GaussianHMM(n_components=3, covariance_type="full", n_iter=1000, random_state=2010) model.fit(data[cols]) hidden_status = model.predict(data[cols]) retu...
a30ea507c261d44bfdf89ed6911db8c2a82666a0
39,922
def N_interrupts(): """(read-only) Number of interruptions this bus per year""" return lib.Bus_Get_N_interrupts()
9974c75574222e11f284c52f7f0e600477258b4c
39,923
def strip_parameter(context, param): """ A template tag to remove the specified parameter from the url string. If there are no parameter left, it returns the bare url (without any parameters or ?-mark) """ query = context["request"].GET.copy() query.pop(param) if len(query): r...
8bfa38f79743fa66ea3e8e966a8577753cbdfe32
39,924
def get_center_radius(ra, dec, logger=logger): """Get a list of RA and DEC coordinates and returns the center and the search radius.""" center_ra = (np.max(ra) + np.min(ra))/2 center_dec = (np.max(dec) + np.min(dec))/2 radius = np.max([np.max(ra) - np.min(ra), np.max(dec) - np.m...
990216ef19f51791a71a9f32cdd4beb2e0a5f353
39,925
def calculate_health(package_name, package_version=None, verbose=False, no_output=False): """ Calculates the health of a package, based on several factors :param package_name: name of package on pypi.python.org :param package_version: version number of package to check, optional - defaults to latest ve...
46029e7563ca0ebb4ac1349b85734786998a1c25
39,926
def _df_to_array(instances): """ Transform inputs into arrays Parameters ---------- instances : DataFrame, Series or array Input data Returns ------- instances : array Transformed features """ if isinstance(instances, pd.DataFrame): return instances.valu...
f0112ef718d4075eda4f041a46d5feaf3e2103d3
39,927
def S2(Scat, Source, phi, theta): """Function compute :math:`S_2` component of scattered FarField defined as Eq:III.111 of B&B. :math:`S_2 = \sum_{n=1}^\\infty \sum_{m=-n}^{n} \\frac{2n+1}{n(n+1)} \\Big[ a_n g_{n,TM}^m \\tau_n^{|m|} \\big(\cos (\\theta) \\big) + m i b_n g_{n,TE...
b8a83e40e606f11aed53dfb045e4c69cd58f8354
39,928
def text_to_html(string): """Take text as input and return html that renders nicely. For example replace newlines with '<br/>' This was built for use in reminder emails, please check for effects there if you are updating it.""" string = "<html><body>" + string + "</body></html>" string = string...
86cbbc0d35bc994450bb16e989264f96c992aaa3
39,929
def spacecraft_vel(deltaw, deltan, deltar, dij, vmap): """ function to calculate pixel-wise spacecraft velocities for Sunpy map Based on Haywood et al. (2016) and described in Ervin et al. (2021) - In Prep. Parameters ---------- deltaw: float, array relative westward position of pixel ...
78c2acffc4f14c3f707cc50e1594ad7012bc1b08
39,930
import types def task__package_mkdir_iso_root() -> types.TaskDict: """Create the packages root directory on the ISO.""" return targets.Mkdir( directory=constants.REPO_ROOT, task_dep=['_iso_mkdir_root'] ).task
5625b04905dff0905ba34a4021d7a9c349bbce0a
39,931
def _gen_3d_examples(x1_size: float, x2_size: float, num_examples: int, noise_prob: float): """Generates 3D examples Each example has coordinates [x1, x2] where: - x1 is on interval [0, x1] - x2 is on interval [0, x2] Args: x1_size: Size of first axis. x2_s...
cb0837163a9293c1ee7f9a3935cace420000547c
39,932
from typing import List def get_target_args(args: List[Arg]) -> List[Arg]: """Given args for a controlled operation, get the args that are being acted on""" return [arg for arg in args if arg[0] < 2 and arg[1] > -1]
6497788de387cb752dd7af5fe44377aefd38ebfe
39,933
def gen_stats_grouped_accum(_, group_type): """ Args: _: Http Request (ignored in this function) group_type: Keyword defining group label (day,month,year) Returns: Activities grouped by (day or month or year) wrapped on response's object """ error_messages = [] success_messages = [] status = HTTP_200_OK ...
9a743c1af582288d7d2e67496c1b1a5f5aec180a
39,934
def ClassWeightedLabelSmoothingLoss(real,pred,weights,vocab_size,epsilon): """ pred (FloatTensor): batch_size x seq_len x vocab_size real (LongTensor): batch_size x seq_len weights (FloatTensor): vocab_size """ real = tf.cast(real,tf.int32) real_onehot = tf.one_hot(real,depth=vocab_size) ...
4a67e21f32391589da5297565849f63cd5390b38
39,935
def find_spots(input_path, output_path, intensity_percentile=99.995, filter_width=2, small_peak_min=4, small_peak_max=100, big_peak_min=25, big_peak_max=10000, small_peak_dist=2, big_peak_dist=0.75, block_dim_fraction=0.25, spot_pad_pixels=2, keep_existing=False): """ Find and keep...
82d020e8b89184bce28b52c916e0068d9017ca73
39,936
def get_compilation_step_args(session, task): """Prepare arguments passe to each compilation step.""" latex_document = _get_node_from_dictionary( task.depends_on, session.config["latex_source_key"] ).value compiled_document = _get_node_from_dictionary( task.produces, session.config["late...
ff3f7cfaa2985deb93515d4ad639ab224dc39fa4
39,937
def persistent_q_learning( q_tm1: Array, a_tm1: Numeric, r_t: Numeric, discount_t: Numeric, q_t: Array, action_gap_scale: float, stop_target_gradients: bool = True, ) -> Numeric: """Calculates the persistent Q-learning temporal difference error. See "Increasing the Action Gap: New Opera...
ed8a3ee5f88f604394f64e6759161d9692638ff3
39,938
def preprocess_data(tokenizer, task): """Preprocess dataset to test.""" log.info('Loading dev data...') if task == 'QA': # question_answering batchify_fn = nlp.data.batchify.Tuple( nlp.data.batchify.Stack(), nlp.data.batchify.Pad(axis=0, pad_val=vocab[vocab.padding_to...
72997e909944b9722669958278009393ffb6d604
39,939
def do_with_retry(func, *args, **kwargs): """ Tries a function 3 times using exponential backoff according to Google API specs. Optional kwargs: `_attempts` - override the number of attempts before giving up. `_catch` - tuple of exception types used in `except types as e`. """ MINIM...
daef1d5a87d0d287fbc55baddefedaf1ae2edd4c
39,940
def to_int(s): """convert a string to an integer with PRECISION""" assert isinstance(s, str) # don't convert twice! result = int(float(s) * PRECISION) return result
da57a39bfa545a1058ab98f6ad5d786fc5bbbbce
39,941
def cast(value): """ Casts a RETS value into a Python data type Since RETS servers can return non-Boolean strings (like 'yes' or 'no') or numeric values (namely 0 or 1) for Booleans, these values are left alone and are NOT cast into Python Booleans. Application developers should decide on a cas...
4bf96080c555014907462ef09675a46ac50591e9
39,942
def submit_txn_sold(): """ Endpoint to create a new transaction via our application. """ guid = request.form["guid"] fish = fetch_fish(guid) if fish == None: # Error looking up fish. It might not exist? print("Fish is None") return redirect('/') lastConsumption = fi...
ae4af629531d432f83c75d5bc12b4846e5f553d4
39,943
import os def folder_exists(folder_path): """Checks if a folder exists""" return os.path.exists(folder_path)
7554e4b72c87ffb921104e849454c92e405fc4a1
39,944
from datetime import datetime def validate_calendar_date(date_to_validate): """Checks to see if date (yyyy, yyy-mm, or yyyy-mm-dd) is a valid Gregorian calendar date. """ parts = str(date_to_validate).split('-') if len(parts) == 3: year = parts[0] month = parts[1] day = ...
afdd7a2a1586e66fa26340424e791be805a4b57e
39,945
async def async_setup(hass, config): """Set up the updater component.""" if "dev" in current_version: # This component only makes sense in release versions _LOGGER.info("Running on 'dev', only analytics will be submitted") conf = config.get(DOMAIN, {}) if conf.get(CONF_REPORTING): ...
d71b0ad37eb7eba5ec6b570ff2e008c00c078624
39,946
def ListMessagesMatchingQuery(service, user_id, query=''): """List all Messages of the user's mailbox matching the query. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. query: String used to filter me...
c80b7afc4d52250038bdd8c1c3b2f6d860e41423
39,947
import glob from sys import path import pickle def calibrate_camera(nx, ny, basepath): """ :param nx: number of grids in x axis :param ny: number of grids in y axis :param basepath: path contains the calibration images :return: write calibration file into basepath as calibration_pickle.p """ ...
39ebf9a907fd2b1affe686ef5f5c057b7c4c54bc
39,948
import time def convert_time(t): """Takes epoch time and translates it to a human readable version""" return time.strftime('%Y-%m-%d', time.localtime(t))
e591e32e30a8ceb81c9934f4e67556896a56b79a
39,949
import typing import types def convert( value: typing.Any, *, schema: oa_types.Schema, read_only: typing.Optional[bool] = None, ) -> types.TOptObjectDict: """ Convert object schema value to dictionary. Args: value: The value to convert. schema: The schema for the value. ...
7b195dffe6190dbb6bc4b0d96d91a5340fa5816e
39,950
import uuid import os def getuniqname(base, ext, pre=""): """Returns a unique random file name at the given base directory. Does not create a file.""" while True: uniq = op.join(base, pre + "tmp" + str(uuid.uuid4())[:6] + ext) if not os.path.exists(uniq): break return op.no...
534c2e2a7338686e9af745a7cb585b8edefc6d14
39,951
def _get_proto_summaries( proto_expressions ): """Gets the proto summaries.""" result = [] # type: List[ProtoRequirements] for expr in proto_expressions: def get_summary(tensor_of_protos, desc): for summary in result: if id(summary.tensor) == id( tensor_of_protos) and summary.d...
eaaa5bbf2e279997afc102a254fb0e6a07c083da
39,952
from typing import List from functools import reduce def singleNumber(nums: List[int]) -> int: """ 思路:排序,哈希,位运算(异或) 0^1 = 1, 1^1 = 0 """ # n = 0 # for val in nums: # n ^= val # return n return reduce(lambda x, y: x ^ y, nums)
444b2e2685d42bcc717d95058a6c86dc4da31609
39,953
def getPort(): """ Retreives the current TCP port. Returns: hostIP(str): Current TCP port """ return port
c9e589df3abaef21f324b98a9b4508319409dae6
39,954
def setup_prior(prior=None, num_causes=None): """Setup for prior array Parameters ---------- prior : array_like, optional Prior distribution to use. If not specified, each cause bin will be assigned an equal probability (default is None, and uniform prior will be used). num_...
1301833c7801e0ce8df1e9f1c61de64665f9a2d5
39,955
def get_intact_complex_portal_xrefs_df() -> pd.DataFrame: """Get IntAct-Complex Portal xrefs.""" df = _get_complexportal_df() df['source_ns'] = 'intact' df['target_ns'] = 'complexportal' df['source'] = COMPLEXPORTAL_MAPPINGS df = df[['source_ns', 'source_id', 'target_ns', 'target_id', 'source']]...
8bc35dc888c5b6e5652fabdf99d92eddcc59c249
39,956
def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.cast(image, tf.float32) * 255, label
c91c747b04fdcc876859907cec826563020daba4
39,957
def valid_box(box, host_extent): """Returns True if the entire box is within a grid of size host_extent. input arguments (unmodified): box: numpy int array of shape (2, 3) lower & upper indices in 3 dimensions defining a logical cuboid subset of a 3D cartesian grid in python protocol...
c6b1bc144e23b35002a1fbf17d4e02d9ba904655
39,958
import numpy as np from scipy.interpolate import interp1d def spec_stich_n_norm(spec, wave, cont, sig): """This stitches and continuum normalises CARMENES E2DS spectra into 1D spectra for use in molecfit. N. Borsato - 24-02-2021""" #These arrays will be filled with the stiched data. Total_Specs ...
7ffc89b7d3b3ca2898f2e990c67d712f28c0cfba
39,959
def average(self, key_selector=None): """Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. Example res = source.average(); res = source.average(lambda x: x.value) ...
a9ecd7c4509a3a3203f96bc9fd33bc453fb76ba7
39,960
def disparate_impact_remover(structured_data): """ Perform disparate impact removal from dataset and convert to pandas dataframe. Parameters: aif_standard_data (aif360.datasets.standard_dataset.StandardDataset): Structured dataset. Returns: data_transf_df (pandas dataframe): Pandas dat...
950549d2bd042890830c9adc389d6e46ceed3fff
39,961
def PyDateTime_DATE_GET_SECOND(space, w_obj): """Return the second, as an int from 0 through 59. """ try: return space.int_w(space.getattr(w_obj, space.newtext("second"))) except OperationError: return 0 # see comments in PyDateTime_DATE_GET_HOUR
8b64a6ed2fa7cd57d5a79646f8bbc381ca0972fc
39,962
def get_market_tops(symbols=None, **kwargs): """ Top-level function to obtain TOPS data for a symbol or list of symbols Parameters ---------- symbols: str or list, default None, optional A symbol or list of symbols kwargs: Additional Request Parameters (see base class) """ ...
081bccdedf7dfe888c6508a6df1cbb0deada3da7
39,963
def has_all_params_ortho(**params) -> bool: """ Returns True, if all 12 keys of an orthotropic material are provided.""" return len(missing_params_ortho(**params)) == 0
52d30d36dbd7e52119353af177fa10d0a24513c2
39,964
def hgw_init(): """Instantiate all the needed objects and setups references between them.""" collector = DataCollector() cabinet = FilingCabinet() broker = MessageBroker() adc = AsynchronousDataCarrier() sdc = SynchronousDataCarrier() # NOTE: collector -> cabinet <-> broker <-> carrier collector.cabinet = ca...
bc375a934151b08f8e7ce075491ec753a6ca409e
39,965
def piechartgrid(x='None', y='None', data='None', legendmode ='on', legendposition = 'auto', subfigsize=(2,2), dpi=100, latex=True, **kwargs): """Generates a of pie charts for categorial data. Based on the unique values in dataframe columns ``x`` and ``y`` the grid of subplots is constructed and the associate...
ddc441657fcc5db41b7e6723bb648f1866ebea69
39,966
def fix_curie(curie:str) -> str: """ Biothings explorer has some very weird curie prefixes, like "HP:HP:0012092" and "MESH.DISEASE:ICD10CM:E11.8". This method chooses the first prefix that appears in the response of the bioentities endpoint. If it can't fix the curie then it returns it. Example...
d92b4a51390506e64f840c7a2acb7efd9cd29ef9
39,967
def answer(request, question_id): """ Add an answer to a question """ question = get_object_or_404(Question, pk=question_id) try: answer_text = request.POST.get('answertext') if answer_text: # check to make sure that a new answer was entered and then save it ...
96b18ee4a14b861c018c28c638b436c7d6bcffab
39,968
def map_genome_events(time, domains, header): """Map a genome's properties to its state Args: time: time of the current state domains: dictionary of the genome. keys are gene names, values are the genome objects header: csv header to make sure we have the values in the right order Re...
bf59018ab32ae200ef71ba2256863a62305600a3
39,969
def replace_check_sum(data): """ data[2:-2]のチェックサムを計算し data[-2:]を置き換える @param data データ。4バイト以上の長さが必要 @return 最終2バイトをチェックサムに置き換えたデータ """ cksum = 0 for i in range(2, len(data) - 2): cksum += data[i] return data[:-2] + pack('BB', cksum % 256, cksum // 256)
f7e444d6ca166e73503f5635189f2d9695d7635a
39,970
def conv3x3(in_channels, out_channels, stride=1, padding=1, dilation=1): """3x3 convolution""" return nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=padding, dilation=dilation, bias=False, )
a18e885a6d3a08ac242d9966f6bb0b19b9360d90
39,971
import json def set_event_type(request, event_id): """ Set event type. Should be an AJAX POST. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param event_id: The ObjectId of the event to update. :type event_id: str :returns: :class:`djang...
ad437ded87ca01f2dc4017810ba7d41b24ed5e47
39,972
def rect(x: np.ndarray) -> np.ndarray: """ Rectangle function. """ try: return np.array( [ 1.0 if (x_i < 0.5 and x_i > -0.5) else 0. for x_i in x ] ) except: return 1.0 if (x < 0.5 and x > -0.5) else 0.
9c65576b6d0e3f6bf915517a1f10648c92626404
39,973
async def challenge(msg, mobj): """ The Challenge Picks a random Dota 2 hero to play and gives you 3 items to work towards Optional: supply a hero and get the 3 items to play (sd/ap/rd applicable) Example: !challenge -> Bloodseeker: Guardian Greaves, Abyssal Blade, Dagon """ ms...
edcd9c99e589d148f9ce8494aeac9b88e81811f1
39,974
import os import sys def saveFileInTag(soup, pagefolder, url, session, tag2find='img', inner='src'): """saves on specified `pagefolder` all tag2find objects""" # count for files that doesn't has a filename count = 0 # store the url of all downloaded files, so that we won't download duplicate files ...
0a925fe97748218bbe8a4672aaac182815442d44
39,975
from typing import Sequence def generate_pydot_graph(root, visibility_level): """ Generate the pydot graph - this is usually the first step in rendering the tree to file. See also :py:func:`render_dot_tree`. Args: root (:class:`~py_trees.behaviour.Behaviour`): the root of a tree, or subtree ...
937a1d97e4a029a22e86cf8573df18b64b13ad14
39,976
import os def upload_metadata_api(): """ Upload the metadata.csv file to a specific folder data = {'folder_name': 'desired_name'} files = {'metadata': open('metadata.csv'), 'rb')} """ folder_name = request.form.get('folder_name', None) if not folder_name: app.logger.warning('No fo...
e85322869cb93452ed778c07745c92605e1de59a
39,977
def _lookahead(param, lookahead_ema, step, beta_lookahead=0.5, lookahead_every_nth_iter=4): """lookahead at the param level instead of group level""" condition = step % lookahead_every_nth_iter < 0.5 # == 0. but inexact to deal with roundoffs lookahead_ema = jnp.where(condition, beta_lookahead*lookahead_ema...
2a5faedcaad366a015549f9246b3608900fc5363
39,978
import tempfile import os import logging import shutil import subprocess def test_rsync_source_dir(gearman_worker): """ Verify the source directory exists for a rsync server transfer """ return_val = [] # Create temp directory tmpdir = tempfile.mkdtemp() rsync_password_filepath = os.path...
35299a31130516b5cf94ad18e25bca40fe89dc03
39,979
import dill as cPickle import cPickle def load_pickle(h5f, safe=True): """ Deserialize and load a pickled object within a hickle file WARNING: Pickle has Parameters ---------- h5f: h5py.File object safe (bool): Disable automatic depickling of arbitrary python objects. DO NOT set this to Fal...
7fe94a91c331fbf685f2dbc7cbeb09c2d16c3b2a
39,980
from typing import Generator def dataset_using_generator(samples, reader, **kwargs): """ A generator class which wraps samples so that they can be used with tf.data.Dataset.from_generator Parameters ---------- samples : [:obj:`object`] A list of samples to be given to ``reader`` to loa...
f95a00ba20aaa99afe673628aa55f17106e1914f
39,981
import sys import collections def getBarcodesFromSnapSimple(fname): """Read barcodes from a snap file Attributes: fname - a snap-format file Return: a dictionary contains barcode without qc """ try: f = h5py.File(fname, 'r'); except IOError: print("error: ...
85f459951325a418f17a59a08fb568f6f17595c5
39,982
import yaml def yaml_dump_result(obj, stream): """Redefinition of yaml.safe_dump with added float representer The float representer uses float precision of four decimal digits """ def float_representer(dumper, value): text = '{0:.4f}'.format(value) return dumper.represent_scalar(u'tag...
55a8a06e918276060505224a680e1cb136d4a541
39,983
def _poly_fit_delta(data_series_in): """Given an input Pandas Series (data_series_in) with a PeriodIndex and at least 3 non-nan values, models the expected last value of the series and returns the difference between the modeled and actual value. A linear regression is computed for the input da...
27ed61322f9eabbb18d4a38c9c91cc0306a9d5cd
39,984
import time from bs4 import BeautifulSoup def scrape_last_patch_change(names, save=True): """ Scrapes the last patch in which each champion was changed from League Wiki and saves them to a csv file, but returns nothing Parameters ---------- names : pandas series Contains the c...
cd1ddc78192f145c97bfb1e2be5edd00af38439b
39,985
def delete_all(): """ Delete all predictions in the database. Args: None. """ return Prediction.objects.all().delete()
011f5332d568195b639b41104354584fd9ede600
39,986
def strip_readonly(model: ModelNormal): """Strip read only fields before sending to server""" for field in [ elt for elt in model.attribute_map.values() if hasattr(model, elt) and isinstance( getattr(model, elt), (models.Id16ReadOnly, models.Id16ReadOnlyNu...
412f87ea0b17996dea8fb939412bc736b59dccfa
39,987
def get_stock_rack_assembler(entity, rack_barcodes, excluded_racks=None, requested_tubes=None, include_dummy_output=False, **kw): """ Factory method generating a stock rack assembler (XL20 worklist generator) tool for the passed entity. The generator...
f9a7aed7c2c4d9c55736fb2b4c1512ec34e35cf4
39,988
import string import random def random_string(length=-1, charset=string.ascii_letters): """ Returns a random string of "length" characters. If no length is specified, resulting string is in between 6 and 15 characters. A character set can be specified, defaulting to just alpha letters. """ if ...
170082275e16d19d6e2bd37178e1c654b75ef261
39,989
def rho_NFW(r, rs, rhos): """ The density profile [GeV/cm**3] of an NFW halo. Parameters ---------- r : the distance from the center [kpc] rs : the NFW r_s parameter [kpc] rhos : the NFW rho_s parameter [GeV/cm**3] """ res = rhos/(r/rs)/(1.+r/rs)**2 return res
3b8f97713610c1622815e15f13a75d39ad7e64ba
39,990
import numpy as np from .model_store import get_model_file import os def get_jasper(version, use_dw=False, use_dr=False, bn_eps=1e-3, vocabulary=None, model_name=None, pretrained=False, root=os.path.join("~", ".te...
5f4d4248b4d180e7ad38f14a89f87f46884788ca
39,991
def _load_local_auth(): """Returns a LocalAuthParameters tuple from LUCI_CONTEXT. Returns: LocalAuthParameters for connecting to a local auth server. Raises: BadLuciContextParameters if file is missing or not valid. """ data = luci_context.read('local_auth') if data is None: raise BadLuciConte...
f1bf1f5ab11723956c81a3d852dc9094d0bef8b3
39,992
def ifequal(parser, token): """ Output the contents of the block if the two arguments equal each other. Examples:: {% ifequal user.id comment.user_id %} ... {% endifequal %} {% ifnotequal user.id comment.user_id %} ... {% else %} ... ...
18ef87d1c957620083a493661f90f92aa831c13d
39,993
from skimage.metrics import structural_similarity def ssim(x: np.ndarray, y: np.ndarray) -> float: """Calculate the structural similarity metric (SSIM) between images. Note: This function requires skimage. """ assert x.dtype == y.dtype return structural_similarity(x, y, channel_axis=2, ...
6183c839168a9043c39c12d722142b8de751b1b4
39,994
def get_config_data(request): """ Sends form configuration data to the frontend. This allows clientside validation to mirror serverside validation. """ return JsonResponse({ "nameMaxLength": settings.CONTACTFORM_NAME_MAX_LENGTH, "organizationMaxLength": settings.CONTACTFORM_ORGANIZA...
e93e6b790af947008410bf99ce76f1e10f8caeb3
39,995
def read(fileObj, securityTrader=None, _flowType=None): """ 读取 excel 文件,并返回 :param fileObj: 已经打开的 file 文件实例,限制 file 实例是为了可以不依赖磁盘文件,直接使用内存 :param securityTrader: 对应的券商 :param _flowType: :return: """ flowing = Flowing.open(fileObj, securityTrader) return flowing
90d34bde95d80cc91c5868e44c9880be3adf1d67
39,996
from bs4 import BeautifulSoup def get_saml_assertion(response): """Parses a requests.Response object that contains a SAML assertion. Returns an base64 encoded SAML Assertion if one is found""" # Decode the requests.Response object and extract the SAML assertion soup = BeautifulSoup(response.text, "html...
33dff6ee1725ddc86be2452e3e6d8306723474bf
39,997
def register_for_init_call(m): """ Decorator that tags a method to be called at the end of processing cmds. NOTE: This decorator MUST BE the outermost decorator used on a method decorated with multiple decorators! The custom user attributes of a method aren't preserved in python 2.7 even...
8d10aadd600e2e83089d0095d320a8b2a2aac3e1
39,998
def breakup_names(df): """Breakup full name into surname, title, first name""" df[['surname','given_name']] = df['Name'].str.split(",", expand= True) df[['title', 'first_name']] = df['given_name'].str.split(n=1, expand= True) df = df.drop(columns=['Name', 'given_name']) return df
ee76975b88702daf47fa9638c4d1217ca22e1e6e
39,999