content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def batchify_rays(rays_flat, chunk=1024*32, random_directions=None, background_color=None, **kwargs):
"""Render rays in smaller minibatches to avoid OOM.
"""
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(rays_flat[i:i+chunk], random_directions=random_directions, ba... | 5,337,900 |
def extract_surfaces(pvol):
""" Extracts surfaces from a volume.
:param pvol: input volume
:type pvol: abstract.Volume
:return: extracted surface
:rtype: dict
"""
if not isinstance(pvol, BSpline.abstract.Volume):
raise TypeError("The input should be an instance of abstract.Volume")
... | 5,337,901 |
def read_file(filepath: str, config: Config = DEFAULT_CONFIG) -> pd.DataFrame:
"""
Read .csv, .xlsx, .xls to pandas dataframe. Read only a certain sheet name and skip
to header row using sheet_name and header_index.
:filepath: path to file (str)
:config: dtype.Config
Returns pd.Dat... | 5,337,902 |
async def alterar_nome(usuario: Usuario, nome: str) -> None:
"""
Altera o nome do usuário que já está conectado.
:param usuario: O usuário que receberá o nome.
:param nome: O nome que deve ser atribuído ao usuário.
"""
nome_antigo = usuario.nome
if await usuario.atribuir_nome(nome):
... | 5,337,903 |
def euler2quaternion( euler_angs ):
"""
Description
-----------
This code is directly from the following reference
[REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr
Conv... | 5,337,904 |
def run_server(server, thread=False, port=8080):
"""
Runs the server.
@param server if None, it becomes ``HTTPServer(('localhost', 8080), SimpleHandler)``
@param thread if True, the server is run in a thread
and the function returns right away,
... | 5,337,905 |
def validate(aLine):
"""
>>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,12.1,20.0*0F")
[b'GPGSA', b'A', b'2', b'29', b'19', b'28', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'23.4', b'12.1', b'20.0']
>>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceb... | 5,337,906 |
def matlabize(s):
"""Make string s suitable for use as a MATLAB function/script name"""
s = s.replace(' ', '_')
s = s.replace('.', '_')
s = s.replace('-', '_')
assert len(s) <= 63 # MATLAB function/script name length limitation
return s | 5,337,907 |
def getApiResults(case, installer, version, criteria):
"""
Get Results by calling the API
criteria is to consider N last results for the case success criteria
"""
results = json.dumps([])
# to remove proxy (to be removed at the end for local test only)
# proxy_handler = urllib2.ProxyHandler... | 5,337,908 |
def generate_noisy_gaussian(center, std_dev, height, x_domain, noise_domain,
n_datapoints):
"""
Generate a gaussian with some aspect of noise.
Input:
center = central x value
std_dev = standard deviation of the function
height = height (y-off set) of the ... | 5,337,909 |
def run_corrsearch3d(
path_to_original: Path,
path_to_new: Path,
tomogram_trimming: float
):
"""Reads mrc files size, sets patch size, numbers, boundaries, and runs IMODs corrsearch3d function
"""
#Read mrc files
mrc_original = mrcfile.open(path_to_original)
mrc_new = mrcfile.open(p... | 5,337,910 |
def filter_group_delay(
sos_or_fir_coef: np.ndarray,
N: int = 2048,
fs: float = None,
sos: bool = True,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Given filter spec in second order sections or (num, den) form, return group delay.
Uses method in [1], which is cited by `scipy.signal.group_delay` ... | 5,337,911 |
def plotmodel(axs, m, x, z, vmin, vmax,
params=('VP', 'VS', 'Rho'),
cmap='gist_rainbow', title=None):
"""Quick visualization of model
"""
for ip, param in enumerate(params):
axs[ip].imshow(m[:, ip],
extent=(x[0], x[-1], z[-1], z[0]),
... | 5,337,912 |
def create_custom_job(
type,
gcp_project,
gcp_region,
payload,
gcp_resources,
):
"""
Create and poll custom job status till it reaches a final state.
This follows the typical launching logic
1. Read if the custom job already exists in gcp_resources
- If already exists, jump to step 3 ... | 5,337,913 |
def query():
"""Perform a query on the dataset, where the search terms are given by the saleterm parameter"""
# If redis hasn't been populated, stick some tweet data into it.
if redis_db.get("tweet_db_status") != "loaded":
tweet_scraper.add_tweets(default_num_tweets_to_try)
sale_term = request.... | 5,337,914 |
def _set_random_seed(seed, deterministic=False):
"""Set random seed.
Args:
seed (int): Seed to be used.
deterministic (bool): Whether to set the deterministic option for
CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
to True and `torch.backends.cudnn.bench... | 5,337,915 |
def get_spec_res(z=2.2, spec_res=2.06, pix_size=1.8):
""" Calculates the pixel size (pix_size) and spectral resolution (spec_res) in
km/s for the MOCK SPECTRA.
arguments: z, redshift. spec_res, spectral resoloution in Angst. pixel_size
in sngst.
returns:
(pixel_size, spec_res) in km/s
"""
... | 5,337,916 |
def _process_general_config(config: ConfigType) -> ConfigType:
"""Process the `general` section of the config
Args:
config (ConfigType): Config object
Returns:
[ConfigType]: Processed config
"""
general_config = deepcopy(config.general)
general_config.id = general_config.id.re... | 5,337,917 |
def api_response(response):
"""Response generation for ReST API calls"""
# Errors present
if response.message:
messages = response.message
if not isinstance(messages, list):
messages = [messages]
# Report the errors
return Response({'errors': messages}, status=s... | 5,337,918 |
def batch_norm(name, inpvar, decay=0.9, epsilon=1e-5, use_affine=True, param_dtype=__default_dtype__):
"""
Batch normalization.
:param name: operator name
:param inpvar: input tensor, of data type NHWC
:param decay: decay for moving average
:param epsilon: epsilon
:param use_affine: add aff... | 5,337,919 |
def get_engine(onnx_file_path, engine_file_path="", input_shapes=((1, 3, 640, 640)), force_rebuild=False):
"""Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it."""
assert len(input_shapes) in [1, 3], 'length of input_shapes should be 1 or 3, 3 for dynamic in... | 5,337,920 |
def describe_adjustment_types():
"""
Describes the available adjustment types for Amazon EC2 Auto Scaling scaling policies. These settings apply to step scaling policies and simple scaling policies; they do not apply to target tracking scaling policies.
The following adjustment types are supported:
See ... | 5,337,921 |
def test_empty_directories_non_current(empty_directory):
"""Find empty directory.
See https://docs.python.org/3/library/os.html#os.listdir
"""
for instance in empty_directory:
with mock.patch("os.walk", return_value=instance):
album_path = instance[0][0]
with mock.patch(... | 5,337,922 |
def _window_when(closing_mapper: Callable[[], Observable]) -> Callable[[Observable], Observable]:
"""Projects each element of an observable sequence into zero or
more windows.
Args:
source: Source observable to project into windows.
Returns:
An observable sequence of windows.
"""
... | 5,337,923 |
def generate_features(df):
"""Generate features for a stock/index based on historical price and performance
Args:
df(dataframe with columns "Open", "Close", "High", "Low", "Volume", "Adjusted Close")
Returns:
dataframe, data set with new features
"""
df_new = pd.DataFrame()
#... | 5,337,924 |
def assert_equal(left, right):
"""compare two terms and display them when unequal
"""
try:
assert left == right
except AssertionError:
print(left)
print(' is not the same as')
print(right)
raise | 5,337,925 |
def format_plate(barcode: str) -> Dict[str, Union[str, bool, Optional[int]]]:
"""Used by flask route /plates to format each plate. Determines whether there is sample data for the barcode and if
so, how many samples meet the fit to pick rules.
Arguments:
barcode (str): barcode of plate to get sample... | 5,337,926 |
def method_only_in(*states):
"""
Checks if function has a MethodMeta representation, calls wrap_method to
create one if it doesn't and then adds only_in to it from *states
Args:
*args(list): List of state names, like DefaultStateMachine.RESETTING
Returns:
function: Updated function... | 5,337,927 |
def restart():
"""
Restart gunicorn worker processes for the project.
If the processes are not running, they will be started.
"""
pid_path = "%s/gunicorn.pid" % env.proj_path
if exists(pid_path):
run("supervisorctl restart gunicorn_%s" % env.proj_name)
else:
run("supervisorct... | 5,337,928 |
def to_igraph(adjacency_matrix:Image, centroids:Image=None):
"""
Converts a given adjacency matrix to a iGraph [1] graph data structure.
Note: the given centroids typically have one entry less than the adjacency matrix is wide, because
those matrices contain a first row and column representing backgrou... | 5,337,929 |
def Laplacian(src, ddepth, dst=None, ksize=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT):
"""dst = cv.Laplacian( src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]] )
Executes the Laplacian operator on hardware if input parameters fit to hardware constraints.
Otherwise the OpenCV Laplacian fun... | 5,337,930 |
def get_docptr(n_dw_matrix):
"""
Parameters
----------
n_dw_matrix: array-like
Returns
-------
np.array
row indices for the provided matrix
"""
return _get_docptr(n_dw_matrix.shape[0], n_dw_matrix.indptr) | 5,337,931 |
def check_if_shift_v0(data, column_name, start_index, end_index, check_period):
""" using median to see if it changes significantly in shift """
period_before = data[column_name][start_index - check_period: start_index]
period_in_the_middle = data[column_name][start_index:end_index]
period_after = data[... | 5,337,932 |
def opening2d(value, kernel, stride=1, padding="SAME"):
"""
erode and then dilate
Parameters
----------
value : Tensor
4-D with shape [batch, in_height, in_width, depth].
kernel : Tensor
Must have the same type as 'value'. 3-D with shape '[kernel_height, kernel_width, depth]... | 5,337,933 |
def convert_npy_mat(user_num, item_num, df):
"""
method of convert dataframe to numpy matrix
Parameters
----------
user_num : int, the number of users
item_num : int, the number of items
df : pd.DataFrame, rating dataframe
Returns
-------
mat : np.matrix, rating matrix
"""
... | 5,337,934 |
def split_kernel2(S, r, out):
"""
:param S: B x NY x NX x 2
:param r: K x2
:param out: K x MY x MX x 2
:return:
"""
n = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x
K, MY, MX, B, _ = out.shape
N = K * MY * MX * B
k = n // (B)
b = (n - k * B)
if n < N:
f... | 5,337,935 |
def user_enter_state_change_response():
"""
Prompts the user to enter a key event response.
nothing -> str
"""
return input('>> ') | 5,337,936 |
def test_simulate_outbreaks(SimulationAlgo, shared_datadir):
"""Test against changes in simulation behavior."""
simulation_model = SimulationAlgo(seed=1)
if "state_weight" in inspect.signature(simulation_model.simulate).parameters:
simulated = simulation_model.simulate(length=100, state_weight=1)
... | 5,337,937 |
def call_worker(job_spec):
"""Calls command `cron_worker run <job_spec>` and parses the output"""
output = call_command("cron_worker", "run", job_spec)
status = exc_class_name = exc_message = None
if output:
result_match = RESULT_PATTERN.match(output)
if result_match:
status ... | 5,337,938 |
def overlap(a, b):
"""check if two intervals overlap.
Positional arguments:
a -- First interval.
b -- Second interval.
"""
return a[1] > b[0] and a[0] < b[1] | 5,337,939 |
def contAvg_headpos(condition, method='median', folder=[], summary=False):
"""
Calculate average transformation from dewar to head coordinates, based
on the continous head position estimated from MaxFilter
Parameters
----------
condition : str
String containing part of common f... | 5,337,940 |
def Scan_SlitSize(slit,start,stop,step,setslit=None,scanIOC=None,scanDIM=1,**kwargs):
"""
Scans the slit center:
slit='1H','1V','2H' or '2V'
Slit 1A is set to (1.75,1.75,0,0) unless setslit= not None
Logging is automatic: use **kwargs or the optional logging arguments see scanlog() for details
... | 5,337,941 |
def getconstantfunc(name, **kwargs):
"""Get constants from file by name."""
from . import __path__ as path
from numpy import fromfile
from os.path import join
from os import listdir
path = path[0]
if not name in listdir(path):
from ..IO.output import printError
printError("... | 5,337,942 |
def scalar_prod_logp0pw_beta_basis_npf(pw, p0, DV, alpha):
"""
From normalized p_fact
Args:
pw: a batch of probabilities (row:word, column:chi)
DV: centered statistics (for p0, to be consistent)
p0: the central probability on which tangent space to project (row vector)
alpha... | 5,337,943 |
def get_seminars() -> List[Tuple[str, str, datetime, str]]:
"""
Returns summary information for upcoming ITEE seminars, comprising
seminar date, seminar title, venue, and an information link.
"""
html = BeautifulSoup(get_seminar_summary_page(), 'html.parser')
summary_table = html.find('table', s... | 5,337,944 |
def cluster_hierarchically(active_sites,num_clusters=7):
"""
Cluster the given set of ActiveSite instances using a hierarchical algorithm.
Input: a list of ActiveSite instances
(OPTIONAL): number of clusters (default 7)
Output: a list of clusterings
(each clustering is a list of lists o... | 5,337,945 |
def test_shap_rfe_group_cv(X, y, groups, sample_weight, capsys):
"""
Test ShapRFECV with StratifiedGroupKFold.
"""
clf = DecisionTreeClassifier(max_depth=1, random_state=1)
cv = StratifiedGroupKFold(n_splits=2, shuffle=True, random_state=1)
with pytest.warns(None) as record:
shap_elimina... | 5,337,946 |
def test_pickelable_tinydb_can_be_pickled_and_unpickled():
"""PickleableTinyDB should be able to be pickled and unpickled."""
test_dict = {'test_key': ['test', 'values']}
db = PickleableTinyDB(storage=MemoryStorage)
db.insert(test_dict)
db = pickle.loads(pickle.dumps(db))
assert db.search(where(... | 5,337,947 |
def insert(table: _DMLTableArgument) -> Insert:
"""Construct an :class:`_expression.Insert` object.
E.g.::
from sqlalchemy import insert
stmt = (
insert(user_table).
values(name='username', fullname='Full Username')
)
Similar functionality is available via... | 5,337,948 |
def parallelize_window_generation_imap(passed_args, procs=None):
"""Produce window files, in a parallel fashion
This method calls the get_win function as many times as sets of arguments
specified in passed_args. starmap is used to pass the list of arguments to
each invocation of get_win. The pool is cr... | 5,337,949 |
def build_train(q_func, ob_space, ac_space, optimizer, sess, grad_norm_clipping=None,
scope="deepq", reuse=None, full_tensorboard_log=False):
"""
Creates the train function:
:param q_func: (DQNPolicy) the policy
:param ob_space: (Gym Space) The observation space of the environment
:... | 5,337,950 |
def function_that_prints_stuff():
"""
>>> function_that_prints_stuff()
stuff
"""
print('stuff') | 5,337,951 |
def _make_global_var_name(element):
"""creates a global name for the MAP element"""
if element.tag != XML_map:
raise ValueError('Expected element <%s> for variable name definition, found <%s>' % (XML_map,element.tag))
base_name = _get_attrib_or_None(element,XML_attr_name)
if base_name is None:
... | 5,337,952 |
def list_user_images(user_id):
"""
Given a user_id, returns a list of Image objects scoped to that user.
:param user_id: str user identifier
:return: List of Image (messsage) objects
"""
db = get_session()
try:
imgs = [msg_mapper.db_to_msg(i).to_dict() for i in db.query(Image).filte... | 5,337,953 |
def is_lower_cased_megatron(pretrained_model_name):
"""
Returns if the megatron is cased or uncased
Args:
pretrained_model_name (str): pretrained model name
Returns:
do_lower_cased (bool): whether the model uses lower cased data
"""
return MEGATRON_CONFIG_MAP[pretrained_model_na... | 5,337,954 |
def unsuspend_trip(direction, day, driver):
"""
Removes a trip from its suspension.
:param direction: "Salita" or "Discesa".
:param day: A day spanning the whole work week ("Lunedì"-"Venerdì").
:param driver: The chat_id of the driver.
:return:
"""
dt.groups[direction][day][drive... | 5,337,955 |
def merge(incr_a, incr_b):
"""Yield the elements of strictly increasing iterables incr_a and incr_b, removing
repeats. Assume that incr_a and incr_b have no repeats. incr_a or incr_b may or may not
be infinite sequences.
>>> m = merge([0, 2, 4, 6, 8, 10, 12, 14], [0, 3, 6, 9, 12, 15])
>>> type(m)
... | 5,337,956 |
def bright(args, return_data=True):
"""
Executes CA Brightside with arguments of this function. The response is returned as Python data structures.
Parameter ``return_data`` is by default ``True`` and it caused to return only the data section without metadata.
Metadata are processed automatically and ... | 5,337,957 |
def handle_mentions(utils, mentions):
"""
Processes a batch (list) of mentions.
Parameters
----------
utils : `Utils object`
extends tweepy api wrapper
mentions : `list`
list of Status objects (mentions)
"""
for mention in mentions:
if mention.user.screen_name ==... | 5,337,958 |
def decipher(string, key, a2i_dict, i2a_dict):
"""
This function is BASED on https://github.com/jameslyons/pycipher
"""
key = [k.upper() for k in key]
ret = ''
for (i, c) in enumerate(string):
i = i % len(key)
ret += i2a_dict[(a2i_dict[c] - a2i_dict[key[i]]) % len(a2i_dic... | 5,337,959 |
def keep_samples_from_pcoa_data(headers, coords, sample_ids):
"""Controller function to filter coordinates data according to a list
Parameters
----------
headers : list, str
list of sample identifiers, if used for jackknifed data, this
should be a list of lists containing the sample ide... | 5,337,960 |
def get_default_command() -> str:
"""get_default_command returns a command to execute the default output of g++ or clang++. The value is basically `./a.out`, but `.\a.exe` on Windows.
The type of return values must be `str` and must not be `pathlib.Path`, because the strings `./a.out` and `a.out` are different... | 5,337,961 |
def roi_circle(roi_index, galactic=True, radius=5.0):
""" return (lon,lat,radius) tuple for given nside=12 position
"""
from skymaps import Band
sdir = Band(12).dir(roi_index)
return (sdir.l(),sdir.b(), radius) if galactic else (sdir.ra(),sdir.dec(), radius) | 5,337,962 |
def find_by_user_defined_key(user_defined_key: str) -> List[models.BBoundingBoxDTO]:
"""Get a list of bounding boxes by a user-defined key."""
res_json = BoundingBoxes.get('query/userdefinedkey/{}'.format(user_defined_key))
return list(map(models.BBoundingBoxDTO.from_dict, res_json)) | 5,337,963 |
def object_type(r_name):
"""
Derives an object type (i.e. ``user``) from a resource name (i.e. ``users``)
:param r_name:
Resource name, i.e. would be ``users`` for the resource index URL
``https://api.pagerduty.com/users``
:returns: The object type name; usually the ``type`` property of... | 5,337,964 |
def test_atomic_g_month_enumeration_1_nistxml_sv_iv_atomic_g_month_enumeration_2_3(mode, save_output, output_format):
"""
Type atomic/gMonth is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/gMonth/Schema+Instance/NISTSchema-SV-IV-atomic-gMonth-enumeration-2.xsd",
... | 5,337,965 |
def fix_ascendancy_positions(path: os.PathLike) -> None:
"""Normalise the relative positions of ascendancy nodes on the passive skill tree.
Ascendancy positions in the passive skill tree data we receive from GGG look
scrambled, which is why we have to fix them before importing the skill tree in PoB.
.... | 5,337,966 |
def create_comment(args, global_var):
"""
创建一条新评论 (每天只能允许创建最多 1000 条评论)
-------------
关于 uuid:
1. raw_str 就用 data["content"]
2. 由于生成的 comment_id 格式中有中划线, 很奇怪, 所以建议删掉: uuid = "-".join(uuid)
"""
can_create = hit_daily_comment_creation_threshold(global_var)
if not can_create:
... | 5,337,967 |
def gen_value(schema: DataType):
"""
VALUE -> OBJECT
| ARRAY
| STRING
| NUMBER
| BOOL
"""
if isinstance(schema, StructType):
for t in gen_object(schema):
yield t
elif isinstance(schema, ArrayType):
for t in gen_array(schema.el... | 5,337,968 |
def get_aggregated_metrics(expr: ExperimentResource):
"""
Get aggregated metrics using experiment resource and metric resources.
"""
versions = [expr.spec.versionInfo.baseline]
if expr.spec.versionInfo.candidates is not None:
versions += expr.spec.versionInfo.candidates
# messages not w... | 5,337,969 |
def lsa_main(args):
"""Runs lsa on a data directory
:args: command line argument namespace
"""
if args.outfile is None:
os.makedirs(os.path.join("data", "tmp"), exist_ok=True)
args.outfile = os.path.join("data", "tmp", f"lsa-{args.n_components}.pkl")
print("LSA Embedding will be sto... | 5,337,970 |
def get_bart(folder_path, checkpoint_file):
"""
Returns a pretrained BART model.
Args:
folder_path: str, path to BART's model, containing the checkpoint.
checkpoint_file: str, name of BART's checkpoint file (starting from BART's folder).
"""
from fairseq.models.bart import BARTMode... | 5,337,971 |
async def test_login():
"""Test login."""
# assert os.environ.get("NOIP_USERNAME"), 'You need to set NOIP_USERNAME, e.g. set NOIP_USERNAME="your noip_username or email address or set it up in .env (refer to .env.sample)'
# assert os.environ.get("NOIP_PASSWORD"), 'You need to set NOIP_USERNAME, e.g. set NOIP... | 5,337,972 |
def construct_s3_raw_data_path(study_id, filename):
""" S3 file paths for chunks are of this form:
RAW_DATA/study_id/user_id/data_type/time_bin.csv """
return os.path.join(RAW_DATA_FOLDER, study_id, filename) | 5,337,973 |
def reset_password_email(recipient, link):
""" Sends out an email telling the recipients that
their password is able to be reset. Passed in is
a recipient to receive the password reset, along
with a password reset link.
"""
subject = "NordicSHIFT password reset request"
message = "Your pass... | 5,337,974 |
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
#time_taken is a series formed of subtraction of end and start times
df['End Time'] = pd.to_datet... | 5,337,975 |
def _mixed_s2(x, filters, name=None):
"""Utility function to implement the 'stride-2' mixed block.
# Arguments
x: input tensor.
filters: a list of filter sizes.
name: name of the ops
# Returns
Output tensor after applying the 'stride-2' mixed block.
"""
if len(filte... | 5,337,976 |
def get_convertor(cls: Union[Type, str]) -> Convertor:
"""Returns Convertor for data type.
Arguments:
cls: Type or type name. The name could be simple class name, or full name that includes
the module name.
Note:
When `cls` is a type name:
1. If class name is NOT regi... | 5,337,977 |
def cli():
"""The pypi CLI.
\b
Examples:
\b
pypi stat Django
pypi browse Flask
To get help with a subcommand, add the --help option after the command.
\b
pypi stat --help
"""
pass | 5,337,978 |
def adjust_learning_rate(optimizer, epoch):
"""For resnet, the lr starts from 0.1, and is divided by 10 at 80 and 120 epochs"""
if epoch < 80:
lr = 0.1
elif epoch < 120:
lr = 0.01
else:
lr = 0.001
for param_group in optimizer.param_groups:
param_group['lr'] =... | 5,337,979 |
def partPos2video(pos, fname='video.mp4', limits=[2, 4, 2, 4, 5, 7], ftime=100, partSize=5, shadowSize=1, psf=[0.15, 0.15, 0.45]):
"""
Convert SPAD-FCS particle positions to video
===========================================================================
Input Meaning
---------- ------------... | 5,337,980 |
def get_all_todo_list(request):
"""
This gets all the todolist associated with the user
:param request:
:return:
"""
pass | 5,337,981 |
def _is_mchedr(filename):
"""
Checks whether a file format is mchedr
(machine-readable Earthquake Data Report).
:type filename: str
:param filename: Name of the mchedr file to be checked.
:rtype: bool
:return: ``True`` if mchedr file.
.. rubric:: Example
>>> _is_mchedr('/path/to/m... | 5,337,982 |
def ddr3_8x8_profiling(
trace_file=None,
word_sz_bytes=1,
page_bits=8192, # number of bits for a dram page/row
min_addr_word=0,
max_addr_word=100000
):
"""
this code takes non-stalling dram trace and reorganizes the trace to meet the bandwidth requirement.
currently, it does not generate... | 5,337,983 |
def get_sites_by_latlon(latlon, filter_date='', **kwargs):
"""Gets list of sites from BETYdb, filtered by a contained point.
latlon (tuple) -- only sites that contain this point will be returned
filter_date -- YYYY-MM-DD to filter sites to specific experiment by date
"""
latlon_api_arg = "%s,%... | 5,337,984 |
def event_setup():
"""
Loads event dictionary into memory
:return: nothing
"""
global _EVENT_DICT
_EVENT_DICT = _get_event_dictionary() | 5,337,985 |
def get_context(book, chapter, pharse):
"""
Given book, chapter, and pharse number, return the bible context.
"""
try:
context = repository['{} {}:{}'.format(book, chapter, pharse)]
return context
except KeyError:
bookname = bookid2chinese[book]
pharse_name = '{}{}:{}... | 5,337,986 |
def find_cocotb_base (path = "", debug = False):
"""
Find Cocotb base directory in the normal installation path. If the user
specifies a location it attempts to find cocotb in that directory. This
function failes quietly because most people will probably not use cocotb
on the full design so it's not... | 5,337,987 |
def read_dicom_volume(dcm_path):
"""
This function reads all dicom volumes in a folder as a volume.
"""
dcm_files = [ f for f in os.listdir(dcm_path) if f.endswith('.dcm')]
dcm_files = ns.natsorted(dcm_files, alg=ns.IGNORECASE)
Z = len(dcm_files)
reference = dicom.read_file(os.path.join(dcm_path,... | 5,337,988 |
def _compare_namelists(gold_namelists, comp_namelists, case):
###############################################################################
"""
Compare two namelists. Print diff information if any.
Returns comments
Note there will only be comments if the namelists were not an exact match
Expect a... | 5,337,989 |
def directMultiCreate( data, cfg_params='', *, dtype='',
doInfo = True, doScatter = True, doAbsorption = True ):
"""Convenience function which creates Info, Scatter, and Absorption objects
directly from a data string rather than an on-disk or in-memory
file. Such usage obviously... | 5,337,990 |
def write_date_json(date: str, df: DataFrame) -> str:
""" Just here so we can log in the list comprehension """
file_name = f"pmg_reporting_data_{date}.json"
print(f"Writing file {file_name}")
df.to_json(file_name, orient="records", date_format="iso")
print(f"{file_name} written")
return file... | 5,337,991 |
def fit_composite_peak(bands, intensities, locs, num_peaks=2, max_iter=10,
fit_kinds=('lorentzian', 'gaussian'), log_fn=print,
band_resolution=1):
"""Fit several peaks to a single spectral feature.
locs : sequence of float
Contains num_peaks peak-location guesses,
... | 5,337,992 |
def main(args):
"""
main function
:param args: input arguments
"""
# make kowiki dir
if not os.path.exists(args.data_dir):
os.makedirs(args.data_dir)
print(f"make kowiki data dir: {args.data_dir}")
# download latest kowiki dump
filename = download_kowiki(args.data_dir)
... | 5,337,993 |
def plot_score(model, title=None, figsize=(12,4), directory=None, filename=None):
"""Plots training score (and optionally validation score) by epoch."""
# Validate request
if not model.metric:
raise Exception("No metric designated for score.")
if not isinstance(model, Estimator):
raise ... | 5,337,994 |
def entry_generator(tree):
"""
Since the RSS Feed has a fixed structure the method
heavily relies on simply finding the nodes belonging
to the same level: shortly, it yields a new dictionary
containing at every <entry> tag it finds; this is
useful for appending them to a list (see how is called
... | 5,337,995 |
def eprint(*args, **kwargs):
"""
Print to stderr
"""
print(*args, file=sys.stderr, **kwargs) | 5,337,996 |
def test_session():
"""test of Session class
"""
session = MockSession()
assert session.remote_address.full_address == 'mock'
assert str(session) == '<mprpc.transport.Session: remote_address=mock>'
assert repr(session) == '<mprpc.transport.Session: remote_address=mock>' | 5,337,997 |
def param():
"""
Create a generic Parameter object with generic name, description and no value defined
"""
return parameter.Parameter("generic_param",template_units.kg_s,"A generic param") | 5,337,998 |
def colorneighborhood(graph, start_node, colors, color_last_edges=True):
"""
Color nodes and edges according to how far they are from a specific starting node.
Likely only useful for debugging. Arguments:
- graph: NetworkX DiGraph to color in-place
- start_node: node ID of starting node
- color... | 5,337,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.