content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_code(base_dir):
"""
creates a folder structure starting from the base_dir based on the hierarchy of
the commands, with a folder for each command containing an __init__ module
that contains the "verb" functions (if any) associated with that command
"""
commands = get_commands()
... | 45,100 |
def javascript():
"""
Return javascript library for the Sage Notebook. This is done by
reading the template ``notebook_lib.js`` where all of the
javascript code is contained and replacing a few of the values
specific to the running session.
Before the code is returned (as a string), it is run ... | 45,101 |
def _attach_decorators(flow, decospecs):
"""
Attach decorators to all steps during runtime. This has the same
effect as if you defined the decorators statically in the source for
every step. Used by --with command line parameter.
"""
# Attach the decorator to all steps that don't have this decor... | 45,102 |
def load_coedit_data(resource_dir):
"""Load preprocessed data about edit overlap between users."""
app.logger.info("Loading co-edit data")
expected_header = ["user_text", "user_neighbor", "num_pages_overlapped"]
with open(os.path.join(resource_dir, "coedit_counts.tsv"), "r") as fin:
assert next(... | 45,103 |
def fahrenheit2celsius(f: float) -> float:
"""Utility function to convert from Fahrenheit to Celsius."""
return (f - 32) * 5/9 | 45,104 |
def loadFireTurnMap():
"""load in hard-coded 11x11 fire turn map, then flip so that access is [x][y] to match Board access"""
boardSize = 11
fireMapFile = open( "fireTurnMap.txt", "r" )
data = [[int(n) for n in line.split()] for line in fireMapFile]
fireMapFile.close()
rotated = [[None for j in ... | 45,105 |
def get_param_list(params, mode='grid', n_iter=25):
"""
Get a list with all the parameter combinations that will be tested
for optimization.
Parameters
----------
params: dictionary
Each key corresponds to a parameter.
The values correspond to a list of parameters to be exp... | 45,106 |
def debugMsg(message):
"""Debuging function prints given mesage to stderr.
Args:
message (whatever): Debug mesage to print on stderr.
"""
pass
# print(message, file=sys.stderr)
# print("="*60, file=sys.stderr) | 45,107 |
def _apple_universal_binary_rule_transition_impl(settings, attr):
"""Rule transition for `apple_universal_binary` supporting forced CPUs."""
forced_cpus = attr.forced_cpus
platform_type = attr.platform_type
new_settings = dict(settings)
# If forced CPUs were given, first we overwrite the existing C... | 45,108 |
def xml_get_text(_node):
"""Helper function to get character data from an XML tree"""
rc = list()
for node in _node.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return unquote(''.join(rc)) | 45,109 |
def volume_get_all(context, marker, limit, sort_keys=None, sort_dirs=None,
filters=None, offset=None):
"""Retrieves all volumes.
If no sort parameters are specified then the returned volumes are sorted
first by the 'created_at' key and then by the 'id' key in descending
order.
:... | 45,110 |
def merge_multirnn_lstm_state(states, w, b):
""" Given two multirnn lstm states, merge them into a new state of the same shape, merged by concatation and then projection
Args:
state1: the first state to mergem, of shape (s1, s2, s3, ...),
each s is of shape LSTMStateTuple(c,... | 45,111 |
def gen_iocs(indicator_list):
"""
Generates a list of IOCs from a list of Anomali indicators
:param indicator_list: list of Anomali indicators, types ip_address, url, or domain
:return: list of IOC objects
"""
ioc_list = list()
for i in indicator_list:
pp = process_pattern(i.get('pat... | 45,112 |
def run_job(job_id, run_date, user_id, rerun_flag,
schedule_id, schedulelog_id, mark_complete=False):
"""
run the job
"""
logging.debug('run_job for id: %s', str(job_id))
"""
status: job_id,
success/failure: 0 - failure, 1 success , 2 - not ready
job object
... | 45,113 |
def extension_file_from_string(toolchain, ext_file, source_string,
source_name="module.cpp", debug=False):
"""Using *toolchain*, build the extension file named *ext_file*
from the source code in *source_string*, which is saved to a
temporary file named *source_name*. Raise :exc:`CompileError` in
... | 45,114 |
def format_and_save_plot(ax, title, output_img=None, x_label='', y_label='',
show_legend=True, horiz_grid=True, show=False):
"""
Utility function that formats a plot and saves it to a file. Also closes the current plot.
This gives the generated plots a uniform look-and-feel across t... | 45,115 |
def to_indexable(*args, **kwargs):
"""Ensure that all args are an indexable type.
Conversion runs lazily for dask objects, immediately otherwise.
Parameters
----------
args : array_like or scalar
allow_scalars : bool, optional
Whether to allow scalars in args. Default is False.
"""... | 45,116 |
def parse_input_specifications() -> dict[str, InputFile]:
"""
Ingest the input specs file and return a dictionary of the data.
"""
with open(PATH_INPUT_SPECS, 'r') as f:
reader = csv.reader(f)
next(reader)
input_files = {}
for row in reader:
if not any(row)... | 45,117 |
def image_base64(img):
"""Return image as base64."""
if isinstance(img, str):
img = get_thumbnail(img)
with BytesIO() as buffer:
img.save(buffer, "jpeg")
return base64.b64encode(buffer.getvalue()).decode() | 45,118 |
def read_file(file):
"""This function reads the raw data file, gets the scanrate and stepsize
and then reads the lines according to cycle number. Once it reads the data
for one cycle, it calls read_cycle function to denerate a dataframe. It
does the same thing for all the cycles and finally returns a di... | 45,119 |
def data_loader(parent_dir='',
dataset_list=('HD1', 'HD2', 'HD3', 'HD4', 'HD5', 'HD6'),
min_gap=1,
max_gap=4,
min_stride=1,
max_stride=2,
epochs=-1,
batch_size=1,
random_lighting=False,
... | 45,120 |
def calculate_performance(data):
"""Calculates swarm performance using a performance function"""
df = pd.DataFrame(data)
prev_column = None
V = 0
G = 0
C = 0
vcount = 0
gcount = 0
ccount = 0
for column in df:
v = calculate_max_speed(df, column, prev_column)
g = calculate_vertical_mse(df, column)
c = c... | 45,121 |
def ipn(request):
"""
Webhook handling for Coinbase Commerce
"""
if request.method == 'POST':
request_sig = request.META.get('HTTP_X_CC_WEBHOOK_SIGNATURE', None)
'''
# this was done in flask = request.data.decode('utf-8')
try:
# signature verificatio... | 45,122 |
def get_decomposed_entries(structure_type, species):
"""
Get decomposed entries for mix types
Args:
structure_type(str): "garnet" or "perovskite"
species (dict): species in dictionary.
structure_type(str): garnet or perovskite
Returns:
decompose entries(list):
... | 45,123 |
def nf_step_to_process(step, out_handle):
"""Convert CWL step into a nextflow process.
"""
pprint.pprint(step)
directives = []
for req in step["task_definition"]["requirements"]:
if req["requirement_type"] == "docker":
directives.append("container '%s'" % req["value"])
e... | 45,124 |
def init_db():
"""Initializes the database."""
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit() | 45,125 |
def create_job_script(m):
"""
This is the first function that runs when a user initializes a new untargeted workflow
"""
#setup directories
if not os.path.isdir(m['basedir']):
os.mkdir(m['basedir'])
dirs_to_make = ['job_scripts','logs','intermediate_results','%s_%s'%(m['basename'],m['... | 45,126 |
def closest_point(p1, p2, s):
"""closest point on line segment (p1,p2) to s; could be an endpoint or midspan"""
#if the line is a single point, the closest point is the only point
if p1==p2:
return (0,p1)
seg_vector = vector_diff(p2,p1)
seg_mag = mag(seg_vector)
#print( "seg_ve... | 45,127 |
def new_name():
"""
Returns a new legal identifier in C each time it's called
Note: Not thread-safe in its current incarnation
>>> name1 = new_name()
>>> name2 = new_name()
>>> name1 != name2
True
"""
global _num_names
_num_names += 1
return '_id_{}'.format(_num_names) | 45,128 |
def pollard_brent_f(c, n, x):
"""Return f(x) = (x^2 + c)%n. Assume c < n.
"""
x1 = (x * x) % n + c
if x1 >= n:
x1 -= n
assert x1 >= 0 and x1 < n
return x1 | 45,129 |
def morphological_transformation(input_dir):
""" Performs advanced morphological transformations.
Args:
input_dir: Input Picture Data Stream.
Returns:
Picture Data Stream after Rotation Correction Processing.
"""
raw_image = cv2.imread(input_dir)
gray_image = cv2.cvtColor(raw_... | 45,130 |
def fmt_to_datatype_v3(fmt, shape, array=False):
"""convert numpy dtype format string to mdf versions 2 and 3
channel data type and size
Parameters
----------
fmt : numpy.dtype
numpy data type
shape : tuple
numpy array shape
array : bool
disambiguate between bytearra... | 45,131 |
def import_this(**kwargs):
"""Print the Zen of Python"""
# https://stackoverflow.com/a/23794519
zen = io.StringIO()
with contextlib.redirect_stdout(zen):
import this # noqa: F401
text = f"```{zen.getvalue()}```"
return text | 45,132 |
def getCurrentPane():
"""Retrieve the current pane index as an int."""
return int(tget("display-message -p '#P'")) | 45,133 |
def get_lcc_size(G,seed_nodes):
"""
return the lcc size
"""
# getting subgraph that only consists of the black_nodes
g = nx.subgraph(G,list(seed_nodes))
if g.number_of_nodes() != 0:
# get all components
max_CC = max(nx.connected_component_subgraphs(g), key=len)
return ... | 45,134 |
def IsParalogLink(link, cds1, cds2):
"""sort out ortholog relationships between
transcripts of orthologous genes.
"""
map_a2b = alignlib_lite.makeAlignmentVector()
alignlib_lite.AlignmentFormatEmissions(
link.mQueryFrom, link.mQueryAli,
link.mSbjctFrom, link.mSbjctAli).copy(map_a2b... | 45,135 |
def segments(points):
"""
Return the bounded segments of the Voronoi diagram of the given points.
INPUT:
- ``points`` -- a list of complex points
OUTPUT:
A list of pairs ``(p1, p2)``, where ``p1`` and ``p2`` are the
endpoints of the segments in the Voronoi diagram.
EXAMPLES::
... | 45,136 |
def test_appending_tags_inline_is_persisted(db_session):
"""
In-place changes to Annotation.tags should be persisted.
Changes made by Annotation.tags.append() should be persisted to the
database.
"""
annotation = Annotation(userid='fred')
annotation.tags = [] # FIXME: Annotation should ha... | 45,137 |
def spew(path, data, owner=None):
""" Writes data to path
Arguments:
path: path of file to write to
data: contents to write
owner: optional owner of file
"""
with open(path, 'w') as f:
f.write(data)
if owner:
try:
chown(path, owner)
except:
... | 45,138 |
def git_clone(url):
"""Run 'git clone' with a given url."""
execute("git clone {}".format(url)) | 45,139 |
def tpu_ordinal_fn(shard_index_in_host, replicas_per_worker):
"""Return the TPU ordinal associated with a shard."""
return shard_index_in_host % replicas_per_worker | 45,140 |
def replace_example_chapter(path_to_documentation, chapter_lines):
"""func(path_to_doc._tx, [new_chapter]) -> [regenerated_documentation]
Opens the documentation and searches for the text section
separated through the global marks START_MARK/END_MARK. Returns
the opened file with that section replaced by c... | 45,141 |
def trajectory_plt(model, inputs, targets, timesteps, highlight_inputs=False,
include_arrow=False, save_fig=''):
"""Plots trajectory of input points when evolved through model. Works for 2
and 3 dimensions.
Parameters
----------
model : anode.models.ODENet instance
inputs : ... | 45,142 |
def debug(msg):
"""A debugging function"""
if options.debug:
print(msg) | 45,143 |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if(winner(board)):
return True
for i in range(3):
for j in range(3):
if(board[i][j]==EMPTY):
return False
return True | 45,144 |
def combine_files(
uvis_file_names: List[str],
release_number: int,
uvis_dir: Path,
spice_dir: Path,
uvis_projector: UVISAuroralProjector,
projection_dir: Path,
sensitivity: int = 1,
creator: str = "unknown",
n_workers: Optional[int] = None,
overwrite: bool = False,
compress:... | 45,145 |
def get_network(layers, phase):
"""Get structure of the network.
Parameters
----------
layers : list
list of layers parsed from network parameters
phase : int
0 : train
1 : test
"""
num_layers = len(layers)
network = OrderedDict()
for i in xrange(num_layers)... | 45,146 |
def create_category_hiearchy(cats, categoryType):
"""A function that creates a dict of the root and subroot categories"""
dict_out = {}
for key in cats.keys():
name = cats[key]['name']
parent_name = cats[key]['parent']['name']
cat_type = cats[key]['categoryType']
if cat_typ... | 45,147 |
def run(event, _context):
""" save string API Key as SecureString """
graphql_api_key_key_path = os.environ.get('GRAPHQL_API_KEY_KEY_PATH')
print("graphql_api_key_key_path =", graphql_api_key_key_path)
graphql_api_key = _get_parameter(graphql_api_key_key_path)
if graphql_api_key:
_save_secur... | 45,148 |
def date():
"""
Returns the current time formated with HTTP format.
@return: `str`
"""
return time.strftime('%a, %d %b %Y %H:%M:%S GMT') | 45,149 |
def _estimate_gaussian_covariances_tied(resp, X, nk, means, reg_covar):
"""Estimate the tied covariance matrix.
Parameters
----------
resp : array-like of shape (n_samples, n_components)
X : array-like of shape (n_samples, n_features)
nk : array-like of shape (n_components,)
m... | 45,150 |
def rights(value_strategy: SearchStrategy[A]
) -> SearchStrategy[either.Right[A]]:
"""
Create a search strategy that produces `pfun.either.Right` values
Args:
value_strategy: search strategy to draw values from
Example:
>>> rights(integers()).example()
Right(0)
Re... | 45,151 |
def lpad(col, len, pad):
"""
Left-pad the string column to width `len` with `pad`.
>>> df = spark.createDataFrame([('abcd',)], ['s',])
>>> df.select(lpad(df.s, 6, '#').alias('s')).collect()
[Row(s=u'##abcd')]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.lp... | 45,152 |
def dsds_multigroup1():
"""Use the fact that given u=nu/temp
if κ = u⁻³, κ_p^g = [ln(1 - e^(-u)]_g^{g+1}
"""
Nr, Nt, Np, Ng = 30, 80, 1000, 100
nu = np.logspace(-1, np.log10(50e3), Np+1)
dens = np.logspace(-8, 2, Nr)
temp = np.logspace(0.01, 5, Nt)
groups_idx = np.array(np.linspa... | 45,153 |
def get_audio_features(audios_data, audio_tStamp, frameRate, video_length, device='cuda'):
"""audio feature extraction"""
extractor = ResNet50().to(device)
output1 = torch.Tensor().to(device)
output2 = torch.Tensor().to(device)
extractor.eval()
patchSize = 224
frameSkip = 2
with torch.n... | 45,154 |
async def node_watch_profile_report_builder(data_id: str):
"""
Allows the front-end to update the display information once a profile report builds successfully.
Necessary because the profile report entails opening a separate tab.
"""
time_waited = 0
while time_waited < 600:
if fs.profile... | 45,155 |
def write_report_systemsorted(system, username):
""" function that prepares return values and paths """
"""
the return values (prefix 'r') are used for the `mkdocs.yml` file
they build the key-value-pair for every system
"""
# return system_id for mkdocs.yml
rid = str(system.system_id)
... | 45,156 |
def compute_entailment_graph_agreement(graph1, graph2):
"""
Compute the agreement for the entailment graph: entities, arguments and predicates
:param graph1: the first annotator's graph
:param graph2: the second annotator's graph
:return:
"""
# Compute the agreement for the entity e... | 45,157 |
def main(argv=None):
""" Runs the main program.
:param argv: The command line arguments.
:return: The return code for the program's termination.
"""
args, ret = parse_cmdline(argv)
if ret != GOOD_RET or args is None:
return ret
kbt = calc_kbt(args.temp)
if args.src_file is not... | 45,158 |
def test_number_of_nodes_edges():
"""
Test getting number of nodes and edges in an NxGraph.
"""
g = get_graphs()[1]
assert g.number_of_nodes() == 5
assert g.number_of_edges() == 3 | 45,159 |
def is_outlier(points, threshold=3.5):
"""
This returns a boolean array with "True" if points are outliers and "False" otherwise.
These are the data points with a modified z-score greater than
this:
# value will be classified as outliers.
"""
# transform into vectors
if len(points.shape) =... | 45,160 |
def describe_configuration_recorder_status(ConfigurationRecorderNames=None):
"""
Returns the current status of the specified configuration recorder. If a configuration recorder is not specified, this action returns the status of all configuration recorders associated with the account.
See also: AWS API Docu... | 45,161 |
def load_cogs(bot: commands.Bot, cogs_list: list, cogs_path: str) -> str:
"""
Функция для загрузки когов бота.
:param bot: Бот, для которого загружаются коги.
:param cogs_list: Список когов, которые загружаются.
:param cogs_path: Путь к когам, которые загружаются.
"""
for cog in cogs_l... | 45,162 |
def hill_climbing_random_restart(problem,restarts=10):
"""From the initial node, keep choosing the neighbor with highest value,
stopping when no neighbor is better. [Figure 4.2]"""
# restarts = cantidad de reinicios aleatorios al llegar a un estado inmejorable
current = Node(problem.initial)
best =... | 45,163 |
def ordinal(n):
"""Converts an integer into its ordinal equivalent.
Args:
n: number to convert
Returns:
nth: ordinal respresentation of passed integer
"""
nth = "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4])
return nth | 45,164 |
def check_date(date):
"""check if date string has correct format.
Args:
date as a string mmddyyyy
Returns:
a boolean indicating if valid (True) or not (False)
"""
if len(date) != 8:
return False
if not date.isdigit():
return False
# months are between '01' ~... | 45,165 |
async def expected_raceplan_individual_sprint_27_contestants(
event_individual_sprint: dict,
) -> Raceplan:
"""Create a mock raceplan object - 27 contestants."""
raceplan = Raceplan(event_id=event_individual_sprint["id"], races=list())
raceplan.id = "390e70d5-0933-4af0-bb53-1d705ba7eb95"
raceplan.no... | 45,166 |
def signal_to_m_converter(dataframe, dbm="4(dBm)"):
"""
This function convert a (beacon)dataframe with signal values from the tracer
to the corresponding *m*eter values, depend on dBm power that was used.
By default dbm = 4(dBm)
"""
# extract all different values from dataframe
dataframe_uni... | 45,167 |
def return_lines_as_list(file):
"""
:rtype: list of str
"""
# read lines
lines = file.readlines()
def strip(string):
"""
Removes whitespace from beginning and end of string
:type string: str
"""
return string.strip()
# Coverts our lines to list
... | 45,168 |
def cvInitMatNDHeader(*args):
"""cvInitMatNDHeader(CvMatND mat, int dims, int type, void data=None) -> CvMatND"""
return _cv.cvInitMatNDHeader(*args) | 45,169 |
def getObjectInfo(fluiddb, objectId):
"""
Get information about an object.
"""
return fluiddb.objects[objectId].get(showAbout=True) | 45,170 |
def calculate_logAUC(true_y, predicted_score, FPR_range=(0.001, 0.1)):
"""
Calculate logAUC in a certain FPR range (default range: [0.001, 0.1]).
This was used by previous methods [1] and the reason is that only a
small percentage of samples can be selected for experimental tests in
consideration of... | 45,171 |
def format_inline(str_, reset='normal'):
"""Format a string if there is any markup present."""
if const.regex['url'].search(str_):
text = slugify(str_.split('[[')[1].split('][')[1].split(']]')[0])
str_ = const.regex['url'].sub(const.styles['url'] + text + const.styles[reset], str_)
for key,... | 45,172 |
def procces_data(formatted_input):
"""
Purpose:
Proccess data
Args:
formatted_input - formatted input data
Returns:
proccesed_data - processed input
"""
# TODO
logging.info("Processing Data")
return formatted_input | 45,173 |
def stat_bwa(workflow, conf): ## use samtools to parse mappable reads from bwa
"""
bam files are filtered by samtools -q 1, so mapped reads are considered to be unique
"""
for t in conf.sample_targets:
stat = attach_back(workflow, ShellCommand(
"""
{tool} view -Sc {input[sam]} > ... | 45,174 |
def serialize_values(
data_dictionary: Dict[str, Any], data_format: PersistedJobDataFormat
) -> Dict[str, Any]:
"""
Serializes the `data_dictionary` values to the format specified by `data_format`.
Args:
data_dictionary (Dict[str, Any]): Dict whose values are to be serialized.
data_form... | 45,175 |
def print_level_order(tree):
"""
prints each level of k-tree on own line
input <--- Tree
output <--- Prints nodes level by level
"""
if not isinstance(tree, KTree):
raise TypeError('argument must be of type <KTree>')
all_strings = []
def recurse(nodelist):
nonlocal all... | 45,176 |
async def admin_cmd_set_prefix(message: discord.Message, args: str, isDM: bool):
"""admin command setting the calling guild's command prefix
:param discord.Message message: the discord message calling the command
:param str args: the command prefix to use
:param bool isDM: Whether or not the command is... | 45,177 |
def test_oversized_ring():
"""Test SELFIES that have a ring, with Q so large that the (Q + 1)-th
previously derived atom does not exist.
"""
assert decode_eq("[C][C][C][C][Ring1][O]", "C1CCC1")
assert decode_eq("[C][C][C][C][Ring2][O][C]", "C1CCC1")
# special case: Ring2 takes Q_1 = [O] and Q_... | 45,178 |
def spark_add():
"""ReduceByKey with the addition function.
:input RDD data: The RDD to convert.
:output Any result: The result.
"""
def inner(data: pyspark.rdd.RDD) -> ReturnType[pyspark.rdd.RDD]:
o = data.reduceByKey(lambda a,b: a+b)
return ReturnEntry(result=o)
return inner | 45,179 |
async def test_setup_entry_encrypted_missing_device_info_none(hass):
"""Test setup with encrypted config entry and device info set to None."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=MOCK_CONFIG_DATA[CONF_HOST],
data={**MOCK_CONFIG_DATA, **MOCK_ENCRYPTION_DATA},
)
... | 45,180 |
def edit():
"""
Allows the user to edit or delete a reservation
"""
user = db.session.query(models.Rideshare_user).filter(models.Rideshare_user.netid == session['netid']).first()
form = forms.EditReservationFactory()
reservation = None
rideNumber = request.args.get('rideNo')
userHasRev=c... | 45,181 |
def webapp():
"""Create a webapp fixture for accessing the site.
Just include 'webapp' as an argument to the test method to use.
"""
# Create a webtest Test App for use
testapp = flask.ext.webtest.TestApp(dnstwister.app)
testapp.app.debug = True
# Clear the cache
dnstwister.c... | 45,182 |
async def study_export(
app: web.Application,
tmp_dir: str,
project_id: str,
user_id: int,
product_name: str,
archive: bool = False,
formatter_class: Type[BaseFormatter] = FormatterV2,
) -> Path:
"""
Generates a folder with all the data necessary for exporting a project.
If archi... | 45,183 |
def gen_fileext_type_map():
"""
Generate previewed file extension and file type relation map.
"""
d = {}
for filetype in list(PREVIEW_FILEEXT.keys()):
for fileext in PREVIEW_FILEEXT.get(filetype):
d[fileext] = filetype
return d | 45,184 |
def umm_fields(item):
"""Return only the UMM part of the data"""
return scom.umm_fields(item) | 45,185 |
def alert_following_list(organization_id: UUID = typer.Argument(..., help="UUID of the organization"),
following_ids: Optional[List[UUID]] = typer.Option(None, help="Only list alerts from the specified scan targets."),
state: Optional[List[AlertState]] = typer.Option(
... | 45,186 |
def test_create_compute_service(publisher_ocean_instance):
"""Tests that a compute service is correctly created.
Includes cluster, container and server creation."""
ocn_compute = publisher_ocean_instance.compute
cluster = ocn_compute.build_cluster_attributes("kubernetes", "/cluster/url")
container... | 45,187 |
def converts_to_message(*args):
"""Decorator to register a custom NumPy-to-Message handler."""
def decorator(function):
for message_type in args:
if not issubclass(message_type, Message):
raise TypeError()
_to_message[message_type] = function
return f... | 45,188 |
def oil_rho_sat(
rho0: NDArrayOrFloat, g: NDArrayOrFloat, rg: NDArrayOrFloat, b0: NDArrayOrFloat
) -> NDArrayOrFloat:
"""Calculate the gas saturated oil density
B&W Eq 24
Args:
rho0: The oil reference density (g/cc) at 15.6 degC
g: The gas specific gravity
rg: The Gas... | 45,189 |
def astar(array, start, goal):
"""A* algorithm for pathfinding.
It searches for paths excluding diagonal movements. The function is composed
by two components, gscore and fscore, as seem below.
f(n) = g(n) + h(n)
"""
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
close_set = set()
cam... | 45,190 |
def download_jar(req, domain, app_id):
"""
See ApplicationBase.create_jadjar
This is the only view that will actually be called
in the process of downloading a complete CommCare.jar
build (i.e. over the air to a phone).
"""
response = HttpResponse(mimetype="application/java-archive")
a... | 45,191 |
def fetch_sss_files(p, subjects, run_indices):
"""Pull SSS files (only designed for *nix platforms)"""
if len(subjects) == 0:
return
includes = []
for subj in subjects:
includes += ['--include', subj,
'--include', op.join(subj, 'sss_fif'),
'--inc... | 45,192 |
def cond(addr, condexpr):
"""
set a condtion breakpoint at addr.
"""
return setBreakpoint(addr, False, condexpr) | 45,193 |
def get_host_credentials(config, hostname):
"""Get login information for a host `hostip` (ipv4) from marvin's `config`
@return the tuple username, password for the host else raise keyerror"""
for zone in config.get('zones', []):
for pod in zone.get('pods', []):
for cluster in pod.get('c... | 45,194 |
def is_flat_dtype(dtype: np.dtype) -> bool:
"""
Determines whether a numpy dtype object is flat.
Checks whether the ``dtype`` just encodes one element or a shape. A dtype
can characterise an array of other base types, which can then be embedded
as an element of another array.
Parameters
--... | 45,195 |
def _solarize_impl(pil_img, level):
"""Applies PIL Solarize to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Image... | 45,196 |
def version_flash(cmd="flash"):
"""Return the version of flash (as a short string).
Parses the output with ``-v``::
$ flash -v | head -n 1
FLASH v1.2.11
It would capture the version from the first line as follows:
>>> version_flash()
'v1.2.11'
If the command is not on the pa... | 45,197 |
def initialise_df(*column_names):
"""
Initialise a pandasdataframe with n column names
:param str column_names: N column names
:return: Empty pandas dataframe with specified column names
"""
return pd.DataFrame(columns=column_names) | 45,198 |
def _get_reporting_category(context):
"""Returns the current member reporting category"""
member = _get_member(context)
return member[TransactionLoops.MEMBER_REPORTING_CATEGORIES][-1] | 45,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.