content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_distributed_mean(value: Union[float, torch.Tensor]):
"""Computes distributed mean among all nodes."""
if check_torch_distributed_initialized():
# Fix for runtime warning:
# To copy construct from a tensor, it is recommended to use
# sourceTensor.clone().detach() or
# sour... | 5,335,900 |
def js_div(A, B):
""" Jensen-Shannon divergence between two discrete probability
distributions, represented as numpy vectors """
norm_A = A / A.sum()
norm_B = B / B.sum()
M = (norm_A+norm_B)/2
return 0.5 * (kl_div(norm_A,M)+kl_div(norm_B,M)) | 5,335,901 |
def test_outputs():
"""
testing correct functionality and outputs of function
"""
df = pd.DataFrame({'x': [1, 2, 11, 22, 7], 'y': [100, 110, 120, 130, 140]})
out1 = pythcat.suscat(df, [0, 1], n=80)
out2 = pythcat.suscat(df, [0], num='number', n=2)
assert isinstance(out1, dict)
assert ... | 5,335,902 |
def _fixTimeStrings(scModel, gopLoader):
"""
USed to correct the use of the third ':' which indicated frames since time.
This caused confusion. Users often used the the third ':' for milliseconds.
The journals are of course incorrect. Cannot fix that here.
:param scModel:
:param gopLoader:
... | 5,335,903 |
def test_getextensible():
"""py.test for getextensible"""
data = (
([{u'format': [u'singleLine'],
u'group': u'Simulation Parameters',
u'idfobj': u'Version',
u'memo': [u'Specifies the EnergyPlus version of the IDF file.'],
u'unique-object': [u'']}, {}, {}, {}
],
None), # objidd, expected
([{u'... | 5,335,904 |
def run_collector(db_host, db_port, db_name,
watcher_cls, watcher_kwargs, updater_cls, updater_kwargs,
num_updaters=1):
""" Run up instances of the watcher and updaters with the configured watcher and updaters.
"""
num_updaters = int(num_updaters)
log.info("Starting {... | 5,335,905 |
def _build_request_url(
base: str,
params_dict: Dict[str, str]) -> str:
"""Returns an URL combined from base and parameters
:param base: base url
:type base: str
:param params_dict: dictionary of parameter names and values
:type params_dict: Dict[str, str]
:return: a complete ... | 5,335,906 |
def test_is_ten_prime():
"""Is five successfully determined to be prime?"""
assert not is_prime(10) | 5,335,907 |
def add_DX(self, timeperiod=14, type="line", color="secondary", **kwargs):
"""Directional Movement Index."""
if not (self.has_high and self.has_low and self.has_close):
raise Exception()
utils.kwargs_check(kwargs, VALID_TA_KWARGS)
if "kind" in kwargs:
type = kwargs["kind"]
name = ... | 5,335,908 |
def aesDecrypt(key, data):
"""AES decryption fucnction
Args:
key (str): packed 128 bit key
data (str): packed encrypted data
Returns:
Packed decrypted data string
"""
cipher = python_AES.new(key)
return cipher.decrypt(data) | 5,335,909 |
def store_preparation_emails(recipients, daylist, jokes):
"""
Takes a message, a list of recipients and a list of datetimes to store
emails including a timestamp as basis of a scheduled mail sender.
If number of days is greater than number of jokes, I don't want to spam
my collegues with duplicate j... | 5,335,910 |
def __format_number_input(number_input, language):
"""Formats the specified number input.
Args:
number_input (dict): A number input configuration to format.
language (dict): A language configuration used to help format the input configuration.
Returns:
dict: A formatted number inpu... | 5,335,911 |
def get_players(picks):
"""Return the list of players in the team
"""
players = []
for rd in picks:
play = list(rd.keys())
players = players+play
players = list(set(players))
return players | 5,335,912 |
def verify_file_details_exists(device,
root_path,
file,
max_time=30,
check_interval=10):
""" Verify file details exists
Args:
device ('obj'): Device object
roo... | 5,335,913 |
def generateVoID(g, dataset=None, res=None, distinctForPartitions=True):
"""
Returns a new graph with a VoID description of the passed dataset
For more info on Vocabulary of Interlinked Datasets (VoID), see:
http://vocab.deri.ie/void
This only makes two passes through the triples (once to detect t... | 5,335,914 |
def add(filename, destination, number, time):
"""
Запросить данные о маршруте.
"""
if os.path.exists(filename):
routes = load_routes(filename)
else:
routes = []
routes.append(
{
'destination': destination,
'number': number,
'time': tim... | 5,335,915 |
def extract_screen_name_from_twitter_url(url):
"""
Function returning the screen_name from a given Twitter url.
Args:
url (str) : Url from which we extract the screen_name if found.
Returns:
str : screen_name if the url is a valid twitter url, None otherwise.
"""
parsed_twitt... | 5,335,916 |
def sub_vectors(a, b):
"""Subtracts two vectors.
Args:
pos1 (tuple[int]): first position
pos1:(tuple[int]): second position
Returns:
tuple[int]: element wise subtraction
Examples:
>>> sub_vectors((1,4,6), (1,3,7))
(0, 1, -1)
"""
return tuple(a[i] - b[i]... | 5,335,917 |
def infer_on_stream(args, client):
"""
Initialize the inference network, stream video to network,
and output stats and video.
:param args: Command line arguments parsed by `build_argparser()`
:param client: MQTT client
:return: None
"""
# Initialize the Inference Engine
infer_networ... | 5,335,918 |
def get_prediction_info(predicted_one_hot, predicted_int, y_test, PLOTS_DIR, filename = "test_file"):
"""
Saves useful information for error analysis in plots directory
:param predicted_one_hot:
:param predicted_int:
:param y_test:
:param PLOTS_DIR:
:return:
"""
def get_info_for_labe... | 5,335,919 |
def save_excel_file():
"""File save dialog for an excel file.
Returns:
str: file path
"""
return pick_excel_file(save=True) | 5,335,920 |
def load_app_paths(file_path=None, dir_path=None, user_file_path=None,
user_dir_path=None, default=None, paths=None, **kwargs):
"""Parse and merge user and app config files
User config will have precedence
:param file_path: Path to the base config file
:param dir_path: Path to the e... | 5,335,921 |
def search_playlists(spotify_token, playlist):
"""
:param spotify_token:
:param playlist:
:return:
"""
return _search(spotify_token, query=playlist, type='playlist', limit=9, market='ES', offset=0) | 5,335,922 |
def text_pre_process(result):
""" 이미지에서 인식된 글자를 정제 합니다.
특수문자 제거, 1-2단어 제거, 줄바꿈 및 공백 제거
:param result: 이미지에서 인식된 글자
:return: 문자를 전처리한 결과
"""
copy = str(result)
copy2 = copy.replace("\n", "")
copy3 = re.sub('[^ㄱ-힗]', '', copy2)
# re.sub('[^A-Za-z0-9]', '', copy2)
result = re.sub('[-=+,#}/\{:^$.@*\※~&%ㆍ!『「』\... | 5,335,923 |
def test_invalid_index(trimatrix):
"""Test various invalid indices."""
# Too many
with pytest.raises(ValueError):
trimatrix[:, :, :]
# Float scalar
with pytest.raises(TypeError):
trimatrix[0.5]
# Float array
with pytest.raises(ValueError):
trimatrix[np.linspace(0, 10)] | 5,335,924 |
def pandas_data_get():
"""pandas api进行值的获取"""
df2 = pd.DataFrame({
'A': 1.,
# series对象作为一列
'B': pd.Series(1, index=list(range(4)), dtype='float32'),
'C': np.array([3] * 4, dtype='int32'),
'd': pd.Timestamp('20130102'),
# 单值也会与其他列长度保持一致
'F': 'foo',
... | 5,335,925 |
def push_thread_callback(app: Flask):
"""Process outstanding MDM commands by issuing a push to device(s).
TODO: A push with no response needs an exponential backoff time.
Commands that are ready to send must satisfy these criteria:
- Command is in Queued state.
- Command.after is null.
- Comm... | 5,335,926 |
def get_conventional_std_cell(atoms):
"""Given an ASE atoms object, return the ASE atoms object in the conventional standard cell.
It uses symmetries to find the conventional standard cell.
In particular, it gives a structure with a conventional cell according to the standard defined in
W. Setyawan, an... | 5,335,927 |
def close_ind_lst(ind_lst):
"""
Closes index objects supplied in input parameter list
"""
for index in ind_lst:
index.close() | 5,335,928 |
def get_if_rcnn(inputs: Tensor):
"""
:param inputs: Tensor from Input Layer
:return:
"""
# get back bone outputs
if_backbones_out = backbones(inputs)
return if_backbones_out | 5,335,929 |
def method_3(num_chars: int):
"""
Pythonicish way of generating random password
Args:
num_chars (int): Number of Characters the password will be
Returns:
string: The generated password
"""
chars = string.ascii_letters + string.digits + string.punctuation
password = "".join(... | 5,335,930 |
def get_animation_for_block(
block_start: int,
frame_num: int,
total_frames: int,
duration: int=5,
):
"""Generate CSS to pop a block from gray to red at the right frame
block_start: int
frame_num: int
total_frames: int
duration: int # seconds"""
animation_function = gray_... | 5,335,931 |
def get_all_pokemon_stats():
"""
Get all the pokemon and their stats by an API call.
"""
database_handler = DatabaseAPIHandler()
# There are 807 pokemon callable in the API.
for pokemon_number in range(1, 808):
pokemon_status_data = database_handler.get_pokemon_status_data(pokemon_numb... | 5,335,932 |
def find_student_by_username(usuario_id, test=False):
"""Consulta toda la información de un estudiante según su usuario."""
query = 'SELECT * FROM estudiante WHERE id_usuario = %s'
return execute_sql(query, args=[usuario_id], rows=1, test=test) | 5,335,933 |
def download_rt_files(dst_dir, fs=None, date="2021-08-01", glob_path=None):
"""Download all files for an GTFS RT feed (or multiple feeds)
If date is specified, downloads daily data for all feeds. Otherwise, if
glob_path is specified, downloads data for a single feed.
Parameters:
date: date of ... | 5,335,934 |
def reduce_mem_usage(df, use_float16=False):
"""
Iterate through all the columns of a dataframe and modify the data type to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024 ** 2
print("Memory usage of dataframe is {:.2f} MB".format(start_mem))
for col in df.columns:
... | 5,335,935 |
def ParseCommandYAML():
"""Function for parsing command line arguments for input to YAML HDIprep"""
# if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--im", nargs='*')
parser.add_argument("--pars")
parser.add_argument("--out_dir")
args = parser.parse_args(... | 5,335,936 |
def silence_flask_startup() -> None:
# pylint: disable=line-too-long
"""Calling this function monkey patches the function flask.cli.show_server_banner
(https://github.com/pallets/flask/blob/a3f07829ca03bf312b12b3732e917498299fa82d/src/flask/cli.py#L657-L683)
which by default outputs something like:
... | 5,335,937 |
def creature_ability_093(field, player, opponent, virtual, target, itself):
"""
Last Words: Give Ward to a random allied follower.
"""
length = len(field.get_creature_location()[player.player_num])
if length > 0:
target_id = random.randint(0, length - 1)
target_creature = field.card_... | 5,335,938 |
def cat_files(src, dst, no_redundant_header=False, is_header_f=return_false):
"""Concatenate files in src and save to dst.
src --- source file names in a list
dst --- destinate file name
no_redundant_header --- Only keep headers in the 1st file, skip others.
is_header_f --- return True i... | 5,335,939 |
def create_global_step() -> tf.Variable:
"""Creates a `tf.Variable` suitable for use as a global step counter.
Creating and managing a global step variable may be necessary for
`AbstractTrainer` subclasses that perform multiple parameter updates per
`Controller` "step", or use different optimizers on different... | 5,335,940 |
def convert_part_merging(argstuple):
"""
Convert a corpus part into plain text and merging multiple word entries.
Args:
argstuple: Tuple of methods arguments (``inpath`` (*str*): Path to this processes' corpus part / ``dir_outpath``
(*str*): Path to this processes' output / ``log_path`` (*str*): Path to this... | 5,335,941 |
def rl_label_weights(name=None):
"""Returns the weight for importance."""
with tf.variable_scope(name, 'rl_op_selection'):
num_classes = get_src_num_classes()
num_choices = FLAGS.num_choices
logits = tf.get_variable(
name='logits_rl_w',
initializer=tf.initializers.zeros(),
shape... | 5,335,942 |
def run_de_test(dataset1: Dataset, dataset2,
test_cells: List[str], control_cells: List[List[str]],
test_label: str = None, control_group_labels: list = None,
exp_frac_thresh: float = 0.25, log2_fc_thresh: float = 1,
qval_thresh: float = 0.05, tqdm_msg: s... | 5,335,943 |
def say_hello_twice(subject):
"""Says hello twice using `say_hello`."""
return say_hello(subject) + " " + say_hello(subject) | 5,335,944 |
def get_zones(ec2):
"""
Return all available zones in the region
"""
zones = []
try:
aws_zones = ec2.describe_availability_zones()['AvailabilityZones']
except ClientError as e:
print(e.response['Error']['Message'])
return None
for zone in aws_zones:
if zone['State'] == 'available':
... | 5,335,945 |
def main():
"""Main function"""
parser = argparse.ArgumentParser()
parser.add_argument('-Dir', type=str)
opt = parser.parse_args()
Dataset(opt) | 5,335,946 |
def x_gate():
"""
Pauli x
"""
return torch.tensor([[0, 1], [1, 0]]) + 0j | 5,335,947 |
def merge_dictionaries(default_dictionary, user_input_dictionary, path=None):
"""Merges user_input_dictionary into default dictionary;
default values will be overwritten by users input."""
return {**default_dictionary, **user_input_dictionary} | 5,335,948 |
def create_frequencyvector(T_end, f_max_requested):
""" A function to create the vector of frequencies we need to solve using the reflectivity
method, to achieve the desired length of time and highest modelled frequency.
NOTE: Because we require the number of frequencies to be odd, the maximum frequency may... | 5,335,949 |
def get_fiber_protein_intake(
nutrients_lower_lists, nutrients_middle_lists,nutrients_upper_lists):
"""Gets financial class-wise fibee and protein intake data."""
lower_fiber_prot = nutrients_lower_lists.map(lambda x: (x[1], x[3]))
middle_fiber_prot = nutrients_middle_lists.map(lambda x: (x[1], x[3... | 5,335,950 |
def _add_fvar(font, axes, instances, axis_map):
"""
Add 'fvar' table to font.
axes is a dictionary mapping axis-id to axis (min,default,max)
coordinate values.
instances is list of dictionary objects with 'location', 'stylename',
and possibly 'postscriptfontname' entries.
axisMap is dictionary mapping axis-id... | 5,335,951 |
def init_nornir(username, password):
"""INITIALIZES NORNIR SESSIONS"""
nr = InitNornir(
config_file="network_automation/topology_builder/graphviz/config/config.yml"
)
nr.inventory.defaults.username = username
nr.inventory.defaults.password = password
managed_devs = nr.filter(F(groups__c... | 5,335,952 |
def _format_rest_url(host: str, append: str = "") -> str:
"""Return URL used for rest commands."""
return f"http://{host}:8001/api/v2/{append}" | 5,335,953 |
def create(config, directory):
"""Add evaluation files to client storage"""
for path in directory.iterdir():
upload(config['name'], path)
# Add listening test files to client storage
if 'listening_test' in config:
upload(config['name'], reseval.LISTENING_TEST_DIRECTORY) | 5,335,954 |
def load(name: str,
device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu",
jit: bool = False,
download_root: str = None):
"""Load a CLIP model
Parameters
----------
name : str
A model name listed by `clip.available_models()`, or the path to a ... | 5,335,955 |
def show_components(im, comps, npixels=128, fig=None, vmax=None, vmin=None, title=''):
""" Show components against an image
:param im:
:param comps:
:param npixels:
:param fig:
:return:
"""
import matplotlib.pyplot as plt
if vmax is None:
vmax = numpy.max(im.data[0, 0, ... | 5,335,956 |
def add_h(mol: oechem.OEMol):
"""Add explicit hydrogens to a molecule"""
for atom in mol.GetAtoms():
oechem.OEAddExplicitHydrogens(mol, atom) | 5,335,957 |
def test_provision_no_vmx():
"""Test provisioning."""
mock_inst = MagicMock()
mock_inst.vmx = None
mock_inst.provider = 'vmware'
with raises(SystemExit, match=r"Need to provide vmx.*"):
mech.utils.provision(instance=mock_inst, show=None) | 5,335,958 |
def _handle_sample(edf, res):
"""SAMPLE_TYPE"""
e = edf_get_sample_data(edf).contents
off = res['offsets']['sample']
res['samples'][:, off] = _to_list(e, res['edf_sample_fields'],
res['eye_idx'])
res['offsets']['sample'] += 1 | 5,335,959 |
def get_synonyms(prefix: str) -> Optional[Set[str]]:
"""Get the synonyms for a given prefix, if available."""
entry = get_resource(prefix)
if entry is None:
return None
return entry.get_synonyms() | 5,335,960 |
def results(request):
""" Returns the actual body of the search results, for AJAX stuff """
query = request.GET.get("q", "")
if len(query) >= 4:
ctx = _search_context(query, request.user)
return TemplateResponse(request, "search/results.html", ctx)
return TemplateResp... | 5,335,961 |
def is_correlated(corr_matrix, feature_pairs, rho_threshold=0.8):
"""
Returns dict where the key are the feature pairs and the items
are booleans of whether the pair is linearly correlated above the
given threshold.
"""
results = {}
for pair in feature_pairs:
f1, f2 = pair.split("__"... | 5,335,962 |
def find_password(liste, login):
""" """
for user in liste:
if user[0] == login:
return user[1]
return None | 5,335,963 |
def sample_weather_scenario():
"""
Generate a weather scenario with known values for the wind condition.
"""
times = pd.date_range('1/1/2000', periods=72, freq='6H')
latitude = np.linspace(0, 10, 11)
longitude = np.linspace(0, 10, 11)
wsp_vals = np.full((72, 11, 11), 10.0)
wdi_vals = np.... | 5,335,964 |
def parse_csv_file(csv_filepath, expect_negative_correlation = False, STDev_cutoff = 1.0, headers_start_with = 'ID', comments_start_with = None, separator = ','):
"""
Analyzes a CSV file.
Expects a CSV file with a header line starting with headers_start_with e.g. "ID,experimental value, prediction 1 value, ... | 5,335,965 |
def ToTensor(pic):
"""Converts a PIL.Image or numpy.ndarray (H x W x C) in the range
[0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
"""
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img.float().div(255)
if pic.mode == "I":
img = t... | 5,335,966 |
def test_get_url_content_compressed(request):
"""should automatically decompress compressed URL content"""
url = 'https://www.bible.com/bible/59/psa.23'
gzip_buf = StringIO()
with GzipFile(fileobj=gzip_buf, mode='wb') as gzip_file:
gzip_file.write(html_content)
gzipped_content = gzip_buf.get... | 5,335,967 |
def part2(data):
"""
>>> part2([[43, 19], [2, 29, 14]])
105
>>> part2([[9, 2, 6, 3, 1], [5, 8, 4, 7, 10]])
291
>>> part2(read_input())
32528
"""
deck_one = tuple(data[0])
deck_two = tuple(data[1])
_, winning_deck = combat(deck_one, deck_two)
return score(winning_deck) | 5,335,968 |
def write_traces(directory, traces):
"""
Write traces locally to files
"""
for trace in traces:
traceid = trace["traceID"]
path = directory + "/" + traceid + ".json"
with open(path, 'w') as fd:
fd.write(json.dumps(trace)) | 5,335,969 |
def validate_recording(
ai_file_path, ephys_ap_data_path, debug=False, sampling_rate=30000
):
"""
Checks that an ephys recording and bonsai behavior recording
are correctly syncd. To do this:
1. check that number of recording sync signal pulses is the same for both sources
Argum... | 5,335,970 |
def manual(no_usb_hardware):
"""
Starts the manual mode application
"""
if no_usb_hardware:
print("Running in test mode with no USB hardware attached.")
options = {'hardware': "false"}
else:
print("USB hardware attached!")
options = {'hardware': "true"}
_roslaunch... | 5,335,971 |
def dehyphenate(string):
"""Remove hyphenated linebreaks from 'string'."""
return hyphen_newline_re.sub("", string) | 5,335,972 |
def grounder(img, dtype=None):
"""Tries to remove absolute offset
'img' must be a 3 colors image"""
shape = img.shape
"""
# Mise en forme
a = img.reshape((shape[0] * shape[1], 3))
min = np.zeros(a.shape)
max = np.zeros(a.shape)
# Minimas/maximas
min[:,0] = min[:,1] = min[:,2] =... | 5,335,973 |
def create_folders(path):
""" recursively create folders """
if not os.path.isdir(path):
while True:
try:
os.makedirs(path)
except:
pass
time.sleep(1)
else:
break | 5,335,974 |
def arch_prob(arch, dims, **kwds):
""" Returns the combined probability of for arch given values """
values = dict(kwds)
dimkeys = list(dims.keys())
assert isinstance(arch, (tuple, list)), "Archictecture must be tuple or list"
serial = isinstance(arch, list)
probs = [None] * len(arch)
for i, subarch in ... | 5,335,975 |
def test_has_permission_no_subscription(
api_rf, enable_premium_requirement, method, entry_factory
):
"""
If the owner of the journal entry does not have an active premium
subscription, a 404 error should be raised.
"""
entry = entry_factory(km_user__user__has_premium=False)
api_rf.user = e... | 5,335,976 |
def get_bin_values(base_dataset, bin_value):
"""Gets the values to be used when sorting into bins for the given dataset, from the configured options."""
values = None
if bin_value == "results":
values = base_dataset.get_output()
elif bin_value == "all":
# We set all values to 0, assuming... | 5,335,977 |
def scan(
ws_spec: io.TextIOWrapper,
par_name: str,
lower_bound: Optional[float],
upper_bound: Optional[float],
n_steps: int,
asimov: bool,
figfolder: str,
) -> None:
"""Performs and visualizes a likelihood scan over a parameter.
Parameter bounds are determined automatically, unless... | 5,335,978 |
def get_reviews(revision_range):
"""Returns the list of reviews found in the commits in the revision range.
"""
log = check_output(['git',
'--no-pager',
'log',
'--no-color',
'--reverse',
r... | 5,335,979 |
def send_mail(sender_email, receiver_email, password, message):
"""
TODO: documentation
"""
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
# Create a secure SSL context
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) a... | 5,335,980 |
def get_lines(filename: str) -> Generator[str, None, None]:
"""
Yield each line of the given .bz2 compressed log file
"""
with bz2.open(filename, 'rb') as fh:
for line_bytes in fh:
line = line_bytes.decode('utf-8', 'backslashreplace')
line = line.rstrip('\r\n')
... | 5,335,981 |
def create_cert_req(keyType=crypto.TYPE_RSA,
bits=1024,
messageDigest="md5"):
"""
Create certificate request.
Returns: certificate request PEM text, private key PEM text
"""
# Create certificate request
req = crypto.X509Req()
# Generate private key
... | 5,335,982 |
def large_xyz_to_lab_star(large_xyz, white=const_d50_large_xyz):
"""
# 概要
L*a*b* から XYZ値を算出する
# 入力データ
numpy形式。shape = (N, M, 3)
# 参考
https://en.wikipedia.org/wiki/Lab_color_space
"""
if not common.is_img_shape(large_xyz):
raise TypeError('large_xyz shape must be (N, M, 3)')
... | 5,335,983 |
def saveData(datalist,savepath):
"""
创建excel表格并将爬取到的数据写入excel
:param datalist:爬取到的数据的列表
:param savepath: 保存数据的excel表格的路径
:return:
"""
logger.info("开始保存书籍信息...")
workbook = xlwt.Workbook(encoding="utf-8") #创建workbook
worksheet = workbook.add_sheet('微信读书Top20',cell_overwrite_... | 5,335,984 |
def return_value(value: Any) -> ObservableBase:
"""Returns an observable sequence that contains a single element,
using the specified scheduler to send out observer messages.
There is an alias called 'just'.
example
res = rx.Observable.return(42)
res = rx.Observable.return(42, rx.Scheduler.time... | 5,335,985 |
def compare_policies(current_policy, new_policy):
""" Compares the existing policy and the updated policy
Returns True if there is a difference between policies.
"""
return set(_hashable_policy(new_policy, [])) != set(_hashable_policy(current_policy, [])) | 5,335,986 |
def meanPSD(d0,win=np.hanning,dx=1.,axis=0,irregular=False,returnInd=False,minpx=10):
"""Return the 1D PSD averaged over a surface.
Axis indicates the axis over which to FFT
If irregular is True, each slice will be stripped
and then the power spectra
interpolated to common frequency grid
Presume... | 5,335,987 |
async def get_temperatures(obj):
"""Get temperatures as read by the thermostat."""
return await obj["madoka"].temperatures.query() | 5,335,988 |
def system_check():
"""
function: collected OS information
input : dataFileName
output: Successfully collected OS information
"""
g_logger.debug("Collecting OS information.")
g_jobInfo.jobName = "Collecting OS information"
dataFileName = "%s/systemfiles/OS_information_%s.txt" % (
g_r... | 5,335,989 |
def get_zero_to_2pi_input(label, required, placeholder=None, initial=None, validators=()):
"""
Method to get a custom positive float number field
:param label: String label of the field
:param required: Boolean to define whether the field is required or not
:param placeholder: Placeholder to appear ... | 5,335,990 |
def compile_math(math):
""" Compile a mathematical expression
Args:
math (:obj:`str`): mathematical expression
Returns:
:obj:`_ast.Expression`: compiled expression
"""
math_node = evalidate.evalidate(math,
addnodes=[
... | 5,335,991 |
def test_z_to_cMpc_redshift_array():
"""
Test using a redshift array returns an array of distances
"""
redshift_array = np.array([0.0, 1.0])
# Must return an array
expected_distance_array = np.array([0.0, 3395.905416665515])
calculated_distance_array = pyxcosmo.z_to_cMpc(redshift_array).va... | 5,335,992 |
def start_command(update: Update, context: CallbackContext = None) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
update.message.reply_markdown_v2(
fr'Hallo {user.mention_markdown_v2()}\! Silahkan masukan artikel/topik yang hendak dianalisa',
re... | 5,335,993 |
def save_urdf(dir, urdfName,
meshName,
objMass=0.1,
x_scale=1, y_scale=1, z_scale=1):
"""
#* Save URDF file at the specified path with the name. Assume 0.1kg mass and random inertia. Single base link.
"""
# Write to an URDF file
f = open(dir + urdfName + '.urd... | 5,335,994 |
def colfilter(
data,
skip: Optional[Union[str, List[str]]] = None,
only: Optional[Union[str, List[str]]] = None,
):
"""
Remove some variables (skip) or keep only certain variables (only)
Parameters
----------
data: pd.DataFrame
The DataFrame to be processed and return... | 5,335,995 |
def choice(seq: Sequence[Any]) -> Any:
"""
Returns a random element from the non-empty sequence ``seq``.
If ``seq`` is empty, raises ``IndexError``.
""" | 5,335,996 |
def test_global_and_user_rate_limiter():
"""
Both Global/User Rate Limiter Test
+-----+------------------+--------------------+--------+
| No. | Quota Remainings | API Request Time | Result |
| +---------+--------+ | |
| | Global | User | ... | 5,335,997 |
def acos(x):
"""
"""
return math.acos(x) | 5,335,998 |
def get_callable_from_string(f_name):
"""Takes a string containing a function name (optionally module qualified) and returns a callable object"""
try:
mod_name, func_name = get_mod_func(f_name)
if mod_name == "" and func_name == "":
raise AttributeError("%s couldn't be converted to a... | 5,335,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.