content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def p_propiedadescol(p):
"""
propiedadescol : CORCHETEA NOT NULL CORCHETEC
| CORCHETEA PRIMARY KEY CORCHETEC
| CORCHETEA REFERENCES id CORCHETEC
"""
p[0] = p[1] + p[2] + " " + p[3] + p[4] | 67,100 |
def stationary_fixed_points(history):
"""Take the decision if the point is stationary. It runs for different
orders.
Parameters
----------
sequence: np.ndarray
the sequence information.
Returns
-------
stationary: boolean
if the sequence is in a stationary point.
fi... | 67,101 |
def test___bytes__(manifest_data: TypingManifestData):
"""Test __bytes__ pass-through for different variants."""
assert bytes(manifest_data["manifest"]) == manifest_data["bytes"] | 67,102 |
def WRAP(r, Hr, wrapname):
"""Wrapping
(macro)
e.g. WRAP(r, ['D', 'E', 'F'], 'X') (or r.wrap(['D', 'E', 'F'], 'X')
(Tutorial D equivalent: r WRAP { D, E, .., F } AS X
"""
return r.extend([wrapname], lambda t:{wrapname:t.project(Hr)}).remove(Hr) | 67,103 |
def record(ctx, port, log_dir, header_routing, specs_dir, mode, daemon):
"""
Record HTTP traffic from a reverse proxy.
"""
if ctx.invoked_subcommand is None:
ctx.forward(start_record) | 67,104 |
def test_scalar_dewpoint_from_relative_humidity():
"""Test dewpoint_from_relative_humidity with scalar values."""
td = dewpoint_from_relative_humidity(10.6 * units.degC, 0.37)
assert_almost_equal(td, 26. * units.degF, 0) | 67,105 |
def clean_sequence_data_from_outliers(
record: pd.Series, input_path: str, output_path: str
):
"""
:param record: pandas row representative of a cluster of species sequences
:param input_path: path to the aligned sequences that include outliers
:param output_path: path to create in aligned sequences... | 67,106 |
def is_empty(iterable):
"""
This filter checks whether the given iterable is empty.
:param iterable: The requested iterable
:type iterable: ~collections.abc.Iterable
:return: Whether or not the given iterable is empty
:rtype: bool
"""
return not bool(iterable) | 67,107 |
def odometer(syms=range(10), rolls=2, start=0, stop=None):
"""
Logic exercise. For each roll, if the previous roll rolled over,
roll the roll.
The range of "values" is defined by syms, it is a list with any
objects. Yield all possible combinations being len(syms)**rolls.
Examples:
>>> Hex... | 67,108 |
async def delete_snapshot(request):
"""delete a snapshot
:Example:
curl -X DELETE http://localhost:8081/fledge/snapshot/plugins/1554204238
When auth is mandatory:
curl -X DELETE http://localhost:8081/fledge/snapshot/plugins/1554204238 -H "authorization: <token>"
"""
try:
... | 67,109 |
def order_flag_field(key, value):
"""Return the fields key value pairs in the correct order (name (str), bit (int)).
Args:
key (int/str): Bit int or name.
value (str/int): Name or bit int.
Returns:
field (tuple): (name (str), bit (int))
"""
bit, name = order_flag_options(ke... | 67,110 |
def genFullHouserData():
"""Удаление не актуальных записей из индекса"""
for event, node in doc:
if event == \
pulldom.START_ELEMENT and node.tagName \
== address.TAG:
yield {
"_index": address.IndexName,
"_type": "_doc",
... | 67,111 |
def priprav_bs(url, params):
"""BeautifulSoup z celé stránky
url: str
params: dict
Vrátí: bs4.BeautifulSoup
"""
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0'}
r = requests.get(url, params=params, headers=headers)
r.encoding ... | 67,112 |
def evaporation():
"""
Real Name: b'Evaporation'
Original Eqn: b'Max(0,"monthly evaporation -1 Finesk" (Time)*"normal evaporation -1 Finesk"*"surface -1 Finesk"\\\\ )'
Units: b'MCM/Month'
Limits: (None, None)
Type: component
b''
"""
return np.maximum(
0,
monthly_evap... | 67,113 |
def calcAnisousFromModel(model, ):
"""Returns a Nx6 matrix containing anisotropic B factors (ANISOU lines)
from a covariance matrix calculated from **model**.
:arg model: 3D model from which to calculate covariance matrix
:type model: :class:`.ANM`, :class:`.PCA`
.. ipython:: python
from p... | 67,114 |
def write_out(s):
"""
Write a string to ``sys.stdout``, strip escapes if output is a pipe.
:param string s: The title.
"""
write_to(sys.stdout, s) | 67,115 |
def local_opchains_to_MPO(qd, L, lopchains):
"""
Construct Hamiltonian as MPO based on local operator chains,
which are shifted along a 1D lattice.
Args:
qd: physical quantum numbers at each site
L: number of lattice sites
lopchains: local operator chains
Returns:
... | 67,116 |
def solve(ar):
"""
Given an array of 5 integers, return the minimal and maximal sum of 4 out of
5 of the integers.
"""
# Just sort the list of integers in place and take the sum of the first 4
# then the last 4.
ar.sort()
minSum = reduce((lambda x, y: x + y), ar[0:4])
maxSum = reduce... | 67,117 |
def linux_rsync_cache_lru_cleanup(target, path, max_kbytes):
"""Cleanup an LRU rsync cache in a path in the target
An LRU rsync cache is a file tree which is used as an accelerator
to rsync trees in to the target for the POS deployment system;
When it grows too big, we need to purge the files/dirs tha... | 67,118 |
def pytest_generate_tests(metafunc):
"""pyTest Generat Test"""
# called once per each test function
funcarglist = metafunc.cls.params[metafunc.function.__name__]
argnames = sorted(funcarglist[0])
metafunc.parametrize(argnames, [[funcargs[name] for name in argnames] \
... | 67,119 |
def outputRecommend(db, deckList, top=20, dustLimit=-1, decktype=None, cardClass=None, keywordList=[]):
"""Output recommend deck list
Args:
db: The all cards' database
deckList: The recommand deck list to output
top: The number of decks to output
dustLimit: If this value > 0, filter dec... | 67,120 |
def landmark_elastic_registration_warping(
fd: FData,
landmarks: ArrayLike,
*,
location: Optional[ArrayLike] = None,
grid_points: Optional[GridPointsLike] = None,
) -> FDataGrid:
"""Calculate the transformation used in landmark registration.
Let :math:`t_{ij}` the time where the sample ... | 67,121 |
def composite(ifrom, ito, values, comp_length=1.0, min_comp_length=-1.0):
"""
cfrom,cto,clen,cvar,cacum= composite(ifrom, ito, values,
comp_length = 1, min_comp_length=-1)
Composite intervals in a single drillhole. The From-To
intervals may be sorted.
Parame... | 67,122 |
def search_by_stop_id(stop_id):
""" Search for a stop by its stop_id
returns a list that should contain only one stop
"""
return [Stop.from_json(_query("stops/bystop/" + stop_id))] | 67,123 |
def frontend(args):
"""Generate the LLVM bitcode file."""
bitcodes = []
libs = set()
noreturning_frontend = False
def add_libs(lang):
if lang in extra_libs():
libs.add(extra_libs()[lang])
if args.language:
lang = languages()[args.language]
if lang in ['boogie', 'svcomp', 'json']:
... | 67,124 |
def run_tiempo(input_dictionary, prefix_atm_data, sourcefolder, save_name_data, savefolder = None, save_P=True, save_T=True, n_jobs = 30, n_batches = 8,\
obs_time = 3600., grid = .2, x_length_strip = 65536., separation = 1.1326,\
galaxy_on = True, luminosity = 13.7, redshift = 4.43... | 67,125 |
def check_for_overflow(param, before, added_value, after,
checkpoints=None,
file_name=None,
raise_exception=True,
max_value=None):
"""Check for overflow in param accumulation."""
overflow = (abs(after) > max_value) if ma... | 67,126 |
def plot_signals(
signals,
times,
background=None,
highlight=0,
start=None,
stop=None,
ax=None,
):
"""Plot signals vs time using matplotlib."""
from matplotlib import pyplot
signals = numpy.moveaxis(signals, 0, -1)
times = times * 1e9
start, stop = slice(start, stop).ind... | 67,127 |
def poly_regression(sequence, seq_range):
"""Return (x0,y0,x1,y1) of a poly_line fit to a segment of a sequence using polynomial regression"""
y = sequence.values[seq_range[0]:seq_range[1]]
x = np.arange(seq_range[0], seq_range[1])
if len(x) != len(y):
x = np.arange(seq_range[0], seq_range[1])[:... | 67,128 |
async def api_get_donations(g: WalletTypeInfo = Depends(get_key_type)):
"""Return list of all donations assigned to wallet with given invoice
key
"""
wallet_ids = (await get_user(g.wallet.user)).wallet_ids
donations = []
for wallet_id in wallet_ids:
new_donations = await get_donations(wa... | 67,129 |
def get_coverage_data(genes, degnorm_dir, save_dir=None):
"""
Access raw and DegNorm-estimated coverage matrices of a set of genes run through the DegNorm pipeline.
By default, returns two lists:
- raw coverage pandas.DataFrames
- DegNorm-estimated coverage pandas.DataFrames
Each cover... | 67,130 |
async def test_addon_installed(
hass, supervisor, addon_installed, addon_options, set_addon_options, start_addon
):
"""Test add-on already installed but not running on Supervisor."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_ini... | 67,131 |
def yolo_eval(yolo_outputs,
anchors,
num_classes,
origin_image_shape,
max_boxes=20,
score_threshold=.6,
iou_threshold=.5, return_xy=True, lite_return=False):
"""Evaluate YOLO model on given input and return filtered boxes.
只适用于一... | 67,132 |
def combine_matrix_4_128_1_64(input1, input2):
"""
Combine diag matrix.
Args:
input1:tvm.Tensor of type float32 with shape [4,128,128].
input2:tvm.Tensor of type float32 with shape [1,64,64].
Returns:
akg.tvm.Tensor of type float32 with shape [576,576]
"""
batch_dim_1 =... | 67,133 |
def create_bounding_box_global(elements: List[int]) -> int:
"""create a bounding box that is aligned to the global coordinate system.
Args:
elements (List[int]): element IDs
Returns:
int: element ID bounding box
""" | 67,134 |
def test_can():
"""Test that dict key is accessible as a hash ."""
md = MagicDot({"num": 1})
assert md.num.get() == 1 | 67,135 |
def global_order_idxs_to_local(
global_indices: torch.Tensor, x_possible_actions: torch.Tensor, *, ignore_missing=False
) -> torch.Tensor:
"""Convert global order indices to local order indices.
Args:
global_indices: Long tensor [B, 7, S] of indices in ORDER_VOCABULARY
x_possible_actions: L... | 67,136 |
def mapBinStr(x, y, binStr, rCh, gCh, bCh, aCh, mapTable, byteFcn):
"""Map bin contents into image.
Args:
x (int): x coordinate for image (leftmost).
y (int): y coordinate for image (topmost).
binStr (unicode): Contents of bin with image data.
rCh (np array): red channel array.
... | 67,137 |
def instance(*names):
""" Set hosts to be that having the tags Name set to each of the
arguments. Takes multiple names.
"""
cloud = get_current_cloud()
for name in names:
inst = cloud.get_instance_by_name(name)
dns_name = get_hostname_dns(inst)
env.hosts.append(dns_name)... | 67,138 |
def test_rawclient_get_exception():
"""Will test if exception handling is triggered in _base_request."""
rm = requests_mock.Mocker()
with pytest.raises(r.HTTPError):
rm.get(URL, status_code=500)
client = EntsoeRawClient(api_key="test123")
client.query_load(country_code, start, end) | 67,139 |
def read(address, args={}):
"""
Read pool by address
"""
return resource.read(**{**{
'type': 'pool',
'key': address,
}, **args}) | 67,140 |
def test_logger():
"""
Tests the logger
"""
# Move into folder
test_path = resource_filename('phys2bids', 'tests/data')
subprocess.run(f'cd {test_path}', shell=True, check=True)
# Input arguments
test_filename = 'tutorial_file.txt'
test_chtrig = 1
test_outdir = test_path
#... | 67,141 |
def main():
""" See collect_task.collect_task for more on the merge script API. """
logging.info(sys.argv)
parser = argparse.ArgumentParser()
# configuration-name (previously perf-id) is the name of bot the tests run on
# For example, buildbot-test is the name of the android-go-perf bot
# configuration-name... | 67,142 |
def main():
"""
Parse command line arguments and run the URL checks with the data provided.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--details", dest="details", action="store_true",
help="Print details for all categories")
parser.add_... | 67,143 |
def ftpwalk(ftp, top, topdown=True, onerror=None):
"""
Generator that yields tuples of (root, dirs, nondirs).
"""
# Make the FTP object's current directory to the top dir.
ftp.cwd(top)
# We may not have read permission for top, in which case we can't
# get a list of the files the directory ... | 67,144 |
def force_auth_user(app, admin=False):
"""EditFlask-Login's request loader to force a logged in user."""
user = User.query.filter(User.email == str(ADM if admin else USR)).first()
@app.login_manager.request_loader
def load_user_from_request(_request):
return user | 67,145 |
def get_config_data():
"""
Get config data object.
"""
return Config().__data__ | 67,146 |
def chain_bed_intersect(chain, bed):
"""Entry point."""
# get list of chrom: ranges for both
skipped = []
chain_data = parse_chain(chain)
bed_data = parse_bed(bed)
chroms = list(set(bed_data.keys()).intersection(chain_data.keys()))
# to save beds that are skipped at this stage:
only_bed... | 67,147 |
def verify_package(ns, package):
"""
Returns the instances of ``LMI_SoftwareIdentityFileCheck`` representing
files, that did not pass the verification.
:param package: Instance or instance name of
``LMI_SoftwareIdentity`` representing package to verify.
:type package: :py:class:`lmi.shell.L... | 67,148 |
def parse_time(ev_time, datetime_format="%Y%m%d %H%M%S%f", unix=False):
"""Convert EV datetime to a numpy datetime64 object
Parameters
----------
ev_time : str, list
EV datetime string or list of these
datetime_format : str
Format of datestring to be used with datetime strptime
... | 67,149 |
def aes_encrypt(key, data):
"""
AES ECB模式 Pkcs7补全 加密
:param key: 密钥
:param data: 待加密表单
:return:
"""
data = json.dumps(data).replace(' ', '')
# 初始化 AES 加密, ECB模式
encrypter = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# Pkcs7 补全
pad_pkcs7 = pad(data.encode('utf-8'), AES.block_s... | 67,150 |
def class_to_xy(poly, grid_size):
"""
NOTE: Numpy function
poly: [bs, time_steps] or [time_steps]
Returns: [bs, time_steps, 2] or [time_steps, 2]
"""
x = (poly % grid_size).astype(np.int32)
y = (poly / grid_size).astype(np.int32)
out_poly = np.stack([x, y], axis=-1)
return out_pol... | 67,151 |
def fit_polynomial(leftx, lefty, rightx, righty, fit, visualize=False,
img=np.array([], [])):
"""
Fits a 2nd order polynomial to the detected pixels on the lane lines
"""
# Fit a poltnomial x = A*y**2 + B*y + C to the detected lane line pixels
try:
left_fit = np.polyfit(le... | 67,152 |
def preprocess_dataset(args, tokenizer) -> None:
"""
After loading the dataset, pre-process the lowercase and space the eos.
And output the dataset as an Excel file.
"""
# load dataset
trans = load_excel("data/translation_eng_kor(fixed).xlsx", args)
trans["번역문"] = trans["번역문"].progress_appl... | 67,153 |
def file_to_subtitles(filename):
""" Converts a srt file into subtitles.
The returned list is of the form ``[((ta,tb),'some text'),...]``
and can be fed to SubtitlesClip.
Only works for '.srt' format for the moment.
"""
with open(filename,'r') as f:
lines = f.readlines()
times_te... | 67,154 |
def all_layers():
"""Sample layer elevation grid where some layers
are completely pinched out (no botm elevation specified) and
others partially pinched out (botms specified locally).
Returns
-------
"""
nlay, nrow, ncol = 9, 10, 10
all_layers = np.zeros((nlay + 1, nrow, ncol), dtype=f... | 67,155 |
def _run_module_code(code, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, alter_sys=False):
"""Helper for run_module"""
# Set up the top level namespace dictionary
if alter_sys:
# Modify sys.argv[0] and sys.module[mod_name]
temp_mod... | 67,156 |
def calculate_border(grid_dims, width, height):
"""Calculate each line in all borders.
Args:
grid_dims: tuple of the number of tiles in grid. In format `(row, column)`
width: float width in pixels
height: float height in pixels
Returns:
list: containing dictionaries keys `(... | 67,157 |
def df_fe2num_frames(fn_instance):
"""
create a df in which each row contains the number of frames that a FE is a part of
:param instance of nltk.corpus.reader.framenet.FramenetCorpusReader fn_instance: instace of fn version
:rtype: pandas.core.frame.DataFrame
:return: df with for each FE the num... | 67,158 |
def removeObject(ID):
""" remove an object from the simulation """
OpenNero.getSimContext().removeObject(ID) | 67,159 |
def check_y_pos(act: Act, acts: list) -> bool:
"""Checks if the y position of Activities overlaps any other given Activities.
Args:
act: Activity of which to check the overlap.
acts: List of Activities to check against.
Returns:
True if Activity does not... | 67,160 |
def aggregate_data_for_timespan(data):
"""
Calculate aggregate values for all data in a given timespan
:param data: dict of result data from query_data_for_timespan()
:type data: dict
"""
res = {}
res['reports'] = {'run_count': 0,
'run_time_total': datetime.timedelta()... | 67,161 |
def dijkstra_heap(siten):
"""
1-indexed
疎グラフの時に有効 O(E log(V))
:return:
"""
dist = [INF] * (n + 1)
dist[siten] = 0
que = []
heappush(que, (dist[siten], siten))
while len(que):
d, v = heappop(que)
if d > dist[v]:
continue
for e in G[v]:
... | 67,162 |
def _parse_face(face_row):
"""Parses a line in a PLY file which encodes a face of the mesh."""
face = [int(index) for index in face_row.strip().split()]
# Assert that number of vertices in a face is 3, i.e. it is a triangle
if len(face) != 4 or face[0] != 3:
raise ValueError(
'Only supports face repre... | 67,163 |
def execute(command,
env=None,
split_lines=False,
ignore_errors=False,
extra_ignore_errors=(),
translate_newlines=True,
with_errors=True,
none_on_ignored_error=False,
return_error_code=False,
log_output_on_error=... | 67,164 |
def test_zu_mandelbaum15():
"""
"""
halocat = FakeSim()
model = PrebuiltHodModelFactory('zu_mandelbaum15', prim_haloprop_key='halo_mvir')
model.populate_mock(halocat) | 67,165 |
def check_residue_starts(computed_starts, nuc_sample_array):
"""
Assert that computed starts are residue starts.
"""
residue_starts = struc.get_residue_starts(nuc_sample_array)
for start in computed_starts.flatten():
assert start in residue_starts | 67,166 |
def include_keys(include, d):
"""
Pick out the `include` keys from a dict
Args:
include: list or set of keys to be included
d: raw dict that might have irrelevant keys
"""
assert is_sequence(include)
return {k: v for k, v in d.items() if k in set(include)} | 67,167 |
def compute_topologyzoo_treewidths():
"""Computes the treewidth of all contained topology zoo graphs. Stores the output in the output/ folder and the log in log/."""
util.ExperimentPathHandler.initialize(check_emptiness_log=False, check_emptiness_output=False)
log_file = os.path.join(util.ExperimentPathHand... | 67,168 |
def spherical_interpolate(p1, p2, n_steps=8):
"""Spherical interpolation between two vectors."""
assert p1.dim() == p2.dim() == 1, "Only 1d vectors are currently supported."
def _spherical_interpolate_pytorch():
ratios = torch.linspace(0, 1, steps=n_steps)
vectors = [slerp(ratio, p1, p2).un... | 67,169 |
def override_serializer(format_output, dimension, base_serializer_class):
"""
Override Serializer switch output format and dimension data
"""
if format_output == 'geojson':
if dimension == '3':
class GeneratedGeo3DSerializer(BaseGeoJSONSerializer,
... | 67,170 |
def test_quick_brown_fox_no_whitespace():
"""Testing quick brown fox no whitespace"""
plaintext = "thequickbrownfoxjumpsoverthelazydog"
_test_shift(plaintext, fitness.english.quadgrams) | 67,171 |
def _parse_args(argv=None):
"""Parse command line args."""
default_config_file = default_config_file_path()
parser = argparse.ArgumentParser(
description=("Updates the AWS ParallelCluster configuration file."),
epilog='For command specific flags, please run: "pcluster-config [command] --hel... | 67,172 |
def _get_config():
"""Return a config dictionary."""
return {
DYSON_DOMAIN: {
CONF_USERNAME: "email",
CONF_PASSWORD: "password",
CONF_LANGUAGE: "GB",
CONF_DEVICES: [
{"device_id": "XX-XXXXX-XX", "device_ip": "192.168.0.1"},
... | 67,173 |
def test_parallel_pathos_pp_task ( ) :
"""Test parallel processnig with parallel_pathos (task interface)
"""
logger = getLogger ("ostap.test_parallel_pathos_pp_task")
if not WorkManager :
logger.error ("Failure to import WorkManager")
return
logger.info ('Test job submission w... | 67,174 |
def create_r2_script_content(sample_file_path, decoded_strings, stack_strings):
"""
Create r2script contents for r2 session annotations.
:param sample_file_path: input file path
:param decoded_strings: list of decoded strings ([DecodedString])
:param stack_strings: list of stack strings ([StackStrin... | 67,175 |
def ReadData(filename='PEP_2012_PEPANNRES_with_ann.csv'):
"""Reads filename and returns populations in thousands
filename: string
returns: pandas Series of populations in thousands
"""
df = pandas.read_csv(filename, header=None, skiprows=2,
encoding='iso-8859-1')
popul... | 67,176 |
def formatRealization(rlz):
"""
Converts types of each input.
@ In, rlz, dict, var:val
@ Out, rlz, dict, formatted
"""
for k,v in rlz.items():
rlz[k] = np.atleast_1d(v) | 67,177 |
def get_new_username():
"""提示用户输入用户名"""
username = input('请输入用户名:\n')
filename = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
return username | 67,178 |
def bezier3_split_batch(batch):
"""Split N bezier3 curves in 2xN bezier3 curves at t=0.5"""
return np.moveaxis(np.dot(BEZIER3_SPLIT, batch), 0, -2).reshape((-1, 4, 2)) | 67,179 |
def create_indices(ordering_1: SortedList, ordering_2: SortedList):
"""
Creates indices np.array which represents how agents from ordering_1 have to be rearranged
in order to fit agents from ordering_2. If such relation is not possible, return False.
:param ordering_1: first agents ordering
:param ... | 67,180 |
def extend_conv_spec(convolutions):
"""
添加默认配置(残差)
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
(kernel size, dim size and optionally how many layers behind to look for residual)
to default the residual propagation param if it is not specified
"""
extended ... | 67,181 |
def bin_spectra(filename, start=None, end=None, save=True, dec=3, function=None):
"""
Sums spectra from raw file and outputs to excel file
:param filename: raw or mzML filename
:param start: start scan (None will default to 1)
:param end: end scan (None will default to the last scan)
:param sav... | 67,182 |
def internal_manifest_from_external(
manifest: ImportManifest, content_records: list
) -> InternalImportManifest:
"""
Construct an internal manifest from an external one plus the db records for the content
:param manifest: ImportManifest object
:param content_records: list of ImageImportContent rec... | 67,183 |
def hello():
"""Return a friendly HTTP greeting."""
if request.method == 'POST':
return "Yes {}".format(request.form.get("myname"))
return "<form id='myform' method='POST'><input name='myname'/></form>" | 67,184 |
def dockerfile_image(
name,
dockerfile,
build_args = None,
docker_path = None,
driver = "docker",
kaniko_digest = None,
kaniko_tag = None):
""" Creates a repository with a docker tarball generated from Dockerfile.
This macro wraps (and simplifies) invocat... | 67,185 |
def prepare(topic_model, docs, **kargs):
"""Transforms the GraphLab TopicModel and related corpus data into
the data structures needed for the visualization.
Parameters
----------
topic_model : graphlab.toolkits.topic_model.topic_model.TopicModel
An already trained GraphLab topic model.
... | 67,186 |
def fit_gaussians(data, height, width, savedir='./', overplot=False,
savename='./Data-With-Gaussians.csv'):
"""
Fits gaussians to the data peaks.
Parameters
----------
data: string or Pandas DataFrame
This should be a string that points to the csv DataFrame file
or... | 67,187 |
def population_downscaling_validation(df_osm_built, df_insee):
"""
Validates the population downscaling estimation by means of aggregating the sum of buildings estimated population lying within each population square
Allows to compare the real population count with the estimated population lying within each square
... | 67,188 |
def parseargs() -> argparse.ArgumentParser:
""" Parse arguments """
parser = worker.parseargs('Manage origins')
parser.add_argument("--list", action="store_true", help="List origins")
parser.add_argument("--add", action="store_true", help="List origins")
parser.add_argument("--delete", action="store... | 67,189 |
def aci_app_proxy():
""" this function is a workaround to current ACI app api restriction that
only allows for post/get requests and static one-level urls. Instead
of doing get/post/delete to dynamic url as provided by this app,
the request will be posted to a static 'proxy' url with the f... | 67,190 |
def f(x):
"""return x*x"""
return x * x | 67,191 |
def divideURL(url, queryDelim="&"):
"""Divides a URL into a dict with the following keys,
whose values are an empty str if optional and not set:
- scheme (str)
- authority (dict. Keys: username, password, host, port)
- path (str)
- query (dict. Keys are query keys = list of their values)
- ... | 67,192 |
def permutation_kronecker(perm1: FixedPermutation, perm2: FixedPermutation) -> FixedPermutation:
"""Combine two permutations of size n1 and n2 into their Kronecker product of size n1 * n2.
"""
n1, n2 = perm1.permutation.shape[-1], perm2.permutation.shape[-1]
x = torch.arange(n2 * n1, device=perm1.permut... | 67,193 |
def get_palate_line_segments(speaker_tensor, name, mt_hull, plot_bool):
"""
data: unordered x,y coordinates from tongue coils T1/TT, T2/TB, T3/TD
and data from T1/TT in the case of 'faet0', 'mjjn0', 'fsew0' are used
to create a convex hull estimate as to where the palate is
in order to calcula... | 67,194 |
def update_results(results, res):
"""Update results in-place."""
results["changes"].update(res["changes"])
results["comment"].append(res["comment"]) | 67,195 |
def third_round_phase(tableau, phase_stabilizer, phase_destabilizer):
"""Adds a diagonal matrix to the Z destabilizer matrix such that Zd + D = M*M' for some invertible M"""
num_qubits = int(len(tableau[0, :]) / 2)
x_destab = tableau[0:num_qubits, 0:num_qubits]
z_destab = tableau[0:num_qubits, num_qubit... | 67,196 |
def conv_en2ko(string):
"""
conv_en2ko(string)
Convert English characters to Korean characters.
:return: String (Korean)
"""
char_groups = split_en(string)
converted_string = ''
for char_group in char_groups:
top_idx = 0
mid_idx = 0
bot_idx = 0
for char_... | 67,197 |
def register():
"""
register Register all BlenderNC functions into Blender
"""
# Update addon by CGCookie
addon_updater_ops.register(bl_info)
registerBlenderNC()
bpy.utils.register_class(BlenderNC_Preferences)
print("Registering to Change Defaults")
bpy.app.handlers.load_factory_star... | 67,198 |
def _check_to_numpy(plugin, tensor):
"""Check the tensor and return a numpy.ndarray."""
np_value = tensor.asnumpy()
if plugin == 'scalar':
if np_value.size == 1:
return np_value
raise ValueError('The tensor holds more than one value, but the scalar plugin expects on value.')
... | 67,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.