content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_power_VARIANT(input_data, working_dir, t_pt=0):
"""Calculate the power distributions from VARIANT
Parameters
----------
data : dict
DASSH input data dictionary
working_dir : str
Path to current working directory
Returns
-------
dict
DASSH Power objects ... | 5,344,400 |
def from_float32(buffer):
"""Interprets an arbitrary string or NumPy array as Vax single-precision
floating-point binary values, and returns the equivalent array in IEEE
values."""
# Convert the buffer to 2-byte elements
if isinstance(buffer, (str, np.str_, bytes, bytearray)):
pairs = np.fr... | 5,344,401 |
def p_cmdexpr_xmlunescape(p):
"""cmdexpr : XMLUNESCAPE
| XMLUNESCAPE arglist
| XMLUNESCAPE MACRO""" | 5,344,402 |
def draw_bound_box_on_image(image, xmin, ymin, xmax, ymax, vis=True):
"""
:param image:
:param xmin, ymin, xmax, ymax: 归一化后的边角坐标
:param vis:
:return:
"""
pil_image = PIL.Image.fromarray(image)
draw = ImageDraw(pil_image)
xmin *= pil_image.width
xmax *= pil_image.width
... | 5,344,403 |
def get_file_stats(file_name, entity_type='file', lineno=None, cursorpos=None,
plugin=None, language=None, local_file=None):
"""Returns a hash of information about the entity."""
language = standardize_language(language, plugin)
stats = {
'language': language,
'dependenci... | 5,344,404 |
def setup(app: sphinx.application.Sphinx) -> dict[str, object]:
"""Called by Sphinx to set up the extension."""
app.add_config_value("gaphor_models", {}, "env", [dict])
app.add_directive("diagram", DiagramDirective)
app.connect("config-inited", config_inited)
return {
"version": "0.1",
... | 5,344,405 |
def create_vmhc(use_ants, flirt_only=False, name='vmhc_workflow', ants_threads=1):
"""
Compute the map of brain functional homotopy, the high degree of synchrony in spontaneous activity between geometrically corresponding interhemispheric (i.e., homotopic) regions.
Parameters
----------
None
... | 5,344,406 |
def get_chunk_index(connection, db, # pylint: disable=too-many-arguments
tbl, chunk,
ch_db='percona', ch_tbl='checksums'):
"""
Get index that was used to cut the chunk
:param connection: MySQLDb connection
:param db: database of the chunk
:param tbl: table o... | 5,344,407 |
def _get_tree(code):
"""Return an AST tree of the JS passed in `code`."""
if not code:
return
# Acceptable unicode characters still need to be stripped. Just remove the
# slash: a character is necessary to prevent bad identifier errors.
code = JS_ESCAPE.sub("u", unicodehelper.decode(code))... | 5,344,408 |
def initial_assignment_alpha_MSS(agents: List[AdditiveAgent], items: List[str], alpha: float)->Allocation:
"""
Initial division for allocting agents according to their alpha-MMS.
:param agents: valuations of agents, normalized such that MMS=1 for all agents,
and valuation are ordered in ascending orde... | 5,344,409 |
def start_interactive_mode(result):
"""starts an interactive shell so that the user can inspect errors
"""
debuggers = result.debuggers
descrs = result.error_descrs + result.fail_descrs
if len(debuggers) == 1:
# don't ask for test name if there's only one failure
debuggers[0].start()... | 5,344,410 |
def find_furious_yaml(config_file=__file__):
"""
Traverse directory trees to find a furious.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of... | 5,344,411 |
def comp_axes(
self,
axes_list,
machine=None,
axes_dict_in=None,
is_periodicity_a=None,
is_periodicity_t=None,
per_a=None,
is_antiper_a=None,
per_t=None,
is_antiper_t=None,
):
"""Compute simulation axes such as time / angle / phase axes, with or without periodicities
and ... | 5,344,412 |
def update_credentials():
"""
Update the credentials zip file
"""
from base.application import create_app
app = create_app()
app.app_context().push()
click.secho("Zipping env_config", fg='green')
zipdir('env_config/', 'env_config.zip')
zip_creds = get_item('credential', 'travis-c... | 5,344,413 |
def update_person(s, I_ID, firstname, lastname, dob, phonenum=None):
"""This function will update a person's records.
"""
pers = s.query(Person).filter(Person.id == I_ID).one()
pers.first_name = firstname
pers.last_name = lastname
pers.DOB = dob
pers.phone = phonenum
pers.age = age(dob)
s.commit() | 5,344,414 |
def clean_vehicles(country):
"""Delete all vehicles from given country."""
with elastic() as client:
search = Vehicle.search(using=client).filter("term", country=country)
count = search.count()
search.delete()
return count | 5,344,415 |
def render_template(
env: NativeEnvironment,
template: Union[Text, Path],
context: Any,
) -> Any:
"""Utility function for rendering Jinja2 text or file templates.
Args:
env: The Jinja2 environment to use for rendering
template: The template string or file to render
context: ... | 5,344,416 |
def _get_template_dirs(type="plugin"):
"""Return a list of directories where templates may be located.
"""
template_dirs = [
os.path.expanduser(os.path.join("~", ".rapport", "templates", type)),
os.path.join("rapport", "templates", type) # Local dev tree
]
return template_dirs | 5,344,417 |
def aspect_ToCString(*args):
"""
* Translates an ExtendedString to a CString depending of the local format.
:param aString:
:type aString: TCollection_ExtendedString &
:rtype: char *
"""
return _Aspect.aspect_ToCString(*args) | 5,344,418 |
def execute(args, parser):
"""Executes the :ref:`authorise <authorise-cli>` command."""
print('To generate a personal access token do the following:')
print(' 1. Login to your GitHub account')
print(' 2. Go to Settings -> Developer settings -> Personal access tokens')
print(' 3. Click "Generate n... | 5,344,419 |
def suites_list(request):
"""List suites."""
return TemplateResponse(
request,
"manage/suite/suites.html",
{
"suites": model.Suite.objects.select_related().annotate(
case_count=NotDeletedCount("cases", distinct=True)),
}
) | 5,344,420 |
def main():
"""Runs your solution -- no need to update (except to maybe try out different databases)."""
# Sample implementation of the autocomplete API
database = ["abracadara", "al", "alice", "alicia", "allen", "alter", "altercation", "bob", "element", "ello", "eve", "evening", "event", "eventually", "mal... | 5,344,421 |
def push_gitlab_event_dict():
"""
Cleared version of the push gitlab webhook content.
"""
return {
"object_kind": "push",
"event_name": "push",
"before": "0e27f070efa4bef2a7c0168f07a0ac36ef90d8cb",
"after": "cb2859505e101785097e082529dced35bbee0c8f",
"ref": "refs/... | 5,344,422 |
def compute_rotation_effects(VD, settings, EW_small, GAMMA, len_mach, X, CHORD, XLE, XBAR,
rhs, COSINP, SINALF, PITCH, ROLL, YAW, STB, RNMAX):
""" This computes the effects of the freestream and aircraft rotation rate on
CLE, the induced flow at the leading edge
Assumptio... | 5,344,423 |
def setup():
"""
Sets up the database session
"""
global connection
connection = MySQLdb.connect(host=config.get('mysql.host'),
user=config.get('mysql.user'),
passwd=config.get('mysql.password'),
db=co... | 5,344,424 |
def introduction(course):
"""This method represents route to 'courses/<course>/intro.html' where the character introduction is rendered.
This method handles both GET and POST requests.
Args:
course (string): Name of the course.
Returns:
render_template: Returns rendered 'courses/<cours... | 5,344,425 |
def available_formats():
"""Return the available formats for reading and writing
Returns
-------
tuple: tuple of sets. First set are the available formats for reading.
Second set are the available sets for writing.
"""
import pesummary.core.file.formats
import pesummary.gw.file.formats
... | 5,344,426 |
def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2):
"""Get center and scale for bounding box from openpose detections."""
with open(openpose_file, 'r') as f:
keypoints = json.load(f)['people'][0]['pose_keypoints_2d']
keypoints = np.reshape(np.array(keypoints), (-1, 3))
vali... | 5,344,427 |
def test_g_year_month_enumeration004_1194_g_year_month_enumeration004_1194_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=2001-03
2000-10 2001-12 and document value=2001-03
"""
assert_bindings(
schema="msData/datatypes/Facets/gYearMonth/... | 5,344,428 |
def datasets(tablefmt: str):
"""List datasets."""
click.echo(_help_datasets(tablefmt)) | 5,344,429 |
def test_main_fails_on_requests_error(
runner: CliRunner, mock_requests_get: Mock
) -> None:
"""It exits with exit code 1 if wikipedia throws exception."""
mock_requests_get.side_effect = Exception("Boom")
result = runner.invoke(console.main)
assert result.exit_code == 1 | 5,344,430 |
def calc_KPs(TempC, Sal, P=None):
"""
Calculate equilibrium constants for P species.
KP1 = H3PO4
KP2 = H2PO4
KP3 = HPO4
Chapter 5, Section 7.2.5 of Dickson, Sabine and Christian
(2007, http://cdiac.ornl.gov/oceans/Handbook_2007.html)
**WITHOUT APPROX PH SCALE CONVERSION IN CONSTANT**
... | 5,344,431 |
def evaluate_model_sector_prediction(
model,
test_data_x,
test_data_y,
test_data_industry,
test_data_size,
mode_classifier=True,
max_seq_length=512,
batch_size=8,
):
"""This is a function to predict the sector given the input text ids"""
model = model.eval()
pred_label_test ... | 5,344,432 |
def is_no_op(module: Module) -> bool:
"""Return whether the module does no operation in graph.
Args:
module: module
Returns:
whether module is no operation
"""
no_op_modules = (Sequential, _Branch, Parallel, ReduceTuple, GraphModule)
return isinstance(module, no_op_modules) | 5,344,433 |
def check_dirs_make(dir_fullpaths:list):
"""
Check if a directory exists. If not, create it.
@type dir_fullpaths: list
@param dir_fullpaths: Paths to directorys to check
"""
for dir_fullpath in dir_fullpaths:
if not os.path.isdir(dir_fullpath):
os.mkdir(dir_full... | 5,344,434 |
def process_json_file(filename):
"""The entry point - loops through data files and loads each in"""
assert isinstance(filename, str)
if os.path.isdir(filename):
LOGGER.info("Filename points to a directory")
return
else:
LOGGER.info('Processing {}'.format(filename))
with ... | 5,344,435 |
def has_ext(path_name, *, multiple=None, if_all_ext=False):
"""
Determine if the given path name has an extension
"""
base = os.path.basename(path_name)
count = base.count(EXT)
if not if_all_ext and base[0] == EXT and count != 0:
count -= 1
if multiple is None:
return count... | 5,344,436 |
def index_directory(directory,
labels,
formats,
class_names=None,
shuffle=True,
seed=None,
follow_links=False):
"""Make list of all files in the subdirs of `directory`, with their labels.
Args:
... | 5,344,437 |
def execute_actions(protocol, device, actions):
"""
iterate through the actions and call the execute method at the Protocol class
:param protocol:
:param device:
:param actions:
:return:
"""
for action in actions:
protocol.execute(device, action) | 5,344,438 |
def test_cray_config_unset(cli_runner):
""" Test `cray init` for creating the default configuration """
runner, cli, opts = cli_runner
config = opts['default']
configname = config['configname']
filep = '.config/cray/configurations/{}'.format(configname)
with open(filep, encoding='utf-8') as f:
... | 5,344,439 |
def bugprint(content: object):
"""
Only prints message if in debug mode
:type content: str
:param content: the string to print
"""
if LOG is not None and LOG == 1:
print(content) | 5,344,440 |
def colors_from_cmap(length=50, cmap=None, start=None, stop=None):
"""Return color cycle from a given colormap.
Parameters
----------
length : int
The number of colors in the cycle. When `length` is large (> ~10), it
is difficult to distinguish between successive lines because successiv... | 5,344,441 |
def mag_thresh(img, sobel_kernel=3, mag_thresh=(30, 100)):
"""
Return the magnitude of the gradient
for a given sobel kernel size and threshold values
"""
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the gradient in x and y separately... | 5,344,442 |
def mean_absolute_percentage_error(predictions, targets):
"""Calculate mean absolute percentage error"""
mask = (targets != 0.0)
return (np.fabs(targets - predictions)/targets)[mask].mean()*100.0 | 5,344,443 |
def make_net_xds_list(data_xds_list, coords_per_xds):
"""Construct a list of dicts of xarray.Datasets to house the net gains.
Args:
data_xds_list: A List of xarray.Dataset objects containing MS data.
coords_per_xds: A List of Dicts containing dataset coords.
Returns:
net_gain_xds_l... | 5,344,444 |
def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | 5,344,445 |
def check_builds():
"""Base task"""
response = requests.get(
url=urljoin(Config.SISENSE_URL, "v2/builds"), headers=Config.SISENSE_HEADERS
)
builds = pd.DataFrame(data=response.json())
failed_builds = builds.loc[(builds.status == "failed")]
# for each failed cube:
for build in failed_... | 5,344,446 |
def comp_neworig(tileid,dirn='/global/cfs/cdirs/desi/survey/catalogs/testfiberassign/SV3rerun/orig/'):
"""
check that new matches the original
"""
ts = str(tileid).zfill(6)
fa = fitsio.read('/global/cfs/cdirs/desi/target/fiberassign/tiles/trunk/'+ts[:3]+'/fiberassign-'+ts+'.fits.gz')
fn = ... | 5,344,447 |
def create_cluster(config):
"""Create a PostgreSQL cluster for verification.
Once the cluster is initialized, access should be strictly controlled.
The postgresql.conf and pg_hba.conf should be set, and a random
password set for the postgres user.
"""
cluster_path = os.path.join(config['working... | 5,344,448 |
def _get_widget_handler(webmanager):
"""
Returns a handler to get the widgets
:param WebManager webmanager:
:return tornado.web.RequestHandler:
"""
class WidgetHandler(web.RequestHandler):
"""
Handler for all communications over WebSockets
"""
def get(self):
... | 5,344,449 |
def get_model_field_type(model, field_label):
"""
Returns model's field type.
"""
return FIELD_TYPES_MAPPING.get(type(get_model_field(model, field_label)), 'STRING') | 5,344,450 |
def test_yt32():
"""
Testing permutations with Young tableaux without the shape [2,2]
Expected answer is
25 mesh patterns (some classical)
Suffices to look at permutations up to length 6
"""
A = read_bisc_file(ppf + "yt_perm_avoids_32_good_len8")
B = read_bisc_file(ppf + "yt_perm_av... | 5,344,451 |
def touch(path):
"""Creates an empty file at the specified path."""
perms = (os.O_WRONLY | os.O_CREAT | os.O_NONBLOCK | os.O_NOCTTY)
fd = None
try:
fd = os.open(path, perms)
os.utime(path, None)
finally:
if fd is not None:
os.close(fd) | 5,344,452 |
def prepare_elements_default_wallet(my_node):
"""this will collect the free coins we have created with -initialfreecoins=2100000000000000
and transfer them to the default-wallet
"""
rpc = my_node.rpcconn.get_rpc()
wallet = rpc.wallet("")
freehash = rpc.getblockhash(0)
freetxid = rpc.getblock... | 5,344,453 |
def test_set_nonexisting_working_dir(known_dirs):
"""Working dir not added to sys paths if not exist."""
p = '/arb/path'
assert sys.path == ['arb']
moduleloader.set_working_directory(p)
assert sys.path == ['arb']
assert moduleloader._known_dirs == {p} | 5,344,454 |
def Normalize_Column_Scores(df, columns, norm_type = 'divide_by_max'):
"""Normalizes scores for specified columns in a pandas dataframe
Parameters
----------
df : a pandas DataFrame object that contains the specified columns
columns: a list object that includes the columns to normalize
... | 5,344,455 |
def custom_pdf_merge(doctype,docid,attach_to_og_doc=False,doc_to_merge={}):
"""
doc_to_merge = {
"dt_to_merge": "", ##doctype on which merge is to be performed
"dt_to_merge_id": "", ##docid on which merge is to be performed
"attach_fieldname": "", ##fieldname of the attach field through which CAD doc is u... | 5,344,456 |
def test_schema_from_parquet_with_namespace(filename):
"""Test the creation of a new model from a parquet file."""
origin = Path(__file__).parent / "data" / "original" / filename
target_dir = Path(__file__).parent / "data" / "schemas"
namespace = "pydf"
schema = Schema.from_parquet(
str(or... | 5,344,457 |
def find_most_common_word(sentence):
"""Return the most common word in the sentence."""
# Change to lowercase and strip out punctuation
sentence = clean_sentence(sentence)
list_of_words = sentence.split()
word_to_count = dict()
# Create a histogram of the occurrence of all words
for w... | 5,344,458 |
def fast_rcnn_inference(boxes, scores, image_shapes, predictions, score_thresh, nms_thresh, topk_per_image):
"""
Call `fast_rcnn_inference_single_image` for all images.
Args:
boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic
boxes for each image. Elem... | 5,344,459 |
def GetVar(doc:NexDoc, varNumber, varType) -> NexVar:
"""Returns the reference to the specified variable."""
return NexRun("GetVar", locals()) | 5,344,460 |
def full_issuance(cfr_title, cfr_part, version):
"""Create a full regulation tree from a notice"""
process_version_if_needed(cfr_title, cfr_part, version)
process_tree_if_needed(cfr_title, cfr_part, version) | 5,344,461 |
def putversenotes():
"""Serves AJAX call for json data to save notes.
See also [M:NOTESAVE.putVerseNotes][notesave.NOTESAVE.putVerseNotes].
Client code: [{noteverse.sendnotes}][noteversesendnotes]
"""
session.forget(response)
Books = BOOKS()
Note = NOTE(Books)
NoteSave = NOTESAVE(Note)... | 5,344,462 |
def prepend(list, item):
"""Adds the provided item to the front of the list."""
list.insert(0, item) | 5,344,463 |
def _valid_multiview_args(cfg_user, logger):
"""
Validates the "multiview" parameters of a json configuration file used for training.
The function returns False if an error has occurred and True if all settings have passed the check.
:param cfg_user: EasyDict, json configuration file imported as dicti... | 5,344,464 |
def generate_extension(project=None, outdir=None, *,
_project_from_raw=info.Project.from_raw,
_abspath=os.path.abspath,
_projfiles=None,
_gen=None,
):
"""Produce all needed files to build an extension ... | 5,344,465 |
def apply_gradient_descent(var_list, obj, learning_rate = 0.01):
"""
Sets up the gradient descent optimizer
Args:
var_list: List of variables to optimizer over.
obj: Node of the objective to minimize
Notes:
learning_rate: What learning rate to run with. (Default = ``0.01... | 5,344,466 |
def save_to_csv(dealtime,number,vercode, amount):
"""
写入内容到csv
"""
dealtime = dealtime.split(' ')[0] # 切割时间取年月日
number = number + '\t'
vercode = vercode + '\t'
amount = amount[0]
data = (dealtime, number, vercode, amount)
file_path = strftime("jd-assistant_%Y_%m.csv") # 按照当前系统时间创建... | 5,344,467 |
def make_cls_accept_cls_annotated_deps(cls: type[T]) -> type[T]:
"""
Make class `cls` accept class-annotated dependencies, performing following modifications:
- Update `__init__` function to set any class-annotated dependencies as instance attributes
- Update `__signature__` attribute to indicate to Fas... | 5,344,468 |
def getReviewRedirect(entity, params):
"""Returns the redirect to review the specified entity.
"""
return '/%s/review/%s' % (
params['url_name'], entity.key().id_or_name()) | 5,344,469 |
def leapfrog_step(state, target_log_prob_fn, kinetic_energy_fn, step_size, rng=None):
"""Single step of leapfrog.
Notes
=====
The canonical distribution is related to the energy of the system
by
p(p, \theta) = 1/Zexp(-H(\theta, p)/T)
For now, we assume that the kinetic energy takes
the... | 5,344,470 |
def test_atomic_string_max_length_1_nistxml_sv_iv_atomic_string_max_length_2_4(mode, save_output, output_format):
"""
Type atomic/string is restricted by facet maxLength with value 969.
"""
assert_bindings(
schema="nistData/atomic/string/Schema+Instance/NISTSchema-SV-IV-atomic-string-maxLength-2... | 5,344,471 |
def get_plugins_json(url: str = "https://repobee.org/plugins.json") -> dict:
"""Fetch and parse the plugins.json file.
Args:
url: URL to the plugins.json file.
Returns:
A dictionary with the contents of the plugins.json file.
"""
resp = requests.get(url)
if resp.status_code != 2... | 5,344,472 |
def add_available_prefixes(parent, prefix_list):
"""
Create fake Prefix objects for all unallocated space within a prefix.
"""
# Find all unallocated space
available_prefixes = IPSet(parent) ^ IPSet([p.prefix for p in prefix_list])
available_prefixes = [Prefix(prefix=p) for p in available_prefi... | 5,344,473 |
def isready() -> bool:
"""Is the embedded R ready for use."""
INITIALIZED = RPY_R_Status.INITIALIZED
return bool(
rpy2_embeddedR_isinitialized == INITIALIZED.value
) | 5,344,474 |
def yolo2_loss(args, anchors, num_classes, label_smoothing=0, use_crossentropy_loss=False, use_crossentropy_obj_loss=False, rescore_confidence=False):
"""YOLOv2 loss function.
Parameters
----------
yolo_output : tensor
Final convolutional layer features.
true_boxes : tensor
Ground ... | 5,344,475 |
def create_compressed_model(model: tf.keras.Model,
config: NNCFConfig,
compression_state: Optional[Dict[str, Any]] = None) \
-> Tuple[CompressionAlgorithmController, tf.keras.Model]:
"""
The main function used to produce a model ready for compressi... | 5,344,476 |
def load_misc_config():
"""Load misc configuration.
Returns: Misc object for misc config.
"""
return Misc(config.load_config('misc.yaml')) | 5,344,477 |
async def test_wrong_device_now_has_our_ip(hass: HomeAssistant) -> None:
"""Test setup is retried when the wrong device is found."""
bulb = _mocked_wizlight(None, None, FAKE_SOCKET)
bulb.mac = "dddddddddddd"
_, entry = await async_setup_integration(hass, wizlight=bulb)
assert entry.state is config_e... | 5,344,478 |
def filter_activations_remove_neurons(X, neurons_to_remove):
"""
Filter activations so that they do not contain specific neurons.
.. note::
The returned value is a view, so modifying it will modify the original
matrix.
Parameters
----------
X : numpy.ndarray
Numpy Matri... | 5,344,479 |
def adaptive_threshold(im, block_size, constant, mode=cv2.THRESH_BINARY):
"""
Performs an adaptive threshold on an image
Uses cv2.ADAPTIVE_THRESH_GAUSSIAN_C:
threshold value is the weighted sum of neighbourhood values where
weights are a gaussian window.
Uses cv2.THRESH_BINARY:
... | 5,344,480 |
def get_loss(stochastic, variance_regularizer):
"""Get appropriate loss function for training.
Parameters
----------
stochastic : bool
determines if policy to be learned is deterministic or stochastic
variance_regularizer : float
regularization hyperparameter to penalize high varianc... | 5,344,481 |
def simul_growth_ho_amir(nbstart, run_time, params, name):
"""Simulate the Ho and Amir model (Front. in Microbiol. 2015) with inter-initiation per origin adder and
timer from initiation to division
Parameters
----------
nbstart : int
number of cells to simulate
run_time: int
... | 5,344,482 |
def variable_id(variable):
"""Return variable identification for .dot file"""
if isinstance(variable, FileAccess):
return "a_{}".format(variable.id)
act_id = variable.activation_id
act_id = "global" if act_id == -1 else act_id
return "v_{}_{}".format(act_id, variable.id) | 5,344,483 |
def node_set_power_state(request, node_id, state, soft=False):
"""Set power state for a given node.
:param request: HTTP request.
:param node_id: The UUID or name of the node.
:param state: the power state to set ['on', 'off', 'reboot'].
:param soft: flag for graceful power 'off' or reboot
:ret... | 5,344,484 |
def __sympyToC_Grad(exprs: list, doOpts: bool = False) -> str:
""" creates C code from a list of sympy functions (somewhat optimized).
source: https://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy
and modified """
tmpsyms = sympy.numbered_symbols("tmp")
if doOpts:
s... | 5,344,485 |
def startServer(mock=True, mockS3=False):
"""
Test cases that communicate with the server should call this
function in their setUpModule() function.
"""
# If the server starts, a database will exist and we can remove it later
dbName = cherrypy.config['database']['uri'].split('/')[-1]
usedDBs... | 5,344,486 |
def get_loans(m='BTC_ETH'):
"""
"""
pass | 5,344,487 |
def index():
"""User friendly index page at the root of the server
guides the user to the reportss
"""
return render_template('index.html') | 5,344,488 |
def read_lookup(infile):
"""
-----------------------------------------------------------------------------
Read data from a lookup database.
Inputs:
infile [string] Input file containing the lookup data base.
Outputs:
[tuple] each element of the tuple is a numpy array. The elements in ... | 5,344,489 |
def sum_function(context, nodeset, string):
"""
The dyn:sum function calculates the sum for the nodes passed as the first
argument, where the value of each node is calculated dynamically using an
XPath expression passed as a string as the second argument.
http://www.exslt.org/dyn/functions/sum/inde... | 5,344,490 |
def event_detail(request, id):
""" Return a JSON dict mapping for event given id
"""
event = get_object_or_404(Event, pk=id)
event_dict = {
"success": 1,
"result": [{
"id": event.id,
"title": event.title,
"description": event.description,
"... | 5,344,491 |
def main(args):
"""
Main interface
"""
if args.outdir != '' and not os.path.isdir(args.outdir):
os.makedirs(args.outdir)
# load metdata {seq_uuid : taxon}
idx, ntaxa = load_meta(args.metadata)
# load clusters
clst = {}
clst['rrna'] = load_uclust(args.uclust, idx)
clst['cd... | 5,344,492 |
def test_backup(dbsession, ini_settings):
"""Execute backup script with having our settings content."""
f = NamedTemporaryFile(delete=False)
temp_fname = f.name
f.close()
ini_settings["websauna.backup_script"] = "websauna.tests:backup_script.bash"
ini_settings["backup_test.filename"] = temp_fn... | 5,344,493 |
def prepare_state(qubits: list[cirq.Qid], x: int) -> list[cirq.Gate]:
"""Prepare qubits into an initial state.
Args:
qubits: The qubits to prepare.
x: The initial state of the qubits. Must be non-negative.
Returns:
A list of gates to prepare the qubits.
Raises:
ValueEr... | 5,344,494 |
def manage(id):
"""Manage room request."""
room_request = RoomRequest.query.get(id)
if room_request is None:
return abort(404)
return render_template('room_request/manage.html', room_request=room_request) | 5,344,495 |
def ger(self, y):
"""Computer an outer product between two vectors"""
assert self.dim() == 1 and y.dim() == 1, "Outer product must be on 1D tensors"
return self.view((-1, 1)).matmul(y.view((1, -1))) | 5,344,496 |
def test_resolution_norm():
"""Tests resolution gaussian
"""
p = np.array([0., 0., 1., 0., 0., 1.43, 23867.71, 22311.93, 20739.82])
a, b = np.linspace(-1, 1, 501), np.linspace(-1, 1, 501)
q = np.meshgrid(a, b, sparse=True)
y = functions.resolution(p, q)
integ = simps(simps(y, b), a)
asse... | 5,344,497 |
def interpret(input, debug=False):
"""Downloads data and runs commands as per the Arx file."""
if debug:
log.configure(level='debug')
data = yaml.load(input.read())
task = Task(data)
task.run() | 5,344,498 |
def delete_request(user_id): # удаление запроса
"""
:param user_id: user_id
:return: удаление запроса
"""
global connect
global cursor
cursor.execute("DELETE FROM Requests WHERE toUserID={0}".format(user_id))
connect.commit() | 5,344,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.