hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53e0da0292786cb8507f48a5713dbbdcd6b02a28 | 417 | py | Python | db/mongo_db_layer.py | noamn1/horse-race | 1b9946b383262a7980874e1f80e96e84afcf92ff | [
"MIT"
] | 1 | 2020-06-03T08:54:45.000Z | 2020-06-03T08:54:45.000Z | db/mongo_db_layer.py | noamn1/horse-race | 1b9946b383262a7980874e1f80e96e84afcf92ff | [
"MIT"
] | null | null | null | db/mongo_db_layer.py | noamn1/horse-race | 1b9946b383262a7980874e1f80e96e84afcf92ff | [
"MIT"
] | null | null | null | from db.base_db_layer import BaseDBLayer
import pymongo
from bson import ObjectId
class MongoDBLayer(BaseDBLayer):
def __connect(self):
self.__client = pymongo.MongoClient('localhost', 27017)
self.__db = self.__client["horse_race"]
def shutdown(self):
self.__client.close()
def __init__(self, cache):
super(MongoDBLayer, self).__init__(cache)
self.__connect()
| 23.166667 | 63 | 0.690647 | 48 | 417 | 5.520833 | 0.520833 | 0.113208 | 0.10566 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015152 | 0.208633 | 417 | 17 | 64 | 24.529412 | 0.787879 | 0 | 0 | 0 | 0 | 0 | 0.045564 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0 | 0.583333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
53e1de5b32ded36383c7f1447fbd3126a911c682 | 209 | py | Python | xhr/resources/echo-content-type.py | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | xhr/resources/echo-content-type.py | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 7,642 | 2018-05-28T09:38:03.000Z | 2022-03-31T20:55:48.000Z | xhr/resources/echo-content-type.py | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | def main(request, response):
response.headers.set(b"Content-Type", b"text/plain")
response.status = 200
response.content = request.headers.get(b"Content-Type")
response.close_connection = True
| 34.833333 | 59 | 0.722488 | 28 | 209 | 5.357143 | 0.607143 | 0.106667 | 0.16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.01676 | 0.143541 | 209 | 5 | 60 | 41.8 | 0.821229 | 0 | 0 | 0 | 0 | 0 | 0.162679 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.2 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
53f2bc01a04c39be17e1d0b2afef78530804c96b | 518 | py | Python | pyisemail/email_validator.py | moshfrid/pyIsEmail | 229db4fe4f790b5a95e1e85bffbdd42464472ea5 | [
"MIT"
] | 65 | 2015-10-14T08:34:01.000Z | 2022-02-28T01:45:33.000Z | pyisemail/email_validator.py | moshfrid/pyIsEmail | 229db4fe4f790b5a95e1e85bffbdd42464472ea5 | [
"MIT"
] | 17 | 2015-03-02T11:34:34.000Z | 2022-02-20T21:59:30.000Z | pyisemail/email_validator.py | moshfrid/pyIsEmail | 229db4fe4f790b5a95e1e85bffbdd42464472ea5 | [
"MIT"
] | 11 | 2017-06-10T13:53:02.000Z | 2022-03-07T14:17:06.000Z | class EmailValidator(object):
"""Abstract email validator to subclass from.
You should not instantiate an EmailValidator, as it merely provides the
interface for is_email, not an implementation.
"""
def is_email(self, address, diagnose=False):
"""Interface for is_email method.
Keyword arguments:
address -- address to check.
diagnose -- flag to report a diagnose or just True/False
"""
raise NotImplementedError()
is_valid = is_email
| 25.9 | 75 | 0.660232 | 61 | 518 | 5.52459 | 0.672131 | 0.083086 | 0.083086 | 0.11276 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | 518 | 19 | 76 | 27.263158 | 0.891534 | 0.586873 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
53f73ec11715ed1128e12d1c2a7366a9c0e6acb6 | 1,884 | py | Python | analysis/generate_deciles_charts.py | testiaindillingham/nhsx-demo | b19eac50037f687aedc59497a45fdfcef789f193 | [
"MIT"
] | null | null | null | analysis/generate_deciles_charts.py | testiaindillingham/nhsx-demo | b19eac50037f687aedc59497a45fdfcef789f193 | [
"MIT"
] | 8 | 2021-06-08T11:26:21.000Z | 2022-03-23T10:01:16.000Z | analysis/generate_deciles_charts.py | testiaindillingham/nhsx-demo | b19eac50037f687aedc59497a45fdfcef789f193 | [
"MIT"
] | 4 | 2021-12-09T22:47:45.000Z | 2021-12-16T09:33:37.000Z | import re
import numpy
import pandas
import utils
from ebmdatalab import charts
from pandas import Series
MEASURE_FNAME_REGEX = re.compile(r"measure_(?P<id>\w+)\.csv")
DECILES = Series(numpy.arange(0.1, 1, 0.1), name="deciles")
def _get_denominator(measures_table):
return measures_table.columns[-3]
def _get_group_by(measures_table):
return list(measures_table.columns[:-4])
def get_measures_tables():
for path in utils.OUTPUT_DIR.iterdir():
measure_fname_match = re.match(MEASURE_FNAME_REGEX, path.name)
if measure_fname_match is not None:
# The `date` column is assigned by the measures framework.
measures_table = pandas.read_csv(path, parse_dates=["date"])
# We can reconstruct the parameters passed to `Measure` without
# the study definition.
measures_table.attrs["id"] = measure_fname_match.group("id")
measures_table.attrs["denominator"] = _get_denominator(measures_table)
measures_table.attrs["group_by"] = _get_group_by(measures_table)
yield measures_table
def drop_rows(measures_table):
return measures_table[measures_table[measures_table.attrs["denominator"]] > 0]
def write_deciles_chart(measures_table):
facets = measures_table.attrs["group_by"][1:]
assert not facets, "Faceted deciles charts are not supported" # FIXME
plt = charts.deciles_chart(
measures_table,
"date",
"value",
show_outer_percentiles=False,
)
id_ = measures_table.attrs["id"]
fname = f"deciles_chart_{id_}.png"
fpath = utils.OUTPUT_DIR / fname
plt.savefig(fpath, dpi=300, bbox_inches="tight")
def main():
for measures_table in get_measures_tables():
measures_table = drop_rows(measures_table)
write_deciles_chart(measures_table)
if __name__ == "__main__":
main()
| 28.984615 | 82 | 0.69586 | 246 | 1,884 | 5.020325 | 0.373984 | 0.242105 | 0.087449 | 0.063158 | 0.213765 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007989 | 0.20276 | 1,884 | 64 | 83 | 29.4375 | 0.814248 | 0.077495 | 0 | 0 | 0 | 0 | 0.094634 | 0.027121 | 0 | 0 | 0 | 0.015625 | 0.02381 | 1 | 0.142857 | false | 0 | 0.142857 | 0.071429 | 0.357143 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
53fd305dd8ef004ad3bf37404c42c31742b57bdd | 6,505 | py | Python | tests/tests/test_two_factor_auth.py | rebotics/django-simple-2fa | 004124122434b252a0a67dd79ac5f8aea6e03ad3 | [
"MIT"
] | 4 | 2021-05-06T09:25:03.000Z | 2021-07-07T08:40:16.000Z | tests/tests/test_two_factor_auth.py | rebotics/django-simple-2fa | 004124122434b252a0a67dd79ac5f8aea6e03ad3 | [
"MIT"
] | null | null | null | tests/tests/test_two_factor_auth.py | rebotics/django-simple-2fa | 004124122434b252a0a67dd79ac5f8aea6e03ad3 | [
"MIT"
] | null | null | null | import uuid
from unittest import mock
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.mail import EmailMultiAlternatives
from django.http import HttpRequest
from rest_framework.test import APITestCase
from django_simple_2fa.auth_types import DirectTwoFactorAuthType
from django_simple_2fa.base import TwoFactorAuth
from django_simple_2fa.dto import TwoFactorRequester
from django_simple_2fa.errors import TwoFactorAuthError
from django_simple_2fa.settings import app_settings
UserModel = get_user_model()
class TwoFactorAuthView(APITestCase):
def setUp(self):
self.username = str(uuid.uuid4())
self.password = '123456'
self.device_id = str(uuid.uuid4())
self.user = UserModel(username=self.username, email=f'{self.username}@gmail.com')
self.user.set_password(self.password)
self.user.save()
self.request = HttpRequest()
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: True)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_status(self):
cache.clear()
result = TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).get_status()
self.assertIn(result.two_factor_type.type, 'email')
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: True)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_status_with_invalid_login(self):
cache.clear()
for _ in range(3):
with self.assertRaises(expected_exception=TwoFactorAuthError):
TwoFactorAuth(TwoFactorRequester(
username=str(uuid.uuid4()),
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).get_status()
TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).get_status()
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: False)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_status_without_2fa(self):
cache.clear()
result = TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).get_status()
self.assertIn(result.two_factor_type.type, DirectTwoFactorAuthType.type)
# @override_config(ENABLE_TWO_FACTOR_AUTH=True, ENABLE_IP_THROTTLING=True)
# def test_status_without_user_2fa(self):
# cache.clear()
#
# self.user.profile.two_factor_auth_type = DirectTwoFactorAuthType.type
# self.user.profile.save(update_fields=('two_factor_auth_type',))
#
# result = TwoFactorAuth(TwoFactorRequester(
# username=self.username,
# password=self.password,
# device_id=self.device_id,
# ip='127.0.0.1',
# )).get_status()
#
# self.assertIn(result.two_factor_type.type, DirectTwoFactorAuthType.type)
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: True)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_obtain(self):
cache.clear()
with mock.patch.object(EmailMultiAlternatives, 'send') as mocked_send_mail:
result = TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).obtain()
self.assertTrue(mocked_send_mail.called)
self.assertTrue(result.message)
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: True)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_obtain_with_few_attempts(self):
cache.clear()
for _ in range(3):
with self.assertRaises(expected_exception=TwoFactorAuthError):
TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=str(uuid.uuid4()),
device_id=self.device_id,
ip='127.0.0.1',
)).obtain()
with self.assertRaises(expected_exception=TwoFactorAuthError):
TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).obtain()
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: True)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_verify(self):
cache.clear()
message: str = ''
def _mocked_send(self):
nonlocal message
message = self.body
with mock.patch.object(EmailMultiAlternatives, 'send', new=_mocked_send):
TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).obtain()
phrase = 'verification code '
start_position = message.index(phrase) + len(phrase)
verification_code = message[start_position:start_position + 6]
response = TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).verify(verification_code)
self.assertEqual(response.user, self.user)
@mock.patch.object(app_settings, attribute='IS_ENABLED', new=lambda: False)
@mock.patch.object(app_settings, attribute='THROTTLING_IS_ENABLED', new=lambda: True)
def test_verify_without_2fa(self):
cache.clear()
response = TwoFactorAuth(TwoFactorRequester(
username=self.username,
password=self.password,
device_id=self.device_id,
ip='127.0.0.1',
)).verify('')
self.assertEqual(response.user, self.user)
| 36.340782 | 89 | 0.64043 | 720 | 6,505 | 5.593056 | 0.156944 | 0.045692 | 0.059598 | 0.062578 | 0.687112 | 0.672709 | 0.632977 | 0.632977 | 0.632977 | 0.632977 | 0 | 0.017898 | 0.252729 | 6,505 | 178 | 90 | 36.544944 | 0.810533 | 0.082706 | 0 | 0.646154 | 0 | 0 | 0.062006 | 0.028903 | 0 | 0 | 0 | 0 | 0.069231 | 1 | 0.069231 | false | 0.092308 | 0.092308 | 0 | 0.169231 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
990344c9a3aea96fe94e2f1fd67eec17e2974740 | 2,259 | py | Python | API/main/migrations/0012_auto_20200421_2246.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | API/main/migrations/0012_auto_20200421_2246.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | API/main/migrations/0012_auto_20200421_2246.py | Ju99ernaut/grapeflowAPI | 0d6599775e5b666ad735160b65262624fea0bf99 | [
"MIT"
] | null | null | null | # Generated by Django 3.0.3 on 2020-04-21 20:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0011_auto_20200419_1214'),
]
operations = [
migrations.RemoveField(
model_name='block',
name='assets',
),
migrations.RemoveField(
model_name='block',
name='components',
),
migrations.RemoveField(
model_name='block',
name='styles',
),
migrations.AddField(
model_name='page',
name='slug',
field=models.CharField(blank=True, default='', max_length=100),
),
migrations.AddField(
model_name='project',
name='branding',
field=models.BooleanField(blank=True, default=True),
),
migrations.AddField(
model_name='project',
name='customDomain',
field=models.BooleanField(blank=True, default=False),
),
migrations.AddField(
model_name='project',
name='customDomainUrl',
field=models.URLField(blank=True, default='', max_length=100),
),
migrations.AddField(
model_name='project',
name='description',
field=models.TextField(blank=True, default=''),
),
migrations.AddField(
model_name='project',
name='market',
field=models.BooleanField(blank=True, default=False),
),
migrations.AddField(
model_name='project',
name='multipage',
field=models.BooleanField(blank=True, default=False),
),
migrations.AddField(
model_name='project',
name='public',
field=models.BooleanField(blank=True, default=False),
),
migrations.AlterField(
model_name='project',
name='domain',
field=models.CharField(blank=True, default='', max_length=100),
),
migrations.AlterField(
model_name='project',
name='published',
field=models.BooleanField(blank=True, default=False),
),
]
| 29.723684 | 75 | 0.537406 | 195 | 2,259 | 6.128205 | 0.297436 | 0.097908 | 0.133891 | 0.150628 | 0.70795 | 0.70795 | 0.463598 | 0.426778 | 0.38159 | 0.38159 | 0 | 0.026846 | 0.340416 | 2,259 | 75 | 76 | 30.12 | 0.775168 | 0.01992 | 0 | 0.652174 | 1 | 0 | 0.098101 | 0.010398 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.014493 | 0 | 0.057971 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9907f525328b1b0694810547111de4f9f840f683 | 5,444 | py | Python | scripts/scramble/patches/PasteScript/setup.py | blankenberg/galaxy-data-resource | ca32a1aafd64948f489a4e5cf88096f32391b1d9 | [
"CC-BY-3.0"
] | 2 | 2016-02-23T00:09:14.000Z | 2019-02-11T07:48:44.000Z | scripts/scramble/patches/PasteScript/setup.py | blankenberg/galaxy-data-resource | ca32a1aafd64948f489a4e5cf88096f32391b1d9 | [
"CC-BY-3.0"
] | 1 | 2015-02-21T18:48:19.000Z | 2015-02-27T15:50:32.000Z | scripts/scramble/patches/PasteScript/setup.py | blankenberg/galaxy-data-resource | ca32a1aafd64948f489a4e5cf88096f32391b1d9 | [
"CC-BY-3.0"
] | 6 | 2015-05-27T13:09:50.000Z | 2019-02-11T07:48:46.000Z | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import re, os
version = '1.7.3'
news = os.path.join(os.path.dirname(__file__), 'docs', 'news.txt')
news = open(news).read()
parts = re.split(r'([0-9\.]+)\s*\n\r?-+\n\r?', news)
found_news = ''
for i in range(len(parts)-1):
if parts[i] == version:
found_news = parts[i+i]
break
if not found_news:
print 'Warning: no news for this version found'
long_description="""\
This is a pluggable command-line tool.
It includes some built-in features;
* Create file layouts for packages. For instance, ``paste create
--template=basic_package MyPackage`` will create a `setuptools
<http://peak.telecommunity.com/DevCenter/setuptools>`_-ready
file layout.
* Serving up web applications, with configuration based on
`paste.deploy <http://pythonpaste.org/deploy/paste-deploy.html>`_.
The latest version is available in a `Subversion repository
<http://svn.pythonpaste.org/Paste/Script/trunk#egg=PasteScript-dev>`_.
For the latest changes see the `news file
<http://pythonpaste.org/script/news.html>`_.
"""
if found_news:
title = 'Changes in %s' % version
long_description += "\n%s\n%s\n" % (title, '-'*len(title))
long_description += found_news
setup(
name="PasteScript",
version=version,
description="A pluggable command-line frontend, including commands to setup package file layouts",
long_description=long_description,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Paste",
],
keywords='web wsgi setuptools framework command-line setup',
author="Ian Bicking",
author_email="ianb@colorstudy.com",
url="http://pythonpaste.org/script/",
namespace_packages=['paste'],
license='MIT',
packages=find_packages(exclude='tests'),
package_data={
'paste.script': ['paster-templates/basic_package/setup.*',
'paster-templates/basic_package/tests/*.py',
# @@: docs/ doesn't have any files :(
'paster-templates/basic_package/+package+/*.py'],
},
zip_safe=False,
scripts=['scripts/paster'],
extras_require={
'Templating': [],
'Cheetah': ['Cheetah'],
'Config': ['PasteDeploy'],
'WSGIUtils': ['WSGIUtils'],
'Flup': ['Flup'],
# the Paste feature means the complete set of features;
# (other features are truly optional)
'Paste': ['PasteDeploy', 'Cheetah'],
},
entry_points="""
[paste.global_paster_command]
help=paste.script.help:HelpCommand
create=paste.script.create_distro:CreateDistroCommand [Templating]
serve=paste.script.serve:ServeCommand [Config]
request=paste.script.request:RequestCommand [Config]
post=paste.script.request:RequestCommand [Config]
exe=paste.script.exe:ExeCommand
points=paste.script.entrypoints:EntryPointCommand
make-config=paste.script.appinstall:MakeConfigCommand
setup-app=paste.script.appinstall:SetupCommand
[paste.paster_command]
grep = paste.script.grep:GrepCommand
[paste.paster_create_template]
basic_package=paste.script.templates:BasicPackage
[paste.server_runner]
wsgiutils=paste.script.wsgiutils_server:run_server [WSGIUtils]
flup_ajp_thread=paste.script.flup_server:run_ajp_thread [Flup]
flup_ajp_fork=paste.script.flup_server:run_ajp_fork [Flup]
flup_fcgi_thread=paste.script.flup_server:run_fcgi_thread [Flup]
flup_fcgi_fork=paste.script.flup_server:run_fcgi_fork [Flup]
flup_scgi_thread=paste.script.flup_server:run_scgi_thread [Flup]
flup_scgi_fork=paste.script.flup_server:run_scgi_fork [Flup]
cgi=paste.script.cgi_server:paste_run_cgi
cherrypy=paste.script.cherrypy_server:cpwsgi_server
twisted=paste.script.twisted_web2_server:run_twisted
[paste.app_factory]
test=paste.script.testapp:make_test_application
[paste.entry_point_description]
paste.entry_point_description = paste.script.epdesc:MetaEntryPointDescription
paste.paster_create_template = paste.script.epdesc:CreateTemplateDescription
paste.paster_command = paste.script.epdesc:PasterCommandDescription
paste.global_paster_command = paste.script.epdesc:GlobalPasterCommandDescription
paste.app_install = paste.script.epdesc:AppInstallDescription
# These aren't part of Paste Script particularly, but
# we'll document them here
console_scripts = paste.script.epdesc:ConsoleScriptsDescription
# @@: Need non-console scripts...
distutils.commands = paste.script.epdesc:DistutilsCommandsDescription
distutils.setup_keywords = paste.script.epdesc:SetupKeywordsDescription
egg_info.writers = paste.script.epdesc:EggInfoWriters
# @@: Not sure what this does:
#setuptools.file_finders = paste.script.epdesc:SetuptoolsFileFinders
[console_scripts]
paster=paste.script.command:run
[distutils.setup_keywords]
paster_plugins = setuptools.dist:assert_string_list
[egg_info.writers]
paster_plugins.txt = setuptools.command.egg_info:write_arg
""",
install_requires=[
],
)
| 37.287671 | 102 | 0.71565 | 655 | 5,444 | 5.783206 | 0.384733 | 0.104541 | 0.044879 | 0.033263 | 0.102693 | 0.051742 | 0 | 0 | 0 | 0 | 0 | 0.001761 | 0.165687 | 5,444 | 145 | 103 | 37.544828 | 0.832233 | 0.022961 | 0 | 0.01626 | 0 | 0.01626 | 0.764628 | 0.382691 | 0 | 0 | 0 | 0 | 0.00813 | 0 | null | null | 0 | 0.02439 | null | null | 0.00813 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
54cfd50eb3e34fd95914bb2386867f75a9f3795c | 2,695 | py | Python | django_workflow/tests_queries.py | dani0805/django_workflow | 4eb20fefa95c5d917628fc32b5479879d119a7e1 | [
"BSD-3-Clause"
] | 7 | 2017-08-29T16:16:25.000Z | 2021-03-13T20:35:45.000Z | django_workflow/tests_queries.py | dani0805/django_workflow | 4eb20fefa95c5d917628fc32b5479879d119a7e1 | [
"BSD-3-Clause"
] | 3 | 2020-02-11T23:11:27.000Z | 2021-06-10T20:49:53.000Z | django_workflow/tests_queries.py | dani0805/django_workflow | 4eb20fefa95c5d917628fc32b5479879d119a7e1 | [
"BSD-3-Clause"
] | null | null | null | LIST_WORKFLOWS_GQL = '''
query workflowList {
workflowList {
edges{
node {
id
name
objectType
initialPrefetch
initialState {
id
name
}
initialTransition {
id
name
}
}
}
}
}
'''
LIST_STATES_GQL = '''
query stateList {
stateList {
edges{
node {
id
name
active
initial
workflow {
id
name
}
}
}
}
}
'''
MUTATE_WORKFLOW_GRAPH_GQL = '''
mutation workflowMutation($param: WorkflowMutationInput!) {
workflowMutation(input:$param) {
id
name
initialPrefetch
objectType
errors {
messages
}
}
}
'''
MUTATE_STATE_GRAPH_GQL = '''
mutation stateMutation($param: StateMutationInput!) {
stateMutation(input:$param) {
id
name
initial
active
workflow
errors {
messages
}
}
}
'''
LIST_TRANSITIONS_GQL = '''
query transitionList($param: ID) {
transitionList(workflow_Id:$param) {
edges{
node {
id
name
initialState {
id
name
active
initial
variableDefinitions {
edges {
node {
id
name
}
}
}
}
finalState {
id
name
active
initial
variableDefinitions {
edges {
node {
id
name
}
}
}
}
conditionSet {
edges {
node {
id
conditionType
functionSet {
edges {
node {
id
functionModule
functionName
parameters{
edges {
node {
id
name
value
}
}
}
}
}
}
}
}
}
}
}
}
}
'''
LIST_WORKFLOW_STATES_GQL = '''
query stateList($param: ID) {
stateList(workflow_Id:$param) {
edges{
node {
id
name
active
initial
workflow {
id
name
}
}
}
}
}
'''
LIST_WORKFLOW_GRAPH_GQL = '''
query workflowList($param: String) {
workflowList(name:$param) {
edges{
node {
id
name
graph
}
}
}
}
''' | 16.041667 | 59 | 0.37885 | 157 | 2,695 | 6.375796 | 0.267516 | 0.095904 | 0.10989 | 0.11988 | 0.254745 | 0.234765 | 0.234765 | 0.18981 | 0.18981 | 0 | 0 | 0 | 0.552505 | 2,695 | 168 | 60 | 16.041667 | 0.830017 | 0 | 0 | 0.518293 | 0 | 0 | 0.918398 | 0.087166 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
54ddc15f9dcc0bb771e5c5f8d3eae325327cc439 | 184 | py | Python | seeg_utils/__init__.py | lneisenman/seeg_utils | 198c4fc2b9a451df5f6ba94e32bf975b57ebdd69 | [
"BSD-3-Clause"
] | 1 | 2021-06-12T12:28:14.000Z | 2021-06-12T12:28:14.000Z | seeg_utils/__init__.py | lneisenman/seeg_utils | 198c4fc2b9a451df5f6ba94e32bf975b57ebdd69 | [
"BSD-3-Clause"
] | null | null | null | seeg_utils/__init__.py | lneisenman/seeg_utils | 198c4fc2b9a451df5f6ba94e32bf975b57ebdd69 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from .seeg_utils import combine_electrode_files, electrodes_to_fcsv
__author__ = """Larry Eisenman"""
__email__ = 'leisenman@wustl.edu'
__version__ = '0.1.0'
| 23 | 67 | 0.728261 | 24 | 184 | 4.875 | 0.958333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.024691 | 0.119565 | 184 | 7 | 68 | 26.285714 | 0.697531 | 0.11413 | 0 | 0 | 0 | 0 | 0.236025 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
54e41bb495fad40e1c12239152dee35be9f33ae0 | 13,582 | py | Python | dynamic/test_client.py | piglei/python-base | d25434b5a900093508acb2ccab1bd3874f8523e2 | [
"Apache-2.0"
] | 1 | 2022-01-03T09:22:27.000Z | 2022-01-03T09:22:27.000Z | dynamic/test_client.py | piglei/python-base | d25434b5a900093508acb2ccab1bd3874f8523e2 | [
"Apache-2.0"
] | null | null | null | dynamic/test_client.py | piglei/python-base | d25434b5a900093508acb2ccab1bd3874f8523e2 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 The Kubernetes Authors.
#
# 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 time
import unittest
import uuid
from kubernetes.e2e_test import base
from kubernetes.client import api_client
from . import DynamicClient
from .exceptions import ResourceNotFoundError
def short_uuid():
id = str(uuid.uuid4())
return id[-12:]
class TestDynamicClient(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.config = base.get_e2e_configuration()
def test_cluster_custom_resources(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
with self.assertRaises(ResourceNotFoundError):
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ClusterChangeMe')
crd_api = client.resources.get(
api_version='apiextensions.k8s.io/v1beta1',
kind='CustomResourceDefinition')
name = 'clusterchangemes.apps.example.com'
crd_manifest = {
'apiVersion': 'apiextensions.k8s.io/v1beta1',
'kind': 'CustomResourceDefinition',
'metadata': {
'name': name,
},
'spec': {
'group': 'apps.example.com',
'names': {
'kind': 'ClusterChangeMe',
'listKind': 'ClusterChangeMeList',
'plural': 'clusterchangemes',
'singular': 'clusterchangeme',
},
'scope': 'Cluster',
'version': 'v1',
'subresources': {
'status': {}
}
}
}
resp = crd_api.create(crd_manifest)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
resp = crd_api.get(
name=name,
)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
try:
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ClusterChangeMe')
except ResourceNotFoundError:
# Need to wait a sec for the discovery layer to get updated
time.sleep(2)
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ClusterChangeMe')
resp = changeme_api.get()
self.assertEqual(resp.items, [])
changeme_name = 'custom-resource' + short_uuid()
changeme_manifest = {
'apiVersion': 'apps.example.com/v1',
'kind': 'ClusterChangeMe',
'metadata': {
'name': changeme_name,
},
'spec': {}
}
resp = changeme_api.create(body=changeme_manifest)
self.assertEqual(resp.metadata.name, changeme_name)
resp = changeme_api.get(name=changeme_name)
self.assertEqual(resp.metadata.name, changeme_name)
changeme_manifest['spec']['size'] = 3
resp = changeme_api.patch(
body=changeme_manifest,
content_type='application/merge-patch+json'
)
self.assertEqual(resp.spec.size, 3)
resp = changeme_api.get(name=changeme_name)
self.assertEqual(resp.spec.size, 3)
resp = changeme_api.get()
self.assertEqual(len(resp.items), 1)
resp = changeme_api.delete(
name=changeme_name,
)
resp = changeme_api.get()
self.assertEqual(len(resp.items), 0)
resp = crd_api.delete(
name=name,
)
time.sleep(2)
client.resources.invalidate_cache()
with self.assertRaises(ResourceNotFoundError):
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ClusterChangeMe')
def test_namespaced_custom_resources(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
with self.assertRaises(ResourceNotFoundError):
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ChangeMe')
crd_api = client.resources.get(
api_version='apiextensions.k8s.io/v1beta1',
kind='CustomResourceDefinition')
name = 'changemes.apps.example.com'
crd_manifest = {
'apiVersion': 'apiextensions.k8s.io/v1beta1',
'kind': 'CustomResourceDefinition',
'metadata': {
'name': name,
},
'spec': {
'group': 'apps.example.com',
'names': {
'kind': 'ChangeMe',
'listKind': 'ChangeMeList',
'plural': 'changemes',
'singular': 'changeme',
},
'scope': 'Namespaced',
'version': 'v1',
'subresources': {
'status': {}
}
}
}
resp = crd_api.create(crd_manifest)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
resp = crd_api.get(
name=name,
)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
try:
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ChangeMe')
except ResourceNotFoundError:
# Need to wait a sec for the discovery layer to get updated
time.sleep(2)
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ChangeMe')
resp = changeme_api.get()
self.assertEqual(resp.items, [])
changeme_name = 'custom-resource' + short_uuid()
changeme_manifest = {
'apiVersion': 'apps.example.com/v1',
'kind': 'ChangeMe',
'metadata': {
'name': changeme_name,
},
'spec': {}
}
resp = changeme_api.create(body=changeme_manifest, namespace='default')
self.assertEqual(resp.metadata.name, changeme_name)
resp = changeme_api.get(name=changeme_name, namespace='default')
self.assertEqual(resp.metadata.name, changeme_name)
changeme_manifest['spec']['size'] = 3
resp = changeme_api.patch(
body=changeme_manifest,
namespace='default',
content_type='application/merge-patch+json'
)
self.assertEqual(resp.spec.size, 3)
resp = changeme_api.get(name=changeme_name, namespace='default')
self.assertEqual(resp.spec.size, 3)
resp = changeme_api.get(namespace='default')
self.assertEqual(len(resp.items), 1)
resp = changeme_api.get()
self.assertEqual(len(resp.items), 1)
resp = changeme_api.delete(
name=changeme_name,
namespace='default'
)
resp = changeme_api.get(namespace='default')
self.assertEqual(len(resp.items), 0)
resp = changeme_api.get()
self.assertEqual(len(resp.items), 0)
resp = crd_api.delete(
name=name,
)
time.sleep(2)
client.resources.invalidate_cache()
with self.assertRaises(ResourceNotFoundError):
changeme_api = client.resources.get(
api_version='apps.example.com/v1', kind='ChangeMe')
def test_service_apis(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
api = client.resources.get(api_version='v1', kind='Service')
name = 'frontend-' + short_uuid()
service_manifest = {'apiVersion': 'v1',
'kind': 'Service',
'metadata': {'labels': {'name': name},
'name': name,
'resourceversion': 'v1'},
'spec': {'ports': [{'name': 'port',
'port': 80,
'protocol': 'TCP',
'targetPort': 80}],
'selector': {'name': name}}}
resp = api.create(
body=service_manifest,
namespace='default'
)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
resp = api.get(
name=name,
namespace='default'
)
self.assertEqual(name, resp.metadata.name)
self.assertTrue(resp.status)
service_manifest['spec']['ports'] = [{'name': 'new',
'port': 8080,
'protocol': 'TCP',
'targetPort': 8080}]
resp = api.patch(
body=service_manifest,
name=name,
namespace='default'
)
self.assertEqual(2, len(resp.spec.ports))
self.assertTrue(resp.status)
resp = api.delete(
name=name, body={},
namespace='default'
)
def test_replication_controller_apis(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
api = client.resources.get(
api_version='v1', kind='ReplicationController')
name = 'frontend-' + short_uuid()
rc_manifest = {
'apiVersion': 'v1',
'kind': 'ReplicationController',
'metadata': {'labels': {'name': name},
'name': name},
'spec': {'replicas': 2,
'selector': {'name': name},
'template': {'metadata': {
'labels': {'name': name}},
'spec': {'containers': [{
'image': 'nginx',
'name': 'nginx',
'ports': [{'containerPort': 80,
'protocol': 'TCP'}]}]}}}}
resp = api.create(
body=rc_manifest, namespace='default')
self.assertEqual(name, resp.metadata.name)
self.assertEqual(2, resp.spec.replicas)
resp = api.get(
name=name, namespace='default')
self.assertEqual(name, resp.metadata.name)
self.assertEqual(2, resp.spec.replicas)
resp = api.delete(
name=name, body={}, namespace='default')
def test_configmap_apis(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
api = client.resources.get(api_version='v1', kind='ConfigMap')
name = 'test-configmap-' + short_uuid()
test_configmap = {
"kind": "ConfigMap",
"apiVersion": "v1",
"metadata": {
"name": name,
"labels": {
"e2e-test": "true",
},
},
"data": {
"config.json": "{\"command\":\"/usr/bin/mysqld_safe\"}",
"frontend.cnf": "[mysqld]\nbind-address = 10.0.0.3\n"
}
}
resp = api.create(
body=test_configmap, namespace='default'
)
self.assertEqual(name, resp.metadata.name)
resp = api.get(
name=name, namespace='default', label_selector="e2e-test=true")
self.assertEqual(name, resp.metadata.name)
test_configmap['data']['config.json'] = "{}"
resp = api.patch(
name=name, namespace='default', body=test_configmap)
resp = api.delete(
name=name, body={}, namespace='default')
resp = api.get(namespace='default', pretty=True, label_selector="e2e-test=true")
self.assertEqual([], resp.items)
def test_node_apis(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
api = client.resources.get(api_version='v1', kind='Node')
for item in api.get().items:
node = api.get(name=item.metadata.name)
self.assertTrue(len(dict(node.metadata.labels)) > 0)
# test_node_apis_partial_object_metadata lists all nodes in the cluster, but only retrieves object metadata
def test_node_apis_partial_object_metadata(self):
client = DynamicClient(api_client.ApiClient(configuration=self.config))
api = client.resources.get(api_version='v1', kind='Node')
params = {'header_params': {'Accept': 'application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io'}}
resp = api.get(**params)
self.assertEqual('PartialObjectMetadataList', resp.kind)
self.assertEqual('meta.k8s.io/v1', resp.apiVersion)
params = {'header_params': {'aCcePt': 'application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io'}}
resp = api.get(**params)
self.assertEqual('PartialObjectMetadataList', resp.kind)
self.assertEqual('meta.k8s.io/v1', resp.apiVersion)
| 35.186528 | 114 | 0.548373 | 1,301 | 13,582 | 5.620292 | 0.165257 | 0.069748 | 0.036926 | 0.04308 | 0.723332 | 0.718955 | 0.687226 | 0.671772 | 0.65919 | 0.656865 | 0 | 0.010658 | 0.329922 | 13,582 | 385 | 115 | 35.277922 | 0.79277 | 0.057576 | 0 | 0.613115 | 0 | 0 | 0.159521 | 0.044203 | 0 | 0 | 0 | 0 | 0.15082 | 1 | 0.029508 | false | 0 | 0.022951 | 0 | 0.059016 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
54e4e5b4ab9a9a478aee741f284792a72a679982 | 1,458 | py | Python | Desktop/cs61a/lab/lab04/tests/mutability.py | cpvb13/cal-hack-5-proj | 13e31fff3f56b57030c34147b04cef1d6309c62b | [
"MIT"
] | null | null | null | Desktop/cs61a/lab/lab04/tests/mutability.py | cpvb13/cal-hack-5-proj | 13e31fff3f56b57030c34147b04cef1d6309c62b | [
"MIT"
] | null | null | null | Desktop/cs61a/lab/lab04/tests/mutability.py | cpvb13/cal-hack-5-proj | 13e31fff3f56b57030c34147b04cef1d6309c62b | [
"MIT"
] | null | null | null | test = {
'name': 'Mutability',
'points': 0,
'suites': [
{
'type': 'wwpp',
'cases': [
{
'code': """
>>> lst = [5, 6, 7, 8]
>>> lst.append(6)
Nothing
>>> lst
[5, 6, 7, 8, 6]
>>> lst.insert(0, 9)
>>> lst
[9, 5, 6, 7, 8, 6]
>>> x = lst.pop(2)
>>> lst
[9, 5, 7, 8, 6]
>>> lst.remove(x)
>>> lst
[9, 5, 7, 8]
>>> a, b = lst, lst[:]
>>> a is lst
True
>>> b == lst
True
>>> b is lst
False
"""
},
]
},
{
'type': 'wwpp',
'cases': [
{
'code': """
>>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151}
>>> pokemon['pikachu']
25
>>> len(pokemon)
3
>>> pokemon['jolteon'] = 135
>>> pokemon['mew'] = 25
>>> len(pokemon)
4
>>> 'mewtwo' in pokemon
False
>>> 'pikachu' in pokemon
True
>>> 25 in pokemon
False
>>> 148 in pokemon.values()
True
>>> 151 in pokemon.keys()
False
>>> 'mew' in pokemon.keys()
True
>>> pokemon['ditto'] = pokemon['jolteon']
>>> pokemon['ditto']
135
"""
},
]
}
]
}
| 20.828571 | 69 | 0.30727 | 129 | 1,458 | 3.472868 | 0.348837 | 0.120536 | 0.020089 | 0.026786 | 0.075893 | 0 | 0 | 0 | 0 | 0 | 0 | 0.080282 | 0.513032 | 1,458 | 69 | 70 | 21.130435 | 0.550704 | 0 | 0 | 0.333333 | 0 | 0 | 0.849794 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
54fb804928a51be8fb2889fe712c326cda40600e | 308 | py | Python | patterns/number pattern_11.py | ZephyrAveryl777/Python-Programs | 26de85c31af28382d406d27d54186b966a7b1bfc | [
"MIT"
] | 6 | 2020-08-13T11:49:29.000Z | 2021-03-07T05:46:17.000Z | patterns/number pattern_11.py | ZephyrAveryl777/Python-Programs | 26de85c31af28382d406d27d54186b966a7b1bfc | [
"MIT"
] | null | null | null | patterns/number pattern_11.py | ZephyrAveryl777/Python-Programs | 26de85c31af28382d406d27d54186b966a7b1bfc | [
"MIT"
] | 1 | 2021-04-24T06:12:48.000Z | 2021-04-24T06:12:48.000Z | '''
Pattern
Enter number of rows: 5
1
21
321
4321
54321
'''
print('Number Pattern:')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(row,0,-1):
if column < 10:
print(f'0{column}',end=' ')
else:
print(column,end=' ')
print() | 17.111111 | 49 | 0.616883 | 50 | 308 | 3.76 | 0.5 | 0.117021 | 0.138298 | 0.180851 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.095041 | 0.214286 | 308 | 18 | 50 | 17.111111 | 0.681818 | 0.165584 | 0 | 0 | 0 | 0 | 0.206009 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.444444 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
54fd024d49cd1d3aa4af71d6a6f03985232dae5d | 2,792 | py | Python | finetune/task_builder.py | Wangkaixinlove/sentiment | a1bd7f099c4885d4e65435e403ff5932ebfab73a | [
"Apache-2.0"
] | null | null | null | finetune/task_builder.py | Wangkaixinlove/sentiment | a1bd7f099c4885d4e65435e403ff5932ebfab73a | [
"Apache-2.0"
] | null | null | null | finetune/task_builder.py | Wangkaixinlove/sentiment | a1bd7f099c4885d4e65435e403ff5932ebfab73a | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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.
"""Returns task instances given the task name."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import configure_finetuning
from finetune.classification import classification_tasks
from finetune.qa import qa_tasks
from finetune.tagging import tagging_tasks
from model import tokenization
def get_tasks(config: configure_finetuning.FinetuningConfig):
tokenizer = tokenization.FullTokenizer(vocab_file=config.vocab_file,
do_lower_case=config.do_lower_case)
return [get_task(config, task_name, tokenizer)
for task_name in config.task_names]
def get_task(config: configure_finetuning.FinetuningConfig, task_name,
tokenizer):
"""Get an instance of a task based on its name."""
if task_name == "cola":
return classification_tasks.CoLA(config, tokenizer)
elif task_name == "mrpc":
return classification_tasks.MRPC(config, tokenizer)
elif task_name == "mnli":
return classification_tasks.MNLI(config, tokenizer)
elif task_name == "sst":
return classification_tasks.SST(config, tokenizer)
elif task_name == "rte":
return classification_tasks.RTE(config, tokenizer)
elif task_name == "qnli":
return classification_tasks.QNLI(config, tokenizer)
elif task_name == "qqp":
return classification_tasks.QQP(config, tokenizer)
elif task_name == "sts":
return classification_tasks.STS(config, tokenizer)
elif task_name == "squad":
return qa_tasks.SQuAD(config, tokenizer)
elif task_name == "squadv1":
return qa_tasks.SQuADv1(config, tokenizer)
elif task_name == "newsqa":
return qa_tasks.NewsQA(config, tokenizer)
elif task_name == "naturalqs":
return qa_tasks.NaturalQuestions(config, tokenizer)
elif task_name == "triviaqa":
return qa_tasks.TriviaQA(config, tokenizer)
elif task_name == "searchqa":
return qa_tasks.SearchQA(config, tokenizer)
elif task_name == "chunk":
return tagging_tasks.Chunking(config, tokenizer)
elif task_name == "senticorp":
return classification_tasks.SentiCorp(config, tokenizer)
else:
raise ValueError("Unknown task " + task_name)
| 38.246575 | 76 | 0.747851 | 364 | 2,792 | 5.554945 | 0.348901 | 0.083086 | 0.14095 | 0.170623 | 0.200297 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004733 | 0.167622 | 2,792 | 72 | 77 | 38.777778 | 0.865318 | 0.239255 | 0 | 0 | 0 | 0 | 0.046667 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.040816 | false | 0 | 0.163265 | 0 | 0.55102 | 0.020408 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
070ce7392e55dc75f35c619ce7df641377e5ac36 | 134 | py | Python | Python/1096 - SequenciaIJ2.py | carloshenrique051994/exerciciosUri | 1f73a32b44c79cd7aa47a89f2afb8e9618d27e3b | [
"MIT"
] | null | null | null | Python/1096 - SequenciaIJ2.py | carloshenrique051994/exerciciosUri | 1f73a32b44c79cd7aa47a89f2afb8e9618d27e3b | [
"MIT"
] | null | null | null | Python/1096 - SequenciaIJ2.py | carloshenrique051994/exerciciosUri | 1f73a32b44c79cd7aa47a89f2afb8e9618d27e3b | [
"MIT"
] | null | null | null | contador = 1
while contador <= 9:
for contador2 in range(7, 4, -1):
print(f'I={contador} J={contador2}')
contador += 2 | 26.8 | 44 | 0.589552 | 20 | 134 | 3.95 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.079208 | 0.246269 | 134 | 5 | 45 | 26.8 | 0.70297 | 0 | 0 | 0 | 0 | 0 | 0.192593 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
071a6d7bb57724cbd1a6ee6ffa2ecdb2a4dec855 | 799 | py | Python | detail/Event2.py | rainforest-tokyo/AutoNaptPython | 5c021ca18e7a8280b52fd168ff6c443321ff3e31 | [
"MIT"
] | null | null | null | detail/Event2.py | rainforest-tokyo/AutoNaptPython | 5c021ca18e7a8280b52fd168ff6c443321ff3e31 | [
"MIT"
] | null | null | null | detail/Event2.py | rainforest-tokyo/AutoNaptPython | 5c021ca18e7a8280b52fd168ff6c443321ff3e31 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------
# AutoNaptPython
#
# Copyright (c) 2018 RainForest
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#-----------------------------------
class Event2(object):
def __init__(self, doc = None):
self.handlers = []
self.__doc__ = doc
def __str__(self):
return 'Event<%s>' % str(self.__doc__)
def add(self, handler):
self.handlers.append(handler)
return self
def remove(self, handler):
self.handlers.remove(handler)
return self
def __call__(self, sender, e):
for handler in self.handlers:
handler(sender, e)
__iadd__ = add
__isub__ = remove
| 22.828571 | 50 | 0.548185 | 86 | 799 | 4.767442 | 0.569767 | 0.117073 | 0.073171 | 0.112195 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010084 | 0.255319 | 799 | 34 | 51 | 23.5 | 0.678992 | 0.317897 | 0 | 0.117647 | 0 | 0 | 0.016822 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.294118 | false | 0 | 0 | 0.058824 | 0.647059 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
071fe4318517684b6f8ce5ed395562d53c360274 | 2,158 | py | Python | java/sqlTableToJavaClass.py | skylarkgit/sql2java | befd55180969b0ec68e242991c3260272d755cc9 | [
"MIT"
] | 2 | 2019-10-23T08:27:30.000Z | 2019-10-23T09:58:45.000Z | java/sqlTableToJavaClass.py | skylarkgit/sql2java | befd55180969b0ec68e242991c3260272d755cc9 | [
"MIT"
] | null | null | null | java/sqlTableToJavaClass.py | skylarkgit/sql2java | befd55180969b0ec68e242991c3260272d755cc9 | [
"MIT"
] | null | null | null | from sql.sqlTable import SQLTable
from dialectUtil import *
class JavaProperty:
def __init__(self, scope, name, type):
self.name = name
self.type = getJavaType(type)
self.scope = scope
def code(self):
if (self.name == 'id'):
return '@Id\n' + '@GeneratedValue(strategy = GenerationType.AUTO)\n' + self.scope + ' ' + self.type + ' ' + self.name + ';\n'
return self.scope + ' ' + self.type + ' ' + self.name + ';\n'
def getter(self):
return JavaFunction('public', 'get' + camel(self.name), self.type, '', 'return ' + self.name + ';')
def setter(self):
return JavaFunction('public', 'set' + camel(self.name), 'void', self.type + ' ' + self.name, 'this.' + self.name + '=' + self.name + ';')
class SQLTableToJavaClass:
def __init__(self, sqlTable):
self.table = sqlTable
self.properties = []
self.initProperties()
self.annotations = '@Entity\n'
def initProperties(self):
for prop in self.table.fields:
prop = self.table.fields[prop]
self.properties.append(JavaProperty('private', prop.name, prop.type))
def getJavaClass(self):
return ('package com.metacube.learninganddevelopment.model;\nimport java.util.UUID;import java.sql.Timestamp;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;'
+ self.annotations + JavaScope('public', JavaClass(self.table.name, (''.join(map(lambda property : property.code(), self.properties))
+ (''.join(map(lambda property : property.getter(), self.properties)))
+ (''.join(map(lambda property : property.setter(), self.properties)))))))
def getRepositoryClass(self):
return ('package com.metacube.learninganddevelopment.repository;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport com.metacube.learninganddevelopment.model.' + self.table.name + ';\n'
+ JavaScope('public', 'interface ' + self.table.name + 'Repository extends JpaRepository<' + self.table.name + ', Long> {\n\n}\n')) | 52.634146 | 258 | 0.647822 | 237 | 2,158 | 5.864979 | 0.308017 | 0.057554 | 0.034532 | 0.034532 | 0.222302 | 0.171223 | 0.099281 | 0 | 0 | 0 | 0 | 0 | 0.197405 | 2,158 | 41 | 259 | 52.634146 | 0.80254 | 0 | 0 | 0 | 0 | 0.060606 | 0.279296 | 0.199629 | 0 | 0 | 0 | 0 | 0 | 1 | 0.242424 | false | 0 | 0.121212 | 0.121212 | 0.606061 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
072a88578c2804640774ada3506642ec8990b527 | 326 | py | Python | prubaDjango/Prueba/models.py | nepta1998/PruebaPhoenixWare | 1edcc238a352e539fedb9407dbb22a2501504ed2 | [
"MIT"
] | null | null | null | prubaDjango/Prueba/models.py | nepta1998/PruebaPhoenixWare | 1edcc238a352e539fedb9407dbb22a2501504ed2 | [
"MIT"
] | 5 | 2021-03-10T10:45:11.000Z | 2022-02-18T22:28:45.000Z | prubaDjango/Prueba/models.py | nepta1998/PruebaPhoenixWare | 1edcc238a352e539fedb9407dbb22a2501504ed2 | [
"MIT"
] | null | null | null | from django.db import models
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Create your models here.
class GoogleDoc(models.Model):
file = models.FileField()
url = models.URLField()
| 25.076923 | 54 | 0.803681 | 43 | 326 | 6.046512 | 0.674419 | 0.076923 | 0.107692 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.131902 | 326 | 12 | 55 | 27.166667 | 0.918728 | 0.07362 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.666667 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
072fe982a8475e19e0af955cbf086d96d10d0496 | 261 | py | Python | src/oscar/apps/offer/config.py | highbiza/django-oscar | 7eba207a77e5dd56b04a63b9283a9d76da2f64ac | [
"BSD-3-Clause"
] | 1 | 2019-10-22T01:10:20.000Z | 2019-10-22T01:10:20.000Z | src/oscar/apps/offer/config.py | highbiza/django-oscar | 7eba207a77e5dd56b04a63b9283a9d76da2f64ac | [
"BSD-3-Clause"
] | 10 | 2020-05-11T20:33:31.000Z | 2022-03-12T00:24:28.000Z | src/oscar/apps/offer/config.py | highbiza/django-oscar | 7eba207a77e5dd56b04a63b9283a9d76da2f64ac | [
"BSD-3-Clause"
] | 3 | 2019-03-20T16:17:58.000Z | 2022-02-25T09:38:38.000Z | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class OfferConfig(AppConfig):
label = 'offer'
name = 'oscar.apps.offer'
verbose_name = _('Offer')
def ready(self):
from . import signals # noqa
| 21.75 | 54 | 0.689655 | 32 | 261 | 5.5 | 0.6875 | 0.113636 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.218391 | 261 | 11 | 55 | 23.727273 | 0.862745 | 0.015326 | 0 | 0 | 0 | 0 | 0.101961 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.375 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
0730255708718cdcc4dd11d2ecbbdc64e32356ad | 1,828 | py | Python | ArduinoPCKeyboardController/HardwareKeyboard/HeadlessKeyboard.py | manashmndl/ArduinoPCKeyboardController | 89811756d801f8fd64a72991075f9df99a0acf87 | [
"MIT"
] | 1 | 2016-09-03T03:01:29.000Z | 2016-09-03T03:01:29.000Z | ArduinoPCKeyboardController/HardwareKeyboard/HeadlessKeyboard.py | manashmndl/ArduinoPCKeyboardController | 89811756d801f8fd64a72991075f9df99a0acf87 | [
"MIT"
] | null | null | null | ArduinoPCKeyboardController/HardwareKeyboard/HeadlessKeyboard.py | manashmndl/ArduinoPCKeyboardController | 89811756d801f8fd64a72991075f9df99a0acf87 | [
"MIT"
] | null | null | null | import pyautogui as keyboard
from SerialHandler.ArduinoController import Controller
class ArduinoHeadlessKeyboard:
def __init__(self):
self.arduino = Controller()
self.command = ''
def is_connected(self):
return self.arduino.is_open()
def autoconnect(self):
self.arduino.autoconnect()
def set_baud(self, baud):
self.arduino.set_baud(baud)
def set_port(self, port):
self.arduino.set_port(port)
def disconnect(self):
self.arduino.disconnect()
return self.arduino.is_open()
def connect(self):
self.arduino.connect()
def execute_command(self):
if self.arduino.is_open():
self.command = self.arduino.readline()
# Remove the trailing newline
self.command = self.command[:len(self.command)-1]
# Convert byte to regular string
self.command = str(self.command, 'utf-8')
keyboard.press(self.command)
return True
print("Arduino Connection Error! Reconnect arduino and try again")
return False
def exec_command(self, cmd):
keyboard.press(cmd)
def get_last_command(self):
return self.command
def get_command(self):
if self.arduino.is_open():
self.command = self.arduino.readline()
self.command = self.command[:len(self.command)-1]
self.command = str(self.command, 'utf-8')
def execute_latest_command(self):
keyboard.press(self.command)
def get_arduino_details(self):
if len (self.arduino.get_arduino_details()) != 0:
return self.arduino.get_arduino_details()[1]
def get_arduino_port(self):
if len(self.arduino.get_arduino_details()) != 0:
return self.arduino.get_arduino_details()
| 28.5625 | 74 | 0.632932 | 219 | 1,828 | 5.136986 | 0.269406 | 0.156444 | 0.075556 | 0.060444 | 0.398222 | 0.398222 | 0.352 | 0.300444 | 0.234667 | 0.234667 | 0 | 0.005197 | 0.263129 | 1,828 | 63 | 75 | 29.015873 | 0.829993 | 0.031729 | 0 | 0.311111 | 0 | 0 | 0.037917 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.311111 | false | 0 | 0.044444 | 0.044444 | 0.533333 | 0.022222 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
073f72ed3ded36007799abd17a3e7dbfcf1e511e | 434 | py | Python | system/urls.py | okotdaniel/past-paper | f933bf7caf419123e7a8e37f2a3907b812d5efaa | [
"MIT"
] | null | null | null | system/urls.py | okotdaniel/past-paper | f933bf7caf419123e7a8e37f2a3907b812d5efaa | [
"MIT"
] | null | null | null | system/urls.py | okotdaniel/past-paper | f933bf7caf419123e7a8e37f2a3907b812d5efaa | [
"MIT"
] | null | null | null | from . import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import os
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('papers.urls'))
]
urlpatterns +=staticfiles_urlpatterns()
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 28.933333 | 75 | 0.790323 | 54 | 434 | 6.259259 | 0.351852 | 0.118343 | 0.150888 | 0.16568 | 0.224852 | 0.224852 | 0 | 0 | 0 | 0 | 0 | 0 | 0.108295 | 434 | 14 | 76 | 31 | 0.873385 | 0 | 0 | 0 | 0 | 0 | 0.039171 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
074f383e3e6cc7f62ddf1a625089a05bea7f0844 | 3,281 | py | Python | app/core/settings/base.py | DCC-FCFM-UCHILE/django-boilerplate | 9fd7a71f8a1734419159316228f0853f7622c9e0 | [
"MIT"
] | null | null | null | app/core/settings/base.py | DCC-FCFM-UCHILE/django-boilerplate | 9fd7a71f8a1734419159316228f0853f7622c9e0 | [
"MIT"
] | null | null | null | app/core/settings/base.py | DCC-FCFM-UCHILE/django-boilerplate | 9fd7a71f8a1734419159316228f0853f7622c9e0 | [
"MIT"
] | null | null | null | # core/settings/base.py
from pathlib import Path
from core.functions import get_env_variable
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = get_env_variable("DJANGO_SECRET_KEY")
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"sso.apps.SsoConfig",
"demo.apps.DemoConfig",
]
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",
]
ROOT_URLCONF = "core.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
"templates",
],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "core.wsgi.application"
DATABASES = {
"default": {
"ENGINE": get_env_variable("DJANGO_DB_ENGINE"),
"NAME": get_env_variable("DJANGO_DB_NAME"),
"USER": get_env_variable("DJANGO_DB_USER"),
"PASSWORD": get_env_variable("DJANGO_DB_PASSWORD"),
"HOST": get_env_variable("DJANGO_DB_HOST"),
"PORT": get_env_variable("DJANGO_DB_PORT"),
}
}
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",
},
]
LANGUAGE_CODE = "es-cl"
TIME_ZONE = "America/Santiago"
USE_I18N = True
USE_L10N = False
USE_TZ = True
DATETIME_FORMAT = "d/m/Y H:i:s"
DATE_FORMAT = "d/m/Y"
STATIC_URL = "static/"
STATIC_ROOT = "/static"
STATICFILES_DIRS = ("staticfiles",)
MEDIA_ROOT = get_env_variable("DJANGO_MEDIA_ROOT", "/media")
MEDIA_URL = "media/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
EMAIL_BACKEND = get_env_variable("DJANGO_EMAIL_BACKEND")
EMAIL_HOST = get_env_variable("DJANGO_EMAIL_HOST")
EMAIL_PORT = get_env_variable("DJANGO_EMAIL_PORT")
EMAIL_USE_TLS = get_env_variable("DJANGO_EMAIL_USE_TLS")
EMAIL_HOST_USER = get_env_variable("DJANGO_EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = get_env_variable("DJANGO_EMAIL_HOST_PASSWORD")
SERVER_EMAIL = get_env_variable("DJANGO_SERVER_EMAIL")
BASE_URL = get_env_variable("DJANGO_BASE_URL")
# DCC SSO
LOGIN_URL = get_env_variable("DJANGO_LOGIN_URL")
SSO_URL = get_env_variable("DJANGO_SSO_URL")
SSO_APP = get_env_variable("DJANGO_SSO_APP")
SSO_AUTH = get_env_variable("DJANGO_SSO_AUTH")
| 28.780702 | 91 | 0.708321 | 371 | 3,281 | 5.90027 | 0.299191 | 0.057561 | 0.134308 | 0.182732 | 0.277752 | 0.11101 | 0 | 0 | 0 | 0 | 0 | 0.001461 | 0.165803 | 3,281 | 113 | 92 | 29.035398 | 0.798319 | 0.008839 | 0 | 0.021978 | 0 | 0 | 0.485688 | 0.314251 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.076923 | 0.021978 | 0 | 0.021978 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
0764914f4ed9bfc21502ed7841413e439d3fba93 | 1,397 | py | Python | src/legacy/telecom.py | joaopfonseca/tourism_telecom | 5ed4854a82456c0e2131424f2471aa1ca2f90b92 | [
"MIT"
] | null | null | null | src/legacy/telecom.py | joaopfonseca/tourism_telecom | 5ed4854a82456c0e2131424f2471aa1ca2f90b92 | [
"MIT"
] | null | null | null | src/legacy/telecom.py | joaopfonseca/tourism_telecom | 5ed4854a82456c0e2131424f2471aa1ca2f90b92 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import plotly
from config import _data_dir
import logging.config
import logging
import credentials
plotly.tools.set_credentials_file(username=credentials.plotlyu, api_key=credentials.plotlykey)
class CDRAnalysis:
"""CDR Analysis"""
def __init__(self, params, data_feature_extracted):
self.params = params
self.data_feature_extracted = data_feature_extracted
self.cdr_main(self.data_feature_extracted)
@staticmethod
def cdr_main(df):
""" Exploratory analysis of CDR data """
# Create a frequency count of how many average daily calls each customer makes
daily_calls = df.groupby(['user_id', 'date'], as_index=True).count()
# Create a frequency count of how many average hourly calls each customer makes
hourly_calls = df.groupby(['user_id', 'time'], as_index=True).count()
# Count calls per customer
calls_per_cust = df.groupby(['user_id'], as_index=False).count()
# Total estimated daily presences: Italians & Foreigners
# Make a stacked bar plot day by day through summer
# Estimated daily presence of foreign visitors
# Estimated daily presence of Italian visitors
# Duration of stay of foreign visitors
# Duration of stay of Italian visitors
return None
| 24.946429 | 94 | 0.692198 | 180 | 1,397 | 5.211111 | 0.461111 | 0.046908 | 0.085288 | 0.047974 | 0.172708 | 0.078891 | 0.078891 | 0.078891 | 0 | 0 | 0 | 0.000933 | 0.232641 | 1,397 | 55 | 95 | 25.4 | 0.874067 | 0.37151 | 0 | 0 | 0 | 0 | 0.034238 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.105263 | false | 0 | 0.368421 | 0 | 0.578947 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
076a0a8329caac15737104bd072a7ae99babfa9b | 921 | py | Python | IGS-Software-Manager/igs/employee/views.py | anolivei/IGS | ce0415461d47e2675b25fa33ae14be085a01e9a7 | [
"MIT"
] | null | null | null | IGS-Software-Manager/igs/employee/views.py | anolivei/IGS | ce0415461d47e2675b25fa33ae14be085a01e9a7 | [
"MIT"
] | null | null | null | IGS-Software-Manager/igs/employee/views.py | anolivei/IGS | ce0415461d47e2675b25fa33ae14be085a01e9a7 | [
"MIT"
] | null | null | null | from rest_framework import viewsets, generics
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from django.db.models.functions import Lower
from igs.employee.models import Employee
from igs.employee.serializers import EmployeeSerializer
class EmployeeViewSet(viewsets.ModelViewSet):
"""Lists all employees ordered by id"""
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
http_method_names = ['get', 'post', 'put', 'path', 'delete']
authentication_classes = [BasicAuthentication]
permission_classes = [IsAuthenticated]
class Employee(generics.ListAPIView):
"""Lists all employees ordered by name"""
queryset = Employee.objects.all().order_by(Lower("name"))
serializer_class = EmployeeSerializer
authentication_classes = [BasicAuthentication]
permission_classes = [IsAuthenticated]
| 36.84 | 64 | 0.783931 | 95 | 921 | 7.473684 | 0.463158 | 0.033803 | 0.071831 | 0.067606 | 0.276056 | 0.202817 | 0 | 0 | 0 | 0 | 0 | 0 | 0.131379 | 921 | 24 | 65 | 38.375 | 0.8875 | 0.074919 | 0 | 0.352941 | 0 | 0 | 0.028537 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.352941 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
4ac9cb55aec05451141c0c5425a601054eed08ff | 2,754 | py | Python | Automaten/Python/nka_terme.py | jneug/schule-projekte | 4f1d56d6bb74a47ca019cf96d2d6cc89779803c9 | [
"MIT"
] | 2 | 2020-09-24T12:11:16.000Z | 2022-03-31T04:47:24.000Z | Automaten/Python/nka_terme.py | jneug/schule-projekte | 4f1d56d6bb74a47ca019cf96d2d6cc89779803c9 | [
"MIT"
] | 1 | 2021-02-27T15:06:27.000Z | 2021-03-01T16:32:48.000Z | Automaten/Python/nka_terme.py | jneug/schule-projekte | 4f1d56d6bb74a47ca019cf96d2d6cc89779803c9 | [
"MIT"
] | 1 | 2021-02-24T05:12:35.000Z | 2021-02-24T05:12:35.000Z | def transition(state, char, stack_char):
new_state = -1
new_stack_chars = ""
if state == 0:
new_state = 1
new_stack_chars = "S#"
elif state == 1:
if stack_char in "0123456789+-*:().":
new_state = 1
new_stack_chars = ""
elif stack_char == "S":
if char in "123456789":
new_state = 1
new_stack_chars = "A"
elif char == "0":
new_state = 1
new_stack_chars = "B"
elif char == "(":
new_state = 1
new_stack_chars = "E)R"
elif stack_char == "A":
if char in "0123456789":
new_state = 1
new_stack_chars = "A"
elif char == ".":
new_state = 1
new_stack_chars = "C"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "B":
if char == ".":
new_state = 1
new_stack_chars = "C"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "C":
if char in "0123456789":
new_state = 1
new_stack_chars = "D"
elif stack_char == "D":
if char in "0123456789":
new_state = 1
new_stack_chars = "D"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "E":
if char in "123456789":
new_state = 1
new_stack_chars = "A"
elif char == "0":
new_state = 1
new_stack_chars = "B"
elif char == "(":
new_state = 1
new_stack_chars = "E)R"
elif stack_char == "R":
if char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif char == "":
new_state = 2
elif stack_char == "#":
new_state = 2
return new_state, new_stack_chars
def scan_word(word):
state = 0
stack = ["#"]
for char in word:
stack_char = stack.pop(0)
state, stack_chars = transition(state, char, stack_char)
for sc in reversed(stack_chars):
stack.insert(0, sc)
if len(stack) > 0:
transition(state, "", stack[0])
return word == "" and state == 2
if __name__ == "__main__":
word = input("Bitte ein Wort eingeben: ")
accepted = scan_word(word)
if accepted:
print("Wort gehört zur Sprache")
else:
print("Wort gehört nicht zur Sprache")
| 28.391753 | 64 | 0.444808 | 308 | 2,754 | 3.707792 | 0.149351 | 0.14711 | 0.216287 | 0.189142 | 0.638354 | 0.59282 | 0.59282 | 0.549912 | 0.549912 | 0.512259 | 0 | 0.057971 | 0.448802 | 2,754 | 96 | 65 | 28.6875 | 0.694335 | 0 | 0 | 0.564706 | 0 | 0 | 0.073348 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.023529 | false | 0 | 0 | 0 | 0.047059 | 0.023529 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4ad0e4888299834dea0c51a8f223fb7ecd2f113f | 1,651 | py | Python | tensorflow/lite/python/metrics_wrapper/metrics_wrapper.py | ashutom/tensorflow-upstream | c16069c19de9e286dd664abb78d0ea421e9f32d4 | [
"Apache-2.0"
] | 8 | 2021-08-03T03:57:10.000Z | 2021-12-13T01:19:02.000Z | tensorflow/lite/python/metrics_wrapper/metrics_wrapper.py | ashutom/tensorflow-upstream | c16069c19de9e286dd664abb78d0ea421e9f32d4 | [
"Apache-2.0"
] | 17 | 2021-08-12T19:38:42.000Z | 2022-01-27T14:39:35.000Z | tensorflow/lite/python/metrics_wrapper/metrics_wrapper.py | ashutom/tensorflow-upstream | c16069c19de9e286dd664abb78d0ea421e9f32d4 | [
"Apache-2.0"
] | 4 | 2022-01-13T11:23:44.000Z | 2022-03-02T11:11:42.000Z | # Lint as: python2, python3
# Copyright 2021 The TensorFlow 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.
# ==============================================================================
"""Stub to make pywrap metrics wrapper accessible."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.lite.python import wrap_toco
from tensorflow.lite.python.metrics_wrapper import converter_error_data_pb2
from tensorflow.lite.python.metrics_wrapper._pywrap_tensorflow_lite_metrics_wrapper import MetricsWrapper # pylint: disable=unused-import
def retrieve_collected_errors():
"""Returns and clears the list of collected errors in ErrorCollector.
The RetrieveCollectedErrors function in C++ returns a list of serialized proto
messages. This function will convert them to ConverterErrorData instances.
Returns:
A list of ConverterErrorData.
"""
serialized_message_list = wrap_toco.wrapped_retrieve_collected_errors()
return list(
map(converter_error_data_pb2.ConverterErrorData.FromString,
serialized_message_list))
| 41.275 | 138 | 0.758934 | 214 | 1,651 | 5.67757 | 0.546729 | 0.049383 | 0.039506 | 0.059259 | 0.062551 | 0.062551 | 0 | 0 | 0 | 0 | 0 | 0.008445 | 0.13931 | 1,651 | 39 | 139 | 42.333333 | 0.846587 | 0.623259 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0.545455 | 0 | 0.727273 | 0.090909 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
4ad1555125c18acaa949e91152e7bf7c6301ba7e | 1,826 | py | Python | test/test_output_handlers.py | aappl/reg-mapper | 6ab2e78ae7e6298e55a7dab23987d7c892011cf5 | [
"Apache-2.0"
] | null | null | null | test/test_output_handlers.py | aappl/reg-mapper | 6ab2e78ae7e6298e55a7dab23987d7c892011cf5 | [
"Apache-2.0"
] | 1 | 2021-06-02T00:32:45.000Z | 2021-06-02T00:32:45.000Z | test/test_output_handlers.py | aappl/reg-mapper | 6ab2e78ae7e6298e55a7dab23987d7c892011cf5 | [
"Apache-2.0"
] | 1 | 2019-05-12T08:43:13.000Z | 2019-05-12T08:43:13.000Z | from pathlib import Path
from context import reg_mapper
from reg_mapper import output_handlers
import test_utils
def test_output_files(tmpdir):
system = test_utils.create_test_object()
config = {
"outputs": ["vhdl"],
"vhdl": {
"output_path": tmpdir,
},
"c": {
"output_path": tmpdir
}
}
output_handlers.output_files(config, system)
filename = system.register_maps[0].name + ".vhd"
output_file = tmpdir / filename
assert output_file.exists()
with open(output_file, 'r') as f:
assert f.read() == """package test_map is
constant test_register0 : integer := 0;
constant test_register0_test_register0_bit_map0_0 : integer := 0;
constant test_register0_test_register0_bit_map0_1 : integer := 1;
constant test_register0_test_register0_bit_map0_2 : integer := 2;
constant test_register0_test_register0_bit_map0_3 : integer := 3;
constant test_register0_test_register0_bit_map1_0 : integer := 4;
constant test_register0_test_register0_bit_map1_1 : integer := 5;
constant test_register0_test_register0_bit_map1_2 : integer := 6;
constant test_register0_test_register0_bit_map1_3 : integer := 7;
constant test_register1 : integer := 1;
constant test_register1_test_register1_bit_map0_0 : integer := 0;
constant test_register1_test_register1_bit_map0_1 : integer := 1;
constant test_register1_test_register1_bit_map0_2 : integer := 2;
constant test_register1_test_register1_bit_map0_3 : integer := 3;
constant test_register1_test_register1_bit_map1_0 : integer := 4;
constant test_register1_test_register1_bit_map1_1 : integer := 5;
constant test_register1_test_register1_bit_map1_2 : integer := 6;
constant test_register1_test_register1_bit_map1_3 : integer := 7;
end package test_map;
"""
| 36.52 | 67 | 0.745893 | 249 | 1,826 | 5 | 0.216867 | 0.173494 | 0.151807 | 0.160643 | 0.655422 | 0.640964 | 0.640964 | 0.15743 | 0.15743 | 0 | 0 | 0.056441 | 0.175246 | 1,826 | 49 | 68 | 37.265306 | 0.770252 | 0 | 0 | 0 | 0 | 0 | 0.690033 | 0.350493 | 0 | 0 | 0 | 0 | 0.04878 | 1 | 0.02439 | false | 0 | 0.097561 | 0 | 0.121951 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4ad8c4b3786d95f3f0ba8ed98f3daea4d42a247d | 1,376 | py | Python | rpy2_arrow/r6b.py | paleolimbot/rpy2-arrow | 162842e27046a6802ce650a8268a1b61c68ce51c | [
"MIT"
] | 10 | 2021-07-05T22:54:11.000Z | 2022-02-14T14:25:42.000Z | rpy2_arrow/r6b.py | paleolimbot/rpy2-arrow | 162842e27046a6802ce650a8268a1b61c68ce51c | [
"MIT"
] | 3 | 2021-12-06T20:34:47.000Z | 2022-01-25T12:11:38.000Z | rpy2_arrow/r6b.py | paleolimbot/rpy2-arrow | 162842e27046a6802ce650a8268a1b61c68ce51c | [
"MIT"
] | 1 | 2022-01-05T12:31:27.000Z | 2022-01-05T12:31:27.000Z | import rpy2_R6.r6b as r6b
import rpy2_arrow.pyarrow_rarrow as pyr
import rpy2.rinterface as rinterface
import rpy2.robjects
import rpy2.robjects.conversion
# Python proxies for the R6 class factories
array_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.Array)
recordbatch_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.RecordBatch)
chunkedarray_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.ChunkedArray)
schema_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.Schema)
table_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.Table)
# Conversion functions and rules
converter = rpy2.robjects.conversion.Converter(
'R6b conversion for pyarrow/arrow',
template=rpy2.robjects.default_converter
)
def rpy2py_array(obj):
return array_factory.__R6CLASS__(obj)
def rpy2py_recordbatch(obj):
return recordbatch_factory.__R6CLASS__(obj)
def rpy2py_chunkedarray(obj):
return chunkedarray_factory.__R6CLASS__(obj)
def rpy2py_schema(obj):
return schema_factory.__R6CLASS__(obj)
def rpy2py_table(obj):
return table_factory.__R6CLASS__(obj)
(converter.rpy2py_nc_name[rinterface.SexpEnvironment]
.update({
'Array': array_factory.__R6CLASS__,
'ChunkedArray': chunkedarray_factory.__R6CLASS__,
'RecordBatch': recordbatch_factory.__R6CLASS__,
'Table': table_factory.__R6CLASS__,
'Schema': schema_factory.__R6CLASS__
}))
| 27.52 | 75 | 0.802326 | 158 | 1,376 | 6.56962 | 0.253165 | 0.134875 | 0.15896 | 0.17341 | 0.302505 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031148 | 0.113372 | 1,376 | 49 | 76 | 28.081633 | 0.819672 | 0.052326 | 0 | 0 | 0 | 0 | 0.054573 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.15625 | false | 0 | 0.15625 | 0.15625 | 0.46875 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
4adb45806142c20964298f84829088cba0684df7 | 248 | py | Python | notice/utils/email.py | myl7/conus | 6eb2c9ee55c45d8b9c7f9de0e5998f94954b1a4e | [
"MIT"
] | null | null | null | notice/utils/email.py | myl7/conus | 6eb2c9ee55c45d8b9c7f9de0e5998f94954b1a4e | [
"MIT"
] | null | null | null | notice/utils/email.py | myl7/conus | 6eb2c9ee55c45d8b9c7f9de0e5998f94954b1a4e | [
"MIT"
] | null | null | null | from django.core.mail import send_mass_mail
def notify_email(users, notice):
title = f'{notice.title if notice.title else "无标题"} | conus 通知推送'
send_mass_mail([(title, notice.body, None, user) for user in users if user.contactinfo.email])
| 35.428571 | 98 | 0.737903 | 40 | 248 | 4.45 | 0.625 | 0.185393 | 0.134831 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.149194 | 248 | 6 | 99 | 41.333333 | 0.843602 | 0 | 0 | 0 | 0 | 0 | 0.217742 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4af5e0dcff679f79b7393b5512f3f37bdbb5c8e8 | 22,004 | py | Python | VTJM.py | Ltango/VTJM | 064b545b3100d2493ac90811bce3a93324111179 | [
"MIT"
] | 1 | 2019-01-07T20:40:08.000Z | 2019-01-07T20:40:08.000Z | VTJM.py | Ltango/VTJM | 064b545b3100d2493ac90811bce3a93324111179 | [
"MIT"
] | null | null | null | VTJM.py | Ltango/VTJM | 064b545b3100d2493ac90811bce3a93324111179 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import getpass
import requests
from jira import JIRA
import re
import base64
import hashlib
import hmac
import uuid
import datetime
import urllib2
import ssl
import time
import json
from threading import _BoundedSemaphore as BoundedSemaphore, Timer
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
from pyvirtualdisplay import Display
from bs4 import BeautifulSoup
import email
import os
#pip install selenium, requests, jira, bs4, pyvirtualdisplay
#need to install chrome web driver
#For testing purposes
enable_Jira_Actions = True
#VT's acceptable level of positive hits on a URL
#Using 2 because it gets all angry about google
ACCEPTABLE_CLEAN_VALUE = 1
regexString = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
#hyperlinkString = r"""<a +href="(.+?)" *>"""
NumberOfMaxResults = 200
#This is our Rate Limiting Class - we use it to make sure that we don't send too many requests to virus total. There is additional
#Handling in the VTCheck() method that looks for 204s (which mean you need to wait to send more requests) so the program won't crash
class RatedSemaphore(BoundedSemaphore):
#Limit to 1 request per `period / value` seconds (over long run).
def __init__(self, value=1, period=1):
BoundedSemaphore.__init__(self, value)
t = Timer(period, self._add_token_loop,
kwargs=dict(time_delta=float(period) / value))
t.daemon = True
t.start()
def _add_token_loop(self, time_delta):
#Add token every time_delta seconds.
while True:
try:
BoundedSemaphore.release(self)
except ValueError: # ignore if already max possible value
pass
time.sleep(time_delta) # ignore EINTR
def release(self):
pass # do nothing (only time-based release() is allowed)
rate_limit = RatedSemaphore(4, 61)
#Here we utilize a regular expression string in an attempt to find all possible URL combinations in any string
def get_all_URLS_in_text(text):
urlList = list()
hyperlinkList = list()
reconstructedHyperlinkList = list()
urlList = re.findall(regexString, text)
# hyperlinkList = re.findall(hyperlinkString, text)
hyperlinkList = parseHTMLforLinks(text)
if hyperlinkList:
print 'Found ' + str(len(hyperlinkList)) + ' Hyperlinks'
#print '\nHYPERLINKS FOUND:\n' + str(hyperlinkList)
try:
#print hyperlinkList[0]
for link in hyperlinkList:
if link.startswith('3D'):
link = link[3:-1]
elif link.startswith('"'):
link = link[1:-1]
#print link
reconstructedHyperlinkList.append(str(link))
#print 'reconstructed hyperlinks: ' + reconstructedHyperlinkList
except:
pass
#print urlList
urlList.extend(reconstructedHyperlinkList)
#print urlList
return urlList
def parseHTMLforLinks(text):
soup = BeautifulSoup(text, 'html.parser')
hyperlinkList = list()
for link in soup.find_all('a'):
hyperlinkList.append(link.get('href'))
return hyperlinkList
#Our Virus Total API check method, we check to see if there is already a report for the URL inserted - and since 'scan' is set to '1'
#We will request the URL to be scanned if it hasn't been already. If we get a 204 response or the report hasn't been generated yet
#We will make another call to this function in our main method after waiting 15 seconds.
def VTCheck(URL):
malwareCount = 0
totalCount = 0
headers = {
"Accept-Encoding": "gzip, deflate","User-Agent" : "gzip, My Python requests library example client or username"}
params = {'apikey': VTAPIToken, 'resource':URL, 'scan':'1'}
#response = requests.post('https://www.virustotal.com/vtapi/v2/url/report', params=params, headers = headers)
with rate_limit, requests.post('https://www.virustotal.com/vtapi/v2/url/report', params=params, headers = headers) as response:
if response.status_code == 204:
return['recheck',0,0]
try:
json_response = response.json()
except:
return ['Unable to find URL report',0,0]
waitCheck = json_response['verbose_msg']
if waitCheck == 'Scan request successfully queued, come back later for the report':
return['recheck',0,0]
#if VT screws up (main module picks up on 0 total checks from VT)
try:
malwareCount = json_response['positives']
totalCount = json_response['total']
scanID = json_response['scan_id']
#print malwareCount, totalCount, scanID
except:
return ['Unable to find URL report',0,0]
if totalCount == 0:
return ['Unable to find URL report',0,0]
if malwareCount <= ACCEPTABLE_CLEAN_VALUE:
#print 'URL: ' + URL + ' is CLEAN!\n'
return ['CLEAN',malwareCount,totalCount]
else:
#print 'URL: ' + URL + ' is Possible Malware!\n'
return ['Possible Malware', malwareCount, totalCount]
def initializeChromeWebDriver():
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
#options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(options=options, executable_path=r'/usr/bin/chromedriver')
driver.get("http://google.com/")
print ("Headless Chrome Initialized")
return driver
# options = webdriver.ChromeOptions()
# options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
# chrome_driver_binary = "/usr/local/bin/chromedriver"
# driver = webdriver.Chrome(chrome_driver_binary, chrome_options=options)
def JiraGetTickets():
jql = 'labels = "~Potential_Malware_Phishing~" AND status != "RESOLVED"'
return jira.search_issues(jql, maxResults = NumberOfMaxResults)
#######################################################MAIN METHOD####################################################################
if __name__ == "__main__":
if enable_Jira_Actions:
print 'JIRA ACTIONS WILL TAKE PLACE ON TARGETTED ISSUES'
else:
print 'JIRA ACTIONS WILL NOT TAKE PLACE - CHANGE VARIABLE enable_Jira_Actions TO TRUE TO ENABLE'
JiraUserName = raw_input("user?")
JiraPassword = getpass.getpass("password?")
while True:
try:
ticketResolveCount = 0
start_time = time.time()
display = Display(visible=0, size=(800, 600))
display.start()
jira = JIRA(basic_auth=(JiraUserName, JiraPassword), options = {'server': 'https://jira.company.com'})
JiraTicketObjects = JiraGetTickets()
numberOfTicketsToResolve = len(JiraTicketObjects)
print 'Number of tickets to resolve: ' + str(numberOfTicketsToResolve)
ticketCount = 0
driver = initializeChromeWebDriver()
for ticket in JiraTicketObjects:
print("---Current Execution Time: %s Seconds ---" % round(time.time() - start_time, 2))
specialMimecastMessageFound = False
URL_FOUND = False
URL_BLOCKED = False
jiraBeforeMessage = ''
jiraMessage = ''
jiraAfterMessage = ''
jiraStartMessage = ''
dirtyMark = 0
#THIS SEEMS REDUNDANT BUT ISSUES NEED TO BE LOOKED UP THIS WAY OR THEY WILL NOT HAVE ATTACHMENTS IN THEIR FIELDS
issue = jira.issue(ticket.key)
#TODO REMOVE
#issue = jira.issue('SD-79299', expand="attachment")
ticketCount += 1
print '(' + str(ticketCount) + '/' + str(numberOfTicketsToResolve) + ')[' + str(ticketResolveCount) + ']resolved\nNow working on... ' + issue.key
jiraBeforeMessage = "This is an automated message.\n\n"
jiraStartMessage += "==========VIRUS TOTAL WAS ABLE TO FIND THE FOLLOWING URLs==========\n\n"
jiraEndMessage = ''
URL_List = list()
Email_list = list()
textField = issue.fields.description
textField = textField.replace('|',' ')
URL_List.extend(get_all_URLS_in_text(textField))
comments = jira.comments(issue.key)
skipIssue = False
for comment in comments:
#print comment.author.name
if comment.author.name == 'ltang':
skipIssue = True
break
if skipIssue == True:
print '\nalready commented for this issue - skipping\n'
numberOfTicketsToResolve -= 1
ticketCount -= 1
continue
try:
attachments = issue.fields.attachment
for attachment in attachments:
print("Name: '{filename}', size: {size}".format(filename=attachment.filename, size=attachment.size))
#print("\n\nContent: '{}'\n\n".format(attachment.get()))
if attachment.filename.endswith('.eml'):
print 'found .eml file!'
#print '\n\n\n ' + str(attachment) + ' \n\n\n'
#print '\n\n\n ' + str(attachment.raw) + ' \n\n\n'
#print '\n\nattachment:\n\n' + str(type(attachment))
data = attachment.get()
#with open('/tmp/Issue1_CA_JCD_6585.png', 'wb') as f:
# f.write(image)
#print '\n\ndata:\n\n' + str(type(data))
#TODO DELETE
#print 'PREPARSE\n\n' + data
data = data.replace('=\r\n', '')
#print 'IMPORTANT PARSE\n\n' + data
data = data.replace('\n', '').replace('\r', '')
#print 'AFTER PARSE\n\n' + data
attachmentURLS = get_all_URLS_in_text(data)
URL_List.extend(attachmentURLS)
except:
print 'no attachments found'
#removes duplicates
URL_List = list(set(URL_List))
tempList = list()
#print '\nPotential URLs found:\n\n' + str(URL_List) + '\n\n'
for URL in URL_List:
if not URL.lower().endswith('outlook.com') and not URL.lower().startswith('http://www.w3.org') and not URL.lower().endswith('.png') and not URL.lower().endswith('.jpg') and not URL.lower().endswith('.gif'):
#OUR CHROME DRIVER IS SO GOOD AND SO MUCH BETTER THAN URLLIB2 THAT WERE NOT GOING TO USE IT
"""
try:
#get redirect URL
context = ssl._create_unverified_context()
req = urllib2.Request(URL)
res = urllib2.urlopen(req, context = context)
finalurl = res.geturl()
print ' URL after redirect\n ' + finalurl
tempList.append(finalurl)
except Exception as e: print('failed urllib2')
try:
#try with requests module
r = requests.get(URL)
print ' requests redirect option:\n ' + r.url
tempList.append(r.url)
print ' requests history option:\n ' + r.history
except Exception as e: print('failed requests')
"""
try:
#try with chrome driver module
driver.get(URL)
print 'URL Before redirect: ' + URL
print 'Driver redirect option: ' + driver.current_url
try:
req = requests.head(driver.current_url, verify=False)
print 'Code: ' + str(req.status_code)
except Exception as e:
#print e
pass
else:
if not (str(req.status_code) == 404 or str(req.status_code) == 301):
print 'Adding:: ' + driver.current_url
jiraEndMessage += 'Dead Link: ' + driver.current_url + '\n'
tempList.append(driver.current_url)
except Exception as e: print('Invalid URL: ' + URL)
URL_List = tempList
URL_List = list(set(URL_List))
print '\nFinal URL list has been compiled:'
#print str(URL_List) + '\n\n'
print 'Found ' + str(len(URL_List)) + ' potential URLs\n'
for URL in URL_List:
URL_FOUND = True
VTreport = ["",0,0]
AlreadyBlocked = False
#WE FOUND A BLOCKED URL THROUGH MIMECAST! HUZZAH!!!
if URL.startswith('MIMECAST BLOCK URL'):
URL_BLOCKED = True
jiraBeforeMessage += 'This link has already been blocked by Mimecast:\n' + URL + '\n\n'
continue
#WE FOUND A BLOCKED URL THROUGH UMBRELLA?! HUZZAH!!! (This requires further testing)
elif URL.startswith('OTHER BLOCK URL'):
URL_BLOCKED = True
jiraBeforeMessage += 'This link has already been blocked by OTHER.\n' + URL + '\n\n'
continue
elif URL.startswith('ANOTHER OTHER BLOCK URL'):
URL_BLOCKED = True
jiraBeforeMessage += 'This link has already been blocked by ANOTHER OTHER.\n' + URL + '\n\n'
continue
#I DON'T THINK WE WILL NEED THIS - CHROME DRIVER AUTO RESOLVES TO EITHER BLOCKED OR UNBLOCKED URL
elif URL.startswith('MIMECAST URL'):
print URL + "\nFound dead mimecast URL\n"
jiraEndMessage += ' Dead mimecast link:\n' + URL + '\n\n'
URL_BLOCKED = True
#dirtyMark += 1
# durl = mimecastCheckURL(URL)
# if durl is blocked:
# jiraMessage += 'URL: ' + durl + '(' + URL + ')' + ' has been blocked by mimecast.\n'
# else:
#pass
#skip google
elif URL == 'https://www.google.com/':
continue
elif URL.startswith('MIMECAST RELEASE URL'):
specialMimecastMessageFound = True
#SKIP OUT ON THIS CRAP THAT WE DON'T NEED TO CHECK
elif URL == 'picutreurl' or URL == 'pictureurl':
continue
else:
print 'SCANNING URL: ' + URL
#We are going to continually look for the URL report from VT every 15 seconds until it gives it to us
#If the report doesn't exist yet we automatically ask for VT to make a scan report of the URL
expireCount = 0
while True:
try:
VTreport = VTCheck(URL)
except:
print 'failed VTCheck for ' + URL
jiraEndMessage += 'This URL should be manuallly checked, virustotal could not find anything:\n' + URL + '\n'
break
if not VTreport[0] == 'recheck':
break
time.sleep(15)
expireCount += 1
if expireCount > 5:
print 'failed VTCheck for ' + URL
jiraEndMessage += 'This URL should be manuallly checked, virustotal could not find anything:\n' + URL + '\n'
break
#print VTreport
if VTreport[2] == 0: #total checks is zero somehow
jiraEndMessage += 'This URL should be manuallly checked, virustotal could not find anything:\n' + URL + '\n'
dirtyMark += 1
else:
VTmessage = 'Virus Total Check Results:\n'+ URL +'\n' + str(VTreport[0]) + '\n' + str(VTreport[1]) + ' out of ' + str(VTreport[2]) + ' flagged as malware\n\n'
print VTmessage
jiraMessage += VTmessage
#We mark the issue with a dirtyMark for everytime VT finds a malicious link
if VTreport[0] == 'Possible Malware':
dirtyMark += 1
jiraMessage += "\n=====VIRUS TOTAL WAS NOT ABLE TO FIND ANYTHING FOR THE URLs BELOW=====\n\n"
jiraMessage = jiraBeforeMessage + jiraStartMessage + jiraMessage + jiraEndMessage
if dirtyMark == 0 and URL_FOUND:
#ASSIGN ISSUE TO WHOEVER RAN THE SCRIPT and RESOLVE THE TICKET
#HAD TO EXCHANGE THIS - SOME TICKETS ARE BEING CLOSED B/C VT DID NOT PICK UP ON PHISH SITE
#if enable_Jira_Actions
if enable_Jira_Actions and (URL_BLOCKED or specialMimecastMessageFound):
print 'completely clear - closing ticket'
jira.assign_issue(issue, JiraUserName)
#sleep to make sure the assign change goes through and we can find the resolve issue id
time.sleep(5)
transitions = jira.transitions(issue)
#print [(t['id'], t['name']) for t in transitions]
for t in transitions:
if t['name'] == 'Resolve Issue':
id = t['id']
#print id
continue
try:
jira.transition_issue(issue, id)
except:
time.sleep(1)
try:
jira.transition_issue(issue, id)
except:
print 'ERROR JIRA WAS UNABLE TO FINISH RESOLVING: ' + issue.key
jira.add_comment(issue = issue.key, body = 'automation was unable to resolve this issue for unknown reasons', is_internal = True)
jiraMessage += 'This ticket has been parsed as clean and can be resolved - recommended manually checking links for phishing attempts if left unresolved'
#INTERNAL COMMENT and INCREMENT RESOLVE COUNT
print '\n\n----------BEGIN INTERNAL JIRA MESSAGE----------\n\n' + jiraMessage + '\n\n----------END INTERNAL JIRA MESSAGE----------\n\n'
#HAD TO EXCHANGE THIS - SOME TICKETS ARE BEING CLOSED B/C VT DID NOT PICK UP ON PHISH SITE
#if enable_Jira_Actions:
if enable_Jira_Actions and (URL_BLOCKED or specialMimecastMessageFound):
jira.add_comment(issue = issue.key, body = jiraMessage, is_internal = True)
ticketResolveCount += 1
#print 'Resolved ' + str(ticketResolveCount) + ' tickets so far...'
print 'du-du-du ... ANOTHER TICKET BITES THE DUST!!!'
#EXTERNAL COMMENT for A BLOCKED URL HAS BEEN FOUND
if URL_BLOCKED:
externalComment = 'This is an automated message.\n\nThank you reporting this. Our security systems identified the link or attachment as malicious and has blocked it. Please go ahead and delete the email.\n\nThank you for helping keep Company secure.'
print '\n\n----------BEGIN JIRA MESSAGE----------\n\n' + externalComment + '\n\n----------END JIRA MESSAGE----------\n\n'
if enable_Jira_Actions:
jira.add_comment(issue = issue.key, body = externalComment)
#EXTERNAL COMMENT for NO BLOCKED URLs FOUND and NOTHING BAD FOUND BY VIRUS TOTAL
#else:
#HAD TO EXCHANGE THIS - SOME TICKETS ARE BEING CLOSED B/C VT DID NOT PICK UP ON PHISH SITE
if specialMimecastMessageFound == True:
if specialMimecastMessageFound == True:
externalComment = 'This is an automated message.\n\nThis is a legitimate system generated email notification from Company’s email security system called Mimecast. This system detects and protects you against harmful emails. This system also detects emails that are not necessarily malicious but may be unwanted ‘spam’.\nMimecast will send daily digests three times throughout the day with information about emails that it suspects are unwanted ‘spam’ for your review. Communications from Mimecast will come from a Postmaster email address and allow you to see a list of emails that you can choose to release, block, or permit.\n• Release = releases the message to come into your inbox\n• Block = adds the sender to your personal blocked senders list and blocks the message and future messages from this sender to your inbox\n• Permit = adds the sender to your personal allow list and releases the message and future messages from this sender to your inbox\n'
else:
externalComment = 'This is an automated message.\n\nThe email you reported does not appear to have any malicious links or attachments. You should first check to see if this is a legitimate email as all links have been cleared by the security team.\n\nOtherwise this may either be spam or junk email. Due to this there is limited activities that we could do for these but you can block the sender on your end if you like. Open up the email and in the upper left click "Junk" then click on "Block Sender".'
print '\n\n----------BEGIN JIRA MESSAGE----------\n\n' + externalComment + '\n\n----------END JIRA MESSAGE----------\n\n'
if enable_Jira_Actions:
jira.add_comment(issue = issue.key, body = externalComment)
#NO URL FOUND internal comment: MANUAL INVESTIGATION MESSAGE
elif not URL_FOUND:
print 'No URL\'s found'
jiraMessage = "No URL's were found automatically, manual investigation is advised."
print '\n\n----------BEGIN INTERNAL JIRA MESSAGE----------\n\n' + jiraMessage + '\n\n----------END INTERNAL JIRA MESSAGE----------\n\n'
if enable_Jira_Actions:
jira.add_comment(issue = issue.key, body = jiraMessage, is_internal = True)
#BAD URLs FOUND internal comment MANUAL INVESTIGATION MESSAGE
else:
print 'This could be dangerous'
jiraMessage += 'This ticket will require manual interaction before closing'
print '\n\n----------BEGIN INTERNAL JIRA MESSAGE----------\n\n' + jiraMessage + '\n\n----------END INTERNAL JIRA MESSAGE----------\n\n'
if enable_Jira_Actions:
jira.add_comment(issue = issue.key, body = jiraMessage, is_internal = True)
#close out our long lost and forgotten driver and display
driver.quit()
display.stop()
print 'chrome driver has properly quit'
print 'resolved ' + str(ticketResolveCount) + ' out of ' + str(numberOfTicketsToResolve) + ' tickets (' + str(ticketResolveCount/numberOfTicketsToResolve) + '%)\n\n'
print("---Total Execution Time: %s Seconds ---" % round(time.time() - start_time, 2))
except:
time.sleep(60)
#for capatcha
#https://jira.company.com/login.jsp
| 45.182752 | 2,010 | 0.673105 | 3,240 | 22,004 | 4.525617 | 0.276543 | 0.006274 | 0.012753 | 0.008866 | 0.281866 | 0.265566 | 0.233172 | 0.2181 | 0.2181 | 0.210394 | 0 | 0.006869 | 0.186239 | 22,004 | 486 | 2,011 | 45.27572 | 0.811739 | 0.20928 | 0 | 0.283388 | 0 | 0.026059 | 0.410845 | 0.135861 | 0 | 0 | 0 | 0.002058 | 0 | 0 | null | null | 0.022801 | 0.074919 | null | null | 0.117264 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ab02b00715a39ce44c9883a7f016679fe1662c5c | 402 | py | Python | softhub/views/UserUpdate.py | davcri/softhub | 5a932da36d1393c361b1940283d468692fe57d9d | [
"MIT"
] | 1 | 2018-05-05T20:01:15.000Z | 2018-05-05T20:01:15.000Z | softhub/views/UserUpdate.py | davcri/softhub | 5a932da36d1393c361b1940283d468692fe57d9d | [
"MIT"
] | 2 | 2021-03-18T20:16:53.000Z | 2021-06-08T19:09:15.000Z | softhub/views/UserUpdate.py | davcri/softhub | 5a932da36d1393c361b1940283d468692fe57d9d | [
"MIT"
] | 2 | 2017-05-10T22:33:39.000Z | 2018-01-30T14:05:06.000Z | from django.views.generic import UpdateView
from django.urls import reverse
from softhub.models.User import User
from softhub.views.UserForm import UserForm
class UserUpdate(UpdateView):
model = User
template_name = 'registration/user_update.html'
# form_class = UserForm
fields = ['username', 'email']
def get_success_url(self):
return reverse('softhub:user_profile')
| 23.647059 | 51 | 0.743781 | 50 | 402 | 5.86 | 0.62 | 0.068259 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.171642 | 402 | 16 | 52 | 25.125 | 0.87988 | 0.052239 | 0 | 0 | 0 | 0 | 0.163588 | 0.076517 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1 | false | 0 | 0.4 | 0.1 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
ab16cd9d9496d027a3ff25f67074d38293593598 | 421 | py | Python | hood_watch/forms.py | JuneMuoti/Hood-watch | 2659a0a0b4025e4cbb9680f1de078de7801f46b9 | [
"MIT"
] | null | null | null | hood_watch/forms.py | JuneMuoti/Hood-watch | 2659a0a0b4025e4cbb9680f1de078de7801f46b9 | [
"MIT"
] | null | null | null | hood_watch/forms.py | JuneMuoti/Hood-watch | 2659a0a0b4025e4cbb9680f1de078de7801f46b9 | [
"MIT"
] | null | null | null | from .models import User,Post
from django import forms
class ProfileForm(forms.ModelForm):
class Meta:
model = User
exclude = []
widgets = {}
class PostForm(forms.ModelForm):
class Meta:
model = Post
exclude = []
widgets = {}
class HoodForm(ProfileForm):
class Meta:
model=User
fields=[
'hood','user_id'
]
widgets={}
| 21.05 | 35 | 0.551069 | 41 | 421 | 5.634146 | 0.463415 | 0.116883 | 0.181818 | 0.199134 | 0.242424 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.349169 | 421 | 19 | 36 | 22.157895 | 0.843066 | 0 | 0 | 0.526316 | 0 | 0 | 0.026128 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.105263 | 0 | 0.421053 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ab2d0650a50c995cf0205b9072cf99f20625ab3a | 7,909 | py | Python | announcer/opt/acct_mgr/announce.py | dokipen/trac-announcer-plugin | 7ef4123a7508c5395c8008fa2a8478b1888b4f63 | [
"BSD-3-Clause"
] | null | null | null | announcer/opt/acct_mgr/announce.py | dokipen/trac-announcer-plugin | 7ef4123a7508c5395c8008fa2a8478b1888b4f63 | [
"BSD-3-Clause"
] | 1 | 2018-06-11T14:48:06.000Z | 2018-06-11T14:48:06.000Z | announcer/opt/acct_mgr/announce.py | dokipen/trac-announcer-plugin | 7ef4123a7508c5395c8008fa2a8478b1888b4f63 | [
"BSD-3-Clause"
] | null | null | null | #-*- coding: utf-8 -*-
#
# Copyright (c) 2010, Robert Corsaro
# Copyright (c) 2010, Steffen Hoffmann
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <ORGANIZATION> nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from trac.core import *
from trac.web.chrome import Chrome
from genshi.template import NewTextTemplate, TemplateLoader
from announcer.api import AnnouncementSystem, AnnouncementEvent
from announcer.api import IAnnouncementFormatter, IAnnouncementSubscriber
from announcer.api import IAnnouncementPreferenceProvider
from announcer.api import _
from announcer.distributors.mail import IAnnouncementEmailDecorator
from announcer.util.mail import set_header, next_decorator
from announcer.util.settings import BoolSubscriptionSetting
from acct_mgr.api import IAccountChangeListener
class AccountChangeEvent(AnnouncementEvent):
def __init__(self, category, username, password=None, token=None):
AnnouncementEvent.__init__(self, 'acct_mgr', category, None)
self.username = username
self.password = password
self.token = token
class AccountManagerAnnouncement(Component):
"""Send announcements on account changes."""
implements(
IAccountChangeListener,
IAnnouncementSubscriber,
IAnnouncementFormatter,
IAnnouncementEmailDecorator,
IAnnouncementPreferenceProvider
)
# IAccountChangeListener interface
def user_created(self, username, password):
self._notify('created', username, password)
def user_password_changed(self, username, password):
self._notify('change', username, password)
def user_deleted(self, username):
self._notify('delete', username)
def user_password_reset(self, username, email, password):
self._notify('reset', username, password)
def user_email_verification_requested(self, username, token):
self._notify('verify', username, token=token)
# IAnnouncementSubscriber interface
def subscriptions(self, event):
if event.realm == 'acct_mgr':
for subscriber in self._get_membership(event):
self.log.debug("AccountManagerAnnouncement added '%s " \
"(%s)'", subscriber[1], subscriber[2])
yield subscriber
# IAnnouncementFormatter interface
def styles(self, transport, realm):
if realm == 'acct_mgr':
yield 'text/plain'
def alternative_style_for(self, transport, realm, style):
if realm == 'acct_mgr' and style != 'text/plain':
return 'text/plain'
def format(self, transport, realm, style, event):
if realm == 'acct_mgr' and style == 'text/plain':
return self._format_plaintext(event)
# IAnnouncementEmailDecorator
def decorate_message(self, event, message, decorates=None):
if event.realm == "acct_mgr":
prjname = self.env.project_name
subject = '[%s] %s: %s' % (prjname, event.category, event.username)
set_header(message, 'Subject', subject)
return next_decorator(event, message, decorates)
# IAnnouncementPreferenceProvider interface
def get_announcement_preference_boxes(self, req):
if req.authname == "anonymous" and 'email' not in req.session:
return
yield "acct_mgr_subscription", _("Account Manager Subscription")
def render_announcement_preference_box(self, req, panel):
settings = self._settings()
if req.method == "POST":
for k, setting in settings.items():
setting.set_user_setting(req.session,
value=req.args.get('acct_mgr_%s_subscription'%k),
save=False)
req.session.save()
data = {}
for k, setting in settings.items():
data[k] = setting.get_user_setting(req.session.sid)[1]
return "prefs_announcer_acct_mgr_subscription.html", data
# private methods
def _notify(self, category, username, password=None, token=None):
try:
announcer = AnnouncementSystem(self.env)
announcer.send(
AccountChangeEvent(category, username, password, token)
)
except Exception, e:
self.log.exception("Failure creating announcement for account "
"event %s: %s", username, category)
def _settings(self):
ret = {}
for n in ('created', 'change', 'delete'):
ret[n] = BoolSubscriptionSetting(self.env, "acct_mgr_%s"%n, None)
return ret
def _get_membership(self, event):
settings = self._settings()
if event.category in settings.keys():
for result in settings[event.category].get_subscriptions():
yield result
elif event.category in ('verify', 'reset'):
yield ('email', event.username, True, None)
def _format_plaintext(self, event):
acct_templates = {
'created': 'acct_mgr_user_change_plaintext.txt',
'change': 'acct_mgr_user_change_plaintext.txt',
'delete': 'acct_mgr_user_change_plaintext.txt',
'reset': 'acct_mgr_reset_password_plaintext.txt',
'verify': 'acct_mgr_verify_plaintext.txt'
}
data = {
'account': {
'action': event.category,
'username': event.username,
'password': event.password,
'token': event.token
},
'project': {
'name': self.env.project_name,
'url': self.env.abs_href(),
'descr': self.env.project_description
},
'login': {
'link': self.env.abs_href.login()
}
}
if event.category == 'verify':
data['verify'] = {
'link': self.env.abs_href.verify_email(token=event.token)
}
chrome = Chrome(self.env)
dirs = []
for provider in chrome.template_providers:
dirs += provider.get_templates_dirs()
templates = TemplateLoader(dirs, variable_lookup='lenient')
template = templates.load(acct_templates[event.category],
cls=NewTextTemplate)
if template:
stream = template.generate(**data)
output = stream.render('text')
return output
| 40.979275 | 79 | 0.64787 | 846 | 7,909 | 5.933806 | 0.325059 | 0.022311 | 0.011952 | 0.01753 | 0.122112 | 0.085857 | 0.058167 | 0.041833 | 0.041833 | 0.027092 | 0 | 0.002034 | 0.253888 | 7,909 | 192 | 80 | 41.192708 | 0.84867 | 0.232899 | 0 | 0.030303 | 0 | 0 | 0.116605 | 0.046943 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.090909 | 0.083333 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
ab2e920b0e8043fe4419bfed85ef69f6159eb81c | 217 | py | Python | apps/requestlogger/urls.py | commtrack/commtrack-old-to-del | cc9c22754ac192a45483cef609bdcf09aa990340 | [
"BSD-3-Clause"
] | 1 | 2017-05-19T07:23:00.000Z | 2017-05-19T07:23:00.000Z | apps/requestlogger/urls.py | commtrack/commtrack-old-to-del | cc9c22754ac192a45483cef609bdcf09aa990340 | [
"BSD-3-Clause"
] | null | null | null | apps/requestlogger/urls.py | commtrack/commtrack-old-to-del | cc9c22754ac192a45483cef609bdcf09aa990340 | [
"BSD-3-Clause"
] | null | null | null | from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^requestlog/?$', 'requestlogger.views.list'),
(r'^requestlog/demo/?$', 'requestlogger.views.demo'),
)
| 27.125 | 61 | 0.557604 | 19 | 217 | 6.368421 | 0.736842 | 0.181818 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.262673 | 217 | 7 | 62 | 31 | 0.75625 | 0 | 0 | 0 | 0 | 0 | 0.373272 | 0.221198 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.2 | 0 | 0.2 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ab3acc04aa5795fa97e5ee8582b00a7d30c5ad25 | 949 | py | Python | api/application/__init__.py | gerardovitale/covid-project | b4e28e8ee095070f2a2433f61725fd8c0374365e | [
"MIT"
] | null | null | null | api/application/__init__.py | gerardovitale/covid-project | b4e28e8ee095070f2a2433f61725fd8c0374365e | [
"MIT"
] | null | null | null | api/application/__init__.py | gerardovitale/covid-project | b4e28e8ee095070f2a2433f61725fd8c0374365e | [
"MIT"
] | null | null | null | from flask import Flask
from application.config.Config import DevelopmentConfig, Config
from application.controllers.home_controller import home_bp
from application.controllers.covid_summary_controller import covid_summary_bp
from application.controllers.covid_new_cases_controller import covid_new_cases_bp
from application.controllers.covid_new_deaths_controller import covid_new_deaths_bp
from application.controllers.vaccination_summary import vaccination_bp
def init_app(config: Config):
app = Flask(
__name__,
template_folder=config.TEMPLATE_FOLDER,
static_folder=config.STATIC_FOLDER,
)
app.config.from_object(config)
with app.app_context():
app.register_blueprint(home_bp)
app.register_blueprint(covid_summary_bp)
app.register_blueprint(covid_new_cases_bp)
app.register_blueprint(covid_new_deaths_bp)
app.register_blueprint(vaccination_bp)
return app
| 39.541667 | 83 | 0.800843 | 120 | 949 | 5.95 | 0.241667 | 0.12605 | 0.182073 | 0.156863 | 0.268908 | 0.184874 | 0 | 0 | 0 | 0 | 0 | 0 | 0.14647 | 949 | 23 | 84 | 41.26087 | 0.881481 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.047619 | false | 0 | 0.333333 | 0 | 0.428571 | 0.238095 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
ab455fff64bfa6c27f7aeb9078b0580aaf8dfd37 | 1,670 | py | Python | redis_sessions/settings.py | ReznikovRoman/django-redis-sessions | c52e37fed3174deddca6cf59c33551ead3d513d3 | [
"BSD-3-Clause"
] | null | null | null | redis_sessions/settings.py | ReznikovRoman/django-redis-sessions | c52e37fed3174deddca6cf59c33551ead3d513d3 | [
"BSD-3-Clause"
] | null | null | null | redis_sessions/settings.py | ReznikovRoman/django-redis-sessions | c52e37fed3174deddca6cf59c33551ead3d513d3 | [
"BSD-3-Clause"
] | null | null | null | from django.conf import settings
# SESSION_REDIS - Default
SESSION_REDIS = getattr(settings, 'SESSION_REDIS', {})
SESSION_REDIS_CONNECTION_OBJECT = getattr(settings, 'SESSION_REDIS_CONNECTION_OBJECT', None)
SESSION_REDIS_HOST = SESSION_REDIS.get('host', 'localhost')
SESSION_REDIS_PORT = SESSION_REDIS.get('port', 6379)
SESSION_REDIS_SOCKET_TIMEOUT = SESSION_REDIS.get('socket_timeout', 0.1)
SESSION_REDIS_RETRY_ON_TIMEOUT = SESSION_REDIS.get('retry_on_timeout', False)
SESSION_REDIS_DB = SESSION_REDIS.get('db', 0)
SESSION_REDIS_PREFIX = SESSION_REDIS.get('prefix', '')
SESSION_REDIS_PASSWORD = SESSION_REDIS.get('password', None)
SESSION_REDIS_UNIX_DOMAIN_SOCKET_PATH = SESSION_REDIS.get('unix_domain_socket_path', None)
SESSION_REDIS_URL = SESSION_REDIS.get('url', None)
"""
Should be on the format:
[
{
'host': 'localhost2',
'port': 6379,
'db': 0,
'password': None,
'unix_domain_socket_path': None,
'url': None,
'weight': 1,
},
{
'host': 'localhost1',
'port': 6379,
'db': 0,
'password': None,
'unix_domain_socket_path': None,
'url': None,
'weight': 1,
},
]
"""
SESSION_REDIS_POOL = SESSION_REDIS.get('POOL', None)
# should be on the format [(host, port), (host, port), (host, port)]
SESSION_REDIS_SENTINEL_LIST = getattr(settings, 'SESSION_REDIS_SENTINEL_LIST', None)
SESSION_REDIS_SENTINEL_MASTER_ALIAS = getattr(settings, 'SESSION_REDIS_SENTINEL_MASTER_ALIAS', None)
SESSION_REDIS_USE_SSL = getattr(settings, 'SESSION_REDIS_USE_SSL', False)
SESSION_REDIS_SSL_CA_CERT_PATH = getattr(settings, 'SESSION_REDIS_SSL_CA_CERT_PATH', None)
| 35.531915 | 100 | 0.716168 | 217 | 1,670 | 5.110599 | 0.21659 | 0.357078 | 0.135257 | 0.146078 | 0.32642 | 0.203787 | 0.158702 | 0.110009 | 0.110009 | 0.110009 | 0 | 0.014925 | 0.157485 | 1,670 | 46 | 101 | 36.304348 | 0.773276 | 0.053892 | 0 | 0 | 0 | 0 | 0.215703 | 0.14409 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.058824 | 0.058824 | 0 | 0.058824 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
ab48963d939babd70913515b4fd2bbfc0016b496 | 404 | py | Python | tests/deepImpute_test.py | granatumx/gbox-deepimpute | 4f4190435387ef96fdad5f88a4209e2cd7112612 | [
"MIT"
] | 1 | 2021-12-24T19:41:03.000Z | 2021-12-24T19:41:03.000Z | g_packages/deepImpute2/docker/tests/deepImpute_test.py | lanagarmire/granatumx | 3dee3a8fb2ba851c31a9f6338aef1817217769f9 | [
"MIT"
] | 16 | 2020-01-28T23:03:40.000Z | 2022-02-10T00:30:16.000Z | g_packages/deepImpute2/docker/tests/deepImpute_test.py | lanagarmire/granatumx | 3dee3a8fb2ba851c31a9f6338aef1817217769f9 | [
"MIT"
] | 3 | 2020-06-24T22:44:17.000Z | 2021-11-08T19:29:09.000Z | import unittest
import test_data
from deepimpute.deepImpute import deepImpute
# test sending data transposed
class TestDeepImpute(unittest.TestCase):
""" """
def test_all(self):
_ = deepImpute(test_data.rawData, ncores=4, NN_lim=1000)
def test_minExpressionLevel(self):
_ = deepImpute(test_data.rawData, ncores=4, minVMR=1)
if __name__ == "__main__":
unittest.main()
| 19.238095 | 64 | 0.715347 | 48 | 404 | 5.6875 | 0.541667 | 0.087912 | 0.131868 | 0.161172 | 0.263736 | 0.263736 | 0.263736 | 0 | 0 | 0 | 0 | 0.021148 | 0.180693 | 404 | 20 | 65 | 20.2 | 0.803625 | 0.069307 | 0 | 0 | 0 | 0 | 0.021798 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.3 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
ab513a2410089fd96a821b595d564d8941a35a82 | 1,210 | py | Python | src/appengine/handlers/report_csp_failure.py | mi-ac/clusterfuzz | 0b5c023eca9e3aac41faba17da8f341c0ca2ddc7 | [
"Apache-2.0"
] | 1 | 2021-12-20T14:48:42.000Z | 2021-12-20T14:48:42.000Z | src/appengine/handlers/report_csp_failure.py | mi-ac/clusterfuzz | 0b5c023eca9e3aac41faba17da8f341c0ca2ddc7 | [
"Apache-2.0"
] | 2 | 2021-09-28T05:36:03.000Z | 2021-12-13T20:48:34.000Z | src/appengine/handlers/report_csp_failure.py | mi-ac/clusterfuzz | 0b5c023eca9e3aac41faba17da8f341c0ca2ddc7 | [
"Apache-2.0"
] | 1 | 2021-09-27T20:06:07.000Z | 2021-09-27T20:06:07.000Z | # Copyright 2019 Google LLC
#
# 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.
"""Log incoming reports of CSP violations."""
from flask import request
from handlers import base_handler
from libs import handler
from libs import helpers
from metrics import logs
class ReportCspFailureHandler(base_handler.Handler):
"""Log failures on HTML pages caused by CSP."""
@handler.post(handler.JSON, handler.JSON)
@handler.check_user_access(need_privileged_access=False)
def post(self):
"""Handle a POST request."""
report = request.get('csp-report')
if not report:
raise helpers.EarlyExitException('No CSP report.', 400)
logs.log_error('CSP violation: {}'.format(report))
return 'OK'
| 32.702703 | 74 | 0.747107 | 175 | 1,210 | 5.125714 | 0.617143 | 0.06689 | 0.028986 | 0.035674 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010902 | 0.166116 | 1,210 | 36 | 75 | 33.611111 | 0.878097 | 0.540496 | 0 | 0 | 0 | 0 | 0.081439 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.071429 | false | 0 | 0.357143 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
ab60c06fd8cae5155bba5804f312e7a6d0636211 | 3,338 | py | Python | nlplingo/tasks/eventargument/example.py | BBN-E/nlplingo | 32ff17b1320937faa3d3ebe727032f4b3e7a353d | [
"Apache-2.0"
] | 3 | 2020-10-22T13:28:00.000Z | 2022-03-24T19:57:22.000Z | nlplingo/tasks/eventargument/example.py | BBN-E/nlplingo | 32ff17b1320937faa3d3ebe727032f4b3e7a353d | [
"Apache-2.0"
] | null | null | null | nlplingo/tasks/eventargument/example.py | BBN-E/nlplingo | 32ff17b1320937faa3d3ebe727032f4b3e7a353d | [
"Apache-2.0"
] | 1 | 2020-10-22T13:29:51.000Z | 2020-10-22T13:29:51.000Z |
import numpy as np
from nlplingo.tasks.common.binary.binary_event_entity import BinaryEventEntity
from nlplingo.common.data_types import int_type
class EventArgumentExample(BinaryEventEntity):
def __init__(self, arg0, arg1, event_domain, label_str):
# def __init__(self, anchor, argument, sentence, event_domain, extractor_params, features, hyper_params, event_role=None, usable_features=None):
"""We are given an anchor, candidate argument, sentence as context, and a role label (absent in decoding)
:type anchor: nlplingo.text.text_span.Anchor
:type argument: nlplingo.text.text_span.EntityMention
:type sentence: nlplingo.text.text_span.Sentence
:type event_domain: nlplingo.event.event_domain.EventDomain
:type extractor_params: dict
:type features: nlplingo.tasks.eventargument.feature.EventArgumentFeature
:type hyper_params: nlplingo.nn.extractor.HyperParameters
:type event_role: str
"""
super(EventArgumentExample, self).__init__(arg0, arg1, event_domain, label_str)
num_labels = len(self.event_domain.event_roles)
self.label = np.zeros(num_labels, dtype=int_type)
# vec_size = extractor_params['embeddings']['vector_size']
# anchor_datapoint = EventDatapoint(
# anchor, event_domain, vec_size, anchor.label, usable_features)
#argument_datapoint = EntityDatapoint(
# argument, event_domain, vec_size, argument.label, usable_features)
#super(EventArgumentExample, self).__init__(
# anchor_datapoint, argument_datapoint,
# event_domain, features, event_role, usable_features)
# self.sentence = sentence
# self.anchor_obj = None
# if 'none_token_index' in extractor_params['embeddings']:
# none_token_index = extractor_params['embeddings']['none_token_index']
# else:
# none_token_index = 1
#self._allocate_arrays(hyper_params,
# extractor_params['embeddings']['vector_size'],
# none_token_index,
# features)
@property
def event_role(self):
""":rtype: str"""
return self.label_str
@event_role.setter
def event_role(self, label):
""":type label: str"""
self.label_str = label
@property
def anchor(self):
""":rtype: nlplingo.text.text_span.Anchor"""
return self.arg0.span
@property
def argument(self):
""":rtype: nlplingo.text.text_span.EventArgument"""
return self.arg1.span
"""
@argument.setter
def argument(self, argument):
:type argument: nlplingo.text.text_span.EventArgument
argument_datapoint = EntityDatapoint(
argument, self.event_domain, self.argument.embedding_vector_size,
argument.label, usable_features)
self.right_datapoint = argument_datapoint
"""
def get_event_role_index(self):
"""
+1
"""
return self.event_domain.get_event_role_index(self.event_role)
def to_triplet_with_relation(self):
# This can only be used for within-sentence relations.
triplet = self.to_triplet()
triplet.update({'relation' : self.event_role})
return triplet | 38.367816 | 148 | 0.663271 | 370 | 3,338 | 5.702703 | 0.267568 | 0.057346 | 0.045498 | 0.056872 | 0.230332 | 0.120379 | 0 | 0 | 0 | 0 | 0 | 0.003163 | 0.242361 | 3,338 | 87 | 149 | 38.367816 | 0.831159 | 0.477232 | 0 | 0.115385 | 0 | 0 | 0.006364 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.269231 | false | 0 | 0.115385 | 0 | 0.615385 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
ab61998ce63ae09c01a85d1a72e5d74744d3e173 | 498 | py | Python | tests/factories.py | seik/django-belt | 0a214a04332184bc1736fe344b0bf54d1590f9c4 | [
"MIT"
] | null | null | null | tests/factories.py | seik/django-belt | 0a214a04332184bc1736fe344b0bf54d1590f9c4 | [
"MIT"
] | null | null | null | tests/factories.py | seik/django-belt | 0a214a04332184bc1736fe344b0bf54d1590f9c4 | [
"MIT"
] | null | null | null | from factory import DjangoModelFactory
from factory.fuzzy import FuzzyText
from tests.app.models import Post, Category, Blog
from factory.declarations import SubFactory
class BlogFactory(DjangoModelFactory):
class Meta:
model = Blog
class PostFactory(DjangoModelFactory):
blog = SubFactory(BlogFactory)
title = FuzzyText()
content = FuzzyText()
class Meta:
model = Post
class CategoryFactory(DjangoModelFactory):
class Meta:
model = Category
| 19.92 | 49 | 0.730924 | 50 | 498 | 7.28 | 0.44 | 0.090659 | 0.115385 | 0.175824 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.208835 | 498 | 24 | 50 | 20.75 | 0.923858 | 0 | 0 | 0.1875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.8125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
db444d34d3b48c6dbb516d5c23e38c08d092ad78 | 3,741 | py | Python | runway/core/providers/aws/_response.py | troyready/runway | 4fd299961a4b73df39e14f4f19a7236f7be17dd8 | [
"Apache-2.0"
] | null | null | null | runway/core/providers/aws/_response.py | troyready/runway | 4fd299961a4b73df39e14f4f19a7236f7be17dd8 | [
"Apache-2.0"
] | null | null | null | runway/core/providers/aws/_response.py | troyready/runway | 4fd299961a4b73df39e14f4f19a7236f7be17dd8 | [
"Apache-2.0"
] | null | null | null | """Base class for AWS responses."""
from typing import Any, Dict, Union # pylint: disable=W
from ....http_backport import HTTPStatus
class ResponseError(object): # pylint: disable=too-few-public-methods
"""Analyse the response from AWS S3 HeadBucket API response.
Attributes:
code (str): A unique short code representing the error that was emitted.
message (str): A longer human readable error message.
"""
def __init__(self, **kwargs):
# type: (str) -> None
"""Instantiate class.
Keyword Args:
Code (str): A unique short code representing the error that was emitted.
Message (str): A longer human readable error message.
"""
self.code = kwargs.get("Code", "")
self.message = kwargs.get("Message", "")
def __bool__(self):
# type: () -> bool
"""Implement evaluation of instances as a bool."""
return bool(self.code or self.message)
__nonzero__ = __bool__ # python2 compatability
class ResponseMetadata(object):
"""Analyse the response from AWS S3 HeadBucket API response.
Attributes:
host_id (Optional[str]): Host ID data.
https_headers (Dict[str, Any]): A map of response header keys and
their respective values.
http_status_code (int): The HTTP status code of the response (e.g., 200, 404).
request_id (Optional[str]): The unique request ID associated with the response.
Log this value when debugging requests for AWS support.
retry_attempts (int): The number of retries that were attempted
before the request was completed.
"""
def __init__(self, **kwargs):
# type: (Union[int, None, str]) -> None
"""Instantiate class.
Keyword Args:
HostId (str): Host ID data.
HTTPHeaders (Dict[str, Any]): A map of response header keys and
their respective values.
HTTPStatusCode (int): The HTTP status code of the response
(e.g., 200, 404).
RequestId (str): The unique request ID associated with the response.
Log this value when debugging requests for AWS support.
RetryAttempts (int): The number of retries that were attempted
before the request was completed.
"""
self.host_id = kwargs.get("HostId")
self.https_headers = kwargs.get("HTTPHeaders", {})
self.http_status_code = kwargs.get("HTTPStatusCode", 200)
self.request_id = kwargs.get("RequestId")
self.retry_attempts = kwargs.get("RetryAttempts", 0)
@property
def forbidden(self):
# type: () -> bool
"""Whether the response returned 403 (forbidden)."""
return self.http_status_code == HTTPStatus.FORBIDDEN
@property
def not_found(self):
# type: () -> bool
"""Whether the response returned 404 (Not Found)."""
return self.http_status_code == HTTPStatus.NOT_FOUND
class BaseResponse(object): # pylint: disable=too-few-public-methods
"""Analyse the response from AWS S3 HeadBucket API response.
Attributes:
error (ResponseError): Information about a service or networking error.
metadata (ResponseMetadata): Information about the request.
"""
def __init__(self, **kwargs):
# type: (Dict[str, Any]) -> None
"""Instantiate class.
Keyword Args:
Error: Information about a service or networking error.
ResponseMetadata: Information about the request.
"""
self.error = ResponseError(**kwargs.pop("Error", {}))
self.metadata = ResponseMetadata(**kwargs.pop("ResponseMetadata", {}))
| 35.292453 | 87 | 0.627907 | 433 | 3,741 | 5.325635 | 0.284065 | 0.042931 | 0.036427 | 0.028621 | 0.621856 | 0.544666 | 0.48569 | 0.417173 | 0.417173 | 0.417173 | 0 | 0.009541 | 0.271585 | 3,741 | 105 | 88 | 35.628571 | 0.836697 | 0.593424 | 0 | 0.192308 | 0 | 0 | 0.069388 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.230769 | false | 0 | 0.076923 | 0 | 0.576923 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
db4ff8e6bf9bd177e85c3cca00ef98657ca15f1b | 767 | py | Python | src/kernel/testdata/repo/oopl/python/demo/cards2_test/.DeckTest.py | metaesque/meta | c3e6413ca6cc6ff5456158b128070b36baf2d36a | [
"AML",
"TCL",
"Ruby"
] | null | null | null | src/kernel/testdata/repo/oopl/python/demo/cards2_test/.DeckTest.py | metaesque/meta | c3e6413ca6cc6ff5456158b128070b36baf2d36a | [
"AML",
"TCL",
"Ruby"
] | 1 | 2018-10-30T03:14:34.000Z | 2018-10-30T03:19:35.000Z | src/kernel/testdata/repo/oopl/python/demo/cards2_test/.DeckTest.py | metaesque/meta | c3e6413ca6cc6ff5456158b128070b36baf2d36a | [
"AML",
"TCL",
"Ruby"
] | null | null | null | import demo.cards2 # target=//demo/cards2:cards2
import demo.cards2_test # target=//demo/cards2_test:cards2_test
import demo.cards2_test # target=//demo/cards2_test:cards2_test
########## End Imports ##########
class DeckTest(demo.cards2_test.TestCase):
"""Auto-generated test class for demo.cards2.Deck"""
__metaclass__ = DeckTestMeta
def test_shuffle(self):
"""here"""
import random
random.seed(0)
deck = demo.cards2.FrenchDeck()
deck.shuffle()
self.iseqvec(
[deck.asStr(card) for card in deck.cards()[:10]],
['2H', '4S', 'KD', 'KS', '3D', 'TS', '8D', '6S', '8H', '2D'])
def test_meta(self):
"""here"""
# noop
pass
########## Start Harness ##########
if __name__ == '__main__':
metax.test.main()
| 25.566667 | 67 | 0.612777 | 97 | 767 | 4.628866 | 0.505155 | 0.200445 | 0.155902 | 0.089087 | 0.222717 | 0.222717 | 0.222717 | 0.222717 | 0.222717 | 0.222717 | 0 | 0.034865 | 0.177314 | 767 | 29 | 68 | 26.448276 | 0.676704 | 0.254237 | 0 | 0.117647 | 0 | 0 | 0.054688 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.117647 | false | 0.058824 | 0.235294 | 0 | 0.470588 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
db5994758305014eceb4681623c49021f2cf39c2 | 365 | py | Python | api/models/log.py | thegrowthapp/backend | 37f90822cef9fecb2f0912200fbb2416cd75946c | [
"MIT"
] | 1 | 2018-08-04T07:45:04.000Z | 2018-08-04T07:45:04.000Z | api/models/log.py | jonhue/the_growth_app | 37f90822cef9fecb2f0912200fbb2416cd75946c | [
"MIT"
] | 23 | 2018-07-25T19:06:02.000Z | 2018-09-05T13:15:50.000Z | api/models/log.py | thegrowthapp/backend | 37f90822cef9fecb2f0912200fbb2416cd75946c | [
"MIT"
] | 1 | 2018-08-04T07:45:07.000Z | 2018-08-04T07:45:07.000Z | import datetime as dt
from mongoengine import *
from .log_attachment import LogAttachment
from .user import User
class Log(EmbeddedDocument):
user = ReferenceField(User, required=True)
content = StringField()
attachments = SortedListField(EmbeddedDocumentField(LogAttachment))
created_at = DateTimeField(required=True, default=dt.datetime.now())
| 28.076923 | 72 | 0.780822 | 39 | 365 | 7.25641 | 0.641026 | 0.084806 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.139726 | 365 | 12 | 73 | 30.416667 | 0.901274 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.444444 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
db5c3627c01231243b61c3abde318f77b4d874b7 | 413 | py | Python | CalculationWithDots/Python/src/exceptions.py | timrabl/playground | d94bdc6dc92d65176192169113890bd538700ee9 | [
"MIT"
] | null | null | null | CalculationWithDots/Python/src/exceptions.py | timrabl/playground | d94bdc6dc92d65176192169113890bd538700ee9 | [
"MIT"
] | null | null | null | CalculationWithDots/Python/src/exceptions.py | timrabl/playground | d94bdc6dc92d65176192169113890bd538700ee9 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
""" This is the exceptions file foi the CalculationsWithDots project """
class InvalidName(Exception):
""" Description of InvalidName
This Exception class is raised, if the given name is invalid.
"""
pass
class InvalidCoordinate(Exception):
""" Description of InvalidCoordinate
This Exception class is raised, if the given coordinate is invalid.
"""
pass | 25.8125 | 72 | 0.711864 | 49 | 413 | 6 | 0.510204 | 0.136054 | 0.14966 | 0.136054 | 0.244898 | 0.244898 | 0.244898 | 0.244898 | 0 | 0 | 0 | 0.003058 | 0.208232 | 413 | 16 | 73 | 25.8125 | 0.896024 | 0.670702 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.5 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
db61778a09e4696e5d3e5ab18f2a6bc78b745a71 | 580 | py | Python | base.py | alecperkins/fairdistrict | 3856155d60b3fc582b5f3a9624374bde4a8f12e9 | [
"Unlicense"
] | 1 | 2016-03-08T23:46:53.000Z | 2016-03-08T23:46:53.000Z | base.py | alecperkins/fairdistrict | 3856155d60b3fc582b5f3a9624374bde4a8f12e9 | [
"Unlicense"
] | null | null | null | base.py | alecperkins/fairdistrict | 3856155d60b3fc582b5f3a9624374bde4a8f12e9 | [
"Unlicense"
] | null | null | null | import pymongo
connection = pymongo.Connection()
db = connection.redistrict
def printCount(*args):
if len(args) > 0:
if args[0] % 1000 == 0:
print args[0]
else:
print
print db.districts.count(), 'districts'
print db.blocks.count(), 'blocks'
print db.groups.count(), 'block groups'
print db.counties.count(), 'counties'
print
def ensureBlockIndex():
db.eval('db.blocks.ensureIndex({ state_fips: 1, county_fips: 1, tract: 1, group: 1})')
if __name__ == '__main__':
ensureBlockIndex() | 25.217391 | 90 | 0.601724 | 68 | 580 | 4.985294 | 0.455882 | 0.082596 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.028037 | 0.262069 | 580 | 23 | 91 | 25.217391 | 0.764019 | 0 | 0 | 0.111111 | 0 | 0.055556 | 0.203098 | 0.039587 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.055556 | null | null | 0.444444 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
db6a6671d0df7bb29139eb1f1ea90c59c144f333 | 210 | py | Python | tests/test_msgdb.py | kozalosev/textUtilsBot | 40ee65517768dd29676874aed0b376eb6ffd6c7e | [
"MIT"
] | 6 | 2018-11-12T22:07:20.000Z | 2021-10-11T16:03:51.000Z | tests/test_msgdb.py | kozalosev/textUtilsBot | 40ee65517768dd29676874aed0b376eb6ffd6c7e | [
"MIT"
] | 13 | 2018-03-03T02:13:59.000Z | 2020-07-12T15:16:41.000Z | tests/test_msgdb.py | kozalosev/textUtilsBot | 40ee65517768dd29676874aed0b376eb6ffd6c7e | [
"MIT"
] | 1 | 2020-07-16T07:14:52.000Z | 2020-07-16T07:14:52.000Z | import msgdb
def test_database(tmpdir):
msgdb._mock_database(str(tmpdir.join('messages.db')))
rowid = msgdb.insert("Hello World")
assert rowid == 1
assert msgdb.select(rowid) == "Hello World"
| 23.333333 | 57 | 0.690476 | 28 | 210 | 5.071429 | 0.642857 | 0.140845 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005747 | 0.171429 | 210 | 8 | 58 | 26.25 | 0.810345 | 0 | 0 | 0 | 0 | 0 | 0.157143 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.166667 | false | 0 | 0.166667 | 0 | 0.333333 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
db73e028551d396d9d7e7bdc7a718e9281b2e4e6 | 383 | py | Python | src/travel/context_processors.py | dakrauth/travel | 761605611aba3204ecf826acd0f8bb6bb5f2d23c | [
"MIT"
] | 5 | 2015-02-19T07:29:02.000Z | 2020-05-21T08:00:20.000Z | src/travel/context_processors.py | dakrauth/travel | 761605611aba3204ecf826acd0f8bb6bb5f2d23c | [
"MIT"
] | 4 | 2019-12-07T04:07:01.000Z | 2019-12-11T02:20:37.000Z | src/travel/context_processors.py | dakrauth/travel | 761605611aba3204ecf826acd0f8bb6bb5f2d23c | [
"MIT"
] | 3 | 2017-02-13T09:14:06.000Z | 2020-06-09T15:55:41.000Z | from travel import forms
from travel.models import TravelLog
from django.contrib.sites.models import Site
def _checklist(user):
return TravelLog.objects.checklist(user) if user.is_authenticated else {}
def search(request):
return {
'site': Site.objects.get_current(),
'search_form': forms.SearchForm(),
'checklist': _checklist(request.user)
}
| 23.9375 | 77 | 0.710183 | 46 | 383 | 5.804348 | 0.543478 | 0.074906 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.185379 | 383 | 15 | 78 | 25.533333 | 0.855769 | 0 | 0 | 0 | 0 | 0 | 0.062663 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.181818 | false | 0 | 0.272727 | 0.181818 | 0.636364 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
db799254eeaf7a3b6e96ddb52669f812205c346c | 2,784 | py | Python | app/grandchallenge/verifications/models.py | kaczmarj/grand-challenge.org | 8dc8a2170e51072354f7e94f2a22578805a67b94 | [
"Apache-2.0"
] | null | null | null | app/grandchallenge/verifications/models.py | kaczmarj/grand-challenge.org | 8dc8a2170e51072354f7e94f2a22578805a67b94 | [
"Apache-2.0"
] | null | null | null | app/grandchallenge/verifications/models.py | kaczmarj/grand-challenge.org | 8dc8a2170e51072354f7e94f2a22578805a67b94 | [
"Apache-2.0"
] | null | null | null | from datetime import timedelta
from allauth.account.signals import email_confirmed
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Q
from django.utils.html import format_html
from pyswot import is_academic
from grandchallenge.subdomains.utils import reverse
from grandchallenge.verifications.tokens import (
email_verification_token_generator,
)
def email_is_trusted(*, email):
return is_academic(email)
class Verification(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
user = models.OneToOneField(
get_user_model(), unique=True, on_delete=models.CASCADE
)
email = models.EmailField(blank=True)
email_is_verified = models.BooleanField(default=False, editable=False)
email_verified_at = models.DateTimeField(
blank=True, null=True, editable=False
)
is_verified = models.BooleanField(default=None, null=True, editable=False)
verified_at = models.DateTimeField(blank=True, null=True, editable=False)
def __str__(self):
return f"Verification for {self.user}"
@property
def signup_email(self):
return self.user.email
@property
def signup_email_activated(self):
return self.user.emailaddress_set.filter(
verified=True, email=self.signup_email
).exists()
@property
def signup_email_is_trusted(self):
return self.signup_email_activated and email_is_trusted(
email=self.signup_email
)
@property
def token(self):
return email_verification_token_generator.make_token(self.user)
@property
def verification_url(self):
return reverse("verifications:confirm", kwargs={"token": self.token})
@property
def review_deadline(self):
return self.modified + timedelta(
days=settings.VERIFICATIONS_REVIEW_PERIOD_DAYS
)
@property
def user_info(self):
return format_html(
"<span>{} <br/> {} <br/> {} <br/> {} <br/> {}</span>",
self.user.get_full_name(),
self.user.user_profile.institution,
self.user.user_profile.department,
self.user.user_profile.country,
self.user.user_profile.website,
)
def create_verification(email_address, *_, **__):
if (
email_is_trusted(email=email_address.email)
and not Verification.objects.filter(
Q(user=email_address.user) | Q(email__iexact=email_address.email)
).exists()
):
Verification.objects.create(
user=email_address.user, email=email_address.email
)
email_confirmed.connect(create_verification)
| 29 | 78 | 0.69181 | 328 | 2,784 | 5.64939 | 0.295732 | 0.038856 | 0.030221 | 0.041015 | 0.101457 | 0.063681 | 0.063681 | 0.063681 | 0.063681 | 0.063681 | 0 | 0 | 0.21408 | 2,784 | 95 | 79 | 29.305263 | 0.846892 | 0 | 0 | 0.121622 | 0 | 0.013514 | 0.037716 | 0.007543 | 0 | 0 | 0 | 0 | 0 | 1 | 0.135135 | false | 0 | 0.135135 | 0.121622 | 0.513514 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
db7c63292b6407a4b97f16987db5496ccae83c9f | 4,384 | py | Python | XLEWS_SERVER/xlem/data/xml.py | bopopescu/xlews | 68954dcd30a3e4bcd0bc7b9f4d25d27b605568ef | [
"Apache-2.0"
] | null | null | null | XLEWS_SERVER/xlem/data/xml.py | bopopescu/xlews | 68954dcd30a3e4bcd0bc7b9f4d25d27b605568ef | [
"Apache-2.0"
] | null | null | null | XLEWS_SERVER/xlem/data/xml.py | bopopescu/xlews | 68954dcd30a3e4bcd0bc7b9f4d25d27b605568ef | [
"Apache-2.0"
] | 1 | 2020-07-24T09:59:39.000Z | 2020-07-24T09:59:39.000Z | '''
Created on Mar 9, 2014
@author: mgshow
Copyright 2012-2014 XLEM by Lemansys S.r.l. - ITALY
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 xml.sax
from threading import Thread
class SaxThread(Thread):
def __init__(self, source):
Thread.__init__(self)
self.__source=source
self.__handler=XLemContentHandler(self)
self.__currTagName=""
self.__isFirstTag=True
def getCurrTagName(self):
while self.__handler.isAlive() and self.__currTagName=="":
self.__currTagName=self.__handler.getCurrTagName()
return self.__currTagName
def goToNext(self):
self.__currTagName=""
self.__handler.goToNext()
#s=self.getCurrTagName()
return self.__handler.isAlive()
def close(self):
self.__handler.close()
if(self.isAlive()):
self._stop()
def run(self):
print("SONO PARTITO ALLA GRANDE!")
try:
xml.sax.parse(self.__source, self.__handler, None)
except Exception as err:
print("ERRORE SAX", err)
self.close()
print("SAX THREAD FINITO!")
pass
class XLemContentHandler(xml.sax.ContentHandler):
def __init__(self, sourceThread:Thread):
xml.sax.ContentHandler.__init__(self)
self.__sourceThread=sourceThread
#__currSTATUS='START_ELEMENT'
self.__waitForNext=True
self.__currTagName=""
self.__isAlive=True
def isAlive(self):
return self.__isAlive
def close(self):
self.__isAlive=False
def getCurrTagName(self):
return self.__currTagName
def goToNext(self):
self.__currTagName=""
#print("Sono sul tag:'",self.__currTagName,"' e passo al prossimo!")
self.__waitForNext=False
pass
def startElement(self, name, attrs):
self.__currTagName=""
print("<<'" + name + "'>>")
self.__currTagName=name
self.__waitForNext = True
while self.__isAlive and self.__waitForNext:
pass
self.__currTagName=""
#self.__currTagName=""
#if name == "address":
# print("\tattribute type='" + attrs.getValue("type") + "'")
def endElement(self, name):
print("<</'" + name + "'>>")
self.__currTagName=""
self.__currTagName="/"+name
self.__waitForNext = True
while self.__isAlive and self.__waitForNext:
pass
self.__currTagName=""
def endDocument(self):
print("HANDLER TERMINATO!")
self.__isAlive=False
def characters(self, content):
print("characters '" + content + "'")
class XmlParser(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.__thread=None
self.__exception=None
def geterror(self):
if self.__exception is None:
return ""
return repr(self.__exception)
def open(self, sourceFileName):
try:
source=open(sourceFileName)
self.__thread=SaxThread(source)
self.__thread.start()
return True
except Exception as ex:
self.__exception=ex
return False
pass
def close(self):
self.__thread.close()
print("THREAD CLOSED!")
pass
def currtagname(self):
return self.__thread.getCurrTagName()
def next(self):
return self.__thread.goToNext()
def istag(self,tagName):
return self.currtagname()==tagName
def isclosedtag(self,tagName):
return self.istag("/"+tagName)
def getnexttag(self):
return self.__thread.goToNext()
pass | 25.940828 | 76 | 0.592838 | 450 | 4,384 | 5.5 | 0.337778 | 0.10303 | 0.053737 | 0.036364 | 0.15596 | 0.114747 | 0.114747 | 0.114747 | 0.073535 | 0.073535 | 0 | 0.00559 | 0.306341 | 4,384 | 169 | 77 | 25.940828 | 0.808287 | 0.196624 | 0 | 0.346535 | 0 | 0 | 0.032555 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.227723 | false | 0.069307 | 0.019802 | 0.059406 | 0.405941 | 0.079208 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
db7fd92682d6c42d2756eb8989eda0fe406fe5c1 | 479 | py | Python | Methods/Geometry/Segment/get_end.py | Superomeg4/pyleecan | 2b695b5f39e77475a07aa0ea89489fb0a9659337 | [
"Apache-2.0"
] | 2 | 2020-06-29T13:48:37.000Z | 2021-06-15T07:34:05.000Z | Methods/Geometry/Segment/get_end.py | Superomeg4/pyleecan | 2b695b5f39e77475a07aa0ea89489fb0a9659337 | [
"Apache-2.0"
] | null | null | null | Methods/Geometry/Segment/get_end.py | Superomeg4/pyleecan | 2b695b5f39e77475a07aa0ea89489fb0a9659337 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""@package Methods.Geometry.Segment.get_end
Return the end point of an Segment method
@date Created on Thu Jul 27 13:51:43 2018
@copyright (C) 2015-2016 EOMYS ENGINEERING.
@author pierre_b
@todo unittest it
"""
def get_end(self):
"""Return the end point of the segment
Parameters
----------
self : Segment
A Segment object
Returns
-------
end: complex
End point of the Segment
"""
return self.end
| 18.423077 | 44 | 0.628392 | 67 | 479 | 4.447761 | 0.656716 | 0.080537 | 0.100671 | 0.114094 | 0.228188 | 0 | 0 | 0 | 0 | 0 | 0 | 0.058496 | 0.250522 | 479 | 25 | 45 | 19.16 | 0.771588 | 0.795407 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.04 | 0 | 1 | 0.5 | false | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
db99181edd634d8984b768a50bd9c52d935c650e | 1,403 | py | Python | src/bubot/devices/ThermostatSML1000/lib/ThermostatSML1000.py | businka/bubot_ThermostatSML1000 | 5359effca0c4ee26e63a7c08f183cde9ef02506b | [
"Apache-2.0"
] | null | null | null | src/bubot/devices/ThermostatSML1000/lib/ThermostatSML1000.py | businka/bubot_ThermostatSML1000 | 5359effca0c4ee26e63a7c08f183cde9ef02506b | [
"Apache-2.0"
] | null | null | null | src/bubot/devices/ThermostatSML1000/lib/ThermostatSML1000.py | businka/bubot_ThermostatSML1000 | 5359effca0c4ee26e63a7c08f183cde9ef02506b | [
"Apache-2.0"
] | null | null | null | from aio_modbus_client.ModbusDevice import ModbusDevice
from aio_modbus_client.DataFormatter import DataFormatterInteger
class ThermostatSML1000(ModbusDevice):
file = __file__
def __init__(self, address, protocol, **kwargs):
self.formatter['decimal05'] = FormatterDecimal05
self.formatter['boolean5a'] = FormatterBoolean5a
super().__init__(address, protocol, **kwargs)
pass
class FormatterDecimal05(DataFormatterInteger):
@classmethod
def encode(cls, device, param, value):
return value * 2
# return value.to_bytes(cls.get_register_count(device, param), byteorder=param.get('reg_byteorder', 'big'))
@classmethod
def decode(cls, device, param, value):
return int.from_bytes(value, byteorder=param.get('reg_byteorder', 'big')) / 2
class FormatterBoolean5a(DataFormatterInteger):
@classmethod
def encode(cls, device, param, value):
return 0xA5 if value else 0x5A
# return value.to_bytes(cls.get_register_count(device, param), byteorder=param.get('reg_byteorder', 'big'))
@classmethod
def decode(cls, device, param, value):
value = int.from_bytes(value, byteorder=param.get('reg_byteorder', 'big'))
if value == 0xA5:
return True
elif value == 0x5A:
return False
else:
return Exception('Illegal value {}'.format(value))
| 31.886364 | 115 | 0.683535 | 154 | 1,403 | 6.045455 | 0.337662 | 0.070892 | 0.06015 | 0.081633 | 0.506982 | 0.500537 | 0.500537 | 0.500537 | 0.500537 | 0.360902 | 0 | 0.020739 | 0.209551 | 1,403 | 43 | 116 | 32.627907 | 0.818756 | 0.150392 | 0 | 0.275862 | 0 | 0 | 0.055509 | 0 | 0 | 0 | 0.013457 | 0 | 0 | 1 | 0.172414 | false | 0.034483 | 0.068966 | 0.103448 | 0.586207 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
db9dd56244047b7eaa042b6be812e4e239298667 | 3,213 | py | Python | tests/issues/test_477.py | aaronslaff/hgvs | fa585c18d60e086b94e1b2c80ba4fa1a6d2b626b | [
"Apache-2.0"
] | null | null | null | tests/issues/test_477.py | aaronslaff/hgvs | fa585c18d60e086b94e1b2c80ba4fa1a6d2b626b | [
"Apache-2.0"
] | null | null | null | tests/issues/test_477.py | aaronslaff/hgvs | fa585c18d60e086b94e1b2c80ba4fa1a6d2b626b | [
"Apache-2.0"
] | null | null | null | import pytest
from hgvs.exceptions import HGVSInvalidIntervalError
tests = (
# {"c": "", "g": "", "rs": "" },
# GPHB5, GRCh37 https://www.ncbi.nlm.nih.gov/gene/122876
{"c": "NM_145171.3:c.-63A>G", "g": "NC_000014.8:g.63785599T>C", "rs": "GPHB5/GRCh37/rs1299953722", "ex": HGVSInvalidIntervalError },
{"c": "NM_145171.3:c.-56G>A", "g": "NC_000014.8:g.63785592C>T", "rs": "GPHB5/GRCh37/rs982881702" },
{"c": "NM_145171.3:c.2T>C", "g": "NC_000014.8:g.63784562A>G", "rs": "GPHB5/GRCh37/rs1221379530" },
{"c": "NM_145171.3:c.388A>G", "g": "NC_000014.8:g.63779647T>C", "rs": "GPHB5/GRCh37/rs1380832691" },
{"c": "NM_145171.3:c.*4C>T", "g": "NC_000014.8:g.63779638G>A", "rs": "GPHB5/GRCh37/rs753041439" },
{"c": "NM_145171.3:c.*84A>G", "g": "NC_000014.8:g.63779558T>C", "rs": "GPHB5/GRCh37/rs1204774077" },
{"c": "NM_145171.3:c.*99G>A", "g": "NC_000014.8:g.63779543C>T", "rs": "GPHB5/GRCh37/rs144659601", "ex": HGVSInvalidIntervalError },
# GPHB5, GRCh37 https://www.ncbi.nlm.nih.gov/gene/122876
{"c": "NM_145171.3:c.-63A>G", "g": "NC_000014.9:g.63318885T>C", "rs": "GPHB5/GRCh38/rs1299953722", "ex": HGVSInvalidIntervalError },
{"c": "NM_145171.3:c.-56G>A", "g": "NC_000014.9:g.63318878C>T", "rs": "GPHB5/GRCh38/rs982881702" },
{"c": "NM_145171.3:c.2T>C", "g": "NC_000014.9:g.63317848A>G", "rs": "GPHB5/GRCh38/rs1221379530" },
{"c": "NM_145171.3:c.388A>G", "g": "NC_000014.9:g.63312933T>C", "rs": "GPHB5/GRCh38/rs1380832691" },
{"c": "NM_145171.3:c.*4C>T", "g": "NC_000014.9:g.63312924G>A", "rs": "GPHB5/GRCh38/rs753041439" },
{"c": "NM_145171.3:c.*84A>G", "g": "NC_000014.9:g.63312844T>C", "rs": "GPHB5/GRCh38/rs1204774077" },
{"c": "NM_145171.3:c.*99G>A", "g": "NC_000014.9:g.63312829C>T", "rs": "GPHB5/GRCh38/rs144659601", "ex": HGVSInvalidIntervalError },
# COX6A2 https://www.ncbi.nlm.nih.gov/gene/1339
{"c": "NM_005205.3:c.-106G>A", "g": "NC_000016.10:g.31428431C>T", "rs": "COX6A2/GRCh38/rs1033792906", "ex": HGVSInvalidIntervalError },
{"c": "NM_005205.3:c.-96C>T", "g": "NC_000016.10:g.31428421G>A", "rs": "COX6A2/GRCh38/rs755670336" },
{"c": "NM_005205.3:c.2T>C", "g": "NC_000016.10:g.31428324A>G", "rs": "COX6A2/GRCh38/rs200780049" },
{"c": "NM_005205.3:c.293G>A", "g": "NC_000016.10:g.31427775C>T", "rs": "COX6A2/GRCh38/rs764753905" },
{"c": "NM_005205.3:c.*3C>T", "g": "NC_000016.10:g.31427771G>A", "rs": "COX6A2/GRCh38/rs909673485" },
{"c": "NM_005205.3:c.*42G>C", "g": "NC_000016.10:g.31427732C>G", "rs": "COX6A2/GRCh38/rs375688325" },
{"c": "NM_005205.3:c.*43A>G", "g": "NC_000016.10:g.31427731T>C", "rs": "COX6A2/GRCh38/rs961248971" },
{"c": "NM_005205.3:c.*44G>A", "g": "NC_000016.10:g.31427730C>T", "rs": "COX6A2/GRCh38/rs756406653", "ex": HGVSInvalidIntervalError },
)
@pytest.mark.parametrize("pair", tests, ids=[p["rs"] for p in tests])
def test_pair(parser, am38, pair):
var_c = parser.parse(pair["c"])
var_g = parser.parse(pair["g"])
if "ex" in pair:
with pytest.raises(pair["ex"]):
var_gtoc = am38.g_to_c(var_g, var_c.ac)
else:
var_gtoc = am38.g_to_c(var_g, var_c.ac)
assert pair["c"] == str(var_gtoc)
| 65.571429 | 139 | 0.611267 | 516 | 3,213 | 3.693798 | 0.21124 | 0.034627 | 0.066107 | 0.073452 | 0.475341 | 0.419727 | 0.359391 | 0.346275 | 0.346275 | 0.346275 | 0 | 0.302867 | 0.131653 | 3,213 | 48 | 140 | 66.9375 | 0.380287 | 0.05789 | 0 | 0.055556 | 0 | 0 | 0.545334 | 0.371939 | 0 | 0 | 0 | 0 | 0.027778 | 1 | 0.027778 | false | 0 | 0.055556 | 0 | 0.083333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
db9e992a0a7e7f0abfa533cccdbed59ff172e754 | 5,455 | py | Python | env/Lib/site-packages/autobahn/websocket/test/test_websocket_url.py | AnilCharles96/django_chat_app | 4b90fa90a703fe002e7e305e85c7621db7275d6f | [
"MIT"
] | 1 | 2020-09-09T23:07:49.000Z | 2020-09-09T23:07:49.000Z | env/Lib/site-packages/autobahn/websocket/test/test_websocket_url.py | AnilCharles96/django_chat_app | 4b90fa90a703fe002e7e305e85c7621db7275d6f | [
"MIT"
] | 12 | 2020-06-06T01:22:26.000Z | 2022-03-12T00:13:42.000Z | env/Lib/site-packages/autobahn/websocket/test/test_websocket_url.py | AnilCharles96/django_chat_app | 4b90fa90a703fe002e7e305e85c7621db7275d6f | [
"MIT"
] | 1 | 2020-12-14T07:10:57.000Z | 2020-12-14T07:10:57.000Z | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
from __future__ import absolute_import
import unittest
from autobahn.websocket.util import create_url, parse_url
class TestCreateWsUrl(unittest.TestCase):
def test_create_url01(self):
self.assertEqual(create_url("localhost"), "ws://localhost:80/")
def test_create_url02(self):
self.assertEqual(create_url("localhost", port=8090), "ws://localhost:8090/")
def test_create_url03(self):
self.assertEqual(create_url("localhost", path="ws"), "ws://localhost:80/ws")
def test_create_url04(self):
self.assertEqual(create_url("localhost", path="/ws"), "ws://localhost:80/ws")
def test_create_url05(self):
self.assertEqual(create_url("localhost", path="/ws/foobar"), "ws://localhost:80/ws/foobar")
def test_create_url06(self):
self.assertEqual(create_url("localhost", isSecure=True), "wss://localhost:443/")
def test_create_url07(self):
self.assertEqual(create_url("localhost", isSecure=True, port=443), "wss://localhost:443/")
def test_create_url08(self):
self.assertEqual(create_url("localhost", isSecure=True, port=80), "wss://localhost:80/")
def test_create_url09(self):
self.assertEqual(create_url("localhost", isSecure=True, port=9090, path="ws", params={'foo': 'bar'}), "wss://localhost:9090/ws?foo=bar")
def test_create_url10(self):
wsurl = create_url("localhost", isSecure=True, port=9090, path="ws", params={'foo': 'bar', 'moo': 23})
self.assertTrue(wsurl == "wss://localhost:9090/ws?foo=bar&moo=23" or wsurl == "wss://localhost:9090/ws?moo=23&foo=bar")
def test_create_url11(self):
self.assertEqual(create_url("127.0.0.1", path="ws"), "ws://127.0.0.1:80/ws")
def test_create_url12(self):
self.assertEqual(create_url("62.146.25.34", path="ws"), "ws://62.146.25.34:80/ws")
def test_create_url13(self):
self.assertEqual(create_url("subsub1.sub1.something.com", path="ws"), "ws://subsub1.sub1.something.com:80/ws")
def test_create_url14(self):
self.assertEqual(create_url("::1", path="ws"), "ws://::1:80/ws")
def test_create_url15(self):
self.assertEqual(create_url("0:0:0:0:0:0:0:1", path="ws"), "ws://0:0:0:0:0:0:0:1:80/ws")
class TestParseWsUrl(unittest.TestCase):
# parse_url -> (isSecure, host, port, resource, path, params)
def test_parse_url01(self):
self.assertEqual(parse_url("ws://localhost"), (False, 'localhost', 80, '/', '/', {}))
def test_parse_url02(self):
self.assertEqual(parse_url("ws://localhost:80"), (False, 'localhost', 80, '/', '/', {}))
def test_parse_url03(self):
self.assertEqual(parse_url("wss://localhost"), (True, 'localhost', 443, '/', '/', {}))
def test_parse_url04(self):
self.assertEqual(parse_url("wss://localhost:443"), (True, 'localhost', 443, '/', '/', {}))
def test_parse_url05(self):
self.assertEqual(parse_url("wss://localhost/ws"), (True, 'localhost', 443, '/ws', '/ws', {}))
def test_parse_url06(self):
self.assertEqual(parse_url("wss://localhost/ws?foo=bar"), (True, 'localhost', 443, '/ws?foo=bar', '/ws', {'foo': ['bar']}))
def test_parse_url07(self):
self.assertEqual(parse_url("wss://localhost/ws?foo=bar&moo=23"), (True, 'localhost', 443, '/ws?foo=bar&moo=23', '/ws', {'moo': ['23'], 'foo': ['bar']}))
def test_parse_url08(self):
self.assertEqual(parse_url("wss://localhost/ws?foo=bar&moo=23&moo=44"), (True, 'localhost', 443, '/ws?foo=bar&moo=23&moo=44', '/ws', {'moo': ['23', '44'], 'foo': ['bar']}))
def test_parse_url09(self):
self.assertRaises(Exception, parse_url, "http://localhost")
def test_parse_url10(self):
self.assertRaises(Exception, parse_url, "https://localhost")
def test_parse_url11(self):
self.assertRaises(Exception, parse_url, "http://localhost:80")
def test_parse_url12(self):
self.assertRaises(Exception, parse_url, "http://localhost#frag1")
def test_parse_url13(self):
self.assertRaises(Exception, parse_url, "wss://")
def test_parse_url14(self):
self.assertRaises(Exception, parse_url, "ws://")
| 42.617188 | 180 | 0.656829 | 743 | 5,455 | 4.694482 | 0.228802 | 0.0582 | 0.119839 | 0.100344 | 0.546445 | 0.450401 | 0.312787 | 0.2543 | 0.15195 | 0.116112 | 0 | 0.048123 | 0.150504 | 5,455 | 127 | 181 | 42.952756 | 0.704575 | 0.210082 | 0 | 0 | 0 | 0.015625 | 0.251091 | 0.089675 | 0 | 0 | 0 | 0 | 0.453125 | 1 | 0.453125 | false | 0 | 0.046875 | 0 | 0.53125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
dba5fad0b4a1e51c42a46d415c25271ddec9022a | 292 | py | Python | projects/models.py | Anillab/Personal_Portfolio | 4d8c383a42aadc1f4532a432ff28d37b6513041e | [
"MIT"
] | null | null | null | projects/models.py | Anillab/Personal_Portfolio | 4d8c383a42aadc1f4532a432ff28d37b6513041e | [
"MIT"
] | 5 | 2021-03-19T01:52:13.000Z | 2021-09-22T18:52:17.000Z | projects/models.py | Anillab/Personal_Portfolio | 4d8c383a42aadc1f4532a432ff28d37b6513041e | [
"MIT"
] | null | null | null | from django.db import models
# Create your models here.
class Project(models.Model):
title=models.CharField(max_length=100)
description=models.TextField()
technology=models.TextField()
image=models.FilePathField(path="/img")
def __str__(self):
return self.title
| 24.333333 | 43 | 0.722603 | 36 | 292 | 5.722222 | 0.75 | 0.145631 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012346 | 0.167808 | 292 | 11 | 44 | 26.545455 | 0.835391 | 0.082192 | 0 | 0 | 0 | 0 | 0.015038 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.125 | 0.125 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
dbbe21b4fb280895caad73d76e8b3372a3220f47 | 564 | py | Python | xframes/toolkit/cluster.py | cchayden/xframes | 1656cc69c814bda8132362b3a22f7cdf8a24637f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xframes/toolkit/cluster.py | cchayden/xframes | 1656cc69c814bda8132362b3a22f7cdf8a24637f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | xframes/toolkit/cluster.py | cchayden/xframes | 1656cc69c814bda8132362b3a22f7cdf8a24637f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | from abc import ABCMeta
from xframes.toolkit.model import Model, ModelBuilder
# Models
class ClusterModel(Model):
__metaclass__ = ABCMeta
class KMeansModel(ClusterModel):
"""
KMeans Model
"""
pass
class GaussianMixtureModel(ClusterModel):
"""
Gaussian Mixture Model
"""
pass
# Builders
class ClusterBuilder(ModelBuilder):
__metaclass__ = ABCMeta
class KMeans(ClusterBuilder):
"""
KMeans Builder
"""
pass
class GaussianMixture(ClusterBuilder):
"""
Gaussian Moxture Builder
"""
pass
| 14.1 | 53 | 0.671986 | 49 | 564 | 7.571429 | 0.469388 | 0.086253 | 0.113208 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.241135 | 564 | 39 | 54 | 14.461538 | 0.866822 | 0.163121 | 0 | 0.428571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.285714 | 0.142857 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
dbc01be7f070ca20a7efd8f93b1c157e1082fbd1 | 965 | py | Python | coingecko/models/enums/filter_24h_change.py | kkristof200/py_coingecko | ea289fc738c1b5c077a1ebcb422319527a2545ff | [
"MIT"
] | null | null | null | coingecko/models/enums/filter_24h_change.py | kkristof200/py_coingecko | ea289fc738c1b5c077a1ebcb422319527a2545ff | [
"MIT"
] | null | null | null | coingecko/models/enums/filter_24h_change.py | kkristof200/py_coingecko | ea289fc738c1b5c077a1ebcb422319527a2545ff | [
"MIT"
] | null | null | null | # --------------------------------------------------------------- Imports ---------------------------------------------------------------- #
# System
from enum import Enum
# ---------------------------------------------------------------------------------------------------------------------------------------- #
# --------------------------------------------------------- enum: Filter24hChange -------------------------------------------------------- #
class Filter24hChange(Enum):
ALL = 0
OVER_50 = 1 # > +50%
BETWEEN_10_50 = 2 # +10% to +50%
BETWEEN_0_10 = 3 # 0% to +10%
BETWEEN_MINUS10_0 = 4 # -10% to 0%
BETWEEN_MINUS50_MINUS10 = 5 # -50% to -10%
UNDER_MINUS50 = 7 # < -50%
# ---------------------------------------------------------------------------------------------------------------------------------------- # | 43.863636 | 140 | 0.202073 | 49 | 965 | 3.77551 | 0.469388 | 0.097297 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.062417 | 0.219689 | 965 | 22 | 141 | 43.863636 | 0.183267 | 0.678756 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.111111 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
dbc55f29d5a600e39eae4ef01d9d9c7c03eada76 | 589 | py | Python | Exercicios/ex029.py | HenriqueSOliver/Python_CursoEmVideo | 6a8ab0c0fa3443990fc0bbbd817314065cf4e01b | [
"MIT"
] | 1 | 2021-04-08T19:54:01.000Z | 2021-04-08T19:54:01.000Z | Python (3)/Ex_finalizados/ex029.py | Gafanhoto742/Python-3 | b0a13ec4cf60185af3ed2508fc69188e36415b80 | [
"MIT"
] | null | null | null | Python (3)/Ex_finalizados/ex029.py | Gafanhoto742/Python-3 | b0a13ec4cf60185af3ed2508fc69188e36415b80 | [
"MIT"
] | null | null | null | '''Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.'''
print('-=-' *20)
velocidade = float(input('\033[1mQual é a velocidade atual do carro?\033[m '))
print('-=-' *20)
if velocidade > 80:
print('\033[1;31mMULTADO!\033[m Você excedeu o \033[33mlimite permitido que é 80 Km/h.\033[m')
multa = (velocidade -80 ) * 7
print ('Você deve pagar uma \033[1;31mmulta de R${:.2f}\033[m'.format(multa))
print('Tenha um bom dia! Dirija com segurança!') | 65.444444 | 191 | 0.691002 | 102 | 589 | 3.990196 | 0.598039 | 0.039312 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.101215 | 0.16129 | 589 | 9 | 192 | 65.444444 | 0.722672 | 0.314092 | 0 | 0.25 | 0 | 0.125 | 0.58396 | 0.06015 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.625 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
dbc832451958ac3103d55389bdc7888a9b3cbe9e | 1,210 | gyp | Python | packages/lib-node/lib/binding.gyp | ton-actions/ton-client-js | 988d335f8f3f706466d6bc944a5410ec412a7f74 | [
"Apache-2.0"
] | null | null | null | packages/lib-node/lib/binding.gyp | ton-actions/ton-client-js | 988d335f8f3f706466d6bc944a5410ec412a7f74 | [
"Apache-2.0"
] | null | null | null | packages/lib-node/lib/binding.gyp | ton-actions/ton-client-js | 988d335f8f3f706466d6bc944a5410ec412a7f74 | [
"Apache-2.0"
] | null | null | null | {
'variables': {
'base_cflags': [
'-Wall',
'-Wextra',
'-Wno-unused-parameter',
'-std=c++11',
],
'debug_cflags': ['-g', '-O0'],
'release_cflags': ['-O3'],
},
'targets': [
{
'target_name': 'tonclient',
'sources': ['binding.cc'],
'conditions': [
['OS == "win"', {
'libraries': [
'../tonclient.lib',
'advapi32.lib',
'ws2_32.lib',
'userenv.lib',
'shell32.lib',
'Secur32.lib',
'Crypt32.lib',
],
}, {
'libraries': [
'../libtonclient.a',
'-Wl,-rpath,./addon/'
],
}],
],
'configurations': {
'Debug': {
'cflags': ['<@(debug_cflags)'],
'xcode_settings': {
'OTHER_CFLAGS': ['<@(debug_cflags)'],
},
},
'Release': {
'cflags': ['<@(release_cflags)'],
'xcode_settings': {
'OTHER_CFLAGS': ['<@(release_cflags)'],
},
},
},
'cflags': ['<@(base_cflags)'],
'xcode_settings': {
'OTHER_CFLAGS': ['<@(base_cflags)'],
},
},
],
}
| 22 | 51 | 0.375207 | 80 | 1,210 | 5.4625 | 0.55 | 0.100687 | 0.130435 | 0.16476 | 0.20595 | 0 | 0 | 0 | 0 | 0 | 0 | 0.020747 | 0.402479 | 1,210 | 54 | 52 | 22.407407 | 0.583679 | 0 | 0 | 0.185185 | 0 | 0 | 0.428099 | 0.017355 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
dbdb722bfe4e508c9a8aa3844902722519592fe9 | 367 | py | Python | gmusicapi/__init__.py | maxjoehnk/gmusicapi | 94e0d898aa2b978032bb0a25e5504011424639f9 | [
"BSD-3-Clause"
] | 1,621 | 2015-06-21T15:52:54.000Z | 2022-03-21T23:09:32.000Z | gmusicapi/__init__.py | maxjoehnk/gmusicapi | 94e0d898aa2b978032bb0a25e5504011424639f9 | [
"BSD-3-Clause"
] | 359 | 2015-06-21T03:17:58.000Z | 2022-01-21T16:17:49.000Z | gmusicapi/__init__.py | maxjoehnk/gmusicapi | 94e0d898aa2b978032bb0a25e5504011424639f9 | [
"BSD-3-Clause"
] | 227 | 2015-06-24T02:08:44.000Z | 2022-03-05T22:34:36.000Z | from gmusicapi._version import __version__
from gmusicapi.clients import Webclient, Musicmanager, Mobileclient
from gmusicapi.exceptions import CallFailure
__copyright__ = 'Copyright 2018 Simon Weber'
__license__ = 'BSD 3-Clause'
__title__ = 'gmusicapi'
# appease flake8: the imports are purposeful
(__version__, Webclient, Musicmanager, Mobileclient, CallFailure)
| 33.363636 | 67 | 0.825613 | 39 | 367 | 7.230769 | 0.641026 | 0.138298 | 0.234043 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018405 | 0.111717 | 367 | 10 | 68 | 36.7 | 0.846626 | 0.114441 | 0 | 0 | 0 | 0 | 0.145511 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.428571 | 0 | 0.428571 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
915a9bfb4d9593d8f7566f8209b8cb3753ccf990 | 3,533 | py | Python | src/treq/api.py | chevah/treq | 2d45c8227246583bc96cb4924722d9f79e95d4d7 | [
"MIT"
] | null | null | null | src/treq/api.py | chevah/treq | 2d45c8227246583bc96cb4924722d9f79e95d4d7 | [
"MIT"
] | null | null | null | src/treq/api.py | chevah/treq | 2d45c8227246583bc96cb4924722d9f79e95d4d7 | [
"MIT"
] | null | null | null | from __future__ import absolute_import, division, print_function
from twisted.web.client import Agent
from treq.client import HTTPClient
from treq._utils import default_pool, default_reactor
def head(url, **kwargs):
"""
Make a ``HEAD`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).head(url, **kwargs)
def get(url, headers=None, **kwargs):
"""
Make a ``GET`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).get(url, headers=headers, **kwargs)
def post(url, data=None, **kwargs):
"""
Make a ``POST`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).post(url, data=data, **kwargs)
def put(url, data=None, **kwargs):
"""
Make a ``PUT`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).put(url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
"""
Make a ``PATCH`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).patch(url, data=data, **kwargs)
def delete(url, **kwargs):
"""
Make a ``DELETE`` request.
See :py:func:`treq.request`
"""
return _client(**kwargs).delete(url, **kwargs)
def request(method, url, **kwargs):
"""
Make an HTTP request.
:param str method: HTTP method. Example: ``'GET'``, ``'HEAD'``. ``'PUT'``,
``'POST'``.
:param str url: http or https URL, which may include query arguments.
:param headers: Optional HTTP Headers to send with this request.
:type headers: Headers or None
:param params: Optional parameters to be append as the query string to
the URL, any query string parameters in the URL already will be
preserved.
:type params: dict w/ str or list/tuple of str values, list of 2-tuples, or
None.
:param data: Optional request body.
:type data: str, file-like, IBodyProducer, or None
:param json: Optional JSON-serializable content to pass in body.
:type json: dict, list/tuple, int, string/unicode, bool, or None
:param reactor: Optional twisted reactor.
:param bool persistent: Use persistent HTTP connections. Default: ``True``
:param bool allow_redirects: Follow HTTP redirects. Default: ``True``
:param auth: HTTP Basic Authentication information.
:type auth: tuple of ``('username', 'password')``.
:param cookies: Cookies to send with this request. The HTTP kind, not the
tasty kind.
:type cookies: ``dict`` or ``cookielib.CookieJar``
:param int timeout: Request timeout seconds. If a response is not
received within this timeframe, a connection is aborted with
``CancelledError``.
:param bool browser_like_redirects: Use browser like redirects
(i.e. Ignore RFC2616 section 10.3 and follow redirects from
POST requests). Default: ``False``
:param bool unbuffered: Pass ``True`` to to disable response buffering. By
default treq buffers the entire response body in memory.
:rtype: Deferred that fires with an IResponse provider.
"""
return _client(**kwargs).request(method, url, **kwargs)
#
# Private API
#
def _client(*args, **kwargs):
agent = kwargs.get('agent')
if agent is None:
reactor = default_reactor(kwargs.get('reactor'))
pool = default_pool(reactor,
kwargs.get('pool'),
kwargs.get('persistent'))
agent = Agent(reactor, pool=pool)
return HTTPClient(agent)
| 27.387597 | 79 | 0.638834 | 453 | 3,533 | 4.933775 | 0.315673 | 0.03132 | 0.056376 | 0.042953 | 0.195973 | 0.150336 | 0.120805 | 0.120805 | 0.120805 | 0 | 0 | 0.002952 | 0.232947 | 3,533 | 128 | 80 | 27.601563 | 0.821771 | 0.576847 | 0 | 0 | 0 | 0 | 0.021002 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.296296 | false | 0 | 0.148148 | 0 | 0.740741 | 0.037037 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
915c8f0ff80bdc887763a51d9204c844f60e2418 | 3,194 | py | Python | elastic_workplace_search/apis/documents.py | yakhinvadim/enterprise-search-python | a2010e8773a6250cb81ea48f760088bb23466bb1 | [
"Apache-2.0"
] | null | null | null | elastic_workplace_search/apis/documents.py | yakhinvadim/enterprise-search-python | a2010e8773a6250cb81ea48f760088bb23466bb1 | [
"Apache-2.0"
] | null | null | null | elastic_workplace_search/apis/documents.py | yakhinvadim/enterprise-search-python | a2010e8773a6250cb81ea48f760088bb23466bb1 | [
"Apache-2.0"
] | null | null | null | class Documents:
def __init__(self, session):
self.session = session
def index_documents(self, content_source_key, documents, **kwargs):
"""Index a batch of documents in a content source.
Raises :class:`~elastic_workplace_search.NonExistentRecord` if the
content_source_key is malformed or invalid. Raises
:class:`~elastic_workplace_search.WorkplaceSearchError` if there are any
HTTP errors.
:param content_source_key: Key for the content source.
:param documents: Array of documents to be indexed.
:return: Array of document indexing results.
>>> from elastic_workplace_search import Client
>>> from elastic_workplace_search.exceptions import WorkplaceSearchError
>>> content_source_key = 'content source key'
>>> authorization_token = 'authorization token'
>>> client = Client(authorization_token)
>>> documents = [
{
'id': '1',
'url': 'https://github.com/elastic/workplace-search-python',
'title': 'Elastic Workplace Search Official Python client',
'body': 'A descriptive body'
}
]
>>> try:
>>> document_results = client.documents.index_documents(content_source_key, documents)
>>> print(document_results)
>>> except WorkplaceSearchError:
>>> # handle exception
>>> pass
[{'errors': [], 'id': '1', 'id': None}]
"""
return self._async_create_or_update_documents(content_source_key,
documents)
def delete_documents(self, content_source_key, ids):
"""Destroys documents in a content source by their ids.
Raises :class:`~elastic_workplace_search.NonExistentRecord` if the
content_source_key is malformed or invalid. Raises
:class:`~elastic_workplace_search.WorkplaceSearchError` if there are any
HTTP errors.
:param content_source_key: Key for the content source.
:param ids: Array of document ids to be destroyed.
:return: Array of result dicts, with keys of `id` and `status`
>>> from elastic_workplace_search import Client
>>> from elastic_workplace_search.exceptions import WorkplaceSearchError
>>> content_source_key = 'content source key'
>>> authorization_token = 'authorization token'
>>> client = Client(authorization_token)
>>> try:
>>> response = client.documents.delete_documents(content_source_key, ['1'])
>>> print(response)
>>> except WorkplaceSearchError:
>>> # handle exception
>>> pass
[{"id": '1',"success": True}]
"""
endpoint = "sources/{}/documents/bulk_destroy".format(
content_source_key)
return self.session.request('post', endpoint, json=ids)
def _async_create_or_update_documents(self, content_source_key, documents):
endpoint = "sources/{}/documents/bulk_create".format(content_source_key)
return self.session.request('post', endpoint, json=documents)
| 43.753425 | 98 | 0.62774 | 327 | 3,194 | 5.917431 | 0.281346 | 0.134367 | 0.1323 | 0.05168 | 0.672351 | 0.530233 | 0.490956 | 0.490956 | 0.490956 | 0.490956 | 0 | 0.001723 | 0.273325 | 3,194 | 72 | 99 | 44.361111 | 0.831969 | 0.63588 | 0 | 0 | 0 | 0 | 0.0953 | 0.084856 | 0 | 0 | 0 | 0 | 0 | 1 | 0.307692 | false | 0 | 0 | 0 | 0.615385 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
9168dcc5d3fbd347e77651a865fe36d6375dccba | 4,142 | py | Python | WRM v0.9.2.2/lib/WRMjsonLoader.py | mipsou/warframe-slchatbot-mission-randomizer | 3e3620154d0d127e3038a807c6a1af1848c9dcb2 | [
"MIT"
] | null | null | null | WRM v0.9.2.2/lib/WRMjsonLoader.py | mipsou/warframe-slchatbot-mission-randomizer | 3e3620154d0d127e3038a807c6a1af1848c9dcb2 | [
"MIT"
] | 1 | 2018-06-04T11:27:13.000Z | 2018-06-06T16:20:29.000Z | WRM v0.9.2.2/lib/WRMjsonLoader.py | mipsou/warframe-slchatbot-mission-randomizer | 3e3620154d0d127e3038a807c6a1af1848c9dcb2 | [
"MIT"
] | 1 | 2018-06-02T02:43:21.000Z | 2018-06-02T02:43:21.000Z |
import clr
clr.AddReference("IronPython.SQLite.dll")
clr.AddReference("IronPython.Modules.dll")
import codecs
import datetime
import json
import logging
import os
import random
import sqlite3
import sys
import time
def GetFactionNames():
factionNamesJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/factionNames.json")
if factionNamesJSON and os.path.isfile(factionNamesJSON):
with codecs.open(factionNamesJSON) as f:
factionNames = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return factionNames
def GetBossLocations():
bossesJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/assassinationTargets.json")
if bossesJSON and os.path.isfile(bossesJSON):
with codecs.open(bossesJSON) as f:
bosses = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return bosses
def GetMissionType():
missionTypesJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/missionTypes.json")
if missionTypesJSON and os.path.isfile(missionTypesJSON):
with codecs.open(missionTypesJSON) as f:
missionTypes = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return missionTypes
def GetNavMissionNodes():
navMissionsJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/navMissions.json")
if navMissionsJSON and os.path.isfile(navMissionsJSON):
with codecs.open(navMissionsJSON) as f:
navMissions = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return navMissions
def GetRelics():
relicNamesJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/relicNames.json")
if relicNamesJSON and os.path.isfile(relicNamesJSON):
with codecs.open(relicNamesJSON) as f:
relicNames = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return relicNames
def GetSolNodes():
solNodesJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/solNodes.json")
if solNodesJSON and os.path.isfile(solNodesJSON):
with codecs.open(solNodesJSON) as f:
solNodes = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return solNodes
# TODO only fetch language.json once ?
def GetLanguageFile():
languageJSON = os.path.join(os.path.dirname(__file__), "../lib/jsons/languages.json")
if languageJSON and os.path.isfile(languageJSON):
with codecs.open(languageJSON) as f:
languageDict = json.load(f)
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib/classes"))
return languageDict
class JsonLoader:
def __init__(self):
self.factionNames = GetFactionNames()
self.language = GetLanguageFile()
self.missionTypes = GetMissionType()
self.relicNames = GetRelics()
self.solNodes = GetSolNodes()
self.bosses = GetBossLocations()
self.navMissions = GetNavMissionNodes()
#self.syndicateNames =
#self.warframes =
#self.weapons =
#self.factionNames = os.path.join(os.path.dirname(__file__), "/lib/jsons/factionNames.json")
#self.missionTypes = os.path.join(os.path.dirname(__file__), "/lib/jsons/missionTypes.json")
#self.relicNames = os.path.join(os.path.dirname(__file__), "/lib/jsons/relicNames.json")
#self.solNodes = os.path.join(os.path.dirname(__file__), "/lib/jsons/solNodes.json")
#self.syndicateNames = os.path.join(os.path.dirname(__file__), "/lib/jsons/syndicateNames.json")
#self.warframes = os.path.join(os.path.dirname(__file__), "/lib/jsons/warframes.json")
#self.weapons = os.path.join(os.path.dirname(__file__), "/lib/jsons/weapons.json")
def getBossNames(self):
return self.bosses
def getFactionNames(self):
return self.factionNames
def getLanguageFile(self):
return self.language
def getMissionTypes(self):
return self.missionTypes
def getNavMissions(self):
return self.navMissions
def getRelicNames(self):
return self.relicNames
def getSolNodes(self):
return self.solNodes
def getSyndicatenames(self):
return self.syndicateNames
def getWarframes(self):
return self.warframes
def getWeapons(self):
return self.weapons | 32.873016 | 98 | 0.746499 | 534 | 4,142 | 5.625468 | 0.142322 | 0.09787 | 0.069907 | 0.083888 | 0.353196 | 0.353196 | 0.353196 | 0.353196 | 0.353196 | 0.283289 | 0 | 0.000271 | 0.10985 | 4,142 | 126 | 99 | 32.873016 | 0.814483 | 0.169725 | 0 | 0.077778 | 0 | 0 | 0.101838 | 0.073242 | 0 | 0 | 0 | 0.007937 | 0 | 1 | 0.2 | false | 0 | 0.111111 | 0.111111 | 0.511111 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
9171b9c40620024c4e041e73c0ac5db4164cc05d | 177 | py | Python | .frameworks/skdiscovery/Series/Accumulators/Plotter.py | MITeaps/codesnippets | 7621ec4d4c667e95a66c355563e467e50f0fadf6 | [
"MIT"
] | null | null | null | .frameworks/skdiscovery/Series/Accumulators/Plotter.py | MITeaps/codesnippets | 7621ec4d4c667e95a66c355563e467e50f0fadf6 | [
"MIT"
] | null | null | null | .frameworks/skdiscovery/Series/Accumulators/Plotter.py | MITeaps/codesnippets | 7621ec4d4c667e95a66c355563e467e50f0fadf6 | [
"MIT"
] | null | null | null | # Create Plotter
acc_plotter = skdiscovery.data_structure.series.accumulators.Plotter('Plotter')
# Create stage containter for Plotter
sc_plotter = StageContainer(acc_plotter)
| 29.5 | 79 | 0.830508 | 21 | 177 | 6.809524 | 0.619048 | 0.13986 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.090395 | 177 | 5 | 80 | 35.4 | 0.888199 | 0.282486 | 0 | 0 | 0 | 0 | 0.056452 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
917ac12b1bd5c280f75d21326e7ff76396758677 | 65 | py | Python | Janaagraha Bot/venv/Lib/site-packages/pyasn1_modules/__init__.py | CFGIndia20/team-19 | e2b27ad8009303d262c2dc60551d6fcc4645b3b5 | [
"MIT"
] | 15 | 2020-06-29T08:33:39.000Z | 2022-02-12T00:28:51.000Z | Janaagraha Bot/venv/Lib/site-packages/pyasn1_modules/__init__.py | CFGIndia20/team-19 | e2b27ad8009303d262c2dc60551d6fcc4645b3b5 | [
"MIT"
] | 21 | 2020-03-01T18:21:09.000Z | 2020-05-26T14:49:08.000Z | Janaagraha Bot/venv/Lib/site-packages/pyasn1_modules/__init__.py | CFGIndia20/team-19 | e2b27ad8009303d262c2dc60551d6fcc4645b3b5 | [
"MIT"
] | 11 | 2020-06-29T08:40:24.000Z | 2022-02-24T17:39:16.000Z | # http://www.python.org/dev/peps/pep-0396/
__version__ = '0.2.8'
| 21.666667 | 42 | 0.676923 | 12 | 65 | 3.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.116667 | 0.076923 | 65 | 2 | 43 | 32.5 | 0.55 | 0.615385 | 0 | 0 | 0 | 0 | 0.217391 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91822944d3827f770545ec75edb2f493072c8eb2 | 3,016 | py | Python | Cylance.py | azabyo/cylance | 9a1724975ef476b8e821cbca6a7ea95ce9b9fde9 | [
"MIT"
] | null | null | null | Cylance.py | azabyo/cylance | 9a1724975ef476b8e821cbca6a7ea95ce9b9fde9 | [
"MIT"
] | null | null | null | Cylance.py | azabyo/cylance | 9a1724975ef476b8e821cbca6a7ea95ce9b9fde9 | [
"MIT"
] | null | null | null | # -*-coding:utf-8-*-
from module.clsCylance import Cylance, ROOT_PATH
from module.clsDevice import deviceAPI
from module.clsGlobal import globalAPI
from module.clsPolicy import policyAPI
from module.clsUser import userAPI
from module.clsZone import zoneAPI
from module.clsThreat import threatAPI
import json
AZABYO_DID = "938a56e5-d736-431f-9a0a-3f9a3622aeba"
DESKTOP_TBU = "ad2c74d5-a129-4457-9cbb-8643bc9b972d"
TEST_ZONE_ID = "4a7fdbf7-d3c7-4533-a5d5-6ea13a5fb921"
MY_PC_ZONE_ID = "3526b55e-8ca0-4af5-ae29-b3c05c1e756f"
TROUBLESHT_PID = "d7b277fe-2ac3-47f9-bb82-9becf2b4d7b2"
CTMUSD32000_SHA256 = "c5e853eb2b51a5df8ec68a541a9be3cc3785219572ce574929fa92ca9a6e891e"
CTMUSD32000_MD5 = "B3CCBC4AF8977A12E2AEE0C9F7E8E518"
ADD_TEST_SHA256 = "c59b088e106f8dfdc93a35802c8b3c82d6b3f14fca55af9120dfb40b95eb35a1"
YGKANG_UID = "2e442b0d-ce6d-4cdd-9ecc-f5be8a03c009"
TEST_PID = "afb9d559-03d0-4559-877d-e68523b22247"
TEST_PID_LIST = ["39dd1277-9bf7-47c8-8f9c-7a99753418a3",
"deb471eb-e1cf-447e-ac02-907b6a84980b"]
def main():
# ### User API ###
# print userAPI().getUsers()
# userAPI().createUser('ygkang_test5@sk.com', _role=userAPI.ZONE_MNGR,
# _zrtype=userAPI.ZONE_MNGR)
# print userAPI().getUser('ygkang@sk.com')
# print userAPI().deleteUser('ygkang_test1@sk.com')
# print userAPI().sendMail('ygkang@sk.com', _invite=False)
# ### Deviced API ###
# device = deviceAPI()
# print deviceAPI().updateDevice("938a56e5-d736-431f-9a0a-3f9a3622aeba",
# "azabyo_update2")
# print device.getDevices()
# print device.getDeviceThreats(DESKTOP_TBU)
# print device.getZoneDevices(MY_PC_ZONE_ID)
# print device.getAgentInstallerLink()
# print deviceAPI().getDeviceByMACAddress("08-00-27-27-C2-6A")
# ### Global API ###
# print globalAPI().getGlobalList(3)
# print globalAPI().addToGlobalList(ADD_TEST_SHA256)
# ### Policy API ###
print policyAPI().getPolicy("48084450-ea2e-4683-9ed1-36469522f8d9")
# print policyAPI().getPolicies()
# print policyAPI().deletePolicy(TEST_PID)
# print policyAPI().deletePolicies(TEST_PID_LIST)
# print policyAPI().createPolicy("test_policy", YGKANG_UID)
# #### Zone API ####
# print zoneAPI().createZone(_upid=TROUBLESHT_PID, _zname="test_zone")
# print zoneAPI().getZones()
# print zoneAPI().getDeviceZones(AZABYO_DID)
# print zoneAPI().getZone(MY_PC_ZONE_ID)
# print zoneAPI().updateZone(_upid=TROUBLESHT_PID,
# _uzid="3ee9d754-dd45-4d0a-9a3b-5b915ff0fc33",
# _zname="test_zone_update")
# print zoneAPI().deleteZone("3ee9d754-dd45-4d0a-9a3b-5b915ff0fc33")
# ### Threat API ###
# print threatAPI().getThreat(CTMUSD32000_SHA256)
# print threatAPI().getThreats()
# print threatAPI().getThreatDevices(CTMUSD32000_SHA256)
# print threatAPI().getThreatDownloadURL(CTMUSD32000_SHA256)
if __name__ == "__main__":
main()
| 40.213333 | 87 | 0.707891 | 317 | 3,016 | 6.542587 | 0.501577 | 0.033751 | 0.011572 | 0.014465 | 0.076181 | 0 | 0 | 0 | 0 | 0 | 0 | 0.160714 | 0.164456 | 3,016 | 74 | 88 | 40.756757 | 0.662302 | 0.535477 | 0 | 0 | 0 | 0 | 0.399093 | 0.393046 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.333333 | null | null | 0.041667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
9188b5864406d9875dfd8b4063f568034c0a779b | 9,380 | py | Python | thrift/test/py/TestServer.py | fakeNetflix/facebook-repo-fbthrift | 24f2357142d1da8c89f4cabc6cb144d83749b3c6 | [
"Apache-2.0"
] | 2 | 2021-06-29T13:42:22.000Z | 2021-09-06T10:57:34.000Z | thrift/test/py/TestServer.py | fakeNetflix/facebook-repo-fbthrift | 24f2357142d1da8c89f4cabc6cb144d83749b3c6 | [
"Apache-2.0"
] | null | null | null | thrift/test/py/TestServer.py | fakeNetflix/facebook-repo-fbthrift | 24f2357142d1da8c89f4cabc6cb144d83749b3c6 | [
"Apache-2.0"
] | 5 | 2021-06-29T13:42:26.000Z | 2022-02-08T02:41:34.000Z | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import os.path
import sys
import time
sys.path.insert(0, './gen-py')
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
lib_path = glob.glob('../../lib/py/build/lib.*')
if lib_path:
sys.path.insert(0, lib_path[0])
from optparse import OptionParser
from ThriftTest import ThriftTest, SecondService
from ThriftTest.ttypes import *
from thrift import TMultiplexedProcessor
from thrift.Thrift import TProcessorEventHandler
from thrift.transport import TTransport
from thrift.transport import TSocket, TSSLSocket
from thrift.transport.THeaderTransport import CLIENT_TYPE
from thrift.protocol import TBinaryProtocol
from thrift.protocol import THeaderProtocol
from thrift.server import TServer, TCppServer
class SecondHandler(SecondService.Iface):
def blahBlah(self):
print('blahBlah()')
class SecondContextHandler(SecondService.ContextIface):
def __init__(self,):
self.th = SecondHandler()
def blahBlah(self, handler_ctx):
self.th.blahBlah()
class TestHandler(ThriftTest.Iface):
def testVoid(self):
print('testVoid()')
def testString(self, str):
print('testString(%s)' % str)
return str
def testByte(self, byte):
print('testByte(%d)' % byte)
return byte
def testI16(self, i16):
print('testI16(%d)' % i16)
return i16
def testI32(self, i32):
print('testI32(%d)' % i32)
return i32
def testI64(self, i64):
print('testI64(%d)' % i64)
return i64
def testDouble(self, dub):
print('testDouble(%f)' % dub)
return dub
def testFloat(self, flt):
print('testFloat(%f)' % flt)
return flt
def testStruct(self, thing):
print('testStruct({%s, %d, %d, %d})' % (thing.string_thing,
thing.byte_thing, thing.i32_thing, thing.i64_thing))
return thing
def testException(self, str):
print('testException(%s)' % str)
if str == 'Xception':
x = Xception()
x.errorCode = 1001
x.message = str
raise x
elif str == "throw_undeclared":
raise ValueError("foo")
def testOneway(self, seconds):
print('testOneway(%d) => sleeping...' % seconds)
time.sleep(seconds)
print('done sleeping')
def testNest(self, thing):
return thing
def testMap(self, thing):
return thing
def testSet(self, thing):
return thing
def testList(self, thing):
return thing
def testEnum(self, thing):
return thing
def testTypedef(self, thing):
return thing
class TestContextHandler(ThriftTest.ContextIface):
def __init__(self, server_port):
self.th = TestHandler()
self._server_port = server_port
def testVoid(self, handler_ctx):
self.th.testVoid()
# This is here so we can check that handler_ctx is getting set,
# without modifying the service definition which would require
# modifying all the languages.
if not (handler_ctx[0].endswith("127.0.0.1") or \
handler_ctx[0].endswith("::1")) or \
handler_ctx[1] == self._server_port:
raise ValueError("handler_ctx not set properly " +
str(handler_ctx))
def testString(self, handler_ctx, str):
return self.th.testString(str)
def testByte(self, handler_ctx, byte):
return self.th.testByte(byte)
def testI16(self, handler_ctx, i16):
return self.th.testI16(i16)
def testI32(self, handler_ctx, i32):
return self.th.testI32(i32)
def testI64(self, handler_ctx, i64):
return self.th.testI64(i64)
def testDouble(self, handler_ctx, dub):
return self.th.testDouble(dub)
def testFloat(self, handler_ctx, flt):
return self.th.testFloat(flt)
def testStruct(self, handler_ctx, thing):
return self.th.testStruct(thing)
def testException(self, handler_ctx, str):
return self.th.testException(str)
def testOneway(self, handler_ctx, seconds):
return self.th.testOneway(seconds)
def testNest(self, handler_ctx, thing):
return self.th.testNest(thing)
def testMap(self, handler_ctx, thing):
return self.th.testMap(thing)
def testSet(self, handler_ctx, thing):
return self.th.testSet(thing)
def testList(self, handler_ctx, thing):
return self.th.testList(thing)
def testEnum(self, handler_ctx, thing):
return self.th.testEnum(thing)
def testTypedef(self, handler_ctx, thing):
return self.th.testTypedef(thing)
class ContextEventHandler(TProcessorEventHandler):
def getHandlerContext(self, fn_name, server_context):
# this is a tuple ("hostname", port)
return server_context.getPeerName()
class HeaderEventHandler(ContextEventHandler):
def getHandlerContext(self, fn_name, server_context):
self.htrans = server_context.iprot.trans
return ContextEventHandler.getHandlerContext(self,
fn_name, server_context)
def preWrite(self, handler_context, fn_name, result):
for str_key, str_value in self.htrans.get_headers().items():
# Just spit them back for testing.
self.htrans.set_header(str_key, str_value)
class TestServerEventHandler(TServer.TServerEventHandler):
def __init__(self):
self.num_pre_serve = 0
self.request_count = 0
self.num_new_conns = 0
self.num_conns_destroyed = 0
def newConnection(self, context):
self.num_new_conns += 1
def preServe(self, address):
self.num_pre_serve += 1
def clientBegin(self, iprot, oprot):
self.request_count += 1
def connectionDestroyed(self, context):
self.num_conns_destroyed += 1
if __name__ == "__main__":
parser = OptionParser()
parser.add_option(
"--ssl",
action="store_true",
dest="ssl",
default=False,
help="use SSL for encrypted transport")
parser.add_option(
"--multiple",
action="store_true",
dest="multiple",
default=False,
help="use multiple service")
parser.add_option(
"--header",
action="store_true",
dest="header",
default=False,
help="use the Header protocol")
parser.add_option(
"--context",
action="store_true",
dest="context",
default=False,
help="Use the context-passing Handler")
parser.add_option(
"--port",
action="store",
type="int",
dest="port",
default=9090)
parser.add_option(
"--timeout",
action="store",
type="int",
dest="timeout",
default=60)
options, args = parser.parse_args()
event_handler = TestServerEventHandler()
if options.header:
pfactory = THeaderProtocol.THeaderProtocolFactory(
True,
[CLIENT_TYPE.HEADER,
CLIENT_TYPE.FRAMED_DEPRECATED,
CLIENT_TYPE.UNFRAMED_DEPRECATED,
CLIENT_TYPE.HTTP_SERVER]
)
else:
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
if options.context:
processor = ThriftTest.ContextProcessor(TestContextHandler(
options.port))
else:
processor = ThriftTest.Processor(TestHandler())
if options.multiple:
processor = TMultiplexedProcessor.TMultiplexedProcessor()
if options.context:
processor.registerProcessor("ThriftTest",
ThriftTest.ContextProcessor(TestContextHandler(
options.port)))
processor.registerProcessor("SecondService",
SecondService.ContextProcessor(SecondContextHandler()))
else:
processor.registerProcessor("ThriftTest",
ThriftTest.Processor(TestHandler()))
processor.registerProcessor("SecondService",
SecondService.Processor(SecondHandler()))
server = TCppServer.TCppServer(processor)
server.setPort(options.port)
if options.header:
server.processor.setEventHandler(HeaderEventHandler())
elif options.context:
server.processor.setEventHandler(ContextEventHandler())
server.setServerEventHandler(event_handler)
server.serve()
| 29.404389 | 75 | 0.652026 | 1,056 | 9,380 | 5.666667 | 0.260417 | 0.040107 | 0.042112 | 0.022226 | 0.126003 | 0.067012 | 0.060328 | 0 | 0 | 0 | 0 | 0.013352 | 0.249467 | 9,380 | 318 | 76 | 29.496855 | 0.836648 | 0.105437 | 0 | 0.165939 | 0 | 0 | 0.070515 | 0.002868 | 0 | 0 | 0 | 0 | 0 | 1 | 0.200873 | false | 0.004367 | 0.082969 | 0.100437 | 0.454148 | 0.061135 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
91a117168bee9fcf2ca415763431140df5d591e8 | 255 | py | Python | modules/dataproviders/__init__.py | imdatsolak/bender | e20a5c7553d0db60440573b4fc3e907d6a8d5fad | [
"BSD-3-Clause"
] | null | null | null | modules/dataproviders/__init__.py | imdatsolak/bender | e20a5c7553d0db60440573b4fc3e907d6a8d5fad | [
"BSD-3-Clause"
] | null | null | null | modules/dataproviders/__init__.py | imdatsolak/bender | e20a5c7553d0db60440573b4fc3e907d6a8d5fad | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from .mldataprovider import MLDataProvider
from .currentdatetime import CurrentDateTimeProvider
from .wpbiographyprovider import WPBiographyProvider
__author__ = 'Imdat Solak'
__email__ = 'imdat@solak.de'
__version__ = '0.1.1'
| 23.181818 | 53 | 0.780392 | 26 | 255 | 7.192308 | 0.653846 | 0.106952 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.017857 | 0.121569 | 255 | 10 | 54 | 25.5 | 0.816964 | 0.082353 | 0 | 0 | 0 | 0 | 0.12987 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
91a95699e59d85368748f832fe10eed1725225fd | 310 | py | Python | vmc/result_analysis/lib/pathmaker.py | kmaasrud/vmc | 1d29f18a4cb08ed65ab531a174f1869748f5ac2a | [
"MIT"
] | 2 | 2021-01-23T22:44:35.000Z | 2021-06-03T00:34:43.000Z | vmc/python/lib/pathmaker.py | kmaasrud/vmc-fys4411 | e96e2f6b1403118ee48ad5b5ff38582310ba4d2a | [
"MIT"
] | 47 | 2021-01-14T14:13:32.000Z | 2021-04-05T10:32:02.000Z | vmc/result_analysis/lib/pathmaker.py | kmaasrud/vmc | 1d29f18a4cb08ed65ab531a174f1869748f5ac2a | [
"MIT"
] | null | null | null | import os
import matplotlib.pyplot as plt
def pathmaker(DIR):
if not os.path.exists(DIR):
os.makedirs(DIR)
print(f'made directory {DIR}')
def join_path(DIR, id):
return os.path.join(DIR, id)
def save_fig(DIR,id):
plt.savefig(join_path(DIR, id) + ".png", format = 'png')
| 20.666667 | 60 | 0.629032 | 49 | 310 | 3.918367 | 0.530612 | 0.104167 | 0.114583 | 0.135417 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.225806 | 310 | 14 | 61 | 22.142857 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0.087379 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.3 | false | 0 | 0.2 | 0.1 | 0.6 | 0.1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
91b0429db4f29c8d72405fba60fb11381cd537f6 | 648 | py | Python | src/pebl/test/learner/test_simanneal.py | Delwddrylliwr/pebl-project | da52e573dc4ce3cf62a63278bac28f2d0644205f | [
"MIT"
] | 53 | 2015-01-11T06:31:44.000Z | 2021-06-28T08:09:39.000Z | src/pebl/test/learner/test_simanneal.py | arnaudsj/pebl | 5b3270d79696e1c89bb9ae9814e1307f64cf3550 | [
"MIT"
] | 2 | 2016-02-10T07:40:27.000Z | 2021-06-20T10:21:35.000Z | src/pebl/test/learner/test_simanneal.py | arnaudsj/pebl | 5b3270d79696e1c89bb9ae9814e1307f64cf3550 | [
"MIT"
] | 13 | 2015-01-30T14:53:55.000Z | 2019-07-17T06:12:38.000Z | from pebl.test import testfile
from pebl import data, result
from pebl.learner import simanneal
class TestGreedyLearner:
def setUp(self):
self.data = data.fromfile(testfile('testdata5.txt'))
self.data.discretize()
def test_default_params(self):
s = simanneal.SimulatedAnnealingLearner(self.data)
s.run()
assert True
def test_param_effect(self):
s1 = simanneal.SimulatedAnnealingLearner(self.data)
s1.run()
s2 = simanneal.SimulatedAnnealingLearner( self.data, start_temp = 50)
s2.run()
assert s1.stats.iterations > s2.stats.iterations
| 25.92 | 77 | 0.662037 | 73 | 648 | 5.808219 | 0.465753 | 0.09434 | 0.268868 | 0.29717 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.01848 | 0.248457 | 648 | 24 | 78 | 27 | 0.852156 | 0 | 0 | 0 | 0 | 0 | 0.020124 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 1 | 0.176471 | false | 0 | 0.176471 | 0 | 0.411765 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91c40f1db412a4d23242d1f3f4aad1460127316f | 6,811 | py | Python | airflow/providers/alibaba/cloud/operators/oss.py | qgallet/airflow | 8cf3d120ff44c6604e330cc9c4e7945b3f1edc6c | [
"Apache-2.0"
] | null | null | null | airflow/providers/alibaba/cloud/operators/oss.py | qgallet/airflow | 8cf3d120ff44c6604e330cc9c4e7945b3f1edc6c | [
"Apache-2.0"
] | 1 | 2021-11-19T00:29:26.000Z | 2021-11-19T00:29:26.000Z | airflow/providers/alibaba/cloud/operators/oss.py | qgallet/airflow | 8cf3d120ff44c6604e330cc9c4e7945b3f1edc6c | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""This module contains Alibaba Cloud OSS operators."""
from typing import Optional
from airflow.models import BaseOperator
from airflow.providers.alibaba.cloud.hooks.oss import OSSHook
class OSSCreateBucketOperator(BaseOperator):
"""
This operator creates an OSS bucket
:param region: OSS region you want to create bucket
:type region: str
:param bucket_name: This is bucket name you want to create
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.create_bucket(bucket_name=self.bucket_name)
class OSSDeleteBucketOperator(BaseOperator):
"""
This operator to delete an OSS bucket
:param region: OSS region you want to create bucket
:type region: str
:param bucket_name: This is bucket name you want to delete
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.delete_bucket(bucket_name=self.bucket_name)
class OSSUploadObjectOperator(BaseOperator):
"""
This operator to upload an file-like object
:param key: the OSS path of the object
:type key: str
:param file: local file to upload.
:type file: str
:param region: OSS region you want to create bucket
:type region: str
:param bucket_name: This is bucket name you want to create
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
key: str,
file: str,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.key = key
self.file = file
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.upload_local_file(bucket_name=self.bucket_name, key=self.key, file=self.file)
class OSSDownloadObjectOperator(BaseOperator):
"""
This operator to Download an OSS object
:param key: key of the object to download.
:type key: str
:param local_file: local path + file name to save.
:type local_file: str
:param region: OSS region
:type region: str
:param bucket_name: OSS bucket name
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
key: str,
file: str,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.key = key
self.file = file
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.download_file(bucket_name=self.bucket_name, key=self.key, local_file=self.file)
class OSSDeleteBatchObjectOperator(BaseOperator):
"""
This operator to delete OSS objects
:param key: key list of the objects to delete.
:type key: str
:param region: OSS region
:type region: str
:param bucket_name: OSS bucket name
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
keys: list,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.keys = keys
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.delete_objects(bucket_name=self.bucket_name, key=self.keys)
class OSSDeleteObjectOperator(BaseOperator):
"""
This operator to delete an OSS object
:param key: key of the object to delete.
:type key: str
:param region: OSS region
:type region: str
:param bucket_name: OSS bucket name
:type bucket_name: str
:param oss_conn_id: The Airflow connection used for OSS credentials.
:type oss_conn_id: Optional[str]
"""
def __init__(
self,
key: str,
region: str,
bucket_name: Optional[str] = None,
oss_conn_id: str = 'oss_default',
**kwargs,
) -> None:
super().__init__(**kwargs)
self.key = key
self.oss_conn_id = oss_conn_id
self.region = region
self.bucket_name = bucket_name
def execute(self, context):
oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region)
oss_hook.delete_object(bucket_name=self.bucket_name, key=self.key)
| 30.68018 | 96 | 0.663045 | 927 | 6,811 | 4.653722 | 0.142395 | 0.111266 | 0.087622 | 0.036161 | 0.698192 | 0.690774 | 0.688224 | 0.649977 | 0.642096 | 0.624478 | 0 | 0.000785 | 0.251652 | 6,811 | 221 | 97 | 30.819005 | 0.845595 | 0.406989 | 0 | 0.838095 | 0 | 0 | 0.017671 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.114286 | false | 0 | 0.028571 | 0 | 0.2 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91cf9f21c0e92eab0083f8498610af82d8c87e00 | 240 | py | Python | tests/target.py | chrahunt/python-hunter | b3a1310b0593d2c6b6ef430883843896e17d6a81 | [
"BSD-2-Clause"
] | null | null | null | tests/target.py | chrahunt/python-hunter | b3a1310b0593d2c6b6ef430883843896e17d6a81 | [
"BSD-2-Clause"
] | null | null | null | tests/target.py | chrahunt/python-hunter | b3a1310b0593d2c6b6ef430883843896e17d6a81 | [
"BSD-2-Clause"
] | null | null | null | import sys
import time
def stuff():
print('Doing stuff ...')
time.sleep(1)
if __name__ == '__main__':
if sys.argv[1] == 'manhole':
from hunter import remote
remote.install()
while True:
stuff()
| 13.333333 | 33 | 0.566667 | 29 | 240 | 4.413793 | 0.689655 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011905 | 0.3 | 240 | 17 | 34 | 14.117647 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0.125 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | true | 0 | 0.272727 | 0 | 0.363636 | 0.090909 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91d8dfa0efd2bf759d0d99cd38fb337687b5c0d8 | 26,531 | py | Python | ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/highlevelstream/highlevelstream.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/highlevelstream/highlevelstream.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/highlevelstream/highlevelstream.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class HighLevelStream(Base):
"""A Flow Group that is generated from the Traffic Item. Each Traffic Item generates one or more Flow Groups, which in turn map to hardware streams on the port. Each Flow Group/highLevelStream picks up its QOS, Rate, Frame size properties/attributes from its corresponding configElement configuration under the Traffic Item.
The HighLevelStream class encapsulates a list of highLevelStream resources that are managed by the system.
A list of resources can be retrieved from the server using the HighLevelStream.find() method.
"""
__slots__ = ()
_SDM_NAME = 'highLevelStream'
_SDM_ATT_MAP = {
'AppliedFrameRate': 'appliedFrameRate',
'AppliedFrameSize': 'appliedFrameSize',
'AppliedPacketCount': 'appliedPacketCount',
'Crc': 'crc',
'CurrentPacketCount': 'currentPacketCount',
'DestinationMacMode': 'destinationMacMode',
'Distributions': 'distributions',
'Enabled': 'enabled',
'EncapsulationName': 'encapsulationName',
'EndpointSetId': 'endpointSetId',
'Name': 'name',
'OverSubscribed': 'overSubscribed',
'Pause': 'pause',
'PreambleCustomSize': 'preambleCustomSize',
'PreambleFrameSizeMode': 'preambleFrameSizeMode',
'RxPortIds': 'rxPortIds',
'RxPortNames': 'rxPortNames',
'State': 'state',
'Suspend': 'suspend',
'TxPortId': 'txPortId',
'TxPortName': 'txPortName',
}
def __init__(self, parent):
super(HighLevelStream, self).__init__(parent)
@property
def FramePayload(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framepayload.framepayload.FramePayload): An instance of the FramePayload class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framepayload.framepayload import FramePayload
if self._properties.get('FramePayload', None) is None:
return FramePayload(self)._select()
else:
return self._properties.get('FramePayload')
@property
def FramePreemption(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.framepreemption.framepreemption.FramePreemption): An instance of the FramePreemption class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.framepreemption.framepreemption import FramePreemption
if self._properties.get('FramePreemption', None) is None:
return FramePreemption(self)
else:
return self._properties.get('FramePreemption')
@property
def FrameRate(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framerate.framerate.FrameRate): An instance of the FrameRate class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framerate.framerate import FrameRate
if self._properties.get('FrameRate', None) is None:
return FrameRate(self)._select()
else:
return self._properties.get('FrameRate')
@property
def FrameSize(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framesize.framesize.FrameSize): An instance of the FrameSize class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.framesize.framesize import FrameSize
if self._properties.get('FrameSize', None) is None:
return FrameSize(self)._select()
else:
return self._properties.get('FrameSize')
@property
def Stack(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.stack.stack.Stack): An instance of the Stack class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.stack.stack import Stack
if self._properties.get('Stack', None) is None:
return Stack(self)
else:
return self._properties.get('Stack')
@property
def StackLink(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.stacklink.stacklink.StackLink): An instance of the StackLink class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.stacklink.stacklink import StackLink
if self._properties.get('StackLink', None) is None:
return StackLink(self)
else:
return self._properties.get('StackLink')
@property
def TableUdf(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.tableudf.tableudf.TableUdf): An instance of the TableUdf class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.tableudf.tableudf import TableUdf
if self._properties.get('TableUdf', None) is None:
return TableUdf(self)
else:
return self._properties.get('TableUdf')
@property
def TransmissionControl(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.transmissioncontrol.transmissioncontrol.TransmissionControl): An instance of the TransmissionControl class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.configelement.transmissioncontrol.transmissioncontrol import TransmissionControl
if self._properties.get('TransmissionControl', None) is None:
return TransmissionControl(self)._select()
else:
return self._properties.get('TransmissionControl')
@property
def Udf(self):
"""
Returns
-------
- obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.udf.udf.Udf): An instance of the Udf class
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.traffic.trafficitem.highlevelstream.udf.udf import Udf
if self._properties.get('Udf', None) is None:
return Udf(self)
else:
return self._properties.get('Udf')
@property
def AppliedFrameRate(self):
"""
Returns
-------
- str:
"""
return self._get_attribute(self._SDM_ATT_MAP['AppliedFrameRate'])
@property
def AppliedFrameSize(self):
"""
Returns
-------
- str: (Read only) Indicates the applied frame size of the high level stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['AppliedFrameSize'])
@property
def AppliedPacketCount(self):
"""
Returns
-------
- number: (Read only) Indicates the aplied packet count of the high level stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['AppliedPacketCount'])
@property
def Crc(self):
"""
Returns
-------
- str(badCrc | goodCrc): The Cyclic Redundancy Check frame of the configured high level stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['Crc'])
@Crc.setter
def Crc(self, value):
self._set_attribute(self._SDM_ATT_MAP['Crc'], value)
@property
def CurrentPacketCount(self):
"""
Returns
-------
- number: (Read only) Denotes the number of packets.
"""
return self._get_attribute(self._SDM_ATT_MAP['CurrentPacketCount'])
@property
def DestinationMacMode(self):
"""
Returns
-------
- str(arp | manual): The mode in which the Destination MAC Address is configured, either manual or ARP.
"""
return self._get_attribute(self._SDM_ATT_MAP['DestinationMacMode'])
@DestinationMacMode.setter
def DestinationMacMode(self, value):
self._set_attribute(self._SDM_ATT_MAP['DestinationMacMode'], value)
@property
def Distributions(self):
"""
Returns
-------
- list(dict(arg1:str,arg2:str)): Denotes the distribution of the high level stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['Distributions'])
@property
def Enabled(self):
"""
Returns
-------
- bool:
"""
return self._get_attribute(self._SDM_ATT_MAP['Enabled'])
@Enabled.setter
def Enabled(self, value):
self._set_attribute(self._SDM_ATT_MAP['Enabled'], value)
@property
def EncapsulationName(self):
"""
Returns
-------
- str: Name of the configured encapsulation type.
"""
return self._get_attribute(self._SDM_ATT_MAP['EncapsulationName'])
@property
def EndpointSetId(self):
"""
Returns
-------
- number: The ID of the configured endpoint set.
"""
return self._get_attribute(self._SDM_ATT_MAP['EndpointSetId'])
@property
def Name(self):
"""
Returns
-------
- str: An alphanumeric string that returns the name of the field.
"""
return self._get_attribute(self._SDM_ATT_MAP['Name'])
@Name.setter
def Name(self, value):
self._set_attribute(self._SDM_ATT_MAP['Name'], value)
@property
def OverSubscribed(self):
"""
Returns
-------
- bool: If true, the rate is oversubscribed.
"""
return self._get_attribute(self._SDM_ATT_MAP['OverSubscribed'])
@property
def Pause(self):
"""
Returns
-------
- bool: If true then pause is enabled.
"""
return self._get_attribute(self._SDM_ATT_MAP['Pause'])
@Pause.setter
def Pause(self, value):
self._set_attribute(self._SDM_ATT_MAP['Pause'], value)
@property
def PreambleCustomSize(self):
"""
Returns
-------
- number: Customizes the preamble size of the frame.
"""
return self._get_attribute(self._SDM_ATT_MAP['PreambleCustomSize'])
@PreambleCustomSize.setter
def PreambleCustomSize(self, value):
self._set_attribute(self._SDM_ATT_MAP['PreambleCustomSize'], value)
@property
def PreambleFrameSizeMode(self):
"""
Returns
-------
- str(auto | custom): The starting size of the frame.
"""
return self._get_attribute(self._SDM_ATT_MAP['PreambleFrameSizeMode'])
@PreambleFrameSizeMode.setter
def PreambleFrameSizeMode(self, value):
self._set_attribute(self._SDM_ATT_MAP['PreambleFrameSizeMode'], value)
@property
def RxPortIds(self):
"""
Returns
-------
- list(str[None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport]): A list of virtual ports that are the receiving ports
"""
return self._get_attribute(self._SDM_ATT_MAP['RxPortIds'])
@RxPortIds.setter
def RxPortIds(self, value):
self._set_attribute(self._SDM_ATT_MAP['RxPortIds'], value)
@property
def RxPortNames(self):
"""
Returns
-------
- list(str): A list of names from the receiving virtual ports.
"""
return self._get_attribute(self._SDM_ATT_MAP['RxPortNames'])
@property
def State(self):
"""
Returns
-------
- str: (Read only) Denotes the current state of the stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['State'])
@property
def Suspend(self):
"""
Returns
-------
- bool: Suspends all traffic on this high level stream.
"""
return self._get_attribute(self._SDM_ATT_MAP['Suspend'])
@Suspend.setter
def Suspend(self, value):
self._set_attribute(self._SDM_ATT_MAP['Suspend'], value)
@property
def TxPortId(self):
"""
Returns
-------
- str(None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport): The virtual port that is the transmitting port.
"""
return self._get_attribute(self._SDM_ATT_MAP['TxPortId'])
@TxPortId.setter
def TxPortId(self, value):
self._set_attribute(self._SDM_ATT_MAP['TxPortId'], value)
@property
def TxPortName(self):
"""
Returns
-------
- str: The name of the virtual port that is the transmitting port.
"""
return self._get_attribute(self._SDM_ATT_MAP['TxPortName'])
def update(self, Crc=None, DestinationMacMode=None, Enabled=None, Name=None, Pause=None, PreambleCustomSize=None, PreambleFrameSizeMode=None, RxPortIds=None, Suspend=None, TxPortId=None):
"""Updates highLevelStream resource on the server.
Args
----
- Crc (str(badCrc | goodCrc)): The Cyclic Redundancy Check frame of the configured high level stream.
- DestinationMacMode (str(arp | manual)): The mode in which the Destination MAC Address is configured, either manual or ARP.
- Enabled (bool):
- Name (str): An alphanumeric string that returns the name of the field.
- Pause (bool): If true then pause is enabled.
- PreambleCustomSize (number): Customizes the preamble size of the frame.
- PreambleFrameSizeMode (str(auto | custom)): The starting size of the frame.
- RxPortIds (list(str[None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport])): A list of virtual ports that are the receiving ports
- Suspend (bool): Suspends all traffic on this high level stream.
- TxPortId (str(None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport)): The virtual port that is the transmitting port.
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
def find(self, AppliedFrameRate=None, AppliedFrameSize=None, AppliedPacketCount=None, Crc=None, CurrentPacketCount=None, DestinationMacMode=None, Distributions=None, Enabled=None, EncapsulationName=None, EndpointSetId=None, Name=None, OverSubscribed=None, Pause=None, PreambleCustomSize=None, PreambleFrameSizeMode=None, RxPortIds=None, RxPortNames=None, State=None, Suspend=None, TxPortId=None, TxPortName=None):
"""Finds and retrieves highLevelStream resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve highLevelStream resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all highLevelStream resources from the server.
Args
----
- AppliedFrameRate (str):
- AppliedFrameSize (str): (Read only) Indicates the applied frame size of the high level stream.
- AppliedPacketCount (number): (Read only) Indicates the aplied packet count of the high level stream.
- Crc (str(badCrc | goodCrc)): The Cyclic Redundancy Check frame of the configured high level stream.
- CurrentPacketCount (number): (Read only) Denotes the number of packets.
- DestinationMacMode (str(arp | manual)): The mode in which the Destination MAC Address is configured, either manual or ARP.
- Distributions (list(dict(arg1:str,arg2:str))): Denotes the distribution of the high level stream.
- Enabled (bool):
- EncapsulationName (str): Name of the configured encapsulation type.
- EndpointSetId (number): The ID of the configured endpoint set.
- Name (str): An alphanumeric string that returns the name of the field.
- OverSubscribed (bool): If true, the rate is oversubscribed.
- Pause (bool): If true then pause is enabled.
- PreambleCustomSize (number): Customizes the preamble size of the frame.
- PreambleFrameSizeMode (str(auto | custom)): The starting size of the frame.
- RxPortIds (list(str[None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport])): A list of virtual ports that are the receiving ports
- RxPortNames (list(str)): A list of names from the receiving virtual ports.
- State (str): (Read only) Denotes the current state of the stream.
- Suspend (bool): Suspends all traffic on this high level stream.
- TxPortId (str(None | /api/v1/sessions/1/ixnetwork/lag | /api/v1/sessions/1/ixnetwork/vport)): The virtual port that is the transmitting port.
- TxPortName (str): The name of the virtual port that is the transmitting port.
Returns
-------
- self: This instance with matching highLevelStream resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
def read(self, href):
"""Retrieves a single instance of highLevelStream data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the highLevelStream resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
def DeleteQuickFlowGroups(self):
"""Executes the deleteQuickFlowGroups operation on the server.
Deletes a list of quick flow groups.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
return self._execute('deleteQuickFlowGroups', payload=payload, response_object=None)
def DuplicateQuickFlowGroups(self, *args, **kwargs):
"""Executes the duplicateQuickFlowGroups operation on the server.
Duplicate selected quick flows with the count provided.
duplicateQuickFlowGroups(Arg2=number)
-------------------------------------
- Arg2 (number): Duplicate count
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('duplicateQuickFlowGroups', payload=payload, response_object=None)
def GetPacketViewInHex(self, *args, **kwargs):
"""Executes the getPacketViewInHex operation on the server.
Gets packet in Hex format for selected highLevelstream and for the given packet index
getPacketViewInHex(Arg2=number)string
-------------------------------------
- Arg2 (number): Packet Index (0 based)
- Returns str: Packet in Hex format
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('getPacketViewInHex', payload=payload, response_object=None)
def PauseStatelessTraffic(self, *args, **kwargs):
"""Executes the pauseStatelessTraffic operation on the server.
Pause or Resume stateless traffic.
pauseStatelessTraffic(Arg2=bool)
--------------------------------
- Arg2 (bool): If true, it will pause running traffic. If false, it will resume previously paused traffic.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('pauseStatelessTraffic', payload=payload, response_object=None)
def PreviewFlowPackets(self, *args, **kwargs):
"""Executes the previewFlowPackets operation on the server.
Preview packets for selected highLevelstream
previewFlowPackets(Arg2=number, Arg3=number)object
--------------------------------------------------
- Arg2 (number):
- Arg3 (number):
- Returns dict(arg1:number,arg2:number,arg3:list[str],arg4:list[list[str]]): No return value.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('previewFlowPackets', payload=payload, response_object=None)
def StartStatelessTraffic(self):
"""Executes the startStatelessTraffic operation on the server.
Start the traffic configuration for stateless traffic items only.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
return self._execute('startStatelessTraffic', payload=payload, response_object=None)
def StartStatelessTrafficBlocking(self):
"""Executes the startStatelessTrafficBlocking operation on the server.
Start the traffic configuration for stateless traffic items only. This will block until traffic is fully started.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
return self._execute('startStatelessTrafficBlocking', payload=payload, response_object=None)
def StopStatelessTraffic(self):
"""Executes the stopStatelessTraffic operation on the server.
Stop the stateless traffic items.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
return self._execute('stopStatelessTraffic', payload=payload, response_object=None)
def StopStatelessTrafficBlocking(self):
"""Executes the stopStatelessTrafficBlocking operation on the server.
Stop the traffic configuration for stateless traffic items only. This will block until traffic is fully stopped.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
return self._execute('stopStatelessTrafficBlocking', payload=payload, response_object=None)
| 40.38204 | 417 | 0.651954 | 2,849 | 26,531 | 5.985258 | 0.123903 | 0.025862 | 0.017945 | 0.025158 | 0.60638 | 0.580753 | 0.540523 | 0.521757 | 0.492787 | 0.448628 | 0 | 0.003599 | 0.245863 | 26,531 | 656 | 418 | 40.443598 | 0.848661 | 0.482341 | 0 | 0.246696 | 0 | 0 | 0.116209 | 0.02035 | 0 | 0 | 0 | 0 | 0 | 1 | 0.23348 | false | 0 | 0.048458 | 0 | 0.524229 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
91db7b3ed00b34e2c5b30939e491462d11c394f1 | 377 | py | Python | src/lib/killable_thread.py | theyaoster/valorant-rpc | ffc54d5cdbca27a6b4433689628017a1e9fad6af | [
"MIT"
] | null | null | null | src/lib/killable_thread.py | theyaoster/valorant-rpc | ffc54d5cdbca27a6b4433689628017a1e9fad6af | [
"MIT"
] | null | null | null | src/lib/killable_thread.py | theyaoster/valorant-rpc | ffc54d5cdbca27a6b4433689628017a1e9fad6af | [
"MIT"
] | null | null | null | from threading import Thread, Event
class KillableThread(Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(KillableThread, self).__init__(*args, **kwargs)
self._stop_event = Event()
def stop(self):
self._stop_event.set() | 31.416667 | 72 | 0.668435 | 47 | 377 | 5.106383 | 0.574468 | 0.083333 | 0.108333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.212202 | 377 | 12 | 73 | 31.416667 | 0.808081 | 0.275862 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.285714 | false | 0 | 0.142857 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
91dd1bc91472d2676d65ea686c2ddb23ea30f5d4 | 1,991 | py | Python | test_filter.py | BenPortner/panflute-filters | 4b35c68f95eb411fa511d889ff7c8d08db17a700 | [
"BSD-3-Clause"
] | 49 | 2016-04-27T05:31:10.000Z | 2022-02-22T22:01:16.000Z | test_filter.py | BenPortner/panflute-filters | 4b35c68f95eb411fa511d889ff7c8d08db17a700 | [
"BSD-3-Clause"
] | 3 | 2018-08-17T02:15:01.000Z | 2020-01-02T01:43:58.000Z | test_filter.py | BenPortner/panflute-filters | 4b35c68f95eb411fa511d889ff7c8d08db17a700 | [
"BSD-3-Clause"
] | 17 | 2016-12-12T18:15:03.000Z | 2022-03-17T22:35:30.000Z | """
Test a filter directly from python instead of through markdown
Note: this is an experimental program
"""
# Test a filter in ./filters
# Use markdown text from ./tests
# Avoid pandoc with its ineffective error messages
# https://realpython.com/blog/python/comparing-python-command-line-parsing-libraries-argparse-docopt-click/
import os
import io
import sys
import importlib
import panflute as pf
def run_test(name, action):
input_fn = os.path.join('tests', name + '.md')
# Read markdown, convert to JSON and then to elements
with open(input_fn, encoding='utf-8') as f:
md = f.read()
print('~' * 80)
print(' ' * 30, 'INPUT')
print('~' * 80)
print(md)
print('~' * 80, '\n')
print('... Parsing markdown')
doc = pf.convert_text(md, output_format='doc')
doc.format = 'markdown'
assert type(doc) == pf.Doc
print(' Done.')
# Walk through AST
sys.path.append('filters')
print('... Importing module')
mod = importlib.import_module(name)
print(' Done.')
f_action = mod.__dict__[action]
print('... Applying filters')
altered = doc.walk(f_action, doc)
print(' Done.')
# Convert AST into JSON
print('... Converting document into JSON')
with io.StringIO() as f:
pf.dump(altered, f)
contents = f.getvalue()
print(' Done.')
# Convert JSON into markdown
print('... Converting JSON into markdown')
md = pf.convert_text(contents, input_format='json', output_format='markdown')
print(' Done.')
print('~' * 80)
print(' ' * 30, 'OUTPUT')
print('~' * 80)
print(md)
print('~' * 80, '\n')
# Create markdown
if __name__ == '__main__':
if len(sys.argv) == 1:
print('Invalid syntax')
raise Exception
name = sys.argv[1]
action = sys.argv[2]
# TODO: add support for prepare .. output format, etc.
run_test(name, action)
print('Done!') | 25.857143 | 107 | 0.60221 | 253 | 1,991 | 4.644269 | 0.442688 | 0.035745 | 0.040851 | 0.028936 | 0.037447 | 0.037447 | 0.037447 | 0 | 0 | 0 | 0 | 0.013468 | 0.254144 | 1,991 | 77 | 108 | 25.857143 | 0.777778 | 0.252637 | 0 | 0.270833 | 0 | 0 | 0.179348 | 0 | 0 | 0 | 0 | 0.012987 | 0.020833 | 1 | 0.020833 | false | 0 | 0.145833 | 0 | 0.166667 | 0.458333 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
91e7b0d0d98ad67ee34d262b781c1c226622b58f | 3,135 | py | Python | 2020/21_AllergenAssessment/test_label.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 1 | 2021-01-03T23:09:28.000Z | 2021-01-03T23:09:28.000Z | 2020/21_AllergenAssessment/test_label.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | 6 | 2020-12-26T21:02:42.000Z | 2020-12-26T21:02:52.000Z | 2020/21_AllergenAssessment/test_label.py | deanearlwright/AdventOfCode | ca4cf6315c0efa38bd7748fb6f4bc99e7934871d | [
"MIT"
] | null | null | null | # ======================================================================
# Allergen Assessment
# Advent of Code 2020 Day 21 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ======================================================================
# t e s t _ l a b e l . p y
# ======================================================================
"Test Label for Advent of Code 2020 day 21, Allergen Assessment"
# ----------------------------------------------------------------------
# import
# ----------------------------------------------------------------------
import unittest
import label
# ----------------------------------------------------------------------
# constants
# ----------------------------------------------------------------------
EXAMPLE_TEXT = "mxmxvkd kfcds sqjhc nhms (contains dairy, fish)"
# ======================================================================
# TestLabel
# ======================================================================
class TestLabel(unittest.TestCase): # pylint: disable=R0904
"Test Label object"
def test_empty_init(self):
"Test the default Label creation"
# 1. Create default Label object
myobj = label.Label()
# 2. Make sure it has the default values
self.assertEqual(myobj.part2, False)
self.assertEqual(myobj.text, None)
self.assertEqual(len(myobj.ingredients), 0)
self.assertEqual(len(myobj.allergens), 0)
def test_text_init(self):
"Test the Label object creation from text"
# 1. Create Label object from text
myobj = label.Label(text=EXAMPLE_TEXT)
# 2. Make sure it has the expected values
self.assertEqual(myobj.part2, False)
self.assertEqual(len(myobj.text), 47)
self.assertEqual(len(myobj.ingredients), 4)
self.assertEqual(len(myobj.allergens), 2)
# 3. Check methods
self.assertEqual(myobj.has_ingredient('mxmxvkd'), True)
self.assertEqual(myobj.has_ingredient('kfcds'), True)
self.assertEqual(myobj.has_ingredient('dairy'), False)
self.assertEqual(myobj.has_allergen('dairy'), True)
self.assertEqual(myobj.has_allergen('fish'), True)
self.assertEqual(myobj.has_allergen('soy'), False)
self.assertEqual(myobj.has_allergen('kfcds'), False)
# ----------------------------------------------------------------------
# module initialization
# ----------------------------------------------------------------------
if __name__ == '__main__':
pass
# ======================================================================
# end t e s t _ l a b e l . p y end
# ======================================================================
| 41.25 | 72 | 0.388198 | 243 | 3,135 | 4.91358 | 0.378601 | 0.188442 | 0.167504 | 0.134841 | 0.4866 | 0.348409 | 0.103853 | 0.103853 | 0.018425 | 0.018425 | 0 | 0.012098 | 0.235407 | 3,135 | 75 | 73 | 41.8 | 0.486024 | 0.597767 | 0 | 0.068966 | 0 | 0 | 0.172563 | 0 | 0 | 0 | 0 | 0 | 0.517241 | 1 | 0.068966 | false | 0.034483 | 0.068966 | 0 | 0.172414 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91e7d3d6232e739ccea2011d82a6b3d0479b2e79 | 975 | py | Python | album/migrations/0004_auto_20210908_1452.py | Leparwa/personal_gallery | d64d925d5e92d83229dbcdfced323c6981a6dd9f | [
"MIT"
] | null | null | null | album/migrations/0004_auto_20210908_1452.py | Leparwa/personal_gallery | d64d925d5e92d83229dbcdfced323c6981a6dd9f | [
"MIT"
] | null | null | null | album/migrations/0004_auto_20210908_1452.py | Leparwa/personal_gallery | d64d925d5e92d83229dbcdfced323c6981a6dd9f | [
"MIT"
] | null | null | null | # Generated by Django 3.2.7 on 2021-09-08 11:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('album', '0003_auto_20210906_2229'),
]
operations = [
migrations.RenameField(
model_name='image',
old_name='image_category',
new_name='category',
),
migrations.RenameField(
model_name='image',
old_name='image_description',
new_name='description',
),
migrations.RenameField(
model_name='image',
old_name='image_location',
new_name='location',
),
migrations.RenameField(
model_name='image',
old_name='image_name',
new_name='name',
),
migrations.AlterField(
model_name='image',
name='image',
field=models.ImageField(upload_to='images/'),
),
]
| 25 | 57 | 0.538462 | 90 | 975 | 5.6 | 0.455556 | 0.178571 | 0.138889 | 0.238095 | 0.373016 | 0.373016 | 0.373016 | 0.373016 | 0 | 0 | 0 | 0.048742 | 0.347692 | 975 | 38 | 58 | 25.657895 | 0.743711 | 0.046154 | 0 | 0.4375 | 1 | 0 | 0.162716 | 0.024784 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.03125 | 0 | 0.125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
91ea40fb9c20a2bf06d186e2c47c00994dfb8423 | 269 | py | Python | yasc/data/_utils.py | Keris/yasc | eb55000e730fb2e60515a39dac82b851239a2c57 | [
"MIT"
] | 4 | 2020-05-21T06:35:48.000Z | 2021-04-12T10:49:55.000Z | yasc/data/_utils.py | Keris/yasc | eb55000e730fb2e60515a39dac82b851239a2c57 | [
"MIT"
] | null | null | null | yasc/data/_utils.py | Keris/yasc | eb55000e730fb2e60515a39dac82b851239a2c57 | [
"MIT"
] | null | null | null | # Author: Liqiang Du <keris.du@gmail.com>
import pandas as pd
import pkg_resources
def german_data():
"""Return german data as a data frame."""
filename = pkg_resources.resource_filename("yasc", "data/german.csv")
df = pd.read_csv(filename)
return df
| 24.454545 | 73 | 0.70632 | 40 | 269 | 4.625 | 0.6 | 0.12973 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.174721 | 269 | 10 | 74 | 26.9 | 0.833333 | 0.282528 | 0 | 0 | 0 | 0 | 0.101604 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
91ef4b96877e8c3f73d65338465c5a055a450889 | 2,659 | py | Python | kolibri/content/management/commands/generate_schema.py | jonboiser/kolibri | 8ea2febc1739ac772007aae4084f0226dfb4ed40 | [
"MIT"
] | null | null | null | kolibri/content/management/commands/generate_schema.py | jonboiser/kolibri | 8ea2febc1739ac772007aae4084f0226dfb4ed40 | [
"MIT"
] | 5 | 2016-01-22T18:43:44.000Z | 2019-07-25T20:34:16.000Z | kolibri/content/management/commands/generate_schema.py | jonboiser/kolibri | 8ea2febc1739ac772007aae4084f0226dfb4ed40 | [
"MIT"
] | null | null | null | import io
import json
import os
import pickle
from django.apps import apps
from django.core.management import call_command
from django.core.management.base import BaseCommand
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from kolibri.content.utils.sqlalchemybridge import get_default_db_string
from kolibri.content.utils.sqlalchemybridge import SCHEMA_PATH_TEMPLATE
DATA_PATH_TEMPLATE = os.path.join(os.path.dirname(__file__), '../../fixtures/{name}_content_data.json')
class Command(BaseCommand):
"""
This management command produces SQLAlchemy schema reflections of the content database app.
It should be run when the Content Models schema is updated, and if it is a change between released
versions the CONTENT_DB_SCHEMA version should have been incremented.
It also produces a data dump of the content test fixture that fits to this database schema,
so that we can use it for testing purposes.
Note: this command requires an empty, but migrated, database to work properly.
"""
def add_arguments(self, parser):
parser.add_argument('version', type=str)
def handle(self, *args, **options):
engine = create_engine(get_default_db_string(), convert_unicode=True)
metadata = MetaData()
app_config = apps.get_app_config('content')
# Exclude channelmetadatacache in case we are reflecting an older version of Kolibri
table_names = [model._meta.db_table for name, model in app_config.models.items() if name != 'channelmetadatacache']
metadata.reflect(bind=engine, only=table_names)
Base = automap_base(metadata=metadata)
# TODO map relationship backreferences using the django names
Base.prepare()
session = sessionmaker(bind=engine, autoflush=False)()
# Load fixture data into the test database with Django
call_command('loaddata', 'content_import_test.json', interactive=False)
def get_dict(item):
value = {key: value for key, value in item.__dict__.items() if key != '_sa_instance_state'}
return value
data = {}
for table_name, record in Base.classes.items():
data[table_name] = [get_dict(r) for r in session.query(record).all()]
with open(SCHEMA_PATH_TEMPLATE.format(name=options['version']), 'wb') as f:
pickle.dump(metadata, f, protocol=2)
data_path = DATA_PATH_TEMPLATE.format(name=options['version'])
with io.open(data_path, mode='w', encoding='utf-8') as f:
json.dump(data, f)
| 40.287879 | 123 | 0.719443 | 360 | 2,659 | 5.163889 | 0.436111 | 0.030124 | 0.015062 | 0.02582 | 0.087144 | 0.087144 | 0 | 0 | 0 | 0 | 0 | 0.000937 | 0.197067 | 2,659 | 65 | 124 | 40.907692 | 0.869789 | 0.252727 | 0 | 0 | 0 | 0 | 0.074397 | 0.032324 | 0 | 0 | 0 | 0.015385 | 0 | 1 | 0.078947 | false | 0 | 0.368421 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
37ce8f45d3d854f037d61817419a14100f6e5695 | 473 | py | Python | Ago-Dic-2019/Jorge Alberto Hernandez Sanchez/Practicas/Practica1/6.4_Glossary_2.py | Arbupa/DAS_Sistemas | 52263ab91436b2e5a24ce6f8493aaa2e2fe92fb1 | [
"MIT"
] | 41 | 2017-09-26T09:36:32.000Z | 2022-03-19T18:05:25.000Z | Ago-Dic-2019/Jorge Alberto Hernandez Sanchez/Practicas/Practica1/6.4_Glossary_2.py | Arbupa/DAS_Sistemas | 52263ab91436b2e5a24ce6f8493aaa2e2fe92fb1 | [
"MIT"
] | 67 | 2017-09-11T05:06:12.000Z | 2022-02-14T04:44:04.000Z | Ago-Dic-2019/Jorge Alberto Hernandez Sanchez/Practicas/Practica1/6.4_Glossary_2.py | Arbupa/DAS_Sistemas | 52263ab91436b2e5a24ce6f8493aaa2e2fe92fb1 | [
"MIT"
] | 210 | 2017-09-01T00:10:08.000Z | 2022-03-19T18:05:12.000Z | glosario = {'listas' : "Se pueden identificar con []", 'tuplas' : "Se identifican con *()",
'glosario' : "Se identifican con {}", 'if' : "Condicional", 'for' : "Ciclo", '#' : "Para crear un comentario",
'str' : "Abreviacion de String", '==' : "usado para comparar elementos", "=!" : "Usado para verificar que dos elementos son diferentes",
'and' : "Usado en condicionales para comprar mas formas a los elementos"}
for clave in glosario.values():
print(clave.title()) | 67.571429 | 136 | 0.661734 | 57 | 473 | 5.491228 | 0.719298 | 0.083067 | 0.102236 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.162791 | 473 | 7 | 137 | 67.571429 | 0.790404 | 0 | 0 | 0 | 0 | 0 | 0.658228 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.166667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
37dcc568e518aacf8dd11afa2f8cea83ce5733e8 | 139 | py | Python | ex007.py | maurocesarj/Aulas-Senac-Python | 422dcde9c4bfc899d79706df8949dae582dd6ad4 | [
"MIT"
] | null | null | null | ex007.py | maurocesarj/Aulas-Senac-Python | 422dcde9c4bfc899d79706df8949dae582dd6ad4 | [
"MIT"
] | null | null | null | ex007.py | maurocesarj/Aulas-Senac-Python | 422dcde9c4bfc899d79706df8949dae582dd6ad4 | [
"MIT"
] | null | null | null | n = 8
fib0 = 0
fib1 = 1
if n > 0:
temp = fib0
fib0 = fib1
fib1 = fib1 + temp
n = n - 1
else:
print(f'Resultado {fib0}') | 13.9 | 30 | 0.503597 | 24 | 139 | 2.916667 | 0.5 | 0.228571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147727 | 0.366906 | 139 | 10 | 30 | 13.9 | 0.647727 | 0 | 0 | 0 | 0 | 0 | 0.114286 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.1 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
37e32c5acdb023afee668ac7692f842808a5e5c1 | 1,025 | py | Python | pandas_market_calendars/exchange_calendar_dce_night.py | keli/pandas_market_calendars | a289d7dfe52b38c24c767bd9a9f8ad53e34464fc | [
"MIT"
] | null | null | null | pandas_market_calendars/exchange_calendar_dce_night.py | keli/pandas_market_calendars | a289d7dfe52b38c24c767bd9a9f8ad53e34464fc | [
"MIT"
] | null | null | null | pandas_market_calendars/exchange_calendar_dce_night.py | keli/pandas_market_calendars | a289d7dfe52b38c24c767bd9a9f8ad53e34464fc | [
"MIT"
] | null | null | null | from datetime import time, timedelta
from functools import partial
from dateutil.relativedelta import MO
from pandas import DateOffset, Timestamp
from pandas.tseries.holiday import Holiday, next_monday, sunday_to_monday
from pytz import timezone
from pandas.tseries.holiday import AbstractHolidayCalendar
from pandas_market_calendars.holidays_us import USNewYearsDay
from .market_calendar import MarketCalendar
from .exchange_calendar_sse import SSEExchangeCalendar
from .holidays_cn import *
class DCENightExchangeCalendar(SSEExchangeCalendar):
"""
Exchange calendar for Dalian Commodity Exchange
Night Session:
Open Time: 9:00 PM, Asia/Shanghai
Close Time: 11:00 PM, Asia/Shanghai
"""
aliases = ['DCE_night']
regular_market_times = {
"market_open": ((None, time(21, 0)), ),
"market_close": ((None, time(2, 30), 1), ),
}
@property
def name(self):
return "DCE_night"
@property
def tz(self):
return timezone('Asia/Shanghai')
| 26.282051 | 73 | 0.725854 | 122 | 1,025 | 5.967213 | 0.52459 | 0.054945 | 0.046703 | 0.065934 | 0.082418 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016949 | 0.194146 | 1,025 | 38 | 74 | 26.973684 | 0.864407 | 0.137561 | 0 | 0.086957 | 0 | 0 | 0.063084 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.086957 | false | 0 | 0.478261 | 0.086957 | 0.782609 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
37e63889ad82e60a173352371336c284092c7199 | 3,351 | py | Python | tests/test_connection.py | ggarcias/esgf-pyclient-cmip6 | 9e7975d2e676ed2c4001edb4e25c9c20cc16b7af | [
"BSD-3-Clause"
] | 17 | 2016-09-07T02:55:30.000Z | 2022-03-10T15:34:53.000Z | tests/test_connection.py | ggarcias/esgf-pyclient-cmip6 | 9e7975d2e676ed2c4001edb4e25c9c20cc16b7af | [
"BSD-3-Clause"
] | 61 | 2015-05-27T08:10:46.000Z | 2022-03-17T12:36:45.000Z | tests/test_connection.py | ggarcias/esgf-pyclient-cmip6 | 9e7975d2e676ed2c4001edb4e25c9c20cc16b7af | [
"BSD-3-Clause"
] | 22 | 2015-10-27T11:21:05.000Z | 2022-01-12T08:26:16.000Z | """
Test SearchConnection object
"""
# !TODO: replace calls to the a live search service with a mock.
# !TODO: Test for HTTP proxies
import pytest
from pyesgf.search.connection import SearchConnection
import pyesgf.search.exceptions as exc
from unittest import TestCase
import os
import datetime
class TestConnection(TestCase):
def setUp(self):
self.test_service = 'http://esgf-index1.ceda.ac.uk/esg-search'
self.cache = os.path.join(os.path.dirname(__file__), 'url_cache')
def test_blank_query(self):
conn = SearchConnection(self.test_service, cache=self.cache)
json = conn.send_search({})
assert sorted(json.keys()) == sorted(['facet_counts',
'responseHeader', 'response'])
@pytest.mark.skip(reason="no exception is thrown")
def test_get_shard_list_fail(self):
conn = SearchConnection(self.test_service, cache=self.cache,
distrib=False)
with pytest.raises(exc.EsgfSearchException):
conn.get_shard_list
def test_get_shard_list(self):
conn = SearchConnection(self.test_service, cache=self.cache,
distrib=True)
shards = conn.get_shard_list()
# !NOTE: the exact shard list will change depending on the shard
# replication configuration
# on the test server
assert 'esgf-index1.ceda.ac.uk' in shards
# in esg-search in esgf-index1.ceda.ac.uk, there are a bunch
# of replicas hosted on esgf-index2
assert len(shards['esgf-index2.ceda.ac.uk']) > 1
def test_url_fixing(self):
# Switch off warnings for this case because we are testing that issue
import warnings
warnings.simplefilter("ignore")
conn1 = SearchConnection(self.test_service)
conn2 = SearchConnection(self.test_service + '/')
conn3 = SearchConnection(self.test_service + '///')
conn4 = SearchConnection(self.test_service + '/search')
conn5 = SearchConnection(self.test_service + '/search///')
warnings.resetwarnings()
assert conn1.url == conn2.url == conn3.url == conn4.url == conn5.url
def test_passed_session(self):
import requests
session = requests.session()
conn = SearchConnection(self.test_service, session=session)
context = conn.new_context(project='cmip5')
assert context.facet_constraints['project'] == 'cmip5'
def test_passed_cached_session(self):
import requests_cache
td = datetime.timedelta(hours=1)
session = requests_cache.CachedSession(self.cache,
expire_after=td)
conn = SearchConnection(self.test_service, session=session)
context = conn.new_context(project='cmip5')
assert context.facet_constraints['project'] == 'cmip5'
def test_connection_instance(self):
import requests_cache
td = datetime.timedelta(hours=1)
session = requests_cache.CachedSession(self.cache,
expire_after=td)
with SearchConnection(self.test_service, session=session) as conn:
context = conn.new_context(project='cmip5')
assert context.facet_constraints['project'] == 'cmip5'
| 39.423529 | 77 | 0.640704 | 380 | 3,351 | 5.510526 | 0.339474 | 0.045845 | 0.08596 | 0.162846 | 0.441261 | 0.361987 | 0.340497 | 0.340497 | 0.340497 | 0.315186 | 0 | 0.009705 | 0.262011 | 3,351 | 84 | 78 | 39.892857 | 0.83704 | 0.120561 | 0 | 0.305085 | 0 | 0 | 0.077448 | 0.015012 | 0 | 0 | 0 | 0.011905 | 0.118644 | 1 | 0.135593 | false | 0.033898 | 0.169492 | 0 | 0.322034 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
37eff37a79d6fa2720133b72c94b03a522b25653 | 1,616 | py | Python | aiotdlib/api/functions/report_chat_photo.py | jraylan/aiotdlib | 4528fcfca7c5c69b54a878ce6ce60e934a2dcc73 | [
"MIT"
] | null | null | null | aiotdlib/api/functions/report_chat_photo.py | jraylan/aiotdlib | 4528fcfca7c5c69b54a878ce6ce60e934a2dcc73 | [
"MIT"
] | null | null | null | aiotdlib/api/functions/report_chat_photo.py | jraylan/aiotdlib | 4528fcfca7c5c69b54a878ce6ce60e934a2dcc73 | [
"MIT"
] | null | null | null | # =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# #
# =============================================================================== #
from __future__ import annotations
import typing
from pydantic import Field
from ..base_object import BaseObject
from ..types import ChatReportReason
class ReportChatPhoto(BaseObject):
"""
Reports a chat photo to the Telegram moderators. A chat photo can be reported only if this is a private chat with a bot, a private chat with a user sharing their location, a supergroup, or a channel, since other chats can't be checked by moderators
:param chat_id: Chat identifier
:type chat_id: :class:`int`
:param file_id: Identifier of the photo to report. Only full photos from chatPhoto can be reported
:type file_id: :class:`int`
:param reason: The reason for reporting the chat photo
:type reason: :class:`ChatReportReason`
:param text: Additional report details; 0-1024 characters, defaults to None
:type text: :class:`str`, optional
"""
ID: str = Field("reportChatPhoto", alias="@type")
chat_id: int
file_id: int
reason: ChatReportReason
text: typing.Optional[str] = Field(None, max_length=1024)
@staticmethod
def read(q: dict) -> ReportChatPhoto:
return ReportChatPhoto.construct(**q)
| 37.581395 | 252 | 0.5625 | 174 | 1,616 | 5.155172 | 0.5 | 0.0301 | 0.022297 | 0.035674 | 0.037904 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007686 | 0.275371 | 1,616 | 42 | 253 | 38.47619 | 0.758326 | 0.649752 | 0 | 0 | 1 | 0 | 0.041068 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.071429 | false | 0 | 0.357143 | 0.071429 | 0.928571 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
532346ec2586c3d4db1bec6c41278704fb4cdb8f | 402 | py | Python | Python/Basic Programs/Electricity_bill.py | themohitpapneja/Code_Dump | ec72144e66d12cba2ce719c37292517588490b42 | [
"Apache-2.0"
] | null | null | null | Python/Basic Programs/Electricity_bill.py | themohitpapneja/Code_Dump | ec72144e66d12cba2ce719c37292517588490b42 | [
"Apache-2.0"
] | null | null | null | Python/Basic Programs/Electricity_bill.py | themohitpapneja/Code_Dump | ec72144e66d12cba2ce719c37292517588490b42 | [
"Apache-2.0"
] | null | null | null | ##Electricity Bill Calculator, given the units consumed.
## using if-else ladder
n=eval(input("Enter Units : "))
price=0
if n<=100:
price=n*1.5+25
elif 101 <= n <= 200:
price=(100*1.5)+(n-100)*3+50
elif 201 <= n <= 300:
price= (100*1.5)+(100*3)+(n-200)*5+75
elif 301 <= n <= 400:
price= (100*1.5) + (100*3) + 100 * 5 + (n - 300) * 7 + 100
else:
price=400
print("Price is :",price)
| 23.647059 | 62 | 0.574627 | 75 | 402 | 3.08 | 0.453333 | 0.034632 | 0.116883 | 0.12987 | 0.121212 | 0.121212 | 0 | 0 | 0 | 0 | 0 | 0.234375 | 0.20398 | 402 | 16 | 63 | 25.125 | 0.4875 | 0.186567 | 0 | 0 | 0 | 0 | 0.074303 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.076923 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5324494c8886b06a7cded4611335f11d128501aa | 1,651 | py | Python | mov_sdk/utils.py | Bytom/mov_api_doc | 484e995cf5a0b0e2423d62c6c0fef5362bc49157 | [
"MIT"
] | 3 | 2020-05-12T01:36:17.000Z | 2021-01-12T08:02:18.000Z | mov_sdk/utils.py | Bytom/mov_api_doc | 484e995cf5a0b0e2423d62c6c0fef5362bc49157 | [
"MIT"
] | 5 | 2021-06-02T01:45:42.000Z | 2022-03-12T00:28:41.000Z | mov_sdk/utils.py | Bytom/mov_api_doc | 484e995cf5a0b0e2423d62c6c0fef5362bc49157 | [
"MIT"
] | null | null | null | import qrcode
import pybase64
import six
import hmac
from io import BytesIO
from binascii import hexlify
from binascii import unhexlify
from .edwards25519 import *
# create_qrcode_base64 create qrcode, then encode it to base64
# type(s) is str
def create_qrcode_base64(s):
img = qrcode.make(s)
buffered = BytesIO()
img.save(buffered, format="JPEG")
base64_str = pybase64.b64encode(buffered.getvalue()).decode("utf-8")
return base64_str
if six.PY3:
def byte2int(b):
return b
def int2byte(i):
return bytes(chr(i % 256), encoding="UTF-8")
elif six.PY2:
def byte2int(b):
return ord(b)
def int2byte(i):
return chr(i % 256)
L = 2 ** 252 + 27742317777372353535851937790883648493
def hmac_sha_512(data, key):
digest = hmac.new(key, msg=data, digestmod=hashlib.sha512).digest()
return digest
def sha_512(data):
md = hashlib.sha512()
md.update(data)
return md.digest()
def hex2int(hex):
## converts a hex string to integer
unhex = unhexlify(hex)
s = 0
for i in range(len(unhex)):
s += 256 ** i * byte2int(unhex[i])
return s
def int2hex(int):
## converts an integer to a little endian encoded hex string
return hexlify(encodeint(int))
def sc_reduce32(input):
## convert hex string input to integer
int = hex2int(input)
## reduce mod l
modulo = int % L
## convert back to hex string for return value
return int2hex(modulo)
def sc_muladd(a, b, c):
a_int = hex2int(a)
b_int = hex2int(b)
c_int = hex2int(c)
s = a_int * b_int + c_int
modulo = s % L
return int2hex(modulo)
| 20.134146 | 72 | 0.65536 | 241 | 1,651 | 4.419087 | 0.390041 | 0.033803 | 0.033803 | 0.033803 | 0.035681 | 0 | 0 | 0 | 0 | 0 | 0 | 0.083067 | 0.241672 | 1,651 | 81 | 73 | 20.382716 | 0.767572 | 0.156875 | 0 | 0.117647 | 0 | 0 | 0.010152 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.215686 | false | 0 | 0.156863 | 0.098039 | 0.588235 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
53251378d77be4e5f6a8b0612e0995707b4638ef | 260 | py | Python | ex022.py | joaovitorsud/Python-exercicios | e2b49e10eef991a9fc8029d5afdaae0a7326192c | [
"MIT"
] | null | null | null | ex022.py | joaovitorsud/Python-exercicios | e2b49e10eef991a9fc8029d5afdaae0a7326192c | [
"MIT"
] | null | null | null | ex022.py | joaovitorsud/Python-exercicios | e2b49e10eef991a9fc8029d5afdaae0a7326192c | [
"MIT"
] | null | null | null | nome = input("qual é o seu nome?").strip()
print("nome em letras maiusculas", nome.upper())
print("nome com letras minusculas", nome.lower())
print("numero de letras no nome {}".format(len(nome)-nome.count(" ")))
print("primeiro nome tem {} letras".format())
| 37.142857 | 70 | 0.688462 | 39 | 260 | 4.589744 | 0.589744 | 0.100559 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.115385 | 260 | 6 | 71 | 43.333333 | 0.778261 | 0 | 0 | 0 | 0 | 0 | 0.478764 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.8 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
5331a05c46daa5eac2060b0caaeecf05e8340f6c | 313 | py | Python | robonomicsinterface/exceptions.py | nakata5321/robonomics-interface | 724af30bea6643b2ee9ece334343229e64aa4285 | [
"Apache-2.0"
] | null | null | null | robonomicsinterface/exceptions.py | nakata5321/robonomics-interface | 724af30bea6643b2ee9ece334343229e64aa4285 | [
"Apache-2.0"
] | null | null | null | robonomicsinterface/exceptions.py | nakata5321/robonomics-interface | 724af30bea6643b2ee9ece334343229e64aa4285 | [
"Apache-2.0"
] | null | null | null | class NoPrivateKey(Exception):
"""
No private key was provided so unable to perform any operations requiring message signing.
"""
pass
class DigitalTwinMapError(Exception):
"""
No Digital Twin was created with this index or there is no such topic in Digital Twin map.
"""
pass
| 20.866667 | 94 | 0.686901 | 40 | 313 | 5.375 | 0.8 | 0.102326 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.249201 | 313 | 14 | 95 | 22.357143 | 0.914894 | 0.578275 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.5 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
5334a67c03b90c76d0c53780409062fad2c6c899 | 20,812 | py | Python | pysnmp/CISCO-VPN-LIC-USAGE-MONITOR-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/CISCO-VPN-LIC-USAGE-MONITOR-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/CISCO-VPN-LIC-USAGE-MONITOR-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 CISCO-VPN-LIC-USAGE-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VPN-LIC-USAGE-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:26 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
MibIdentifier, ObjectIdentity, Counter64, TimeTicks, IpAddress, ModuleIdentity, Bits, Unsigned32, Counter32, NotificationType, iso, Gauge32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "ObjectIdentity", "Counter64", "TimeTicks", "IpAddress", "ModuleIdentity", "Bits", "Unsigned32", "Counter32", "NotificationType", "iso", "Gauge32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoVpnLicUsageMonitorMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 816))
ciscoVpnLicUsageMonitorMIB.setRevisions(('2013-09-13 00:00',))
if mibBuilder.loadTexts: ciscoVpnLicUsageMonitorMIB.setLastUpdated('201309130000Z')
if mibBuilder.loadTexts: ciscoVpnLicUsageMonitorMIB.setOrganization('Cisco Systems, Inc.')
class VPNLicType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("other", 1), ("anyconnectpremium", 2))
class VPNLicDeviceRole(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("server", 1), ("bkpserver", 2), ("client", 3))
class LicServerStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("active", 1), ("inactive", 2), ("expired", 3))
class LicServerRegistered(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("no", 1), ("yes", 2), ("invalid", 3))
ciscoVpnLicUsageMonitorMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 0))
ciscoVpnLicUsageMonitorMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 1))
ciscoVpnLicUsageMonitorMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 1, 1))
cvpnLicDeviceRole = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 1), VPNLicDeviceRole()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicDeviceRole.setStatus('current')
cvpnLicServer = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2))
cvpnLicBkpServer = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3))
cvpnLicClient = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4))
cvpnLicServerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 1), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerAddrType.setStatus('current')
cvpnLicServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 2), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerAddr.setStatus('current')
cvpnLicBkpSerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 3), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpSerAddrType.setStatus('current')
cvpnLicBkpSerAddr = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 4), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpSerAddr.setStatus('current')
cvpnLicServerVer = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerVer.setStatus('current')
cvpnLicServerStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 6), LicServerStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerStatus.setStatus('current')
cvpnLicServerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7), )
if mibBuilder.loadTexts: cvpnLicServerTable.setStatus('current')
cvpnLicServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7, 1), ).setIndexNames((0, "CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerVPNLicType"))
if mibBuilder.loadTexts: cvpnLicServerEntry.setStatus('current')
cvpnLicServerVPNLicType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7, 1, 1), VPNLicType())
if mibBuilder.loadTexts: cvpnLicServerVPNLicType.setStatus('current')
cvpnLicServerNumLicCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7, 1, 2), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerNumLicCapacity.setStatus('current')
cvpnLicServerNumLicAvail = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7, 1, 3), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerNumLicAvail.setStatus('current')
cvpnLicServerUtilized = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 2, 7, 1, 4), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerUtilized.setStatus('current')
cvpnLicBkpServerAddrType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 1), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerAddrType.setStatus('current')
cvpnLicBkpServerAddr = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 2), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerAddr.setStatus('current')
cvpnLicBkpServerDevID = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerDevID.setStatus('current')
cvpnLicBkpServerVer = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 4), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerVer.setStatus('current')
cvpnLicBkpServerRegd = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 5), LicServerRegistered()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerRegd.setStatus('current')
cvpnLicBkpServerHAPeerDevID = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerHAPeerDevID.setStatus('current')
cvpnLicBkpServerHAPeerRegd = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 7), LicServerRegistered()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerHAPeerRegd.setStatus('current')
cvpnLicBkpServerStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 8), LicServerStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicBkpServerStatus.setStatus('current')
cvpnLicServerHelloTx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 9), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerHelloTx.setStatus('current')
cvpnLicServerHelloRx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 10), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerHelloRx.setStatus('current')
cvpnLicServerHelloError = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 11), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerHelloError.setStatus('current')
cvpnLicServerSyncTx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 12), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerSyncTx.setStatus('current')
cvpnLicServerSyncRx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 13), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerSyncRx.setStatus('current')
cvpnLicServerSyncError = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 14), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerSyncError.setStatus('current')
cvpnLicServerUpdateTx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 15), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerUpdateTx.setStatus('current')
cvpnLicServerUpdateRx = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 16), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerUpdateRx.setStatus('current')
cvpnLicServerUpdateError = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 3, 17), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicServerUpdateError.setStatus('current')
cvpnLicClntInfoTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1), )
if mibBuilder.loadTexts: cvpnLicClntInfoTable.setStatus('current')
cvpnLicClntInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1), ).setIndexNames((0, "CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntVPNLicType"), (0, "CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoDeviceID"))
if mibBuilder.loadTexts: cvpnLicClntInfoEntry.setStatus('current')
cvpnLicClntVPNLicType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 1), VPNLicType())
if mibBuilder.loadTexts: cvpnLicClntVPNLicType.setStatus('current')
cvpnLicClntInfoDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64)))
if mibBuilder.loadTexts: cvpnLicClntInfoDeviceID.setStatus('current')
cvpnLicClntInfoHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoHostName.setStatus('current')
cvpnLicClntInfoPlatLmt = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 4), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoPlatLmt.setStatus('current')
cvpnLicClntInfoCurUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 5), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoCurUsage.setStatus('current')
cvpnLicClntInfoHigh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 6), Unsigned32()).setUnits('license').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoHigh.setStatus('current')
cvpnLicClntInfoRegReqTx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 7), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRegReqTx.setStatus('current')
cvpnLicClntInfoRegReqRx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 8), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRegReqRx.setStatus('current')
cvpnLicClntInfoRegReqError = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 9), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRegReqError.setStatus('current')
cvpnLicClntInfoGetReqTx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 10), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoGetReqTx.setStatus('current')
cvpnLicClntInfoGetReqRx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 11), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoGetReqRx.setStatus('current')
cvpnLicClntInfoGetReqError = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 12), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoGetReqError.setStatus('current')
cvpnLicClntInfoRelReqTx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 13), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRelReqTx.setStatus('current')
cvpnLicClntInfoRelReqRx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 14), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRelReqRx.setStatus('current')
cvpnLicClntInfoRelReqError = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 15), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoRelReqError.setStatus('current')
cvpnLicClntInfoTransferReqTx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 16), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoTransferReqTx.setStatus('current')
cvpnLicClntInfoTransferReqRx = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 17), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoTransferReqRx.setStatus('current')
cvpnLicClntInfoTransferReqError = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 816, 0, 4, 1, 1, 18), Counter32()).setUnits('packets').setMaxAccess("readonly")
if mibBuilder.loadTexts: cvpnLicClntInfoTransferReqError.setStatus('current')
ciscoVpnLicUsageMonitorMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 816, 1, 2))
ciscoVpnLicUsageMonitorMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 816, 1, 1, 1)).setObjects(("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "ciscoVPNSharedLicUsageMandatoryGroup"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "ciscoVPNSharedLicOptUsageGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVpnLicUsageMonitorMIBCompliance = ciscoVpnLicUsageMonitorMIBCompliance.setStatus('current')
ciscoVPNSharedLicUsageMandatoryGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 816, 1, 2, 1)).setObjects(("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicDeviceRole"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerAddrType"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerAddr"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpSerAddrType"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpSerAddr"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerVer"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerStatus"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerNumLicCapacity"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerNumLicAvail"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerUtilized"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoHostName"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoPlatLmt"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoCurUsage"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoHigh"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVPNSharedLicUsageMandatoryGroup = ciscoVPNSharedLicUsageMandatoryGroup.setStatus('current')
ciscoVPNSharedLicOptUsageGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 816, 1, 2, 2)).setObjects(("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerAddrType"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerAddr"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerDevID"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerVer"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerRegd"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerHAPeerDevID"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerHAPeerRegd"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicBkpServerStatus"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerHelloTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerHelloRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerHelloError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerSyncTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerSyncRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerSyncError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerUpdateTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerUpdateRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicServerUpdateError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRegReqTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRegReqRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRegReqError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoGetReqTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoGetReqRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoGetReqError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRelReqTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRelReqRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoRelReqError"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoTransferReqTx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoTransferReqRx"), ("CISCO-VPN-LIC-USAGE-MONITOR-MIB", "cvpnLicClntInfoTransferReqError"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoVPNSharedLicOptUsageGroup = ciscoVPNSharedLicOptUsageGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-VPN-LIC-USAGE-MONITOR-MIB", cvpnLicClient=cvpnLicClient, cvpnLicServerVer=cvpnLicServerVer, cvpnLicClntInfoEntry=cvpnLicClntInfoEntry, cvpnLicBkpServerHAPeerDevID=cvpnLicBkpServerHAPeerDevID, cvpnLicBkpServerHAPeerRegd=cvpnLicBkpServerHAPeerRegd, cvpnLicServerHelloTx=cvpnLicServerHelloTx, LicServerStatus=LicServerStatus, cvpnLicClntInfoHostName=cvpnLicClntInfoHostName, cvpnLicClntInfoRelReqRx=cvpnLicClntInfoRelReqRx, ciscoVpnLicUsageMonitorMIBCompliance=ciscoVpnLicUsageMonitorMIBCompliance, cvpnLicServerUpdateRx=cvpnLicServerUpdateRx, ciscoVpnLicUsageMonitorMIBGroups=ciscoVpnLicUsageMonitorMIBGroups, cvpnLicClntInfoTransferReqTx=cvpnLicClntInfoTransferReqTx, cvpnLicServerUpdateError=cvpnLicServerUpdateError, cvpnLicServerSyncTx=cvpnLicServerSyncTx, cvpnLicClntInfoTransferReqError=cvpnLicClntInfoTransferReqError, ciscoVpnLicUsageMonitorMIBCompliances=ciscoVpnLicUsageMonitorMIBCompliances, cvpnLicServerVPNLicType=cvpnLicServerVPNLicType, ciscoVPNSharedLicOptUsageGroup=ciscoVPNSharedLicOptUsageGroup, cvpnLicServerStatus=cvpnLicServerStatus, VPNLicDeviceRole=VPNLicDeviceRole, cvpnLicServerUpdateTx=cvpnLicServerUpdateTx, ciscoVPNSharedLicUsageMandatoryGroup=ciscoVPNSharedLicUsageMandatoryGroup, cvpnLicBkpSerAddr=cvpnLicBkpSerAddr, cvpnLicBkpServerRegd=cvpnLicBkpServerRegd, cvpnLicClntVPNLicType=cvpnLicClntVPNLicType, cvpnLicClntInfoPlatLmt=cvpnLicClntInfoPlatLmt, cvpnLicClntInfoRelReqTx=cvpnLicClntInfoRelReqTx, cvpnLicClntInfoRegReqTx=cvpnLicClntInfoRegReqTx, ciscoVpnLicUsageMonitorMIB=ciscoVpnLicUsageMonitorMIB, cvpnLicBkpServerAddrType=cvpnLicBkpServerAddrType, cvpnLicClntInfoGetReqRx=cvpnLicClntInfoGetReqRx, cvpnLicServerUtilized=cvpnLicServerUtilized, cvpnLicBkpServerStatus=cvpnLicBkpServerStatus, cvpnLicServerSyncRx=cvpnLicServerSyncRx, cvpnLicClntInfoTable=cvpnLicClntInfoTable, cvpnLicClntInfoRegReqRx=cvpnLicClntInfoRegReqRx, cvpnLicClntInfoCurUsage=cvpnLicClntInfoCurUsage, cvpnLicServerTable=cvpnLicServerTable, cvpnLicServerNumLicAvail=cvpnLicServerNumLicAvail, PYSNMP_MODULE_ID=ciscoVpnLicUsageMonitorMIB, ciscoVpnLicUsageMonitorMIBConform=ciscoVpnLicUsageMonitorMIBConform, cvpnLicClntInfoRegReqError=cvpnLicClntInfoRegReqError, cvpnLicClntInfoGetReqTx=cvpnLicClntInfoGetReqTx, cvpnLicClntInfoRelReqError=cvpnLicClntInfoRelReqError, LicServerRegistered=LicServerRegistered, cvpnLicBkpServerAddr=cvpnLicBkpServerAddr, cvpnLicClntInfoTransferReqRx=cvpnLicClntInfoTransferReqRx, cvpnLicBkpServerVer=cvpnLicBkpServerVer, cvpnLicClntInfoGetReqError=cvpnLicClntInfoGetReqError, VPNLicType=VPNLicType, cvpnLicServerHelloRx=cvpnLicServerHelloRx, cvpnLicDeviceRole=cvpnLicDeviceRole, cvpnLicServerHelloError=cvpnLicServerHelloError, cvpnLicServerAddrType=cvpnLicServerAddrType, cvpnLicServer=cvpnLicServer, ciscoVpnLicUsageMonitorMIBObjects=ciscoVpnLicUsageMonitorMIBObjects, cvpnLicServerEntry=cvpnLicServerEntry, cvpnLicServerSyncError=cvpnLicServerSyncError, cvpnLicClntInfoHigh=cvpnLicClntInfoHigh, cvpnLicServerAddr=cvpnLicServerAddr, cvpnLicClntInfoDeviceID=cvpnLicClntInfoDeviceID, cvpnLicBkpSerAddrType=cvpnLicBkpSerAddrType, cvpnLicBkpServer=cvpnLicBkpServer, cvpnLicBkpServerDevID=cvpnLicBkpServerDevID, cvpnLicServerNumLicCapacity=cvpnLicServerNumLicCapacity)
| 130.893082 | 3,231 | 0.772679 | 2,212 | 20,812 | 7.268987 | 0.097197 | 0.010075 | 0.011381 | 0.015175 | 0.42882 | 0.411406 | 0.313515 | 0.295914 | 0.262765 | 0.178058 | 0 | 0.05912 | 0.075918 | 20,812 | 158 | 3,232 | 131.721519 | 0.776934 | 0.017106 | 0 | 0.068493 | 0 | 0 | 0.207268 | 0.117964 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.061644 | 0 | 0.171233 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
533f80695218538c69244409fba7c7a9a2692b9e | 7,465 | py | Python | get-status.py | akleber/go-eCharger-tools | c57cb64c2fb0d983b7e2b3a0a0ab8e0846b2b859 | [
"MIT"
] | 8 | 2018-01-18T20:53:42.000Z | 2021-02-10T21:41:39.000Z | get-status.py | akleber/go-eCharger-tools | c57cb64c2fb0d983b7e2b3a0a0ab8e0846b2b859 | [
"MIT"
] | 2 | 2018-01-18T20:14:40.000Z | 2018-01-19T11:58:59.000Z | get-status.py | akleber/go-eCharger-tools | c57cb64c2fb0d983b7e2b3a0a0ab8e0846b2b859 | [
"MIT"
] | 3 | 2018-01-18T19:38:44.000Z | 2021-09-23T07:50:48.000Z |
"""
Example:
python3 get-status.py
"""
import requests
import sys
import os
import json
import time
from datetime import timedelta, date, datetime
hostname = "go-echarger"
def main(argv):
datestring = datetime.now().strftime("%Y_%m_%d-%H-%M-%S")
url = "http://" + hostname + "/status"
r = requests.get(url, timeout=5)
r.raise_for_status()
jsondata = r.json()
# remove some private data
jsondata['wke'] = '***'
jsondata['wak'] = '***'
jsondata['rca'] = '***'
jsondata['sse'] = '******'
# write data to file
with open("status_" + datestring + ".json", 'w') as f:
json.dump(jsondata, f, indent=4)
# print infos
print("version '{}' api version, the code below only supports version B".format(jsondata['version']))
print("car '{}' 1=ready for charging, 2=charging, 3=waiting for car".format(jsondata['car']))
print("amp '{}' ampere (current setting)".format(jsondata['amp']))
print("err '{}' error state, 1:RCCB, 3:PHASE, 8:NO_GROUND, 10:INTERNAL".format(jsondata['err']))
print("ast '{}' access state, 0:OPEN, 1:RFID_REQ".format(jsondata['ast']))
print("alw '{}' allow charging, 0:false, 1:true".format(jsondata['alw']))
print("stp '{}' 0: STOP_STATE_NONE, 2:STOP_STATE_KWH".format(jsondata['stp']))
print("cbl '{}' cable capability in A, 0 for no cable".format(jsondata['cbl']))
print("pha '{}' number of phases".format(jsondata['pha']))
print("tmp '{}' mainboard temperature".format(jsondata['tmp']))
print("dws '{}' deka-watt-seconds, 1000 equals, 10.000 Ws charged in this charge process".format(jsondata['dws']))
print("dwo '{}' turn off value for dws (for charge XY kWh function), if(dwo!=0 && dws/36000>=dwo)alw=0".format(jsondata['dwo']))
print("adi '{}' adapter_in, 0:NO_ADAPTER, 1:16A_ADAPTER".format(jsondata['adi']))
print("uby '{}' unlocked by RFID card no.".format(jsondata['uby']))
print("eto '{}' Energy total .1 kWh (value of 120 means 12 kWh charged)".format(jsondata['eto']))
print("wst '{}' wifi state, 3:connected, default:unconnected".format(jsondata['wst']))
print("nrg '{}' voltage L1 in V".format(jsondata['nrg'][0]))
print("nrg '{}' voltage L2 in V".format(jsondata['nrg'][1]))
print("nrg '{}' voltage L3 in V".format(jsondata['nrg'][2]))
print("nrg '{}' voltage on N, is !=0 when Schuko adapter is plugged in reversed".format(jsondata['nrg'][3]))
print("nrg '{}' current L1 in .1 A".format(jsondata['nrg'][4]))
print("nrg '{}' current L2 in .1 A".format(jsondata['nrg'][5]))
print("nrg '{}' current L3 in .1 A".format(jsondata['nrg'][6]))
print("nrg '{}' power L1 in .1 kW".format(jsondata['nrg'][7]))
print("nrg '{}' power L2 in .1 kW".format(jsondata['nrg'][8]))
print("nrg '{}' power L3 in .1 kW".format(jsondata['nrg'][9]))
print("nrg '{}' power on N".format(jsondata['nrg'][10]))
# if(Math.floor(pha/8) ==1 && parseInt(nrg[3])>parseInt(nrg[0])){
# nrg[0]=nrg[3]
# nrg[7]=nrg[10]
# nrg[11]=nrg[14]
# }
print("nrg '{}' power total in 100 kW".format(jsondata['nrg'][10]))
print("nrg '{}' powerfactor L1 in %".format(jsondata['nrg'][11]))
print("nrg '{}' powerfactor L2 in %".format(jsondata['nrg'][12]))
print("nrg '{}' powerfactor L1 in %".format(jsondata['nrg'][13]))
print("nrg '{}' powerfactor N".format(jsondata['nrg'][14]))
print("fwv '{}' firmware version (this code only supports below 020)".format(jsondata['fwv']))
print("sse '{}' serial number (formatted as %06d string)".format(jsondata['sse']))
print("wss '{}' wlan extern SSID".format(jsondata['wss']))
print("wke '{}' wlan extern kennwort/password in cleartext".format(jsondata['wke']))
print("wen '{}' wlan extern enabled".format(jsondata['wen']))
print("tof '{}' time_offset for internal battery powered RTC".format(jsondata['tof']))
print("tds '{}' use daylight saving time for internal RTC".format(jsondata['tds']))
print("lbr '{}' led brightness, 0-255".format(jsondata['lbr']))
print("aho '{}' awattar hours to charge".format(jsondata['aho']))
print("afi '{}' awattar hour:00 to be finished".format(jsondata['afi']))
print("ama '{}' absolute max ampere".format(jsondata['ama']))
print("al1 '{}' button ampere level 1'".format(jsondata['al1']))
print("al2 '{}' button ampere level 2'".format(jsondata['al2']))
print("al3 '{}' button ampere level 3'".format(jsondata['al3']))
print("al4 '{}' button ampere level 4'".format(jsondata['al4']))
print("al5 '{}' button ampere level 5'".format(jsondata['al5']))
print("cid '{}' color idle, parseInt(HEX_CODE), 24bit".format(jsondata['cid']))
print("cch '{}' color charging, parseInt(HEX_CODE), 24bit".format(jsondata['cch']))
print("cfi '{}' color finished, parseInt(HEX_CODE), 24bit".format(jsondata['cfi']))
print("ust '{}' unlock method, 0:standard, 1:auto_unlock, 2:always_locked".format(jsondata['ust']))
print("wak '{}' wlan hotspot kennwort/password'".format(jsondata['wak']))
print("nmo '{}' norway mode, 0:false, 1:true".format(jsondata['nmo']))
print("eca '{}' energy charged with card 1, in .1kWh".format(jsondata['eca']))
print("ecr '{}' energy charged with card 2, in .1kWh".format(jsondata['ecr']))
print("ecd '{}' energy charged with card 3, in .1kWh".format(jsondata['ecd']))
print("ec4 '{}' energy charged with card 4, in .1kWh".format(jsondata['ec4']))
print("ec5 '{}' energy charged with card 5, in .1kWh".format(jsondata['ec5']))
print("ec6 '{}' energy charged with card 6, in .1kWh".format(jsondata['ec6']))
print("ec7 '{}' energy charged with card 7, in .1kWh".format(jsondata['ec7']))
print("ec8 '{}' energy charged with card 8, in .1kWh".format(jsondata['ec8']))
print("ec9 '{}' energy charged with card 9, in .1kWh".format(jsondata['ec9']))
print("ec1 '{}' energy charged with card 10, in .1kWh".format(jsondata['ec1']))
# parameter names generated automatically, takes first character || first character after '_',
# and next character that yields an unused paramter name
# rfid_card_1 --> rca
# rfid_card_2 --> rcr (because rca was already used and c was the next character that yields an unused paramter name
# rfid_card_3 --> crd
# rfid_card_4 --> rc4 ...
print("rca '{}' rfid card1 UID (only available for fwv<020)".format(jsondata['rca']))
print("rcr '{}'".format(jsondata['rcr']))
print("rcd '{}'".format(jsondata['rcd']))
print("rc4 '{}'".format(jsondata['rc4']))
print("rc5 '{}'".format(jsondata['rc5']))
print("rc6 '{}'".format(jsondata['rc6']))
print("rc7 '{}'".format(jsondata['rc7']))
print("rc8 '{}'".format(jsondata['rc8']))
print("rc9 '{}'".format(jsondata['rc9']))
print("rc1 '{}'".format(jsondata['rc1']))
print("rna '{}' rfid name1 (only available for fwv<020)".format(jsondata['rna']))
print("rnm '{}'".format(jsondata['rnm']))
print("rne '{}'".format(jsondata['rne']))
print("rn4 '{}'".format(jsondata['rn4']))
print("rn5 '{}'".format(jsondata['rn5']))
print("rn6 '{}'".format(jsondata['rn6']))
print("rn7 '{}'".format(jsondata['rn7']))
print("rn8 '{}'".format(jsondata['rn8']))
print("rn9 '{}'".format(jsondata['rn9']))
print("rn1 '{}'".format(jsondata['rn1']))
if __name__ == "__main__":
main(sys.argv)
| 51.130137 | 173 | 0.614334 | 1,005 | 7,465 | 4.526368 | 0.296517 | 0.258518 | 0.059793 | 0.046164 | 0.130798 | 0.117608 | 0.055836 | 0.040009 | 0.022423 | 0.022423 | 0 | 0.034599 | 0.167582 | 7,465 | 145 | 174 | 51.482759 | 0.697457 | 0.079036 | 0 | 0 | 0 | 0.009524 | 0.468622 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.009524 | false | 0.019048 | 0.057143 | 0 | 0.066667 | 0.8 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
534278534a9f8126b60378fc2e40b13658c4a785 | 866 | py | Python | access/tests/test_datasets.py | vidal-anguiano/access | 49b97d38392d13c4ada24b19623a4959b5e569e0 | [
"BSD-3-Clause"
] | 6 | 2019-10-01T20:36:03.000Z | 2021-01-17T00:43:19.000Z | access/tests/test_datasets.py | vidal-anguiano/access | 49b97d38392d13c4ada24b19623a4959b5e569e0 | [
"BSD-3-Clause"
] | 31 | 2019-06-14T15:56:06.000Z | 2020-05-31T18:52:48.000Z | access/tests/test_datasets.py | vidal-anguiano/access | 49b97d38392d13c4ada24b19623a4959b5e569e0 | [
"BSD-3-Clause"
] | null | null | null | import os
import sys
sys.path.append('../..')
import math
import unittest
import numpy as np
import pandas as pd
import geopandas as gpd
from access.datasets import datasets
import util as tu
class TestDatasets(unittest.TestCase):
def test_file_download(self):
file_name = 'chi_times'
file_path = os.path.join(datasets._dir_path, datasets._datasets[file_name])
if os.path.exists(file_path):
os.remove(file_path)
datasets.load_data(file_name)
actual = os.path.exists(file_path)
self.assertEqual(actual, True)
def test_load_geopandas_dataset(self):
result = datasets.load_data('chi_doc_geom')
actual = type(result) == gpd.geodataframe.GeoDataFrame
self.assertEqual(actual, True)
def test_prints_available_datasets(self):
datasets.available_datasets()
| 22.205128 | 83 | 0.700924 | 114 | 866 | 5.114035 | 0.421053 | 0.054889 | 0.034305 | 0.054889 | 0.178388 | 0.109777 | 0 | 0 | 0 | 0 | 0 | 0 | 0.209007 | 866 | 38 | 84 | 22.789474 | 0.851095 | 0 | 0 | 0.08 | 0 | 0 | 0.030023 | 0 | 0 | 0 | 0 | 0 | 0.08 | 1 | 0.12 | false | 0 | 0.36 | 0 | 0.52 | 0.04 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
5344205e16cce095c921e4833479f5f6e6d324f9 | 1,186 | py | Python | setup.py | denis-ryzhkov/mc_xclip | 54196578f28ecda59712ad4330f027e36344839b | [
"MIT"
] | null | null | null | setup.py | denis-ryzhkov/mc_xclip | 54196578f28ecda59712ad4330f027e36344839b | [
"MIT"
] | 1 | 2017-03-30T06:00:46.000Z | 2017-03-30T07:33:42.000Z | setup.py | denis-ryzhkov/mc_xclip | 54196578f28ecda59712ad4330f027e36344839b | [
"MIT"
] | null | null | null | from distutils.core import setup
setup(
name='mc_xclip',
version='0.3.0',
description='Syncs clipboards of Midnight Commander and X Window System.',
long_description='''
**NEW:**
Don't use ``mc_xclip``! Instead:
* ``sudo apt-get install xclip``
* Make sure ``mc`` is NOT running, or it will overwrite the next changes.
* Find ``clipboard_store`` in ``~/.config/mc/ini``
* Set ``clipboard_store=xclip -i -selection clipboard``
* Set ``clipboard_paste=xclip -o -selection clipboard``
* Thanks to https://github.com/IvanAli
**OLD:**
Install::
sudo apt-get install xclip
sudo pip install mc_xclip
# If you use Display Manager:
echo 'mc_xclip &' >> ~/.xprofile
# Else:
echo 'mc_xclip &' >> ~/.xinitrc
# Reboot.
''',
url='https://github.com/denis-ryzhkov/mc_xclip',
author='Denis Ryzhkov',
author_email='denisr@denisr.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Programming Language :: Python :: 2.7',
'Topic :: Utilities',
],
scripts=[
'scripts/mc_xclip',
],
)
| 23.72 | 78 | 0.621417 | 146 | 1,186 | 4.965753 | 0.657534 | 0.067586 | 0.027586 | 0.046897 | 0.06069 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006508 | 0.222597 | 1,186 | 49 | 79 | 24.204082 | 0.779826 | 0 | 0 | 0.051282 | 0 | 0 | 0.744519 | 0.038786 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.025641 | 0 | 0.025641 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5345611f0b7927012ef7eecbd8eeea185ebca034 | 3,975 | py | Python | pyapps/support_vector_machine/support_vector_machine.py | zsamadi/pml_tools | 0de0c8a6d5bc7ab2c20aab0649e407799b387bdb | [
"Apache-2.0"
] | 2 | 2022-02-10T15:10:32.000Z | 2022-02-10T15:10:34.000Z | pyapps/support_vector_machine/support_vector_machine.py | zsamadi/pyml_tools | 0de0c8a6d5bc7ab2c20aab0649e407799b387bdb | [
"Apache-2.0"
] | null | null | null | pyapps/support_vector_machine/support_vector_machine.py | zsamadi/pyml_tools | 0de0c8a6d5bc7ab2c20aab0649e407799b387bdb | [
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 16:29:231 2021
@author: zayn
"""
## Initialization
import sys
sys.path.append('../../software/algorithms/')
import svm_cls as svm
import scipy.io
import numpy as np
import time
from sklearn.svm import SVC
## =============== Part 1: Loading and Visualizing Data ================
# We start this example application by first loading and visualizing the dataset.
# The following code will load the dataset and plot the data.
#
print('Loading and Visualizing Data ...\n')
mat = scipy.io.loadmat('../../data/svm_data/svmdata1.mat')
X=mat["X"]
y=mat["y"]
y=np.ravel(y)
svmal=svm.svmal()
# Plot training data
ax=svmal.plotData(X, y);
## ==================== Training Linear SVM ====================
# The following code will train a linear SVM on the dataset and plot the
# decision boundary learned.
#
y_svm=-(-1)**y
C=10
tol=0.001
max_passes=20
ktype='linear'
svmal=svm.svmal(C=C, ktype=ktype)
svm_sam=svmal.svmz(X, y_svm,tol=0.001, max_passes=20)
alpha_vec=svm_sam.alphas
b=svm_sam.b
alphay=alpha_vec*y_svm
w=alphay@X
svmal.visualizeBoundryLinear(ax, w, b, X)
aa=svmal.score(X, y)
print('train acuracy using developed svm is {0:.2f}%\n'.format(aa*100))
# %% =============== Part 2: Loading and Visualizing Data ================
# We load another set of data
print('=============== New Training ================')
print('Loading and Visualizing Data ...\n')
mat = scipy.io.loadmat('../../data/svm_data/svmdata2.mat')
X=mat["X"]
y=mat["y"]
y=np.ravel(y)
y_svm=-(-1)**y
svmal=svm.svmal()
ax=svmal.plotData(X, y);
# % SVM Parameters
C=1
tol=0.001
max_passes=20
gamma=50
ktype='rbf'
tic=time.time()
svco=SVC(C=C,kernel=ktype, gamma=gamma).fit(X,y)
toc=time.time()
pass_time=toc-tic
print('sklearn svm training lasted {0:.2f}s\n'.format(pass_time))
percentage=svco.score(X,y)
print('train accuracy using sklearn svm is: {0:.2f}% \n'.format(percentage*100))
tic=time.time()
svmal=svm.svmal(C=C, ktype=ktype, gamma=gamma)
svm_sam=svmal.svmz(X, y_svm,tol, max_passes)
b=svm_sam.b
alpha_vec=svm_sam.alphas
toc=time.time()
pass_time=toc-tic
print('svm training lasted {0:.2f}s\n'.format(pass_time))
Xe=X[alpha_vec>0]
ye=y_svm[alpha_vec>0]
alpha_vece=alpha_vec[alpha_vec>0]
svmal.visualizeBoundry(ax, alpha_vece, b,Xe,ye, ktype, gamma)
aa=svmal.score(X, y)
print('train acuracy using developed svm is {0:.2f}%\n'.format(aa*100))
# =============== Part 3: Visualizing Dataset 3 ================
# The following code will load the next dataset into and plot the data.
#
print('=============== New Training ================')
print('Loading and Visualizing Data ...')
mat = scipy.io.loadmat('../../data/svm_data/svmdata3.mat')
X=mat["X"]
y=mat["y"]
Xval=mat["Xval"]
yval=mat["yval"]
y=np.ravel(y)
y_svm=-(-1)**y
yval=np.ravel(yval)
ax=svmal.plotData(X, y);
# ========== Training SVM with RBF Kernel ==========
C=1
tol=0.001
max_passes=20
gamma=50
ktype='rbf'
tic=time.time()
svco=SVC(C=C,kernel=ktype, gamma=gamma).fit(X,y)
toc=time.time()
pass_time=toc-tic
print('sklearn svm training lasted {0:.2f}s\n'.format(pass_time))
percentage=svco.score(Xval,yval)
print('validation accuracy using sklearn svm is: {0:.2f}%\n'.format(percentage*100))
tic=time.time()
svmal=svm.svmal(C=C, ktype=ktype, gamma=gamma)
svm_sam=svmal.svmz(X, y_svm,tol, max_passes)
b=svm_sam.b
alpha_vec=svm_sam.alphas
toc=time.time()
pass_time=toc-tic
print('svm training lasted {0:.2f}s\n'.format(pass_time))
Xe=X[alpha_vec>0]
ye=y_svm[alpha_vec>0]
alpha_vece=alpha_vec[alpha_vec>0]
svmal.visualizeBoundry(ax, alpha_vece, b,Xe,ye, ktype, gamma)
aa=svmal.score(Xval, yval)
print('validation acuracy using developed svm is {0:.2f}%\n'.format(aa*100))
| 19.974874 | 85 | 0.628176 | 640 | 3,975 | 3.820313 | 0.201563 | 0.011452 | 0.051534 | 0.051125 | 0.7591 | 0.677301 | 0.621268 | 0.594274 | 0.576278 | 0.547648 | 0 | 0.028753 | 0.168805 | 3,975 | 198 | 86 | 20.075758 | 0.711259 | 0.198742 | 0 | 0.73 | 0 | 0 | 0.243985 | 0.041342 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.14 | 0.06 | 0 | 0.06 | 0.14 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
5346f3cce692f260719747a6089c86e48621003a | 11,160 | py | Python | Server/integrations.deprecatred/toopher/ToopherExternalAuthenticator.py | corriganjeff/oxAuth | 6e750b2d29473bcb6b53f044aee57b9267281798 | [
"MIT"
] | 380 | 2015-01-08T23:28:43.000Z | 2022-03-07T20:19:51.000Z | Server/integrations.deprecatred/toopher/ToopherExternalAuthenticator.py | corriganjeff/oxAuth | 6e750b2d29473bcb6b53f044aee57b9267281798 | [
"MIT"
] | 1,489 | 2020-11-06T14:04:47.000Z | 2020-11-06T14:30:43.000Z | Server/integrations.deprecatred/toopher/ToopherExternalAuthenticator.py | HomeMeCEO/oxAuth | e391298e55e34f0f732c7ecd199bffe42289992b | [
"MIT"
] | 172 | 2015-01-10T09:48:21.000Z | 2022-02-24T03:01:59.000Z | # oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
# Copyright (c) 2016, Gluu
#
# Author: Yuriy Movchan
#
import java
import json
from com.toopher import RequestError
from com.toopher import ToopherAPI
from java.util import Arrays
from org.gluu.model.custom.script.type.auth import PersonAuthenticationType
from org.gluu.oxauth.security import Identity
from org.gluu.oxauth.service import EncryptionService
from org.gluu.oxauth.service import UserService, AuthenticationService
from org.gluu.service.cdi.util import CdiUtil
from org.gluu.util import StringHelper, ArrayHelper
class PersonAuthentication(PersonAuthenticationType):
def __init__(self, currentTimeMillis):
self.currentTimeMillis = currentTimeMillis
def init(self, configurationAttributes):
print "Toopher. Initialization"
toopher_creds_file = configurationAttributes.get("toopher_creds_file").getValue2()
# Load credentials from file
f = open(toopher_creds_file, 'r')
try:
creds = json.loads(f.read())
except:
return False
finally:
f.close()
consumer_key = creds["CONSUMER_KEY"]
consumer_secret = creds["CONSUMER_SECRET"]
try:
encryptionService = CdiUtil.bean(EncryptionService)
consumer_secret = encryptionService.decrypt(consumer_secret)
except:
return False
self.tapi = ToopherAPI(consumer_key, consumer_secret)
print "Toopher. Initialized successfully"
return True
def destroy(self, configurationAttributes):
print "Toopher. Destroy"
print "Toopher. Destroyed successfully"
return True
def getApiVersion(self):
return 1
def isValidAuthenticationMethod(self, usageType, configurationAttributes):
return True
def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
return None
def authenticate(self, configurationAttributes, requestParameters, step):
userService = CdiUtil.bean(UserService)
authenticationService = CdiUtil.bean(AuthenticationService)
identity = CdiUtil.bean(Identity)
credentials = identity.getCredentials()
toopher_user_timeout = int(configurationAttributes.get("toopher_user_timeout").getValue2())
user_name = credentials.getUsername()
if (step == 1):
print "Toopher. Authenticate for step 1"
user_password = credentials.getPassword()
logged_in = False
if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
userService = CdiUtil.bean(UserService)
logged_in = authenticationService.authenticate(user_name, user_password)
if (not logged_in):
return False
# Get user entry
userService = CdiUtil.bean(UserService)
find_user_by_uid = authenticationService.getAuthenticatedUser()
if (find_user_by_uid == None):
print "Toopher. Authenticate for step 1. Failed to find user"
return False
# Check if the user paired account to phone
user_external_uid_attr = userService.getCustomAttribute(find_user_by_uid, "oxExternalUid")
if ((user_external_uid_attr == None) or (user_external_uid_attr.getValues() == None)):
print "Toopher. Authenticate for step 1. There is no external UIDs for user: ", user_name
else:
topher_user_uid = None
for ext_uid in user_external_uid_attr.getValues():
if (ext_uid.startswith('toopher:')):
topher_user_uid = ext_uid[8:len(ext_uid)]
break
if (topher_user_uid == None):
print "Toopher. Authenticate for step 1. There is no Topher UID for user: ", user_name
else:
identity.setWorkingParameter("toopher_user_uid", topher_user_uid)
return True
elif (step == 2):
print "Toopher. Authenticate for step 2"
passed_step1 = self.isPassedDefaultAuthentication
if (not passed_step1):
return False
sessionAttributes = identity.getSessionId().getSessionAttributes()
if (sessionAttributes == None) or not sessionAttributes.containsKey("toopher_user_uid"):
print "Toopher. Authenticate for step 2. toopher_user_uid is empty"
# Pair with phone
pairing_phrase_array = requestParameters.get("pairing_phrase")
if ArrayHelper.isEmpty(pairing_phrase_array):
print "Toopher. Authenticate for step 2. pairing_phrase is empty"
return False
pairing_phrase = pairing_phrase_array[0]
try:
pairing_status = self.tapi.pair(pairing_phrase, user_name)
toopher_user_uid = pairing_status.id
except RequestError, err:
print "Toopher. Authenticate for step 2. Failed pair with phone: ", err
return False
pairing_result = self.checkPairingStatus(toopher_user_uid, toopher_user_timeout)
if (not pairing_result):
print "Toopher. Authenticate for step 2. The pairing has not been authorized by the phone yet"
return False
print "Toopher. Authenticate for step 2. Storing toopher_user_uid in user entry", toopher_user_uid
# Store toopher_user_uid in user entry
find_user_by_uid = userService.addUserAttribute(user_name, "oxExternalUid", "toopher:" + toopher_user_uid)
if (find_user_by_uid == None):
print "Toopher. Authenticate for step 2. Failed to update current user"
return False
identity.setWorkingParameter("toopher_user_uid", toopher_user_uid)
else:
toopher_user_uid = sessionAttributes.get("toopher_user_uid")
# Check pairing stastus
print "Toopher. Authenticate for step 2. toopher_user_uid: ", toopher_user_uid
pairing_result = self.checkPairingStatus(toopher_user_uid, 0)
if (not pairing_result):
print "Toopher. Authenticate for step 2. The pairing has not been authorized by the phone yet"
return False
return True
elif (step == 3):
print "Toopher. Authenticate for step 3"
passed_step1 = self.isPassedDefaultAuthentication
if (not passed_step1):
return False
sessionAttributes = identity.getSessionId().getSessionAttributes()
if (sessionAttributes == None) or not sessionAttributes.containsKey("toopher_user_uid"):
print "Toopher. Authenticate for step 3. toopher_user_uid is empty"
return False
toopher_user_uid = sessionAttributes.get("toopher_user_uid")
passed_step1 = StringHelper.isNotEmptyString(toopher_user_uid)
if (not passed_step1):
return False
toopher_terminal_name = configurationAttributes.get("toopher_terminal_name").getValue2()
try:
request_status = self.tapi.authenticate(toopher_user_uid, toopher_terminal_name)
request_id = request_status.id
except RequestError, err:
print "Toopher. Authenticate for step 3. Failed to send authentication request to phone: ", err
return False
print "Toopher. Authenticate for step 3. request_id: ", request_id
request_result = self.checkRequestStatus(request_id, toopher_user_timeout)
if (not request_result):
print "Toopher. Authenticate for step 3. The authentication request has not received a response from the phone yet"
return False
print "Toopher. Authenticate for step 3. The request was granted"
return True
else:
return False
def prepareForStep(self, configurationAttributes, requestParameters, step):
return True
def getExtraParametersForStep(self, configurationAttributes, step):
if (step in [2, 3]):
return Arrays.asList("toopher_user_uid")
return None
def getCountAuthenticationSteps(self, configurationAttributes):
return 3
def getPageForStep(self, configurationAttributes, step):
if (step == 2):
return "/auth/toopher/tppair.xhtml"
elif (step == 3):
return "/auth/toopher/tpauthenticate.xhtml"
return ""
def isPassedDefaultAuthentication():
identity = CdiUtil.bean(Identity)
credentials = identity.getCredentials()
user_name = credentials.getUsername()
passed_step1 = StringHelper.isNotEmptyString(user_name)
return passed_step1
def checkPairingStatus(self, pairing_id, timeout):
try:
curTime = java.lang.System.currentTimeMillis()
endTime = curTime + timeout * 1000
while (endTime >= curTime):
pairing_status = self.tapi.getPairingStatus(pairing_id)
if (pairing_status.enabled):
print "Toopher. Pairing complete"
return True
java.lang.Thread.sleep(2000)
curTime = java.lang.System.currentTimeMillis()
except java.lang.Exception, err:
print "Toopher. Could not check pairing status: ", err
return False
print "Toopher. The pairing has not been authorized by the phone yet"
return False
def checkRequestStatus(self, request_id, timeout):
try:
curTime = java.lang.System.currentTimeMillis()
endTime = curTime + timeout * 1000
while (endTime >= curTime):
request_status = self.tapi.getAuthenticationStatus(request_id)
if (request_status.cancelled):
print "Toopher. The authentication request has been cancelled"
return False
if (not request_status.pending):
if (request_status.granted):
print "Toopher. The request was granted"
return True
java.lang.Thread.sleep(2000)
curTime = java.lang.System.currentTimeMillis()
except java.lang.Exception, err:
print "Toopher. Could not check authentication status: ", err
return False
print "Toopher. The authentication request has not received a response from the phone yet"
return False
def logout(self, configurationAttributes, requestParameters):
return True
| 40.288809 | 131 | 0.625896 | 1,111 | 11,160 | 6.130513 | 0.185419 | 0.052856 | 0.047276 | 0.075319 | 0.429012 | 0.383791 | 0.323888 | 0.27529 | 0.254148 | 0.245192 | 0 | 0.008551 | 0.308423 | 11,160 | 276 | 132 | 40.434783 | 0.873931 | 0.027688 | 0 | 0.428571 | 0 | 0 | 0.178153 | 0.007473 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.059113 | 0.054187 | null | null | 0.147783 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
5347c3252204d929c53d921387dc20218d0bfced | 246 | py | Python | Include/urls.py | percevalm/aumyproject | b24b38005188ce9dd41ed663cf54dad5464afef3 | [
"bzip2-1.0.6"
] | null | null | null | Include/urls.py | percevalm/aumyproject | b24b38005188ce9dd41ed663cf54dad5464afef3 | [
"bzip2-1.0.6"
] | 16 | 2020-03-24T17:30:37.000Z | 2022-03-11T23:57:41.000Z | Include/urls.py | percevalm/aumyproject | b24b38005188ce9dd41ed663cf54dad5464afef3 | [
"bzip2-1.0.6"
] | null | null | null |
from django.urls import path, include
from .views import ArchivesuploadsListView
from . import views
#from mysite.search import views
urlpatterns = [
path('publications/',views.ArchivesuploadsListView.as_view(), name ='publications'),
]
| 18.923077 | 87 | 0.768293 | 27 | 246 | 6.962963 | 0.555556 | 0.117021 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.134146 | 246 | 12 | 88 | 20.5 | 0.882629 | 0.126016 | 0 | 0 | 0 | 0 | 0.117371 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
5353db5793fdc45da939df277c38cf09dd01bc06 | 8,313 | py | Python | fastai/distributed.py | ProblemSolversGuild/fastai | f4a6ce2af146864bfa46096d9f5a27a527f66c1a | [
"Apache-2.0"
] | null | null | null | fastai/distributed.py | ProblemSolversGuild/fastai | f4a6ce2af146864bfa46096d9f5a27a527f66c1a | [
"Apache-2.0"
] | null | null | null | fastai/distributed.py | ProblemSolversGuild/fastai | f4a6ce2af146864bfa46096d9f5a27a527f66c1a | [
"Apache-2.0"
] | null | null | null | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/20a_distributed.ipynb (unless otherwise specified).
__all__ = ['ParallelTrainer', 'setup_distrib', 'teardown_distrib', 'DistributedDL', 'DistributedTrainer', 'rank0_first']
# Cell
from .basics import *
from .callback.progress import ProgressCallback
from torch.nn.parallel import DistributedDataParallel, DataParallel
from .data.load import _FakeLoader,_loaders
# Cell
@patch
def reset(self: DataParallel):
"Patch required `reset` call into `DataParallel`"
if hasattr(self.module, 'reset'): self.module.reset()
# Cell
class ParallelTrainer(Callback):
"Wrap a model `DataParallel` automatically"
run_after,run_before = TrainEvalCallback,Recorder
def __init__(self, device_ids): self.device_ids = device_ids
def before_fit(self): self.learn.model = DataParallel(self.learn.model, device_ids=self.device_ids)
def after_fit(self): self.learn.model = self.learn.model.module
# Cell
@patch
def to_parallel(self: Learner, device_ids=None):
"Add `ParallelTrainer` callback to a `Learner`"
self.add_cb(ParallelTrainer(device_ids))
return self
# Cell
@patch
def detach_parallel(self: Learner):
"Remove `ParallelTrainer` callback from a Learner"
self.remove_cb(ParallelTrainer)
return self
# Cell
@patch
@contextmanager
def parallel_ctx(self: Learner, device_ids=None):
"A context manager to adapt a learner to train in data parallel mode."
try:
self.to_parallel(device_ids)
yield self
finally: self.detach_parallel()
# Cell
@patch
def reset(self: DistributedDataParallel):
"Patch required `reset` call into `DistributedDataParallel`"
if hasattr(self.module, 'reset'): self.module.reset()
# Cell
def setup_distrib(gpu=None):
"Setup this process to participate in distributed training"
if gpu is None: return gpu
gpu = int(gpu)
torch.cuda.set_device(int(gpu))
if num_distrib() > 0: torch.distributed.init_process_group(backend='nccl', init_method='env://')
return gpu
# Cell
def teardown_distrib():
"Free distributed training resources"
if torch.distributed.is_initialized(): torch.distributed.destroy_process_group()
# Cell
def _round_to_multiple(number,multiple): return int(math.ceil(number/multiple)*multiple)
# Cell
class DistributedDL(TfmdDL):
"A `TfmdDL` which splits a batch into equal size pieces for each worker"
def __init__(self,dl,rank=None,world_size=None):
if rank is None: rank=rank_distrib()
if world_size is None: world_size=num_distrib()
store_attr()
if type(dl) == torch.utils.data.DataLoader:
shuffle = True if eq(type(dl.sampler), torch.utils.data.RandomSampler) else False
self.dl = DataLoader(dataset=dl.dataset, bs=dl.batch_size, num_workers=dl.num_workers, \
pin_memory=dl.pin_memory, timeout=dl.timeout, shuffle=shuffle, drop_last=dl.drop_last, persistent_workers=dl.persistent_workers)
self.bs,self.device,self.drop_last,self.dataset,fake,self.num_workers,self.offs,self.pin_memory = \
attrgetter('bs','device','drop_last','dataset','fake_l','num_workers','offs','pin_memory')(self.dl)
self.fake_l = _FakeLoader(self, fake.pin_memory, fake.num_workers, fake.timeout, persistent_workers=fake.persistent_workers)
def _broadcast(self,t,rank):
"Broadcasts t from rank `rank` to all other ranks. Returns t so t is same for all ranks after call."
t = LongTensor(t).cuda() # nccl only works with cuda tensors
torch.distributed.broadcast(t,rank)
return t.cpu().tolist()
def _to_detach(self,b,cpu=True,gather=True): return to_detach(b,cpu,gather) # member func so we can override for test
def __len__(self): return _round_to_multiple(len(self.dl),self.world_size)//self.world_size
def get_idxs(self):
idxs = list(self.dl.get_idxs()) # compute get_idxs in all ranks (we'll only use rank 0 but size must be consistent)
idxs = self._broadcast(idxs,0) # broadcast and receive it from rank 0 to all
self.n = len(idxs) # we assumed n was dl.n but we really care about number of idxs
# add extra samples to make it evenly divisible
self.n_padded = _round_to_multiple(self.n,self.world_size)
idxs += (idxs * (self.n_padded//self.n))[:self.n_padded-self.n] # idx needs to be repeated when n_padded>>n
# slice padded idxs so that each rank gets self.n_padded//self.world_size tensors
return idxs[self.rank*self.n_padded//self.world_size:(self.rank+1)*self.n_padded//self.world_size]
def before_iter(self):
self.i = 0
self.dl.before_iter()
def randomize(self): self.dl.randomize()
def after_batch(self,b):
self.i += find_bs(b)
return self.dl.after_batch(b)
def after_iter(self): self.dl.after_iter()
def create_batches(self,samps): return self.dl.create_batches(samps)
def to_detach(self,b, cpu=True, gather=True):
b = self._to_detach(b, cpu, gather)
def _inner(b):
if b.ndim>0:
# for each rank, compute overflow of read idxs vs self.n and accumulate them to unpad totals after gathering
n = sum([min(0,max(-len(b)//self.world_size,
self.n-(self.i+r*self.n_padded//self.world_size))) for r in range(self.world_size)])
b = b[:n or None]
return b
return apply(_inner,b) if gather and all(hasattr(self,o) for o in ('i','n','n_padded')) else b
# Cell
class DistributedTrainer(Callback):
"Wrap `model` in `DistributedDataParallel` and `dls` in `DistributedDL`"
fup = None
def __init__(self, cuda_id=0,sync_bn=True): store_attr()
def before_fit(self):
opt_kwargs = { 'find_unused_parameters' : DistributedTrainer.fup } if DistributedTrainer.fup is not None else {}
self.learn.model = DistributedDataParallel(
nn.SyncBatchNorm.convert_sync_batchnorm(self.model) if self.sync_bn else self.model,
device_ids=[self.cuda_id], output_device=self.cuda_id, **opt_kwargs)
self.old_dls = list(self.dls)
self.learn.dls.loaders = [self._wrap_dl(dl) for dl in self.dls]
if rank_distrib(): self.learn.logger=noop
def _wrap_dl(self, dl): return dl if isinstance(dl,DistributedDL) else DistributedDL(dl)
def before_train(self): self.learn.dl = self._wrap_dl(self.learn.dl)
def before_validate(self): self.learn.dl = self._wrap_dl(self.learn.dl)
def after_fit(self): self.learn.model,self.learn.dls.loaders = self.learn.model.module,self.old_dls
# Cell
@patch
def to_distributed(self: Learner, cuda_id, sync_bn=True):
"Add `DistributedTrainer` to a learner"
self.add_cb(DistributedTrainer(cuda_id,sync_bn))
if rank_distrib(): self.remove_cb(ProgressCallback)
return self
# Cell
@patch
def detach_distributed(self: Learner):
"Remove `DistributedTrainer` from a learner"
if num_distrib() <=1: return self
self.remove_cb(DistributedTrainer)
if rank_distrib() and not hasattr(self, 'progress'): self.add_cb(ProgressCallback())
return self
# Cell
@patch
@contextmanager
def distrib_ctx(self: Learner, cuda_id=None,sync_bn=True):
"A context manager to adapt a learner to train in distributed data parallel mode."
# Figure out the GPU to use from rank. Create a dpg if none exists yet.
if cuda_id is None: cuda_id = rank_distrib()
if not torch.distributed.is_initialized():
setup_distrib(cuda_id)
cleanup_dpg = torch.distributed.is_initialized()
else: cleanup_dpg = False
# Adapt self to DistributedDataParallel, yield, and cleanup afterwards.
try:
if num_distrib(): self.to_distributed(cuda_id,sync_bn)
yield self
finally:
self.detach_distributed()
if cleanup_dpg: teardown_distrib()
# Cell
def rank0_first(func, *args, **kwargs):
"Execute `func` in the Rank-0 process first, then in other ranks in parallel."
if args or kwargs: func = partial(func, *args, **kwargs)
dummy_l = Learner(DataLoaders(device='cpu'), nn.Linear(1,1), loss_func=lambda: 0)
with dummy_l.distrib_ctx():
if not rank_distrib(): res = func()
distrib_barrier()
if rank_distrib(): res = func()
return res | 43.52356 | 144 | 0.701071 | 1,202 | 8,313 | 4.680532 | 0.219634 | 0.022396 | 0.020796 | 0.015997 | 0.185389 | 0.12069 | 0.067721 | 0.067721 | 0.067721 | 0.027728 | 0 | 0.002669 | 0.188861 | 8,313 | 191 | 145 | 43.52356 | 0.831677 | 0.209672 | 0 | 0.136986 | 1 | 0.006849 | 0.144818 | 0.00969 | 0 | 0 | 0 | 0 | 0 | 1 | 0.226027 | false | 0 | 0.027397 | 0.034247 | 0.356164 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
535425d9c17e85f5c5efd98e6c8de51c70e06a64 | 13,891 | py | Python | home-aided-query/aid.py | qiaolunzhang/home-aided-query | ba8e08534f40d792bc7ce62614fddbecf2e03e09 | [
"MIT"
] | null | null | null | home-aided-query/aid.py | qiaolunzhang/home-aided-query | ba8e08534f40d792bc7ce62614fddbecf2e03e09 | [
"MIT"
] | null | null | null | home-aided-query/aid.py | qiaolunzhang/home-aided-query | ba8e08534f40d792bc7ce62614fddbecf2e03e09 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import select
import socket
import struct
import os
from datetime import datetime
import math
import random
import utils
import time
def generate_points(x, y, R):
theta = 2.0 * math.pi * random.random()
x1 = x + R * math.sin(theta)
y1 = y + R * math.cos(theta)
x1 = str(x1)
y1 = str(y1)
R = str(R)
message = x1 + "|" + y1 + "|" + R
return message
def generate_three_points(x, y, R):
message = generate_points(x, y, R)
for i in range(2):
message = message + "|" + generate_points(x, y, R)
return message
def decode_three_points(message):
points_list = []
for i in range(3):
point = []
x1_len = message[0:4]
x1_len = struct.unpack('>I', x1_len)[0]
x1 = message[4:4+x1_len]
y1_len = message[4+x1_len:8+x1_len]
y1_len = struct.unpack('>I', y1_len)[0]
y1 = message[8+x1_len:8+x1_len+y1_len]
print(x1, y1)
x1 = float(x1)
y1 = float(y1)
point.append(x1)
point.append(y1)
points_list.append(point)
print(x1*x1 + y1*y1)
message = message[8+x1_len+y1_len:]
print(points_list)
def decode_points(message):
message = message.split('|')
print(message)
x1 = float(message[0])
y1 = float(message[1])
r = float(message[2])
print(x1, y1, r)
return x1, y1, r
def get_packet_request(content_name, content, packet_type):
# 请求名长度
message = struct.pack('>I', len(content_name))
# 请求名
message = message + content_name + content
# 长度+类型+message
message = struct.pack('>I', len(message)) + struct.pack('>I', packet_type) + message
return message
class BaseServer:
MAX_WAITING_CONNECTIONS = 100
RECV_BUFFER = 4096
RECV_msg_content = 4
RECV_MSG_TYPE_LEN = 4
def __init__(self, config_file):
# 用于保存文件名
self.request_times = 0
self.message_points_list = ['', '', '']
self.content_name_dic = {}
self.new_content_name_dic = {}
self.host = ''
self.port = 20000
self.connections = [] # collects all the incoming connections
self.out_conn_dic = {} # collects all the outcoming connections
self.ip_to_sock_dic = {}
self.sock_to_ip_dic = {}
self.cs_dic = {}
self.load_config(config_file)
print("loading config complete.")
self._run()
def load_config(self, config_file):
try:
with open(config_file) as f:
for line in f:
if line[0] != '#':
line = line.split()
if line[0] == 'router_ip':
self.router_host = line[1]
self.router_port = int(line[2])
if line[0] == 'local_ip':
self.host = line[1]
self.port = int(line[2])
continue
if line[0] == 'aid_ip':
self.aid_host = line[1]
self.aid_port = int(line[2])
continue
if line[0] == 'server_ip':
self.server_host = line[1]
self.server_port = int(line[2])
continue
if line[0] == 'client_ip':
self.client_host = line[1]
continue
except Exception, e:
print(Exception, ", ", e)
print("Failed to load the config file")
raise SystemExit
def _bind_socket(self):
"""
Create the sever socket and bind it to the given host and port
:return:
"""
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Now binding the socket, host is ", self.host, " port is ", self.port)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(self.MAX_WAITING_CONNECTIONS)
self.connections.append(self.server_socket)
def _receive(self, sock):
"""
first get length
then get type
process
:return:
"""
data = None
# Retrieves the first 4 bytes form message
tot_len = 0
msg_content = 0
typ_content = 0
# msg_content: 序列化后的数据包的总长度
while tot_len < self.RECV_msg_content:
msg_content = sock.recv(self.RECV_msg_content)
tot_len += len(msg_content)
tot_len = 0
# typ_content: 序列化后的数据包的类型
while tot_len < self.RECV_MSG_TYPE_LEN:
typ_content = sock.recv(self.RECV_MSG_TYPE_LEN)
tot_len += len(typ_content)
if typ_content:
try:
packet_type = struct.unpack('>I', typ_content)[0]
print("The package type is ", packet_type)
except Exception, e:
print(Exception, ", ", e)
print("Failed to unpack the package type")
return
# 如果包里头没有内容,那就并不做处理
if msg_content:
data = ''
try:
# Unpacks the message and gets the message length
msg_content_unpack = struct.unpack('>I', msg_content)[0]
tot_data_len = 0
while tot_data_len < msg_content_unpack:
# Retrieves the chunk i-th chunk of RECV_BUFFER size
chunk = sock.recv(self.RECV_BUFFER)
# If there isn't the expected chunk...
if not chunk:
data = None
break # ... Simply breaks the loop
else:
# Merges the chunks content
data += chunk
tot_data_len += len(chunk)
# 原始的整个数据包
data_origin = msg_content + typ_content + data
# sock.send(data)
print("The received data is ", data, 'the length is', len(data))
self._process_packet(sock, packet_type, data_origin, data)
except Exception, e:
print(Exception, ", ", e)
print("Failed to unpack the packet length")
def _process_packet_interest(self, sock, content_name, content):
"""
send packet to router
"""
# @todo 在这里需要先根据content name得到对应的点
print("Interest packet")
print("Now cs table is: ")
print(self.cs_dic)
print("Now content name is: ")
print(content_name)
x, y, r = decode_points(content_name)
if content_name in self.content_name_dic.keys():
# @todo remove the following line
message = self.cs_dic[content_name]
message = get_packet_request(content_name, message, 4)
#message = self.content_name_dic[content_name]
#message = get_packet_request(message, "", 3)
else:
message = generate_three_points(x, y, r)
# content_name对应新的content_name
self.content_name_dic[content_name] = message
self.new_content_name_dic[message] = content_name
message = get_packet_request(message, "", 3)
"""
for i in range(3):
message = generate_points(x, y, r)
message = get_packet_request(message, "", 3)
self.message_points_list[i] = message
"""
if self.router_host in self.out_conn_dic.keys():
self.out_conn_dic[self.router_host].send(message)
else:
sock_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_client.connect((self.router_host, self.router_port))
self.out_conn_dic[self.router_host] = sock_client
self.sock_to_ip_dic[sock_client] = self.router_host
self.connections.append(sock_client)
sock_client.send(message)
def _find_best_point(self, points, original_content_name, best_point):
"""
points: 3.0|3.0|5.0|5.0|4.0|5.0|5.0|3.0
"""
original_content_name = original_content_name.split('|')
x = float(original_content_name[0])
y = float(original_content_name[1])
z = float(original_content_name[2])
points = points.split('|')
num_points = len(points) / 2
for i in range(num_points):
distance_best = (best_point[0] - x) * (best_point[0] - x) + (best_point[1] - y) * (best_point[1] - y)
index = 2 * i
x_tmp = float(points[index])
y_tmp = float(points[index+1])
distance_now = (x_tmp-x)*(x_tmp-x) + (y_tmp - y) * (y_tmp - y)
if distance_now <= distance_best:
best_point[0] = x_tmp
best_point[1] = y_tmp
return best_point
def _process_packet_data(self, sock, content_name, content):
"""
"""
# @todo 选出最好的点
best_point = [0, 0]
points_returned = content.split(';')
original_content_name = self.new_content_name_dic[content_name]
r = float(content_name.split('|')[2])
print("points returned is: ")
print(points_returned)
print("r is: ", r)
for points in points_returned:
print(points)
if points:
best_point = self._find_best_point(points, original_content_name, best_point)
best_point[0] = str(best_point[0])
best_point[1] = str(best_point[1])
best_point = "|".join(best_point)
message = get_packet_request(self.new_content_name_dic[content_name], best_point, 4)
if self.router_host in self.out_conn_dic.keys():
self.out_conn_dic[self.router_host].send(message)
else:
sock_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_client.connect((self.router_host, self.router_port))
self.out_conn_dic[self.router_host] = sock_client
self.sock_to_ip_dic[sock_client] = self.router_host
self.connections.append(sock_client)
sock_client.send(message)
# @todo 作为是否开启缓存
self.cs_dic[self.new_content_name_dic[content_name]] = best_point
def _process_packet(self, sock, typ_content, data_origin, data):
print("Now process the packet: ", typ_content)
content_name_len = data[0:4]
content_name_len = struct.unpack('>I', content_name_len)[0]
content_name = data[4:4+content_name_len]
if (4+content_name_len) >= len(data):
content = ""
else:
content = data[4+content_name_len:]
print "The content name is: ",
print content_name.decode('utf-8')
print "The content is: ",
print content.decode('utf-8')
if typ_content == 1:
self._process_packet_interest(sock, content_name, content)
elif typ_content == 2:
self._process_packet_data(sock, content_name, content)
elif typ_content == 3:
self._process_packet_aid_query(sock, content_name, content)
elif typ_content == 4:
self._process_packet_aid_reply(sock, content_name, content)
if typ_content == 1:
self.request_times = self.request_times + 1
if self.request_times == 1:
self.time_clock_start = time.clock()
self.time_end = time.time()
self.time_clock_end = time.clock()
self.time_clock_total = self.time_clock_end - self.time_clock_start
if self.request_times > 1:
print("The cpu execution time is: ", self.time_clock_total)
if self.request_times >= 11:
self.request_times = 0
self.time_start = time.time()
print("*******************************************************************************")
def _run(self):
self._bind_socket()
while True:
"""
Actually runs the server.
"""
# Gets the list of sockets which are ready to be read through select non-blocking calls
# The select has a timeout of 60 seconds
try:
ready_to_read, ready_to_write, in_error = select.select(self.connections, [], [], 60)
except socket.error:
continue
else:
for sock in ready_to_read:
if sock == self.server_socket:
if sock == self.server_socket:
try:
# Handles a new client connection
client_socket, client_address = self.server_socket.accept()
self.ip_to_sock_dic[client_address[0]] = client_socket
self.sock_to_ip_dic[client_socket] = client_address[0]
except socket.error:
break
else:
self.connections.append(client_socket)
print "Client (%s, %s) connected" % client_address
# ... else is an incoming client socket connection
else:
try:
#next_route_ip, data = self._receive(sock)
self._receive(sock)
except socket.error:
#print("Client is offline" % client_address)
sock.close()
self.connections.remove(sock)
continue
r = BaseServer("./config/aid.conf")
| 36.459318 | 113 | 0.540278 | 1,646 | 13,891 | 4.316525 | 0.143985 | 0.074314 | 0.021675 | 0.013793 | 0.325686 | 0.251795 | 0.183814 | 0.146798 | 0.117945 | 0.100211 | 0 | 0.018697 | 0.356994 | 13,891 | 380 | 114 | 36.555263 | 0.776758 | 0.06875 | 0 | 0.215827 | 1 | 0 | 0.047685 | 0.006418 | 0 | 0 | 0 | 0.005263 | 0 | 0 | null | null | 0 | 0.032374 | null | null | 0.115108 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
53583b3fa46fe2fa791bd9bb6f7e8087b73a6512 | 661 | py | Python | examples/type/str_url_data.py | millcityrunner/serialize | ae991b99ceeb56ed63d7b450c6b3f18efd4b010b | [
"MIT"
] | null | null | null | examples/type/str_url_data.py | millcityrunner/serialize | ae991b99ceeb56ed63d7b450c6b3f18efd4b010b | [
"MIT"
] | null | null | null | examples/type/str_url_data.py | millcityrunner/serialize | ae991b99ceeb56ed63d7b450c6b3f18efd4b010b | [
"MIT"
] | null | null | null | from serialize-mcr import serialize-mcr
class StrURLData(serialize-mcr):
schema = [
{'name': 'prop1', 'type': (str, 'url')}
]
valid_data = StrURLData({'prop1': 'https://www.google.com/'})
print(valid_data)
# >>> {"prop1": "https://www.google.com/"}
valid_data = StrURLData({'prop1': 'https://www.youtube.com/watch?v=PUCLToWjMKs'})
print(valid_data)
# >>> {"prop1": "https://www.youtube.com/watch?v=PUCLToWjMKs"}
invalid_data = StrURLData({'prop1': 'ttps://www.youtube.com/watch?v=PUCLToWjMKs'})
# >>> ValueError: Property: 'prop1' with Value: 'ttps://www.youtube.com/watch?v=PUCLToWjMKs' does not confirm with Type: (<class 'str'>, 'url').
| 34.789474 | 144 | 0.665658 | 85 | 661 | 5.117647 | 0.376471 | 0.082759 | 0.11954 | 0.165517 | 0.593103 | 0.551724 | 0.34023 | 0.183908 | 0 | 0 | 0 | 0.011925 | 0.111952 | 661 | 18 | 145 | 36.722222 | 0.729131 | 0.369138 | 0 | 0.2 | 0 | 0 | 0.336562 | 0.101695 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.1 | null | null | 0.2 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5366a5b9ed21a67faab1621326bd037327475f57 | 2,295 | py | Python | pysnmp-with-texts/A3COM0027-RMON-EXTENSIONS.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/A3COM0027-RMON-EXTENSIONS.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/A3COM0027-RMON-EXTENSIONS.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 A3COM0027-RMON-EXTENSIONS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM0027-RMON-EXTENSIONS
# Produced by pysmi-0.3.4 at Wed May 1 11:08:40 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)
#
rmonExtensions, = mibBuilder.importSymbols("A3COM0004-GENERIC", "rmonExtensions")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Bits, ObjectIdentity, Unsigned32, MibIdentifier, NotificationType, ModuleIdentity, Counter64, iso, Counter32, TimeTicks, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Bits", "ObjectIdentity", "Unsigned32", "MibIdentifier", "NotificationType", "ModuleIdentity", "Counter64", "iso", "Counter32", "TimeTicks", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
remotePoll = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 1))
hostExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 2))
alarmExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 3))
eventExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 4))
command = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 5))
probeConfigNetExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 25, 6))
mibBuilder.exportSymbols("A3COM0027-RMON-EXTENSIONS", remotePoll=remotePoll, probeConfigNetExtensions=probeConfigNetExtensions, hostExtensions=hostExtensions, eventExtensions=eventExtensions, command=command, alarmExtensions=alarmExtensions)
| 104.318182 | 515 | 0.772113 | 245 | 2,295 | 7.232653 | 0.420408 | 0.090858 | 0.05079 | 0.054176 | 0.404063 | 0.292325 | 0.292325 | 0.292325 | 0.292325 | 0.292325 | 0 | 0.079312 | 0.088017 | 2,295 | 21 | 516 | 109.285714 | 0.76732 | 0.149891 | 0 | 0 | 0 | 0 | 0.263646 | 0.03553 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
536bb349dfcf557a82011052de2db72dd9fff76d | 302 | py | Python | main/scripts/Advice.py | danille/ClothesAdvisor-server | 3c0e91001490ca87f89c0799b5abfa93c7012605 | [
"Apache-2.0"
] | 1 | 2016-05-26T17:56:15.000Z | 2016-05-26T17:56:15.000Z | main/scripts/Advice.py | danille/ClothesAdvisor-server | 3c0e91001490ca87f89c0799b5abfa93c7012605 | [
"Apache-2.0"
] | null | null | null | main/scripts/Advice.py | danille/ClothesAdvisor-server | 3c0e91001490ca87f89c0799b5abfa93c7012605 | [
"Apache-2.0"
] | null | null | null | class Advice:
def __init__(self):
self.clothes = []
self.weather = None
def add_cloth(self, cloth):
self.clothes.append(cloth)
def add_message(self, message):
self.clothes.append(message)
def add_weather(self, weather):
self.weather = weather
| 21.571429 | 36 | 0.619205 | 36 | 302 | 5 | 0.333333 | 0.183333 | 0.188889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.274834 | 302 | 13 | 37 | 23.230769 | 0.821918 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 0 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
7254acc9ddbabf32d59e23a6e9fe77a20de84220 | 6,365 | py | Python | userbot/ayiinxd/linker.py | sensiherme/sensiubot | 698e7d07d6ea98d74c1af24c88296f5bb0516a46 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/ayiinxd/linker.py | sensiherme/sensiubot | 698e7d07d6ea98d74c1af24c88296f5bb0516a46 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/ayiinxd/linker.py | sensiherme/sensiubot | 698e7d07d6ea98d74c1af24c88296f5bb0516a46 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | # Ayiin - Userbot
# Credits (C) 2022-2023 @AyiinXd
#
# FROM Ayiin-Userbot <https://github.com/AyiinXd/Ayiin-Userbot>
# t.me/AyiinXdSupport & t.me/AyiinSupport
# ========================×========================
# Link For Collaborator
# ========================×========================
# ========================Asupan Sagapung========================
asupan_sagapung = [
"https://t.me/AsupanSagapungRobot?start=Z2V0LTk2MTYwOTU5NzQ3NTUy",
"https://t.me/asupanexorBot?start=Z2V0LTMyMDU2NDMzNzc2ODY0",
"https://t.me/asupanexorBot?start=Z2V0LTM0MDU5OTYwODg3OTE4",
"https://t.me/asupanexorBot?start=Z2V0LTM1MDYxNzI0NDQzNDQ1"]
# ========================Exolink========================
exolink = ["https://t.me/asupanexorBot?start=Z2V0LTI1MDQ0MDg4ODg4MTc1",
"https://t.me/asupanexorBot?start=Z2V0LTI2MDQ1ODUyNDQzNzAy",
"https://t.me/asupanexorBot?start=Z2V0LTI4MDQ5Mzc5NTU0NzU2",
"https://t.me/asupanexorBot?start=Z2V0LTMwMDUyOTA2NjY1ODEw",
"https://t.me/asupanexorBot?start=Z2V0LTMxMDU0NjcwMjIxMzM3",
"https://t.me/asupanexorBot?start=Z2V0LTMzMDU4MTk3MzMyMzkx",
"https://t.me/asupanexorBot?start=Z2V0LTMyMDU2NDMzNzc2ODY0",
"https://t.me/asupanexorBot?start=Z2V0LTM0MDU5OTYwODg3OTE4",
"https://t.me/asupanexorBot?start=Z2V0LTM1MDYxNzI0NDQzNDQ1",
"https://t.me/asupanexorBot?start=Z2V0LTQyMDc0MDY5MzMyMTM0",
"https://t.me/asupanexorBot?start=Z2V0LTM5MDY4Nzc4NjY1NTUz",
"https://t.me/asupanexorBot?start=Z2V0LTQxMDcyMzA1Nzc2NjA3",
"https://t.me/asupanexorBot?start=Z2V0LTQwMDcwNTQyMjIxMDgw",
"https://t.me/asupanexorBot?start=Z2V0LTQzMDc1ODMyODg3NjYx",
"https://t.me/asupanexorBot?start=Z2V0LTQ0MDc3NTk2NDQzMTg4",
"https://t.me/asupanexorBot?start=Z2V0LTQ1MDc5MzU5OTk4NzE1",
"https://t.me/asupanexorBot?start=Z2V0LTQ2MDgxMTIzNTU0MjQy",
"https://t.me/asupanexorBot?start=Z2V0LTQ3MDgyODg3MTA5NzY5",
"https://t.me/asupanexorBot?start=Z2V0LTQ5MDg2NDE0MjIwODIz",
"https://t.me/asupanexorBot?start=Z2V0LTQ4MDg0NjUwNjY1Mjk2",
"https://t.me/asupanexorBot?start=Z2V0LTU1MDk2OTk1NTUzOTg1",
"https://t.me/asupanexorBot?start=Z2V0LTU0MDk1MjMxOTk4NDU4",
"https://t.me/asupanexorBot?start=Z2V0LTUxMDg5OTQxMzMxODc3",
"https://t.me/asupanexorBot?start=Z2V0LTUwMDg4MTc3Nzc2MzUw",
"https://t.me/asupanexorBot?start=Z2V0LTUyMDkxNzA0ODg3NDA0",
"https://t.me/asupanexorBot?start=Z2V0LTUzMDkzNDY4NDQyOTMx",
"https://t.me/asupanexorBot?start=Z2V0LTU2MDk4NzU5MTA5NTEy",
"https://t.me/asupanexorBot?start=Z2V0LTYxMTA3NTc2ODg3MTQ3",
"https://t.me/asupanexorBot?start=Z2V0LTU3MTAwNTIyNjY1MDM5",
"https://t.me/asupanexorBot?start=Z2V0LTU4MTAyMjg2MjIwNTY2",
"https://t.me/asupanexorBot?start=Z2V0LTU5MTA0MDQ5Nzc2MDkz",
"https://t.me/asupanexorBot?start=Z2V0LTYwMTA1ODEzMzMxNjIw",
"https://t.me/asupanexorBot?start=Z2V0LTY1MTE0NjMxMTA5MjU1",
"https://t.me/asupanexorBot?start=Z2V0LTY0MTEyODY3NTUzNzI4",
"https://t.me/asupanexorBot?start=Z2V0LTYyMTA5MzQwNDQyNjc0",
"https://t.me/asupanexorBot?start=Z2V0LTYzMTExMTAzOTk4MjAx",
"https://t.me/asupanexorBot?start=Z2V0LTY2MTE2Mzk0NjY0Nzgy",
"https://t.me/asupanexorBot?start=Z2V0LTY3MTE4MTU4MjIwMzA5",
"https://t.me/asupanexorBot?start=Z2V0LTY4MTE5OTIxNzc1ODM2",
"https://t.me/asupanexorBot?start=Z2V0LTcyMTI2OTc1OTk3OTQ0",
"https://t.me/asupanexorBot?start=Z2V0LTcwMTIzNDQ4ODg2ODkw",
"https://t.me/asupanexorBot?start=Z2V0LTY5MTIxNjg1MzMxMzYz",
"https://t.me/asupanexorBot?start=Z2V0LTcxMTI1MjEyNDQyNDE3",
"https://t.me/asupanexorBot?start=Z2V0LTc3MTM1NzkzNzc1NTc5",
"https://t.me/asupanexorBot?start=Z2V0LTczMTI4NzM5NTUzNDcx",
"https://t.me/asupanexorBot?start=Z2V0LTc0MTMwNTAzMTA4OTk4",
"https://t.me/asupanexorBot?start=Z2V0LTc4MTM3NTU3MzMxMTA2",
"https://t.me/asupanexorBot?start=Z2V0LTc1MTMyMjY2NjY0NTI1",
"https://t.me/asupanexorBot?start=Z2V0LTc2MTM0MDMwMjIwMDUy",
"https://t.me/asupanexorBot?start=Z2V0LTc5MTM5MzIwODg2NjMz",
"https://t.me/asupanexorBot?start=Z2V0LTgxMTQyODQ3OTk3Njg3",
"https://t.me/asupanexorBot?start=Z2V0LTgyMTQ0NjExNTUzMjE0",
"https://t.me/asupanexorBot?start=Z2V0LTgwMTQxMDg0NDQyMTYw",
"https://t.me/asupanexorBot?start=Z2V0LTgzMTQ2Mzc1MTA4NzQx",
"https://t.me/asupanexorBot?start=Z2V0LTg4MTU1MTkyODg2Mzc2",
"https://t.me/asupanexorBot?start=Z2V0LTg2MTUxNjY1Nzc1MzIy",
"https://t.me/asupanexorBot?start=Z2V0LTg3MTUzNDI5MzMwODQ5",
"https://t.me/asupanexorBot?start=Z2V0LTg0MTQ4MTM4NjY0MjY4",
"https://t.me/asupanexorBot?start=Z2V0LTg1MTQ5OTAyMjE5Nzk1",
"https://t.me/asupanexorBot?start=Z2V0LTg5MTU2OTU2NDQxOTAz",
"https://t.me/asupanexorBot?start=Z2V0LTkwMTU4NzE5OTk3NDMw",
"https://t.me/asupanexorBot?start=Z2V0LTkzMTY0MDEwNjY0MDEx",
"https://t.me/asupanexorBot?start=Z2V0LTk0MTY1Nzc0MjE5NTM4",
"https://t.me/asupanexorBot?start=Z2V0LTkxMTYwNDgzNTUyOTU3",
"https://t.me/asupanexorBot?start=Z2V0LTkyMTYyMjQ3MTA4NDg0",
"https://t.me/asupanexorBot?start=Z2V0LTk2MTY5MzAxMzMwNTky",
"https://t.me/asupanexorBot?start=Z2V0LTk4MTcyODI4NDQxNjQ2",
"https://t.me/asupanexorBot?start=Z2V0LTk1MTY3NTM3Nzc1MDY1",
"https://t.me/asupanexorBot?start=Z2V0LTk3MTcxMDY0ODg2MTE5",
"https://t.me/asupanexorBot?start=Z2V0LTk5MTc0NTkxOTk3MTcz",
"https://t.me/asupanexorBot?start=Z2V0LTEwMDE3NjM1NTU1MjcwMA",
"https://t.me/asupanexorBot?start=Z2V0LTEwMTE3ODExOTEwODIyNw",
"https://t.me/asupanexorBot?start=Z2V0LTEwMjE3OTg4MjY2Mzc1NA",
"https://t.me/asupanexorBot?start=Z2V0LTEwNTE4NTE3MzMzMDMzNQ",
"https://t.me/asupanexorBot?start=Z2V0LTEwMzE4MTY0NjIxOTI4MQ",
"https://t.me/asupanexorBot?start=Z2V0LTEwNDE4MzQwOTc3NDgwOA",
"https://t.me/asupanexorBot?start=Z2V0LTEwNjE4NjkzNjg4NTg2Mg",
"https://t.me/asupanexorBot?start=Z2V0LTEwNzE4ODcwMDQ0MTM4OQ"
]
| 61.201923 | 73 | 0.67557 | 525 | 6,365 | 8.192381 | 0.198095 | 0.058591 | 0.152523 | 0.395489 | 0.523134 | 0.069751 | 0.069751 | 0.069751 | 0.069751 | 0.069751 | 0 | 0.078534 | 0.15978 | 6,365 | 103 | 74 | 61.796117 | 0.725318 | 0.063629 | 0 | 0.047619 | 0 | 0 | 0.789376 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
725eb8d55c7d76874dc5c24e6ca86afdd343a589 | 3,943 | py | Python | p3_bayes_nets/keyboardAgents.py | peteryuan123/CS181-Homework | f6074399e747136cf8bc52202f91cae6287ec484 | [
"MIT"
] | 3 | 2021-06-17T07:34:16.000Z | 2022-02-21T16:45:27.000Z | p3_bayes_nets/keyboardAgents.py | peteryuan123/CS181-Homework | f6074399e747136cf8bc52202f91cae6287ec484 | [
"MIT"
] | 1 | 2017-08-07T23:37:53.000Z | 2017-08-07T23:37:53.000Z | p3_bayes_nets/keyboardAgents.py | peteryuan123/CS181-Homework | f6074399e747136cf8bc52202f91cae6287ec484 | [
"MIT"
] | 2 | 2021-09-13T13:50:11.000Z | 2021-12-17T05:40:30.000Z | # keyboardAgents.py
# -----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
# keyboardAgents.py
# -----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Directions
import random
class KeyboardAgent(Agent):
"""
An agent controlled by the keyboard.
"""
# NOTE: Arrow keys also work.
WEST_KEY = 'a'
EAST_KEY = 'd'
NORTH_KEY = 'w'
SOUTH_KEY = 's'
BLAST_KEY = 'b'
LASER_KEY = 'n'
STOP_KEY = 'q'
def __init__( self, index = 0 ):
self.lastMove = Directions.STOP
self.index = index
self.keys = []
def getAction( self, state):
from graphicsUtils import keys_waiting
from graphicsUtils import keys_pressed
keys = keys_waiting() + keys_pressed()
if keys != []:
self.keys = keys
legal = state.getLegalActions(self.index)
move = self.getMove(legal)
if move == Directions.STOP:
# Try to move in the same direction as before
if self.lastMove in legal:
move = self.lastMove
if (self.STOP_KEY in self.keys) and Directions.STOP in legal: move = Directions.STOP
if move not in legal:
move = random.choice(legal)
self.lastMove = move
return move
def getMove(self, legal):
move = Directions.STOP
if (self.WEST_KEY in self.keys or 'Left' in self.keys) and Directions.WEST in legal: move = Directions.WEST
if (self.EAST_KEY in self.keys or 'Right' in self.keys) and Directions.EAST in legal: move = Directions.EAST
if (self.NORTH_KEY in self.keys or 'Up' in self.keys) and Directions.NORTH in legal: move = Directions.NORTH
if (self.SOUTH_KEY in self.keys or 'Down' in self.keys) and Directions.SOUTH in legal: move = Directions.SOUTH
if self.BLAST_KEY in self.keys and Directions.BLAST in legal: move = Directions.BLAST
if self.LASER_KEY in self.keys and Directions.LASER in legal: move = Directions.LASER
return move
class KeyboardAgent2(KeyboardAgent):
"""
A second agent controlled by the keyboard.
"""
# NOTE: Arrow keys also work.
WEST_KEY = 'j'
EAST_KEY = "l"
NORTH_KEY = 'i'
SOUTH_KEY = 'k'
STOP_KEY = 'u'
def getMove(self, legal):
move = Directions.STOP
if (self.WEST_KEY in self.keys) and Directions.WEST in legal: move = Directions.WEST
if (self.EAST_KEY in self.keys) and Directions.EAST in legal: move = Directions.EAST
if (self.NORTH_KEY in self.keys) and Directions.NORTH in legal: move = Directions.NORTH
if (self.SOUTH_KEY in self.keys) and Directions.SOUTH in legal: move = Directions.SOUTH
return move
| 38.281553 | 120 | 0.669795 | 556 | 3,943 | 4.694245 | 0.239209 | 0.052107 | 0.057471 | 0.054789 | 0.713793 | 0.701149 | 0.671264 | 0.671264 | 0.671264 | 0.671264 | 0 | 0.002666 | 0.238904 | 3,943 | 102 | 121 | 38.656863 | 0.867044 | 0.370276 | 0 | 0.132075 | 0 | 0 | 0.011129 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.075472 | false | 0 | 0.09434 | 0 | 0.490566 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.