content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_current_time():
"""just returns time stamp
"""
time_stamp = datetime.datetime.fromtimestamp(
time()).strftime('%Y-%m-%d %H:%M:%S')
return time_stamp | 37,500 |
def get_bad_fname(p, subj, check_exists=True):
"""Get filename for post-SSS bad channels."""
bad_dir = op.join(p.work_dir, subj, p.bad_dir)
if not op.isdir(bad_dir):
os.mkdir(bad_dir)
bad_file = op.join(bad_dir, 'bad_ch_' + subj + p.bad_tag)
if check_exists:
bad_file = None if not op... | 37,501 |
def inference(config):
"""
Args:
config (TYPE): NULL
Returns: TODO
Raises: NULL
"""
if config.model.init_model_params is None:
raise RuntimeError("config.init_model_params should be a valid model path")
dataset_config = {'db_file': config.data.db,
'i... | 37,502 |
def test_check_git_version(mocker, git_version, expected_exception):
"""Tests core._check_git_version"""
mocker.patch('tidy.utils.shell_stdout', autospec=True, return_value=git_version)
with expected_exception:
core._check_git_version() | 37,503 |
def test_atomic_ncname_min_length_nistxml_sv_iv_atomic_ncname_min_length_1_5(mode, save_output, output_format):
"""
Type atomic/NCName is restricted by facet minLength with value 1.
"""
assert_bindings(
schema="nistData/atomic/NCName/Schema+Instance/NISTSchema-SV-IV-atomic-NCName-minLength-1.xsd... | 37,504 |
async def test_script_mode_2(hass, hass_ws_client, script_mode, script_execution):
"""Test overlapping runs with max_runs > 1."""
id = 1
def next_id():
nonlocal id
id += 1
return id
flag = asyncio.Event()
@callback
def _handle_event(_):
flag.set()
event = ... | 37,505 |
def ease_of_movement(high, low, close, volume, n=20, fillna=False):
"""Ease of movement (EoM, EMV)
It relate an asset's price change to its volume and is particularly useful
for assessing the strength of a trend.
https://en.wikipedia.org/wiki/Ease_of_movement
Args:
high(pandas.Series): da... | 37,506 |
def Document(docx=None, word_open_xml=None):
"""
Return a |Document| object loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object.
Optionally, ``word_open_xml`` can be specified as a string of xml.
Either ``docx`` or `word_open_xml`` may be specif... | 37,507 |
def save_raw_shots_as_txt(outdir, ds, wl_idx, chan, pump_idx):
"""Save each shot at a given wavelengths as a CSV.
"""
if not outdir.exists():
outdir.mkdir()
points, _, shots, wavelengths, _ = ds.shape
ts = core.time_axis(length=points)
tmp = np.empty((points, 3, shots, wavelengths, 2))
... | 37,508 |
def write_geogrid_var(path_dir,varname,array,index,bits=32,coord=None):
"""
write geogrid dataset and index
"""
path_dir=osp.abspath(path_dir)
logging.info('write_geogrid_var path_dir=%s varname=%s array=%s index=%s' % (path_dir, varname, inq(array), str(index)))
if not osp.exists(path_dir):
... | 37,509 |
def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
... | 37,510 |
def main(srcdir, destdir):
"""Main parser and generator function.
:param srcdir: directory holding source NeuroML Core Type XML files
:type srcdir: str
:param destdir: directory where generated files should be stored
:type destdir: str
:returns: nothing
"""
# If not defined or empty, ... | 37,511 |
def camelcase(path):
"""Applies mixedcase and capitalizes the first character"""
return mixedcase('_{0}'.format(path)) | 37,512 |
def ImproveData_v2 (Lidar_DataOld,Lidar_Data,Data_Safe,Speed,orientation,orientationm1):
"""
The function calculates new positions for obstacles now taking into account the car's relative speed in relation to each point. We need the accelerometer for that.
Return:
Advanced... | 37,513 |
def label_by_track(mask, label_table):
"""Label objects in mask with track ID
Args:
mask (numpy.ndarray): uint8 np array, output from main model.
label_table (pandas.DataFrame): track table.
Returns:
numpy.ndarray: uint8/16 dtype based on track count.
"""
assert mask.s... | 37,514 |
def load_guidata(filename, report):
"""Check if we have a GUI document."""
report({'INFO'}, "load guidata..")
guidata = None
zdoc = zipfile.ZipFile(filename)
if zdoc:
if "GuiDocument.xml" in zdoc.namelist():
gf = zdoc.open("GuiDocument.xml")
guidata = gf.read()
... | 37,515 |
def question_answers(id2line, convos):
""" Divide the dataset into two sets: questions and answers. """
questions, answers = [], []
for convo in convos:
for index, line in enumerate(convo[:-1]):
questions.append(id2line[convo[index]])
answers.append(id2line[convo[index + 1]])... | 37,516 |
def subgrid_kernel(kernel, subgrid_res, odd=False, num_iter=100):
"""
creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an
iterative approach
:param kernel: initial kernel
:param subgrid_res: subgrid resolution required
:return: kernel with... | 37,517 |
def get_spacy():
"""
Loads the spaCy english processor.
Tokenizing, Parsing, and NER are enabled. All other features are disabled.
Returns:
A spaCy Language object for English
"""
logging.info('Loading spaCy...')
import spacy.en
nlp = spacy.en.English(tagger=False, parser=True,... | 37,518 |
def exec_cmd(cmd_dict, cwd='../', domain_name=None):
"""Executing shell installing-app"""
key = cmd_dict.keys()[0]
val = cmd_dict[key]
cmd = "echo {desc} && {cmd}".format(desc=val, cmd=key) if val else key
p = subprocess.Popen(cmd, cwd=cwd, shell=True, stdout=None, stderr=None)
return_code = p.wait()
if return... | 37,519 |
def get_JDs(period='102', night=True, arrays=True, verbose=True):
"""
Get the Julian days for all ESPRESSO GTO runs in a given period. If
`night`=True, return the JD of sunset and sunrise. This function returns the
runs' start and end in arrays (lists if `arrays`=False).
"""
if night:
#... | 37,520 |
def my_mutate(chromo,maxVal):
"""
Input:
chromo: Chromosome
maxVal: Largest value +1 the chromosome can take
Output:
returns a sequence of Perceptually important point (PIP)
identification and the corresponding time values of size Q_length
"""
if (ran... | 37,521 |
def normalize_breton(breton_string: str) -> str:
"""Applies Breton mutations."""
return (breton_string.strip().lower() @
DO_PREPROCESSING @
DO_SOFT_MUTATION @
DO_HARD_MUTATION @
DO_SPIRANT_MUTATION @
DO_POSTPROCESSING).string() | 37,522 |
def load_mnist(raw=False):
"""Loads MNIST dataset from `DATA_PATH` or downloads it if necessary.
:param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1.
:type raw: `bool`
:return: `(x_train, y_train), (x_test, y_test), min, max`
:rtype: `(np.ndarray... | 37,523 |
def word_flag(*args):
"""
word_flag() -> flags_t
Get a flags_t representing a word.
"""
return _ida_bytes.word_flag(*args) | 37,524 |
def get_spark_config(predictrip_config: Mapping[str, Mapping[str, str]]) -> SparkConf:
"""
Create an object representing the Spark configuration we want
:type predictrip_config: mapping returned by load_config containing configuration options
:return: pyspark.SparkConf instance
"""
# NOTE: cont... | 37,525 |
def test_version():
"""Test version string."""
from counter_robots import __version__
assert __version__ | 37,526 |
def get_sequence_annotations(
sequence: str,
allow: Optional[set] = {"H", "K", "L"},
scheme: Optional[str] = "chothia",
cdr1_scheme: Optional[Dict[str, Iterable]] = {
"H": range(26, 33),
"L": range(24, 35),
},
cdr2_scheme: Optional[Dict[str, Iterable]] = {
"H": range(52, ... | 37,527 |
def skew(variable=None, weights=None, data=None):
"""Return the asymmetry coefficient of a sample.
Parameters
----------
data : pandas.DataFrame
variable : array-like, str
weights : array-like, str
data : pandas.DataFrame
Object which stores ``variable`` and ``weights``.
Return... | 37,528 |
def deep_initial_state(batch_size, h_size, stack_size):
""" Function to make a stack of inital state for a multi-layer GRU.
"""
return tuple(static_initial_state(batch_size, h_size) for layer in range(stack_size)) | 37,529 |
def create_element(pan_elem, elem_type=None)->Element:
"""
Find the element type and call constructor specified by it.
"""
etype = 'ELEMENT TYPE MISSING'
if elem_type is not None:
etype = elem_type
elif 't' in pan_elem:
etype = pan_elem['t']
elif 'pandoc-api-version' in pa... | 37,530 |
def load_weights(variables, file_name):
"""Reshapes and loads official pretrained Yolo weights.
Args:
variables: A list of tf.Variable to be assigned.
file_name: A name of a file containing weights.
Returns:
A list of assign operations.
"""
with open(file_name, "rb") as f:
... | 37,531 |
def parsing_sa_class_id_response(pdu: list) -> int:
"""Parsing TaiSEIA class ID response protocol data."""
packet = SAInfoResponsePacket.from_pdu(pdu=pdu)
if packet.service_id != SARegisterServiceIDEnum.READ_CLASS_ID:
raise ValueError(f'pdu service id invalid, {pdu}')
return int.from_bytes(packe... | 37,532 |
def wrr(self) -> int:
"""
Name: Write ROM port.
Function: The content of the accumulator is transferred to the ROM
output port of the previously selected ROM chip.
The data is available on the output pins until a new WRR
is execute... | 37,533 |
def clear_console():
""" Clear the console. POSIX refers to OSX/Linux. """
os.system('clear' if os.name == 'posix' else 'cls') | 37,534 |
def test_section_is_applied():
"""Test Section is_applied method."""
section_file = Section()
section_file.read = utils.mock_read(SECTION_STR)
assert section_file.is_applied(FILE_WITH_SECTION_STR)
assert not section_file.is_applied(FILE_WITHOUT_SECTION_STR) | 37,535 |
def info(message, **formatting):
"""
Return an info message to the command line
"""
click.secho(message, fg = 'blue', **formatting) | 37,536 |
def convert_to_signed_int_32_bit(hex_str):
"""
Utility function to convert a hex string into a 32 bit signed hex integer value
:param hex_str: hex String
:return: signed 32 bit integer
"""
val = int(hex_str, 16)
if val > 0x7FFFFFFF:
val = ((val+0x80000000) & 0xFFFFFFFF) - 0x80000000
... | 37,537 |
def parent_node(max_child_node, max_parent_node):
"""
Parents child node into parent node hierarchy
:param max_child_node: MaxPlus.INode
:param max_parent_node: MaxPlus.INode
"""
max_child_node.SetParent(max_parent_node)
return max_child_node | 37,538 |
def average_error2(func1, func2, k, n = 12, cycles = 10):
"""
Compares the path length calculated by func2 and func1. This assumes that func1 produces
the optimal path length and func2 is k_optimized_path.
n: number of nodes
cycles: how many times to generate a new set of nodes and run func1 an... | 37,539 |
def mem_naq():
"""
mem_naq()
Defined at ../src/mem_naq.f lines 198-449
"""
_min3p.f90wrap_mem_naq() | 37,540 |
def get_user():
"""从终端获取用户输入的QQ号及密码"""
username = input('please input QQ number: ').strip()
if not re.match(r'^[1-9][0-9]{4,9}$', username):
logging.error('\033[31mQQ number is wrong!\033[0m')
sys.exit(1)
import getpass
password = getpass.getpass('password: ')
return {
... | 37,541 |
def to_numpy_or_python_type(tensors):
"""Converts a structure of `Tensor`s to `NumPy` arrays or Python scalar types.
For each tensor, it calls `tensor.numpy()`. If the result is a scalar value,
it converts it to a Python type, such as a float or int, by calling
`result.item()`.
Numpy scalars are c... | 37,542 |
def _get_flow(args):
"""Ensure the same flow is used in hello world example and system test."""
return (
Flow(cors=True)
.add(uses=MyTransformer, replicas=args.replicas)
.add(uses=MyIndexer, workspace=args.workdir)
) | 37,543 |
def get_group_id(
client: AlgodClient,
txids: list
) -> list:
"""
Gets Group IDs from Transaction IDs
:param client: an AlgodClient (GET)
:param txids: Transaction IDs
:return: gids - Group IDs
"""
# Get Group IDs
gids = []
print("Getting gids...")
... | 37,544 |
def _simple_proc(st, sampling_rate=10, njobs=1):
"""
A parallel version of `_proc`, i.e., Basic processing including downsampling, detrend, and demean.
:param st: an obspy stream
:param sampling_rate: expected sampling rate
:param njobs: number of jobs or CPU to use
:return st: stream after pro... | 37,545 |
def closing_time(date=datetime.date.today()):
"""
Get closing time of the current date.
"""
return datetime.time(13, 0) if date in nyse_close_early_dates(date.year) else datetime.time(16, 0) | 37,546 |
def create_docker_network(network_name: str) -> None:
"""Create docker network.
For more details see
https://docs.docker.com/engine/reference/run/#network-settings
Args:
network_name (str): name of docker network.
"""
print("Creating docker network ...")
try:
args = ["dock... | 37,547 |
def test_read_datafiles_no_data_error(tmp_path):
"""Exit with error message after blank line found."""
os.chdir(tmp_path)
Path("foo").write_text("")
Path("bar").write_text("")
with pytest.raises(SystemExit):
read_datafiles() | 37,548 |
def begin_watch(server=SERVER, port=PORT, debug=False, username=None, password=None):
"""Begin watching the RFID scanner and camera for visitors.
If a person's face is found, it is saved as a file and then sent off
to the server to be validated. When debug is True, the camera
output is displayed on th... | 37,549 |
def get_distances(df):
"""Shows the edits between two postMessages."""
for _, row in df.loc[df["method"] == "gp_window_postMessage"].iterrows():
cases = [(row["value_cookies"], row["value_no_cookies"])]
for a, b in cases:
print('{} => {}'.format(a,b))
for i,s in en... | 37,550 |
def test_constants():
"""Test constants packaged with tfm"""
assert tfm.CROP_SIZE[0] == tfm.CROP_SIZE[1]
assert tfm.CROP_OVERLAP < tfm.CROP_SIZE[0]
assert tfm.DET_SIZE[0] == tfm.DET_SIZE[1]
assert tfm.CLF_SIZE[0] == tfm.CLF_SIZE[1]
assert len(tfm.OD_CLASSES) == 37
assert len(tfm.CLF_CLASSE... | 37,551 |
def cos_fp16(x: tf.Tensor) -> tf.Tensor:
"""Run cos(x) in FP16, first running mod(x, 2*pi) for range safety."""
if x.dtype == tf.float16:
return tf.cos(x)
x_16 = tf.cast(tf.mod(x, 2 * np.pi), tf.float16)
return tf.cos(x_16) | 37,552 |
def install():
"""
Call this function to install Mosketch for Maya
mosketch_for_maya.install()
"""
shelf_name = "MosketchForMaya"
# First get maya "official" shelves layout
top_level_shelf_layout = mel.eval("global string $gShelfTopLevel; $temp = $gShelfTopLevel;")
# Get all shelves... | 37,553 |
def new(**kwargs):
"""Host a new project in the framework"""
CMD.run(API, 'new', **kwargs) | 37,554 |
def test_convert_tweet_to_xy_generator():
""" test the generator function """
my_dict = {'text':
["red and yellow and pink and green, orange and purple and blue, I can sing a rainbow, sing a rainbow, sing a rainbow too",
"sweet dreams are made of this, who am I to disagree, trave... | 37,555 |
def deletePlayers():
"""Remove all the player records from the database."""
db = connect()
c = db.cursor()
c.execute('DELETE FROM players')
db.commit()
db.close() | 37,556 |
def is_documented_by(original: Callable) -> Callable[[_F], _F]:
"""
Decorator to set the docstring of the ``target`` function to that of the ``original`` function.
This may be useful for subclasses or wrappers that use the same arguments.
:param original:
"""
def wrapper(target: _F) -> _F:
document_object_fr... | 37,557 |
def check_if_bst(root, min, max):
"""Given a binary tree, check if it follows binary search tree property
To start off, run `check_if_bst(BT.root, -math.inf, math.inf)`"""
if root == None:
return True
if root.key < min or root.key >= max:
return False
return check_if_bst(root.left,... | 37,558 |
def assert_widget_image(tmpdir, widget, filename, fail_now=True):
"""
Render an image from the given WWT widget and assert that it matches an
expected version. The expected version might vary depending on the platform
and/or OpenGL renderer, so we allow for multiple references and just check
if *any... | 37,559 |
def create_video_file(
root: Union[pathlib.Path, str],
name: Union[pathlib.Path, str],
size: Union[Sequence[int], int] = (1, 3, 10, 10),
fps: float = 25,
**kwargs: Any,
) -> pathlib.Path:
"""Create an video file from random data.
Args:
root (Union[str, pathlib.Path]): Root directory... | 37,560 |
def dump(input, variable, encoding):
"""
Dump contents of an input dataset.
"""
from xcube.api import open_dataset, dump_dataset
with open_dataset(input) as ds:
text = dump_dataset(ds, var_names=variable, show_var_encoding=encoding)
print(text) | 37,561 |
def test045_compress_with_extra_files():
"""TC435
Test case for compressing files with extra files.
**Test scenario**
#. Create two tree with some files and directories.
#. Compress the first tree with extrafiles using the second tree.
#. Uncompress this output file.
#. Check that second tr... | 37,562 |
def aggregate(collection, pipeline):
"""Executes an aggregation on a collection.
Args:
collection: a `pymongo.collection.Collection` or
`motor.motor_tornado.MotorCollection`
pipeline: a MongoDB aggregation pipeline
Returns:
a `pymongo.command_cursor.CommandCursor` or
... | 37,563 |
def decryptAES(key, data, mode=2):
"""decrypt data with aes key"""
return aes.decryptData(key, data, mode) | 37,564 |
def __ipv6_safe_get(endpoint: str, addr: str) -> str:
"""HTTP GET from endpoint with IPv6-safe Host: header
Args:
endpoint: The endpoint path starting with /
addr: full address (IPV6 or IPv4) of server
Notes:
* This is needed because the Pyton requests modul... | 37,565 |
def generateModels(y0, yN, yearsInModel, stepYears, modelFolder):
"""Generate time shifting w2v models on the given time range (y0 - yN).
Each model contains the specified number of years (yearsInModel). The start
year of each new model is set to be stepYears after the previous model.
Resulting models a... | 37,566 |
def test_count_days_method_returns_dict():
"""Test the count days method returns a dictionary."""
jd = JobData('test')
assert isinstance(jd.count_days(), dict) | 37,567 |
def format_advertisement(data):
""" format advertisement data and scan response data. """
resolve_dict = {
# FLAGS AD type
st_constant.AD_TYPE_FLAGS: 'FLAGS',
# Service UUID AD types
st_constant.AD_TYPE_16_BIT_SERV_UUID: '16_BIT_SERV_UUID',
st_constant.AD_TYPE_16_BIT_SERV... | 37,568 |
def main():
"""Handle command-line interface."""
from docopt import docopt
arguments = docopt(__doc__)
if sys.stdout.encoding is None:
encoding = 'utf-8'
else:
encoding = sys.stdout.encoding
runeberg = Runeberg()
if arguments['download-catalogue']:
runeberg.downloa... | 37,569 |
def is_dicom_file(path):
"""Check if the given path appears to be a dicom file.
Only looks at the extension, not the contents.
Args:
path (str): The path to the dicom file
Returns:
bool: True if the file appears to be a dicom file
"""
path = path.lower()
for ext in DICOM_E... | 37,570 |
def iter_weather(city='Washington',state='DC'):
"""Returns an iterator giving weather for today, tomorrow, and the
day after"""
weather = miniweather.getweather(city=city,state=state)
for i in weather.keys():
yield weather[i] | 37,571 |
def check_if_in_interval(interval, value, in_par, name):
""" Checks if the value is within the interval
:param interval: The interval of input parameter in_par
:param value: The value of input parameter in_par
:param in_par: The value of the input parameter
:param name: The na... | 37,572 |
def print_each(text):
"""
Prints each character of text on a line by itself
Example: print_each('abc') displays
a
b
c
Parameter text: The string to split up
Precondition: text is a string
"""
x = text[0]
print(x)
x = test[1]
print(x)
…
x = text[l... | 37,573 |
def build_graph(df_list, sens='ST', top=410, min_sens=0.01,
edge_cutoff=0.0, edge_width=150, log=False):
"""
Initializes and constructs a graph where vertices are the parameters
selected from the first dataframe in 'df_list', subject to the
constraints set by 'sens', 'top', and 'min_sens... | 37,574 |
def inc_dict_values_from_file(path):
"""Reads a dict with numbers as values from file, increments the values,
and writes the updated dict back to the same file, overriding the
original one.
Parameters
----------
path : str
Path to file, including filename.
"""
data = read_json(path)
inc_dict_valu... | 37,575 |
def test_ground_truth_loader_filter_with_parameter_overrides(mock_data: dict):
"""Test the parameter_override input functionality"""
mock_data[GroundTruthLoaderFilter.KEY_PARAMETER_OVERRIDE] = {
"lambda_blood_brain": 3.1,
"a_new_parameter": 1,
}
gt_filter = GroundTruthLoaderFilter()
... | 37,576 |
def ranking_scores(prng=None, mix=False, permute=False, gamma=0.01, beta=5., N=100, l=1, means=None, stds=None):
"""
Generate the ranking scores.
Parameters
----------
prng : random generator container
Seed for the random number generator.
mix : bool
... | 37,577 |
def calculate_direction(G, cutoff, normalize=True):
""" Calculate direction for entire network
Parameters
----------
G : nx.graph
Fault network
cutoff : int, float
Cutoff distance for direction
normalize : bolean
Normalize direction (default: True)
... | 37,578 |
def generateVtBar(row):
"""生成K线"""
bar = VtBarData()
bar.symbol = row['code']
bar.exchange = ''
bar.vtSymbol = bar.symbol
bar.open = row['open']
bar.high = row['high']
bar.low = row['low']
bar.close = row['close']
bar.volume = row['volume']
bar.datetime = datetime.strpti... | 37,579 |
def test_validate_experiment_requests(exp_request, expected_result):
"""Tests that validate_experiment_requests returns True for valid fuzzres
and False for invalid ones."""
assert (automatic_run_experiment.validate_experiment_requests([exp_request])
is expected_result) | 37,580 |
async def is_valid_channel(ctx, channel_name):
"""
TODO: Use discord.py converters instead of is_valid_channel check
"""
matched_channels = [
channel for channel in ctx.guild.channels if channel.name == channel_name
]
if len(matched_channels) == 0:
await ctx.send(
"Ca... | 37,581 |
def coords_to_id(traversed):
"""calculate the id in level-order from the coordinates
Args:
input: traversed tree as list of dict
Returns:
traversed tree (dict) with id as key
"""
traversed_id = {}
#print('coords to id, traversed ', traversed)
for node in traversed:
... | 37,582 |
def dataframe_to_ipy_image(df, f=None, **kwargs):
"""Create IPython Image from PIL Image.
Args:
df - dataframe to render
f - operation to perform on PIL Image (e.g. f=lambda img: img.rotate(-90, expand=True))
kwargs - arguments to IPython.display.Image, such as width and height for html display
... | 37,583 |
def get_yaml_file_info(file_name):
"""Loads a yaml file into a dictionary
Args:
file_name (str): The file to load
Returns:
Raises:
ProgramError
"""
if not os.path.isfile(file_name):
print("Cannot find file %s" % file_name)
raise ProgramError(1)
with open(fi... | 37,584 |
def cleanup():
"""
Cleans up existing terminals before exit.
"""
tmp = copy.copy(manager.term_pool)
for term in tmp:
manager.terminate(term.id) | 37,585 |
def read_dmarkov(columns, rows, D, symbolization_type, division_order, suffix=["normal", "gaussian002"]):
"""
Reads the result files for the D-Markov algorithm. The function requires a configuration for the parameters of
the D-Markov. The suffix parameter indicates if the non-modified files should be loaded... | 37,586 |
def compute_output_shape(observation_space, layers):
"""Compute the size of the output after passing an observation from
`observation_space` through the given `layers`."""
# [None] adds a batch dimension to the random observation
torch_obs = torch.tensor(observation_space.sample()[None])
with torch.... | 37,587 |
def tenure_type():
""" RESTful CRUD controller """
return s3_rest_controller(#rheader = s3db.stdm_rheader,
) | 37,588 |
def _format_port(port):
"""
compute the right port type str
Arguments
-------
port: input/output port object
Returns
-------
list
a list of ports with name and type
"""
all_ports = []
for key in port:
one_port = {}
one_port['name'] = key
port... | 37,589 |
def account_deleted(sender, instance, **kwargs):
"""Remove document."""
delete_credentials(instance) | 37,590 |
def getTileName(minfo,ti,xIndex,yIndex,level = -1):
"""
creates the tile file name
"""
global LastRowIndx
max = ti.countTilesX
if (ti.countTilesY > max):
max=ti.countTilesY
countDigits= len(str(max))
parts=os.path.splitext(os.path.basename(minfo.filename))
if parts[0][0]=="@... | 37,591 |
def proc_cgroups(proc='self'):
"""Read a process' cgroups
:returns:
``dict`` - Dictionary of all the process' subsystem and cgroups.
"""
assert isinstance(proc, int) or '/' not in proc
cgroups = {}
with io.open(_PROC_CGROUP.format(proc), 'r') as f:
for cgroup_line in f:
... | 37,592 |
def load_csv_data(
data_file_name,
*,
data_module=DATA_MODULE,
descr_file_name=None,
descr_module=DESCR_MODULE,
):
"""Loads `data_file_name` from `data_module with `importlib.resources`.
Parameters
----------
data_file_name : str
Name of csv file to be loaded from `data_modu... | 37,593 |
def ptFromSudakov(sudakovValue):
"""Returns the pt value that solves the relation
Sudakov = sudakovValue (for 0 < sudakovValue < 1)
"""
norm = (2*CA/pi)
# r = Sudakov = exp(-alphas * norm * L^2)
# --> log(r) = -alphas * norm * L^2
# --> L^2 = log(r)/(-alphas*norm)
L2 = log(sudakovVal... | 37,594 |
def _set_lod_2(gml_bldg, length, width, height, bldg_center):
"""Adds a LOD 2 representation of the building based on building length,
width and height
alternative way to handle building position
Parameters
----------
gml_bldg : bldg.Building() object
A building object, where bldg is ... | 37,595 |
def load_data(filename: str):
"""
Load Agoda booking cancellation dataset
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector in either of the following formats:
1) Single dataframe with last column representing ... | 37,596 |
def send_mail(subject, message, from_email, recipient_list, html_message='',
scheduled_time=None, headers=None, priority=PRIORITY.medium):
"""
Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method.
"""
subject = force_text(subject)
... | 37,597 |
def proxy_a_distance(source_X, target_X):
"""
Compute the Proxy-A-Distance of a source/target representation
"""
nb_source = np.shape(source_X)[0]
nb_target = np.shape(target_X)[0]
train_X = np.vstack((source_X, target_X))
train_Y = np.hstack((np.zeros(nb_source, dtype=int), np.ones(nb_targe... | 37,598 |
def load_metadata(stock_model_name="BlackScholes", time_id=None):
"""
load the metadata of a dataset specified by its name and id
:return: dict (with hyperparams of the dataset)
"""
time_id = _get_time_id(stock_model_name=stock_model_name, time_id=time_id)
path = '{}{}-{}/'.format(training_data_... | 37,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.