content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def forward_pfb(timestream,nchan=NCHAN,ntap=NTAP,window=h.sinc_hanning):
"""Performs the Chime PFB on a timestream
Parameters
----------
timestream : np.array
Timestream to process
nchan : int
Number of frequencies we want out (probably should be odd
number because of Ny... | 61,100 |
def get_jsrun_launcher(num_procs, args):
"""Return the base launch command using jsrun."""
ppn, num_nodes = get_ppn_and_nodes(num_procs, args.procs_per_node)
return ['jsrun',
'--nrs', str(num_nodes),
'--rs_per_host', '1',
'--tasks_per_rs', str(ppn),
'--cpu_per... | 61,101 |
def generation_solution(villes):
"""
With the cities as a list, we generate a random permutation of this list
to create a solution
"""
return np.random.permutation(villes) | 61,102 |
def main(src, txt, debug, emit=lambda s:sys.stdout.write(s+'\n')):
"""
src is assembly language code for the meta-ii machine.
txt is the input text on which to run the meta-ii code.
emit is function to call for output strings
"""
code,labels = [],{}
# first pass extracts code and labels fro... | 61,103 |
def add_card_types(card_list, accepted_labels):
"""
Adds a new field named "type" to each card in the given list. The type will be a list
of all label names in that card that appear in the list of provided acceptable labels.
If the card has no labels or none match, the type field will be an empty list.
... | 61,104 |
def get_config(config_path: str) -> Dict[str, Any]:
"""Parse the JSON config file at the given path and return the `dict`."""
with open(config_path, 'r') as config_file:
return yaml.load(config_file) | 61,105 |
def dis_gamma_ll(ab, k, theta):
"""Log-likelihood of a discrete gamma distribution
k - shape parameter
theta - scale parameter
Normalization constant is calculated based on a cuf-off (currently set at 10**5)
"""
cutoff = 1e5
gamma_sum = sum(stats.gamma.pdf(range(1, cutoff + 1), k, ... | 61,106 |
def parse_input(input_file):
"""
Parse the input with a dict reader and returns tthe data aggregated per taxid
"""
data_per_taxid = defaultdict(list)
data_per_taxid_and_assembly = defaultdict(list)
with open(input_file) as open_file:
reader = csv.DictReader(open_file, delimiter='\t')
... | 61,107 |
def generate_common_dict(d1, d2):
"""Generate a dictionary by combining d1 and d2
Args:
d1 (list): a list of words
d2 (list): a list of words
Returns:
Counter: combined dictionary
"""
word1 = d1.copy()
word1.extend(d2)
c = Counter(i for i in word1)
retu... | 61,108 |
def add_body_to_combine_request(combine_call, body, body_toggle, info_about_combine_blocks):
"""
Add the parameters of body to the combine request
(if the combine was not called in body element and it has some parameters)
"""
if body_toggle == 'indexes':
list_of_indexes = []
for idx... | 61,109 |
def metrics(
metrics, has_script=None, has_capability=None, matcher=None, access=None, volatile=True
):
"""
Decorator to use inside get_metrics script to denote functions
which can return set of metrics
@metrics(["Metric Type1", "Metric Type2"])
def get_custom_metrics(self, metrics):
..... | 61,110 |
def build_dummy_sequential_net(fc_layer_params, action_spec):
"""Build a dummy sequential network."""
num_actions = action_spec.maximum - action_spec.minimum + 1
logits = functools.partial(
tf.keras.layers.Dense,
activation=None,
kernel_initializer=tf.random_uniform_initializer(
minva... | 61,111 |
def just_the_name(path):
"""Remove extension and path"""
return remove_extensions(os.path.basename(path)) | 61,112 |
def localshop_install():
"""Installs localshop in preexisting virtualenv"""
with prefix(activate_virtualenv):
local("pip install localshop") | 61,113 |
def test_regex_is_not_applied_to_attribute():
"""Test that we don't lose data when expression by pattern fails."""
input_data: dict = {'game': '1. d4 d5'}
config = Attribute(**{
'name': 'moves',
'data_fetchers': [
{
'path': ['game'],
'regex': {
... | 61,114 |
def get_view():
""" Responds with the form for the example"""
return render_template(
"eg001_get_monitoring_data.html",
title="Get monitoring data",
source_file=path.basename(path.dirname(__file__)) + "/controller.py",
source_url=DS_CONFIG["monitor_github_url"] + path.basename(... | 61,115 |
def calc_process_time(t1, t2):
"""Calculates difference between times
Args:
t1 (float): initial time
t2 (float): end time
Returns:
str: difference in times
"""
return str(t2 - t1) | 61,116 |
def mechanism_exponential_discrete_gumbel(x, candidates, epsilon, scorer, sensitivity, monotonic=False):
"""Return an `epsilon`-DP sample from the set of discrete `candidates`.
The sampling probabilities is constructed by running `scorer` on `x` for each candidate.
:param x: 1d dataset for which to release... | 61,117 |
def setupStderrLogger(logger, level, formatter=None):
"""configure logging to stderr. Logger maybe a logger, logger name, or
None for default logger, returns the logger."""
return setupStreamLogger(logger, sys.stderr, _convertLevel(level), formatter) | 61,118 |
def percentile(N: Iterable, percent: int):
"""
Find the percentile of a list of values.
Stolen from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
if not N:
raise ValueError('N must be non-empty iterable')
if not (0 < percent < 100 and type(percent)... | 61,119 |
def connect_socket_with_backoff (address, port, max_backoff_seconds=32):
"""
Attempt to connect to the given address and port.
If the connection attempt fails, exponentially back off, up to the maximum.
return the connected socket, or raise an exception if the connection
was unsuccessful by the time the max... | 61,120 |
def application():
"""Set up global front-end app for functional tests
Initialized once per test-run
"""
application = create_api_app(env_level="TEST")
application.test_client_class = ApiClient
application.response_class = ApiResponse
return application | 61,121 |
def _initialize_options(img_stack,get_darkfield,options):
""" Initialize optimization options
This function modifies the default OPTIONS using information about the images to be processed.
Inputs:
img_stack - A numpy matrix where images are concatenated along the 3rd dimensions
get_darkfie... | 61,122 |
def find_file_with_magic(data: bytes) -> Optional[str]:
"""Find files with the help of magic numbers library"""
res: Text
if len(data) < 8:
return None
try:
res = magic_handle.from_buffer(data)
# try again with a potential padding byte removed
if res == "data":
... | 61,123 |
def test_draw_polygon_cv2_smokescreen():
"""
Test ability to fill a nonconvex polygon.
We don't verify the rendered values since this requires
scanline rendering computation to find the polygon's
exact boundaries on a rasterized grid.
"""
UINT8_MAX = 255
img_w = 40
... | 61,124 |
def read_info_from_data_file(file_path, step_timelength, time_begin, time_end, raw_input, samplerate):
"""
Detect if input is binary or wav then use the appropriate method
"""
if raw_input:
return read_info_from_bin(file_path, step_timelength, time_begin, time_end, samplerate)
else:
... | 61,125 |
def copy_from_aiida(name: str, node, dst: Path):
"""
Copy objects from aiida repository.
:param name: The full name (including the parent path) of the object.
:param node: Node object for which the files in the repo to be copied.
:param dst: Path of the destination folder.
This is a recursive ... | 61,126 |
def _lower(obj: Any) -> str:
"""Helper for the sort filter"""
try:
return str(obj).lower()
except AttributeError:
return "" | 61,127 |
def train_ubm_and_extract_pivectors(env, experiment_paths):
"""
Train UBM for pivector extraction
and adapt GMMs for the given experiments
"""
ubm_path = UBM_PATH.format(env)
os.makedirs(os.path.dirname(ubm_path), exist_ok=True)
# Train UBM if one does not exist
if not os.path.isfile(ubm... | 61,128 |
def update_cupcake(cupcake_id):
"""Update cupcake from data in request. Return updated data.
Returns JSON like:
{cupcake: [{id, flavor, rating, size, image}]}
"""
data = request.json
cupcake = Cupcake.query.get_or_404(cupcake_id)
cupcake.flavor = data['flavor']
cupcake.rating = d... | 61,129 |
def fo_match(pat,inst,freesyms,constants):
""" Compute a partial first-order match. Matches free FO variables to ground terms,
but ignores variable occurrences under free second-order symbols. """
if il.is_variable(pat):
if pat in freesyms and all(x in constants for x in lu.variables_ast(inst)):
... | 61,130 |
def tune_te(
tensors: List[Tensor],
target: Union[str, Target],
config: SearchStrategyConfig,
work_dir: str,
*,
task_name: str = "main",
builder: Optional[Builder] = None,
runner: Optional[Runner] = None,
database: Optional[Database] = None,
cost_model: Optional[CostModel] = None... | 61,131 |
def test_cholesky_solver(n: int, lower: bool, dtype):
"""
Feature: ALL TO ALL
Description: test cases for cholesky solver [N,N]
Expectation: the result match scipy cholesky_solve
"""
a = create_sym_pos_matrix((n, n), dtype)
b = onp.ones((n, 1), dtype=dtype)
tensor_a = Tensor(a)
ten... | 61,132 |
def test_is_safe_to_wait():
""" It's safe to wait for a secret while there are more than reveal timeout
blocks until the lock expiration.
"""
expiration = 40
# expiration is in 30 blocks, 19 blocks safe for waiting
block_number = 10
reveal_timeout = 10
assert mediator.is_safe_to_wait(ex... | 61,133 |
def test_stride_DCA(lorenz_dataset):
"""Check that deterministic and random strides work for DCA.
"""
X = lorenz_dataset
model = DCA(T=1)
model.estimate_data_statistics(X)
ccms1 = model.cross_covs.numpy()
model = DCA(T=1, stride=2)
model.estimate_data_statistics(X)
ccms2 = model.cro... | 61,134 |
def classify_directory(classifier, test_dir, train_dir='train/'):
"""
Classify all images in a directory using an arbitrary sklearn classifier.
Saves results to results/ directory.
"""
# XXX: This is here if the classifier needs to be trained from scratch
#print("Preparing training data...")... | 61,135 |
def contain(descriptors, target_descriptor):
"""Check if the target descriptor is in the descriptors."""
for descriptor in descriptors:
if edit_distance(descriptor, target_descriptor) < 1e-5:
return True
return False | 61,136 |
def test_fitter_AuxTel_rigid_perturbation():
"""Roundtrip using danish model to produce a test image of rigid-body
perturbed AuxTel transverse Zernikes. Model and fitter run through the same
code.
"""
# Nominal donut mode for AuxTel is to despace M2 by 0.8 mm
fiducial_telescope = batoid.Optic.f... | 61,137 |
def setup_dirs(pickle_path, labels):
"""Some error handling for creating the directories if they don't already exist"""
if not os.path.isdir(pickle_path):
os.makedirs(pickle_path)
for label in labels:
file_path = pickle_path + 'data/' + label
if not os.path.isdir(file_path):
... | 61,138 |
def create_page_object(page_cls, response):
"""
Create PageObject instances, resolving all constructor dependencies.
"""
# find out what resources are available
provider_funcs = {cls: provider(response)
for cls, provider in providers.items()}
# find out which arguments pag... | 61,139 |
def _map_dns_to_ec2s(profile_name="default"):
"""Map all DNS records found in the ``InfraNode`` table via ELBs to EC2 instances.
Creates records in the InfraNode table of the following kinds:
- ``aws.elb.dns`` - Public DNS of an Elastic Load Balancer (ELB and ELBv2)
- ``aws.ec2.dns.private`` - Private... | 61,140 |
def create_generic_belle_isle_clear(base_time, out_file):
"""
"""
fp_out = open(out_file, "w")
vehicle_id_list = ["ncar1", "ncar2", "ncar3", "ncar4"]
lat_long = [(42.336412,-83.000058), (42.336592,-82.999269), (42.336941,-82.997649), (42.337136,-82.996683)]
obs_time = time.strftime("%Y%m%d%H%M... | 61,141 |
def remap(im, coords):
"""
Remap an RGB image using the given target coordinate array.
If available, OpenCV is used (faster), otherwise SciPy.
:type im: ndarray of shape (h,w,3)
:param im: RGB image to be remapped
:type coords: ndarray of shape (h,w,2)
:param coords: target coordin... | 61,142 |
def epoch_time(offset=0):
"""Returns time since epoch."""
try:
return time.time() - offset
except TypeError as e:
LOG.error("Couldn't reduce offset, %s, from epoch time, ex %s.",
offset, e)
return time.time() | 61,143 |
def init_device(n=0):
"""
Initialize a GPU device.
Initialize a specified GPU device rather than the default device
found by `pycuda.autoinit`.
Parameters
----------
n : int
Device number.
Returns
-------
dev : pycuda.driver.Device
Initialized device.
"""
... | 61,144 |
def _visit_local(gen_sym, node, to_mangle, mangled):
"""
Replacing known variables with literal values
"""
is_name = type(node) == ast.Name
node_id = node.id if is_name else node.arg
if node_id in to_mangle:
if node_id in mangled:
mangled_id = mangled[node_id]
else... | 61,145 |
def pathtoPath(svg):
"""Converts SVG("path", d="...") into Path(d=[...])."""
if not isinstance(svg, SVG) or svg.t != "path":
raise TypeError, "Only SVG <path /> objects can be converted into Paths"
attr = dict(svg.attr)
d = attr["d"]
del attr["d"]
for key in attr.keys():
if not i... | 61,146 |
def zenodo_doi_metric(mocker, zenodo_doi_index_html, zenodo_doi_june_html):
"""Fixture for COD records metric instance."""
prefix = '10.5281'
def load_index_data(self, url):
return zenodo_doi_index_html
def load_stats_data(self, url):
return zenodo_doi_june_html
mocker.patch.objec... | 61,147 |
def assert_valid_codeobj(allowed_codes, code_obj, expr):
""" Asserts that the provided code object validates against the bytecode
and name constraints.
Recursively validates the code objects stored in its co_consts in case
lambdas are being created/used (lambdas generate their own separated code
ob... | 61,148 |
def convert_shape_to_list(shape):
"""
Convert shape(list, tuple, variable) to list in imperative mode
"""
if isinstance(shape, (list, tuple)):
shape = list(
map(lambda x: x.numpy()[0] if isinstance(x, Variable) else x,
shape))
else:
shape = shape.numpy().a... | 61,149 |
def get_longest_key(tuple_of_tuples):
"""
Why is this needed? Because sometimes we want to know how long a CharField
should be -- so let's have it as long as the longest choice available.
(For example, when we have a radio button and we want to store a single value.)
INPUT=(
('short', 'blah... | 61,150 |
def mass_within_region(gals, x_bound, y_bound):
"""
Calculate the total mass and number of galaxies within a specified region.
Parameters
----------
gals: list of ``Galaxy`` class instances.
Galaxies that we're calculating the mass for.
x_bound, y_bound: [float, float]
The min... | 61,151 |
def submit_and_download(report_request, api_client, data_dir, data_file, overwrite_if_exists, decompress: bool = False):
"""
Submit the download request and then use the ReportingDownloadOperation result to
track status until the report is complete.
Id the file already exists, do nothing
Args:
... | 61,152 |
def getSNR( flmfile, wsig=100, wnoise=500, plot=False ):
"""
Estimates the average S/N ratio for a spectrum.
<wsig>: the smoothing window used to estimate the signal (A)
<wnoise>: the smoothing window used to average the noise (A)
"""
d = np.loadtxt( flmfile )
d = d[ ~np.isnan(d[:,1]) ]
... | 61,153 |
def splitCentersByStrips(centers, splitter_array):
"""
Split list of note centers by strip.
"""
# Sort by rows
row_sorted_centers = sorted(centers, key=lambda x: x[1])
# Split notehead into strips
strips = {}
current_offset = 0
counter = 0
for i in range(1, len(splitt... | 61,154 |
def uploaded_images_list(skill_id: str, oauth_token: str, raw: bool = False) -> Union[dict, requests.Response]:
"""
Get uploaded skill images
:param skill_id: alice skill id
:param oauth_token: oauth token
:param raw: return raw api response
:return: uploaded image id or raw response
"""
... | 61,155 |
def save(corpus,dataFormat,path):
"""
Save a corpus to a directory
:param corpus: The corpus of documents to save
:param dataFormat: Format of data to save (only 'standoff', 'biocxml' and 'pubannotation' are supported currently)
:param path: Path where corpus should be saved. Must be an existing directory for 's... | 61,156 |
def test_build_archive_name():
"""Test building the archive name of a specific software release."""
assert packagerbuddy._build_archive_name("software", "version", ".ext") == "software-version.ext" | 61,157 |
def test_encrypt_load_header():
"""Test that StreamEncryptor can extract header without reading plaintext."""
# Using a non-signed algorithm to simplify header size calculation
algorithm = aws_encryption_sdk.Algorithm.AES_256_GCM_IV12_TAG16_HKDF_SHA256
key_provider = fake_kms_key_provider(algorithm.kdf_... | 61,158 |
def make_trip_geometry(start_station_num: int, end_station_num: int):
"""
Takes 2 stations and returns a linestring between them.
"""
start_point = find_station_geo(start_station_num)
end_point = find_station_geo(end_station_num)
try:
return LineString((start_point, end_point))
exc... | 61,159 |
def wiener(frame_matrix, hop_size, window_type, noise_est, original_signal_length):
"""
Return the enhacned signal after Wiener filtering
"""
# Setting initial variables
frame_length = len(frame_matrix)
fftlen = int(np.around(frame_length / 2) + 1)
hwin = getWindow(frame_length, win... | 61,160 |
def update_user():
"""
@api {post} /users/:id Updates a user
@apiVersion 1.0.0
@apiName update_user
@apiGroup User
@apiParam {Number} id The user's id
@apiParam {String} first_name The first name of the User.
@apiParam {String} last_name The last name of... | 61,161 |
def check_upgrade_allowed(manifest_info: PlatformInformation,
platform_info: PlatformInformation,
dispatcher_callbacks: DispatcherCallbacks) -> None:
"""Check if manifest vendor name matches platform bios vendor and
manifest release date is higher than bios re... | 61,162 |
def normalize_to(target, source=1):
"""
Multiplies the target so that its total content matches the source.
:param target: a tensor
:param source: a tensor or number
:return: normalized tensor of the same shape as target
"""
return target * (math.sum(source) / math.sum(target)) | 61,163 |
def main(in_file, out_file):
"""
The main program reads the input file, processes the calculation
and writes the output file
Args:
in_file: input file path
out_file: output file path
"""
# Read File
days_scan, book_score_list, lib_books, lib_supdays, lib_daily_ships, lib_boo... | 61,164 |
def get_category():
"""
Gets a Category
---
tags:
- category
parameters:
- name: name
in: query
schema:
type: string
description: The name of the category.
- name: sponsor
in: query
schema:
type: string... | 61,165 |
def LAHC_search_loop():
"""
Search loop for Late Acceptance Hill Climbing.
This is the LAHC pseudo-code from Burke and Bykov:
Produce an initial solution best
Calculate initial cost function C(best)
Specify Lfa
For all k in {0...Lfa-1} f_k := C(best)
First itera... | 61,166 |
def string_to_nonstopword_counter(text, lowercase=True):
"""Converts string to util.Counter of non-stopwords in text string.
Args:
text: The string to process.
lowercase: Whether the convert the words in the string to lowercase.
Returns:
util.Counter object containing counts of non... | 61,167 |
def calculate_emissions(config, columns=["CO2 [kg]"], overwrite=False):
"""
"""
# with open("config.json") as file:
# config = json.load(file)
datapath = os.path.join(
os.path.expanduser("~"), config["intermediate_data"], "ship_routes"
)
outputpath = os.path.join(
os.pa... | 61,168 |
def start_streamer(stream: Any, handler: Callable[[core_pb2.Event], None]) -> None:
"""
Convenience method for starting a grpc stream thread for handling streamed events.
:param stream: grpc stream that will provide events
:param handler: function that handles an event
:return: nothing
"""
... | 61,169 |
def plot_bad_chs_group_summary(bad_ch_info, ch_names):
"""
Makes a summary plot of bad channels across all subjects including:
- heatmap of channels by subject indicating if channel was marked bad
- Bad channel % for each participant
- % of subjects with channel marked bad for each subje... | 61,170 |
def submit_entry(contest, code):
"""submits an entry to the submission.
"""
return _update_sketch(contest, code, action="submit") | 61,171 |
def gndvi(image):
"""
Takes an image and processes it using GNDVI. Returns a single channel grayscale scaled output.
:return:
"""
# using array slicing to split into channel
green = image[:, :, 1].astype(np.float32)
NIR = image[:, :, 2].astype(np.float32)
imgOut = (NIR - green) / (NIR +... | 61,172 |
def read_status(path="status.json"):
"""
opens the written status file in case of restarts
that we do not start with an empty status file.
If there is no file, create empty status dict
:path: str
:returns: dict
"""
try:
with open(path, "r") as jsonfile:
status = json.... | 61,173 |
def wipe_screen(*_):
"""
A crude hack to repaint the whole screen. I didnt immediately
see anything to acheive this in the MainLoop methods so this
will do, I suppose.
"""
app.loop.stop()
call("clear", shell=True)
app.loop.start() | 61,174 |
def get_my_ip():
"""Obtain external visible IP address"""
url='https://api.myip.com'
response = urllib.request.urlopen(url)
if response.status != 200:
raise Exception(f'Unable to obtain this hosts public IP, got HTTP status {response.status} from {url}')
doc = json.load(response)
return... | 61,175 |
def create_airport(
id=None,
type=None,
altitude=None,
name=None,
city=None,
municipality=None,
region=None,
country=None,
iata=None,
icao=None,
ident=None,
local_code=None,
latitude=None,
longitude=None,
):
"""
Get or create an Airport.
:param id:
... | 61,176 |
def resource(pool):
"""A Resource instance."""
r = pool.get_resource()
yield r
r.close() | 61,177 |
def tags_match(blacklist_entry, tags):
"""
Returns true if the filename in <blacklist_entry> contains a tag in <tags>.
"""
try:
blacklisted_file = blacklist_entry.split()[0]
except IndexError:
# Empty line
return False
try:
_, tag, _, _ = datman.scanid.parse_file... | 61,178 |
def get_rawdir():
""" Returns the standard raw data directory """
workdir = get_workdir()
rawdir = ut.truepath(join(workdir, '../raw'))
return rawdir | 61,179 |
def write_ellipsoid(sz, loc, mat, cut_neg=[-1, -1, -1], cut_pos=[1, 1, 1], cut_global=[1,1,1], orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0):
"""
@brief Writes an ellipsoid.
@param sz [size u_vec 1, size uvec 2, size uvec 3]
@param loc locati... | 61,180 |
def get_json_for_r_log_entry(req, x_set):
"""Returns a dict used to match r_log entries returned through API."""
return {
"request": req.to_dct(),
"x_set": x_set
} | 61,181 |
def parse_segment(input_seg):
"""
Creates an asrtoolkit segment object from an input gk segment
:param: input_seg: dict (segment-level dict: input_data['segments'][i]
-> dict with keys 'channel', 'startTimeSec' etc mapping to attributes
:return: asrtoolkit segment object
"""
extracted_dict... | 61,182 |
def test_locally_available_editable_package_is_not_archived_in_cache_dir(
pip_conf, tmpdir, runner
):
"""
piptools will not create an archive for a locally available editable requirement
"""
cache_dir = tmpdir.mkdir("cache_dir")
fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_with_de... | 61,183 |
def test_interval_intersection():
"""
This function runs a number of tests of the interval_intersection function.
If it works ok, you will just see the output ("all tests passed") at
the end when you call this function; if some test fails, there will
be an error message.
"""
assert interval... | 61,184 |
def read_vcf(input_file,output_file=None):
"""
Usage: [arg1]:[Input File] [arg2]:[Output File - Optional Parameter (The return dataframe will be written to csv if output path is specified)]
Description: Reads the vcf file and returns the name, phone numbers and email as DataFrame
Returns: [Dataframe of ... | 61,185 |
def _get_sub_types_of_compositional_types(compositional_type: str) -> tuple:
"""
Extract the sub-types of compositional types.
This method handles both specification types (e.g. pt:set[], pt:dict[]) as well as python types (e.g. FrozenSet[], Union[]).
:param compositional_type: the compositional type ... | 61,186 |
def spimi(CHUNK_SIZE, out_dict, out_postings):
"""==================================================================
open up every file
opening file DOES NOT loading file contents into memory
=================================================================="""
# Get disk directory to load in block... | 61,187 |
def test_find_redundant_constraints(verbose=False, show_timing=True, n_runs=1000):
"""Tested against results of LP method in section 3.2 of [1].
[1] S. Paulraj and P. Sumathi, "A comparative study of redundant
constraints identification methods in linear programming problems,"
Math. Probl. Eng., vol. 2... | 61,188 |
def find_python(version, path=None, required=True):
"""
:type version: str
:type path: str | None
:type required: bool
:rtype: str
"""
version_info = tuple(int(n) for n in version.split('.'))
if not path and version_info == sys.version_info[:len(version_info)]:
python_bin = sys.... | 61,189 |
def unsort(list):
"""Return a copy of unsorted list"""
new_list = []
for chance in range(len(list)):
char = random.choice(list)
list.remove(char)
new_list.append(char)
return new_list | 61,190 |
def sample_account(user, **params):
"""Create and return a sample customer"""
defaults = {}
defaults.update(params)
return Account.objects.create(user=user, **defaults) | 61,191 |
def gitupdate(request):
"""
DEPRECATED
This could be reinstated by changing the Git directory seen below.
"""
if request.method == 'POST':
try:
g = git.cmd.Git("/home/ubuntu/seads-git/ShR2/")
g.pull()
return HttpResponse(status=200)
except: re... | 61,192 |
def display_sharpe_ratio(
portfolio: portfolio_model.Portfolio,
risk_free_rate: float,
export: str = "",
):
"""Display sharpe ratio for multiple periods
Parameters
----------
portfolio: Portfolio
Portfolio object with trades loaded
risk_free_rate: float
Risk free rate va... | 61,193 |
def download_file(session, file_id, file_name, request_headers):
"""Download BaseSpace file."""
response = make_get_request(
session,
get_api_file_content_url(file_id),
request_headers,
stream=True
)
try:
with open(file_name, 'wb') as f:
chunk_size = ... | 61,194 |
def _coverage_loss(attn_dists, padding_mask):
"""
Calculates the coverage loss from the attention distributions.
args:
attn_dists: the attention distributions for each decoder timestep. A list of length
max_dec_steps containing shape (batch_size, attn_length)
padding_mask: sha... | 61,195 |
def alpha_083(code, end_date=None, fq="pre"):
"""
公式:
(-1 * RANK(COVIANCE(RANK(HIGH), RANK(VOLUME), 5)))
Inputs:
code: 股票池
end_date: 查询日期
Outputs:
因子的值
"""
end_date = to_date_str(end_date)
func_name = sys._getframe().f_code.co_name
return JQDataClient.insta... | 61,196 |
def make_hop_info_from_url(url, verify_reachability=None):
"""
This is a factory function to build HopInfo object from url.
It allows only telnet and ssh as a valid protocols.
Args:
url (str): The url string describing the node. i.e.
telnet://username@1.1.1.1. The protocol, username... | 61,197 |
def sample_q0(V, lmd, d0, z0):
"""
Inputs:
V: double (n_dofs,n_dofs) eigenvectors of covariance matrix
lmd: double, (n_dofs,) eigenvalues of covariance matrix
d0: int, dimension of the low dimensional subspace
z0: int, (d0,n_sample) Gaussian random... | 61,198 |
def question_uploader_2(root_path, file_name="questions.csv"):
"""
This is the uploader for the second data set collected by Isaac
The root path contains "question.csv" file.
headers are:
image name, text, choice 1, choice 2, ... , choice 5, answer, ... , is multiple choice
:param root_path:
... | 61,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.