content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_plot3d_array_of_arrays(v, interpolation_type, texture, **kwds):
"""
A 3-dimensional plot of a surface defined by a list of lists ``v``
defining points in 3-dimensional space. This is done by making the
list of lists into a matrix and passing back to :func:`list_plot3d`.
See :func:`list_plo... | 72,800 |
def volume(input, copyFrom=None, rescale=True, voltype=None):
"""
Read an existing geoprobe volue or make a new one based on input data
Input:
input: Either the path to a geoprobe volume file or data to
create a geoprobe object from (either a numpy array or
... | 72,801 |
def test_craysdbproc_from_gz_cache():
"""
Initialize CraySdb from compressed cache
"""
# Read from a cache file
craysdbproc = tokio.connectors.craysdb.CraySdbProc(tokiotest.SAMPLE_XTDB2PROC_FILE)
verify_craysdbproc(craysdbproc) | 72,802 |
def view_related_developers(request, tag, slug):
"""
Tutorial > View Related Developers
"""
namespace = CacheHelper.ns('tutorial:views:view_related_developers', tag=tag, slug=slug)
response_data = CacheHelper.io.get(namespace)
if response_data is None:
response_data, tutorial = RelatedH... | 72,803 |
def test_negIntOrZeroInStringValidator_incorrect_values(value):
"""Check the parsing and validating negative integers or a zero stored in string."""
# exception is expected
with pytest.raises(Invalid) as excinfo:
negIntInStringValidator(value) | 72,804 |
def compute_neuron_head_importance(task_name,
model,
data_loader,
num_layers,
num_heads,
loss_fct=nn.loss.CrossEntropyLoss(),
... | 72,805 |
def no_init(_data, weights):
"""
Return the entered weights.
Parameters
----------
_data: ndarray
Data to pick to initialize weights.
weights: ndarray
Previous weight values.
Returns
-------
weights: ndarray
New weight values
Notes
-----
Useful ... | 72,806 |
def primeFactors(someInt):
"""
return a list of the prime factors of
someInt.
e.g.
primeFactors(24)=[2,2,2,3]
primeFactors(23)=[23]
primeFactors(25)=[5,5]
"""
return "stub" | 72,807 |
def create_local_gateway_route(client, local_cidr, **route_kwargs):
"""[summary]
Arguments:
client {[type]} -- [description]
local_cidr {[type]} -- [description]
Keyword Arguments:
gateway {[type]} -- [description] (default: {None})
Returns:
OperationResult
"""
... | 72,808 |
def validate_ui(self, value):
"""Validate EngineUI objects."""
if not isinstance(value, EngineUI):
reason = 'not an EngineUI object'
raise ValueError(self.msg.format(reason))
return value | 72,809 |
def is_valid_uuid(val):
"""
Check if a string is a valid uuid
:param val: uuid String
:return: Returns true if is a string is a valid uuid else False
"""
try:
uuid.UUID(str(val))
return True
except ValueError:
return False | 72,810 |
def generate_stat_string(stat_distribution, name):
"""generates the gear rating string based on the count of the stat"""
count = stat_distribution.count(name)
extra_line = "\n" if name == "versatility" else ""
return "gear_{0}_rating={1}{2}".format(name, count * config["stats"]["steps"], extra_line) | 72,811 |
def _save_step(step_number, variable_to_save, prefix=''):
"""
This method saves all the information corresponding to specific step.
:param int step_number:
Value of the current step in the hyper-heuristic procedure. If it is not a hyper-heuristic, this integer
corresponds to operator index.... | 72,812 |
def pad_dialog(
dialog: Dialog, max_dialog_size: int, max_utterance_size: int
) -> Tuple[List[List[int]], List[List[int]], List[List[int]], List[List[int]]]:
"""Pads utterances in a dialog up to max dialog sizes."""
dialog_usr_input, dialog_usr_mask, dialog_sys_input, dialog_sys_mask = [], [], [], []
for tu... | 72,813 |
def send_files_to_gcp(pid):
"""
Schedule a background task to send the files to GCP.
This function can be runned manually to force a re-send of all the files
to GCP. It only requires the Project ID.
"""
project = PublishedProject.objects.get(id=pid)
exists = utility.check_bucket_exists(proje... | 72,814 |
def _make_sbatch_string(
command: str,
folder: tp.Union[str, Path],
job_name: str = "submitit",
partition: tp.Optional[str] = None,
time: int = 5,
nodes: int = 1,
ntasks_per_node: tp.Optional[int] = None,
cpus_per_task: tp.Optional[int] = None,
cpus_per_gpu: tp.Optional[int] = None,
... | 72,815 |
def test_find_all_occurencies_of_dollar_amounts_with_optional_decimal_values():
""" Find all occurrences of dollar amounts with optional decima lvalues.
- escaped '\$' (because '$' is a special regex character)
- escaped '\.' (because '.' is a special regex character)
"""
report = """
$5,000.00 ... | 72,816 |
def parse_redis_url(url):
"""
Given a url like redis://localhost:6379/0, return a dict with host, port,
and db members.
"""
warnings.warn(
"Use redis.StrictRedis.from_url instead", DeprecationWarning,
stacklevel=2)
parsed = urllib.parse.urlsplit(url)
return {
'host': ... | 72,817 |
def Torque(cc1,cc2,ccp,g,mass=1.0):
"""
cc1: origin of axis, cc2 head of axis
ccp: point
g: Gradients in Cartasian coordinate, [dx,dy,dz]
"""
torque=0.0
x21=cc2[0]-cc1[0]; y21=cc2[1]-cc1[1]; z21=cc2[2]-cc1[2]
xp1=ccp[0]-cc1[0]; yp1=ccp[1]-cc1[1]; zp1=ccp[2]-cc1[2]
dnom=x21**... | 72,818 |
def write_tar_from_contents(contents, filter=None):
"""Writes a tar file from a dict of archive names to bytes that represent the
contents of each file.
"""
digest = io.BytesIO()
with tarfile.TarFile(mode="w", fileobj=digest) as tar:
for filename, content in contents.items():
_ad... | 72,819 |
def selectedPoints(selectionThreshold):
"""
selectedPoints(selectionThreshold) -> iterator
Return an iterator which yields the position of every point currently
selected in the Viewer in turn.
The selectionThreshold parameter is used when working with a soft selection.
Only points with a selection level... | 72,820 |
def exp_ig_genotyping():
"""Shows the performance of Word-Blot in genotyping Immunoglobin heavy
chain genotyping. A thousand reads (average length 240nt) covering the
mature VDJ region of chromosome 14 from the stanford S22 dataset are
genotyped by Word-Blot against the IMGT list of Immunoglobin heavy c... | 72,821 |
def test_multi_mws_failing(client: FlaskClient):
"""test GET method with multiple middlewares"""
resp = client.get('/get-with-auth')
assert resp.status_code == 403
assert not resp.json.get('success') | 72,822 |
def nice_plot(plotlist, spines=['left', 'bottom'], position=10, direction='inward', axesoff = False):
""" Adjust a plot so that it looks nicer than the default matplotlib plot
Also allow quick access to things we like to do for publication plots, including:
using a calbar instead of an axes: calbar ... | 72,823 |
def oci_config(config):
"""collectd configuration callback method"""
global _configuration
_configuration = Configuration(config) | 72,824 |
def eliminate(values, s, d):
"""Eliminate d from values[s]; propagate when values or places <= 2.
Return values, except return False if a contradiction is detected."""
global counttotalsearches # DGTEMP
counttotalsearches += 1 # DGTEMP
if d not in values[s]:
return values ## Already elim... | 72,825 |
def non_zero_uniform(shape):
"""Samples in open range (0, 1).
This avoids the value 0, which can be returned by tf.random.uniform, by
replacing all 0 values with 0.5.
Args:
shape: a list or tuple of integers.
Returns:
A Tensor of the given shape, a dtype of float32, and all values in the open
i... | 72,826 |
def load_detector(device='cpu'):
""" utility function to load a trained detector
"""
this_dir = os.path.dirname(__file__)
cfg.merge_from_file(this_dir + '/w32_256x256.yaml')
# pretrain state_dict by us
state_dict = torch.load(this_dir + '/model_best.pth', map_location=device)
model = get_p... | 72,827 |
def _format_moving_cutoff_predictions(y_preds, cutoffs):
"""Format moving-cutoff predictions"""
if not isinstance(y_preds, list):
raise ValueError(f"`y_preds` must be a list, but found: {type(y_preds)}")
if len(y_preds[0]) == 1:
# return series for single step ahead predictions
retu... | 72,828 |
def wipe_cluster(cluster, force=False):
""" Deletes data on all datanode and namenode disks.
Options:
force: If set to True, the user is not prompted. Default: no.
username: name of the user who is given permissions to
the storage directories. Default: hdfs
"""
try:
... | 72,829 |
def test_starter_on_event_out_of_sequence(mocker, starter, command_list):
""" Test how failure are raised in Starter.on_event_out_of_sequence method. """
# set test planned_jobs and current_jobs
starter.planned_jobs = {'sample_test_2': {1: []}}
for command in command_list:
starter.current_jobs.s... | 72,830 |
def get_bom_contents(bom_file):
"""
Run lsbom on the provided file and return a nested dict representing
the file structure
"""
lsbom = subprocess.Popen(
["/usr/bin/lsbom", bom_file], stdout=subprocess.PIPE
).communicate()[0]
file_list = filter(None,
[ l.split("\t")[0].lstr... | 72,831 |
def get_possible_modes():
"""Get the set of possible modes."""
modes = set()
with open("web/src/helpers/constants.js", encoding="utf-8") as file_:
# The call to `eval` is a hack to parse the `modeOrder` array from the
# JavaScript source file.
for mode in eval(re.search(r"^const mode... | 72,832 |
def remote_restore_from_backup(self):
"""Restore from a backup directory on a remote file system.""" | 72,833 |
def writeToExcel(list, col):
"""Write data to the Excel spreadsheet."""
counter = 0
for rowNum in range(3, 71):
sheet.cell(row=rowNum, column=col).value = list[counter]
counter += 1 | 72,834 |
def live():
"""Connects to the server."""
env.hosts = [os.environ.get('{{cookiecutter.repo_name}}_host')]
env.user = 'freshmilk'
env.cwd = '/var/www/{{cookiecutter.domain_name}}'
env.connect_to = '{0}@{1}:{2}'.format(env.user, env.hosts[0], env.cwd) | 72,835 |
def dates(origin_city, destination_city, raw):
"""List departure dates for a trip from ORIGIN_CITY to DESTINATION_CITY.
ORIGIN_CITY may be a name or ID.
DESTINATION_CITY may be a name or ID.
"""
origin_city_id = get_city_id(origin_city)
destination_city_id = get_city_id(destination_city)
da... | 72,836 |
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
"""
:param m:
:param d:
:param data_portal:
:param scenario_directory:
:param subproblem:
:param stage:
:return:
"""
data_portal.load(
filename=os.path.join(scenario_directory, "inputs", "proj... | 72,837 |
def convert_to_hexadecimal(bits, padding):
"""
Converts bits to a hexadecimal character with padding.
E.g.
Converts [False, False, False, True], 0 to "1".
Converts [True, False, False, False], 2 to "08"
Args:
bits: List of boolean values.
padding: Integer of number of ... | 72,838 |
async def read_patron_list(
session: aio_session.AsyncSession = fastapi.Depends(
dependencies.get_session),
offset: int = 0,
limit: int = fastapi.Query(default=100, le=100),
current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument
dependencies.get_current... | 72,839 |
def beta_table(stocks_weights, start, end):
"""
Returns an attribution table for portfolio beta
:param stocks_weights: table of the name of equities in one column, weights in another
:param start: start date
:param end: end date
:return: table
"""
# Due to the nature of the percentchange... | 72,840 |
def sepconv_relu_sepconv(inputs,
filter_size,
output_size,
first_kernel_size=(1, 1),
second_kernel_size=(1, 1),
padding="LEFT",
nonpadding_mask=None,
... | 72,841 |
def convert(context, base_path, rule):
"""
Convert the python representation of a targets file into a python
representation of a buck file.
"""
converters = [
discard.DiscardingConverter(context, 'cpp_binary_external'),
discard.DiscardingConverter(context, 'haskell_genscript'),
... | 72,842 |
def wrap_do_release_upgrade(unit_name, from_series="trusty",
to_series="xenial",
files=None, workaround_script=None):
"""Wrap do release upgrade.
In a production environment this step would be run administratively.
For testing purposes we need this au... | 72,843 |
async def test_import_entity_already_configured(
hass: HomeAssistant,
vizio_connect: pytest.fixture,
vizio_bypass_setup: pytest.fixture,
) -> None:
"""Test entity is already configured during import setup."""
entry = MockConfigEntry(
domain=DOMAIN,
data=vol.Schema(VIZIO_SCHEMA)(MOCK_... | 72,844 |
def set_review_filters(request):
"""Sets review filters given by passed request.
"""
review_filters = request.session.get("review-filters", {})
if request.POST.get("name", "") != "":
review_filters["name"] = request.POST.get("name")
else:
if review_filters.get("name"):
d... | 72,845 |
def p_else_case_stmt_bool_opt_none(t):
"""
else_case_stmt_bool_opt :
"""
t[0] = None
repGrammar.append(t.slice) | 72,846 |
def _sanitize_title(title):
""" Remove all non alphanumeric characters from title and lowercase """
alphanumeric = string.ascii_lowercase + string.digits + ' '
title = title.lower()
title = "".join(filter(lambda x: x in alphanumeric, title))
return title | 72,847 |
def IsBefore(version, major, minor, revision):
"""Decide if a given version is strictly before a given version.
@param version: (major, minor, revision) or None, with None being
before all versions
@type version: (int, int, int) or None
@param major: major version
@type major: int
@param minor: minor... | 72,848 |
def watermark(app, env):
"""Add watermark."""
if app.config.sphinxmark_enable is True:
LOG.info('adding watermark...', nonl=True)
buildpath, imagefile = getimage(app)
cssname = buildcss(app, buildpath, imagefile)
app.add_css_file(cssname)
LOG.info(' done') | 72,849 |
def save_to_caps(
source_dir, image_id, list_session_ids, caps_dir, overwrite_caps=False
):
"""Save `source_dir`/`image_id`/ to CAPS folder.
This function copies FreeSurfer segmentation and regional_measures folder of `source_dir`/`image_id`/ to
`caps_dir`/subjects/<participant_id>/<long_id>/freesurfer... | 72,850 |
def test_change_a_host_group(basic_host_configuration, existing_host_responses):
"""
Tests if the group of a host is changed when solicited
"""
host, groups, interfaces, kwargs, _ = basic_host_configuration
(
host_get_output,
hostgroup_get_output_up,
hostinterface_get_output,... | 72,851 |
def get_pdf_keys(template_pdf):
"""
Helper function for generating pdf form field keys, debugging, etc.
"""
template_pdf = pdfrw.PdfReader(template_pdf)
annotations = template_pdf.pages[0][ANNOT_KEY]
keys = {}
for page in template_pdf.pages:
annotations = page[ANNOT_KEY]
if ... | 72,852 |
def generateRules(L, supportData, minConf=0.7):
"""
生成关联规则
Args:
L 频繁项集列表
supportData 频繁项集支持度的字典
minConf 最小置信度
Returns:
bigRuleList 可信度规则列表(关于 (A->B+置信度) 3个字段的组合)
"""
bigRuleList = []
for i in range(1, len(L)):
# 获取频繁项集中每个组合的所有元素
for freqSet in... | 72,853 |
def domain_check(f, symbol, p):
"""Returns False if point p is infinite or any subexpression of f
is infinite or becomes so after replacing symbol with p. If none of
these conditions is met then True will be returned.
Examples
========
>>> from sympy import Mul, oo
>>> from sympy.abc impor... | 72,854 |
def makePyramid(elem, graph, levels=4, scale=0.5):
"""
Create a pyramid of num images based upon elem, which becomes the
first child of the new pyramid
"""
p = elem.getparent()
minDim = round(levels / scale)
width = max(int(elem.get(swidth, str(minDim))), minDim)
height = max(int(elem.ge... | 72,855 |
def get_file_handler(log_dir=None):
"""
This function is responsible for creating a file log handler with a global format and returning it.
Returns:
- (obj): A log handler that is responsible for logging to a file.
"""
log_file_dir = log_dir if log_dir else LOGGING_LOG_TO_FILE_DEFAULT_DIR
... | 72,856 |
def parse_negline(neg_line):
"""
Parse the THIRD line of the .mmo file, where the negations are stored.
Why does it not do this per-phrase? Mystery.
We connect the negated-CUI to its appearance in the text using the
ConceptPositionalInfo which _appears_ to correspond to the PosInfo field
which ... | 72,857 |
def validate_cohort_project_allowed():
"""
Returns true if a valid project is provided. Remote call is set up in
static/js/cohortUpload.js.
"""
project = request.args.get('project')
valid = project in db.get_mw_projects()
return json.dumps(valid) | 72,858 |
def atoms_compare():
"""
This function is to check if two uploaded files have same number of atoms
to mention it as conformations of same ensembles
"""
file1 = sys.argv[1]
file2 = sys.argv[2]
#recep_com = '4epw.pdb'
atoms1 = [];
atoms2 = [];
recep_f... | 72,859 |
def depthwise_2d_fast(feat, weights):
"""
"""
feat = tf.convert_to_tensor(feat)
weights = tf.convert_to_tensor(weights)
kernel_size = weights.shape.as_list()[0]
return graphics_tf_module.depthwise_conv_fast(feat, weights, kernel_size) | 72,860 |
def handle_trace_length(state_trace_length):
"""
transform format of trace length
:return:
"""
trace_length_record = []
for length in state_trace_length:
for sub_length in range(0, int(length)):
trace_length_record.append(sub_length + 1)
return trace_length_record | 72,861 |
def compute_ts_map(counts, background, exposure, kernel, mask=None, flux=None,
method='root brentq', optimizer='Brent', parallel=True,
threshold=None):
"""
Compute TS map using different optimization methods.
Parameters
----------
counts : `~gammapy.image.SkyIm... | 72,862 |
def test_flaskproperty_from_testconfig(app: AspenApp):
"""Grab the flask properties from TestingConfig, and ensure that we get a reasonable
list of them."""
test_config = app.aspen_config
assert isinstance(test_config, testing.TestingConfig)
props = test_config.flask_properties()
assert len(prop... | 72,863 |
def test_proj_public_no_project(client):
"""Attempting to get public key without a project should not work"""
token = tests.UserAuth(tests.USER_CREDENTIALS["researchuser"]).token(client)
response = client.get(tests.DDSEndpoint.PROJ_PUBLIC, headers=token)
assert response.status_code == http.HTTPStatus.BA... | 72,864 |
def init_db_storage():
"""Creates and returns path to empty compilation database.
Terminates script if database already exists."""
working_directory = os.getcwd()
compilation_db_path = os.path.join(working_directory, DB_FILENAME)
if os.path.lexists(compilation_db_path):
sys.exit("{filename}... | 72,865 |
def audio_duration(filename):
"""
duration of a audio file (usually mp3)
Parameters
----------
filename : str
must be a valid audio file (usually mp3)
Returns
-------
duration in seconds : float
Note
----
Only supported on Windows and Pythonista. On other platform ... | 72,866 |
def is_moderator(request, view):
"""
Helper function to check if a user is a moderator
Args:
request (HTTPRequest): django request object
view (APIView): a DRF view object
Returns:
bool: True if user is moderator on the channel
"""
user_api = request.channel_api
cha... | 72,867 |
def monkeypatch(monkeypatch):
"""Adapt pytest's monkeypatch to support stdlib's pathlib."""
class Monkeypatcher:
"""Middle man for chdir."""
def _chdir(self, value):
"""Change dir, but converting to str first.
This is because Py35 monkeypatch doesn't support stdlib's p... | 72,868 |
def binom(n, k):
"""
Obtain the binomial coefficient, using a definition that is mathematically
equivalent but numerically stable to avoid arithmetic overflow.
The result of this method is "n choose k", the number of ways choose an
(unordered) subset of k elements from a fixed set of n elements.
... | 72,869 |
def test_stop_if():
"""Test action stop_if"""
execute_workflow(r"""
[0: shared='result']
rep = range(20)
result = []
input: for_each='rep'
stop_if(_rep > 10)
result.append(_rep)
""")
assert env.sos_dict["result"] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | 72,870 |
def main(argv):
"""
Entry point for stlinfo.
Arguments:
argv: command line arguments (without program name!)
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-t', '--text', action='store_true', help='print text representation of the file'
)
... | 72,871 |
def no_auth(request):
"""
Use this if no auth is desired
"""
return request | 72,872 |
def bilstm_layer_cudnn(input_data, num_layers, rnn_size, keep_prob=1.):
"""Multi-layer BiLSTM cudnn version, faster
Args:
input_data: float32 Tensor of shape [seq_length, batch_size, dim].
num_layers: int64 scalar, number of layers.
rnn_size: int64 scalar, hidden size for undirectional L... | 72,873 |
def check_auth(business_identifier: str, jwt: JwtManager, **kwargs):
"""Authorize the user for the business entity."""
bearer_token = jwt.get_token_auth_header() if jwt else None
auth_url = current_app.config.get('AUTH_API_ENDPOINT') + f'entities/{business_identifier}/authorizations'
auth_response = Res... | 72,874 |
def merge_config_bundles(
config_bundle: config_bundle_pb2.ConfigBundle,
backfilled_config_bundle: config_bundle_pb2.ConfigBundle,
):
"""Merges backfilled_config_bundle into config_bundle.
For each repeated field in ConfigBundle, all elements in
backfilled_config_bundle that are not in config_bundl... | 72,875 |
def calculate_smoothed_trends(
case_counts: np.ndarray,
death_counts: np.ndarray,
hosp_counts: np.ndarray,
smoothing_window: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Calculates the smoothed trends with the given smoothing window
:param case_counts: Cases per day
:param death_counts: Deaths per... | 72,876 |
def generate_swagger_params(crown: ViewCrown, swagger_params: dict) -> dict:
"""
assemble params for swagger_auto_schema by crown
"""
default_params = {}
if crown.body_in:
default_params = {"request_body": crown.get_in_serializer_instance()}
elif crown.query_in:
default_params = ... | 72,877 |
def test_get_waypoints_raises_if_no_max_travel_z_clearance() -> None:
"""Raises ArcOutOfBoundsError if max_travel_z doesn't have clearance."""
with pytest.raises(ArcOutOfBoundsError):
get_waypoints(
origin=Point(1, 1, 3),
dest=Point(2, 2, 3),
move_type=MoveType.GENERA... | 72,878 |
def copy_existing_event(url, human_confirms=False):
"""指定したイベントをコピーする
コピーの確認ダイアログを出した状態で止めたければ human_confirms=True を指定する。
connpassの仕様上、管理者のイベントのみコピーできる
画面参考(コピーを作成)
https://help.connpass.com/organizers/event-detail.html#id32
"""
go_to(url)
click("コピーを作成")
if not human_confirms:
... | 72,879 |
def total_size(metainfo):
"""
Compute sum of all files' size
"""
if metainfo.has_key('files'):
total = 0
for infile in metainfo['files']:
if infile.has_key('length'):
total += infile['length']
return total
else:
return None | 72,880 |
def foo():
""" This function has a docstring!
You can write some useful tips here.
See http://www.python.org/dev/peps/pep-0257/
for the general docstring guidelines.
"""
print "Hello" | 72,881 |
def diffmap(adata, **kwargs):
"""\
Scatter plot in diffmap basis.
Parameters
----------
{scatter}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
return scatter(adata, basis="diffmap", **kwargs) | 72,882 |
def test_list_date_time_enumeration_4_nistxml_sv_iv_list_date_time_enumeration_5_5(mode, save_output, output_format):
"""
Type list/dateTime is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-enumeration-5.xsd",
... | 72,883 |
def makeHTMLword(body, fontsize):
"""take words and fontsize, and create an HTML word in that fontsize."""
#num = str(random.randint(0,255))
# return random color for every tags
color = 'rgb(%s, %s, %s)' % (str(random.randint(0, 255)), str(random.randint(0, 255)), str(random.randint(0, 255)))
# get ... | 72,884 |
def sigma_x_rk_new(
thickness,
radius,
length,
f_y_k,
fab_quality=None,
flex_kapa=None
):
"""
Meridional characteristic buckling stress.
Calculates the characteristic meridional buckling stress for a cylindrical shell according to EN1993-1-6 [1].
... | 72,885 |
def createVXlan(vxname,vxid,multicast,vxbackend):
"""
Always brought up too
Created with no protocol, and upped (no ipv4, no ipv6)
Fixed standard : 239.0.x.x, id
# 0000-fe99 for customer vxlans, ff00-ffff for environments
MTU of VXLAN = 1500
"""
cmd = 'ip link add %s type vxlan id %s gro... | 72,886 |
def test_cos():
"""
Function testing cos
"""
a = fwd.Variable()
b = fwd.Variable()
c = a+b
f1 = fwd.cos(a+c)
f2 = fwd.cos(a*b)
assert equals(f1.evaluation_at({a:1.0, b: 2.0}), np.cos(4))
assert equals(f2.evaluation_at({a:1.0,b:2}), np.cos(2))
assert equals(f1.derivative_at(a,... | 72,887 |
def sww2pts(name_in, name_out=None,
data_points=None,
quantity=None,
timestep=None,
reduction=None,
NODATA_value=-9999,
verbose=False,
origin=None):
"""Read SWW file and convert to interpolated values at selected points
The par... | 72,888 |
def exec_command(command, cwd=None, stdout=None, env=None):
"""Returns True in the command was executed successfully"""
try:
command_list = command if isinstance(command, list) else command.split()
env_vars = os.environ.copy()
if env:
env_vars.update(env)
subprocess.c... | 72,889 |
def test_osculating_elements_payload(params, payload):
"""Test osculating elements payload."""
assert OsculatingElements(**params).payload == payload | 72,890 |
def ts_grismc_sim(pixels):
"""
Simple analytic wavelength calibration for Simulated GRISMC data
"""
disp = 0.0010035 ## microns per pixel (toward positive X in raw detector pixels, used in pynrc)
undevWav = 4.0 ## undeviated wavelength
undevPx = 1638.33
wavelengths = (pixels - undevPx) ... | 72,891 |
def get_admin_principal_by(authentication_manager: AuthenticationManager) -> Callable[[Request], PrincipalService]:
"""
admin only
"""
return get_principal_by(authentication_manager, [UserRole.ADMIN]) | 72,892 |
def get_profile_avatar_upload_to(instance, filename):
""" Returns a valid upload path for the avatar associated with a forum profile. """
return instance.get_avatar_upload_to(filename) | 72,893 |
def adcdados(n='desconhecido', i=0):
"""Cria uma lista de pessoas e Adiciona novas pessoas ao arquivo"""
arquivo = open('dados.txt', 'a')
arquivo.write(f'{n};{i}\n')
arquivo.close()
print(f'Novo registro de {n} adicionado.') | 72,894 |
def calc_r(alphas: np.ndarray, colvars: np.ndarray,
calc_jac: bool) -> tuple[np.ndarray, Optional[np.ndarray]]:
"""
Calculate linear combination of reaction coordinates given a weights vector
and colvars matrix. Also returns the jacobian with respect to the alphas if
requested.
Parameter... | 72,895 |
def discretized_exponential(lamb, up_bound, steps):
""" Exponential distribution on discretized interval [0, up_bound] """
return discretized_state(lambda x: stats.expon.pdf(x, scale=1 / lamb),
0, up_bound, steps) | 72,896 |
def timedelta_to_string(dt):
"""
Return hh:min:sec from a timedelta64.
There doesn't seem to be a standard pandas or numpy function to
do this strangely.
"""
total_sec = dt / np.timedelta64(1, 's')
hours = int(total_sec // 3600)
minutes = int((total_sec // 60) % 60)
seconds = int(to... | 72,897 |
def _use_wal(db_file):
""" Ensures that sqlite database is using WAL journal mode """
con = sqlite3.connect(db_file)
cursor = con.cursor()
cursor.execute('PRAGMA journal_mode=wal;') | 72,898 |
def funex(c):
"""
Compile a function by 'exec'
:param c: function to compile
:type c: string
:return: the function 'f' declared in the input string
:rtype: function
"""
dc = {}
exec(c, dc)
return dc['f'] | 72,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.