content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def iter_date(start_date, end_date, day_gap=1, reverse=False):
""" 生成开始日期到结束日期间的所有日期
Args:
start_date: 开始日期,'yyyy-mm-dd'字符串
end_date: 结束日期,'yyyy-mm-dd'字符串
day_gap: 生成的相隔多少天
reverse: 逆序生成日期
Returns:
string类型日期的生成器
"""
start_time = tuple([int(_) for _ in start... | 58,200 |
def resnetv2_50x1_vit(pretrained=False, strict=False, progress=False, **kwargs):
""" ResNetv2-50 from ViT-B/16 hybrid model from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
# create a ResNetV2 w/o pr... | 58,201 |
def pickwords(filename):
"""This function chooses a random word from a chosen wordlist.
:param filename: the wordlist that the function should search.
:return: returns the randomly chosen word.
"""
word = choice(open(filename, 'r').readlines()).rstrip('\r\n')
return word | 58,202 |
async def wait_for(fut, timeout, *, loop=None, race_handler=None):
"""
Alternate implementation of asyncio.wait_for() based on the version from Python 3.8. It handles simultaneous
cancellation of wait and completion of future differently and consistently across python versions 3.6+.
Builtin asyncio.wai... | 58,203 |
def savitsky_wetted(hull):
"""
This is a function based on Daniel Savitsky 1964 / 1976 paper to calculate wetted area
:param hull: Hull Object
:return: wetted area information
"""
v = hull.state.v
beta_d = hull.beta_d
beta = deg_to_rad(beta_d)
trim_d = hull.state.trim_d... | 58,204 |
def visit(visitor: DocxTranslator, node: Node):
"""Start processing line_block node"""
assert isinstance(visitor, DocxTranslator)
assert isinstance(node, Node)
visitor.p_style.append(STYLES[LINE_BLOCK]) | 58,205 |
def test_positions(tokenize):
"""Test the reported line/column position of each token."""
if tokenize is None: # pragma: no cover
pytest.skip('Speedups not available')
css = '/* Lorem\nipsum */\fa {\n color: red;\tcontent: "dolor\\\fsit" }'
tokens = tokenize(css, ignore_comments=False)
r... | 58,206 |
def get_stage_names(json_data: dict) -> List[str]:
""" Returns the names of the stages within the Frew model.
Parameters
----------
json_data : dict
A Python dictionary of the data held within the json model file.
Returns
-------
stage_names : List[str]
A list of the names ... | 58,207 |
def test_paraiba_call():
"""Called the state of Paraiba module, to check to be working"""
valid_number = '060000015'
goais_index = 'PB'
assert con.start(valid_number, goais_index) is True | 58,208 |
def test_password_noconfirm_true_required_false(sdk_client_fs: ADCMClient, login, app):
"""Check save button status for no password confirmation is false and required is false
"""
path = get_data_dir(__file__) + "/password_confirm_true_required_false"
bundle = sdk_client_fs.upload_from_fs(path)
clus... | 58,209 |
def administrator_reporter_spin(request):
"""
纺织类
:param request:
:return:
"""
title_msg = '查询所有纺织大类学员'
param_result = search_parameter(request, 'spin')
if 'school_term' in param_result:
if param_result['school_term'] is None:
message = '尚未添加->报考学期->信息,请->管理员-... | 58,210 |
def evaluate(hps, logdir, traindir, subset="valid", return_val=False):
"""Evaluation."""
hps.batch_size = 100
with tf.Graph().as_default():
with tf.device("/cpu:0"):
with tf.variable_scope("model") as var_scope:
eval_model = RealNVP(hps)
summary_writer = t... | 58,211 |
def V_param_mat_prod(
param: Parameter, mat: Tensor, savefield: str, subsampling: List[int] = None
):
"""Multiply with the GGN(MC) matrix square root ``V`` defined by ``param``.
Args:
param: Parameter defining ``Vᵀ``.
mat: Matrix to be multiplied with ``V``.
savefield: Attribute und... | 58,212 |
def templates(cluster, stdout_writer, config):
"""
input (ignored):
[]
output:
{'templates': [{'attributes': {'cyclecloudhost': ['Boolean', 1],
'mem': ['Numeric', '2048'],
'ncores': ['Numeric', '4'],
'ncpus': ['Num... | 58,213 |
def preprocess_adj(H, variable_weight=False):
"""
calculate G from hypgraph incidence matrix H
:param H: hypergraph incidence matrix H
:param variable_weight: whether the weight of hyperedge is variable
:return: G
"""
H = np.array(H)
n_edge = H.shape[1]
# the weight of the hyper... | 58,214 |
def test_map_key_to_choice(keys):
"""Test mapping a key to a choice."""
states = [0, 1]
streams = ["single", "dual"]
inputs = list(itertools.product(keys, states, streams))
# inputs are:
# [('left', 0, 'single'), -> higher
# ('left', 0, 'dual'), -> red
# ('left', 1, 'single'), -> low... | 58,215 |
def mfold(falist, ct, na_conc, detG):
"""
calling the mfold and check the second structure
:param fa:
:param type:
:param NA_CONC:
:param Tm:
:return:
"""
# falist, ct, na_conc = args
faprefix, left, right = falist[0].split(';')
# TODO, add calculate new Tm filter.
with ... | 58,216 |
def test_core_store(coresys: CoreSys, repository) -> None:
"""Test loading from core store."""
assert coresys.store.get("core")
assert "core_samba" in coresys.addons.store | 58,217 |
def setup(bot):
"""Add Verify cog to bot.
Args:
bot: Bot object to add cog to.
"""
LOG.debug(f"Setting up {__name__} extension...")
cog = Verify(bot, LOG)
LOG.debug(f"Initialised {COG_NAME} cog")
bot.add_cog(cog)
LOG.debug(f"Added {COG_NAME} cog to bot") | 58,218 |
def findWordFreq (word_list, names, threshold = 20, directory=None):
"""
Count the word frequency in each element of the list.
Filter out the common words that do not provide any valuable information.
Keep keywords.
:param word_list: A list where each element is string of all reviews for one bu... | 58,219 |
def test_zeros_like3():
"""
test zeros_like device=cpu name=ss
Returns:
None
"""
with fluid.dygraph.guard():
x = to_variable(np.random.random(size=[100, 100, 100]))
res = paddle.zeros_like(x, device="cpu", name="ss")
expect = np.zeros(shape=[100, 100, 100])
to... | 58,220 |
def wait_port_open(server, port, timeout=None):
""" Wait for network service to appear
@param server: host to connect to (str)
@param port: port (int)
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
... | 58,221 |
def test_frame_processor_bogus_size():
"""
Test that the frame processor fails to parse a frame that's too large.
"""
proc = FrameProcessor()
mtu = 64
frame_size = new_default("count")
data = build_dummy_frame(mtu).with_size_header()[0]
assert len(proc.process(data, frame_size, mtu)) ==... | 58,222 |
def test_odd_input_end():
""" test a list with an odd number of elements
"""
expected = 4
result = array_binary_search([1, 2, 3, 4, 5], 5)
assert expected == result | 58,223 |
def fix_nametable(ttFont):
"""Fix a static font's name table so it conforms to the Google Fonts
supported styles table:
https://github.com/googlefonts/gf-docs/tree/main/Spec#supported-styles
Args:
ttFont: a TTFont instance
"""
if "fvar" in ttFont:
from fontTools.varLib.instancer... | 58,224 |
def Bokeh_Fig_WebCOMPLEX(IRGASON_name):
""" Entradas:
import numpy as npIRGAS
ON_name --> str, Nombre de la carpeta de las estaciones IRGASON:
[
IRGASON_Candelaria,
IRGASON_Federico_Carrasquilla,
IRGASON_SENA,
IRGASON_CASD_10M,
IRGASON_ITM,
IRGASON_V... | 58,225 |
def deleteAlias(obj, aliasName, timeout):
"""
Delete an alias.
"""
click.echo(
"Warning!\nYou are trying to delete an alias. This action cannot be undone!\n"
)
if not click.confirm("Do you want to continue?"):
return
try:
obj.checkConnection()
obj.dropCollecti... | 58,226 |
def patient_add(request):
"""
Add new patient
"""
if request.method == "POST":
form = AddPatientForm(request.POST)
if form.is_valid():
patient = form.save()
request.session['patient_id'] = patient.id
# return redirect('patient_info', patient_id=patient... | 58,227 |
def merge_window():
"""window for merging experiments. will deal with either root growth or germination data,
but not both at the same time."""
# the table of experiments
explist = [
[sg.Table(headings=['Experiments', ], display_row_numbers=False,
auto_size_columns=False, va... | 58,228 |
def grid_sample(input, grid, mode='bilinear'):
"""Given an :attr:`input` and a flow-field :attr:`grid`, computes the
`output` using input pixel locations from the grid.
Uses bilinear interpolation to sample the input pixels.
Currently, only spatial (4 dimensional) inputs are supported.
For each ou... | 58,229 |
def add_memory(mem_kind, mem_value):
"""Add a memory"""
mem = Memory()
mem.kind = mem_kind
mem.value = mem_value
mem.update = datetime.today()
mem.user = 0
session.add(mem)
session_commit()
return mem.key | 58,230 |
def make_global_data_policy(
policy_name: str, policy_config: Dict, tagger: Tagger
) -> GlobalDataPolicy:
"""
Returns a GlobalDataPolicy object containing lists of actions and circumstances.
Actions define what the policy restricts, how it restricts, and for whom it restricts.
Circumstances define w... | 58,231 |
def UTM2rot(xutm,yutm,r):
"""
Convert UTM coordinates to rotated coordinates
Now deprecated by UTM2Island ... delete
"""
# Convert origin to UTM
xu,yu = box2UTMh(0.,0.,r['e0'],r['n0'],r['theta'])
# reverse the calc to find the origin (UTM =0,0) in box coordinates.
# First, just do the r... | 58,232 |
def get_values(units, *args):
"""
Return the values of Quantity objects after optionally converting to units.
Parameters
----------
units : str or `~astropy.units.Unit` or None
Units to convert to. The input values are converted to ``units``
before the values are returned.
args ... | 58,233 |
def h_pca_inverse_plot(bel, fig_dir: str = None, show: bool = False):
"""
Plot used to compare the reproduction of the original physical space after PCA transformation
:param bel: BEL model
:param fig_dir: str:
:param show: bool:
:return:
"""
shape = bel.Y_shape
if bel.Y_obs_pc is ... | 58,234 |
def main():
""" todoc
"""
app = connexion.App(__name__, specification_dir="./definitions/")
app.app.config["DATABASE_URI"] = "sqlite:////tmp/auth.db"
options = {"swagger_ui": True}
app.add_api(
"api.yaml",
options=options,
arguments={"title": "Auth API"},
resolver... | 58,235 |
def generate_input(data,t):
"""
Compute the index word vector for the given Data.
Arguments: data (list of sentences)
t (The Keras instance that Tokenize the words)
"""
encoded_docs = t.texts_to_sequences(data)
max_length = max_length_pad(encoded_docs)
return (encoded_docs... | 58,236 |
def plot_combined_app(df, show=True, save=True):
"""Plot both the regular and the expensive data into a single figure.
Args:
df (pandas.DataFrame): DataFrame holding the benchmark data.
show (bool, optional): Whether to show the plot. Defaults to True.
save (bool, optional): Whether to ... | 58,237 |
def plot_shape_program_pytorch_reconstructions(
path, generative_model, guide, obs, ground_truth_latent
):
"""
Args:
generative_model
guide
obs: [num_test_obs, im_size, im_size]
"""
num_test_obs, im_size, _ = obs.shape
# Deconstruct ground truth latent
(
grou... | 58,238 |
def JoinMatchmakingTicket(request, callback, customData = None, extraHeaders = None):
"""
Join a matchmaking ticket.
https://docs.microsoft.com/rest/api/playfab/multiplayer/matchmaking/joinmatchmakingticket
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise PlayFabErrors.PlayFab... | 58,239 |
def read(filename):
"""Read the input file for rules and return the list of rules and the number of line errors."""
l = list()
with open (filename, 'r') as f:
ruleErrorCount = 0
for line in f:
#rule = parseRule(line)
try:
rule = Rule(line)
... | 58,240 |
def cli(ctx, library_id, filesystem_paths, folder_id="", file_type="auto", dbkey="?", link_data_only="", roles=""):
"""Upload a set of files already present on the filesystem of the Galaxy server to a library.
Output:
"""
return ctx.gi.libraries.upload_from_galaxy_filesystem(library_id, filesystem_pa... | 58,241 |
def test_intersect(csg, tst):
"""
* only 1st intersect is returned, so to see inside and outside of
a shape need to send rays from inside and outside
"""
traverse(tst.root)
csg.compare_intersects( tst )
csg.plot_intersects( plt )
plt.show() | 58,242 |
def iou_score_single(
y_true: np.ndarray,
y_pred: np.ndarray,
k: int | None = None,
excluded_labels: list[int] | None = None,
) -> float:
"""Compute intersection over union of a class `k`.
Parameters
----------
y_true
A np.ndarray of shape `(h, w)` representing the ground truth
... | 58,243 |
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""响应按键"""
if event.key == pygame.K_RIGHT:
ship.moveing_right = True
elif event.key == pygame.K_LEFT:
ship.moveing_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings,screen, ship, bullets)
elif event.key == pygame.K_q:
... | 58,244 |
def raiz_aprox_intervalo_por_secantes(f, a, b, t = TOL, max_iteracoes = MAX_ITER):
"""
Calcula raízes de uma dada função em um dado intervalo pelo método das secantes.
:param f: função que será analizada
:param a: intervalo inferior de análise da função
:param b: intervalo superior de análise da fu... | 58,245 |
def load_genz(genz_num: int, slice_len=None):
"""
Load a dataset of time series with dynamics set by various Genz functions
Separate train, validation, and test datasets are returned, containing data
from 8000, 1000, and 1000 time series. The length of each time series
depends on `slice_len`, and i... | 58,246 |
def get_uptime():
"""
Get uptime
"""
try:
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_time = str(timedelta(seconds=uptime_seconds))
data = uptime_time.split('.', 1)[0]
except Exception as err:
... | 58,247 |
def h2e(az, za, lat):
"""
Horizon to equatorial.
Convert az/za (radian) to HA/DEC (degrees, degrees)
given an observatory latitude (degrees)
"""
sa = numpy.sin(az)
ca = numpy.cos(az)
se = numpy.sin(numpy.pi / 2.0 - za)
ce = numpy.cos(numpy.pi / 2.0 - za)
sp = numpy.sin(lat * nump... | 58,248 |
def read_plumed_output(plumed_output):
"""
This function modifies the given plumed output file if it is corrupted, meaning that
there might be some duplicates in the time series having the same time frames. If the
file is not corrupted, this fucntion does nothing but only read in the data.
Paramet... | 58,249 |
def PZap (inUV, err):
""" Delete underlying files and the basic object.
inUV = Python UV object
err = Python Obit Error/message stack
"""
################################################################
if inUV.myClass=='AIPSUVData':
inUV.zap()
return
inUV.Zap... | 58,250 |
def negative_binomial_graph(state: str, data: Dict[str, Dict[int, List[float]]]) -> str:
"""A function to display a negative binomial regression model graphically"""
pd.options.mode.chained_assignment = None
# First, creating a pandas dataframe for our data
df = pd.DataFrame.from_dict(data[state], ori... | 58,251 |
def get_user_name():
"""Return eser name from console.
Returns:
user_name (string): name of user from console
"""
return prompt.string('May I have your name? ') | 58,252 |
def RMSEerror(bpmES, bpmGT, timesES=None, timesGT=None):
""" RMSE: """
diff = bpm_diff(bpmES, bpmGT, timesES, timesGT)
n,m = diff.shape # n = num channels, m = bpm length
df = np.zeros(n)
for j in range(m):
for c in range(n):
df[c] += np.power(diff[c,j],2)
# -- final RMSE
... | 58,253 |
def rainbow(strip, config, args=None):
"""Draw rainbow that fades across all pixels at once."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color_wheel(int(i * 256 / strip.numPixels()) & 255))
strip.show() | 58,254 |
def decompress_word(word):
"""
Returns the delta values stored on a word.
Outliers are retrieved as -((1<<mode)-1)
"""
GRABS_PER_MODE = (0,28,14,10,7,6,5,4)
FULLMASK = (0,0b1,0b11,0b111,0b1111,0b11111,0b111111,0b1111111)
if (word>>30)==0b00:
mode = 3
elif (word>>30)==0b01:
... | 58,255 |
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | 58,256 |
def verify_context_first(clazz):
"""Verifies that methods accepting a Context keep it the first argument."""
examine = clazz.ctors + clazz.methods
for m in examine:
if len(m.args) > 1 and m.args[0] != "android.content.Context":
if "android.content.Context" in m.args[1:]:
... | 58,257 |
def txtlist(imdir):
"""Return a list of absolute paths of *.txt files in current directory"""
return [os.path.join(imdir, item) for item in os.listdir(imdir) if io.is_text_file(item) and not io.is_hidden_file(item)] | 58,258 |
def concat(inputs, axis=0, **kwargs):
"""Concatenate the inputs along the given axis.
All dimensions except the :attr:`axis` should be same:
```python
x1 = dragon.ones(shape=(2, 3))
x2 = dragon.zeros(shape=(2, 4))
y = dragon.concat([x1, x2], axis=1) # Ok
z = dragon.concat([x1, x2], axis=0... | 58,259 |
def plot_umatrix(
u_matrix: np.ndarray,
n_rows: int,
n_colums: int,
cmap: str = "Greys",
fontsize: int = 18,
) -> plt.Axes:
"""Plot u-matrix.
Parameters
----------
u_matrix : np.ndarray
U-matrix containing the distances between all nodes of the
unsupervised SOM. Shap... | 58,260 |
def some_version_installed(item_pl):
"""Checks to see if some version of an item is installed.
Args:
item_pl: item plist for the item to check for version of.
Returns a boolean.
"""
if item_pl.get('OnDemand'):
# These should never be counted as installed
display.display_debug... | 58,261 |
def download(
asset,
name,
temporal_resolution,
year_initial,
year_final,
logger
):
"""
Download dataset from GEE assets.
"""
logger.debug("Entering download function.")
in_img = ee.Image(asset)
# if temporal_resolution != "one time":
# assert (year_initial and ... | 58,262 |
def _search_in_render_layer_all():
""" 全てのViewLayerのレンダリングプロパティを取得
Returns:
[type]: [description]
"""
render_layer_settings = {}
render_layer_settings["scene_use_freestyle"] = bpy.context.scene.render.use_freestyle
render_layer_settings["linestyle_names"] = _get_linestyle_name... | 58,263 |
def build_all():
"""
Build mkdocs site for en, and then build each language inside, end result is located
at directory ./site/ with each language inside.
"""
site_path = Path("site").absolute()
update_languages(lang=None)
current_dir = os.getcwd()
os.chdir(en_docs_path)
typer.echo("B... | 58,264 |
def load_uvarint_b(buffer):
"""
Variable int deserialization, synchronous from buffer.
:param buffer:
:return:
"""
result = 0
idx = 0
byte = 0x80
while byte & 0x80:
byte = buffer[idx]
result += (byte & 0x7F) << (7 * idx)
idx += 1
return result | 58,265 |
def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=1, **kwargs):
""" A function which accesses the open strain data
This uses `gwpy` to download the open data and then saves a cached copy for
later use
Parameters
----------
file_name: str
The name of the fra... | 58,266 |
def parse_print_dur(print_dur):
"""
Parse formatted string containing print duration to total seconds.
>>> parse_print_dur(" 56m 47s")
3407
"""
h_index = print_dur.find("h")
hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0
m_index = print_dur.find("m")
min... | 58,267 |
def skin(image_path, thres=500):
""" Extract the skin and create a mesh.
Parameters
----------
image_path: str
the MRI image we want to extract the skin.
thres: int
the skin threshold.
Returns
-------
actor: vtkActor
one actor handling the surface.
"""
#... | 58,268 |
def test_filter_by_distance(experiment_class):
"""Test the filter_by_distance method."""
filtered = experiment_class.filter_by_distance(
distance_fname=TEST_DISTANCE_FILE, cutoff=2.0
)
assert "C" not in filtered.residues[1].shifts
assert "CA" in filtered.residues[1].shifts | 58,269 |
def Contract_CloneComboLegs(dst, src):
"""Contract_CloneComboLegs(Contract::ComboLegListSPtr & dst, Contract::ComboLegListSPtr const & src)"""
return _swigibpy.Contract_CloneComboLegs(dst, src) | 58,270 |
def gen_out(path):
"""Generate output in a specified format."""
print("Generating output...")
global err_list
file_type = path[path.rfind('.')+1:]
# CSV output
if file_type == "csv":
f = open(path,'w+')
csv_out = csv.writer(f)
csv_out.writerow(['Filename', 'Check', 'Mess... | 58,271 |
def read_datetext(sPathTxt_):
""" Return date array from text file sPathTxt. """
lstD = [datetime.date(*[int(s) for s in l.strip().split('.')]) for l in open(sPathTxt_, 'r').readlines()]
return np.array(lstD) | 58,272 |
def dist(bot, trigger):
"""
.dist <city1> <city2> [pedestrian], or <city1>|<city2>|[pedestrian] if there is whitespace in the names.
"""
# checks if locations are not given
if not trigger.group(2):
bot.say("'.dist <city1> <city2>' or if there is any whitespace in a city's name then '.dist <... | 58,273 |
def welcoming():
"""
Welcoming for user
"""
return("""
*************************************************
** **
** Welcome to speech emotion recognition! **
** **
********... | 58,274 |
def scan(client, query=None, scroll='5m', raise_on_error=True,
preserve_order=False, size=1000, **kwargs):
"""
Simple abstraction on top of the
:meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that
yields all hits as returned by underlining scroll requests.
By default sc... | 58,275 |
def set_thermal_conductivity(number: int, value: float) -> None:
"""
Args:
number (int): element ID
value (float): value
""" | 58,276 |
def report_threadpool_stats(threadpool, prefix="threadpool"):
"""Report stats about a given threadpool."""
def report():
return {prefix + ".working": len(threadpool.working),
prefix + ".queue": threadpool.q.qsize(),
prefix + ".waiters": len(threadpool.waiters),
... | 58,277 |
def Calc_Hot_Pixels(ts_dem,QC_Map, water_mask, NDVI,NDVIhot_low,NDVIhot_high,Hot_Pixel_Constant):
"""
Function to calculates the hot pixels based on the surface temperature and NDVI
"""
for_hot = np.copy(ts_dem)
for_hot[NDVI <= NDVIhot_low] = np.nan
for_hot[NDVI >= NDVIhot_high] = np.nan
fo... | 58,278 |
def _find_vlan(mac, domain_interfaces):
"""
Given a mac address and a collection of domains and their network
interfaces, find the domain that is assigned the interface with the
desired mac address.
Parameters
----------
mac : str
The MAC address.
domain_interfaces : dict
... | 58,279 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | 58,280 |
def archive_url(file_path, app="processed", is_latest=False):
"""
Accepts the relative path to a CAL-ACCESS file in our achive.
Returns a fully-qualified absolute URL where it can be downloaded.
"""
# If this is the 'latest' version of the file the path will need to be hacked
if is_latest:
... | 58,281 |
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.vertsplit(eqs):
if ca.depends_on(eq, dx):
dae.append(eq)
else:
alg.append(eq)
return {
'dae': ca... | 58,282 |
def upload_boxes(vagrant_cloud_token):
"""Looks for upload_boxes script in each directory and then executes it."""
print('Uploading all images.')
boxes = dict()
get_boxes(boxes, vagrant_cloud_token)
for root, _dirs, files in os.walk(SCRIPT_DIR):
if root != SCRIPT_DIR:
if 'box_inf... | 58,283 |
def CalScore(names_d, daily_d,
once_intime=2, once_late=1.5, twice_intime=1, twice_late=0.5):
"""
Calculate daily score.
"""
due = daily_d["due"]
due = parse(due, settings={'TIMEZONE': 'US/Eastern'})
actions = daily_d["actions"]
for act in actions:
if act["type"]=="ad... | 58,284 |
def cp_series(xlsx_file, target_root):
"""
:param xlsx_file:
:param target_root:
:return:
"""
if not os.path.exists(xlsx_file): return
if not os.path.exists(target_root): os.makedirs(target_root)
tags = pd.read_excel(xlsx_file)
patient_ids = tags['02_PatientID'].values
for i, pat... | 58,285 |
def test_many_newlines():
"""
Test correct Conll parsing when there are too many newlines.
"""
with open(fixture_location('many_newlines.conll')) as f:
conll = Conll(f)
assert len(conll) == 4
assert len(conll[0]) == 10
assert conll[0].id == 'fr-ud-dev_00001'
assert len(conll[1... | 58,286 |
def add_task_from_input():
"""
Use console input prompts to get user data
for adding a new task
"""
daily = input("Is it a daily task? (Y/n)")
name = input("Title of the task: ")
if daily.lower() == 'y':
_add_task(name, is_daily=True)
else:
subject = input("Which course?... | 58,287 |
def test_average_pool_4(op_tester):
"""
The Identity case
"""
d1 = np.random.rand(4, 256, 6, 6).astype(np.float16)
def init_builder(builder):
i1 = builder.addInputTensor(d1)
o = builder.aiOnnx.averagepool([i1],
kernel_shape=[1, 1],
... | 58,288 |
def canonicalize_path(path, prefix=None):
"""Canonicalize a given path.
Remove the prefix from the path. Otherwise, if the path starts with
/build/XXX/package-version then remove this prefix.
Args:
path
Returns:
Canonicalized path.
"""
dummy_prefix = '/build/dummy_pkg/pkg-... | 58,289 |
def insert_dummies_on_linear_atoms(geo, lin_idxs=None, gra=None, dist=1.,
tol=5.):
""" Insert dummy atoms over linear atoms in the geometry.
:param geo: the geometry
:type geo: automol molecular geometry data structure
:param lin_idxs: the indices of the l... | 58,290 |
def get_times(T, dt, ex_in_rate, ns, input_intensity, stop_between=0):
"""Return computation times for numpy and tensorflow models for
networks with n neuron for n in ns"""
# Storage vectors for computation times
tf_build_times = np.empty((len(ns), 1), dtype=np.float32)
np_build_times = np... | 58,291 |
def SO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-07-12", **kwargs
) -> Graph:
"""Retu... | 58,292 |
def parse_peptides(tumfile, normfile, prefix, suffix):
"""
This module takes in a peptides file and squashes it into the minimum number of peptides
required to describe the potential neo-immunopeptidome. It's main function is to take
transcript-level mutation calls and merge them by gene if the sequenc... | 58,293 |
def unpackData( filename, options, data ):
""" unpackData unpacks a pickle object
"""
import cPickle
import os
if not os.path.exists( filename ):
sys.stderr.write( 'Error, %s does not exist.\n' % filename )
sys.exit(1)
f = open( filename, 'rb' )
d = cPickle.load( f )
f.close()
ret... | 58,294 |
def _getvars(expression, user_dict, depth, vm):
"""Get the variables in `expression`.
`depth` specifies the depth of the frame in order to reach local
or global variables.
"""
cexpr = compile(expression, '<string>', 'eval')
if vm == "python":
exprvars = [ var for var in cexpr.co_names
... | 58,295 |
def get_prefixer(prefix: str, resolver: UrlResolver = lambda x: x) -> UrlResolver:
"""Returns a `UrlResolver` that prefixes otherwise invalid URLs with
`prefix`.
"""
def prefixer(url: str) -> str:
url = resolver(url)
if url.startswith("http"):
return url
return prefi... | 58,296 |
def NASNetLarge(
input_shape=None,
include_top=True,
weights="imagenet",
input_tensor=None,
pooling=None,
classes=1000,
):
"""
ImageNet 모드에서, NASNet 모델을 인스턴스화합니다.
선택적으로 ImageNet에서 사전 트레이닝된 가중치를 로드합니다.
모델에서 사용하는 데이터 형식 규칙은 Keras 구성 `~/.keras/keras.json`에 지정된 규칙입니다.
참고 : 각 Ke... | 58,297 |
def load_jobcodes():
"""Load job codes from job-codes.txt into database."""
print("Loading job codes...")
# Delete all rows in table to make sure there are no duplicates
JobCode.query.delete()
# Read user file and insert data
for row in open("data/job-codes.txt"):
row = row.rstrip()
... | 58,298 |
def entityAttrsGet(_id):
""" Responds to GET requests sent to the /v1/entities/<_id>/attrs API endpoint. """
accepted, content_type = hiascdi.process_headers(request)
if accepted is False:
return hiascdi.respond(
406, hiascdi.confs["errorMessages"][str(406)],
"application/js... | 58,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.