content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
""" main body """
# constants
x_init = - 1 / 300
end = 15
step = 0.001
# integrate numerically
record, count = num_solve(x_init, x_dot, step, end)
print(record)
# time axis
time = np.linspace(0, end, count)
# plot both solutions in a graph
plt.plot(time, re... | 57,900 |
def ldns_dnssec_rrsets_contains_type(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_rrsets_contains_type(*args) | 57,901 |
def parameters_from_proto(msg: Parameters) -> typing.Parameters:
"""."""
tensors: List[bytes] = list(msg.tensors)
return typing.Parameters(tensors=tensors, tensor_type=msg.tensor_type) | 57,902 |
def create_loopback_interface(interface_name, vrf="default", ipv4=None, interface_desc=None, **kwargs):
"""
Perform a PUT and/or POST call to create a Loopback Interface table entry for a logical L3 Interface. If the
Loopback Interface already exists and an IPv4 address is given, the function will update th... | 57,903 |
def restart_directory_services():
"""
Restarts directory services (opendirectoryd). Only required when executing
script on booted volume.
"""
if is_booted_volume():
subprocess.call(["killall", "opendirectoryd"])
print "Restarted Directory Services" | 57,904 |
def _detail_collection_tuple(worker: AbstractWorker, my_tuple: Tuple) -> Tuple:
"""
This function is designed to operate in the opposite direction of
_simplify_collection. It takes a tuple of simple python objects
and iterates through it to determine whether objects in the collection
need to be conv... | 57,905 |
def fake_check(name='fake_check', tags=None, is_active=True, run_return=None, run_exception=None,
run_logs=None, run_files=None, changed=False, get_var_return=None):
"""Returns a new class that is compatible with OpenShiftCheck for testing."""
_name, _tags = name, tags
class FakeCheck(objec... | 57,906 |
def hasScript(s):
"""Dig out evil Java/VB script inside an HTML attribute.
>>> hasScript('script:evil(1);')
True
>>> hasScript('expression:evil(1);')
True
>>> hasScript('http://foo.com/ExpressionOfInterest.doc')
False
"""
s = decode_htmlentities(s)
s = ''.join(s.split()).lower()
for t ... | 57,907 |
def rename_image(image_path):
"""Take in image path and rename image by site, camera, and datetime."""
# Get image datetime.
with exiftool.ExifTool() as et:
metadata = et.get_metadata(image_path)
datetime_string = re.sub('[^0-9]+', '', metadata['EXIF:DateTimeOriginal'])
if metadata["EXIF:Mak... | 57,908 |
def _open_db():
"""Open the database and set up the tables"""
global _DB
_DB = sqlite3.connect(_DB_FILENAME)
_DB.execute("""CREATE TABLE IF NOT EXISTS kills(
timestamp CHAR(50) NOT NULL,
winner CHAR(50) NOT NULL,
winner_guild CHAR(50) NOT NULL,
loser CHAR(50) NOT NULL,
loser_guild CH... | 57,909 |
def add_link_data(
link_proto: core_pb2.Link,
) -> Tuple[InterfaceData, InterfaceData, LinkOptions, LinkTypes]:
"""
Convert link proto to link interfaces and options data.
:param link_proto: link proto
:return: link interfaces and options
"""
iface1_data = link_iface(link_proto.iface1)
... | 57,910 |
def _create_sender(net_type, msg_queue_size=2*1024*1024*1024):
"""Create a Sender communicator via C api
Parameters
----------
net_type : str
'socket' or 'mpi'
msg_queue_size : int
message queue size (2GB by default)
"""
assert net_type in ('socket', 'mpi'), 'Unknown network... | 57,911 |
def evaluate_predictions_per_char(predictions, original_sentences, answers):
"""Evaluates predictions per char, returning the accuracy and lists of correct and incorrect sentences."""
predicted_chars = []
sentences_with_preds = []
errors = set()
correct_sentences = []
total = 0
correct = 0
... | 57,912 |
def n2es(x):
"""None/Null to Empty String
"""
if not x:
return ""
return x | 57,913 |
def eval_loss_and_grads(generated):
"""
Computes the loss and gradients
:param generated: The generated image
:return: The loss and the gradients
"""
generated = generated.reshape((1, img_height, img_width, 3))
outs = f_outputs([generated])
loss_value = outs[0]
grad_values = outs[1].... | 57,914 |
def check_lh5_groups(f_lh5):
"""
useful but verbose.
open an LH5 file store and identify all groups, datatypes, etc.
"""
def print_attrs(name, obj):
print(name) # show group name only
# show attributes (lh5 datatypes)
for key, val in obj.attrs.items():
print(f" ... | 57,915 |
def rand_no_gen(seed, a, c, m, no_of_randnos):
"""
This function generates a numpy array of random numbers (positive integers) using Linear congruent method
If r_i is initial random number, the next random number in the sequence is given by
r_i+1 = (a*r_i + c) % m
The random numbers generated will ... | 57,916 |
def get_genes(db, location=None, use_strand=False, overlap=True):
"""
Get Gene objects
"""
gene_ids = get_genes_ids(db, location, use_strand, overlap)
genes = {}
for i, gene_id in enumerate(gene_ids):
genes_temp = get_gene(db, gene_id)
if genes_temp:
for ensembl_id, ... | 57,917 |
def test_generate_names_list_with_custom_seed_data_path():
"""
Case: generate random eos list of names with custom seed data path.
Expect: eos names are returned.
"""
data_path = dirname(__file__) + '/' + '../custom_data/data.txt'
runner = CliRunner()
result = runner.invoke(cli, [
'... | 57,918 |
def proc_frac(cases, lcl, frac=True):
"""fraction or sum of process occurrences per case"""
cl_sum = cases.case.apply(lambda x: 0)
for cl in lcl:
cl_sum += cases.case.apply(lambda x: cl_frac_in_case(x, cl, frac=False))
if frac:
sizes = cases.case.apply(lambda x: x.classes.size)
r... | 57,919 |
def _delay_auto_approval(version):
"""Delay auto-approval for the whole add-on for 24 hours."""
# Always flag for human review.
from olympia.addons.models import AddonReviewerFlags
_flag_for_human_review(version)
in_twenty_four_hours = datetime.now() + timedelta(hours=24)
AddonReviewerFlags.obj... | 57,920 |
def _plot_io(**kwargs):
"""
Helper method to optionally save the figure to file.
:param filename: name of the file to save to, defaults to None (doesn't save)
:type filename: str, optional
:param dpi: dpi of figure to save or plot, defaults to 300
:type dpi: int (between 50-500)
:param show... | 57,921 |
def train(net, optimizer, rollout, gamma=0.95):
"""
Train neural network with a given rollout.
"""
state_batch, action_batch, cost_batch, next_state_batch, done_batch = zip(*rollout)
state_batch = torch.FloatTensor(state_batch)
action_batch = torch.FloatTensor(action_batch)
cost_batch = torc... | 57,922 |
def leArquivosNM(local):
"""
deve ler arquivos sem passar na memoria
testar depois
"""
with open(local) as arqui:
for linha in arqui:
print(linha) | 57,923 |
def print_history(request):
"""Печать истории забора материала за день"""
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Table, TableStyle
from reportlab.lib import colors
from reportlab.platypus import Paragraph
from repo... | 57,924 |
def get_source_version(service_name = None, default_version=None):
"""
Gets the source (from) version of a service participating in an upgrade. If there is no
upgrade or the specific service is not participating, this will return None.
:param service_name: the service name to check for, or None to extract it f... | 57,925 |
def strict_match_data(payload):
"""
Takes in explanation data, and a source of unlabeled data and will annotate the unlabeled data
with the explanations provided. Converts explanations into binary labeling functions and if an
explanation applies to a datapoint the label associated with the e... | 57,926 |
def CollectProcesses_NoCache():
"""Collect raw data here, which can be formatted in Parse(). Called from Parse()"""
metrics = []
# Get our rolled-up parent processes for creating metrics
for info in GetParentProcessItems():
is_system_process = False
if not info['cmdline']:
... | 57,927 |
def stop_mdsd():
"""
Stop mdsd process
:return: None
"""
pids = get_lad_pids()
if not pids:
return 0, "Already stopped"
kill_cmd = "kill " + " ".join(pids)
hutil.log(kill_cmd)
RunGetOutput(kill_cmd)
terminated = False
num_checked = 0
while not terminated and num... | 57,928 |
def get_translation_matrix(translation_vector):
"""Convert a translation vector into a 4x4 transformation matrix
"""
T = mx.nd.zeros(translation_vector.shape[0], 4, 4).as_in_context(
context=translation_vector.context)
t = translation_vector.contiguous().view(-1, 3, 1)
T[:, 0, 0] = 1
T... | 57,929 |
def task_install_node_certificates(ca_cert, node_cert, node_key):
"""
Install certificates and private key required by a node.
:param FilePath ca_cert: Path to CA certificate on local machine.
:param FilePath node_cert: Path to node certificate on
local machine.
:param FilePath node_key: Pa... | 57,930 |
def test_package_version() -> None:
"""Test package version calculation."""
assert package_version() == current_version | 57,931 |
def bayes_model_avg_viscous_posterior_2():
""" Plot the viscosity posterior using a Bayesian Model Average
of the visc. correction models.
Beforehand one needs the posteriors of each invididual model,
as well as their mutual Bayes factors calculated. """
colors = matplotlib.cm.Oranges(np.linspace( ... | 57,932 |
async def on_ready():
"""Display information about turning on"""
print(f"{bot.user} is online") | 57,933 |
def json_subscription_property(request, user_profile, subscription_data=REQ(
validator=check_list(
check_dict([["stream", check_string],
["property", check_string],
["value", check_variable_type(
[check_string, check_bool])]... | 57,934 |
def _get_int_axis_extra_coords(cube_list, axis_coord_names, axis_coord_units, axis):
"""
Retrieve all extra coord names and units assigned to a data axis along a
sequence of cubes.
Parameters
----------
cube_list: `list` of `ndcube.NDCube`
The sequence of cubes from which to extract the ... | 57,935 |
def est_shape( bg, tracking_settings_frame=None ):
"""Estimate fly shape from a bunch of sample frames."""
interactive = params.feedback_enabled and tracking_settings_frame is not None
if interactive:
progressbar = \
wx.ProgressDialog('Computing Shape Model',
... | 57,936 |
def get_class_methods(class_item=None):
"""
Returns the class methods of agiven class object
:param class_item: Class item to introspect
:type class_item: object
:returns: list -- Class methods
"""
from types import FunctionType
_type = FunctionType
return [x for x, y in iteritems(c... | 57,937 |
def get_default_benchmark_simulated_datasets():
"""Default parameter sets to generate simulated data for benchmarking.
The training periods and forecast horizon are chosen to complement default real datasets.
Every tuple has the following structure:
(data_name, frequency, training_periods, forecast_hori... | 57,938 |
def plot_figures_dsco_30days(number_of_days=30):
"""
Download and plot the data from DSCOVR for the last 30 days starting from the present time.
"""
print(f"Code execution for DSCOVR 30 days data started at at (UTC):" +
f"{datetime.datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:... | 57,939 |
def load_config(cfg_path):
"""Load the config from a json file"""
if not os.path.exists(cfg_path):
raise RuntimeError('file {} does not exists!'.format(cfg_path))
with open(cfg_path, 'r') as f:
cfg = json.load(f)
return cfg | 57,940 |
def _cleanup_package_deploy():
"""Delete local temp deploy directory."""
local('rm -r /tmp/endaga-packages-deploy') | 57,941 |
def all_reduce_v2(t,
group_size,
group_key,
instance_key,
merge_op='Add',
final_op='Id',
communication_hint='auto',
timeout=0):
"""Reduces tensors collectively, across devices.
Args:
t:... | 57,942 |
def main(args: typing.List[str] = None) -> None:
"""Entry point."""
if args is None:
args = sys.argv[1:]
if "DISABLE_TIMEWARP" not in os.environ:
try:
# Initialize the Time Warp client.
client = Client()
# Process command line arguments.
pars... | 57,943 |
def test_area_with_area_no_root(test_page):
"""Area inside Area"""
test_page.navigate()
t = test_page.area_in_area_no_root.inner_area.link.text
assert "I'm just a link in a div." == t | 57,944 |
def rollback_snapshot(vm_name, snapshot_name):
"""
Restore a VM to a previous state based on the given snapshot.
:param vm_name: the VM name to be restored
:param snapshot_name: the snapshot name to be used for rollback
"""
with RbdManager(CEPH_CONF, POOL_NAME, NAMESPACE) as rbd:
disk_... | 57,945 |
def get_actions(chunkstart, chunkstop, grid):
"""Updates policy for a subsection of the grid with greedy actions.
Input should be the first and last row of the subsection."""
actions = ['up', 'down', 'left', 'right']
new_actions = []
for i in range(chunkstart, chunkstop):
... | 57,946 |
def clientConnectionLost((host, port)):
"""
Called when a connection is lost. Not sure how to use this yet.
"""
debug("connections.py: Connection has been lost?", info=True)
"""
Remove the connection from the node.
"""
todelete = None
for uid in universe:
if universe[uid].get... | 57,947 |
def log(func):
"""Decorator for functions, to log start/end times"""
@wraps(func)
async def wrapper(*args, **kwargs):
_id = uuid.get_and_increment()
args_text = truncate(args, 2000)
kwargs_text = truncate(kwargs, 2000)
logger.debug(f"{func.__name__} ({_id}) called with {args... | 57,948 |
def test_get_homepage(request_hom, test_ssm_parameters):
"""
Run a request through the lambda_handler and save the response for
later testing.
"""
ssm_prefix = os.environ.get("SSM_PREFIX")
stubber = stubs.mock_config_load_ssm_parameters(ssm_prefix, test_ssm_parameters)
with stubber:
... | 57,949 |
def getFirstFrame(video, name):
"""
The function saves the video file's first frame in the current folder.
Params:
video (string): Path to the video file
name (string): Name of the new image
Returns:
name (string): name of the created image
"""
#Open t... | 57,950 |
def deconv_size(input_height, input_width, stride=2):
"""
Compute the feature size (height and width) after filtering with
a specific stride. Mostly used for setting the shape for deconvolution.
Args:
input_height (int): height of input feature
input_width (int): width of input f... | 57,951 |
def add_pagerank(parts_response, uri2rank):
"""
Adds the pagerank score for each part
Arguments:
parts_response {List} -- List containing all parts from the SPARQL query
uri2rank {List} -- List of each part and its calculated pagerank score
"""
for part in parts_response:
s... | 57,952 |
def G(x, alpha, shift=0):
""" Return Gaussian line shape at x with HWHM alpha """
return np.sqrt(np.log(2) / np.pi) / alpha\
* np.exp(-((x - shift) / alpha)**2 * np.log(2)) | 57,953 |
def boolean_op_wrapper(
_cls=None,
*,
and_: Optional[Type[BinaryOp]] = _And,
or_: Optional[Type[BinaryOp]] = _Or,
not_: Optional[Type[UnaryOp]] = _Not,
):
"""
Provide the atom class with __and__, __or__ and __not__ dunder methods.
:param _cls: the class.
:param and_: the class for t... | 57,954 |
def _evaluate_model_single_file(target_folder, test_file):
"""
Evaluate a model for a single recording.
Parameters
----------
target_folder : string
Folder where the model is
test_file : string
The test file (.hdf5)
"""
logger.info("Create running model...")
model_sr... | 57,955 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Modem Caller ID from a config entry."""
device = entry.data[CONF_DEVICE]
api = PhoneModem(device)
try:
await api.initialize(device)
except EXCEPTIONS as ex:
raise ConfigEntryNotReady(f"Unable to o... | 57,956 |
def prettify():
"""Prettifies JS and SCSS code using prettier"""
for cmd in env["box_prettify"]:
run_local(cmd) | 57,957 |
def run_model(task=None, model_name=None, dataset_name=None, config_file=None,
saved_model=True, train=True, other_args=None):
"""
Args:
task(str): task name
model_name(str): model name
dataset_name(str): dataset name
config_file(str): config filename used to modify... | 57,958 |
def _expect_array(obj):
"""Return an ndarray, or raise TypeError."""
if obj in (0, "0"):
return array([ZERO])
if obj in (1, "1"):
return array([ONE])
if obj in ("x", "X"):
return array([LOGICAL])
if obj == "?":
return array([ILLOGICAL])
if isinstance(obj, BoolExpr... | 57,959 |
def internal_rescue(
container: KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType],
function: Callable[
[_SecondType],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
],
) -> KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType]:
"""
Bind a function over a ... | 57,960 |
def test_superbias_fft():
"""Test the SuperbiasFFTTask"""
task = bias.SuperbiasFFTTask()
if RUN_TASKS:
task.run(slots=['S00'], **RUN_OPTIONS) | 57,961 |
def test_polling_locations_valid_config(volttron_instance, query_agent, config,
result_topics, api_wait):
"""
:param volttron_instance:
:param query_agent:
:param config:
:param result_topics:
:return:
"""
agent_uuid = None
try:
agent_... | 57,962 |
def _library_rule_attrs():
"""Returns an attribute dictionary for `swift_library`-like rules.
The returned dictionary contains the same attributes that are defined by the
`swift_library` rule (including the private `_toolchain` attribute that
specifies the toolchain dependency). Users who are authoring... | 57,963 |
def connection_stats():
"""
Get packet statistics.
"""
return qmilib.wds_get_packet_statistics() | 57,964 |
def date_after(d):
"""
Input: an integer d
Quickly find out the actual calendar date of some day in the EPIC dataset.
Output: the date, d days after 2015-06-13 00:00:00.000
"""
t_i = Time("2015-06-13", format='iso', scale='utc') # make a time object
t_new_MJD = t_i.mjd + d #... | 57,965 |
def load_partial_vars(exe, init_model, main_program):
"""tbd"""
assert os.path.exists(init_model), "[%s] cann't be found." % init_model
def existed_params(var):
"""tbd"""
if not isinstance(var, fluid.framework.Parameter):
logging.info("%s not existed", var.name)
retu... | 57,966 |
def __remove_punctuation(string):
"""
Remove all the punctuation symbols and characters in a string.
:param string: the string where the punctation characters must be removed.
:return: a string without punctuation.
"""
return re.sub("[!@#£$.()/-]", "", string) | 57,967 |
def main(image_id: str = '100241706_00005_2'):
"""
Test an annotation drawing the corresponding bounding boxes on an image
:param image_id: the base name of the image to be tested (without file extension)
"""
# Set up all the paths to the images
path_to_dataset = os.path.join('datasets', 'kaggl... | 57,968 |
def pad_chunk_columns(chunk):
"""Given a set of items to be inserted, make sure they all have the
same columns by padding columns with None if they are missing."""
columns = set()
for record in chunk:
columns.update(record.keys())
for record in chunk:
for column in columns:
... | 57,969 |
def username_check(username: str) -> str:
"""
Run a loop to check and determine if a username is valid.
:param username: The username to check.
"""
running = True
while running:
flag1 = True
flag2 = True
if username_exists(username):
print_error(f"'{username... | 57,970 |
def test_collapse_whitespace(mock_osp):
"""
Should collapse all 2-char+ strings of whitespace.
"""
text = 'w1 \n\t w2 \n\t w3'
path = mock_osp.add_file(content=text, ftype='plain')
syllabus = Syllabus(path)
assert syllabus.unbroken_text == 'w1 w2 w3' | 57,971 |
def get_next_match( map ):
""" This changes the inverse table by removing hits"""
todelete = []
retval = None
for px,s in map.iteritems():
if len(s) > 1:
retval = s.pop(),s.pop()
if retval[0][0] == retval[1][0]:
s.add( retval[1] )
#print retval, s
retval = None
co... | 57,972 |
def coefficient(multiset):
""" multinomial coefficient of the multiset """
S = multiset.size_as_nat()
return math.factorial(S) / facto(multiset) | 57,973 |
def prune_model_one_shot_iter(
model: ModelProto, nodes: List[NodeProto], sparsity: Union[float, List[float]]
):
"""
Iteratively prune a model in-place with one shot pruning (no retraining) according
to magnitude pruning. Does so in an unstructured way currently
:param model: the model to apply pru... | 57,974 |
def join_contains():
"""**Flask POST rule.**
Spatial join on two spatial files drived by contains relationship.
---
post:
summary: Spatial join on two spatial files drived by contains relationship.
description: Create a new spatial file on the condition that the geometry of the **other*... | 57,975 |
def download_site(url, q):
"""Request an URL. If it can properly be retrieved, add it to queue
`q` so that it gets written to a file with the job manager."""
global HEADERS
try:
with requests.get(url, headers=HEADERS) as response:
response_length = len(response.content)
p... | 57,976 |
def read_pickle(text_folder_path, file_name):
"""
Read a pickled file from a directory.
Parameters:
text_folder_path (string): path to the directory where the file is located
file_name (string): name of file to read.
Returns:
read_text (string): text read from the pickle file.
"""
... | 57,977 |
def parse_request_table(path: str) -> pd.DataFrame:
"""Return a dict of userid mapped to keywords.
Capitalised columns are in the original file.
Derived columns are all lower case.
"""
df = pd.read_excel(path).dropna()
df["username"] = df["Link"].str.split("/").str[-1]
return df | 57,978 |
def load_model(model_path):
"""
Loads the model from the path specified.
"""
return joblib.load(model_path) | 57,979 |
def parse_system(system):
"""
Parse a system string into a pair of projectiles and a beam energy.
"""
match = re.fullmatch('([A-Z]?[a-z])([A-Z]?[a-z])([0-9]+)', system)
return match.group(1, 2), int(match.group(3)) | 57,980 |
def addIndexList(root):
""" Add an index listing for all terms inside <span class="index-term"> """
indexes = dict()
for num, node in enumerate(CSSSelector('span.index-term')(root)):
term = node.text_content().strip()
term_id = 'index-term-%d' % num
node.attrib['id'] = term_id
... | 57,981 |
def is_negligible(in_text):
"""" Checks if text or tail of XML element is either empty string or None"""
if in_text is None:
return True
elif type(in_text) is str:
if in_text.strip(chr(160) + ' \t\n\r') == '':
return True
else:
return False
else:
r... | 57,982 |
def get_MD5(file: Union[BufferedReader, str]) -> str:
"""
Creates a MD5 hash of a file
"""
buffered_file: BufferedReader = None
if isinstance(file, str):
buffered_file = open(file, 'rb')
else:
buffered_file = file
chunk_size = 8192
h = md5()
while True:
chu... | 57,983 |
def pytest_addoption(parser):
"""declare options to be used when invoking pytest"""
config = ConfigOption(
"config",
"default.conf",
"the configuration file",
searchpath=SCRIPTDIR
)
options = (
Option(name="x", default="defaultx", help="option x"),
Optio... | 57,984 |
def logbuf(msg, buf):
"""used for debugging test code."""
if buf is None:
buf = b''
logmsg(msg + ': [' + str(len(buf)) + ']')
for i in list(range(0, len(buf), 48)):
logmsg(' ' + repr(buf[i:i+48]))
return | 57,985 |
def jsd_distance_0(x_list, data_list):
"""
:param
x:
a list or an np.ndarray
data:
a list or an np.ndarray
:return:
jsd_list
measure distance between numbers
"""
jsd_list = []
x_list = single_point_list_2_list(x_list)
data_list = pa... | 57,986 |
def test_SynthDefCompiler_basic_04_supriya_vs_bytes(py_synthdef_04):
"""
FreeSelf.
"""
# fmt: off
test_compiled_synthdef = bytes(
b'SCgf'
b'\x00\x00\x00\x02'
b'\x00\x01'
b'\x04test'
b'\x00\x00\x00\x02'
b'C\xdc\x00\x00'
... | 57,987 |
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4]
if isprecise:
... | 57,988 |
def apply_backoff(strategy = None,
max_tries = None,
max_delay = None,
catch_exceptions = None,
on_failure = None,
on_success = None):
"""Decorator that applies a backoff strategy to a decorated function/method.
:param st... | 57,989 |
def make_a_tweet(Hash, Message, Reduced):
"""
Generate a valid tweet using the info passed in.
"""
tweet = Hash + ': ' + Message
if Reduced:
tweet += '…'
return tweet | 57,990 |
def ldns_pkt_edns_udp_size(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_edns_udp_size(*args) | 57,991 |
def folder_delete(args, batch_dict=None):
"""
Read in the batch file, clean up the arguments, run the AzureDelete class for each folder
:param args: type ArgumentParser arguments
:param batch_dict: type Pandas dataframe.transpose().to_dict()
"""
# If batch_dict has not been supplied by the... | 57,992 |
def split_some_by_age(
files_data: Mapping[str, np.ndarray],
metadata
) -> Clients_X_y:
""" Split the datum points (X,y) into three sets based on the age of the patients.
Like `split_by_age`, except the first two sets are mixed. In effect, yes, this
implies that the first value in age_lims i... | 57,993 |
def connect_all_nodes(nodes, sleep_time: float = 0.5):
"""Connect all nodes to each other.
Args:
nodes: A tuple of grid clients.
"""
for i in range(len(nodes)):
for j in range(i):
node_i, node_j = nodes[i], nodes[j]
node_i.connect_grid_node(node_j, sleep_time=sle... | 57,994 |
def _get_size(obj, seen=None):
"""
Recursively find the actual size of an object, in bytes.
Taken as-is (with tweaked function name) from https://github.com/bosswissam/pysize.
"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
... | 57,995 |
def search_with_id(student_id):
"""
Obtain the username for a user with a given Student ID number (if server is tied into WPI network).
:param student_id: Student ID number to use in the search
:return: The user's network username
"""
try:
username = os.popen('id +' + str(student_id) + ... | 57,996 |
async def fetch_confirmed_proposals(request, next_id):
"""Get confirmed proposals for a user, by their next_id."""
log_request(request)
head_block = await get_request_block(request)
start, limit = get_request_paging_info(request)
conn = await create_connection()
proposals = await proposals_query... | 57,997 |
def main_call_twitter_api(start_dates, bearer_token):
"""
This adds one day at the time, for 6 days, and save the returned API
responses into a json format. Where each json file is a day
Parameters
----------
start_dates : list
A list of dates that have not been utilised in the
... | 57,998 |
def get_first_transcript_name(fasta_file):
"""Return the first FASTA sequence from the given FASTA file.
Keyword arguments:
fasta_file -- FASTA format file of the transcriptome
"""
with open_pysam_file(fname=fasta_file, ftype='fasta') as f:
transcript_name = f.references[0]
return tran... | 57,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.