content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def filter_pair_by_len(p, maxlen=c.MAX_LENGTH):
""" Filter out sentences if they are greater than maximum length.
"""
return len(p[0].split(" ")) < maxlen and len(p[1].split(" ")) < maxlen | 75,100 |
def includeme(config):
"""
Can get tween ordering by executing the following on command-line from root dir:
`bin/ptween development.ini`
We could alternatively put these in the base.ini file explicitly.
See: https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#registering-... | 75,101 |
def run_model(params, rollout_size=50, num_steps=50):
"""Perform the training operation.
Parameters
----------
params : dict
flow-specific parameters (see flow/utils/registry.py)
rollout_size : int
length of a single rollout
num_steps : int
total number of training steps... | 75,102 |
def func_lineno(func):
"""Get the line number of a function.
"""
try:
return func.compat_co_firstlineno
except AttributeError:
try:
if PYTHON_VERSION_MAJOR == 3:
return func.__code__.co_firstlineno
return func.func_code.co_firstlineno
excep... | 75,103 |
def calc_cl_metrics(acc_matrix):
"""
Calculate metrics based on an accuracy matrix of N train tasks on N test tasks
The lower triangular matrix is the BWT, the higher triangular matrix is the FWT
The metrics below are taking into account the accuracy of the model at every timestep / task
by dividin... | 75,104 |
def ElectricField(q, r0, x, y):
""" Return the electric field vector E=(Ex, Ey) due to charge q at r0.
"""
den = np.hypot(x - r0[0], y - r0[1]) ** 1.5
return q * (x - r0[0]) / den, q * (y - r0[1]) / den | 75,105 |
def readMirror(fileLocation):
"""Returns saved Model (mirror) from Pickled file at 'fileLocation'
Needed to transfer model from IPY to PY3
"""
import pickle as pickle
#f = open(fileLocation,"rb")
import shelve
import contextlib
with contextlib.closing(shelve.open(fileLocation, 'r'... | 75,106 |
def saveToFile (fileName, str):
"""Save a string to a file. Takes two arguments,
the file name and the string to save:
saveToFile ('c:\\myfile.txt', strVariable)"""
outFile = open(fileName, 'w')
outFile.write(str)
outFile.close() | 75,107 |
def get_api_es_client(session):
"""
Returns an Elasticsearch client for the catalogue cluster.
"""
secrets = session.client("secretsmanager")
credentials = json.loads(
secrets.get_secret_value(SecretId="elasticsearch/api_cleanup/credentials")[
"SecretString"
]
)
... | 75,108 |
def _longmess(*args, skip=0):
"""Message with stack backtrace"""
def ff(fn):
fn = os.path.relpath(fn)
if fn.startswith('./'):
return fn[2:]
return fn
def fa(a):
result = re.sub(r'^\(\*_args=(.*)\)$', r'\1',a).replace(',)', ')')
if result == '[]':
... | 75,109 |
def insertionsort(x, count = False):
"""
For each element e of x, move through the array until you come to a value
that is less than e, or the end of the array, then place e at the new location.
"""
assignments, conditionals = 0, 0
for i in range(1, len(x)):
element = x[i]
j = i... | 75,110 |
def install(enable=False, disable=False, status=None, prefix=None, path=None, verbose=False):
"""Installs the nb_conda_kernels configuration data.
Parameters
----------
enable: bool
Enable nb_conda_kernels; that is, make the changes to
the Jupyter notebook configuration so that it will ... | 75,111 |
def vm_impl_concatOffset(self):
"""Generate vm_impl function for ConcatOffset"""
def vm_impl(x):
out = vm.ConcatOffset(x) # out is tuple
return out
return vm_impl | 75,112 |
def append_theory(program, theory):
"""
Appends the theory to the program.
:param program: the program
:type program: NeuralLogProgram
:param theory: the theory
:type theory: NeuralLogProgram or collections.Iterable[Clause]
"""
if theory is not None:
if isinstance(theory, Neural... | 75,113 |
def get_assimilator_data(mode, assimilator, text, link):
"""
This function is used for get parsed web/local document from a Tika-service
mode: get metadata or content body
assimilator: api address of the text assimilator, running apache tika
text: piece of raw text
link: web url to a html page o... | 75,114 |
def list_channel_messages_since_delta(session, *, deltaLink):
"""List channel messages for the team and channel
session = requests.Session() instance with Graph access token
deltaLink = the leftover delta you were given the last time you called list_channel_messages_since_time
we wi... | 75,115 |
def _smove(src, dst_dir):
"""Move file to destination directory with overwrite.
"""
_smakedirs(dst_dir)
dst_path = os.path.join(dst_dir, os.path.basename(src))
if os.path.exists(dst_path):
os.unlink(dst_path)
shutil.move(src, dst_dir) | 75,116 |
def get_default_title():
""" See description in Bootloader class below """
return __bootloader.get_default_title() | 75,117 |
def parse_config(app):
"""Process the Sphinx Gallery configuration"""
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
src_dir = app.builder.srcdir
abort_on_example_error = app.builder.config.abort_on_exa... | 75,118 |
def get_leader(cluster_name, role_type):
"""
:param cluster_name: 集群名称
:param role_type: 角色类型
:return: overlord or coordinator
"""
cluster = model_manager.get_cluster_obj_by_name_type(cluster_name, DRUID)
conn_info = json.loads(cluster.connection_info)
zk_addr = conn_info[ZOOKEEPER_CONNE... | 75,119 |
def qc_bam_gene_coverage_metrics_singlesample(input_bam, _, output_prefix):
"""Calculates and outputs bam coverage statistics """
run_cmd(cfg, cfg.gatk, "-R {reference} \
-T DepthOfCoverage \
-o {output} \
-I {bam} \
-L {captu... | 75,120 |
def _async_get_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
pv_entry: PowerviewEntryData = hass.data[DOMAIN][entry.entry_id]
shade_data = pv_entry.coordinator.data.get_all_raw_data()
hub_info = async_redact_data(asdict(pv... | 75,121 |
def load():
"""Load recent pastes."""
recent_pastes.clear()
recent_pastes.maxlen = _settings.getint('maxlen')
for args in json.loads(_settings['json']):
recent_pastes.add(*args) | 75,122 |
def execute_dax_query(credential, dataset_id, daxQuery):
"""Execute DAX query"""
url = f"https://api.powerbi.com/v1.0/myorg/datasets/{dataset_id}/executeQueries"
try:
token = credential.get_token("https://analysis.windows.net/powerbi/api/.default").token
headers = { "Content-Ty... | 75,123 |
def nosofsky_1986():
"""Category structure used in [1].
There are three category structures: dimensional, criss-cross,
interior-exterior, and diagonal.
References:
[1] Nosofsky, R. M. (1986). Attention, similarity, and the
identification-categorization relationship. Journal of
Expe... | 75,124 |
def test_nh_energy():
"""Checks total relativistic energy with NH."""
eref = -57.681266930627
norb = 6
nele, h1e, h2e = build_nh_data()
elec_hamil = general_hamiltonian.General((h1e, h2e))
maxb = min(norb, nele)
minb = nele - maxb
ndim = int(binom(norb * 2, nele))
hci = np.zeros((nd... | 75,125 |
def test_remove_stopword_paragragph():
"""
test remove stopwords in paragraph
"""
text = "Lionel Messi pergi Ke pasar di area Jakarta Pusat itu. " \
"Sedangkan Cristiano Ronaldo ke pasar Di area Jakarta Selatan. Dan mereka tidak bertemu begini-begitu."
stopword = StopWord()
expected_r... | 75,126 |
async def test_async_household(aresponses, client: Efergy) -> None:
"""Test getting household data."""
aresponses.add(
"engage.efergy.com",
"/mobile_proxy/getHousehold?token=ur1234567-0abc12de3f456gh7ij89k012&offset=300",
"GET",
aresponses.Response(
status=200,
... | 75,127 |
def persist_likwid(run, session, measurements):
"""
Persist all likwid results.
Args:
run: The run we attach our measurements to.
session: The db transaction we belong to.
measurements: The likwid measurements we want to store.
"""
for (region, name, core, value) in measurem... | 75,128 |
def list_numbers():
"""This function adds numbers to a list"""
i = 0
numbers = []
for i in range(0, a, n):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in number... | 75,129 |
def create_bm25():
"""Function to create or update BM25 object"""
# Run arguments
parser = argparse.ArgumentParser()
parser.add_argument("--task",
default=4,
type=int,
help="Task where: \
-task 1 : classification su... | 75,130 |
def wait_for_tasks(session, tasks, timeout):
"""returns true if all tasks are no longer pending (ie success/failure/cancelled)
and false if a timeout occurs"""
finished = False
start = time.time ()
while not(finished) and ((time.time () - start) < timeout):
finished = True
for task i... | 75,131 |
def get_previous(pair, end, qty):
"""get the previous pairs
Arguments:
pair {string} -- the name of the pair eg. EOSUSD
end {int} -- time of the last records to request
qty {int} -- the number of records to request
Returns:
list -- qty prices before end for the pair
"""... | 75,132 |
def handle_multiple_variantcallers(data):
"""Split samples that potentially require multiple variant calling approaches.
"""
assert len(data) == 1
callers = get_variantcaller(data[0])
if isinstance(callers, basestring):
return [data]
elif not callers:
return []
else:
... | 75,133 |
def skip_everflow_test(tbinfo):
"""
Skip everflow tests on certain testbed types
Args:
tbinfo(fixture): testbed related info fixture
Yields:
None
"""
if 'backend' in tbinfo['topo']['name']:
pytest.skip("Skipping everflow tests. Unsupported topology {}".format(tbinfo['to... | 75,134 |
def guess_host_name():
""" Just a handy function for external use
"""
with open(join(package_path(), 'paths.yml')) as f:
loc_by_name = yaml.load(f, Loader=yaml.FullLoader)
for ld in loc_by_name.values():
if 'host_pattern' in ld:
if re.match(ld['host_pattern'], utils.hostname)... | 75,135 |
def prepare_gensim_archive(fn):
"""Unpacks a gensim archive file
:param fn: Filename of gensim archive file
:return: Filename of an on disk gensim model which can be loaded into memory with LdaModel.load()
"""
if fn.endswith('.tar') or fn.endswith('.bz2') or fn.endswith('.gz'):
upload_folde... | 75,136 |
def progress(_status: str):
""" Update progress information in console. """
sys.stdout.write("{}".format(_status)) | 75,137 |
def main():
"""Runs the tests."""
defaults = {
'TEST_ID':
'MySimpleTest-' + KeystoreTestScenario.DEFAULT_TEST_ID
}
return citest.base.TestRunner.main(
default_binding_overrides=defaults,
test_case_list=[SynchronousKeystoreTest]) | 75,138 |
def get_maze(filename):
"""
Convenience function to get a grid from a file.
Takes the filename of the maze to load, loads the maze from the file,
and builds it into a grid. Then returns that grid.
Args:
filename: the file to load the maze from
Returns:
the grid representation ... | 75,139 |
def main():
"""Main function
"""
args = parse_args()
block_size = get_block_size(
args.width, args.height, args.block_size)
end = '#FFFFFF'
if args.end_color:
end = args.end_color
grid = create_grid(args.width, args.height, block_size, args.color, end)
result_grid = creat... | 75,140 |
def get_loss(name):
"""Returns loss_fn(outputs, ground_truths, **kwargs), where "outputs" are the model outputs.
Args:
name: The name of the loss function.
Returns:
loss_fn: A function that computes the loss between the inputs and the ground_truths
Raises:
ValueError: If Preprocessing `name` is n... | 75,141 |
def get_processed_invoices_df():
"""
this function will read the dataframe and create a text string for each row separated by new line '\n'
to match with resultant data for testing.
"""
process_invoices = spark.sql("select * from processedInvoiceTbl")
text = ""
for i in range(1, process_in... | 75,142 |
def resistance(v='x', i='x', p='x', l='x', a='x', pw='x'):
"""
Calculate and return the value of resistance using given values of the params
How to Use:
Give arguments for v and i params,
or, give arguments for p,l and a params,
or, give arguments for pw and i params
... | 75,143 |
async def edit_a_group(id: int, group: Group):
"""Updates the information stored about a group."""
updated_group = await Group.edit(id, group)
if not updated_group:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="group not found.")
return updated_group | 75,144 |
def test_binning_truncate_True_False(
b: float,
truncate: bool,
expected: Callable,
request: Any,
) -> None:
"""It bins x and y. With and without truncation of end points."""
a, grid = 3, 10
binwidth = (b - a) / (grid - 1)
x = np.linspace(2.2, 6.6, 1000)
y = np.linspace(10, 30, 1000)... | 75,145 |
def derive_password(password: AnyStr) -> Tuple[bytes, bytes]:
"""
Args:
password: Password
Returns:
Encryption key, Mac key
"""
if isinstance(password, str):
password = password.encode()
tmp = PBKDF2HMAC(hashes.SHA256(), 32, b"Yubico", 10000).derive(password)
retur... | 75,146 |
def check_arguments(options, args, parser):
""" Checks if arguments passed to script are plausible.
Returns a ParseResult 6-tuple if successful. """
# Make sure args list may be valid
if len(sys.argv) < 6:
print >> sys.stderr, parser.get_usage()
sys.exit(1)
# Make sure HTTP requ... | 75,147 |
def get_setting(varname):
""" Returns the value of a configuration variable. """
gl = globals()
if varname not in gl.keys():
raise ValueError("Unknown setting %s"%varname)
# Here, possibly add some code to raise exceptions if some
# parameter isn't set set properly, explaining on how to set... | 75,148 |
def get_lr(curr_epoch, hparams, iteration=None):
"""Returns the learning rate during training based on the current epoch."""
assert iteration is not None
batches_per_epoch = int(hparams.train_size / hparams.batch_size)
if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name:
lr = step_lr(hp... | 75,149 |
def _timestamp_to_date_string(timestamp: pd.Timestamp):
"""Return a date-string (YYYY-MM-DD) from a pandas Timestamp."""
if timestamp.tzinfo:
timestamp = timestamp.tz_convert('UTC')
timestamp = timestamp.tz_localize(None)
date = pd.Timestamp.date(timestamp)
if pd.Timestamp(date) != timestamp... | 75,150 |
def beta_tcon(s_gkg,t_cels,p_dbar,tp_cels=None,chkvals=False,
chktol=_CHKTOL,tp_cels0=None,chkbnd=False,useext=False,
mathargs=None):
"""Calculate haline contraction wrt conservative temperature.
Calculate the haline contraction coefficient of seawater at constant
conservative temperature.
... | 75,151 |
def workspace_list_table_format(result):
"""Format workspace list as a table"""
table = []
for item in result:
table.append(workspace_show_table_format(item))
return table | 75,152 |
def do_nothing(_):
"""place holder function for use in cv2.createTrackbar
:param _:
:return: nada
"""
pass | 75,153 |
def get_items(wiki, only_undone=False) -> list:
""" all items page list """
items = []
for page in wiki.pages():
content: str = wiki.page_info(page["pageid"])["*"]
if content.startswith("{{面包屑|物品信息"):
if only_undone and content.find("{{施工中}}") == -1:
continue
... | 75,154 |
def cycle(n):
"""Return the cycle graph on n vertices."""
return circulant(n, [1]) | 75,155 |
def nointernet():
"""Block internet access in requests."""
urls = Counter()
@all_requests
def timeout_mock(url, request):
urls[urlunsplit(url)] += 1
raise requests.ConnectTimeout(f"Connection timeout: {urlunsplit(url)}")
with HTTMock(timeout_mock):
yield urls | 75,156 |
def _attempt_cast_as_float(value: Any) -> float:
"""
:param vale: a value
:return: the value as a float if casting is possible, otherwise return 1
"""
try:
return float(value)
except (ValueError, TypeError):
return 1.0 | 75,157 |
def adjust_dict_property(property_value: Any, model_field: ModelField, depth: int):
"""Convert a dict property for the BigQuery schema"""
dict_value_type = ModelFieldUtils.get_dict_value_type(model_field=model_field)
# Scalar
if model_field.outer_type_ is Dict[str, str]:
return [{"key": k, "valu... | 75,158 |
def put_exh_banner_api_v1(
exhibition_id=Route(str, rules=ObjectIdValid()),
banner_photo=File(rules=MaxFileCount(1))
):
"""전시회 배너 이미지 업로드"""
oid = ObjectId(exhibition_id)
exhibition = Exhibition(g.db).find_one(oid)
if exhibition['owner_id'] != g.user_id:
return forbidden("You are not own... | 75,159 |
def check_for_uniform_time_steps(epoch):
"""Verify that time steps are uniform
Checks that time steps in sorted array epoch are uniform,
otherwise raising ValueError.
Note that this may not work as expected for inexact datatypes
(floats).
"""
delta_t = np.diff(epoch)
if delta_t.min() ... | 75,160 |
def show_permission(permission_id):
"""Get permission."""
data = _get_request_args()
return utils.make_json_response(
200,
permission_api.get_permission(permission_id, user=current_user, **data)
) | 75,161 |
def test_class_with_steps_and_repeated_marks(testdir, improperly_decorated_test_class_with_steps, simple_test_config):
"""Verify that decorating a pytest class with 'test_case_with_steps' mark along with marking methods of said class
with 'test_id' and 'jira' marks will result in test cases being marked with th... | 75,162 |
def train_markov_gz(fn):
""" trains a Markov model on gzipped text data """
with gzip.open(fn, "rt", encoding="utf-8") as f:
text = f.read()
return markovify.Text(text, retain_original=False, state_size=3) | 75,163 |
def execute_sql_by_id(db: sqlite3.Connection, sql: str,
sql_values: List[Any], ids: Sequence[T2], return_type: Optional[Type[T]]=None) \
-> Tuple[int, List[T]]:
"""
Update, delete or whatever rows in batches as constrained by database limitations.
If the update statement returns values ... | 75,164 |
def get_angle_direction(v1, v2, axis):
"""
Return the direction of rotation to get v1 onto v2 about the provided axis.
"""
axes_dict = {'x':0, 'y':1, 'z':2, 'X':0, 'Y':1, 'Z':2}
if axis in axes_dict:
axis = axes_dict[axis]
v1, v2 = np.atleast_2d(v1, v2) # vectors will be (1,3) or (N,3... | 75,165 |
def test_add_features_gpx(empty_space):
"""Test uploading gpx file to the space."""
space = empty_space
gpx_file = Path(__file__).parents[1] / "data" / "example.gpx"
space.add_features_gpx(gpx_file, features_size=500)
resp = space.search(params={"p.ele": "2376"})
flist = list(resp)
assert fl... | 75,166 |
def init_db():
""" Initializes the SQLAlchemy app """
global app
Account.init_db(app) | 75,167 |
def test_context_adjustment_window_udf(alltypes, df, context, window):
""" This test case aims to test context adjustment of
udfs in window method.
"""
with option_context('context_adjustment.time_col', 'timestamp_col'):
expr = alltypes.mutate(v1=calc_mean(alltypes[TARGET_COL]).over(window))... | 75,168 |
def increment_genotype(genotype):
"""Increment a genotype of allele numbers to the next genotype
in VCF sort order.
Parameters
----------
genotype : ndarray, int, shape (ploidy,)
Array of allele numbers in the genotype.
Notes
-----
Mutates genotype array in place.
"""
p... | 75,169 |
def init(name: str, environment: str, template: Optional[str] = None) -> None:
"""
Create the local structure for a new AWS DDK Python project.
NAME is the name of the project.
"""
# Use default Cookiecutter project template
if not template:
template = os.path.join(get_package_root(), D... | 75,170 |
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type):
"""Estimate the log Gaussian probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
means : array-like of shape (n_components, n_features)
precisions_chol : array-like
Cholesky dec... | 75,171 |
async def test_unload_entry(hass, config_entry, controller):
"""Test entries are unloaded correctly."""
controller_manager = Mock(ControllerManager)
hass.data[DOMAIN] = {DATA_CONTROLLER_MANAGER: controller_manager}
with patch.object(hass.config_entries, 'async_forward_entry_unload',
... | 75,172 |
def tilesets(hg_name):
"""
List the datasets in an instance
"""
port = get_port(hg_name)
# use a really high limit to avoid paging
url = "http://localhost:{}/api/v1/tilesets/?limit=10000".format(port)
ret = requests.get(url)
if ret.status_code != 200:
sys.stderr.write("Error re... | 75,173 |
def _build_draw_line(append):
"""Specialize a line plotting kernel for a given append/axis combination"""
@ngjit
def draw_line(x0i, y0i, x1i, y1i, i, plot_start, clipped, *aggs_and_cols):
"""Draw a line using Bresenham's algorithm
This method plots a line segment with integer coordinates on... | 75,174 |
def euler79_():
"""Solution for problem 79."""
pass | 75,175 |
def getLastSensorAcquisitionTime(sensorId, sessionId):
"""
Get the last sensor acquisition timestamp.
URL Path:
- sensorId: sensor ID.
- sessionId: session ID.
HTTP Return Codes:
- 200 OK if success
Returns a json document with last acquisition timestamp. Format of ret... | 75,176 |
def zeros(shape):
"""
:param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width)
:return: array (it's shape=param shape) with initialized values using 'zeros' initializer
"""
return np.zeros(shape=shape) | 75,177 |
def addr_generator(start_ip, port, count):
"""Generator a list of (ip, port).
"""
def tostr(ip):
return '.'.join([str(_) for _ in ip])
ip = [int(_) for _ in start_ip.split('.')]
addr_list = [(tostr(ip), port)]
for i in range(count-1):
ip[-1] += 1
addr_list.append((tostr(i... | 75,178 |
def wait_for_standing_subprocess(p, timeout=None):
"""Waits for a subprocess started by start_standing_subprocess to finish
or times out.
Propagates the exception raised by the subprocess.wait(.) function.
The subprocess.TimeoutExpired exception is raised if the process timed-out
rather then termin... | 75,179 |
def filter_threshold(delta_f, threshold_value):
""" Return indices of the data whose values are above the acceptable level """
return delta_f >= threshold_value | 75,180 |
def handler(event, context) -> utils.Response:
"""lambda entry point."""
return handlers.SnsEventHandler(
name="twitter",
event=utils.LambdaEvent(event),
context=utils.LambdaContext(context),
action=post_status,
).response | 75,181 |
def vector_sum(vectors):
"""一系列向量相加"""
return reduce(vector_add, vectors) | 75,182 |
def main(raw_args=None):
"""//////////////////////////////////////////////////
//////////// PARSE INPUT ARGUMENTS ////////////
//////////////////////////////////////////////////"""
parser = argparse.ArgumentParser(description='NEAT-genReads V3.0',
formatter_cl... | 75,183 |
def retry(func, *args, **kwargs):
"""Repeats a function until it completes successfully or fails too often.
Args:
func:
The function call to repeat.
args:
The arguments which are passed to the function.
kwargs:
Key-word arguments which are passed to t... | 75,184 |
def get_config():
"""获取config.json文件信息"""
if not os.path.isfile(config_path):
logger.warning(u'当前路径:%s 不存在配置文件config.json',
(os.path.split(os.path.realpath(__file__))[0] + os.sep))
sys.exit()
try:
with open(config_path) as f:
config = json.loads(f.r... | 75,185 |
def build_model_columns():
"""
:param data = df_preprocess_noNA
Builds a set of wide and deep feature columns.
"""
# Continuous variable columns
speed = tf.feature_column.numeric_column('speed')
inv_speed = tf.feature_column.numeric_column('inv_speed')
ais_rem_time = tf.feature_column.numeric_column('ai... | 75,186 |
def test_custom_timeout(monkeypatch, fake_response, aqhttp):
"""Timeout should override from the aqhttp.post method."""
class FakeRequest:
def __init__(self, status_code=200, url="myfakeurl.com", method="post"):
self.status_code = status_code
self.url = url
self.meth... | 75,187 |
def run_apidoc(app):
"""Generate API documentation"""
import better_apidoc
better_apidoc.APP = app
better_apidoc.main(
[
"better-apidoc",
"-a",
"-M",
"-t",
os.path.join(".", "templates"),
"--force",
"--no-toc",
... | 75,188 |
def create_tags(dataframe, periods):
"""
Función para clasificar los registros de cierre como
subidas/bajadas fuertes, subidas/bajada, o matiene de
un día con respecto a otro.
Parámetros:
----------
df pd.DataFrame:
DataFrame que se quiere clasificar.
periods int:
... | 75,189 |
def save_report_to_html(csv_file, html_file):
"""
Converts CVS file to HTML, applying CSS
:param csv_file: input CSV file
:param html_file: output HTML file, created in the same directory
:return:
"""
# reads source CSV, ignore first index column
dataframe = pd.read_csv(csv_file, index_... | 75,190 |
def encrypt(data, key):
"""RC4"""
S = list(range(256))
j = 0
out = []
for i in range(256):
j = (j + S[i] + key.encode()[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for char in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j]... | 75,191 |
def crop_by_range(anim: Animation[A], start: float, finish: float) -> Animation[A]:
"""
Render a range of an animation.
`start` and `finish` should be floats from 0 to 1.
"""
if not (0 <= start < finish <= 1):
raise ValueError(
"Invalid range ({}, {}). Expected 0 <= start <= fini... | 75,192 |
def train_val_test():
"""train and val"""
torch.backends.cudnn.benchmark = True
# init distributed
if getattr(FLAGS, 'distributed', False):
init_dist()
# seed
if getattr(FLAGS, 'use_diff_seed', False) and not getattr(FLAGS, 'stoch_valid', False):
print('use diff seed is True')
... | 75,193 |
def test_channel_true(context_channel_fx: Context):
"""Verifies the Context.channel function behaves as expected in a channel context"""
assert context_channel_fx.channel == "#unit_test" | 75,194 |
def hist_match(cdf_org, cdf_tar):
"""
Build the lookup table described in step 3.
Arguments:
-----------
cdf_org: dict
The cumulative distribution function of orginal image.
cdf_tar: dict
The cumulative distribution function of target image.
Returns:
-----------
l... | 75,195 |
def run_one_step(dataframe, start_centers):
"""
Performs one iteration of K-Means.
This function takes a dataframe with dense feature vectors, a set of centroids, and returns
a new set of centroids along with the total distance of points to centroids.
This function calculates for each point the cl... | 75,196 |
def report_options(func):
"""Common report options."""
func = all_option(func)
func = count_option(func)
func = length_option(func)
func = end_option(func)
func = start_option(func)
func = exclude_option(func)
func = include_option(func)
return func | 75,197 |
def db_table_create(db_name,table_name,descriptor):
"""If table_name doesn't exist create it according to 'keys-dypes' descriptor."""
db_command = '''CREATE TABLE IF NOT EXISTS "{}" ({})'''.format(table_name,descriptor)
db_query(db_name, db_command) | 75,198 |
def train_test_split_adjacenty(total_size, test_ratio, test_indexes):
"""
Parameters
----------
A: scipy.sparse.spmatrix
connected sparse unweighted adjacency matrix
test_indexes: list
tuple with (x, y, val) for each idx in test datasets
Returns
-------
train_ones : arra... | 75,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.