content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import ctypes import six def _windows_long_path_name(short_path): """Use Windows' `GetLongPathNameW` via ctypes to get the canonical, long path given a short filename. """ if not isinstance(short_path, six.text_type): short_path = short_path.decode(_fsencoding()) buf = ctypes.create_unico...
72d6b9fc1fb8acd6285019a8d48ea42e847ce8db
4,900
import types def _create_behavioral_cloning_agent( time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec, preprocessing_layers: types.NestedLayer, policy_network: types.Network) -> tfa.agents.TFAgent: """Creates a behavioral_cloning_agent.""" network = policy_network( time...
c3420767aaa153ef44054fdb4fbdcc9540d59775
4,901
import os def prep_fastq_inputs(in_files, data): """Prepare bgzipped fastq inputs """ if len(in_files) == 1 and _is_bam_input(in_files): out = _bgzip_from_bam(in_files[0], data["dirs"], data) elif len(in_files) == 1 and _is_cram_input(in_files): out = _bgzip_from_cram(in_files[0], data...
1dbb51a07068e5a77c59b771a719fb1c2f41858c
4,902
def sidequery(): """Serves AJAX call for HTML content for the sidebar (*query* **record** page). Used when the user is switching between **material** and **record** pages. See also [M:RECORD.body][record.RECORD.body]. Client code: [{sidecontent.fetch}][sidecontentfetch]. """ session.forget(re...
6f5c6660f25e568ea4fa2ad046eac5a57cb4f7e5
4,903
import collections def learn_encoding_model_ln(sess, met, stimulus, response, ttf_in=None, initialize_RF_using_ttf=True, scale_ttf=True, lr=0.1, lam_l1_rf=0): """Learn GLM encoding model using the metric. Uses ttf to initialize ...
bdabe98b689466faeb7fe954cb2cd04e9217fba8
4,904
import pandas import numpy def random_answers_2020_ml(): """ Generates random answers the machine learning challenge of hackathons :ref:`l-hackathon-2020`. """ df = pandas.DataFrame({"index": numpy.arange(473333)}) df['label'] = numpy.random.randint(low=0, high=2, size=(df.shape[0], )) df[...
24a721c1c8e512ade6293644eff61b0866c3f0fe
4,905
import optparse import os def _buildParser(): """Returns a custom OptionParser for parsing command-line arguments. """ parser = _ErrorOptionParser(__doc__) filter_group = optparse.OptionGroup(parser, 'File Options', 'Options used to select which files to process.') filter_group.add_option( '-f...
143fdb5ba476d4b4f5203ce7bf8fca5f6b4964f5
4,906
def _sizeof_fmt(num, suffix='B'): """Format a number as human readable, based on 1024 multipliers. Suited to be used to reformat a size expressed in bytes. By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254 Args: num (int): The number to be formatted. suffix (str...
c70c9ce46f6b391e2389329a6fcd50bf863ea041
4,907
from typing import Optional from typing import Tuple from typing import Union import click import subprocess import os def train( package: str, config: str, gpus: int, gpus_per_node: int = None, cpus_per_task: int = 2, partition: str = None, launcher: str = 'none', port: int = None, ...
f2bd2dc2d73612e3f3f8bda477cb6838915a2209
4,908
def CrawlWithSmbclient(config): """Crawls a list of SMB file shares, using smbclient. Args: config: Config object holding global configuration from commands flags Returns: report: Report object holding the results from the crawling the shares. """ shares = config.Shares() if not shares: ...
d29c7bbf185f56555ab7cd8dd775063525e96b22
4,909
import sys def new_image(): """ Display an image, and ask the user to label it """ user_id = current_user.user_id categories = current_app.config["CATEGORIES"] label_form = LabelForm() label_form.cat_radio.choices = [(cat,cat) for cat in categories] if request.method=="POST": ...
f7b9cb489ccef2fb17103e69386c9f508d97b6ed
4,910
def num_cluster_members(matrix, identity_threshold): """ Calculate number of sequences in alignment within given identity_threshold of each other Parameters ---------- matrix : np.array N x L matrix containing N sequences of length L. Matrix must be mapped to range(0, num_symbol...
e9034a728b22f7a594ef7842f2a4039559751e21
4,911
def get_score(command: str) -> float: """Get pylint score""" output = check_output(command, shell=True).decode("utf-8") start = output.find("Your code has been rated at ") if start == -1: raise ValueError(f'Could not find quality score in "{output.rstrip()}".') start += len("Your code has ...
d32b6f9496033d4c2b569ebc7403be43bb43ceb1
4,912
def tf_abstract_eval(f): """Returns a function that evaluates `f` given input shapes and dtypes. It transforms function `f` to a function that performs the same computation as `f` but only on shapes and dtypes (a.k.a. shape inference). Args: f: the function to be transformed. Returns: A function wh...
7bdd5ddfa69f3be635aed08be9476296c108f79e
4,913
import json def __process_input(request_data: str) -> np.array: """ Converts input request data into numpy array :param request_data in json format :return: numpy array """ return np.asarray(json.loads(request_data)["input"])
7639018f69a4e72568cdf86abc503133ebd734af
4,914
import math def getDist_P2L(PointP,Pointa,Pointb): """计算点到直线的距离 PointP:定点坐标 Pointa:直线a点坐标 Pointb:直线b点坐标 """ #求直线方程 A=0 B=0 C=0 A=Pointa[1]-Pointb[1] B=Pointb[0]-Pointa[0] C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0] #代入点到直线距离公式 distance=0 distance=(...
ca0ec1fc25183a240179faef7473d7b86758a92b
4,915
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype): """Create a batch for SG training objective.""" contexts = mx.nd.array(contexts[2], dtype=index_dtype) indptr = mx.nd.arange(len(centers) + 1) centers = mx.nd.array(centers, dtype=index_dtype) centers_csr = mx.nd.sparse.csr_matri...
e16c7ffd6c4f18e247a885de0b7477ddfa5ed02c
4,916
def JD2RA(JD, longitude=21.42830, latitude=-30.72152, epoch='current'): """ Convert from Julian date to Equatorial Right Ascension at zenith during a specified epoch. Parameters: ----------- JD : type=float, a float or an array of Julian Dates longitude : type=float, longitude of observer ...
14bb4d621449a7fd9fa57acecb107aaa4ea61010
4,917
def _average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. T...
24be75daeeb1d5878a9a481c43be440ced40a0a2
4,918
import os def _get_memory_banks_listed_in_dir(path): """Get all memory banks the kernel lists in a given directory. Such a directory can be /sys/devices/system/node/ (contains all memory banks) or /sys/devices/system/cpu/cpu*/ (contains all memory banks on the same NUMA node as that core).""" # Such d...
a3ee0cf6ad043b4a18c12994b9ac028c538e631c
4,919
import time def get_online_users(guest=False): # pragma: no cover """Returns all online users within a specified time range :param guest: If True, it will return the online guests """ current = int(time.time()) // 60 minutes = range_method(flaskbb_config['ONLINE_LAST_MINUTES']) if guest: ...
39ad71b71e8a8caac0e6a82b7992c6229f85d255
4,920
from typing import Union def reverse_bearing(bearing: Union[int, float]): """ 180 degrees from supplied bearing :param bearing: :return: """ assert isinstance(bearing, (float, int)) assert 0. <= bearing <= 360. new_bearing = bearing + 180. # Ensure strike is between zero and 360 (...
1fd01df40a23c52ff093c17fd5752f0609cee761
4,921
def signUp_page(request): """load signUp page""" return render(request, 'app/signUp_page.html')
ae28acac27264dbb8d2f6a69afb01c6f96a08218
4,922
import os def db(app, request): """ Session-wide test database. """ db_path = app.config["SQLALCHEMY_DATABASE_URI"] db_path = db_path[len("sqlite:///"):] print(db_path) if os.path.exists(db_path): os.unlink(db_path) def teardown(): _db.drop_all() os.unlink(db_p...
2f96da64ff0bbfa54f06758ba816120ccda8b16a
4,923
import csv def read_students(path): """ Read a tab-separated file of students. The only required field is 'github_repo', which is this student's github repository. """ students = [line for line in csv.DictReader(open(path), delimiter='\t')] check_students(students) return students
e64aeb1a73fb79e91d0464d6a95e509d3cc60b94
4,924
from typing import Tuple import torch def get_extended_attention_mask( attention_mask: Tensor, input_shape: Tuple[int], device: torch.device, is_decoder=False, ) -> Tensor: """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arg...
26104733e3cc970536a11c3930866dc3d11d3583
4,925
def getdiskuuidvm(diskuuid): """ get vm uuid from disk uuid and return it """ if debug: print 'vm from disk uuid :',diskuuid cmd='xe vbd-list vdi-uuid='+diskuuid response=docmd(cmd).split('vm-uuid ( RO): ') vmuuid=response[1].split('\n')[0] return vmuuid
ec1ffa56c0a85f0554a367ccc41baeb98d21cd41
4,926
import os def storedata(): """ Upload a new file """ #path = os.path.join(app.config['UPLOAD_DIR'],current_user.name) path = os.path.join(app.config['UPLOAD_DIR']) dirs = os.listdir(path) if dirs!="": # If user's directory is empty dirs.sort(key=str.lower) if request.method == 'POST'...
7795b07b296eced8e97195881d5cabbb5a2d725d
4,927
def adler32(string, start=ADLER32_DEFAULT_START): """ Compute the Adler-32 checksum of the string, possibly with the given start value, and return it as a unsigned 32 bit integer. """ return _crc_or_adler(string, start, _adler32)
ed4a0905b4891ee931ef08f91e92032a613caee7
4,928
def find_earliest_brs_idx(g: Grid, V: np.ndarray, state: np.narray, low: int, high: int) -> int: """ Determines the earliest time the current state is in the reachable set Args: g: Grid V: Value function state: state of dynamical system low: lower bound of search range (inclu...
234a201af98f74c41785a36b3391e23700ac80e6
4,929
def italic(s): """Returns the string italicized. Source: http://stackoverflow.com/a/16264094/2570866 """ return r'\textit{' + s + '}'
7eb9e9629e8556e9410e4d92525dd8c06c3e25de
4,930
import functools def skip_if_disabled(func): """Decorator that skips a test if test case is disabled.""" @functools.wraps(func) def wrapped(*a, **kwargs): func.__test__ = False test_obj = a[0] message = getattr(test_obj, 'disabled_message', 'Test disabled'...
56d42a1e0418f4edf3d4e8478358495b1353f57a
4,931
from typing import Any import itertools def _compare_keys(target: Any, key: Any) -> bool: """ Compare `key` to `target`. Return True if each value in `key` == corresponding value in `target`. If any value in `key` is slice(None), it is considered equal to the corresponding value in `target`. ...
ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf
4,932
def parser(_, objconf, skip=False, **kwargs): """ Parses the pipe content Args: _ (None): Ignored objconf (obj): The pipe configuration (an Objectify instance) skip (bool): Don't parse the content kwargs (dict): Keyword arguments Kwargs: assign (str): Attribute to a...
24bb8327fef14952ce90edd41fa9dc778ac15750
4,933
import xarray as xr import aux_functions_strat as aux def predict_xr(result_ds, regressors): """input: results_ds as came out of MLR and saved to file, regressors dataset""" # if produce_RI isn't called on data then you should explicitely put time info rds = result_ds regressors = regressors.sel(time=...
458f3f9a17d9cc16200f1eb0e20eb2a43f095ea0
4,934
async def list_features(location_id): """ List features --- get: summary: List features tags: - features parameters: - name: envelope in: query required: false description: If set, the returned list will be wrapped in an enve...
0698a63af10a70cc2ae0b8734dff61fb51786829
4,935
def shot_start_frame(shot_node): """ Returns the start frame of the given shot :param shot_node: str :return: int """ return sequencer.get_shot_start_frame(shot_node)
f13582040ad188b6be8217a7657ce53c145fe090
4,936
def word1(x: IntVar) -> UInt8: """Implementation for `WORD1`.""" return word_n(x, 1)
0cc7e254c48596d190ccb43a0e0d3c90b18f34af
4,937
def _getCols1(): """ Robs Version 1 CSV files """ cols = 'Date,DOY,Time,Location,Satellite,Collection,Longitude,Latitude,SolarZenith,SolarAzimuth,SensorZenith,SensorAzimuth,ScatteringAngle,nval_AOT_1020_l20,mean_AOT_1020_l20,mean_AOT_870_l20,mean_AOT_675_l20,sdev_AOT_675_l20,mean_AOT_500_l20,mean_AOT_44...
bf3148b53effc18e212e03cf70673dc25e1d0005
4,938
from typing import Optional from pathlib import Path def run_primer3(sequence, region, primer3_exe: str, settings_dict: dict, padding=True, thermodynamic_params: Optional[Path] = None): """Run primer 3. All other kwargs will be passed on to primer3""" if padding: target_start = region....
670f70b5b50200da5c9cd13b447a5836b748fd31
4,939
import inspect def filter_safe_dict(data, attrs=None, exclude=None): """ Returns current names and values for valid writeable attributes. If ``attrs`` is given, the returned dict will contain only items named in that iterable. """ def is_member(cls, k): v = getattr(cls, k) checks ...
ce457615ba8e360243912c3bba532e8327b8def4
4,940
def fixture_loqus_exe(): """Return the path to a loqus executable""" return "a/path/to/loqusdb"
647b31e37854a5cbc8fd066c982e67f976100c03
4,941
def get_reads_section(read_length_r1, read_length_r2): """ Yield a Reads sample sheet section with the specified R1/R2 length. :rtype: SampleSheetSection """ rows = [[str(read_length_r1)], [str(read_length_r2)]] return SampleSheetSection(SECTION_NAME_READS, rows)
19f3e36e34471c6bac89f2a42bdcb3f4b79c22c7
4,942
def validate(number): """Check if the number is valid. This checks the length, format and check digit.""" number = compact(number) if not all(x in _alphabet for x in number): raise InvalidFormat() if len(number) != 16: raise InvalidLength() if number[-1] == '-': raise Inv...
e191ee9d8631dfd843276b2db7ee9699b974e555
4,943
import re def parse_directory(filename): """ read html file (nook directory listing), return users as [{'name':..., 'username':...},...] """ try: file = open(filename) html = file.read() file.close() except: return [] users = [] for match in re.finditer(r'<b...
1b7fc5b6257b5c382f520a60c9227e8b458d482d
4,944
import time def ShortAge(dt): """Returns a short string describing a relative time in the past. Args: dt: A datetime. Returns: A short string like "5d" (5 days) or "32m" (32 minutes). """ # TODO(kpy): This is English-specific and needs localization. seconds = time.time() - UtcToTimestamp(dt) mi...
1de2391d8f604d145a1771596def13460fd0e982
4,945
import sys import tempfile import os import shutil def _raxml(exe, msa, tree, model, gamma, alpha, freq, outfile): """ Reconstruct ancestral sequences using RAxML_. :param exe: str, path to the executable of an ASR program. :param msa: str, path to the MSA file (must in FASTA format). :param ...
dda8cf011f1a1ec2cce0501e35df24a9fa4a90b3
4,946
from typing import Optional def dec_multiply(*args) -> Optional[Decimal]: """ Multiplication of numbers passed as *args. Args: *args: numbers we want to multiply Returns: The result of the multiplication as a decimal number Examples: >>> dec_multiply(3, 3.5, 4, 2.34) ...
f7d953debc5d24c97ee274ec13683be3fda302eb
4,947
import json def get_networks(): """ Returns a list of all available network names :return: JSON string, ex. "['bitcoin','bitcoin-cash','dash','litecoin']" """ return json.dumps([x[0] for x in db.session.query(Node.network).distinct().all()])
755e0238463aabed0a38102ca793842dd54a6c87
4,948
def get_cache_key_generator(request=None, generator_cls=None, get_redis=None): """Return an instance of ``CacheKeyGenerator`` configured with a redis client and the right cache duration. """ # Compose. if generator_cls is None: generator_cls = CacheKeyGenerator if get_redis is None: ...
80c25a204976492e2741e46bd79d70d0e6b62b1a
4,949
import pathlib def is_from_derms(output): """Given an output, check if it's from DERMS simulation. Parameters ---------- output: str or pathlib.Path """ if not isinstance(output, pathlib.Path): output = pathlib.Path(output) derms_info_file = output / DERMS_INFO_FILENAME ...
e9a9be7e18cda3b22661f773e6bb585c833b74d6
4,950
def js_squeeze(parser, token): """ {% js_squeeze "js/dynamic_minifyed.js" "js/script1.js,js/script2.js" %} will produce STATIC_ROOT/js/dynamic_minifyed.js """ bits = token.split_contents() if len(bits) != 3: raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % bi...
30b10b85001bbb5710584fb41469e1c36d50f086
4,951
def view_extracted_data() -> str: """ Display Raw extracted data from Documents """ extracted_data = read_collection(FIRESTORE_PROJECT_ID, FIRESTORE_COLLECTION) if not extracted_data: return render_template("index.html", message_error="No data to display") return render_template("index.h...
9eccebd4952fc3c988bfc6014d2c12944a197ac4
4,952
import json def get_lstm_trump_text(): """Use the LSTM trump tweets model to generate text.""" data = json.loads(request.data) sl = data["string_length"] st = data["seed_text"] gen_text = lstm_trump.generate_text(seed_text=st, pred_len=int(sl)) return json.dumps(gen_text)
9fbad3e7abcfcbbbfb5919a5c37cf607e972592e
4,953
import os def collect_bazel_rules(root_path): """Collects and returns all bazel rules from root path recursively.""" rules = [] for cur, _, _ in os.walk(root_path): build_path = os.path.join(cur, "BUILD.bazel") if os.path.exists(build_path): rules.extend(read_bazel_build("//" + cur)) return rule...
4f7d9f1a8c768136aac8009eae284df0c526da62
4,954
def countSort(alist): """计数排序""" if alist == []: return [] cntLstLen = max(alist) + 1 cntLst = [0] * cntLstLen for i in range(len(alist)): cntLst[alist[i]] += 1 #数据alist[i] = k就放在第k位 alist.clear() for i in range(cntLstLen): while cntLst[i] > 0: #将每个位置的数据k循环输出多次 ...
6727b41794dc2a2f826023c2a53202798dfa49ab
4,955
def _FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5): """_FloatsTraitsBase_read_values_dataset(hid_t arg2, hid_t arg3, hid_t arg4, unsigned int arg5) -> FloatsList""" return _RMF_HDF5._FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5)
4f2cfb17e5f0b3cfc980f51ef8e9ae8d7d38ba2c
4,956
import requests from bs4 import BeautifulSoup import io def TRI_Query(state=None, county=None,area_code=None, year=None,chunk_size=100000): """Query the EPA Toxic Release Inventory Database This function constructs a query for the EPA Toxic Release Inventory API, with optional arguments for details such ...
48eef06d1409dfe4404c6548435196cc95baff62
4,957
import requests import html def get_monthly_schedule(year, month): """ :param year: a string, e.g. 2018 :param month: a string, e.g. january :return schedule: a pd.DataFrame containing game info for the month """ url = f'https://www.basketball-reference.com/leagues/NBA_{year}_games-{month}.h...
1aa48abaa274166110df8dfd55b49560f72db054
4,958
import csv import zlib def get_gzip_guesses(preview, stream, chunk_size, max_lines): """ :type preview: str :param preview: The initial chunk of content read from the s3 file stream. :type stream: botocore.response.StreamingBody :param stream: StreamingBody object of the s3 dataset file. ...
aa6185ed31fc4bb5d85e991702925502beff86c0
4,959
from typing import List def make_preds_epoch(classifier: nn.Module, data: List[SentenceEvidence], batch_size: int, device: str=None, criterion: nn.Module=None, tensorize_model_inputs: bool=True): """Predi...
67cecfc6648ef4ad10531b086dab2fc9e6e2f6f3
4,960
def array_3_1(data): """ 功能:将3维数组转换成1维数组 \n 参数: \n data:图像数据,3维数组 \n 返回值:图像数据,1维数组 \n """ # 受不了了,不判断那么多了 shape = data.shape width = shape[0] height = shape[1] # z = list() z = np.zeros([width * height, 1]) for i in range(0, width): for j in range(0, heigh...
0b2991da94102e5ecf47d037f995b95a3fd28ac8
4,961
import json def UpdateString(update_intervals): """Calculates a short and long message to represent frequency of updates. Args: update_intervals: A list of interval numbers (between 0 and 55) that represent the times an update will occur Returns: A two-tuple of the long and short message (resp...
35ba60e028c238f304bcf03d745865c93408b9c1
4,962
from typing import Optional from re import T def coalesce(*xs: Optional[T]) -> T: """Return the first non-None value from the list; there must be at least one""" for x in xs: if x is not None: return x assert False, "Expected at least one element to be non-None"
fe388a40ff200f9988514563d0e37d2d604317a7
4,963
def check_phil(phil, scope=True, definition=True, raise_error=True): """ Convenience function for checking if the input is a libtbx.phil.scope only or a libtbx.phil.definition only or either. Parameters ---------- phil: object The object to be tested scope: bool Flag to check if phil is a...
11a59bb25689bfc5882b8e0b0b9c2e9a5f233db0
4,964
import json def get_ssm_environment() -> dict: """Get the value of environment variables stored in the SSM param store under $DSS_DEPLOYMENT_STAGE/environment""" p = ssm_client.get_parameter(Name=fix_ssm_variable_prefix("environment")) parms = p["Parameter"]["Value"] # this is a string, so convert to dic...
2f5a44c7e01f87c0aff092f9fed83f0030d4f7da
4,965
from datetime import datetime def get_default_date_stamp(): """ Returns the default date stamp as 'now', as an ISO Format string 'YYYY-MM-DD' :return: """ return datetime.now().strftime('%Y-%m-%d')
672cd98265b19da2df92c7849f1059e5988473d7
4,966
import re def check_for_launchpad(old_vendor, name, urls): """Check if the project is hosted on launchpad. :param name: str, name of the project :param urls: set, urls to check. :return: the name of the project on launchpad, or an empty string. """ if old_vendor != "pypi": # XXX This ...
87fc4be32cd93671b5d9fe43697d9e6918675843
4,967
import os def apply_file_collation_and_strip(args, fname): """Apply collation path or component strip to a remote filename Parameters: args - arguments fname - file name Returns: remote filename Raises: No special exception handling """ remotefname = fname.repla...
7422a4c4b979dedc58a32a65f139f764cd0e78cb
4,968
import torch def constructRBFStates(L1, L2, W1, W2, sigma): """ Constructs a dictionary dict[tuple] -> torch.tensor that converts tuples (x,y) representing positions to torch tensors used as input to the neural network. The tensors have an entry for each valid position on the race track. For each ...
575572e40f66c121468d547b45fa92c23f78f99f
4,969
import os import json import tqdm def gather_data(path, save_file=None, path_json='src/python_code/settings.json'): """ Gather data from different experiments :param path: path of the experiments :param save_file: path if you want to save data as csv (Default None) :param path_json: setting file ...
ccada8ba540f61b04e37f18d3fd3ffbe7b4e893e
4,970
from typing import Union from typing import Iterator def tile_grid_intersection( src0: DatasetReader, src1: DatasetReader, blockxsize: Union[None, int] = None, blockysize: Union[None, int] = None ) -> tuple[Iterator[Window], Iterator[Window], Iterator[Window], Affine, int, int]: """Generate tiled ...
847092e1a02ed446d7873658340d578248b1e80c
4,971
def etapes_index_view(request): """ GET etapes index """ # Check connected if not check_connected(request): raise exc.HTTPForbidden() records = request.dbsession.query(AffaireEtapeIndex).filter( AffaireEtapeIndex.ordre != None ).order_by(AffaireEtapeIndex.ordre.asc()).al...
a79ec31c3849a7e77528d4607859f9bf77899ffb
4,972
from typing import Optional def brute_force(ciphered_text: str, charset: str = DEFAULT_CHARSET, _database_path: Optional[str] = None) -> int: """ Get Caesar ciphered text key. Uses a brute force technique trying the entire key space until finding a text that can be identified with any of our languages. ...
9b23b4b5068dd36345d6aa43f71bd307f8b24e0c
4,973
def SqZerniketoOPD(x,y,coef,N,xwidth=1.,ywidth=1.): """ Return an OPD vector based on a set of square Zernike coefficients """ stcoef = np.dot(zern.sqtost[:N,:N],coef) x = x/xwidth y = y/ywidth zm = zern.zmatrix(np.sqrt(x**2+y**2),np.arctan2(y,x),N) opd = np.dot(zm,stcoef) return opd
4243f2c4106d5de0b7f6966cfb3244644beff100
4,974
import random def build_voterinfo(campaign, state): """Render a tweet of voting info for a state""" state_info = campaign.info_by_state[state] num_cities = len(state_info[CITIES]) assert num_cities == len(set(state_info[CITIES])), f"Duplicate entries in CITIES for {state}." city_ct = num_cities effective_lengt...
a3f6b7aea9b84174ed1e825cacb38966e099c7eb
4,975
def train_model(training_df, stock): """ Summary: Trains XGBoost model on stock prices Inputs: stock_df - Pandas DataFrame containing data about stock price, date, and daily tweet sentiment regarding that stock stock - String representing stock symbol to be used in training Return value: T...
be28e84c6796bd002217ab56c85958b52fbc199c
4,976
import os def find_ext(files, ext): """ Finds all files with extension `ext` in `files`. Parameters ---------- files : list List of files to search in ext : str File extension Returns ------- dict A dictionary of pairs (filename, full_filename) """ ...
62f64b10ef00290dfbe2feae5d8a7d92ced4a1b0
4,977
def create_test_node(context, **kw): """Create and return a test Node object. Create a node in the DB and return a Node object with appropriate attributes. """ node = get_test_node(context, **kw) node.create() return node
21ff9931a7c6859bbe924014cb3a06b9890f7a63
4,978
def get_physical_id(r_properties): """ Generated resource id """ bucket = r_properties['Bucket'] key = r_properties['Key'] return f's3://{bucket}/{key}'
2cd467d9b1df72a4573d99f7a5d799f9612239c9
4,979
def entity_test_models(translation0, locale1): """This fixture provides: - 2 translations of a plural entity - 1 translation of a non-plural entity - A subpage that contains the plural entity """ entity0 = translation0.entity locale0 = translation0.locale project0 = entity0.resource.pr...
36c6962a69d241e395af1c7ebe16271dcaed975d
4,980
def paris_topology(self, input_path): """Generation of the Paris metro network topology Parameters: input_path: string, input folder path Returns: self.g: nx.Graph(), Waxman graph topology self.length: np.array, lengths of edges """ adj_file = open(input_path + "adj.dat", ...
9f81e111cfe9adf265b9a3aa58390935b752f242
4,981
def _rescale(vector): """Scale values in vector to the range [0, 1]. Args: vector: A list of real values. """ # Subtract min, making smallest value 0 min_val = min(vector) vector = [v - min_val for v in vector] # Divide by max, making largest value 1 max_val = float(max(vector)...
0091deb65c67ef55b2632ac8d5ff8a15b275d12e
4,982
from datetime import datetime def validate_travel_dates(departure, arrival): """It validates arrival and departure dates :param departure: departure date :param arrival: arrival date :returns: error message or Boolean status """ date_format = "%Y-%m-%dT%H:%M:%SZ" status = True error_m...
41759684517daece729ba845b7afc80c6e6b01ea
4,983
def xmatch_arguments(): """ Obtain information about the xmatch service """ return jsonify({'args': args_xmatch})
393e74df6900b8c4ed6f0eac82c162a7287a9b6d
4,984
def rosenbrock_func(x): """Rosenbrock objective function. Also known as the Rosenbrock's valley or Rosenbrock's banana function. Has a global minimum of :code:`np.ones(dimensions)` where :code:`dimensions` is :code:`x.shape[1]`. The search domain is :code:`[-inf, inf]`. Parameters --------...
5d89e22fde50032175b69f36a4c0031bfc07c2bb
4,985
def isHdf5Dataset(obj): """Is `obj` an HDF5 Dataset?""" return isinstance(obj, h5py.Dataset)
b674106e05d5f10585b58d246654987f174d2048
4,986
import numpy def writing_height(sample_wrapper, in_air): """ Returns writing height. :param sample_wrapper: sample wrapper object :type sample_wrapper: HandwritingSampleWrapper :param in_air: in-air flag :type in_air: bool :return: writing height :rtype: float """ # Get the o...
fce6c0abcc65484088278eddd3bb77541725934c
4,987
def simplify_index_permutations(expr, permutation_operators): """ Performs simplification by introducing PermutationOperators where appropriate. Schematically: [abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij] permutation_operators is a list of PermutationOperators to consider. If ...
3a72459c9f9ee9e1f0f030fa96f5a38c0a1985c0
4,988
from typing import Set from typing import Any from typing import Tuple def get_classification_outcomes( confusion_matrix: pd.DataFrame, classes: Set[Any], class_name: str, ) -> Tuple[int, int, int, int]: """ Given a confusion matrix, this function counts the cases of: - **True Positives** : c...
c8d84aa5d84e9405539fa40cd05101ac84eda871
4,989
def points_in_convex_polygon_3d_jit(points, polygon_surfaces, ): """check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of...
b3834ec647fcb6b156f57a36e11dd5dd22bec1d9
4,990
def _get_spamassassin_flag_path(domain_or_user): """ Get the full path of the file who's existence is used as a flag to turn SpamAssassin on. Args: domain_or_user - A full email address or a domain name """ domain = domain_or_user.lower() user = False if '@' in domain: u...
e29055f2cbe81dd7ad2083f5bfdc46d02b354dba
4,991
def format(number): """Reformat the passed number to the standard format.""" number = compact(number) return '-'.join((number[:3], number[3:-1], number[-1]))
90ad8360ef773a9386a122d3f44870a6b371d370
4,992
def get_terms(request): """Returns list of terms matching given query""" if TEST_MODE: thesaurus_name = request.params.get('thesaurus_name') extract_name = request.params.get('extract_name') query = request.params.get('term') else: thesaurus_name = request.validated.get('thes...
b6e6810a1858de9da609b2e42b39a933ee9fbb04
4,993
from .. import sim import __main__ as top def createExportNeuroML2(netParams=None, simConfig=None, output=False, reference=None, connections=True, stimulations=True, format='xml'): """ Wrapper function create and export a NeuroML2 simulation Parameters ---------- netParams : ``netParams object`` ...
84b3fb607ab30b17222143c46d839bab087c4916
4,994
from pathlib import Path def load(file: str) -> pd.DataFrame: """Load custom file into dataframe. Currently will work with csv Parameters ---------- file: str Path to file Returns ------- pd.DataFrame: Dataframe with custom data """ if not Path(file).exists(): ...
97ec2656b81bf722fcb34007f00e5abc9b2aa37e
4,995
def better_get_first_model_each_manufacturer(car_db): """Uses map function and lambda to avoid code with side effects.""" result = map(lambda x: x[0], car_db.values()) # convert map to list return list(result)
8969c23bfe4df2b1c164dca6c4f929a62de5ba2a
4,996
import os import inspect import logging def configurable_testcase(default_config_function): """Decorator to make a test case configurable.""" def internal_configurable_testcase(testcase): _log_testcase_header(testcase.__name__, testcase.__doc__) def wrapper_function(func, name, config, generate_default...
30082e0fa793ea9d45af8b2913eef95fc7dd7856
4,997
from collections import Iterable def _is_scalar(value): """Whether to treat a value as a scalar. Any non-iterable, string, or 0-D array """ return (getattr(value, 'ndim', None) == 0 or isinstance(value, (str, bytes)) or not isinstance(value, (Iterable,)))
725aa4a6002146ecb3dca3a17faa829e213cb3f7
4,998
def copy_random(x, y): """ from 2 randInt calls """ seed = find_seed(x, y) rand = JavaRandom(seed) rand.next() # this will be y so we discard it return rand
f1a1019ed7f012d83edca77ba3c7ccd2a806ee01
4,999