content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extractImageCorners(directory, filename):
"""
Extract the image corners from an image that is assumed to be
a DICOM image.
Corners are returned as:
[bl, br, tl, tr]
:param directory: the directory where the file given with filename exists.
:param filename: the filename of the file to ... | 73,400 |
def merge(this: SchemaCompatibilityResult, that: SchemaCompatibilityResult) -> SchemaCompatibilityResult:
"""
Merges two {@code SchemaCompatibilityResult} into a new instance, combining the list of Incompatibilities
and regressing to the SchemaCompatibilityType.incompatible state if any incompatibilities ar... | 73,401 |
def flatten(attname):
"""Fixup helper for serialize.
Given an attribute name, returns a fixup function suitable for serialize()
that will pull all items from the sub-dict and into the main dict. If
any of the keys from the sub-dict already exist in the main dict, they'll
be overwritten.
"""
... | 73,402 |
def P_DCG(rank, b=2): # pylint: disable=invalid-name
"""
Discounted Cumulative gain based stopping probability
Args:
rank (int): rank
b (int, optional): Defaults to 1. log base.
Returns:
float: stopping probability at the given rank
"""
def __log_n(x, n): # pylint: dis... | 73,403 |
def test_fn__validate_no_return_value_overlap(config_all):
"""Expect pass on valid input data"""
error_messages = []
error_messages = validators._validate_no_return_value_overlap(error_messages, config_all)
if error_messages:
raise AssertionError | 73,404 |
def uninstall_cache() -> None:
"""Uninstalls the cache from all functions"""
modules = sys.modules.copy()
for module in modules.values():
try:
members = inspect.getmembers(module)
except ModuleNotFoundError:
continue
for name, func in members:
if ... | 73,405 |
def _get_player_regions(player_id):
""" Return a list of regions for whom 'player_id' has reported latency values. """
regions_key = _make_player_regions_key(player_id)
if g.redis.conn.exists(regions_key):
return g.redis.conn.smembers(_make_player_regions_key(player_id))
return set() | 73,406 |
def getImageFromTexture2d(texture2d, flip=True) -> Image:
"""
将给定的纹理转换为PIL.Image
:param texture2d: 要转换的纹理
:type texture2d: Texture2D
:param flip: 将图像翻转回原始(默认情况下,所有Uniiity纹理都翻转)
:type flip: bool
:return: PIL.Image object
:rtype: Image
"""
imageData = texture2d.imageData
... | 73,407 |
def _finalize_build(stage_results):
"""
stage_results (list of (stage_exit_code, stage_name, stage_status)) as returned by
_perform_stage()
logs a final report and returns an overall exit code for whether the
build succeeded.
"""
overall_success = True
final_report = ""
for sta... | 73,408 |
def mean_std(mean, std, color):
"""
Adds mean + standard deviation to a currently-opened plot in the
chosen color.
"""
plt.plot(mean, color=color, linewidth=2)
plt.fill_between(np.arange(len(mean)), mean-std, mean+std,
color=color, alpha=0.2... | 73,409 |
def indentr(model, wdir, infile, input_data, aux_file, toab_gmean):
"""Compute the material entropy production with the indirect method.
The function computes the material entropy production with the indirect
method, isolating a vertical and a horizontal component
(after Lucarini et al., 2011). The out... | 73,410 |
def yellow_cb(obj):
""" Yellow button callback function """
print('Yellow button pressed')
# set Button mode
MODE[1] = 1
# set LED mode
set_MODE_value(4)
# Push new LED modes to the driver
set_LED_states()
print(MODE) | 73,411 |
def derive_key(secret: bytes, salt: bytes):
"""Derives the key from specified secret and salt using KDF function"""
kdf = get_kdf(salt)
key = base64.urlsafe_b64encode(kdf.derive(secret))
return key | 73,412 |
def load_image(infilename):
"""
Function to load the image
"""
data = mpimg.imread(infilename)
return data | 73,413 |
def outdir():
"""Determine if test artifacts should be stored somewhere or deleted."""
return None if test_output_dir is None else Path(test_output_dir) | 73,414 |
def check_mask_patches():
"""
Returns this list of mask patches that we have from the images.
There are patches taken from the masks.
:return: python list of strings
"""
path_to_mask_patches = os.path.join(SEGMENTATION_DATA_PATH, "results", "mask_patches_"+ str(PATCH_COUNT_PER_IMAGE ))
pat... | 73,415 |
def test_server_parse_req_bad_get(message):
"""If GET is bad, parse request function returns error code 405."""
with pytest.raises(ValueError):
parse_request(message) | 73,416 |
def status(user):
"""
:param user: User whose status we want to look at
:return: dict of boolean status codes
"""
return AttrDict({
'member': user.member_of(config.member_group),
'traffic_exceeded': user.current_credit < 0,
'network_access': user.has_property('network_access'... | 73,417 |
def doublePendulumDerivativesSolver(t, x):
"""
Returns time derivative of double pendulum phase space vector, solve_ivp
compatible
"""
g = 9.8
t1, w1, t2, w2 = x
return [w1,
(-w1**2*np.sin(t1-t2)*np.cos(t1-t2) + g*np.sin(t2)*np.cos(t1-t2)
- w2**2*np.sin(t1-t2) - 2*g*n... | 73,418 |
def feedback_fm(gain1=1, gain2=1, carrier1=900, modulator1=300, carrier2=900, modulator2=300,
index1=5, index2=0, attack=0.01, release=1, sr=44100):
"""A convenience to render as function call."""
return FeedbackFM1(gain1=gain1, gain2=gain2, carrier1=carrier1, modulator1=modulator1,
... | 73,419 |
def polya():
"""Fixture returning a Polya instance."""
perm_a = np.array([[8, 9, 10, 11], [9, 10, 8, 11], [10, 8, 9, 11],])
perm_b = np.array([[3, 4, 5], [5, 4, 3], [3, 4, 5],])
perms_list = [perm_a, perm_b]
return Polya(perms_list) | 73,420 |
def get_by_string(source_dict, search_string, default_if_not_found=None):
"""
Search a dictionary using keys provided by the search string.
The search string is made up of keywords separated by a '.'
Example: 'fee.fie.foe.fum'
:param source_dict: the dictionary to search
:param search_string: se... | 73,421 |
def fstringify_command(files):
"""
Entry point for --fstringify.
Fstringify the given file, overwriting the file.
"""
for filename in files: # pragma: no cover
if os.path.exists(filename):
print(f"fstringify {filename}")
Fstringify().fstringify_file_silent(filename)... | 73,422 |
def ssm() -> Iterator[None]:
"""Mock SSM."""
with mock_ssm():
yield | 73,423 |
def get_history_dropdown(obj, project=None):
"""Return link to object timeline events within project"""
timeline = get_backend_api('timeline_backend')
if not timeline:
return ''
url = timeline.get_object_url(obj, project)
return (
'<a class="dropdown-item" href="{}">\n'
'<i c... | 73,424 |
def get_na_row_values(columns):
"""
returns na values for all columns starting from gender
"""
row_values = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
False,
-1
]
actions_idx = columns.index('actions')
row_values += [0] * (len(columns) - actions_idx)
return row_val... | 73,425 |
def test_atomic_g_month_day_min_inclusive_3_nistxml_sv_iv_atomic_g_month_day_min_inclusive_4_5(mode, save_output, output_format):
"""
Type atomic/gMonthDay is restricted by facet minInclusive with value
--03-04.
"""
assert_bindings(
schema="nistData/atomic/gMonthDay/Schema+Instance/NISTSchem... | 73,426 |
def avg_waves(*waves):
"""
Create the average wave.
:param waves: an iterator of waves
:return: a wave
"""
return map(lambda x: x / len(waves), add_waves(*waves)) | 73,427 |
def solve():
"""
PART 1:
The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here.
You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activat... | 73,428 |
def md5(fpath="", data=""):
"""
Calculates the the MD5 hash of a file.
You can only provide a file path OR a data string, not both.
:param fpath: Path of the file for which the MD5 hash is required.
:param data: Data string for which the MD5 hash should be calculated.
:return: Returns the string... | 73,429 |
def _drop_ignored(gold, pred, ignore_in_gold, ignore_in_pred):
"""Remove from gold and pred all items with labels designated to ignore."""
keepers = np.ones_like(gold).astype(bool)
for x in ignore_in_gold:
keepers *= np.where(gold != x, 1, 0).astype(bool)
for x in ignore_in_pred:
keepers... | 73,430 |
def nonspecific(rna_id, sequence, min_length, max_length):
"""
Compute all the fragment sequences in case of nonspecific cleavage, based on the info selected by the user
on minimum and maximum length for the sequences generated from nonspecific cleavage
"""
output_sequences, seq_list = [], list(sequ... | 73,431 |
def flatten(iterable, levels=None, cls=None): # noqa: F811
"""
Recursively denest iterable containers.
>>> from sympy import flatten
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3]])
[1, 2, 3]
>>> flatten([1, [2, 3], [4, 5]])
[1, 2, 3, 4, 5]
>>> flatten([1.0, 2, (1, No... | 73,432 |
def black_thresh(img):
"""
Extract the black part based on RGB color space
"""
thresh_R = threshold(thresh(img_channel(img, 'RGB', 0), thresh=[0, 40]))
thresh_G = threshold(thresh(img_channel(img, 'RGB', 1), thresh=[0, 40]))
thresh_B = threshold(thresh(img_channel(img, 'RGB', 2), thresh=[0, 40])... | 73,433 |
def iter_files(path):
"""Walk through all files located under a root path."""
if os.path.isfile(path):
yield path
elif os.path.isdir(path):
for dirpath, _, filenames in os.walk(path):
for f in filenames:
yield os.path.join(dirpath, f)
else:
raise Runti... | 73,434 |
def covmat2direction(covmat):
"""Return eccentricity and principal direction given a covariance matrix.
The eccentricity is the ratio of the largest eigenvalue to the second
largest. In a 3D problem, there is probably some more descriptive shape
metric that uses all three eigenvalues.
"""
evals... | 73,435 |
def test_013_execute_async_no_chroot_context(ssh, ssh_transport_channel):
"""Context-managed chroot path override."""
ssh._chroot_path = "/mnt"
with ssh.chroot(None):
ssh._execute_async(command)
ssh_transport_channel.assert_has_calls((mock.call.makefile_stderr("rb"), mock.call.exec_command(f"{c... | 73,436 |
def get_summary(master_bricks, mastervol, slavehost, slavevol):
"""
Wrapper function around Geo-rep Status and Gluster Volume Info
This combines the output from Bricks list and Geo-rep Status.
If a Master Brick node is down or Status is faulty then increments
the faulty counter. It also collects the... | 73,437 |
def _get_request_url(message: str, chat_id: int):
"""Compose url for telegram."""
bot_token = settings.TELEGRAM_BOT_TOKEN
url = f'{TELEGRAM_API_URL}{bot_token}/sendMessage?chat_id={chat_id}&text={message}'
return url | 73,438 |
def print_projection_cv2(points, color, image, black_background=False):
""" project converted velodyne points into camera image """
if black_background:
image = np.zeros_like(image)
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
for i in range(points.shape[1]):
cv2.circle(
hsv_image, (np.in... | 73,439 |
def int_to_ip(addr):
"""
Converts a the numeric representation of an ip address
to an ip address strin
Example:
>>> int_to_ip(2130706433)
'127.0.0.1'
"""
return socket.inet_ntoa(struct.pack("!I", addr)) | 73,440 |
def armar_camino(distancia,predecesores,pila, origen, dest=None):
"""Reconstruye un camino desde un vertice teniendo sus predecesores"""
if dest==origen:
pila.insert(0,dest)
return
if dest==None:
distancia_max=0
for vertice,distancia in distancia.items():
if dist... | 73,441 |
def _validate_or_generate_image(buf, name, generate, tolerance):
"""Validate or generate an image.
When generate is True, save the image in *buf* to ``output/{name}.png``.
When generate is False, compare the image in *buf* against
the file ``reference/{name}.png``.
"""
if generate:
PIL.... | 73,442 |
def general_telescope(empty_lamda, grid_size, PASSVALUE):
"""
#TODO pass complex datacube for photon phases
propagates instantaneous complex E-field through the optical system in loop over wavelength range
this function is called as a 'prescription' by proper
uses PyPROPER3 to generate the comple... | 73,443 |
def has_hue_shifted(
before: np.ndarray, after: np.ndarray, hue: float, tolerance: float = 0.02
) -> bool:
"""
Detect whether pixels of a specified 'hue' have shifted away from where pixels were in a
baseline image. Used to detect whether rasters of pages with colorized images had
contain accidental... | 73,444 |
def test_content():
"""Sample pytest test function with the pytest fixture as an argument."""
# from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
assert 1 == 1.0 | 73,445 |
def test_construct_attribute() -> None:
"""Test the construct_attribute method."""
result = serializer.construct_attribute("attributes-charset", DEFAULT_CHARSET)
assert result == b"G\x00\x12attributes-charset\x00\x05utf-8"
result = serializer.construct_attribute(
"operations-supported", [IppOpe... | 73,446 |
def plotdim(npanel, maxcol=12, mode="square"):
"""work out a rectangular plot grid that achieves a total of npanel. maxcol
limits how many columns we allow. mode can be 'square' (keep approximately
equal nrow and ncol), 'cols' (as few rows as possible), 'rows' (as few
columns as possible)."""
# here... | 73,447 |
def a_lambda_cardelli_fast(W,R=3.08):
"""Description: inspired by Eran's function of the same name, faster version using numba.
Input : wavelength in microns
Output : numpy array of A(lambda), the size of wavelengths.
Tested : ?
By : Erez (Dec 2019), on top of Ido Irani (Nov 2019)
URL ... | 73,448 |
def preprocess(path: Path) -> Tuple[Collection[Context], Collection[ContextTagging]]:
"""
Preprocess data file
:param path: Path to data file
:return: Contexts with their corresponding tags (if there are any)
"""
with path.open('r') as data:
lines = data.read().splitlines()
conte... | 73,449 |
def parse():
"""Parse system arguments."""
parser = argparse.ArgumentParser(description="Main entry point into \
the MoonTracker application")
parser.add_argument('-p', dest='port', action='store', default=5000,
type=int, help='have Flask listen o... | 73,450 |
def SectionsMenu(base_title="Sections", section_items_key="all", ignore_options=True):
"""
displays the menu for all sections
:return:
"""
items = get_all_items("sections")
return dig_tree(SubFolderObjectContainer(title2="Sections", no_cache=True, no_history=True), items, None,
... | 73,451 |
def validate_flags():
"""Validates flags are set to acceptable values for CloudML Engine runs."""
assert not FLAGS.cloud_tpu
assert not job_dir()
assert FLAGS.output_dir.startswith("gs://")
assert FLAGS.data_dir.startswith("gs://")
assert FLAGS.worker_replicas <= 1
assert FLAGS.ps_replicas <= 0
if FLAGS... | 73,452 |
def query_cat(catalog, min_ra, max_ra, min_dec, max_dec, columns=None,
column_filters=None):
"""
Use vizquery to get a reference catalog from vizier
"""
from astroquery.vizier import Vizier
import numpy as np
from astropy.coordinates import SkyCoord
# Build vizquery statement
wid... | 73,453 |
def hpat_pandas_series_ge(self, other, level=None, fill_value=None, axis=0):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.ge
Limitations
-----------
- Parameters level, fill_value are currently unsupported by Intel ... | 73,454 |
def aa_seq_doc(aa_sequence):
"""This function takes in an amino acid sequence (aa sequence) and adds spaces between each amino acid."""
return ' '.join([aa_sequence[i:i+1]
for i in range(0, len(aa_sequence))]) | 73,455 |
def load(project_path):
"""
Loads the given project and returns a Project Instance
:param project_path: Path to the location you want to save the project
path.
:type project_path: str
:return: fracture.Project instance
"""
return _project.Project(project_path) | 73,456 |
def _find_units(powers_cleaned, dimensions, strict):
"""
Finds the powers associated with each of the units
:param list((chemdataextractor.quantities.Unit, str, str, str)) powers_cleaned: The units found, in the format (units found, string in which this occured, power associated with the unit, string which ... | 73,457 |
def get_result_data(result: Dict, value: Union[str, Callable]) -> Any:
"""Returns data from a GCP API call result dict.
Args:
result: Dict containing the result or a GCP API execute() call.
value: Either directly the name of a key found in result or
a callable like a lambda that fin... | 73,458 |
def expr_plot(data,
exp,
dim=[1, 2],
cmap=plt.cm.magma,
marker='o',
s=MARKER_SIZE,
alpha=1,
edgecolors=EDGE_COLOR,
linewidth=EDGE_WIDTH,
w=libplot.DEFAULT_WIDTH,
h=libplot.DEFAULT_... | 73,459 |
def get_blacklists(blacklist_config, filename):
""" Updates blacklist file.
:param blacklist_config: A dict object containing Name/Url key value pairs.
:param filename: File name to write the lists.
"""
blacklists = get_blacklist_items(blacklist_config)
with open(filename, 'w') as f:
j... | 73,460 |
def neighborhood_density_all_words(corpus_context, tierdict, tier_type = None, sequence_type = None,
algorithm = 'edit_distance', max_distance = 1, output_format = 'spelling',
num_cores = -1, settable_attr = None, collapse_homophones = False,
stop_check = None, call_back = None):
... | 73,461 |
def get_user_data(user):
""" Extrats user data to be save in the session """
extract_attrs = current_app.config.get('SESION_USER_FIELDS', [])
user_data = {}
for attr in extract_attrs:
user_data[attr] = getattr(user, attr, None)
return user_data | 73,462 |
def display_hand(hand):
"""
Displays the letters currently in the hand.
For example:
display_hand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
print(CURRENT_HAND... | 73,463 |
def heartBeatListener():
"""
Sends heartbeat requests and listens to responses.
The responses are then sent to each target's watchdog
This is a workaround because we can bind to the same port only once.
"""
listenQueue = getSetting('heartbeatQueue')
# Hardcoded targetId=1 because there is al... | 73,464 |
def pv_optimize_orientation(
objective,
dfsun, info, tznode, elevation,
solpos, dni_et, airmass,
systemtype,
yearsun, resolutionsun,
dflmp=None, yearlmp=None, resolutionlmp=None, tzlmp=None,
pricecutoff=None,
max_angle=60, backtrack=True, gcr=1./3.,
dcac=1.3,
loss_system=0.14... | 73,465 |
def test_get_ghcnd_version_http():
"""
Test version string
:return:
"""
# Check that we start with 3...
version_string = get_ghcnd_version()
assert_equal(version_string[0], "3") | 73,466 |
def sanitize_metric_name(name):
"""Sanitize a metric name by removing double dots.
:param name: Metric name
:return: Sanitized metric name
"""
if name is None:
return None
return ".".join(_components_from_name(name)) | 73,467 |
def del_account(ctx, account_name):
"""delete an account, its keys and all state.
Make sure you have a backup of your whole account directory first.
"""
account_manager = get_account_manager(ctx)
account_manager.del_account(account_name)
click.echo("account deleted: {!r}".format(account_name))
... | 73,468 |
def get_parser():
"""Args Description"""
# current_year = datetime.datetime.today().year
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--data-dir", type=str, help="baseball data directory", default='.... | 73,469 |
def multinomial_mode(
distribution_or_probs: Union[tfd.Distribution, jnp.DeviceArray]
) -> jnp.DeviceArray:
"""Calculates the (one-hot) mode of a multinomial distribution.
Args:
distribution_or_probs:
`tfp.distributions.Distribution` | List[tensors].
If the former, it is assumed that it has... | 73,470 |
def make_test_model(nsources=100, npix=500, ampl=100, fwhm=30):
"""Create a model of several Gaussian sources.
"""
from numpy.random import random
from sherpa.astro.ui import set_source
from morphology.utils import _set, _name
model = ' + '.join([_name(ii) for ii in range(nsources)])
set_sou... | 73,471 |
def get_image(key):
"""Get image by key (index) from images preloaded when starting the viewer by preload_images().
"""
key=int(key)
img = images[key]
img_buffer = io.BytesIO(img)
return send_file(img_buffer,
attachment_filename=str(key)+'.jpeg',
mimetype='image/jpg') | 73,472 |
def pql_PY(state: State, code_expr: T.string, code_setup: T.string.as_nullable() = objects.null):
"""Evaluate the given Python expression and convert the result to a Preql object
Parameters:
code_expr: The Python expression to evaluate
code_setup: Setup code to prepare for the evaluation
N... | 73,473 |
def test_dialogue_end_session_with_empty_text(fs, mocker):
"""Test whether the :func:`snipskit.mqtt.dialogue.end_session` function
works correctly with :meth:`.MQTTSnipsComponent.publish` when the text is
empty.
"""
config_file = '/etc/snips.toml'
fs.create_file(config_file, contents='[snips-co... | 73,474 |
def grok(module_name=None):
"""Grok a module.
Test helper to 'grok' a module named by `module_name`, a dotted
path to a module like ``'mypkg.mymodule'``. 'grokking' hereby
means to do all the ZCML configurations triggered by directives
like ``grok.context()`` etc. This is only needed if your module... | 73,475 |
def load_statics():
"""Reload all static content from their files"""
global questions
global static
for file in ["admin", "end", "index", "question"]:
with open("templates/" + file + ".html") as f:
static[file] = f.read()
for file in ["client"]:
with open("scrip... | 73,476 |
def set_env_variables():
"""
Set different variables if the environment is running on a local machine
or in the sandbox.
:return: a tuple with a string and a boolean
"""
if 'SERVER_SOFTWARE' not in os.environ \
or os.environ['SERVER_SOFTWARE'].startswith('Development'):
# the... | 73,477 |
def assert_equal(actual: Literal["1450T"], desired: Literal["1450T"]):
"""
usage.statsmodels: 7
"""
... | 73,478 |
def farey_alg(n, largest_divisor=100):
"""
This started simple, but then i figured it could be really close and
then come farther away again, so i changed it to a much more complicated
one.
It can still gives a closing range, but it now gives the best
approximate it has come across, not the las... | 73,479 |
def clean(data, columns, inplace=False) -> pd.DataFrame:
"""
Cleans a dataframe
:param data: the dataframe to clean
:param columns: a single column name or list of column names to clean
:param inplace: if True, changes are made to the specified column; otherwise, a 'cleaned'
column is appended t... | 73,480 |
def vector_add(v, w):
"""向量加法"""
return [v_i + w_i for v_i, w_i in zip(v, w)] | 73,481 |
def load_data(
data_list,
batch_categories=None,
profile='RNA',
join='inner',
batch_key='batch',
batch_name='batch',
min_features=600,
min_cells=3,
n_top_features=2000,
batch_size=64,
chunk_size=CHUNK_SIZE,
log=None,... | 73,482 |
def fast_p_val(A, B, axis=0, metric=np.mean, numResamples=10000):
"""Return the p value that metric(A) and metric(B) differ along an axis.
Parameters
----------
A : array_like
Array containing numbers of first group.
B : array_like
Array containing numbers of second group.
... | 73,483 |
def api_categorize():
"""
the API will receive a POST request containing a JSON with the labels title and tags,
with the data provided it'll serve a category that best fit the data
"""
model = CategoryCLF()
all_predicted = list()
if not request.is_json:
r = {"message": "Input is not... | 73,484 |
def is_calldef_pointer(type):
"""returns True, if type represents pointer to free/member function, False otherwise"""
if not is_pointer(type):
return False
nake_type = remove_alias( type )
nake_type = remove_const( nake_type )
nake_type = remove_volatile( nake_type )
return isinst... | 73,485 |
def pytest_runtest_teardown(item):
"""
called after ``pytest_runtest_call``
"""
log.debug("<<<<< END <<<<<<< {0}".format(item.name)) | 73,486 |
def test_rjd():
"""Test rjd"""
covmats, diags, A = generate_cov(100, 3)
V, D = rjd(covmats) | 73,487 |
def collate_amplifyers():
"""Grab the RT and QT columns then concat assign post type and hashtag
Returns:
amplifyers: A dataframe with a filtered columns bearing the fields with the
network
"""
select_columns = ['hit_sentence','influencer','post_type... | 73,488 |
def _get_valid_stan_args(base_args=None):
"""Fill in default values for arguments not provided in `base_args`.
RStan does this in C++ in stan_args.hpp in the stan_args constructor.
It seems easier to deal with here in Python.
"""
args = base_args.copy() if base_args is not None else {}
# Defau... | 73,489 |
def toolchain_upstream_deps():
"""Implements the set of dependencies that bazel-embedded requires.
These targets are used to override the default toolchain
requirements in the remote bazel-embedded toolchain. The remote
toolchain expects to find two targets;
- "@bazel_embedded_upstream_toolchain/... | 73,490 |
def cancel_env_set_get(resources, node, equiv):
"""Simplify combinations of env_get/setitem.
* get(set(env, k1, v), k2, dflt) =>
* v when k1 == k2
* get(env, k2, dflt) when k1 != k2
"""
key1 = equiv[C1]
key2 = equiv[C2]
if key1.value == key2.value:
retur... | 73,491 |
def test_error_types():
"""test that try / except work normally through glom"""
for err_class in ERROR_CLASSES:
def err_raise(t):
raise err_class()
with pytest.raises(err_class):
glom(None, err_raise) | 73,492 |
def ptb_raw_data(data_path="lm_data/", unk_threshold=2):
"""
Args:
data_path: string path to the directory where simple-examples.tgz has
been extracted.
Returns:
tuple (train_data, valid_data, test_data, vocabulary)
where each of the data objects can be passed to PTBIterator.
"""
train_p... | 73,493 |
def plot_linearly_separable_2d(axes, num_samples, weights, limits, rng):
"""
Plot a linearly separable binary data set in a 2d feature space.
# Arguments
axes: a Matplotlib Axes object into which to plot
num_samples: number of samples to generate
(ie, the number of rows in the r... | 73,494 |
def _create_csv(fields, data, fname):
"""Create a new CSV table from a dictionary.
Parameters:
fields (list): a list of the column names. The order of the fields
in the list will be the order in how they are written. ex:
['id', 'precip', 'total']
data (dict): a ... | 73,495 |
def get_donchian(quotes: Iterable[Quote], lookback_periods: int = 20):
"""Get Donchian Channels calculated.
Donchian Channels, also called Price Channels, are derived from highest High and lowest Low values over a lookback window.
Parameters:
`quotes` : Iterable[Quote]
Historical price... | 73,496 |
def getLigandCodeFromSdf ( sdfFileName ):
"""
Funkcja sluzy do pobierania kodow ligandow z pliku .sdf
Wejscie:
sdfFileName - nazwa pliku sdf
Wyjscie:
ligandCodes - lista znalezionych kodow ligandow
"""
sdfFile= open(sdfFileName, 'r' )
line = sdfFile.readline()
ligandC... | 73,497 |
def pav(y):
"""
PAV uses the pair adjacent violators method to produce a monotonic
smoothing of y
translated from matlab by Sean Collins (2006) as part of the EMAP toolbox
Author : Alexandre Gramfort
license : BSD
"""
y = np.asarray(y)
assert y.ndim == 1
n_samples = len(y)
v... | 73,498 |
def publish(protected):
"""Publish blog easily"""
if protected is True:
cliview.warning()
return
Blog.publish() | 73,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.