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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4e0d346534f0cd20c64f85f0fdb70567bfe1e8d7 | 354 | py | Python | Aulas/Aula1_print.py | alessonsousa/Python3 | 49600ff4368f999c0fb608c796e2d11942edf09f | [
"MIT"
] | null | null | null | Aulas/Aula1_print.py | alessonsousa/Python3 | 49600ff4368f999c0fb608c796e2d11942edf09f | [
"MIT"
] | null | null | null | Aulas/Aula1_print.py | alessonsousa/Python3 | 49600ff4368f999c0fb608c796e2d11942edf09f | [
"MIT"
] | null | null | null | #Para mostra qualquer coisa na tela, Você usa o print()
print('Alesson', 'Sousa', sep='_')# O função sep='-' fala para o print o que colocar para separa os nome
print('Alesson', 'Sousa', sep='_', end='\n')#esse end='' é para fala o que vc quer no final da linha do print
#Exemplo
#123.456.789-00
print('123','456','789', sep='.', end='-')
print('00') | 32.181818 | 109 | 0.652542 | 62 | 354 | 3.693548 | 0.580645 | 0.052402 | 0.148472 | 0.174672 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.073333 | 0.152542 | 354 | 11 | 110 | 32.181818 | 0.69 | 0.587571 | 0 | 0 | 0 | 0 | 0.288732 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 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 | 1 | 0 | 3 |
4e15cecc08b1cde9ac107937e12fe6ec9240cb6d | 190 | py | Python | api/suids/urls.py | CenterForOpenScience/SHARE | c7715af2881f6fa23197d4e7c381d90169a90ed1 | [
"Apache-2.0"
] | 87 | 2015-01-06T18:24:45.000Z | 2021-08-08T07:59:40.000Z | api/suids/urls.py | fortress-biotech/SHARE | 9c5a05dd831447949fa6253afec5225ff8ab5d4f | [
"Apache-2.0"
] | 442 | 2015-01-01T19:16:01.000Z | 2022-03-30T21:10:26.000Z | api/suids/urls.py | fortress-biotech/SHARE | 9c5a05dd831447949fa6253afec5225ff8ab5d4f | [
"Apache-2.0"
] | 67 | 2015-03-10T16:32:58.000Z | 2021-11-12T16:33:41.000Z | from rest_framework.routers import SimpleRouter
from api.suids import views
router = SimpleRouter()
router.register(r'suids', views.SuidViewSet, basename='suid')
urlpatterns = router.urls
| 23.75 | 61 | 0.805263 | 24 | 190 | 6.333333 | 0.708333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 190 | 7 | 62 | 27.142857 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0.047368 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.4 | 0 | 0.4 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
4e269250407fa19774fcf1e0e1854392032b9961 | 569 | py | Python | pyrecard/subscription/plan.py | DiegoMagg/pyrecard | 4a7adc0342703b4eae6c42eabd2f7cd5e1a4d10f | [
"MIT"
] | 6 | 2020-09-03T12:56:49.000Z | 2020-09-03T13:28:31.000Z | pyrecard/subscription/plan.py | DiegoMagg/pyrecard | 4a7adc0342703b4eae6c42eabd2f7cd5e1a4d10f | [
"MIT"
] | 4 | 2020-08-25T15:28:54.000Z | 2020-08-31T17:08:13.000Z | pyrecard/subscription/plan.py | DiegoMagg/pyrecard | 4a7adc0342703b4eae6c42eabd2f7cd5e1a4d10f | [
"MIT"
] | null | null | null | from pyrecard.utils.pyrequest import pyrequest
PLAN_PATH = '/assinaturas/v1/plans'
def create(json):
return pyrequest('POST', PLAN_PATH, json)
def alter(plan_code, json):
return pyrequest('PUT', f'{PLAN_PATH}/{plan_code}', json)
def activate(plan_code):
return pyrequest('PUT', f'{PLAN_PATH}/{plan_code}/activate')
def inactivate(plan_code):
return pyrequest('PUT', f'{PLAN_PATH}/{plan_code}/inactivate')
def fetch(plan_code):
return pyrequest('GET', f'{PLAN_PATH}/{plan_code}')
def fetch_all():
return pyrequest('GET', PLAN_PATH)
| 19.62069 | 66 | 0.706503 | 80 | 569 | 4.825 | 0.3 | 0.165803 | 0.093264 | 0.134715 | 0.357513 | 0.313472 | 0.313472 | 0.313472 | 0.222798 | 0.222798 | 0 | 0.002037 | 0.137083 | 569 | 28 | 67 | 20.321429 | 0.784114 | 0 | 0 | 0 | 0 | 0 | 0.267135 | 0.233743 | 0 | 0 | 0 | 0 | 0 | 1 | 0.428571 | false | 0 | 0.071429 | 0.428571 | 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 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 3 |
4e363f620d0dd72062004bc406ce4122903589f9 | 7,414 | py | Python | socialdistribution/api/adapters.py | CMPUT404-F21T0/CMPUT404-Project-BetterSocial | 04a621915108a434d50e900165cefdb0d4cca45c | [
"Apache-2.0"
] | null | null | null | socialdistribution/api/adapters.py | CMPUT404-F21T0/CMPUT404-Project-BetterSocial | 04a621915108a434d50e900165cefdb0d4cca45c | [
"Apache-2.0"
] | 2 | 2021-10-29T20:18:57.000Z | 2021-12-04T14:57:34.000Z | socialdistribution/api/adapters.py | CMPUT404-F21T0/CMPUT404-Project-BetterSocial | 04a621915108a434d50e900165cefdb0d4cca45c | [
"Apache-2.0"
] | null | null | null | from typing import Dict, Union, Optional
from uuid import UUID
import requests
from requests.auth import HTTPBasicAuth
from yarl import URL
class BaseAdapter:
"""Default handlers for a given node connection. Methods should be overridden for each team, as needed."""
def __init__(self) -> None:
super().__init__()
self.session = requests.session()
self.session.headers['Accept'] = 'application/json'
def post_inbox_item(self, request, *args, **kwargs):
return request
def send_to_inbox(self, node, author_uuid: Union[str, UUID], post_json: Dict, *args, **kwargs) -> requests.Response:
return self.session.post(
self.get_inbox_url(node, author_uuid),
auth = HTTPBasicAuth(node.node_username, node.node_password),
json = post_json
)
def get_author(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> requests.Response:
return self.session.get(
self.get_author_url(node, author_uuid),
auth = HTTPBasicAuth(node.node_username, node.node_password)
)
def get_authors(self, node, *args, **kwargs) -> requests.Response:
return self.session.get(
self.get_authors_url(node),
params = { 'size': 1000 },
headers = { 'Accept': 'application/json' },
auth = HTTPBasicAuth(node.node_username, node.node_password)
)
def shape_author(self, node, author_uuid: Union[str, UUID], response: requests.Response, *args, **kwargs) -> Optional[Dict]:
if response.ok:
return response.json()
else:
return None
def shape_authors(self, node, response: requests.Response, *args, **kwargs) -> Optional[Dict]:
if response.ok:
return response.json()
else:
return None
def get_author_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / '').human_repr()
def get_authors_url(self, node, *args, **kwargs) -> str:
return (URL(node.host) / node.prefix / 'authors' / '').human_repr()
def get_followers(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return self.session.get(
self.get_followers_url(node, author_uuid),
auth = HTTPBasicAuth(node.node_username, node.node_password)
)
def get_followers_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'followers' / '').human_repr()
def send_friend_request(self, node, author_uuid: Union[str, UUID], follower_json: Dict, *args, **kwargs):
return self.session.post(
self.get_inbox_url(node, author_uuid),
auth = HTTPBasicAuth(node.node_username, node.node_password),
json = follower_json
)
def get_inbox_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'inbox' / '').human_repr()
def remove_follower(self, node, author_uuid: Union[str, UUID], user_uuid: Union[str, UUID], *args, **kwargs):
return self.session.delete(
self.get_follower_url(node, author_uuid, user_uuid),
auth = HTTPBasicAuth(node.node_username, node.node_password)
)
def get_follower_url(self, node, author_uuid: Union[str, UUID], user_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
if isinstance(user_uuid, UUID):
user_uuid = str(user_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'follower' / user_uuid / '').human_repr()
def get_posts(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return requests.get(
self.get_posts_url(node, author_uuid, include_slash = True),
headers = { 'Accept': 'application/json' },
auth = HTTPBasicAuth(node.node_username, node.node_password) # Shouldn't need but in case
)
def get_posts_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
url = URL(node.host) / node.prefix / 'author' / str(author_uuid) / 'posts'
if kwargs.get('include_slash') and kwargs['include_slash'] == True:
url /= ''
return url.human_repr()
class Team1Adapter(BaseAdapter):
pass
class Team4Adapter(BaseAdapter):
def get_author_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid).human_repr()
def get_followers_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'followers').human_repr()
def get_follower_url(self, node, author_uuid: Union[str, UUID], user_uuid: Union[str, UUID], *args, **kwargs) -> str:
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
if isinstance(user_uuid, UUID):
user_uuid = str(user_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'follower' / user_uuid).human_repr()
def get_inbox_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
if isinstance(author_uuid, UUID):
author_uuid = str(author_uuid)
return (URL(node.host) / node.prefix / 'author' / author_uuid / 'inbox').human_repr()
def get_posts_url(self, node, author_uuid: Union[str, UUID], *args, **kwargs):
return super().get_posts_url(node, author_uuid, *args, include_slash = False)
class Team7Adapter(BaseAdapter):
def shape_author(self, node, author_uuid: Union[str, UUID], *args, **kwargs) -> Optional[Dict]:
response = super().get_author(node, author_uuid, *args, **kwargs)
if response.ok:
if node.host in response.json()['id']:
return response.json()
else:
return None
def shape_authors(self, node, *args, **kwargs) -> Optional[Dict]:
response = super().get_authors(node, *args, **kwargs)
if response.ok:
output_json = response.json()
new_items = list()
for item in output_json['items']:
if node.host in item['id']:
new_items.append(item)
output_json['items'] = new_items
return output_json
# A global list of adapters that are tied to nodes via the database.
registered_adapters: Dict[str, BaseAdapter] = {
'default': BaseAdapter(),
'team_1': Team1Adapter(),
'team_4': Team4Adapter(),
'team_7': Team7Adapter(),
}
| 37.256281 | 128 | 0.626652 | 916 | 7,414 | 4.872271 | 0.118996 | 0.145642 | 0.081559 | 0.075286 | 0.735604 | 0.711181 | 0.683173 | 0.646426 | 0.646426 | 0.646426 | 0 | 0.002325 | 0.245751 | 7,414 | 198 | 129 | 37.444444 | 0.79578 | 0.026302 | 0 | 0.456522 | 0 | 0 | 0.033971 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.173913 | false | 0.057971 | 0.036232 | 0.057971 | 0.427536 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 3 |
9d84b7b6381a6f3c016023bcfd74caa6a922fa9b | 625 | py | Python | tests/test_jupyter_integration.py | boeddeker/graphviz | acf79bca4518781cad02c102e89ec4e9ce757088 | [
"MIT"
] | null | null | null | tests/test_jupyter_integration.py | boeddeker/graphviz | acf79bca4518781cad02c102e89ec4e9ce757088 | [
"MIT"
] | null | null | null | tests/test_jupyter_integration.py | boeddeker/graphviz | acf79bca4518781cad02c102e89ec4e9ce757088 | [
"MIT"
] | null | null | null | import pytest
from graphviz import jupyter_integration
def test_get_jupyter_format_mimetype_invalid_raises_unknown():
with pytest.raises(ValueError, match=r'unknown'):
jupyter_integration.get_jupyter_format_mimetype('Brian!')
def test_get_jupyter_mimetype_format_normalizes():
assert jupyter_integration.get_jupyter_mimetype_format(
jupyter_integration.get_jupyter_format_mimetype('jpg')) == 'jpeg'
def test_get_jupyter_mimetype_format_raises_unsupported():
with pytest.raises(ValueError, match='unsupported'):
jupyter_integration.get_jupyter_mimetype_format('A boy called Brian!')
| 32.894737 | 78 | 0.808 | 76 | 625 | 6.184211 | 0.355263 | 0.148936 | 0.178723 | 0.238298 | 0.621277 | 0.489362 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1136 | 625 | 18 | 79 | 34.722222 | 0.848375 | 0 | 0 | 0 | 0 | 0 | 0.08 | 0 | 0 | 0 | 0 | 0 | 0.090909 | 1 | 0.272727 | true | 0 | 0.181818 | 0 | 0.454545 | 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 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
9d874b69262d199893f7832d8c3dfc78745d2cab | 544 | py | Python | sarsa.py | lukaspestalozzi/URLNN-Project2 | 425d3a14f063d91ae4b6183aa866fa074dc1d791 | [
"MIT"
] | null | null | null | sarsa.py | lukaspestalozzi/URLNN-Project2 | 425d3a14f063d91ae4b6183aa866fa074dc1d791 | [
"MIT"
] | null | null | null | sarsa.py | lukaspestalozzi/URLNN-Project2 | 425d3a14f063d91ae4b6183aa866fa074dc1d791 | [
"MIT"
] | null | null | null |
import mountaincar as mc
import numpy as np
from collections import namedtuple
from collections import defaultdict
import matplotlib.pylab as plb
import matplotlib.pyplot as plt
from time import time
State = namedtuple('State', ['x', 'v'])
class SarsaMountainCar(object):
def __init__(self, learning_rate=0.1, reward_factor=0.95, eligibility_decay=0.7):
self.learning_rate = learning_rate
self.reward_factor = reward_factor
self.eligibility_decay = eligibility_decay
def _vizualize(self):
pass
| 24.727273 | 85 | 0.740809 | 72 | 544 | 5.402778 | 0.513889 | 0.092545 | 0.107969 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015837 | 0.1875 | 544 | 21 | 86 | 25.904762 | 0.864253 | 0 | 0 | 0 | 0 | 0 | 0.012891 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.133333 | false | 0.066667 | 0.466667 | 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 | 1 | 1 | 0 | 1 | 0 | 0 | 3 |
9d9d2695df7ed5d007311b6af26fc83339dd2f8b | 526 | py | Python | src/test/python/loader_native.py | dlech/xlang | ace2c924cc1fbecd05804866e183124cbb73bd48 | [
"MIT"
] | null | null | null | src/test/python/loader_native.py | dlech/xlang | ace2c924cc1fbecd05804866e183124cbb73bd48 | [
"MIT"
] | null | null | null | src/test/python/loader_native.py | dlech/xlang | ace2c924cc1fbecd05804866e183124cbb73bd48 | [
"MIT"
] | 1 | 2022-01-23T06:01:40.000Z | 2022-01-23T06:01:40.000Z | import sys
sys.path.append("./generated")
sys.path.append("../../package/pywinrt/projection/pywinrt")
import _winrt
_winrt.init_apartment(_winrt.MTA)
def import_ns(ns):
import importlib.machinery
import importlib.util
module_name = "_winrt_" + ns.replace('.', '_')
loader = importlib.machinery.ExtensionFileLoader(module_name, _winrt.__file__)
spec = importlib.util.spec_from_loader(module_name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
| 30.941176 | 82 | 0.747148 | 65 | 526 | 5.723077 | 0.415385 | 0.104839 | 0.069892 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.127376 | 526 | 16 | 83 | 32.875 | 0.810458 | 0 | 0 | 0 | 1 | 0 | 0.114068 | 0.076046 | 0 | 0 | 0 | 0 | 0 | 1 | 0.071429 | false | 0 | 0.571429 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
9da16db4956d4af0439ae0a5ca6c02568b1d609f | 53,171 | py | Python | src/pytris.py | CSID-DGU/2019-2-OSSPC-MDJ-1 | 2987e11b65bc9e31a30cadd39eea4214e2261998 | [
"MIT"
] | 1 | 2019-09-24T04:55:29.000Z | 2019-09-24T04:55:29.000Z | src/pytris.py | CSID-DGU/2019-2-OSSPC-MDJ-1 | 2987e11b65bc9e31a30cadd39eea4214e2261998 | [
"MIT"
] | null | null | null | src/pytris.py | CSID-DGU/2019-2-OSSPC-MDJ-1 | 2987e11b65bc9e31a30cadd39eea4214e2261998 | [
"MIT"
] | 7 | 2019-09-24T05:14:24.000Z | 2019-12-10T04:15:28.000Z | #!/usr/bin/env python
# coding: utf-8
import pygame
import operator
from mino import *
from random import *
from pygame.locals import *
from ui import *
from screeninfo import get_monitors
from pygame.surface import Surface
import sys
from function import *
#화면크기 조정
screen_width = 0
screen_height = 0
for m in get_monitors():
screen_width = int(m.width*0.7)
screen_height = int(m.height*0.7)
# Define
block_size = 25
width = 10 # Board width
height = 20 # Board height
framerate = 30 # Bigger -> Slower
framerate_n = 30
pygame.init()
size = [screen_width, screen_height]
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)
pygame.time.set_timer(pygame.USEREVENT, framerate * 10)
pygame.time.set_timer(pygame.USEREVENT, framerate_n * 10)
pygame.display.set_caption("ACOTRIS™")
background_file = '../assets/images/backgroundimage.png'
# draw single board
def draw_single_board(next, hold, score, level, goal, matrix):
screen.fill(ui_variables.black)
background_image_alpha(screen, background_file,screen_width, screen_height)
# Draw next mino
grid_n = tetrimino.mino_map[next - 1][0]
for i in range(4):
for j in range(4):
dx = screen_width*0.692 + block_size * j
dy = screen_height*0.22 + block_size * i
if grid_n[i][j] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_n[i][j]],
Rect(dx, dy, block_size*0.9, block_size*0.9)
)
# Draw hold mino
grid_h = tetrimino.mino_map[hold - 1][0]
if hold_mino != -1:
for i in range(4):
for j in range(4):
dx = screen_width*0.252 + block_size * j
dy = screen_height*0.22 + block_size * i
if grid_h[i][j] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_h[i][j]],
Rect(dx, dy, block_size*0.9, block_size*0.9)
)
# Set max score
if score > 999999:
score = 999999
# Draw texts
text_hold = ui_variables.DG_v_small.render("HOLD", 1, ui_variables.white)
text_next = ui_variables.DG_v_small.render("NEXT", 1, ui_variables.white)
text_score = ui_variables.DG_v_small.render("SCORE", 1, ui_variables.white)
score_value = ui_variables.DG_v_small.render(str(score), 1, ui_variables.white)
text_level = ui_variables.DG_v_small.render("LEVEL", 1, ui_variables.white)
level_value = ui_variables.DG_v_small.render(str(level), 1, ui_variables.white)
text_goal = ui_variables.DG_v_small.render("GOAL", 1, ui_variables.white)
goal_value = ui_variables.DG_v_small.render(str(goal), 1, ui_variables.white)
aco = ui_variables.DG_v_small.render("ACO level", 1, ui_variables.white)
screen.blit(text_hold, (screen_width*0.25, screen_height*0.15))
screen.blit(text_level, (screen_width*0.25, screen_height*0.35))
screen.blit(level_value, (screen_width*0.25, screen_height*0.4))
screen.blit(text_goal, (screen_width*0.25, screen_height*0.65))
screen.blit(goal_value, (screen_width*0.25, screen_height*0.7))
screen.blit(text_next, (screen_width*0.69, screen_height*0.15))
screen.blit(aco, (screen_width*0.69, screen_height*0.35))
screen.blit(text_score, (screen_width*0.69, screen_height*0.65))
screen.blit(score_value, (screen_width*0.69, screen_height*0.7))\
# 플레이 화면에 아코 사진
aco_level(level, int(screen_width*0.68), int(screen_height*0.41))
# Draw board
for x in range(width):
for y in range(height):
dx = screen_width*0.4 + block_size * x
dy = screen_height*0.1 + block_size * y
draw_block(screen,dx, dy, ui_variables.t_color[matrix[x][y + 1]], block_size)
def draw_multi_board_1(next, hold_n, score, level, goal, matrix_n):
# Draw next mino_player1
grid_n = tetrimino.mino_map[next - 1][0]
for x in range(4):
for y in range(4):
dx = screen_width*0.39 + block_size * 0.72 * y
dy = screen_height*0.23 + block_size * 0.72 * x
if grid_n[x][y] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_n[x][y]],
Rect(dx, dy, block_size * 0.7, block_size * 0.7)
)
# Draw hold mino_player1
grid_h = tetrimino.mino_map[hold_n - 1][0]
if hold_mino_n != -1:
for x in range(4):
for y in range(4):
dx = screen_width*0.095 + block_size * 0.72 * y
dy = screen_height*0.23 + block_size * 0.72 * x
if grid_h[x][y] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_h[x][y]],
Rect(dx, dy, block_size * 0.7, block_size * 0.7)
)
# Set max score
if score > 999999:
score = 999999
# Draw texts
text_hold = ui_variables.DG_v_small.render("HOLD", 1, ui_variables.white)
text_next = ui_variables.DG_v_small.render("NEXT", 1, ui_variables.white)
text_score = ui_variables.DG_v_small.render("SCORE", 1, ui_variables.white)
score_value = ui_variables.DG_v_small.render(str(score), 1, ui_variables.white)
text_level = ui_variables.DG_v_small.render("LEVEL", 1, ui_variables.white)
level_value = ui_variables.DG_v_small.render(str(level), 1, ui_variables.white)
text_goal = ui_variables.DG_v_small.render("GOAL", 1, ui_variables.white)
goal_value = ui_variables.DG_v_small.render(str(goal), 1, ui_variables.white)
# Place texts for player1
screen.blit(text_hold, (screen_width*0.091, screen_height*0.15))
screen.blit(text_level, (screen_width*0.083, screen_height*0.43))
screen.blit(level_value, (screen_width*0.11, screen_height*0.48))
screen.blit(text_goal, (screen_width*0.092, screen_height*0.7))
screen.blit(goal_value, (screen_width*0.115, screen_height*0.75))
screen.blit(text_next, (screen_width*0.389, screen_height*0.15))
screen.blit(text_score, (screen_width*0.388, screen_height*0.7))
screen.blit(score_value, (screen_width*0.393, screen_height*0.75))
#aco_level(screen_width*0.38, screen_height*0.48)
aco = ui_variables.DG_v_small.render("ACO level", 1, ui_variables.white)
screen.blit(aco, (screen_width*0.39, screen_height*0.43))
aco_level(level1, screen_width*0.38, screen_height*0.48)
# Draw board - player1
for x in range(width):
for y in range(height):
dx = screen_width*0.15 + block_size * x
dy = screen_height*0.1 + block_size * y
draw_block(screen, dx, dy, ui_variables.t_color[matrix_n[x][y + 1]], block_size)
# Draw multi board
def draw_multi_board_2(next, hold, score, level, goal, matrix):
# Draw next mino_player
grid_m = tetrimino.mino_map[next - 1][0]
# Draw next mino_player2
for x in range(4):
for y in range(4):
dx = screen_width*0.84 + block_size * 0.72 * y
dy = screen_height*0.23 + block_size * 0.72 * x
if grid_m[x][y] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_m[x][y]],
Rect(dx,dy, block_size*0.7, block_size*0.7)
)
# Draw hold mino_player1
grid_i = tetrimino.mino_map[hold - 1][0]
# Draw hold mino_player2
if hold_mino != -1:
for x in range(4):
for y in range(4):
dx = screen_width*0.55 + block_size * 0.72 * y
dy = screen_height*0.23 + block_size * 0.72 * x
if grid_i[x][y] != 0:
pygame.draw.rect(
screen,
ui_variables.t_color[grid_i[x][y]],
Rect(dx, dy, block_size * 0.7, block_size * 0.7)
)
# Set max score
if score > 999999:
score = 999999
# Draw texts
text_hold = ui_variables.DG_v_small.render("HOLD", 1, ui_variables.white)
text_next = ui_variables.DG_v_small.render("NEXT", 1, ui_variables.white)
text_score = ui_variables.DG_v_small.render("SCORE", 1, ui_variables.white)
score_value = ui_variables.DG_v_small.render(str(score), 1, ui_variables.white)
text_level = ui_variables.DG_v_small.render("LEVEL", 1, ui_variables.white)
level_value = ui_variables.DG_v_small.render(str(level), 1, ui_variables.white)
text_goal = ui_variables.DG_v_small.render("GOAL", 1, ui_variables.white)
goal_value = ui_variables.DG_v_small.render(str(goal), 1, ui_variables.white)
# Place texts for player2
screen.blit(text_hold, (screen_width*0.546, screen_height*0.15))
screen.blit(text_level, (screen_width*0.54, screen_height*0.43))
screen.blit(level_value, (screen_width*0.546, screen_height*0.48))
screen.blit(text_goal, (screen_width*0.54, screen_height*0.7))
screen.blit(goal_value, (screen_width*0.562, screen_height*0.75))
screen.blit(text_next, (screen_width*0.84, screen_height*0.15))
screen.blit(text_score, (screen_width*0.845, screen_height*0.7))
screen.blit(score_value, (screen_width*0.85, screen_height*0.75))
#aco_level(screen_width*0.84, screen_height*0.48)
aco = ui_variables.DG_v_small.render("ACO level", 1, ui_variables.white)
screen.blit(aco, (screen_width*0.845, screen_height*0.43))
aco_level(level, screen_width*0.84, screen_height*0.48)
# Draw board - player2
for i in range(width):
for j in range(height):
di = screen_width*0.6 + block_size * i
dj = screen_height*0.1 + block_size * j
draw_block(screen, di, dj, ui_variables.t_color[matrix[i][j + 1]], block_size)
#background image
def background_image(filename, width, height, blit_pos):
background = pygame.image.load(filename)
picture = pygame.transform.scale(background,(width, height))
screen.blit(picture,(0,blit_pos))
def aco_level(level, x, y):
# 플레이 화면에 아코 사진
if type == 1:
screen.blit(rect_aco1, (x, y))
if level >=5 and level <=9:
screen.blit(rect_aco2, (x, y))
elif level >= 10:
screen.blit(rect_aco3, (x, y))
elif type == 2:
screen.blit(rect_aco2, (x, y))
if level >= 10:
screen.blit(rect_aco3, (x, y))
elif type == 3:
screen.blit(rect_aco3, (x, y))
# insert image x,y 이미지 위치, r이미지 가로 길이, c이미지 세로 길이
def insert_image(image, x, y, r, c):
photo = pygame.transform.scale(image, (r, c))
screen.blit(photo, (x, y))
# image
image_aco1 = pygame.image.load('../assets/images/aco1.png')
image_aco2 = pygame.image.load('../assets/images/aco2.png')
image_aco3 = pygame.image.load('../assets/images/aco3.png')
image_manual = pygame.image.load('../assets/images/manual.png')
image_winner = pygame.image.load('../assets/images/winner1.png')
image_trophy = pygame.image.load('../assets/images/trophy.png')
rect_aco1b = pygame.image.load('../assets/images/aco1.png').convert()
rect_aco2b = pygame.image.load('../assets/images/aco2.png').convert()
rect_aco3b = pygame.image.load('../assets/images/aco3.png').convert()
rect_aco1 = pygame.transform.scale(rect_aco1b, (int(screen_width*0.12), int(screen_height*0.13)))
rect_aco2 = pygame.transform.scale(rect_aco2b, (int(screen_width*0.13), int(screen_height*0.16)))
rect_aco3 = pygame.transform.scale(rect_aco3b, (int(screen_width*0.14), int(screen_height*0.18)))
# Initial values
blink = False
start_single = False # sinlge mode
start_multi = False # multi mode
pause = False
done = False
game_over = False
multi_over = False
show_score = False
show_manual = False
screen_Start = True
game_mode = False
score = 0
score_n = 0
level = 1
level_n = 1
goal = 1
goal_n = 1
bottom_count = 0
bottom_count_n = 0
hard_drop = False
hard_drop_n = False
player = 0
dx, dy = 3, 0 # Minos location status
dp, dq = 3, 0
rotation = 0 # Minos rotation status
rotation_n = 0
mino = randint(1, 7) # Current mino
mino_n = randint(1,7)
next_mino = randint(1, 7) # Next mino
next_mino_n = randint(1,7)
hold = False # Hold status
hold_n=False
hold_mino = -1 # Holded mino
hold_mino_n = -1
name_location = 0
name = [65, 65, 65]
#모드 별 아코 사진 넣을려고 만듦
type = 0
level1 = 0
level2 = 0
with open('leaderboard.txt') as f:
lines = f.readlines()
lines = [line.rstrip('\n') for line in open('leaderboard.txt')]
leaders = {}
for i in lines:
leaders[i.split(' ')[0]] = int(i.split(' ')[1])
leaders = sorted(leaders.items(), key=operator.itemgetter(1), reverse=True)
matrix= [[0 for y in range(height + 1)] for x in range(width)] # Board matrix
matrix_n = [[0 for k in range(height + 1)] for p in range(width)]
###########################################################
# Loop Start
###########################################################
while not done:
# Pause screen
if pause:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
if start_single == True:
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
elif start_multi == True:
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
#pause시 화면 불투명하게
pause_surface = screen.convert_alpha()
pause_surface.fill((0, 0, 0, 0))
pygame.draw.rect(pause_surface, ui_variables.black_t, [0, 0, int(screen_width), int(screen_height)])
screen.blit(pause_surface, (0, 0))
pause_text = ui_variables.DG_70.render("PAUSED", 1, ui_variables.white)
pause_start = ui_variables.DG_small.render("Press esc to continue", 1, ui_variables.white)
screen.blit(pause_text, (screen_width*0.415, screen_height*0.35))
if blink:
screen.blit(pause_start, (screen_width*0.36, screen_height*0.6))
blink = False
else:
blink = True
pygame.display.update()
elif event.type == KEYDOWN:
erase_mino(dx, dy, mino, rotation, matrix)
erase_mino(dp, dq, mino_n, rotation_n, matrix_n)
if event.key == K_ESCAPE:
pause = False
pygame.time.set_timer(pygame.USEREVENT, 1)
elif event.key == K_q:
done = True
# Game screen
# Start_single screen
elif start_single:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
# Set speed
if not game_over:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_DOWN]:
pygame.time.set_timer(pygame.USEREVENT, framerate * 1)
else:
pygame.time.set_timer(pygame.USEREVENT, framerate * 10)
# Draw a mino
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Erase a mino
if not game_over:
erase_mino(dx, dy, mino, rotation, matrix)
# Move mino down
if not is_bottom(dx, dy, mino, rotation, matrix):
dy += 1
# Create new mino
else:
if hard_drop or bottom_count == 6:
hard_drop = False
bottom_count = 0
score += 10 * level
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
if is_stackable(next_mino, matrix):
mino = next_mino
next_mino = randint(1, 7)
dx, dy = 3, 0
rotation = 0
hold = False
else:
start_single = False
game_over = True
single = True
pygame.time.set_timer(pygame.USEREVENT, 1)
else:
bottom_count += 1
# Erase line
erase_count = 0
for j in range(21):
is_full = True
for i in range(10):
if matrix[i][j] == 0:
is_full = False
if is_full:
erase_count += 1
k = j
while k > 0:
for i in range(10):
matrix[i][k] = matrix[i][k - 1]
k -= 1
if erase_count == 1:
score += 50 * level
elif erase_count == 2:
score += 150 * level
elif erase_count == 3:
score += 350 * level
elif erase_count == 4:
score += 1000 * level
# Increase level
goal -= erase_count
if goal < 1 and level < 15:
level += 1
goal += level * 5
framerate = int(framerate * 0.8)
elif event.type == KEYDOWN:
erase_mino(dx, dy, mino, rotation, matrix)
if event.key == K_ESCAPE:
pause = True
#Q누르면 창 나가짐
elif event.key == K_q:
done = True
# Hard drop
elif event.key == K_SPACE:
while not is_bottom(dx, dy, mino, rotation, matrix):
dy += 1
hard_drop = True
pygame.time.set_timer(pygame.USEREVENT, 1)
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Hold
elif event.key == K_LSHIFT:
if hold == False:
if hold_mino == -1:
hold_mino = mino
mino = next_mino
next_mino = randint(1, 7)
else:
hold_mino, mino = mino, hold_mino
dx, dy = 3, 0
rotation = 0
hold = True
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Turn right
elif event.key == K_UP:
if is_turnable_r(dx, dy, mino, rotation, matrix):
rotation += 1
# Kick
elif is_turnable_r(dx, dy - 1, mino, rotation, matrix):
dy -= 1
rotation += 1
elif is_turnable_r(dx + 1, dy, mino, rotation, matrix):
dx += 1
rotation += 1
elif is_turnable_r(dx - 1, dy, mino, rotation, matrix):
dx -= 1
rotation += 1
elif is_turnable_r(dx, dy - 2, mino, rotation, matrix):
dy -= 2
rotation += 1
elif is_turnable_r(dx + 2, dy, mino, rotation, matrix):
dx += 2
rotation += 1
elif is_turnable_r(dx - 2, dy, mino, rotation, matrix):
dx -= 2
rotation += 1
if rotation == 4:
rotation = 0
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Turn left
elif event.key == K_z or event.key == K_LCTRL:
if is_turnable_l(dx, dy, mino, rotation, matrix):
rotation -= 1
# Kick
elif is_turnable_l(dx, dy - 1, mino, rotation, matrix):
dy -= 1
rotation -= 1
elif is_turnable_l(dx + 1, dy, mino, rotation, matrix):
dx += 1
rotation -= 1
elif is_turnable_l(dx - 1, dy, mino, rotation, matrix):
dx -= 1
rotation -= 1
elif is_turnable_l(dx, dy - 2, mino, rotation, matrix):
dy -= 2
rotation += 1
elif is_turnable_l(dx + 2, dy, mino, rotation, matrix):
dx += 2
rotation += 1
elif is_turnable_l(dx - 2, dy, mino, rotation, matrix):
dx -= 2
if rotation == -1:
rotation = 3
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Move left
elif event.key == K_LEFT:
if not is_leftedge(dx, dy, mino, rotation, matrix):
dx -= 1
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
# Move right
elif event.key == K_RIGHT:
if not is_rightedge(dx, dy, mino, rotation, matrix):
dx += 1
draw_mino(dx, dy, mino, rotation, matrix)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
pygame.display.update()
# Start_multi screen
elif start_multi:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
screen.fill(ui_variables.black)
background_image_alpha(screen, background_file, screen_width, screen_height)
if not multi_over:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_DOWN]:
pygame.time.set_timer(pygame.USEREVENT, framerate*1)
else:
pygame.time.set_timer(pygame.USEREVENT, framerate*10)
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
# Erase a mino
if not multi_over:
erase_mino(dx, dy, mino, rotation, matrix)
# Move mino down
if not is_bottom(dx, dy, mino, rotation, matrix):
dy += 1
# Create new mino
else:
if hard_drop or bottom_count == 6:
hard_drop = False
bottom_count = 0
score += 10 * level
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
if is_stackable(next_mino, matrix):
mino = next_mino
next_mino = randint(1, 7)
dx, dy = 3, 0
rotation = 0
hold = False
else:
start_multi = False
multi_over = True
player = 1
single = False
pygame.time.set_timer(pygame.USEREVENT, 1)
else:
bottom_count += 1
# Erase line
erase_count = 0
for j in range(21):
is_full = True
for i in range(10):
if matrix[i][j] == 0:
is_full = False
if is_full:
erase_count += 1
k = j
while k > 0:
for i in range(10):
matrix[i][k] = matrix[i][k - 1]
k -= 1
if erase_count == 1:
score += 50 * level
elif erase_count == 2:
score += 150 * level
elif erase_count == 3:
score += 350 * level
elif erase_count == 4:
score += 1000 * level
# Increase level
goal -= erase_count
if goal < 1 and level < 15:
level += 1
goal += level * 5
framerate = int(framerate * 0.8)
level_2 = level
draw_mino(dp, dq, mino_n, rotation_n ,matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
if not multi_over:
erase_mino(dp, dq, mino_n, rotation_n, matrix_n)
# Move mino down
if not is_bottom(dp, dq, mino_n, rotation_n, matrix_n):
dq += 1
else:
if hard_drop_n or bottom_count_n == 6:
hard_drop_n = False
bottom_count_n = 0
score_n+=10*level_n
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
if is_stackable(next_mino_n, matrix_n):
mino_n = next_mino_n
next_mino_n = randint(1,7)
dp, dq = 3, 0
rotation_n = 0
hold_n = False
else:
start_multi = False
multi_over= True
player = 2
single = False
pygame.time.set_timer(pygame.USEREVENT, 1)
else:
bottom_count_n += 1
erase_count_n = 0
for j in range(21):
is_full_n = True
for i in range(10):
if matrix_n[i][j] == 0:
is_full_n = False
if is_full_n:
erase_count_n += 1
k = j
while k > 0:
for i in range(10):
matrix_n[i][k] = matrix_n[i][k-1]
k -= 1
if erase_count_n == 1:
score_n += 50 * level_n
elif erase_count_n == 2:
score_n += 150 * level_n
elif erase_count_n == 3:
score_n += 350 * level_n
elif erase_count_n == 4:
score_n += 1000 * level_n
# Increase level
goal_n -= erase_count_n
if goal_n < 1 and level_n < 15:
level_n += 1
goal_n += level_n * 5
framerate_n = int(framerate_n * 0.8)
level1 = level_n
elif event.type == KEYDOWN:
erase_mino(dx, dy, mino, rotation, matrix)
erase_mino(dp, dq, mino_n, rotation_n, matrix_n)
if event.key == K_ESCAPE:
pause = True
#Q누르면 창 나가짐
elif event.key == K_q:
done = True
# Hard drop
elif event.key == K_SPACE:
while not is_bottom(dx, dy, mino, rotation, matrix):
dy += 1
hard_drop = True
pygame.time.set_timer(pygame.USEREVENT, framerate)
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
elif event.key == K_LCTRL:
while not is_bottom(dp, dq, mino_n, rotation_n, matrix_n):
dq += 1
hard_drop_n = True
pygame.time.set_timer(pygame.USEREVENT, framerate_n)
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
# Hold
elif event.key == K_RSHIFT:
if hold == False:
if hold_mino == -1:
hold_mino = mino
mino = next_mino
next_mino = randint(1, 7)
else:
hold_mino, mino = mino, hold_mino
dx, dy = 3, 0
rotation = 0
hold = True
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
elif event.key == K_LSHIFT:
if hold_n == False:
if hold_mino_n == -1:
hold_mino_n = mino_n
mino_n = next_mino_n
next_mino_n = randint(1,7)
else:
hold_mino_n, mino_n = mino_n, hold_mino_n
dp, dq = 3, 0
rotation_n = 0
hold_n = True
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
# Turn right
elif event.key == K_UP :
if is_turnable_r(dx, dy, mino, rotation, matrix):
rotation += 1
# Kick
elif is_turnable_r(dx, dy - 1, mino, rotation, matrix):
dy -= 1
rotation += 1
elif is_turnable_r(dx + 1, dy, mino, rotation, matrix):
dx += 1
rotation += 1
elif is_turnable_r(dx - 1, dy, mino, rotation, matrix):
dx -= 1
rotation += 1
elif is_turnable_r(dx, dy - 2, mino, rotation, matrix):
dy -= 2
rotation += 1
elif is_turnable_r(dx + 2, dy, mino, rotation, matrix):
dx += 2
rotation += 1
elif is_turnable_r(dx - 2, dy, mino, rotation, matrix):
dx -= 2
rotation += 1
if rotation == 4:
rotation = 0
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
elif event.key == K_w:
if is_turnable_r(dp, dq, mino_n, rotation_n, matrix_n):
rotation_n += 1
# Kick
elif is_turnable_r(dp, dq - 1, mino_n, rotation_n, matrix_n):
dq -= 1
rotation_n += 1
elif is_turnable_r(dp + 1, dq, mino_n,rotation_n, matrix_n):
dp += 1
rotation_n += 1
elif is_turnable_r(dp - 1, dq, mino_n, rotation_n, matrix_n):
dp -= 1
rotation_n += 1
elif is_turnable_r(dp, dq - 2, mino_n, rotation_n, matrix_n):
dq -= 2
rotation_n+= 1
elif is_turnable_r(dp + 2, dq, mino_n,rotation_n, matrix_n):
dp += 2
rotation_n+= 1
elif is_turnable_r(dp - 2, dq, mino_n, rotation_n, matrix_n):
dp -= 2
rotation_n += 1
if rotation_n == 4:
rotation_n = 0
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
# Move left
elif event.key == K_LEFT:
if not is_leftedge(dx, dy, mino, rotation, matrix):
dx -= 1
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
elif event.key == K_a:
if not is_leftedge(dp, dq, mino_n, rotation_n, matrix_n):
dp -= 1
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
# Move right
elif event.key == K_RIGHT:
if not is_rightedge(dx, dy, mino, rotation, matrix):
dx += 1
draw_mino(dx, dy, mino, rotation, matrix)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
elif event.key == K_d:
if not is_rightedge(dp, dq, mino_n, rotation_n, matrix_n):
dp += 1
draw_mino(dp, dq, mino_n, rotation_n, matrix_n)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
pygame.display.update()
# Game over screen
elif game_over:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
over_text_1 = ui_variables.DG_70.render("GAME OVER", 1, ui_variables.white)
over_start = ui_variables.DG_v_small.render("Press return to continue", 1, ui_variables.white)
draw_single_board(next_mino, hold_mino, score, level, goal, matrix)
#pause시 화면 불투명하게
over_surface = screen.convert_alpha()
over_surface.fill((0, 0, 0, 0))
pygame.draw.rect(over_surface, ui_variables.black_t, [0, 0, int(screen_width), int(screen_height)])
screen.blit(over_surface, (0, 0))
name_1 = ui_variables.DGM40.render(chr(name[0]), 1, ui_variables.white)
name_2 = ui_variables.DGM40.render(chr(name[1]), 1, ui_variables.white)
name_3 = ui_variables.DGM40.render(chr(name[2]), 1, ui_variables.white)
underbar_1 = ui_variables.DGM40.render("_", 1, ui_variables.white)
underbar_2 = ui_variables.DGM40.render("_", 1, ui_variables.white)
underbar_3 = ui_variables.DGM40.render("_", 1, ui_variables.white)
screen.blit(over_text_1, (int(screen_width*0.37), int(screen_height*0.2)))
screen.blit(name_1, (int(screen_width*0.4), int(screen_height*0.5)))
screen.blit(name_2, (int(screen_width*0.5), int(screen_height*0.5)))
screen.blit(name_3, (int(screen_width*0.6), int(screen_height*0.5)))
if blink:
screen.blit(over_start, (int(screen_width*0.38), int(screen_height*0.7)))
blink = False
else:
if name_location == 0:
screen.blit(underbar_1, (int(screen_width*0.4), int(screen_height*0.52)))
elif name_location == 1:
screen.blit(underbar_2, (int(screen_width*0.5), int(screen_height*0.52)))
elif name_location == 2:
screen.blit(underbar_3, (int(screen_width*0.6), int(screen_height*0.52)))
blink = True
pygame.display.update()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
outfile = open('leaderboard.txt','a')
outfile.write(chr(name[0]) + chr(name[1]) + chr(name[2]) + ' ' + str(score) + '\n')
outfile.close()
pygame.time.set_timer(pygame.USEREVENT, 1)
sys.exit()
game_over = False
hold = False
dx, dy = 3, 0
dp, dq = 3, 0
rotation = 0
rotation_n =0
mino = randint(1, 7)
mino_n = randint(1,7)
next_mino = randint(1, 7)
next_mino_n = randint(1,7)
hold_mino = -1
hold_mino_n = -1
framerate = 30
framerate_n = 30
score = 0
score_n = 0
level = 1
level_n = 1
goal = level * 5
goal_n = level_n*5
bottom_count = 0
bottom_count_n = 0
hard_drop = False
hard_drop_n = False
if event.key == K_RIGHT:
if name_location != 2:
name_location += 1
else:
name_location = 0
pygame.time.set_timer(pygame.USEREVENT, 1)
elif event.key == K_LEFT:
if name_location != 0:
name_location -= 1
else:
name_location = 2
pygame.time.set_timer(pygame.USEREVENT, 1)
elif event.key == K_UP:
if name[name_location] != 90:
name[name_location] += 1
else:
name[name_location] = 65
pygame.time.set_timer(pygame.USEREVENT, 1)
elif event.key == K_DOWN:
if name[name_location] != 65:
name[name_location] -= 1
else:
name[name_location] = 90
pygame.time.set_timer(pygame.USEREVENT, 1)
elif event.key == K_q:
done = True
elif multi_over:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
title = "ACOTRIS"
winner_text = "{}P win".format(player)
title_text_1 = ui_variables.DG_big.render(title, 1, ui_variables.white)
over_text_1 = ui_variables.DG_70.render(winner_text, 1, ui_variables.white)
draw_multi_board_1(next_mino_n, hold_mino_n, score_n, level_n, goal_n, matrix_n)
draw_multi_board_2(next_mino, hold_mino, score, level, goal, matrix)
#pause시 화면 불투명하게
over_surface = screen.convert_alpha()
over_surface.fill((0, 0, 0, 0))
pygame.draw.rect(over_surface, ui_variables.black_t, [0, 0, int(screen_width), int(screen_height)])
screen.blit(over_surface, (0, 0))
screen.blit(title_text_1,(int(screen_width*0.35), int(screen_height*0.1)))
screen.blit(over_text_1, (int(screen_width*0.39), int(screen_height*0.75)))
insert_image(image_winner, screen_width*0.25, screen_height*0.12, int(screen_width*0.55), int(screen_height*0.65))
insert_image(image_trophy, screen_width*0.21, screen_height*0.13, int(screen_width*0.1), int(screen_height*0.18))
insert_image(image_trophy, screen_width*0.7, screen_height*0.13, int(screen_width*0.1), int(screen_height*0.18))
pygame.display.update()
if event.type == KEYDOWN:
if event.key == K_q:
done = True
elif event.key == K_RETURN:
done = True
elif game_mode:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
keys = pygame.key.get_pressed()
# Q누르면 창 나가짐
if event.key == K_q:
done = True
elif keys[pygame.K_s] and keys[pygame.K_e]:
start_single = True
level = 1
goal = level * 5
type = 1
elif keys[pygame.K_s] and keys[pygame.K_r]:
level = 5
start_single = True
goal = level * 5
type = 2
elif keys[pygame.K_s] and keys[pygame.K_t]:
level = 10
start_single = True
goal = level * 5
type = 3
elif keys[pygame.K_m] and keys[pygame.K_e]:
level = 1
goal = level * 5
level_n = 1
goal_n = level_n*5
start_multi= True
type = 1
elif keys[pygame.K_m] and keys[pygame.K_r]:
level = 5
goal = level * 5
level_n = 5
goal_n = level_n*5
start_multi = True
type = 2
elif keys[pygame.K_m] and keys[pygame.K_t]:
level = 10
start_multi = True
goal = level * 5
level_n = 10
goal_n = level_n*5
type = 3
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
screen.fill(ui_variables.black)
background_image(background_file, screen_width, int(screen_height/2), int(screen_height/2))
game_mode_title = ui_variables.DG_small.render("게임옵션설정(두개의 키를 동시에 눌러주세요!)", 1, ui_variables.white)
game_mode_choice = ui_variables.DG_v_small.render("게임모드설정", 1, ui_variables.white)
game_mode_speed = ui_variables.DG_v_small.render("게임속도설정", 1, ui_variables.white)
game_mode_single = ui_variables.DG_v_small.render("● Single 모드 (S키)", 1, ui_variables.white)
game_mode_single_des = ui_variables.DG_v_small.render("혼자서 재미있게 하기!!", 1, ui_variables.white)
game_mode_multi = ui_variables.DG_v_small.render("● Multi 모드 (M키)", 1, ui_variables.white)
game_mode_multi_des = ui_variables.DG_v_small.render("둘이서 재미있게 하기!!", 1, ui_variables.white)
game_speed_easy = ui_variables.DG_v_small.render("● 아코 모드(E키)", 1, ui_variables.white)
game_speed_normal = ui_variables.DG_v_small.render("● 엉아코 모드(R키)", 1, ui_variables.white)
game_speed_hard = ui_variables.DG_v_small.render("● 졸업코 모드(T키)", 1, ui_variables.white)
game_speed_easy_des = ui_variables.DG_v_small.render("EASY 모드!", 1, ui_variables.white)
game_speed_normal_des = ui_variables.DG_v_small.render("NORMAL 모드!!", 1, ui_variables.white)
game_speed_hard_des = ui_variables.DG_v_small.render("HARD 모드!!!", 1, ui_variables.white)
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.055)],
[screen_width,int(screen_height*0.055)],2)
screen.blit(game_mode_title, (int(screen_width*0.1)+int(int(screen_width*0.3)*0.4), int(screen_height*0.065)))
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.125)],
[screen_width,int(screen_height*0.125)],2)
pygame.draw.rect(screen, ui_variables.white, [int(screen_width*0.175), int(screen_height*0.2), int(screen_width*0.2), int(screen_height*0.075)], 2)
pygame.draw.rect(screen, ui_variables.white, [int(screen_width*0.625), int(screen_height*0.2), int(screen_width*0.2), int(screen_height*0.075)], 2)
screen.blit(game_mode_choice, (int(screen_width*0.198), int(screen_height*0.215)))
screen.blit(game_mode_speed, (int(screen_width*0.655), int(screen_height*0.215)))
screen.blit(game_mode_single, (int(screen_width*0.15), int(screen_height*0.35)))
screen.blit(game_mode_multi, (int(screen_width*0.15), int(screen_height*0.55)))
screen.blit(game_mode_single_des, (int(screen_width*0.179), int(screen_height*0.4)))
screen.blit(game_mode_multi_des, (int(screen_width*0.179), int(screen_height*0.6)))
screen.blit(game_speed_easy, (int(screen_width*0.6), int(screen_height*0.3)))
screen.blit(game_speed_normal, (int(screen_width*0.6), int(screen_height*0.45)))
screen.blit(game_speed_hard, (int(screen_width*0.6), int(screen_height*0.6)))
screen.blit(game_speed_easy_des, (int(screen_width*0.65), int(screen_height*0.35)))
screen.blit(game_speed_normal_des, (int(screen_width*0.65), int(screen_height*0.5)))
screen.blit(game_speed_hard_des, (int(screen_width*0.65), int(screen_height*0.65)))
insert_image(image_aco1, int(screen_width*0.79), int(screen_height*0.295), int(screen_width*0.1), int(screen_height*0.1))
insert_image(image_aco2, int(screen_width*0.8), int(screen_height*0.445), int(screen_width*0.1), int(screen_height*0.1))
insert_image(image_aco3, int(screen_width*0.8), int(screen_height*0.595), int(screen_width*0.1), int(screen_height*0.1))
pygame.display.update()
# Manual screen
elif show_manual:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
if event.key == K_SPACE:
game_mode = True
elif event.key == K_q:
done = True
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
screen.fill(ui_variables.black)
background_image('../assets/images/manual.png', screen_width, screen_height, 0)
show_score_manual = ui_variables.DG_small.render("Manual", 1, ui_variables.white)
show_desc1_manual = ui_variables.DGM23.render("Pytris는 테트리스 게임으로 총 7가지 모양의 블록이 위에서 아래로", 1, ui_variables.white)
show_desc2_manual = ui_variables.DGM23.render("떨어질 때 블록을 회전, 이동, 낙하 시켜 빈 곳으로 블록을 끼워 넣어", 1, ui_variables.white)
show_desc3_manual = ui_variables.DGM23.render("한 라인을 채우면 라인이 제거되면서 점수를 얻는 방식입니다.", 1, ui_variables.white)
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.055)],
[screen_width,int(screen_height*0.055)],2)
screen.blit(show_score_manual, (int(screen_width*0.3)+int(int(screen_width*0.3)*0.5), int(screen_height*0.06)))
screen.blit(show_desc1_manual, (int(screen_width*0.05)+int(int(screen_width*0.1)*0.5), int(screen_height*0.15)))
screen.blit(show_desc2_manual, (int(screen_width*0.05)+int(int(screen_width*0.1)*0.5), int(screen_height*0.2)))
screen.blit(show_desc3_manual, (int(screen_width*0.05)+int(int(screen_width*0.1)*0.5), int(screen_height*0.25)))
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.125)],
[screen_width,int(screen_height*0.125)],2)
title_start = ui_variables.DGM23.render("<Press space to start>", 1, ui_variables.white)
screen.blit(title_start, (screen_width*0.37, screen_height*0.75))
pygame.display.update()
# Show score
elif show_score:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
# Q누르면 창 나가짐
if event.key == K_q:
done = True
#space누르면 매뉴얼 창으로
elif event.key == K_SPACE:
show_manual = True
elif event.type == USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 300)
screen.fill(ui_variables.black)
background_image(background_file, screen_width, int(screen_height/2), int(screen_height/2))
show_score_list = list()
i = 0
try:
while i<10:
j=0
temp = ui_variables.DG_small.render('%2d' % ((i+1))+'등 '+'{:>6s}'.format(leaders[i][j]) + ' ' + '{:<8s}'.format(str(leaders[i][j+1])), 1, ui_variables.white)
show_score_list.append(temp)
i+=1
except:
show_manual = True
show_name_y = int(screen_height*0.17)
prop = (show_name_y*0.3)
for element in show_score_list:
screen.blit(element, (int(screen_width*0.3)+int(int(screen_width*0.3)*0.25), show_name_y))
show_name_y += prop
show_button_right = ui_variables.DGM23.render("<Press space to start>", 1, ui_variables.white)
show_score_title = ui_variables.DG_small.render("Ranking", 1, ui_variables.white)
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.055)],
[screen_width,int(screen_height*0.055)],2)
screen.blit(show_score_title, (int(screen_width*0.3)+int(int(screen_width*0.3)*0.5), int(screen_height*0.065)))
pygame.draw.line(screen, ui_variables.white,
[0, int(screen_height*0.125)],
[screen_width,int(screen_height*0.125)],2)
screen.blit(show_button_right, (int(screen_width*0.33)+int(int(screen_width*0.33)*0.2), show_name_y+prop))
pygame.display.flip()
# Start screen
else:
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
if event.key == K_SPACE:
show_score=True
#Q 누르면 창 나가짐
elif event.key == K_q:
done = True
screen.fill(ui_variables.white)
background_image(background_file, screen_width, int(screen_height/2), int(screen_height/2))
insert_image(image_aco1, screen_width*0.52, screen_height*0.29, 150, 130)
insert_image(image_aco2, screen_width*0.65, screen_height*0.22, 180, 180)
insert_image(image_aco3, screen_width*0.8, screen_height*0.18, 210, 210)
title = ui_variables.DG_big.render("ACOTRIS", 1, ui_variables.black)
title_uni = ui_variables.DG_small.render("in DGU", 1, ui_variables.black)
title_start = ui_variables.DGM23.render("<Press space to start>", 1, ui_variables.white)
title_info = ui_variables.DGM13.render("Copyright (c) 2017 Jason Kim All Rights Reserved.", 1, ui_variables.white)
if blink:
screen.blit(title_start, (91, 195))
blink = False
else:
blink = True
screen.blit(title, (screen_width*0.028, screen_height*0.3))
screen.blit(title_uni, (screen_width*0.37, screen_height*0.3))
screen.blit(title_start, (screen_width*0.37, screen_height*0.55))
screen.blit(title_info, (screen_width*0.35, screen_height*0.93))
if not show_score:
pygame.display.update()
clock.tick(3)
pygame.quit()
| 41.313908 | 179 | 0.514134 | 6,714 | 53,171 | 3.841823 | 0.063896 | 0.065674 | 0.056951 | 0.040862 | 0.802512 | 0.753702 | 0.714856 | 0.650229 | 0.61964 | 0.577188 | 0 | 0.045269 | 0.383875 | 53,171 | 1,286 | 180 | 41.346034 | 0.74188 | 0.025992 | 0 | 0.627789 | 0 | 0 | 0.018535 | 0.005719 | 0 | 0 | 0 | 0 | 0 | 1 | 0.006085 | false | 0 | 0.010142 | 0 | 0.016227 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 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 | 3 |
9da1ed6becdb22c4f8292e530b55e6268710e72f | 1,346 | py | Python | tests/test_status.py | ehdgua01/blocksync | da0198dde87d284ea3c9472c10f51028e05014a0 | [
"MIT"
] | 5 | 2020-06-03T09:30:15.000Z | 2021-12-14T23:48:47.000Z | tests/test_status.py | ehdgua01/blocksync | da0198dde87d284ea3c9472c10f51028e05014a0 | [
"MIT"
] | 2 | 2021-03-19T07:37:57.000Z | 2021-06-18T11:54:46.000Z | tests/test_status.py | ehdgua01/blocksync | da0198dde87d284ea3c9472c10f51028e05014a0 | [
"MIT"
] | null | null | null | from blocksync._consts import ByteSizes
from blocksync._status import Blocks
def test_initialize_status(fake_status):
# Expect: Set chunk size
assert fake_status.chunk_size == fake_status.src_size // fake_status.workers
def test_add_block(fake_status):
# Expect: Add each blocks and calculate done block
fake_status.add_block("same")
fake_status.add_block("same")
fake_status.add_block("diff")
assert fake_status.blocks == Blocks(same=2, diff=1, done=3)
def test_get_rate(fake_status):
# Expect: Return 0.00 when nothing done
assert fake_status.rate == 0.00
fake_status.block_size = ByteSizes.MiB
fake_status.src_size = fake_status.dest_size = ByteSizes.MiB * 10
# Expect: Return 50.00 when half done
fake_status.add_block("same")
fake_status.add_block("same")
fake_status.add_block("same")
fake_status.add_block("diff")
fake_status.add_block("diff")
assert fake_status.rate == 50.00
# Expect: Return 100.00 when all done
fake_status.add_block("same")
fake_status.add_block("same")
fake_status.add_block("same")
fake_status.add_block("diff")
fake_status.add_block("diff")
assert fake_status.rate == 100.00
# Expect: Return 100.00 when exceeding the total size
fake_status.add_block("diff")
assert fake_status.rate == 100.00
| 30.590909 | 80 | 0.724368 | 204 | 1,346 | 4.509804 | 0.22549 | 0.304348 | 0.197826 | 0.273913 | 0.543478 | 0.543478 | 0.436957 | 0.436957 | 0.419565 | 0.419565 | 0 | 0.035009 | 0.172363 | 1,346 | 43 | 81 | 31.302326 | 0.790844 | 0.173106 | 0 | 0.592593 | 0 | 0 | 0.050633 | 0 | 0 | 0 | 0 | 0 | 0.222222 | 1 | 0.111111 | false | 0 | 0.074074 | 0 | 0.185185 | 0 | 0 | 0 | 0 | null | 1 | 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 | 3 |
9da20747a22e24702a7eb51c79e588aff84309dd | 275 | py | Python | tests/helpers.py | hawkfish/sudoku | eaae1aa3080032266db0fcfc8a6520a9cb5690fe | [
"MIT"
] | null | null | null | tests/helpers.py | hawkfish/sudoku | eaae1aa3080032266db0fcfc8a6520a9cb5690fe | [
"MIT"
] | null | null | null | tests/helpers.py | hawkfish/sudoku | eaae1aa3080032266db0fcfc8a6520a9cb5690fe | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import os
def readFixture(sdk):
f = open(os.path.join('tests', 'fixtures', sdk), 'r')
lines = f.readlines()
f.close()
return [ line.strip('\n') for line in lines]
def valuesFromDisplay(display):
return [value-1 for value in display]
| 21.153846 | 57 | 0.643636 | 40 | 275 | 4.425 | 0.7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009009 | 0.192727 | 275 | 12 | 58 | 22.916667 | 0.788288 | 0.061818 | 0 | 0 | 0 | 0 | 0.062257 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.125 | 0.125 | 0.625 | 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 | 1 | 0 | 0 | 3 |
9dcae389894300bd7f91c57ac11fc79ac0e2fd30 | 14,770 | py | Python | backend/core/migrations/0001_initial.py | mashuq/academia | 571b3db58de4a70210ebd9d92c0f152016aec861 | [
"Unlicense"
] | null | null | null | backend/core/migrations/0001_initial.py | mashuq/academia | 571b3db58de4a70210ebd9d92c0f152016aec861 | [
"Unlicense"
] | null | null | null | backend/core/migrations/0001_initial.py | mashuq/academia | 571b3db58de4a70210ebd9d92c0f152016aec861 | [
"Unlicense"
] | null | null | null | # Generated by Django 3.1.6 on 2021-02-25 05:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Answer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mark', models.FloatField()),
],
),
migrations.CreateModel(
name='Assessment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256)),
('contribution', models.FloatField()),
('start_date', models.DateTimeField()),
('end_date', models.DateTimeField()),
],
),
migrations.CreateModel(
name='Course',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256)),
('code', models.CharField(max_length=10)),
('description', models.TextField()),
('curriculum', models.TextField(blank=True, null=True)),
('image', models.ImageField(upload_to='course_images/')),
('visible', models.BooleanField()),
],
),
migrations.CreateModel(
name='CourseCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256)),
],
),
migrations.CreateModel(
name='Lesson',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mark', models.FloatField()),
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_core.question_set+', to='contenttypes.contenttype')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
),
migrations.CreateModel(
name='Section',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256)),
('start_date', models.DateTimeField()),
('end_date', models.DateTimeField()),
('visible', models.BooleanField()),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.course')),
],
),
migrations.CreateModel(
name='Session',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=512)),
('serial', models.IntegerField()),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.course')),
],
),
migrations.CreateModel(
name='Testimonial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('testimonial', models.CharField(max_length=4000)),
('name', models.CharField(max_length=64)),
('identity', models.CharField(max_length=128)),
('serial', models.IntegerField()),
],
),
migrations.CreateModel(
name='AudioLesson',
fields=[
('lesson_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.lesson')),
('embed', models.TextField()),
('audio_type', models.CharField(choices=[('SOUNDCLOUD', 'SoundCloud')], default='SOUNDCLOUD', max_length=32)),
],
bases=('core.lesson',),
),
migrations.CreateModel(
name='BroadAnswer',
fields=[
('answer_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.answer')),
('answer', models.TextField()),
],
bases=('core.answer',),
),
migrations.CreateModel(
name='BroadQuestion',
fields=[
('question_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.question')),
('question', models.CharField(max_length=512)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.question',),
),
migrations.CreateModel(
name='MultipleChoiceAnswer',
fields=[
('answer_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.answer')),
('answer', models.CharField(max_length=128)),
],
bases=('core.answer',),
),
migrations.CreateModel(
name='MultipleChoiceQuestion',
fields=[
('question_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.question')),
('question', models.CharField(max_length=512)),
('choice1', models.CharField(max_length=128)),
('choice2', models.CharField(max_length=128)),
('choice3', models.CharField(max_length=128)),
('choice4', models.CharField(max_length=128)),
('correct_choice', models.CharField(max_length=128)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.question',),
),
migrations.CreateModel(
name='NoteLesson',
fields=[
('lesson_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.lesson')),
('note', models.FileField(upload_to='course_files/')),
],
bases=('core.lesson',),
),
migrations.CreateModel(
name='ShortAnswer',
fields=[
('answer_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.answer')),
('answer', models.CharField(max_length=2048)),
],
bases=('core.answer',),
),
migrations.CreateModel(
name='ShortQuestion',
fields=[
('question_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.question')),
('question', models.CharField(max_length=512)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('core.question',),
),
migrations.CreateModel(
name='VideoLesson',
fields=[
('lesson_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.lesson')),
('link', models.CharField(max_length=512)),
('video_type', models.CharField(choices=[('YOUTUBE', 'YouTube')], default='YOUTUBE', max_length=32)),
],
bases=('core.lesson',),
),
migrations.CreateModel(
name='Teacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female')], max_length=6)),
('date_of_birth', models.DateTimeField(null=True)),
('biography', models.TextField(null=True)),
('profile_picture', models.ImageField(null=True, upload_to='')),
('teacher_type', models.CharField(choices=[('MAIN', 'Main'), ('ASSISTANT', 'Assistant')], max_length=32)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('gender', models.CharField(choices=[('MALE', 'Male'), ('FEMALE', 'Female')], max_length=6)),
('date_of_birth', models.DateTimeField()),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='question',
name='session',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.session'),
),
migrations.AddField(
model_name='lesson',
name='session',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.session'),
),
migrations.AddField(
model_name='course',
name='course_category',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='core.coursecategory'),
),
migrations.CreateModel(
name='AssessmentResult',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('total_mark', models.FloatField()),
('assessment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.assessment')),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.student')),
],
),
migrations.AddField(
model_name='assessment',
name='section',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.section'),
),
migrations.AddField(
model_name='answer',
name='assessment',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.assessment'),
),
migrations.AddField(
model_name='answer',
name='student',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.student'),
),
migrations.CreateModel(
name='Admin',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='SessionSection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('visible', models.BooleanField()),
('section', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.section')),
('session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.session')),
],
options={
'unique_together': {('section', 'session')},
},
),
migrations.CreateModel(
name='SectionTeacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('section', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.section')),
('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.teacher')),
],
options={
'unique_together': {('section', 'teacher')},
},
),
migrations.CreateModel(
name='Enrolment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('final_grade', models.FloatField()),
('section', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.section')),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.student')),
],
options={
'unique_together': {('section', 'student')},
},
),
migrations.CreateModel(
name='AssessmentQuestion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('assessment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.assessment')),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.question')),
],
options={
'unique_together': {('assessment', 'question')},
},
),
]
| 47.491961 | 207 | 0.561882 | 1,369 | 14,770 | 5.913806 | 0.119065 | 0.032609 | 0.055336 | 0.086957 | 0.740983 | 0.713809 | 0.684906 | 0.679718 | 0.661314 | 0.642416 | 0 | 0.009835 | 0.290928 | 14,770 | 310 | 208 | 47.645161 | 0.763201 | 0.003047 | 0 | 0.693069 | 1 | 0 | 0.134619 | 0.007132 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.009901 | 0 | 0.023102 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
9ddcc75effef9735c94806309f3290c831fcccf5 | 219 | py | Python | UnityEngine/HideFlags/__init__.py | Grim-es/udon-pie-auto-completion | c2cd86554ed615cdbbb01e19fa40665eafdfaedc | [
"MIT"
] | null | null | null | UnityEngine/HideFlags/__init__.py | Grim-es/udon-pie-auto-completion | c2cd86554ed615cdbbb01e19fa40665eafdfaedc | [
"MIT"
] | null | null | null | UnityEngine/HideFlags/__init__.py | Grim-es/udon-pie-auto-completion | c2cd86554ed615cdbbb01e19fa40665eafdfaedc | [
"MIT"
] | null | null | null | from UdonPie import UnityEngine
from UdonPie.Undefined import *
class HideFlags:
def __new__(cls, arg1=None):
'''
:returns: HideFlags
:rtype: UnityEngine.HideFlags
'''
pass
| 18.25 | 37 | 0.611872 | 21 | 219 | 6.190476 | 0.714286 | 0.169231 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006536 | 0.30137 | 219 | 11 | 38 | 19.909091 | 0.843137 | 0.223744 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0.2 | 0.4 | 0 | 0.8 | 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 | 1 | 1 | 0 | 0 | 0 | 0 | 3 |
d1a20a252ae1bd2bda733e48649244f828568be5 | 2,840 | py | Python | S4/S4 Library/generated/protocolbuffers/ResourceKey_pb2.py | NeonOcean/Environment | ca658cf66e8fd6866c22a4a0136d415705b36d26 | [
"CC-BY-4.0"
] | 1 | 2021-05-20T19:33:37.000Z | 2021-05-20T19:33:37.000Z | S4/S4 Library/generated/protocolbuffers/ResourceKey_pb2.py | NeonOcean/Environment | ca658cf66e8fd6866c22a4a0136d415705b36d26 | [
"CC-BY-4.0"
] | null | null | null | S4/S4 Library/generated/protocolbuffers/ResourceKey_pb2.py | NeonOcean/Environment | ca658cf66e8fd6866c22a4a0136d415705b36d26 | [
"CC-BY-4.0"
] | null | null | null | from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
DESCRIPTOR = descriptor.FileDescriptor(name='ResourceKey.proto', package='EA.Sims4.Network', serialized_pb='\n\x11ResourceKey.proto\x12\x10EA.Sims4.Network"<\n\x0bResourceKey\x12\x0c\n\x04type\x18\x01 \x02(\r\x12\r\n\x05group\x18\x02 \x02(\r\x12\x10\n\x08instance\x18\x03 \x02(\x04"G\n\x0fResourceKeyList\x124\n\rresource_keys\x18\x01 \x03(\x0b2\x1d.EA.Sims4.Network.ResourceKeyB\x0eB\x0cResourceKeys')
_RESOURCEKEY = descriptor.Descriptor(name='ResourceKey', full_name='EA.Sims4.Network.ResourceKey', filename=None, file=DESCRIPTOR, containing_type=None, fields=[descriptor.FieldDescriptor(name='type', full_name='EA.Sims4.Network.ResourceKey.type', index=0, number=1, type=13, cpp_type=3, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), descriptor.FieldDescriptor(name='group', full_name='EA.Sims4.Network.ResourceKey.group', index=1, number=2, type=13, cpp_type=3, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), descriptor.FieldDescriptor(name='instance', full_name='EA.Sims4.Network.ResourceKey.instance', index=2, number=3, type=4, cpp_type=4, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None)], extensions=[], nested_types=[], enum_types=[], options=None, is_extendable=False, extension_ranges=[], serialized_start=39, serialized_end=99)
_RESOURCEKEYLIST = descriptor.Descriptor(name='ResourceKeyList', full_name='EA.Sims4.Network.ResourceKeyList', filename=None, file=DESCRIPTOR, containing_type=None, fields=[descriptor.FieldDescriptor(name='resource_keys', full_name='EA.Sims4.Network.ResourceKeyList.resource_keys', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None)], extensions=[], nested_types=[], enum_types=[], options=None, is_extendable=False, extension_ranges=[], serialized_start=101, serialized_end=172)
_RESOURCEKEYLIST.fields_by_name['resource_keys'].message_type = _RESOURCEKEY
DESCRIPTOR.message_types_by_name['ResourceKey'] = _RESOURCEKEY
DESCRIPTOR.message_types_by_name['ResourceKeyList'] = _RESOURCEKEYLIST
class ResourceKey(message.Message, metaclass=reflection.GeneratedProtocolMessageType):
DESCRIPTOR = _RESOURCEKEY
class ResourceKeyList(message.Message, metaclass=reflection.GeneratedProtocolMessageType):
DESCRIPTOR = _RESOURCEKEYLIST
| 167.058824 | 1,189 | 0.817254 | 384 | 2,840 | 5.838542 | 0.239583 | 0.049955 | 0.049955 | 0.040143 | 0.648082 | 0.604371 | 0.400089 | 0.400089 | 0.400089 | 0.400089 | 0 | 0.038604 | 0.051408 | 2,840 | 16 | 1,190 | 177.5 | 0.793615 | 0 | 0 | 0 | 0 | 0.071429 | 0.221831 | 0.175352 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.285714 | 0 | 0.571429 | 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 | 1 | 0 | 0 | 3 |
d1a8c0ef8c78390a7389441f044f0c0970746917 | 529 | py | Python | src/Python/701-800/744.NextGreatestLetter.py | Peefy/PeefyLeetCode | 92156e4b48ba19e3f02e4286b9f733e9769a1dee | [
"Apache-2.0"
] | 2 | 2018-05-03T07:50:03.000Z | 2018-06-17T04:32:13.000Z | src/Python/701-800/744.NextGreatestLetter.py | Peefy/PeefyLeetCode | 92156e4b48ba19e3f02e4286b9f733e9769a1dee | [
"Apache-2.0"
] | null | null | null | src/Python/701-800/744.NextGreatestLetter.py | Peefy/PeefyLeetCode | 92156e4b48ba19e3f02e4286b9f733e9769a1dee | [
"Apache-2.0"
] | 3 | 2018-11-09T14:18:11.000Z | 2021-11-17T15:23:52.000Z |
class Solution:
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
for l in letters:
if l > target:
return l
return letters[0]
if __name__ == '__main__':
solution = Solution()
print(solution.nextGreatestLetter(["c", "f", "j"], "a"))
print(solution.nextGreatestLetter(["c", "f", "j"], "c"))
print(solution.nextGreatestLetter(["c", "f", "j"], "k"))
else:
pass
| 23 | 60 | 0.529301 | 56 | 529 | 4.857143 | 0.482143 | 0.143382 | 0.341912 | 0.352941 | 0.375 | 0.375 | 0 | 0 | 0 | 0 | 0 | 0.002717 | 0.304348 | 529 | 22 | 61 | 24.045455 | 0.736413 | 0.102079 | 0 | 0 | 0 | 0 | 0.046189 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0.076923 | 0 | 0 | 0.307692 | 0.230769 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 3 |
d1ac6a90c4729800926b6568f7d2006371d58651 | 540 | py | Python | it/versions/structures/default/python/bar/v2_1.py | nezdolik/reproto | 2d69d8efca518a6ea23a4182b29872fcc62a1a71 | [
"Apache-2.0",
"MIT"
] | null | null | null | it/versions/structures/default/python/bar/v2_1.py | nezdolik/reproto | 2d69d8efca518a6ea23a4182b29872fcc62a1a71 | [
"Apache-2.0",
"MIT"
] | null | null | null | it/versions/structures/default/python/bar/v2_1.py | nezdolik/reproto | 2d69d8efca518a6ea23a4182b29872fcc62a1a71 | [
"Apache-2.0",
"MIT"
] | null | null | null | class Other:
def __init__(self, name21):
self.name21 = name21
def get_name21(self):
return self.name21
@staticmethod
def decode(data):
f_name21 = data["name21"]
if not isinstance(f_name21, unicode):
raise Exception("not a string")
return Other(f_name21)
def encode(self):
data = dict()
if self.name21 is None:
raise Exception("name21: is a required field")
data["name21"] = self.name21
return data
def __repr__(self):
return "<Other name21:{!r}>".format(self.name21)
| 18.62069 | 52 | 0.648148 | 72 | 540 | 4.694444 | 0.402778 | 0.177515 | 0.094675 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.072464 | 0.233333 | 540 | 28 | 53 | 19.285714 | 0.743961 | 0 | 0 | 0 | 0 | 0 | 0.12963 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.263158 | false | 0 | 0 | 0.105263 | 0.526316 | 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 | 1 | 0 | 0 | 3 |
d1e1409d73a3d66b1d9667d3a5d80cc9f1d444f5 | 1,915 | py | Python | modele/Case.py | JordanSamhi/BricksBreaker | e2efb28e5ec43056e9665479920523576c692a6b | [
"MIT"
] | null | null | null | modele/Case.py | JordanSamhi/BricksBreaker | e2efb28e5ec43056e9665479920523576c692a6b | [
"MIT"
] | null | null | null | modele/Case.py | JordanSamhi/BricksBreaker | e2efb28e5ec43056e9665479920523576c692a6b | [
"MIT"
] | null | null | null | '''
Une case est definie par sa couleur,
ses coordonnees et un acces a la grille
pour recuperer ses voisins
'''
class Case():
def __init__(self, x, y, couleur, grille):
self._x = x
self._y = y
self._couleur = couleur
self._grille = grille
self.GREY = "grey"
def getCouleur(self):
return self._couleur
def getCouleurOriginale(self):
if self._couleur[-1] == "3":
return self._couleur[:-1]+"2"
return self._couleur
def getX(self):
return self._x
def getY(self):
return self._y
def setX(self, x):
self._x = x
def setY(self, y):
self._y = y
def setCouleur(self, couleur):
self._couleur = couleur
def getNord(self):
if self.getY() > 0:
return self._grille[self._y-1][self._x]
return None
def getSud(self):
if self.getY() < len(self._grille) - 1:
return self._grille[self._y+1][self._x]
return None
def getEst(self):
if self.getX() < len(self._grille) - 1:
return self._grille[self._y][self._x+1]
return None
def getOuest(self):
if self.getX() > 0:
return self._grille[self._y][self._x-1]
return None
def getVoisins(self):
return [self.getNord(), self.getSud(), self.getEst(), self.getOuest()]
def getGrille(self):
return self._grille
def surbrillance(self):
self._couleur = self._couleur[:-1] + "2"
def couleurParDefaut(self):
self._couleur = self._couleur[:-1] + "3"
def detruire(self):
self.setCouleur(self.GREY)
def estDetruite(self):
return self._couleur == self.GREY | 26.232877 | 79 | 0.515927 | 223 | 1,915 | 4.264574 | 0.224215 | 0.138801 | 0.088328 | 0.084122 | 0.256572 | 0.256572 | 0.197687 | 0.197687 | 0.197687 | 0.168244 | 0 | 0.013289 | 0.371279 | 1,915 | 73 | 80 | 26.232877 | 0.776578 | 0.053786 | 0 | 0.235294 | 0 | 0 | 0.004648 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.352941 | false | 0 | 0 | 0.117647 | 0.686275 | 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 | 1 | 0 | 0 | 3 |
d1e30a27cb089668fb5805462b206c1f85c6621d | 2,900 | py | Python | tests/test_markdown.py | tripleee/ChatExchange | 5509c7ec1efd5b55d4051d6966bcae7d72e84620 | [
"Apache-2.0",
"MIT"
] | 64 | 2015-02-26T02:56:57.000Z | 2021-11-07T20:40:11.000Z | tests/test_markdown.py | tripleee/ChatExchange | 5509c7ec1efd5b55d4051d6966bcae7d72e84620 | [
"Apache-2.0",
"MIT"
] | 53 | 2015-01-29T03:37:23.000Z | 2021-08-15T11:09:05.000Z | tests/test_markdown.py | tripleee/ChatExchange | 5509c7ec1efd5b55d4051d6966bcae7d72e84620 | [
"Apache-2.0",
"MIT"
] | 39 | 2015-02-11T16:37:40.000Z | 2021-01-12T18:53:40.000Z | import sys
import logging
if sys.version_info[:2] <= (2, 6):
logging.Logger.getChild = lambda self, suffix:\
self.manager.getLogger('.'.join((self.name, suffix)) if self.root is not self else suffix)
import pytest
from chatexchange.markdown_detector import markdown
logger = logging.getLogger(__name__)
def test_markdown():
assert markdown('no markdown here') is None
assert markdown(' code formatting') is not None
assert markdown('hello `code` here') is not None
assert markdown('bare url https://example.com/link gets linked') is not None
assert markdown('[hello](http://example.com/hello)') is not None
assert markdown('adjacent[hello](http://example.com/hello)text') is not None
assert markdown('adjacent.[hello](https://example.com/hello).x') is not None
assert markdown('[ftp](ftp://example.com/link) works too') is not None
assert markdown('text with *italics*') is not None
assert markdown('and **bold** too') is not None
assert markdown('*not italics') is None
assert markdown('**not bold either') is None
assert markdown('***not both neither too also as well') is None
assert markdown('****not bold or italic') is None
# Odd corner cases: many backticks
assert markdown('two ``backticks`` code') is not None
assert markdown('unpaired `single double`` fail') is None
assert markdown('unpaired `single triple``` fail') is None
# Weirdly, 'unpaired ``double triple```' gets rendered as
# 'unpaired <code>double triple</code>`'
#assert markdown('unpaired ``double triple``` fail') is not None
assert markdown('``````````````````18 ticks``````````````````') is not None
# Odd corner cases: broken links
assert markdown(
'[](http://example.com/link) gets linked inside parens') is not None
assert markdown('[no link]() is not linked') is None
assert markdown('[mailto is not linked](mailto:self@example.com)') is None
assert markdown('[sftp](sftp://example.com/link) is not linked') is None
assert markdown('[ftps](ftps://example.com/link) is not linked') is None
assert markdown(
'[https://example.com/no-link]() link in square brackets') is not None
assert markdown(
'empty anchor, link in parens [](https://example.com/)') is not None
# Odd corner cases: mixed bold and italics
assert markdown('this is ***bold italics***') is not None
assert markdown('this is **bold and *italics* too**') is not None
assert markdown(
'this is *italics and **bold** and **more** too*') is not None
# Odd corner cases: broken bold or italics
assert markdown('**unpaired neither*') is None
assert markdown('*unpaired nor**') is None
assert markdown('***unpaired** in the end') is None
# chat actually briefly formats as bold italics, then reverts
#assert markdown('****this is weird****') is None
| 48.333333 | 98 | 0.671724 | 406 | 2,900 | 4.780788 | 0.251232 | 0.238022 | 0.241113 | 0.11592 | 0.472437 | 0.277177 | 0.161257 | 0.0644 | 0.046368 | 0.046368 | 0 | 0.002118 | 0.185862 | 2,900 | 59 | 99 | 49.152542 | 0.819992 | 0.141724 | 0 | 0.090909 | 0 | 0 | 0.402178 | 0.058895 | 0 | 0 | 0 | 0 | 0.704545 | 1 | 0.022727 | false | 0 | 0.090909 | 0 | 0.113636 | 0 | 0 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
d1e35468812dfeba245515055cc9981eeb5b168b | 313 | py | Python | test.py | QBitor/Neuromorphic_AE_Tools | b20f5f931e82888dfc4eebd7b19b2746d142d4bb | [
"MIT"
] | 4 | 2019-02-19T14:19:14.000Z | 2019-07-29T02:46:47.000Z | test.py | ndouard/Neuromorphic_AE_Tools | b20f5f931e82888dfc4eebd7b19b2746d142d4bb | [
"MIT"
] | null | null | null | test.py | ndouard/Neuromorphic_AE_Tools | b20f5f931e82888dfc4eebd7b19b2746d142d4bb | [
"MIT"
] | 2 | 2018-03-05T22:52:53.000Z | 2018-09-13T21:47:00.000Z | x_indexes = [i for i, j in enumerate(xaddr)] if j == myxaddr]
y_indexes = [i for i, j in enumerate(yaddr)] if j == myyaddr]
print('x_indexes: ' + str(x_indexes))
print('y_indexes:' +str(y_indexes))
# keep common indexes
common = [i for i, j in zip(x_indexes, y_indexes) if i == j]
print('common: ' + str(common))
| 39.125 | 61 | 0.670927 | 57 | 313 | 3.54386 | 0.315789 | 0.158416 | 0.074257 | 0.089109 | 0.277228 | 0.237624 | 0.237624 | 0 | 0 | 0 | 0 | 0 | 0.162939 | 313 | 7 | 62 | 44.714286 | 0.770992 | 0 | 0 | 0 | 0 | 0 | 0.099315 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.5 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 3 |
061412d3ce5243bc277fe70e0a5760f272906364 | 233 | py | Python | Django/env_python3.6.1/Lib/site-packages/setupfiles/__init__.py | archu2020/python-2 | 19c626ca9fd37168db8a7ac075fd80c8e2971313 | [
"Apache-2.0"
] | 48 | 2017-12-24T12:19:55.000Z | 2022-02-26T13:14:27.000Z | Django/env_python3.6.1/Lib/site-packages/setupfiles/__init__.py | 17610178081/python | 3975c678d985c468deecd03560d882e9d316bb63 | [
"Apache-2.0"
] | 6 | 2017-11-10T19:45:18.000Z | 2017-11-12T14:50:42.000Z | Django/env_python3.6.1/Lib/site-packages/setupfiles/__init__.py | 17610178081/python | 3975c678d985c468deecd03560d882e9d316bb63 | [
"Apache-2.0"
] | 113 | 2017-08-09T03:10:04.000Z | 2022-03-26T16:05:01.000Z | #!/usr/bin/env python
import distutils
from setupfiles.dist import DistributionMetadata
from setupfiles.setup import setup
__all__ = ["setup"]
distutils.dist.DistributionMetadata = DistributionMetadata
distutils.core.setup = setup
| 23.3 | 58 | 0.824034 | 26 | 233 | 7.230769 | 0.5 | 0.148936 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.098712 | 233 | 9 | 59 | 25.888889 | 0.895238 | 0.085837 | 0 | 0 | 0 | 0 | 0.023585 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 3 |
ae06e563dacfb2f601bc91857ad8c0255bdbcc8b | 1,292 | py | Python | env/Lib/site-packages/OpenGL/GLES2/EXT/sRGB_write_control.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 210 | 2016-04-09T14:26:00.000Z | 2022-03-25T18:36:19.000Z | env/Lib/site-packages/OpenGL/GLES2/EXT/sRGB_write_control.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 72 | 2016-09-04T09:30:19.000Z | 2022-03-27T17:06:53.000Z | env/Lib/site-packages/OpenGL/GLES2/EXT/sRGB_write_control.py | 5gconnectedbike/Navio2 | 8c3f2b5d8bbbcea1fc08739945183c12b206712c | [
"BSD-3-Clause"
] | 64 | 2016-04-09T14:26:49.000Z | 2022-03-21T11:19:47.000Z | '''OpenGL extension EXT.sRGB_write_control
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.sRGB_write_control to provide a more
Python-friendly API
Overview (from the spec)
This extension's intent is to expose new functionality which allows an
application the ability to decide if the conversion from linear space to
sRGB is necessary by enabling or disabling this conversion at framebuffer
write or blending time. An application which passes non-linear vector data
to a shader may not want the color conversion occurring, and by disabling
conversion the application can be simplified, sometimes in very significant
and more optimal ways.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/EXT/sRGB_write_control.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GLES2 import _types, _glgets
from OpenGL.raw.GLES2.EXT.sRGB_write_control import *
from OpenGL.raw.GLES2.EXT.sRGB_write_control import _EXTENSION_NAME
def glInitSrgbWriteControlEXT():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION | 39.151515 | 76 | 0.813467 | 187 | 1,292 | 5.534759 | 0.529412 | 0.057971 | 0.057971 | 0.091787 | 0.114976 | 0.114976 | 0.114976 | 0.083092 | 0.083092 | 0 | 0 | 0.003597 | 0.139319 | 1,292 | 33 | 77 | 39.151515 | 0.927158 | 0.724458 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | true | 0 | 0.777778 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
ae07a130b3eed404ad6c84e0c2e825a8a33c151b | 595 | bzl | Python | source/bazel/deps/osdialog/get.bzl | luxe/unilang | 6c8a431bf61755f4f0534c6299bd13aaeba4b69e | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/bazel/deps/osdialog/get.bzl | luxe/unilang | 6c8a431bf61755f4f0534c6299bd13aaeba4b69e | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/bazel/deps/osdialog/get.bzl | luxe/unilang | 6c8a431bf61755f4f0534c6299bd13aaeba4b69e | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | # Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def osdialog():
http_archive(
name="osdialog" ,
build_file="//bazel/deps/osdialog:build.BUILD" ,
sha256="3fc6dabcf1fcfdca5fd87f2474a113e17212da4211b3fa3deecd263a6a59dc26" ,
strip_prefix="osdialog-a3ca84070c620b186f475ea17b86e65efab5ce57" ,
urls = [
"https://github.com/Unilang/osdialog/archive/a3ca84070c620b186f475ea17b86e65efab5ce57.tar.gz",
],
)
| 35 | 106 | 0.714286 | 56 | 595 | 7.464286 | 0.732143 | 0.052632 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.168699 | 0.173109 | 595 | 16 | 107 | 37.1875 | 0.680894 | 0.169748 | 0 | 0 | 1 | 0 | 0.613035 | 0.386965 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | true | 0 | 0 | 0 | 0.090909 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
ae1dba2c9332b1aaf3dca98391c5242cc59d4eab | 322 | py | Python | jd/api/rest/ComJdQlBasicWsGlscGlscBasicSecondaryWSGetAssortByFidRequest.py | jof2jc/jd | 691bf22c68ed88fb3fb32bfb43dd6da75024994a | [
"MIT"
] | null | null | null | jd/api/rest/ComJdQlBasicWsGlscGlscBasicSecondaryWSGetAssortByFidRequest.py | jof2jc/jd | 691bf22c68ed88fb3fb32bfb43dd6da75024994a | [
"MIT"
] | null | null | null | jd/api/rest/ComJdQlBasicWsGlscGlscBasicSecondaryWSGetAssortByFidRequest.py | jof2jc/jd | 691bf22c68ed88fb3fb32bfb43dd6da75024994a | [
"MIT"
] | null | null | null | from jd.api.base import RestApi
class ComJdQlBasicWsGlscGlscBasicSecondaryWSGetAssortByFidRequest(RestApi):
def __init__(self,domain,port=80):
RestApi.__init__(self,domain, port)
self.assFid = None
def getapiname(self):
return 'jingdong.com.jd.ql.basic.ws.glsc.GlscBasicSecondaryWS.getAssortByFid'
| 20.125 | 80 | 0.776398 | 36 | 322 | 6.722222 | 0.722222 | 0.066116 | 0.115702 | 0.14876 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007117 | 0.127329 | 322 | 15 | 81 | 21.466667 | 0.854093 | 0 | 0 | 0 | 0 | 0 | 0.213836 | 0.213836 | 0 | 0 | 0 | 0 | 0 | 1 | 0.285714 | false | 0 | 0.142857 | 0.142857 | 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 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 3 |
ae209fc837cb7fa92d358e927f5a60ae96f43be3 | 682 | py | Python | tensorflow_gnn/tools/generate_training_data_test.py | mattdangerw/gnn | f39d3ea0d8fc6e51cf58814873fc1502c12554ae | [
"Apache-2.0"
] | 611 | 2021-11-18T06:04:10.000Z | 2022-03-29T11:46:42.000Z | tensorflow_gnn/tools/generate_training_data_test.py | mattdangerw/gnn | f39d3ea0d8fc6e51cf58814873fc1502c12554ae | [
"Apache-2.0"
] | 25 | 2021-11-18T17:21:12.000Z | 2022-03-31T06:36:55.000Z | tensorflow_gnn/tools/generate_training_data_test.py | mattdangerw/gnn | f39d3ea0d8fc6e51cf58814873fc1502c12554ae | [
"Apache-2.0"
] | 52 | 2021-11-18T23:12:30.000Z | 2022-03-27T06:31:08.000Z | """Unit tests for generate training data test."""
from os import path
from absl import flags
import tensorflow as tf
from tensorflow_gnn.tools import generate_training_data
from tensorflow_gnn.utils import test_utils
FLAGS = flags.FLAGS
class GenerateDataTest(tf.test.TestCase):
def test_generate_training_data(self):
schema_filename = test_utils.get_resource("examples/schemas/mpnn.pbtxt")
output_filename = path.join(FLAGS.test_tmpdir, "examples.tfrecords")
generate_training_data.generate_training_data(
schema_filename, output_filename, "tfrecord", 64)
self.assertTrue(path.exists(output_filename))
if __name__ == "__main__":
tf.test.main()
| 26.230769 | 76 | 0.781525 | 91 | 682 | 5.549451 | 0.472527 | 0.158416 | 0.19802 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003373 | 0.130499 | 682 | 25 | 77 | 27.28 | 0.848229 | 0.06305 | 0 | 0 | 1 | 0 | 0.096367 | 0.042654 | 0 | 0 | 0 | 0 | 0.066667 | 1 | 0.066667 | false | 0 | 0.333333 | 0 | 0.466667 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 3 |
ae21fa093e46f99cba061fc2247a9c451b1f519b | 218 | py | Python | FullContact/utils.py | KamalAwasthi/FullContact | fa2e9f29079064b015848d980ddbb8da51f323c9 | [
"Apache-2.0"
] | 2 | 2018-05-31T16:21:06.000Z | 2019-11-28T11:58:12.000Z | FullContact/utils.py | KamalAwasthi/FullContact | fa2e9f29079064b015848d980ddbb8da51f323c9 | [
"Apache-2.0"
] | null | null | null | FullContact/utils.py | KamalAwasthi/FullContact | fa2e9f29079064b015848d980ddbb8da51f323c9 | [
"Apache-2.0"
] | 2 | 2018-02-12T16:37:08.000Z | 2019-11-28T11:58:24.000Z | import requests
def getContacts(email):
payload = {'email': email}
r = requests.get('https://api.fullcontact.com/v2/person.json', params=payload, headers={"X-FullContact-APIKey": "841831f8eef0a46f"})
return r.text
| 31.142857 | 133 | 0.738532 | 28 | 218 | 5.75 | 0.785714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.055556 | 0.091743 | 218 | 6 | 134 | 36.333333 | 0.757576 | 0 | 0 | 0 | 0 | 0 | 0.380734 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.2 | 0 | 0.6 | 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 | 1 | 0 | 0 | 3 |
ae340b92aadfe682e4f7ba5a3b3a05872dd322d2 | 192 | py | Python | pyravendb/data/counters.py | CDuPlooy/ravendb-python-client | dbe51ee8eea166e0d9e60897ab480dd9a693366b | [
"MIT"
] | 19 | 2019-02-16T14:39:38.000Z | 2022-03-23T12:27:00.000Z | pyravendb/data/counters.py | CDuPlooy/ravendb-python-client | dbe51ee8eea166e0d9e60897ab480dd9a693366b | [
"MIT"
] | 24 | 2018-10-21T07:31:21.000Z | 2022-03-27T17:27:29.000Z | pyravendb/data/counters.py | CDuPlooy/ravendb-python-client | dbe51ee8eea166e0d9e60897ab480dd9a693366b | [
"MIT"
] | 14 | 2018-08-14T07:58:46.000Z | 2022-01-05T12:20:08.000Z | from enum import Enum
class CounterOperationType(Enum):
none = "None"
increment = "Increment"
delete = "Delete"
get = "Get"
def __str__(self):
return self.value
| 16 | 33 | 0.625 | 21 | 192 | 5.52381 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.276042 | 192 | 11 | 34 | 17.454545 | 0.834532 | 0 | 0 | 0 | 0 | 0 | 0.114583 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.125 | 0.125 | 1 | 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 | 0 | 1 | 1 | 0 | 0 | 3 |
ae3c1e0a31bb35705167a39456828a45fbe7fc2b | 157 | py | Python | lessons/Test_and_function_programming_in_Python/project/tests/test_sum_benchmark.py | johnklee/oo_dp_lesson | 06814a88b86b38435e0ed8f305ce9e50c1aac1f6 | [
"MIT"
] | null | null | null | lessons/Test_and_function_programming_in_Python/project/tests/test_sum_benchmark.py | johnklee/oo_dp_lesson | 06814a88b86b38435e0ed8f305ce9e50c1aac1f6 | [
"MIT"
] | 7 | 2021-06-07T03:52:37.000Z | 2022-03-14T11:07:31.000Z | lessons/Test_and_function_programming_in_Python/project/tests/test_sum_benchmark.py | johnklee/oo_dp_lesson | 06814a88b86b38435e0ed8f305ce9e50c1aac1f6 | [
"MIT"
] | null | null | null | from my_sum import sum
def test_sum_benchmark(benchmark):
hundred_one_list = [1] * 100
result = benchmark(sum, hundred_one_list)
assert result == 100
| 22.428571 | 43 | 0.751592 | 24 | 157 | 4.625 | 0.583333 | 0.18018 | 0.252252 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.053435 | 0.165605 | 157 | 6 | 44 | 26.166667 | 0.793893 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0.2 | false | 0 | 0.2 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 0 | 1 | 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 | 3 |
ae581ce55f5c70d548f9c9c2e1e5bda4e73bac54 | 11,401 | py | Python | segmentron/utils/visualize.py | GhadeerElmkaiel/Trans2Seg | 6717db602205cbed494ae1913ac7cbbca8e83463 | [
"Apache-2.0"
] | null | null | null | segmentron/utils/visualize.py | GhadeerElmkaiel/Trans2Seg | 6717db602205cbed494ae1913ac7cbbca8e83463 | [
"Apache-2.0"
] | null | null | null | segmentron/utils/visualize.py | GhadeerElmkaiel/Trans2Seg | 6717db602205cbed494ae1913ac7cbbca8e83463 | [
"Apache-2.0"
] | null | null | null | import os
import logging
import numpy as np
import torch
from PIL import Image
#from torchsummary import summary
from thop import profile
__all__ = ['get_color_pallete', 'print_iou', 'set_img_color',
'show_prediction', 'show_colorful_images', 'save_colorful_images']
def print_iou(iu, mean_pixel_acc, class_names=None, show_no_back=False):
n = iu.size
lines = []
for i in range(n):
if class_names is None:
cls = 'Class %d:' % (i + 1)
else:
cls = '%d %s' % (i + 1, class_names[i])
# lines.append('%-8s: %.3f%%' % (cls, iu[i] * 100))
mean_IU = np.nanmean(iu)
mean_IU_no_back = np.nanmean(iu[1:])
if show_no_back:
lines.append('mean_IU: %.3f%% || mean_IU_no_back: %.3f%% || mean_pixel_acc: %.3f%%' % (
mean_IU * 100, mean_IU_no_back * 100, mean_pixel_acc * 100))
else:
lines.append('mean_IU: %.3f%% || mean_pixel_acc: %.3f%%' % (mean_IU * 100, mean_pixel_acc * 100))
lines.append('=================================================')
line = "\n".join(lines)
print(line)
@torch.no_grad()
def show_flops_params(model, device, input_shape=[1, 3, 512, 512]):
#summary(model, tuple(input_shape[1:]), device=device)
input = torch.randn(*input_shape).to(torch.device(device))
flops, params = profile(model, inputs=(input,), verbose=False)
logging.info('{} flops: {:.3f}G input shape is {}, params: {:.3f}M'.format(
model.__class__.__name__, flops / 1000000000, input_shape[1:], params / 1000000))
def set_img_color(img, label, colors, background=0, show255=False):
for i in range(len(colors)):
if i != background:
img[np.where(label == i)] = colors[i]
if show255:
img[np.where(label == 255)] = 255
return img
def show_prediction(img, pred, colors, background=0):
im = np.array(img, np.uint8)
set_img_color(im, pred, colors, background)
out = np.array(im)
return out
def show_colorful_images(prediction, palettes):
im = Image.fromarray(palettes[prediction.astype('uint8').squeeze()])
im.show()
def save_colorful_images(prediction, filename, output_dir, palettes):
'''
:param prediction: [B, H, W, C]
'''
im = Image.fromarray(palettes[prediction.astype('uint8').squeeze()])
fn = os.path.join(output_dir, filename)
out_dir = os.path.split(fn)[0]
if not os.path.exists(out_dir):
os.mkdir(out_dir)
im.save(fn)
def get_color_pallete(npimg, dataset='cityscape'):
"""Visualize image.
Parameters
----------
npimg : numpy.ndarray
Single channel image with shape `H, W, 1`.
dataset : str, default: 'pascal_voc'
The dataset that model pretrained on. ('pascal_voc', 'ade20k')
Returns
-------
out_img : PIL.Image
Image with color pallete
"""
# recovery boundary
if dataset in ('pascal_voc', 'pascal_aug'):
npimg[npimg == -1] = 255
# put colormap
if dataset == 'ade20k':
npimg = npimg + 1
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(adepallete)
return out_img
elif dataset == 'cityscape':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(cityscapepallete)
return out_img
elif dataset == 'trans10kv2' or dataset == 'transparent11':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(trans10kv2pallete)
return out_img
elif dataset == 'pascal_voc':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(vocpallete)
return out_img
elif dataset == 'sber_dataset':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(sberpallete)
return out_img
elif dataset == 'sber_dataset_all':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(sberallpallete)
return out_img
elif dataset == 'sber_dataset_all_no_fu':
out_img = Image.fromarray(npimg.astype('uint8'))
out_img.putpalette(sberallNoFUpallete)
return out_img
def _getvocpallete(num_cls):
n = num_cls
pallete = [0] * (n * 3)
for j in range(0, n):
lab = j
pallete[j * 3 + 0] = 0
pallete[j * 3 + 1] = 0
pallete[j * 3 + 2] = 0
i = 0
while (lab > 0):
pallete[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
pallete[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
pallete[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
i = i + 1
lab >>= 3
return pallete
vocpallete = _getvocpallete(256)
adepallete = [
0, 0, 0, 120, 120, 120, 180, 120, 120, 6, 230, 230, 80, 50, 50, 4, 200, 3, 120, 120, 80, 140, 140, 140, 204,
5, 255, 230, 230, 230, 4, 250, 7, 224, 5, 255, 235, 255, 7, 150, 5, 61, 120, 120, 70, 8, 255, 51, 255, 6, 82,
143, 255, 140, 204, 255, 4, 255, 51, 7, 204, 70, 3, 0, 102, 200, 61, 230, 250, 255, 6, 51, 11, 102, 255, 255,
7, 71, 255, 9, 224, 9, 7, 230, 220, 220, 220, 255, 9, 92, 112, 9, 255, 8, 255, 214, 7, 255, 224, 255, 184, 6,
10, 255, 71, 255, 41, 10, 7, 255, 255, 224, 255, 8, 102, 8, 255, 255, 61, 6, 255, 194, 7, 255, 122, 8, 0, 255,
20, 255, 8, 41, 255, 5, 153, 6, 51, 255, 235, 12, 255, 160, 150, 20, 0, 163, 255, 140, 140, 140, 250, 10, 15,
20, 255, 0, 31, 255, 0, 255, 31, 0, 255, 224, 0, 153, 255, 0, 0, 0, 255, 255, 71, 0, 0, 235, 255, 0, 173, 255,
31, 0, 255, 11, 200, 200, 255, 82, 0, 0, 255, 245, 0, 61, 255, 0, 255, 112, 0, 255, 133, 255, 0, 0, 255, 163,
0, 255, 102, 0, 194, 255, 0, 0, 143, 255, 51, 255, 0, 0, 82, 255, 0, 255, 41, 0, 255, 173, 10, 0, 255, 173, 255,
0, 0, 255, 153, 255, 92, 0, 255, 0, 255, 255, 0, 245, 255, 0, 102, 255, 173, 0, 255, 0, 20, 255, 184, 184, 0,
31, 255, 0, 255, 61, 0, 71, 255, 255, 0, 204, 0, 255, 194, 0, 255, 82, 0, 10, 255, 0, 112, 255, 51, 0, 255, 0,
194, 255, 0, 122, 255, 0, 255, 163, 255, 153, 0, 0, 255, 10, 255, 112, 0, 143, 255, 0, 82, 0, 255, 163, 255,
0, 255, 235, 0, 8, 184, 170, 133, 0, 255, 0, 255, 92, 184, 0, 255, 255, 0, 31, 0, 184, 255, 0, 214, 255, 255,
0, 112, 92, 255, 0, 0, 224, 255, 112, 224, 255, 70, 184, 160, 163, 0, 255, 153, 0, 255, 71, 255, 0, 255, 0,
163, 255, 204, 0, 255, 0, 143, 0, 255, 235, 133, 255, 0, 255, 0, 235, 245, 0, 255, 255, 0, 122, 255, 245, 0,
10, 190, 212, 214, 255, 0, 0, 204, 255, 20, 0, 255, 255, 255, 0, 0, 153, 255, 0, 41, 255, 0, 255, 204, 41, 0,
255, 41, 255, 0, 173, 0, 255, 0, 245, 255, 71, 0, 255, 122, 0, 255, 0, 255, 184, 0, 92, 255, 184, 255, 0, 0,
133, 255, 255, 214, 0, 25, 194, 194, 102, 255, 0, 92, 0, 255]
cityscapepallete = [
128, 64, 128,
244, 35, 232,
70, 70, 70,
102, 102, 156,
190, 153, 153,
153, 153, 153,
250, 170, 30,
220, 220, 0,
107, 142, 35,
152, 251, 152,
0, 130, 180,
220, 20, 60,
255, 0, 0,
0, 0, 142,
0, 0, 70,
0, 60, 100,
0, 80, 100,
0, 0, 230,
119, 11, 32,
]
trans10kv2pallete = [
0, 0, 0,
120, 120, 70,
235, 255, 7,
6, 230, 230,
204, 255, 4,
120, 120, 120,
140, 140, 140,
255, 51, 7,
224, 5, 255,
204, 5, 255,
150, 5, 61,
4, 250, 7]
sberpallete = [
255, 255, 255,
255, 0, 0,
0, 0, 0,
]
# sberallpallete = [
# 102, 255, 102, # Mirror
# 51, 221, 255, # Glass
# 245, 147, 49, # FU
# 184, 61, 245, # Other Optical Surface
# 250, 50, 83, # Floor
# 0, 0, 0,
# ]
sberallNoFUpallete = [
102, 255, 102, # Mirror
51, 221, 255, # Glass
# 245, 147, 49, # FU
250, 50, 83, # Floor
184, 61, 245, # Other Optical Surface
0, 0, 0,
]
sberallpallete = [
102, 255, 102, # Mirror
51, 221, 255, # Glass
245, 147, 49, # FU
184, 61, 245, # Other Optical Surface
250, 50, 83, # Floor
0, 0, 0,
6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47, 47, 48, 48, 48, 49, 49, 49, 50, 50, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 69, 69, 69, 70, 70, 70, 71, 71, 71, 72, 72, 72, 73, 73, 73, 74, 74, 74, 75, 75, 75, 76, 76, 76, 77, 77, 77, 78, 78, 78, 79, 79, 79, 80, 80, 80, 81, 81, 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 85, 85, 85, 86, 86, 86, 87, 87, 87, 88, 88, 88, 89, 89, 89, 90, 90, 90, 91, 91, 91, 92, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 116, 116, 116, 117, 117, 117, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 122, 122, 122, 123, 123, 123, 124, 124, 124, 125, 125, 125, 126, 126, 126, 127, 127, 127, 128, 128, 128, 129, 129, 129, 130, 130, 130, 131, 131, 131, 132, 132, 132, 133, 133, 133, 134, 134, 134, 135, 135, 135, 136, 136, 136, 137, 137, 137, 138, 138, 138, 139, 139, 139, 140, 140, 140, 141, 141, 141, 142, 142, 142, 143, 143, 143, 144, 144, 144, 145, 145, 145, 146, 146, 146, 147, 147, 147, 148, 148, 148, 149, 149, 149, 150, 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 154, 154, 154, 155, 155, 155, 156, 156, 156, 157, 157, 157, 158, 158, 158, 159, 159, 159, 160, 160, 160, 161, 161, 161, 162, 162, 162, 163, 163, 163, 164, 164, 164, 165, 165, 165, 166, 166, 166, 167, 167, 167, 168, 168, 168, 169, 169, 169, 170, 170, 170, 171, 171, 171, 172, 172, 172, 173, 173, 173, 174, 174, 174, 175, 175, 175, 176, 176, 176, 177, 177, 177, 178, 178, 178, 179, 179, 179, 180, 180, 180, 181, 181, 181, 182, 182, 182, 183, 183, 183, 184, 184, 184, 185, 185, 185, 186, 186, 186, 187, 187, 187, 188, 188, 188, 189, 189, 189, 190, 190, 190, 191, 191, 191, 192, 192, 192, 193, 193, 193, 194, 194, 194, 195, 195, 195, 196, 196, 196, 197, 197, 197, 198, 198, 198, 199, 199, 199, 200, 200, 200, 201, 201, 201, 202, 202, 202, 203, 203, 203, 204, 204, 204, 205, 205, 205, 206, 206, 206, 207, 207, 207, 208, 208, 208, 209, 209, 209, 210, 210, 210, 211, 211, 211, 212, 212, 212, 213, 213, 213, 214, 214, 214, 215, 215, 215, 216, 216, 216, 217, 217, 217, 218, 218, 218, 219, 219, 219, 220, 220, 220, 221, 221, 221, 222, 222, 222, 223, 223, 223, 224, 224, 224, 225, 225, 225, 226, 226, 226, 227, 227, 227, 228, 228, 228, 229, 229, 229, 230, 230, 230, 231, 231, 231, 232, 232, 232, 233, 233, 233, 234, 234, 234, 235, 235, 235, 236, 236, 236, 237, 237, 237, 238, 238, 238, 239, 239, 239, 240, 240, 240, 241, 241, 241, 242, 242, 242, 243, 243, 243, 244, 244, 244, 245, 245, 245, 246, 246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 250, 250, 250, 251, 251, 251, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255] | 46.534694 | 3,459 | 0.556179 | 2,005 | 11,401 | 3.105237 | 0.205985 | 0.028269 | 0.013492 | 0.022486 | 0.180212 | 0.15371 | 0.139094 | 0.133633 | 0.105043 | 0.095728 | 0 | 0.410841 | 0.257258 | 11,401 | 245 | 3,459 | 46.534694 | 0.324398 | 0.067363 | 0 | 0.181818 | 0 | 0 | 0.046679 | 0.006736 | 0 | 0 | 0 | 0 | 0 | 1 | 0.045455 | false | 0 | 0.034091 | 0 | 0.136364 | 0.017045 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
ae5c773b88cd0f9d9fbee09e572ef2fc27d6c119 | 40 | py | Python | smileyjoe_io/constant.py | SmileyJoe/smileyjoe_io | 29e3b55e33f17f799f59801158499809fcce0af4 | [
"MIT"
] | null | null | null | smileyjoe_io/constant.py | SmileyJoe/smileyjoe_io | 29e3b55e33f17f799f59801158499809fcce0af4 | [
"MIT"
] | 2 | 2020-02-11T23:34:28.000Z | 2020-06-05T17:33:09.000Z | smileyjoe_io/constant.py | SmileyJoe/smileyjoe_io | 29e3b55e33f17f799f59801158499809fcce0af4 | [
"MIT"
] | null | null | null | SUB_SECRET = 'secret'
SUB_MAIN = 'main'
| 13.333333 | 21 | 0.7 | 6 | 40 | 4.333333 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.15 | 40 | 2 | 22 | 20 | 0.764706 | 0 | 0 | 0 | 0 | 0 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
ae5e90efc8111cc99c18543d5afea38d02da46b8 | 125 | py | Python | crawlerhttp/http_header_generator.py | mcmin001/NBCrawler | ec6a348e32889fb9252651b203a725a39b6836ec | [
"Apache-2.0"
] | null | null | null | crawlerhttp/http_header_generator.py | mcmin001/NBCrawler | ec6a348e32889fb9252651b203a725a39b6836ec | [
"Apache-2.0"
] | null | null | null | crawlerhttp/http_header_generator.py | mcmin001/NBCrawler | ec6a348e32889fb9252651b203a725a39b6836ec | [
"Apache-2.0"
] | null | null | null | def get_http_header(user_agent):
# 字典数据类型 dict
headers = {
'user-agent': user_agent
}
return headers
| 17.857143 | 32 | 0.616 | 15 | 125 | 4.866667 | 0.666667 | 0.369863 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.296 | 125 | 6 | 33 | 20.833333 | 0.829545 | 0.088 | 0 | 0 | 0 | 0 | 0.089286 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 1 | 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 | 3 |
ae6311f1dc6cb97bf176a5a088a3d0aac371ae07 | 176 | py | Python | src/radixlib/constants.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 32 | 2022-01-12T16:52:28.000Z | 2022-03-24T18:05:47.000Z | src/radixlib/constants.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 3 | 2022-01-12T17:01:55.000Z | 2022-02-12T15:14:16.000Z | src/radixlib/constants.py | 0xOmarA/RadixLib | 85d75a47d4c4df4c1a319b74857ae2c513933623 | [
"MIT"
] | 1 | 2022-01-21T04:28:07.000Z | 2022-01-21T04:28:07.000Z | from typing import Dict
XRD_RRI: Dict[str, str] = {
"mainnet": "xrd_rr1qy5wfsfh",
"stokenet": "xrd_tr1qyf0x76s",
"betanet": "xrd_br1qy73gwac",
"localnet": ""
} | 22 | 34 | 0.636364 | 19 | 176 | 5.684211 | 0.736842 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.06338 | 0.193182 | 176 | 8 | 35 | 22 | 0.697183 | 0 | 0 | 0 | 0 | 0 | 0.423729 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.142857 | 0 | 0.142857 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
ae738c094d5028bff43bc7f3386c802a9cf32a46 | 95 | py | Python | ginger/scripts/templates/app_templates/app_name/urls.py | vivsh/django-ginger | d293109becc72845a23f2aeb732ed808a7a67d69 | [
"MIT"
] | null | null | null | ginger/scripts/templates/app_templates/app_name/urls.py | vivsh/django-ginger | d293109becc72845a23f2aeb732ed808a7a67d69 | [
"MIT"
] | null | null | null | ginger/scripts/templates/app_templates/app_name/urls.py | vivsh/django-ginger | d293109becc72845a23f2aeb732ed808a7a67d69 | [
"MIT"
] | null | null | null |
from django.conf.urls import url, patterns
from . import views
urlpatterns = patterns("",
)
| 11.875 | 42 | 0.726316 | 12 | 95 | 5.75 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.168421 | 95 | 7 | 43 | 13.571429 | 0.873418 | 0 | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 3 |
ae836b13e8e1a6b59a6fe8580af78a2b08d03bc1 | 1,958 | py | Python | mobula/solvers/LRUpdater.py | wkcn/mobula | 4eec938d6477776f5f2d68bcf41de83fb8da5195 | [
"MIT"
] | 47 | 2017-07-15T02:13:18.000Z | 2022-01-01T09:37:59.000Z | mobula/solvers/LRUpdater.py | wkcn/mobula | 4eec938d6477776f5f2d68bcf41de83fb8da5195 | [
"MIT"
] | 3 | 2018-06-22T13:55:12.000Z | 2020-01-29T01:41:13.000Z | mobula/solvers/LRUpdater.py | wkcn/mobula | 4eec938d6477776f5f2d68bcf41de83fb8da5195 | [
"MIT"
] | 8 | 2017-09-03T12:42:54.000Z | 2020-09-27T03:38:59.000Z | #coding=utf-8
import numpy as np
# TODO: MULTISTEP
LR_POLICY_NUM = 7
class LR_POLICY:
FIXED, STEP, EXP, INV, MULTISTEP, POLY, SIGMOID = range(LR_POLICY_NUM)
class LRUpdater:
def __init__(self, *args, **kwargs):
if "base_lr" in kwargs:
self.base_lr = kwargs["base_lr"]
else:
self.base_lr = kwargs.get("lr", 1.0)
self.gamma = kwargs.get("gamma", None)
self.stepsize = kwargs.get("stepsize", None)
self.power = kwargs.get("power", None)
self.max_iter = kwargs.get("max_iter", None)
self.method = None
self.lr_policy = kwargs.get("lr_policy", LR_POLICY.FIXED)
self.set_policy(self.lr_policy)
def set_policy(self, p):
self.lr_policy = p
self.method = LRUpdater.METHODS[p]
def get_lr(self, iter_num):
return self.method(self, iter_num)
def fixed(self, iter_num):
return self.base_lr
def step(self, iter_num):
# gamma, stepsize
return self.base_lr * np.power(self.gamma, (iter_num // self.stepsize))
def exp(self, iter_num):
# gamma
return self.base_lr * np.power(self.gamma, iter_num)
def inv(self, iter_num):
# gamma, power
return self.base_lr * np.power(1.0 + self.gamma * iter_num, -self.power)
def poly(self, iter_num):
# power, max_iter
return self.base_lr * np.power(1 - iter_num * 1.0 / self.max_iter, self.power)
def sigmoid(self, iter_num):
# gamma, stepsize
return self.base_lr * (1.0 / (1.0 + np.exp(-self.gamma * (iter_num - self.stepsize))))
LRUpdater.METHODS = [None] * LR_POLICY_NUM
LRUpdater.METHODS[LR_POLICY.FIXED] = LRUpdater.fixed
LRUpdater.METHODS[LR_POLICY.STEP] = LRUpdater.step
LRUpdater.METHODS[LR_POLICY.EXP] = LRUpdater.exp
LRUpdater.METHODS[LR_POLICY.INV] = LRUpdater.inv
LRUpdater.METHODS[LR_POLICY.POLY] = LRUpdater.poly
LRUpdater.METHODS[LR_POLICY.SIGMOID] = LRUpdater.sigmoid
| 37.653846 | 94 | 0.650664 | 285 | 1,958 | 4.287719 | 0.157895 | 0.0982 | 0.065466 | 0.07856 | 0.238953 | 0.188216 | 0.155483 | 0.116203 | 0.116203 | 0.06383 | 0 | 0.008541 | 0.222676 | 1,958 | 51 | 95 | 38.392157 | 0.79435 | 0.048519 | 0 | 0 | 0 | 0 | 0.027478 | 0 | 0 | 0 | 0 | 0.019608 | 0 | 1 | 0.219512 | false | 0 | 0.02439 | 0.170732 | 0.463415 | 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 | 1 | 0 | 0 | 0 | 3 |
ae874a5f5cca2dcc55151c5b0e06fba1846032d7 | 250 | py | Python | urdubiometer/scanner/__init__.py | urdubiometer/urdubiometer | 034c1efc0403352caa9c5c944cf9450b8833bb24 | [
"BSD-3-Clause"
] | null | null | null | urdubiometer/scanner/__init__.py | urdubiometer/urdubiometer | 034c1efc0403352caa9c5c944cf9450b8833bb24 | [
"BSD-3-Clause"
] | 220 | 2019-07-30T19:20:59.000Z | 2022-03-28T10:33:19.000Z | urdubiometer/scanner/__init__.py | urdubiometer/urdubiometer | 034c1efc0403352caa9c5c944cf9450b8833bb24 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""Sub-level package for Scanner, a metrical scanner in Urdu BioMeter."""
__author__ = """A. Sean Pue"""
__email__ = "a@seanpue.com"
from .scanner import * # noqa
from .ghazal import * # noqa
from .types import * # noqa
| 22.727273 | 73 | 0.652 | 34 | 250 | 4.558824 | 0.705882 | 0.193548 | 0.180645 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004926 | 0.188 | 250 | 10 | 74 | 25 | 0.758621 | 0.42 | 0 | 0 | 0 | 0 | 0.176471 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.6 | 0 | 0.6 | 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 | 1 | 0 | 0 | 3 |
8846dbf904bdc1c8ef7bcf560fdf92013cf493ce | 362 | py | Python | Chapter 02/Chap02_Example2.9.py | bpbpublications/Programming-Techniques-using-Python | 49b785f37e95a3aad1d36cef51e219ac56e5e9f0 | [
"MIT"
] | null | null | null | Chapter 02/Chap02_Example2.9.py | bpbpublications/Programming-Techniques-using-Python | 49b785f37e95a3aad1d36cef51e219ac56e5e9f0 | [
"MIT"
] | null | null | null | Chapter 02/Chap02_Example2.9.py | bpbpublications/Programming-Techniques-using-Python | 49b785f37e95a3aad1d36cef51e219ac56e5e9f0 | [
"MIT"
] | null | null | null | s1 = "I am a beginner in python \nI will study the concepts to be familiar with this language.\nIt is a very user friendly language"
print("The long string is: \n" + s1) # -- L1
s2 = """The long string is:
I am a beginner in python
I will study the concepts to be familiar with this language.
It is a very user friendly language"""
print(s2) # -- L2
| 40.222222 | 133 | 0.69337 | 65 | 362 | 3.861538 | 0.476923 | 0.023904 | 0.031873 | 0.095618 | 0.796813 | 0.796813 | 0.63745 | 0.38247 | 0.38247 | 0.38247 | 0 | 0.021352 | 0.223757 | 362 | 8 | 134 | 45.25 | 0.871886 | 0.030387 | 0 | 0 | 0 | 0.142857 | 0.852941 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.285714 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 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 | 3 |
887318ae1de3947a937b8a9fff9e751422b6ec84 | 4,059 | py | Python | python/quantization.py | simnalamburt/snippets | 8ba4cfcb1305d2b82ea892e3305613eeb7ba382b | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 31 | 2016-01-27T07:03:25.000Z | 2022-02-25T07:59:11.000Z | python/quantization.py | simnalamburt/snippets | 8ba4cfcb1305d2b82ea892e3305613eeb7ba382b | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1 | 2015-01-26T01:27:21.000Z | 2015-01-30T16:16:30.000Z | python/quantization.py | simnalamburt/snippets | 8ba4cfcb1305d2b82ea892e3305613eeb7ba382b | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 3 | 2017-02-07T04:17:56.000Z | 2020-06-12T05:01:31.000Z | import numpy as np
min, max = -0.8777435, 0.57090986
M = np.asmatrix([
[0.02355068, -0.50542802, 0.16642167, -0.44872788, -0.05130898, 0.13320047, 0.41464597, -0.55703336, 0.52567458, 0.23784444, 0.15049535, 0.16599870, -0.28757980, 0.22277315, 0.56460077, -0.70838273, -0.61990398, -0.39724344, -0.09969769, 0.45835119, 0.02840372, 0.09637213, 0.04063996, -0.16667950, -0.68209213, -0.09524837, 0.27514741, 0.02957204, -0.11251312, -0.43414843],
[-0.31239739, -0.13213386, -0.59719753, -0.16117097, 0.29835659, -0.21633907, -0.55013347, -0.22406115, -0.47912723, -0.08179668, 0.46718585, 0.38543564, -0.49470344, -0.35172677, -0.23060481, -0.39899889, -0.18135746, -0.54352880, -0.28287631, -0.05576789, 0.20255803, 0.18899839, 0.36582524, 0.43294433, 0.21794824, -0.62954980, -0.52842420, 0.00261285, 0.23226254, 0.27430296],
[-0.12496945, 0.27272177, 0.09565081, -0.19869098, 0.40514281, 0.30038768, -0.13575996, -0.01735646, 0.31392211, -0.34690821, -0.26467761, 0.27735108, 0.25757775, 0.56070799, 0.48236406, -0.16126287, -0.56543708, -0.52047604, 0.31337339, 0.31964961, -0.19712290, 0.29141095, 0.25103137, -0.49437916, -0.00175839, -0.39314604, -0.46974984, -0.24069642, -0.07134162, 0.38584659],
[-0.22494942, -0.23908727, -0.14118181, 0.25917593, -0.46544874, 0.21652603, 0.11955780, -0.08858330, 0.11210553, 0.15425776, 0.35051644, 0.12857421, -0.31161663, -0.10459967, 0.28051424, 0.35245281, 0.21058421, -0.38336727, -0.53721315, -0.45408809, 0.17018577, 0.37464410, 0.25320616, -0.50858176, 0.03510477, 0.28646398, -0.49693882, 0.31466347, 0.34066224, 0.39151987],
[-0.24122262, -0.18464386, -0.50166339, -0.06581594, 0.23343681, -0.28764677, -0.28263095, 0.47374201, -0.14122090, 0.41170570, -0.27171388, -0.76247406, -0.43367779, -0.41885039, -0.58815128, 0.16303478, -0.15360811, 0.40358800, 0.28507465, 0.11577206, -0.05193469, 0.10712312, 0.37356687, 0.17525157, -0.61338550, 0.28956139, 0.04172062, 0.19050168, -0.36498675, -0.48431775],
[0.20951799, -0.57114357, 0.16709965, 0.28986153, -0.48571789, 0.17514014, 0.42663154, -0.58854365, -0.49951825, -0.69118619, -0.12997085, 0.20892869, -0.27441102, 0.25154045, 0.33150116, 0.22571780, 0.00198699, -0.21132891, 0.54626226, -0.39937377, 0.09991331, 0.16465400, -0.31479383, 0.19637901, 0.27371463, -0.35296553, 0.32819411, 0.33079246, 0.09111243, -0.15263695],
[0.23110701, -0.82688808, 0.35345000, -0.63799143, 0.10259465, -0.67562747, 0.06791017, -0.55785728, 0.11328468, 0.03148035, 0.06963930, -0.40473521, 0.15695126, 0.10480986, 0.06786098, 0.05529213, -0.06358500, 0.39808711, -0.46259707, -0.41053730, 0.23919414, 0.06440434, -0.55259717, 0.17278855, -0.26870996, -0.59644037, -0.20437278, -0.15572956, -0.62037915, 0.20436110],
[0.43668377, 0.03184615, -0.79770166, 0.30957624, -0.29246098, 0.41470772, -0.39726156, 0.08003121, 0.32232824, 0.18267424, -0.46286914, -0.52988207, 0.40305007, 0.43693665, 0.57090986, -0.71393168, 0.16701773, -0.01028878, 0.03239791, -0.39907083, 0.20838976, 0.25748143, 0.24718748, -0.05084279, -0.52348840, -0.07115566, -0.33007148, 0.18890919, 0.40487564, 0.28275076],
[0.00545317, 0.05541809, -0.29821581, -0.69852740, 0.23890208, -0.58182591, 0.37835562, -0.12874492, -0.24086623, -0.18621640, 0.20001458, -0.55234039, 0.40093267, 0.19279823, -0.56214923, -0.12595257, -0.13790886, 0.04751531, -0.31666499, 0.33546147, 0.19133377, 0.01450487, -0.69050521, -0.15352796, 0.31702802, 0.13524684, 0.08716883, 0.35998338, 0.36140910, -0.18685688],
[0.13561521, 0.09853959, 0.23551922, -0.37978131, -0.26070073, 0.43132550, -0.10494933, 0.07914228, 0.04663205, -0.41666678, 0.16825140, 0.51182604, 0.13776678, -0.68972874, -0.72430468, -0.10668162, 0.29812980, -0.13480635, -0.66627938, 0.01717626, -0.11104345, 0.31376141, 0.39751169, -0.19769318, -0.28220543, 0.13042673, 0.42700538, 0.08965667, 0.18087055, -0.87774348],
])
S = (max - min)/127.0
result = np.clip(np.ceil(M/S).astype(int), -128, 127).tolist()
print(
'\n'.join(
' '.join(str(e) for e in row)
for row in result
)
)
| 156.115385 | 384 | 0.700172 | 644 | 4,059 | 4.413043 | 0.507764 | 0.006334 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.746101 | 0.099532 | 4,059 | 25 | 385 | 162.36 | 0.031464 | 0 | 0 | 0 | 0 | 0 | 0.000739 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.045455 | 0 | 0.045455 | 0.045455 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
8875c6d752de20720e19e0bcf7801a8392c5567b | 220 | py | Python | int/Lib/site-packages/hn/__init__.py | yoniv/shellHN-main | 767e78f54403ebd3193ee9ada8672cfc06705967 | [
"MIT"
] | null | null | null | int/Lib/site-packages/hn/__init__.py | yoniv/shellHN-main | 767e78f54403ebd3193ee9ada8672cfc06705967 | [
"MIT"
] | null | null | null | int/Lib/site-packages/hn/__init__.py | yoniv/shellHN-main | 767e78f54403ebd3193ee9ada8672cfc06705967 | [
"MIT"
] | 1 | 2021-09-22T10:41:46.000Z | 2021-09-22T10:41:46.000Z | """
Python API for Hacker News.
@author Karan Goel
@email karan@goel.im
"""
__title__ = 'hackernews'
__author__ = 'Karan Goel'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Karan Goel'
from .hn import HN, Story
| 15.714286 | 43 | 0.722727 | 29 | 220 | 4.931034 | 0.689655 | 0.251748 | 0.20979 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.021739 | 0.163636 | 220 | 13 | 44 | 16.923077 | 0.755435 | 0.309091 | 0 | 0 | 0 | 0 | 0.333333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.2 | 0 | 0.2 | 0 | 1 | 0 | 0 | null | 1 | 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 | 0 | 0 | 0 | 0 | 0 | 3 |
88b0a8ec143545a862b4e668eb425512ef141839 | 295 | py | Python | incal_lib/exportres.py | barel-mishal/InCal_lib | 3aa63ebccf2ed3277fac55049c88178541cbb94b | [
"MIT"
] | null | null | null | incal_lib/exportres.py | barel-mishal/InCal_lib | 3aa63ebccf2ed3277fac55049c88178541cbb94b | [
"MIT"
] | null | null | null | incal_lib/exportres.py | barel-mishal/InCal_lib | 3aa63ebccf2ed3277fac55049c88178541cbb94b | [
"MIT"
] | null | null | null | import numpy as np
import pandas as pd
from collections import OrderedDict, Counter
import itertools
from typing import *
Group = tuple[str, list[int]]
Groups = list[Group]
def df_groups(groups: Groups) -> pd.DataFrame:
return pd.DataFrame(dict_groups.values(), index=dict_groups.keys())
| 22.692308 | 71 | 0.762712 | 43 | 295 | 5.162791 | 0.604651 | 0.108108 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.138983 | 295 | 12 | 72 | 24.583333 | 0.874016 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.555556 | 0.111111 | 0.777778 | 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 | 1 | 1 | 0 | 0 | 3 |
31f5361ec9609ecfe4d1234a6a87870a550e57fe | 316 | py | Python | depccg/lang.py | masashi-y/myccg | 263fd0afa7a619626fc2d506016625b6068bb27b | [
"MIT"
] | 75 | 2017-05-01T09:32:56.000Z | 2022-03-07T02:57:31.000Z | depccg/lang.py | masashi-y/myccg | 263fd0afa7a619626fc2d506016625b6068bb27b | [
"MIT"
] | 23 | 2017-05-10T08:28:57.000Z | 2022-02-15T05:15:25.000Z | depccg/lang.py | masashi-y/myccg | 263fd0afa7a619626fc2d506016625b6068bb27b | [
"MIT"
] | 15 | 2017-05-08T13:02:33.000Z | 2022-03-07T01:40:26.000Z |
import logging
logger = logging.getLogger(__name__)
GLOBAL_LANG_NAME = 'en'
def set_global_language_to(lang: str) -> None:
global GLOBAL_LANG_NAME
logger.info('Setting the global language config to: %s', lang)
GLOBAL_LANG_NAME = lang
def get_global_language() -> str:
return GLOBAL_LANG_NAME
| 17.555556 | 66 | 0.737342 | 45 | 316 | 4.8 | 0.466667 | 0.185185 | 0.259259 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.177215 | 316 | 17 | 67 | 18.588235 | 0.830769 | 0 | 0 | 0 | 0 | 0 | 0.136508 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.111111 | 0.111111 | 0.444444 | 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 | 1 | 0 | 0 | 0 | 3 |
ee3d2db0fde263da3c3eb73afde2fa65a46b2a9d | 445 | py | Python | models/batchnorm.py | JingweiJ/JointActorActionSeg | d33904f3f2c02094bb0a32bfec3105affff59426 | [
"MIT"
] | 11 | 2018-12-12T00:44:09.000Z | 2022-01-24T13:25:37.000Z | models/batchnorm.py | JingweiJ/JointActorActionSeg | d33904f3f2c02094bb0a32bfec3105affff59426 | [
"MIT"
] | 1 | 2019-04-24T08:25:12.000Z | 2019-04-24T08:25:12.000Z | models/batchnorm.py | JingweiJ/JointActorActionSeg | d33904f3f2c02094bb0a32bfec3105affff59426 | [
"MIT"
] | 3 | 2018-12-21T08:13:20.000Z | 2020-07-08T22:54:09.000Z | import keras.layers as KL
class BatchNorm(KL.BatchNormalization):
"""Batch Normalization class. Subclasses the Keras BN class and
hardcodes training=False so the BN layer doesn't update
during training.
Batch normalization has a negative effect on training if batches are small
so we disable it here.
"""
def call(self, inputs, training=None):
return super(self.__class__, self).call(inputs, training=False) | 37.083333 | 78 | 0.732584 | 62 | 445 | 5.193548 | 0.693548 | 0.111801 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.197753 | 445 | 12 | 79 | 37.083333 | 0.901961 | 0.521348 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0.25 | 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 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 3 |
ee7ca142b0ca37407f34d60f1083590fe6f55203 | 1,179 | py | Python | setup.py | jjk01/muMap | fe879039d025d62b51a70a088f3b0b275e134d9b | [
"BSD-3-Clause"
] | 8 | 2021-11-23T10:44:02.000Z | 2022-02-23T20:56:05.000Z | setup.py | jjk01/muMap | fe879039d025d62b51a70a088f3b0b275e134d9b | [
"BSD-3-Clause"
] | null | null | null | setup.py | jjk01/muMap | fe879039d025d62b51a70a088f3b0b275e134d9b | [
"BSD-3-Clause"
] | 2 | 2021-12-05T16:52:15.000Z | 2022-03-31T22:15:09.000Z | #! /usr/bin/env python
from setuptools import setup
VERSION = "1.0"
AUTHOR = "James Klatzow, Virginie Uhlmann"
AUTHOR_EMAIL = "uhlmann@ebi.ac.uk"
setup(
name="microMatch",
version=VERSION,
description="3D shape correspondence for microscopy data",
author=AUTHOR,
author_email=AUTHOR_EMAIL,
packages=[
"mumatch",
],
classifiers=[
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"License :: OSI Approved",
"Programming Language :: C",
"Programming Language :: Python",
"Topic :: Software Development",
"Topic :: Scientific/Engineering",
"Operating System :: POSIX",
"Operating System :: Unix",
"Operating System :: MacOS",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: " "Implementation :: CPython",
],
url="https://github.com/uhlmanngroup/muMatch",
python_requires=">=3.6",
)
| 29.475 | 73 | 0.605598 | 113 | 1,179 | 6.283186 | 0.584071 | 0.214085 | 0.246479 | 0.183099 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015927 | 0.254453 | 1,179 | 39 | 74 | 30.230769 | 0.791809 | 0.017812 | 0 | 0.058824 | 0 | 0 | 0.585134 | 0.019015 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.029412 | 0 | 0.029412 | 0 | 0 | 0 | 0 | null | 1 | 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 | 3 |
c9df6ba0ed0d28f7270862edcecc5a88bc403d3d | 615 | py | Python | arcade/rainbow.py | itsMadesh/python-personal-programs | 05355aa098afd87b345c9a2ca21b48552bf5a23b | [
"MIT"
] | null | null | null | arcade/rainbow.py | itsMadesh/python-personal-programs | 05355aa098afd87b345c9a2ca21b48552bf5a23b | [
"MIT"
] | null | null | null | arcade/rainbow.py | itsMadesh/python-personal-programs | 05355aa098afd87b345c9a2ca21b48552bf5a23b | [
"MIT"
] | null | null | null | import arcade
arcade.open_window(500,750,"Rainbow")
arcade.set_background_color(arcade.color.SKY_BLUE)
arcade.start_render()
arcade.draw_parabola_filled(25,80,500,300,arcade.color.RED,0)
arcade.draw_parabola_filled(50,80,470,280,arcade.color.ORANGE,0)
arcade.draw_parabola_filled(75,80,440,260,arcade.color.YELLOW ,0)
arcade.draw_parabola_filled(100,80,410,240,arcade.color.GREEN,0)
arcade.draw_parabola_filled(125,80,380,220,arcade.color.BLUE,0)
arcade.draw_parabola_filled(150,80,350,200,arcade.color.INDIGO,0)
arcade.draw_parabola_filled(175,80,320,180,arcade.color.VIOLET,0)
arcade.finish_render()
arcade.run()
| 43.928571 | 65 | 0.827642 | 108 | 615 | 4.527778 | 0.435185 | 0.179959 | 0.257669 | 0.343558 | 0.306748 | 0 | 0 | 0 | 0 | 0 | 0 | 0.145 | 0.02439 | 615 | 13 | 66 | 47.307692 | 0.67 | 0 | 0 | 0 | 0 | 0 | 0.011382 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.076923 | 0 | 0.076923 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
c9e3019d7f86a0fcc9bd9c9aa1f3b2b74e02646a | 9,232 | py | Python | tests/data/pandas_valid_data.py | craft-ai/craft-ai-client-python | 3d8b3d9a49c0c70964deaeb9645130dd54f9a0b3 | [
"BSD-3-Clause"
] | 14 | 2016-08-26T07:06:57.000Z | 2020-09-22T07:41:21.000Z | tests/data/pandas_valid_data.py | craft-ai/craft-ai-client-python | 3d8b3d9a49c0c70964deaeb9645130dd54f9a0b3 | [
"BSD-3-Clause"
] | 94 | 2016-08-02T14:07:59.000Z | 2021-10-06T11:50:52.000Z | tests/data/pandas_valid_data.py | craft-ai/craft-ai-client-python | 3d8b3d9a49c0c70964deaeb9645130dd54f9a0b3 | [
"BSD-3-Clause"
] | 8 | 2017-02-07T12:05:57.000Z | 2021-10-14T09:45:30.000Z | import pandas as pd
import numpy as np
from numpy.random import randn
from craft_ai.pandas import MISSING_VALUE, OPTIONAL_VALUE
from random import random, randint
NB_OPERATIONS = 300
NB_MANY_OPERATIONS = 1000
SIMPLE_AGENT_BOOSTING_CONFIGURATION = {
"model_type": "boosting",
"context": {
"a": {"type": "enum"},
"b": {"type": "continuous"},
"c": {"type": "continuous"},
"d": {"type": "continuous"},
"e": {"type": "timezone"},
},
"output": ["a"],
"min_samples_per_leaf": 1,
"operations_as_events": True,
"tree_max_operations": 50000,
"num_iterations": 20,
"learning_rate": 0.5,
}
AGENT_BOOSTING_CONFIGURATION_WITHOUT_TIMEZONE = {
"model_type": "boosting",
"context": {
"a": {"type": "enum"},
"b": {"type": "continuous"},
"c": {"type": "day_of_week", "is_generated": True},
"d": {"type": "timezone"},
},
"output": ["a"],
"min_samples_per_leaf": 1,
"operations_as_events": True,
"tree_max_operations": 50000,
"num_iterations": 20,
"learning_rate": 0.5,
}
SIMPLE_AGENT_BOOSTING_CONFIGURATION_WITH_GEN_TYPE = {
"model_type": "boosting",
"context": {
"a": {"type": "enum"},
"b": {"type": "continuous"},
"c": {"type": "continuous"},
"d": {"type": "continuous"},
"e": {"type": "timezone"},
"f": {"type": "day_of_week", "is_generated": True},
"g": {"type": "month_of_year"},
},
"output": ["a"],
"min_samples_per_leaf": 1,
"operations_as_events": True,
"tree_max_operations": 50000,
"num_iterations": 20,
"learning_rate": 0.5,
}
SIMPLE_AGENT_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "continuous"},
"c": {"type": "continuous"},
"d": {"type": "continuous"},
"e": {"type": "continuous"},
},
"output": ["a"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
}
AGENT_BOOSTING_WITHOUT_TIMEZONE_DATA = pd.DataFrame(
[[str(randint(1, 3)), random()] for i in range(NB_OPERATIONS)],
columns=["a", "b"],
index=pd.date_range("20200101", periods=NB_OPERATIONS, freq="T").tz_localize(
"Europe/Paris"
),
)
SIMPLE_AGENT_BOOSTING_DATA = pd.DataFrame(
[
[str(randint(1, 3)), random(), random(), random(), "+01:00"]
for i in range(NB_OPERATIONS)
],
columns=["a", "b", "c", "d", "e"],
index=pd.date_range("20200101", periods=NB_OPERATIONS, freq="T").tz_localize(
"Europe/Paris"
),
)
SIMPLE_AGENT_BOOSTING_MANY_DATA = pd.DataFrame(
[
[str(randint(1, 3)), random(), random(), random(), "+01:00"]
for i in range(NB_MANY_OPERATIONS)
],
columns=["a", "b", "c", "d", "e"],
index=pd.date_range("20200101", periods=NB_MANY_OPERATIONS, freq="T").tz_localize(
"Europe/Paris"
),
)
SIMPLE_AGENT_DATA = pd.DataFrame(
randn(NB_OPERATIONS, 5),
columns=["a", "b", "c", "d", "e"],
index=pd.date_range("20200101", periods=NB_OPERATIONS, freq="T").tz_localize(
"Europe/Paris"
),
)
SIMPLE_AGENT_MANY_DATA = pd.DataFrame(
randn(NB_MANY_OPERATIONS, 5),
columns=["a", "b", "c", "d", "e"],
index=pd.date_range("20200101", periods=NB_MANY_OPERATIONS, freq="T").tz_localize(
"Europe/Paris"
),
)
SIMPLE_AGENT_DATA_DICT = [
{
"timestamp": 1558741230,
"context": {"a": 10, "b": 10, "c": 10, "d": 10, "e": 10},
},
{"timestamp": 1558741331, "context": {"a": 10, "b": 11, "c": 12, "e": 13}},
{"timestamp": 1558741432, "context": {"a": 13, "b": 44, "c": 33, "d": 22}},
{"timestamp": 1558741533, "context": {"a": 11, "d": 55, "e": 55}},
{"timestamp": 1558741634, "context": {"a": 33, "c": 66, "d": 22, "e": 44}},
{"timestamp": 1558741735, "context": {"a": 1, "b": 33, "c": 33, "d": 44}},
]
COMPLEX_AGENT_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["b"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
"operations_as_events": True,
"learning_period": 3600 * 24 * 365,
"tree_max_operations": 50000,
}
COMPLEX_AGENT_CONFIGURATION_2 = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["a"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
"operations_as_events": True,
"learning_period": 3600 * 24 * 365,
"tree_max_operations": 50000,
}
COMPLEX_AGENT_DATA = pd.DataFrame(
[
[1, "Pierre", "+02:00"],
[2, "Paul"],
[3],
[4],
[5, "Jacques"],
[6],
[7],
[8, np.nan, "+01:00"],
[9],
[10],
],
columns=["a", "b", "tz"],
index=pd.date_range("20200101", periods=10, freq="D").tz_localize("Europe/Paris"),
)
COMPLEX_AGENT_DATA_2 = pd.DataFrame(
[
[1, "Pierre", "+02:00", [8, 9]],
[2, "Paul"],
[3],
[4],
[5, "Jacques"],
[6],
[7],
[8, np.nan, "+01:00", [1, 2, 3]],
[9],
[10],
],
columns=["a", "b", "tz", "arrays"],
index=pd.date_range("20200101", periods=10, freq="D").tz_localize("Europe/Paris"),
)
DATETIME_AGENT_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"myTimeOfDay": {"type": "time_of_day"},
"myCoolTimezone": {"type": "timezone"},
},
"output": ["b"],
"time_quantum": 3600,
"min_samples_per_leaf": 1,
}
DATETIME_AGENT_DATA = pd.DataFrame(
[
[1, "Pierre", "+02:00"],
[2, "Paul"],
[3, np.nan, "+04:00"],
[4],
[5, "Jacques", "UTC"],
[6],
[7, np.nan, "+08:00"],
[8],
[9],
[10, np.nan, "+10:00"],
],
columns=["a", "b", "myCoolTimezone"],
index=pd.date_range("20200101 00:00:00", periods=10, freq="H").tz_localize("UTC"),
)
MISSING_AGENT_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["a"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
}
MISSING_AGENT_DATA = pd.DataFrame(
[
[1, MISSING_VALUE, "+02:00"],
[2, "Paul"],
[3, OPTIONAL_VALUE],
[4],
[5, "Jacques"],
[6],
[np.nan, OPTIONAL_VALUE],
[8, None, "+01:00"],
[9],
[10],
],
columns=["a", "b", "tz"],
index=pd.date_range("20200101", periods=10, freq="D").tz_localize("Europe/Paris"),
)
MISSING_AGENT_DATA_DECISION = pd.DataFrame(
[[1, MISSING_VALUE, "+02:00"], [3, OPTIONAL_VALUE]],
columns=["a", "b", "tz"],
index=pd.date_range("20200101", periods=2, freq="D").tz_localize("Europe/Paris"),
)
INVALID_PYTHON_IDENTIFIER_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"1_b": {"type": "enum"},
"None": {"type": "enum"},
"_c": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["a"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
}
INVALID_PYTHON_IDENTIFIER_DATA = pd.DataFrame(
[
[1, "Pierre", "Mignon", "Toto", "+02:00"],
[2, "Paul"],
[3],
[4, "Tata", "Tutu"],
[5, "Jacques"],
[6],
[7],
[8, np.nan, np.nan, np.nan, "+01:00"],
[9],
[10],
],
columns=["a", "1_b", "None", "_c", "tz"],
index=pd.date_range("20200101", periods=10, freq="D").tz_localize("Europe/Paris"),
)
INVALID_PYTHON_IDENTIFIER_DECISION = pd.DataFrame(
[
[1, "Pierre", "Mignon", "Toto", "+02:00"],
[2, "Paul", "Mignon", "Toto", "+02:00"],
[3, "Tata", "Tutu", "Toto", "+02:00"],
],
columns=["a", "1_b", "None", "_c", "tz"],
index=pd.date_range("20200101", periods=3, freq="D").tz_localize("Europe/Paris"),
)
EMPTY_TREE = {
"_version": "2.0.0",
"configuration": {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["b"],
"time_quantum": 100,
"min_samples_per_leaf": 1,
},
"trees": {
"b": {"output_values": [], "prediction": {"confidence": 0, "nb_samples": 0}}
},
}
VALID_GENERATOR_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "continuous"},
"c": {"type": "continuous"},
"d": {"type": "continuous"},
"e": {"type": "continuous"},
},
"output": ["a"],
"time_quantum": 100,
"operations_as_events": True,
"learning_period": 6000000,
"tree_max_operations": 50000,
"filter": ["test_filter"],
}
VALID_COMPLEX_GENERATOR_CONFIGURATION = {
"context": {
"a": {"type": "continuous"},
"b": {"type": "enum"},
"tz": {"type": "timezone"},
},
"output": ["b"],
"time_quantum": 100,
"operations_as_events": True,
"learning_period": 6000000,
"tree_max_operations": 50000,
"filter": ["test_filter"],
}
VALID_TIMESTAMP = 1577833200
VALID_LAST_TIMESTAMP = 1577847600
| 26.682081 | 86 | 0.517006 | 1,053 | 9,232 | 4.320988 | 0.145299 | 0.073846 | 0.031648 | 0.042198 | 0.758242 | 0.728352 | 0.707692 | 0.68044 | 0.666593 | 0.632967 | 0 | 0.075458 | 0.254983 | 9,232 | 345 | 87 | 26.75942 | 0.586072 | 0 | 0 | 0.586207 | 0 | 0 | 0.268847 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.015674 | 0 | 0.015674 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
a0011285cd812341126bdf7a6b702e5a57d05603 | 23,485 | py | Python | old/Lissajous/Lissajous.py | Tony031218/manim-projects | b243dec0f0a007649a92938e90d60eccb4c7dd15 | [
"Apache-2.0"
] | 45 | 2019-10-08T23:58:20.000Z | 2020-05-20T03:49:15.000Z | old/Lissajous/Lissajous.py | Tony031218/manim-projects | b243dec0f0a007649a92938e90d60eccb4c7dd15 | [
"Apache-2.0"
] | null | null | null | old/Lissajous/Lissajous.py | Tony031218/manim-projects | b243dec0f0a007649a92938e90d60eccb4c7dd15 | [
"Apache-2.0"
] | 12 | 2019-08-15T08:07:22.000Z | 2020-05-09T12:34:14.000Z | from manimlib.imports import *
from manim_projects.tony_useful.imports import *
class Test2DLissajousFromLinesIntersection(Scene):
def construct(self):
circle_x = Circle(color=RED).shift(UP * 2.5)
circle_y = Circle(color=RED).shift(LEFT * 2.5)
theta = ValueTracker(0)
point_x = Dot().add_updater(lambda m: m.move_to(circle_x.point_at_angle(1 * theta.get_value())))
point_y = Dot().add_updater(lambda m: m.move_to(circle_y.point_at_angle(3 * theta.get_value())))
line_x = Line(UP * 6 , DOWN * 6).add_updater(lambda m: m.move_to(point_x.get_center()[0] * RIGHT)).set_color(GRAY)
line_y = Line(LEFT * 8, RIGHT * 8).add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP)).set_color(GRAY)
P = Dot(color=BLUE).add_updater(lambda m: m.move_to(line_intersection(line_x.get_start_and_end(), line_y.get_start_and_end())))
path = TracedPath(P.get_center, stroke_width=6, stroke_color=BLUE, min_distance_to_new_point=0.01)
self.add(circle_x, circle_y, point_x, point_y, line_x, line_y, P, path)
self.wait()
self.play(theta.increment_value, PI * 4, run_time=10, rate_func=linear)
self.wait()
class Test2DLissajousFromParametricFunction(Scene):
def construct(self):
line = ParametricFunction(
lambda t: [np.sin(1 * t + PI / 2), np.sin(3 * t), 0],
t_min=0, t_max=4 * TAU, color=BLUE
)
w = ValueTracker(1)
line.add_updater(
lambda m: m.become(
ParametricFunction(
lambda t: [np.sin(1 * t + PI / 2), np.sin(w.get_value() * t), 0],
t_min=0, t_max=4 * TAU, color=BLUE
)
)
)
self.add(line)
self.wait()
self.play(w.increment_value, 8, run_time=10, rate_func=linear)
self.wait()
class Dot3D(Sphere):
CONFIG = {
"radius": 0.08,
"checkerboard_colors": [WHITE, WHITE],
"stroke_width": 0,
}
class Line_(VGroup):
CONFIG = {
"nums": 100,
}
def __init__(self, start, end, **kwargs):
VGroup.__init__(self)
total = end - start
unit = total / self.nums
self.add(Line(start, start + unit, **kwargs))
for i in range(self.nums - 1):
now_start = self[-1].get_end()
now_end = now_start + unit
self.add(Line(now_start, now_end, **kwargs))
class Line__(VGroup):
CONFIG = {
"buff_": 0.02
}
def __init__(self, start, end, **kwargs):
VGroup.__init__(self)
base = Line(start, end, **kwargs)
if start[0] != 0:
self.add(base.copy().shift([0, -self.buff_, self.buff_]))
self.add(base.copy().shift([0, self.buff_, -self.buff_]))
self.add(base.copy().shift([0, self.buff_, self.buff_]))
self.add(base.copy().shift([0, -self.buff_, -self.buff_]))
elif start[1] != 0:
self.add(base.copy().shift([-self.buff_, 0, self.buff_]))
self.add(base.copy().shift([ self.buff_, 0, -self.buff_]))
self.add(base.copy().shift([ self.buff_, 0, self.buff_]))
self.add(base.copy().shift([-self.buff_, 0, -self.buff_]))
else:
self.add(base.copy().shift([-self.buff_, self.buff_, 0]))
self.add(base.copy().shift([ self.buff_, -self.buff_, 0]))
self.add(base.copy().shift([ self.buff_, self.buff_, 0]))
self.add(base.copy().shift([-self.buff_, -self.buff_, 0]))
class Test3DLissajousFromPlaneIntersection(ThreeDScene):
CONFIG = {
"camera_config": {
"background_color": WHITE
},
"dot_class": Dot3D,
"plane_use_ploygon": False,
"line_class": Line,
}
def construct(self):
axes = ThreeDAxes()
# self.add(axes)
self.set_camera_orientation(phi=70*DEGREES, theta=45*DEGREES)
# self.set_camera_orientation(distance=1000000)
self.begin_ambient_camera_rotation(rate=0.5)
circle_x = Circle(color=RED).rotate(PI / 2, RIGHT).shift(DOWN * 2.5).set_shade_in_3d()
circle_y = Circle(color=RED).rotate(PI / 2, DOWN).shift(LEFT * 2.5).set_shade_in_3d()
circle_z = Circle(color=RED).shift(IN * 2.5).set_shade_in_3d()
theta = ValueTracker(0)
point_x = self.dot_class().add_updater(lambda m: m.move_to(circle_x.point_at_angle(1 * theta.get_value()))).set_shade_in_3d().set_color(GREEN)
point_y = self.dot_class().add_updater(lambda m: m.move_to(circle_y.point_at_angle(2 * theta.get_value()))).set_shade_in_3d().set_color(ORANGE)
point_z = self.dot_class().add_updater(lambda m: m.move_to(circle_z.point_at_angle(3 * theta.get_value()))).set_shade_in_3d().set_color(PURPLE)
if self.plane_use_ploygon:
plane_x = Polygon(
np.array([ 2.5, 2.5, 0]),
np.array([-2.5, 2.5, 0]),
np.array([-2.5, -2.5, 0]),
np.array([ 2.5, -2.5, 0]),
fill_color=GREEN,
fill_opacity=0.3,
stroke_width=0
).set_shade_in_3d().add_updater(lambda m: m.move_to(point_x.get_center()[2] * OUT))
plane_y = Polygon(
np.array([ 2.5, 0, 2.5]),
np.array([-2.5, 0, 2.5]),
np.array([-2.5, 0, -2.5]),
np.array([ 2.5, 0, -2.5]),
fill_color=ORANGE,
fill_opacity=0.3,
stroke_width=0
).set_shade_in_3d().add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP))
plane_z = Polygon(
np.array([0, 2.5, 2.5]),
np.array([0, -2.5, 2.5]),
np.array([0, -2.5, -2.5]),
np.array([0, 2.5, -2.5]),
fill_color=PURPLE,
fill_opacity=0.3,
stroke_width=0
).set_shade_in_3d().add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT))
else:
plane_x = ParametricSurface(
lambda u, v: np.array([u, v, 0]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=GREEN, fill_opacity=0.3,
stroke_width=0
).add_updater(lambda m: m.move_to(point_x.get_center()[2] * OUT))
plane_y = ParametricSurface(
lambda u, v: np.array([u, 0, v]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=ORANGE, fill_opacity=0.3,
stroke_width=0
).add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP))
plane_z = ParametricSurface(
lambda u, v: np.array([0, u, v]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=PURPLE, fill_opacity=0.3,
stroke_width=0
).add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT))
line_x = self.line_class(
np.array([-2.5, 0, 0]),
np.array([ 2.5, 0, 0]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP + point_x.get_center()[2] * OUT))
line_y = self.line_class(
np.array([0, -2.5, 0]),
np.array([0, 2.5, 0]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT + point_x.get_center()[2] * OUT))
line_z = self.line_class(
np.array([0, 0, -2.5]),
np.array([0, 0, 2.5]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT + point_y.get_center()[1] * UP))
P = self.dot_class().set_shade_in_3d(False)
P.add_updater(lambda m: m.move_to(np.array([point_z.get_center()[0], point_y.get_center()[1], point_x.get_center()[2]])))
path = TracedPath(P.get_center, stroke_width=6, stroke_color=BLUE, min_distance_to_new_point=0.01)
self.add(circle_x, circle_y, circle_z, point_x, point_y, point_z, P, path, plane_x, plane_y, plane_z, line_x, line_y, line_z)
self.wait()
self.play(theta.increment_value, PI * 4, run_time=10, rate_func=linear)
self.wait(3)
self.stop_ambient_camera_rotation()
self.wait()
self.move_camera(phi=0, theta=TAU, distance=10000)
self.wait(2)
self.move_camera(phi=PI/2, theta=TAU, distance=10000)
self.wait(2)
self.move_camera(phi=PI/2, theta=TAU+PI/2, distance=10000)
self.wait(2)
self.move_camera(phi=70*DEGREES, theta=TAU+45*DEGREES)
self.wait()
class Test3DLissajousFromParametricFunction(ThreeDScene):
def construct(self):
self.set_camera_orientation(phi=90*DEGREES, theta=45*DEGREES, distance=10000)
line = ParametricFunction(
lambda t: np.array([np.sin(2 * t + PI / 2), np.sin(2 * t), np.sin(3 * t)]),
t_min=0, t_max=4 * TAU, color=BLUE
).scale(2.5)
self.add(line)
self.wait()
self.begin_ambient_camera_rotation(rate=1)
self.wait(10)
class Intro2DLissajous(Scene):
CONFIG = {
"camera_config": {
"background_color": WHITE
}
}
def construct(self):
para = TexMobject("(", "\\cos \\theta", ",", "\\sin 3\\theta", ")").set_color(BLACK)
para.scale(1.7).to_corner(DR)
circle_x = Circle(color=RED)#.shift(UP * 2.5)
circle_y = Circle(color=RED)#.shift(LEFT * 2.5)
self.wait()
self.play(ShowCreation(VGroup(circle_x, circle_y)))
self.wait()
self.play(
circle_x.shift, UP * 2.5,
circle_y.shift, LEFT * 2.5
)
self.wait()
theta = ValueTracker(0)
theta_label = TexMobject("\\theta = ").scale(1.7).to_corner(DL).set_color(BLACK)
theta_value = DecimalNumber(0, num_decimal_places=2).set_color(BLACK).scale(1.7).next_to(theta_label, RIGHT)
def updater_of_point_x(obj):
obj.move_to(circle_x.point_at_angle(1 * theta.get_value()))
point_x = Dot(color=GOLD).add_updater(updater_of_point_x)
point_y = Dot(color=GOLD).add_updater(lambda m: m.move_to(circle_y.point_at_angle(3 * theta.get_value())))
line_x = Line(UP * 6 , DOWN * 6, stroke_width=2).add_updater(lambda m: m.move_to(point_x.get_center()[0] * RIGHT)).set_color(GRAY).set_opacity(0.6)
line_y = Line(LEFT * 8, RIGHT * 8, stroke_width=2).add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP)).set_color(GRAY).set_opacity(0.6)
self.play(ShowCreation(point_x))
self.play(ShowCreation(line_x))
self.wait()
self.play(theta.increment_value, PI * 2, run_time=5, rate_func=linear)
self.play(Write(para[1]))
theta.set_value(0)
point_x.remove_updater(updater_of_point_x)
self.wait()
self.play(ShowCreation(point_y))
self.play(ShowCreation(line_y))
self.wait()
self.play(theta.increment_value, PI * 2, run_time=5, rate_func=linear)
self.play(Write(para[3]))
self.wait()
theta.set_value(0)
point_x.add_updater(updater_of_point_x)
P = Dot(color=BLUE).add_updater(lambda m: m.move_to([point_x.get_center()[0], point_y.get_center()[1], 0]))
path = TracedPath(P.get_center, stroke_width=6, stroke_color=BLUE, min_distance_to_new_point=0.01)
self.wait()
self.play(
ShowCreation(P),
FadeIn(VGroup(para[0], para[2], para[4])),
FadeIn(VGroup(theta_label, theta_value))
)
theta_value.add_updater(lambda m: m.set_value(theta.get_value()))
self.add(path)
self.wait()
self.play(theta.increment_value, PI * 4, run_time=10, rate_func=linear)
self.wait(3)
class ALotOf2DLissajous(Scene):
CONFIG = {
"camera_config": {
"background_color": WHITE
}
}
def construct(self):
w = ValueTracker(1)
label = VGroup(
DecimalNumber(0).set_color(BLACK).scale(2),
TexMobject(":").set_color(BLACK).scale(2),
TexMobject("3").set_color(BLACK).scale(2)
).arrange(RIGHT)
label.to_corner(UL, buff=1)
label[0].add_updater(lambda m: m.set_value(w.get_value()))
line = ParametricFunction(
lambda t: [np.cos(1 * t), np.sin(3 * t), 0],
t_min=0, t_max=6*TAU, color=BLUE
)
def updater_of_line(obj):
new = ParametricFunction(
lambda t: [np.cos(w.get_value() * t), np.sin(3 * t), 0],
t_min=0, t_max=6*TAU, color=BLUE
)
obj.become(new)
self.play(FadeIn(line), FadeIn(label))
self.wait()
for i in range(6):
line.add_updater(updater_of_line)
self.play(w.increment_value, 1, run_time=1, rate_func=linear)
line.remove_updater(updater_of_line)
self.wait()
self.wait()
line.add_updater(updater_of_line)
self.play(w.set_value, 1)
line.remove_updater(updater_of_line)
self.wait(2)
def smooth2(t, inflection=6):
error = sigmoid(-inflection / 2)
return np.clip(
(sigmoid(inflection * (t - 0.5)) - error) / (1 - 2 * error),
0, 1,
)
class From2DTo3DLissajous(ThreeDScene):
CONFIG = {
"camera_config": {
"background_color": WHITE
}
}
def construct(self):
axes = ThreeDAxes(number_line_config={"include_tip": False})
self.set_camera_orientation(phi=0*DEGREES, theta=90*DEGREES, distance=10000)
line = ParametricFunction(
lambda t: np.array([np.cos(1 * t), np.sin(3 * t), np.sin(2 * t)]),
t_min=0, t_max=4 * TAU, color=BLUE
)
self.add(line)
self.wait()
self.play(FadeIn(axes))
self.wait()
self.move_camera(phi=70*DEGREES, theta=135*DEGREES, rate_func=smooth2, run_time=5)
self.begin_ambient_camera_rotation(rate=0.8)
self.wait(10)
self.play(FadeOut(axes), FadeOut(line))
self.wait()
class ReadyTo3DLissajous(ThreeDScene):
CONFIG = {
"camera_config": {
"background_color": WHITE
},
"dot_class": Dot3D,
"line_class": Line,
}
def construct(self):
axes = ThreeDAxes()
# self.add(axes)
self.set_camera_orientation(phi=70*DEGREES, theta=45*DEGREES)
# self.set_camera_orientation(distance=1000000)
self.begin_ambient_camera_rotation(rate=0.25)
circle_x = Circle(color=RED).rotate(PI / 2, RIGHT).shift(DOWN * 2.5).set_shade_in_3d()
circle_y = Circle(color=RED).rotate(PI / 2, DOWN).shift(LEFT * 2.5).set_shade_in_3d()
circle_z = Circle(color=RED).shift(IN * 2.5).set_shade_in_3d()
self.wait()
self.play(
ShowCreation(VGroup(circle_x, circle_y, circle_z))
)
theta = ValueTracker(0)
def updater_of_point_x(m):
m.move_to(circle_x.point_at_angle(1 * theta.get_value()))
def updater_of_point_y(m):
m.move_to(circle_y.point_at_angle(2 * theta.get_value()))
def updater_of_point_z(m):
m.move_to(circle_z.point_at_angle(3 * theta.get_value()))
point_x = self.dot_class().add_updater(updater_of_point_x).set_color(GREEN)
def updater_of_plane_x(m):
m.move_to(point_x.get_center()[2] * OUT)
plane_x = ParametricSurface(
lambda u, v: np.array([u, v, 0]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=GREEN, fill_opacity=0.3,
stroke_width=0
).add_updater(updater_of_plane_x)
self.wait()
self.play(ShowCreation(point_x))
self.play(ShowCreation(plane_x))
self.wait()
self.play(theta.increment_value, PI*2, run_time=5, rate_func=linear)
self.wait()
point_x.remove_updater(updater_of_point_x)
plane_x.remove_updater(updater_of_plane_x)
theta.set_value(0)
point_y = self.dot_class().add_updater(updater_of_point_y).set_color(ORANGE)
def updater_of_plane_y(m):
m.move_to(point_y.get_center()[1] * UP)
plane_y = ParametricSurface(
lambda u, v: np.array([u, 0, v]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=ORANGE, fill_opacity=0.3,
stroke_width=0
).add_updater(updater_of_plane_y)
line_x = self.line_class(
np.array([-2.5, 0, 0]),
np.array([ 2.5, 0, 0]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_y.get_center()[1] * UP + point_x.get_center()[2] * OUT))
self.wait()
self.play(ShowCreation(point_y))
self.play(ShowCreation(plane_y))
self.play(ShowCreation(line_x))
self.wait()
self.play(theta.increment_value, PI*2, run_time=5, rate_func=linear)
self.wait()
point_y.remove_updater(updater_of_point_y)
plane_y.remove_updater(updater_of_plane_y)
theta.set_value(0)
point_z = self.dot_class().add_updater(updater_of_point_z).set_color(PURPLE)
def updater_of_plane_z(m):
m.move_to(point_z.get_center()[0] * RIGHT)
plane_z = ParametricSurface(
lambda u, v: np.array([0, u, v]),
u_min=-2.5, u_max=2.5, v_min=-2.5, v_max=2.5,
checkerboard_colors=None,
fill_color=PURPLE, fill_opacity=0.3,
stroke_width=0
).add_updater(updater_of_plane_z)
line_y = self.line_class(
np.array([0, -2.5, 0]),
np.array([0, 2.5, 0]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT + point_x.get_center()[2] * OUT))
line_z = self.line_class(
np.array([0, 0, -2.5]),
np.array([0, 0, 2.5]),
fill_color=GOLD_E,
stroke_width=2
).add_updater(lambda m: m.move_to(point_z.get_center()[0] * RIGHT + point_y.get_center()[1] * UP))
self.wait()
self.play(ShowCreation(point_z))
self.play(ShowCreation(plane_z))
self.play(ShowCreation(line_y), ShowCreation(line_z))
self.wait()
self.play(theta.increment_value, PI*2, run_time=5, rate_func=linear)
self.wait()
theta.set_value(0)
P = self.dot_class().set_shade_in_3d(False)
P.add_updater(lambda m: m.move_to(np.array([point_z.get_center()[0], point_y.get_center()[1], point_x.get_center()[2]])))
self.wait()
self.play(ShowCreation(P))
self.stop_ambient_camera_rotation()
self.wait()
self.move_camera(phi=70*DEGREES, theta=405*DEGREES)
class DualAxisIllusion(ThreeDScene):
CONFIG = {
"camera_config": {
"background_color": WHITE
}
}
def construct(self):
self.set_camera_orientation(phi=90*DEGREES, theta=45*DEGREES, distance=10000, gamma=90*DEGREES)
line = ParametricFunction(
lambda t: np.array([np.cos(2 * t), np.sin(2 * t), 0.6 * np.sin(3 * t)]),
t_min=0, t_max=4 * TAU, color=BLUE, stroke_width=20
).scale(2)
self.add(line)
self.wait()
self.begin_ambient_camera_rotation(rate=0.8)
self.wait(10)
class EndScene(ThreeDScene):
CONFIG = {
"camera_config": {
"background_color": WHITE
}
}
def construct(self):
self.set_camera_orientation(phi=90*DEGREES, theta=45*DEGREES, distance=10000, gamma=90*DEGREES)
line = ParametricFunction(
lambda t: np.array([np.cos(2 * t), np.sin(2 * t), 0.6 * np.sin(3 * t)]),
t_min=0, t_max=4 * TAU, color=BLUE, stroke_width=20
).scale(2)
self.play(FadeIn(line))
self.wait()
self.begin_ambient_camera_rotation(rate=0.5)
self.wait(6)
bg = Rectangle(width=16, height=10).set_fill(color=BLACK, opacity=0.8)
self.camera.add_fixed_in_frame_mobjects(bg)
self.wait()
self.play(FadeIn(bg))
thanks = Group(
Text("特别鸣谢", font="Source Han Sans CN").scale(0.55).set_color(RED),
ImageMobject("GZTime.png").scale(0.3),
Text("@GZTime", font="Source Han Serif CN").scale(0.35).set_color(BLUE),
ImageMobject("cigar.png").scale(0.3),
Text("@cigar666", font="Source Han Serif CN").scale(0.35).set_color(BLUE)
)
self.camera.add_fixed_in_frame_mobjects(thanks)
thanks[0].to_corner(UR)
thanks[2].next_to(thanks[0], DOWN, aligned_edge=RIGHT)
thanks[1].next_to(thanks[2], LEFT)
thanks[3].next_to(thanks[1], DOWN)
thanks[4].next_to(thanks[3], RIGHT)
thanks[1:].next_to(thanks[0], DOWN, aligned_edge=RIGHT)
thanks[1].scale(1.5, about_point=thanks[1].get_center())
refer = VGroup(
Text("参考", font="Source Han Sans CN").scale(0.55).set_color(RED),
Text("[1] Wikipedia利萨茹曲线 https://en.wikipedia.org/wiki/Lissajous_curve", font="Source Han Serif CN").scale(0.3),
Text("[2] processing利萨如图形 https://www.bilibili.com/video/av33110155", font="Source Han Serif CN").scale(0.3),
Text("[3] 双轴错觉 https://killedbyapixel.github.io/Dual-Axis-Illusion/", font="Source Han Serif CN").scale(0.3),
Text("[4] 双周错觉代码仓库 https://github.com/KilledByAPixel/Dual-Axis-Illusion", font="Source Han Serif CN").scale(0.3),
)
self.camera.add_fixed_in_frame_mobjects(refer)
refer.arrange(DOWN, aligned_edge=LEFT)
refer.to_corner(DL)
self.wait()
self.play(FadeInFromDown(thanks))
self.play(FadeIn(refer))
self.wait(10)
class VideoCover(Scene):
def construct(self):
background = Rectangle(width=18, height=3.5, fill_opacity=0.7, fill_color=BLACK, stroke_width=0).shift(DOWN*0.5)
title = VGroup(
Text("可视/三维", font="Source Han Serif CN", color=BLUE).scale(1),
Text("Lissajous图形", font="Source Han Serif CN", color=RED).scale(1.2)
).arrange(DOWN, aligned_edge=RIGHT, buff=0.4)
title_bg = VGroup(
Text("可视/三维", font="Source Han Serif CN", color=BLUE_B).scale(1).set_stroke(width=12, opacity=0.4),
Text("Lissajous图形", font="Source Han Serif CN", color=RED_B).scale(1.2).set_stroke(width=12, opacity=0.4)
).arrange(DOWN, aligned_edge=RIGHT, buff=0.4)
title.to_edge(RIGHT, buff=1.3).shift(DOWN*0.5)
title_bg.to_edge(RIGHT, buff=1.3).shift(DOWN*0.5)
author = VGroup(
TextMobject("@鹤翔万里", background_stroke_width=0).scale(1.2).set_color([YELLOW, RED]),
TextMobject("@\ GZTime", background_stroke_width=0).scale(1.2).set_color([WHITE, BLUE])
).arrange(DOWN, aligned_edge=LEFT)
author.shift(LEFT*4 + DOWN*0.5)
self.add(background, title_bg, title, author)
| 39.60371 | 157 | 0.584245 | 3,393 | 23,485 | 3.817271 | 0.076628 | 0.011272 | 0.014824 | 0.019765 | 0.790766 | 0.742048 | 0.716414 | 0.688774 | 0.661288 | 0.611025 | 0 | 0.040372 | 0.268043 | 23,485 | 592 | 158 | 39.670608 | 0.713089 | 0.0066 | 0 | 0.502959 | 0 | 0 | 0.039491 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043393 | false | 0 | 0.003945 | 0 | 0.096647 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
a00dbbabf32006769aba7ac26d4086798f8f5b92 | 75 | py | Python | Py26/01/main.py | xhexe/Py8R | 44238c5403e7f76988760a040bf5c292824c22e7 | [
"WTFPL"
] | null | null | null | Py26/01/main.py | xhexe/Py8R | 44238c5403e7f76988760a040bf5c292824c22e7 | [
"WTFPL"
] | null | null | null | Py26/01/main.py | xhexe/Py8R | 44238c5403e7f76988760a040bf5c292824c22e7 | [
"WTFPL"
] | null | null | null | inp = input("Enter string: ")
input_string = ord(inp)
print(input_string)
| 15 | 29 | 0.72 | 11 | 75 | 4.727273 | 0.545455 | 0.423077 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | 75 | 4 | 30 | 18.75 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0.186667 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0 | 0 | null | 1 | 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 | 3 |
4e55091a618968c01ac26471c9cd251dd97a71d7 | 9,578 | py | Python | argocd_client/models/application_application_sync_request.py | thepabloaguilar/argocd-client | a6c4ff268a63ee6715f9f837b9225b798aa6bde2 | [
"BSD-3-Clause"
] | 1 | 2021-09-29T11:57:07.000Z | 2021-09-29T11:57:07.000Z | argocd_client/models/application_application_sync_request.py | thepabloaguilar/argocd-client | a6c4ff268a63ee6715f9f837b9225b798aa6bde2 | [
"BSD-3-Clause"
] | 1 | 2020-09-09T00:28:57.000Z | 2020-09-09T00:28:57.000Z | argocd_client/models/application_application_sync_request.py | thepabloaguilar/argocd-client | a6c4ff268a63ee6715f9f837b9225b798aa6bde2 | [
"BSD-3-Clause"
] | 2 | 2020-10-13T18:31:59.000Z | 2021-02-15T12:52:33.000Z | # coding: utf-8
"""
Consolidate Services
Description of all APIs # noqa: E501
The version of the OpenAPI document: version not set
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from argocd_client.configuration import Configuration
class ApplicationApplicationSyncRequest(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'dry_run': 'bool',
'infos': 'list[V1alpha1Info]',
'manifests': 'list[str]',
'name': 'str',
'prune': 'bool',
'resources': 'list[V1alpha1SyncOperationResource]',
'retry_strategy': 'V1alpha1RetryStrategy',
'revision': 'str',
'strategy': 'V1alpha1SyncStrategy'
}
attribute_map = {
'dry_run': 'dryRun',
'infos': 'infos',
'manifests': 'manifests',
'name': 'name',
'prune': 'prune',
'resources': 'resources',
'retry_strategy': 'retryStrategy',
'revision': 'revision',
'strategy': 'strategy'
}
def __init__(self, dry_run=None, infos=None, manifests=None, name=None, prune=None, resources=None, retry_strategy=None, revision=None, strategy=None, local_vars_configuration=None): # noqa: E501
"""ApplicationApplicationSyncRequest - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._dry_run = None
self._infos = None
self._manifests = None
self._name = None
self._prune = None
self._resources = None
self._retry_strategy = None
self._revision = None
self._strategy = None
self.discriminator = None
if dry_run is not None:
self.dry_run = dry_run
if infos is not None:
self.infos = infos
if manifests is not None:
self.manifests = manifests
if name is not None:
self.name = name
if prune is not None:
self.prune = prune
if resources is not None:
self.resources = resources
if retry_strategy is not None:
self.retry_strategy = retry_strategy
if revision is not None:
self.revision = revision
if strategy is not None:
self.strategy = strategy
@property
def dry_run(self):
"""Gets the dry_run of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The dry_run of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: bool
"""
return self._dry_run
@dry_run.setter
def dry_run(self, dry_run):
"""Sets the dry_run of this ApplicationApplicationSyncRequest.
:param dry_run: The dry_run of this ApplicationApplicationSyncRequest. # noqa: E501
:type: bool
"""
self._dry_run = dry_run
@property
def infos(self):
"""Gets the infos of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The infos of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: list[V1alpha1Info]
"""
return self._infos
@infos.setter
def infos(self, infos):
"""Sets the infos of this ApplicationApplicationSyncRequest.
:param infos: The infos of this ApplicationApplicationSyncRequest. # noqa: E501
:type: list[V1alpha1Info]
"""
self._infos = infos
@property
def manifests(self):
"""Gets the manifests of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The manifests of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: list[str]
"""
return self._manifests
@manifests.setter
def manifests(self, manifests):
"""Sets the manifests of this ApplicationApplicationSyncRequest.
:param manifests: The manifests of this ApplicationApplicationSyncRequest. # noqa: E501
:type: list[str]
"""
self._manifests = manifests
@property
def name(self):
"""Gets the name of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The name of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this ApplicationApplicationSyncRequest.
:param name: The name of this ApplicationApplicationSyncRequest. # noqa: E501
:type: str
"""
self._name = name
@property
def prune(self):
"""Gets the prune of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The prune of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: bool
"""
return self._prune
@prune.setter
def prune(self, prune):
"""Sets the prune of this ApplicationApplicationSyncRequest.
:param prune: The prune of this ApplicationApplicationSyncRequest. # noqa: E501
:type: bool
"""
self._prune = prune
@property
def resources(self):
"""Gets the resources of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The resources of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: list[V1alpha1SyncOperationResource]
"""
return self._resources
@resources.setter
def resources(self, resources):
"""Sets the resources of this ApplicationApplicationSyncRequest.
:param resources: The resources of this ApplicationApplicationSyncRequest. # noqa: E501
:type: list[V1alpha1SyncOperationResource]
"""
self._resources = resources
@property
def retry_strategy(self):
"""Gets the retry_strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The retry_strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: V1alpha1RetryStrategy
"""
return self._retry_strategy
@retry_strategy.setter
def retry_strategy(self, retry_strategy):
"""Sets the retry_strategy of this ApplicationApplicationSyncRequest.
:param retry_strategy: The retry_strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:type: V1alpha1RetryStrategy
"""
self._retry_strategy = retry_strategy
@property
def revision(self):
"""Gets the revision of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The revision of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: str
"""
return self._revision
@revision.setter
def revision(self, revision):
"""Sets the revision of this ApplicationApplicationSyncRequest.
:param revision: The revision of this ApplicationApplicationSyncRequest. # noqa: E501
:type: str
"""
self._revision = revision
@property
def strategy(self):
"""Gets the strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:return: The strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:rtype: V1alpha1SyncStrategy
"""
return self._strategy
@strategy.setter
def strategy(self, strategy):
"""Sets the strategy of this ApplicationApplicationSyncRequest.
:param strategy: The strategy of this ApplicationApplicationSyncRequest. # noqa: E501
:type: V1alpha1SyncStrategy
"""
self._strategy = strategy
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ApplicationApplicationSyncRequest):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ApplicationApplicationSyncRequest):
return True
return self.to_dict() != other.to_dict()
| 29.112462 | 200 | 0.618292 | 960 | 9,578 | 6.052083 | 0.129167 | 0.037177 | 0.241652 | 0.199828 | 0.472806 | 0.383305 | 0.365577 | 0.168158 | 0.058176 | 0.013081 | 0 | 0.017934 | 0.295573 | 9,578 | 328 | 201 | 29.20122 | 0.84319 | 0.387764 | 0 | 0.089655 | 1 | 0 | 0.06882 | 0.011236 | 0 | 0 | 0 | 0 | 0 | 1 | 0.165517 | false | 0 | 0.027586 | 0 | 0.324138 | 0.013793 | 0 | 0 | 0 | null | 0 | 1 | 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 | 3 |
4e6138843998a3ede92abaaa70a1ae3fc7c18aae | 711 | py | Python | losses.py | dhaulagiri0/AniGen | bd845a29e771544ade1f64b94f967d8e178952f8 | [
"MIT"
] | null | null | null | losses.py | dhaulagiri0/AniGen | bd845a29e771544ade1f64b94f967d8e178952f8 | [
"MIT"
] | null | null | null | losses.py | dhaulagiri0/AniGen | bd845a29e771544ade1f64b94f967d8e178952f8 | [
"MIT"
] | null | null | null | import tensorflow as tf
from tensorflow.keras import backend
#DEPRECATED
# An implementation of wasserstein used for a naive implementation of WGAN
# calculate wasserstein loss
def wasserstein_loss(y_true, y_pred):
return backend.mean(y_true * y_pred)
# Define the loss functions for the discriminator,
# which should be (fake_loss - real_loss).
# We will add the gradient penalty later to this loss function.
def discriminator_loss(real_img, fake_img):
real_loss = tf.reduce_mean(real_img)
fake_loss = tf.reduce_mean(fake_img)
return real_loss, fake_loss, fake_loss - real_loss
# Define the loss functions for the generator.
def generator_loss(fake_img):
return -tf.reduce_mean(fake_img)
| 32.318182 | 74 | 0.78481 | 111 | 711 | 4.810811 | 0.414414 | 0.059925 | 0.067416 | 0.037453 | 0.17603 | 0.104869 | 0 | 0 | 0 | 0 | 0 | 0 | 0.151899 | 711 | 21 | 75 | 33.857143 | 0.885572 | 0.431786 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.3 | false | 0 | 0.2 | 0.2 | 0.8 | 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 | 1 | 0 | 0 | 3 |
4e63749234da693d5c1f2625bba0bf9c3d524e3f | 274 | py | Python | testproject/fiber_test/tests/test_templatetags/test_fiber_version.py | bsimons/django-fiber | 0f4b03217a4aeba6b48908825507fbe8c5732c8d | [
"Apache-2.0"
] | 143 | 2015-01-06T01:15:22.000Z | 2017-07-08T04:10:08.000Z | testproject/fiber_test/tests/test_templatetags/test_fiber_version.py | bsimons/django-fiber | 0f4b03217a4aeba6b48908825507fbe8c5732c8d | [
"Apache-2.0"
] | 44 | 2015-01-22T14:21:32.000Z | 2017-05-31T16:59:23.000Z | testproject/fiber_test/tests/test_templatetags/test_fiber_version.py | bsimons/django-fiber | 0f4b03217a4aeba6b48908825507fbe8c5732c8d | [
"Apache-2.0"
] | 53 | 2015-01-21T21:48:49.000Z | 2017-06-12T07:33:13.000Z | import fiber
from django.test import SimpleTestCase
from ...test_util import RenderMixin
class TestFiberVersion(RenderMixin, SimpleTestCase):
def test_fiber_version(self):
self.assertRendered('{% load fiber_tags %}{% fiber_version %}', str(fiber.__version__))
| 30.444444 | 95 | 0.766423 | 31 | 274 | 6.483871 | 0.548387 | 0.179104 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.131387 | 274 | 8 | 96 | 34.25 | 0.844538 | 0 | 0 | 0 | 0 | 0 | 0.145985 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 1 | 0.166667 | false | 0 | 0.5 | 0 | 0.833333 | 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 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
4e6b7f322b294819ab5b4b631d1bcc760d50a431 | 618 | py | Python | examples/testpetsc.py | DDMGNI/viVlasov1D | 901dd058711f6943eb6497b941bc115a64e822de | [
"MIT"
] | 2 | 2018-09-13T12:39:07.000Z | 2019-04-05T04:55:59.000Z | examples/testpetsc.py | DDMGNI/viVlasov1D | 901dd058711f6943eb6497b941bc115a64e822de | [
"MIT"
] | null | null | null | examples/testpetsc.py | DDMGNI/viVlasov1D | 901dd058711f6943eb6497b941bc115a64e822de | [
"MIT"
] | null | null | null |
import numpy as np
def temperature(x):
pass
def density(x, L):
# weak Jeans instability
# density = 1. + 0.01 * np.cos(0.8 * (x - 0.5 * L))
# strong Jeans instability
# density = 1. + 0.01 * np.cos(0.1 * (x - 0.5 * L))
# linear Landau damping
# return 1. + 0.01 * np.cos(0.5 * (x - 0.5 * L))
# nonlinear Landau damping
density = 1. + (np.cos(0.5 * x))
return density
def distribution(x, y):
# if y <= 2. and y >= -2.:
# f = 1.
# else:
# f = 0.
f = 1. + 0.5 * (np.cos(x + y*np.pi) - np.cos(x - y*np.pi))
return f
| 16.263158 | 62 | 0.469256 | 102 | 618 | 2.843137 | 0.323529 | 0.103448 | 0.082759 | 0.062069 | 0.372414 | 0.337931 | 0.227586 | 0.227586 | 0.227586 | 0 | 0 | 0.085213 | 0.354369 | 618 | 37 | 63 | 16.702703 | 0.641604 | 0.530744 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0.111111 | 0.111111 | 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 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 3 |
4ea392c525c167ab6e4487bc47072399df2ebdf7 | 2,788 | py | Python | non-regression-tests/config.py | etalab-ia/piaf-ml | cd006b905d4c3e6a358326a42b84179724b00e5f | [
"MIT"
] | 5 | 2021-06-22T08:51:53.000Z | 2021-12-14T17:26:32.000Z | non-regression-tests/config.py | etalab-ia/piaf-ml | cd006b905d4c3e6a358326a42b84179724b00e5f | [
"MIT"
] | 55 | 2021-06-16T07:58:16.000Z | 2021-08-30T10:30:26.000Z | non-regression-tests/config.py | etalab-ia/piaf-ml | cd006b905d4c3e6a358326a42b84179724b00e5f | [
"MIT"
] | null | null | null | import os
parameter_tuning_options = {
"experiment_name": "non-regression-tests",
# Tuning method alternatives:
# - "optimization": use bayesian optimisation
# - "grid_search"
"tuning_method": "grid_search",
# Additionnal options for the grid search method
"use_cache": False,
# Additionnal options for the optimization method
"optimization_ncalls": 10,
}
parameters_fquad = {
"k_retriever": [5],
"k_title_retriever" : [1], # must be present, but only used when retriever_type == title_bm25
"k_reader_per_candidate": [20],
"k_reader_total": [10],
"reader_model_version": ["053b085d851196110d7a83d8e0f077d0a18470be"],
"retriever_model_version": ["1a01b38498875d45f69b2a6721bf6fe87425da39"],
"dpr_model_version": ["v1.0"],
"retriever_type": ["bm25"], # Can be bm25, sbert, dpr, title or title_bm25
"squad_dataset": [
os.getenv("DATA_DIR") + "/non-regression-tests/fquad_dataset.json"
],
"filter_level": [None],
"preprocessing": [False],
"boosting" : [1], #default to 1
"split_by": ["word"], # Can be "word", "sentence", or "passage"
"split_length": [1000],
}
# A dictionnary specifying the criteria a test result must pass. Keys are
# metrics names and keys are predicates on the corresponding metric which must
# return true if the value is satisfying.
pass_criteria_fquad = {
"reader_topk_accuracy_has_answer":
# metric ~= 0.747 +/- 1%
lambda metric: abs(metric / 0.747 - 1) < 0.01
}
parameters_dila = {
"k_retriever": [1],
"k_title_retriever" : [1], # must be present, but only used when retriever_type == title_bm25
"k_reader_per_candidate": [20],
"k_reader_total": [10],
"reader_model_version": ["053b085d851196110d7a83d8e0f077d0a18470be"],
"retriever_model_version": ["1a01b38498875d45f69b2a6721bf6fe87425da39"],
"dpr_model_version": ["v1.0"],
"retriever_type": ["bm25"], # Can be bm25, sbert, dpr, title or title_bm25
"squad_dataset": [
os.getenv("SRC_DIR") + "/piaf-ml/clients/dila/knowledge_base/squad.json"],
"filter_level": [None],
"preprocessing": [False],
"boosting" : [1], #default to 1
"split_by": ["word"], # Can be "word", "sentence", or "passage"
"split_length": [1000],
}
# A dictionnary specifying the criteria a test result must pass. Keys are
# metrics names and keys are predicates on the corresponding metric which must
# return true if the value is satisfying.
pass_criteria_dila = {
"reader_topk_accuracy_has_answer":
# metric ~= 0.427 +/- 1%
lambda metric: abs(metric / 0.427 - 1) < 0.01
}
tests = [
(parameters_fquad, parameter_tuning_options, pass_criteria_fquad),
(parameters_dila, parameter_tuning_options, pass_criteria_dila),
]
| 35.74359 | 97 | 0.681133 | 341 | 2,788 | 5.334311 | 0.337243 | 0.039582 | 0.036284 | 0.026388 | 0.742166 | 0.704783 | 0.679494 | 0.642111 | 0.642111 | 0.642111 | 0 | 0.082155 | 0.187948 | 2,788 | 77 | 98 | 36.207792 | 0.72129 | 0.333572 | 0 | 0.518519 | 0 | 0 | 0.45915 | 0.21732 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.074074 | 0.018519 | 0 | 0.018519 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 3 |
4ece31e4c80ccf74cc98a1222f00653c142ee026 | 65 | py | Python | scuttlecrab/main.py | PUMBA-1997/scuttlecrab.py | 13e0074b7d94af81bf5c13feb5a3d036bc71f133 | [
"Apache-2.0"
] | 4 | 2022-01-05T14:16:07.000Z | 2022-01-09T07:29:08.000Z | scuttlecrab/main.py | Fabrizio1663/scuttlecrab.py | 13e0074b7d94af81bf5c13feb5a3d036bc71f133 | [
"Apache-2.0"
] | null | null | null | scuttlecrab/main.py | Fabrizio1663/scuttlecrab.py | 13e0074b7d94af81bf5c13feb5a3d036bc71f133 | [
"Apache-2.0"
] | null | null | null | from scuttlecrab.classes.bot import CustomBot
bot = CustomBot()
| 16.25 | 45 | 0.8 | 8 | 65 | 6.5 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.123077 | 65 | 3 | 46 | 21.666667 | 0.912281 | 0 | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 3 |
14fbcce3feb4c4d3755700befad3fb8381ba83ea | 719 | py | Python | carnival/migrations/0011_auto_20191017_1045.py | farro4069/allez | c6ba374ee03cb01a494a4f6fe8ae0d0de5ce463c | [
"BSD-2-Clause"
] | null | null | null | carnival/migrations/0011_auto_20191017_1045.py | farro4069/allez | c6ba374ee03cb01a494a4f6fe8ae0d0de5ce463c | [
"BSD-2-Clause"
] | null | null | null | carnival/migrations/0011_auto_20191017_1045.py | farro4069/allez | c6ba374ee03cb01a494a4f6fe8ae0d0de5ce463c | [
"BSD-2-Clause"
] | null | null | null | # Generated by Django 2.1.4 on 2019-10-17 00:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carnival', '0010_auto_20191013_1246'),
]
operations = [
migrations.AlterField(
model_name='register',
name='prime_one',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='register',
name='prime_three',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='register',
name='prime_two',
field=models.BooleanField(default=False),
),
]
| 24.793103 | 53 | 0.5758 | 68 | 719 | 5.955882 | 0.558824 | 0.148148 | 0.185185 | 0.214815 | 0.6 | 0.51358 | 0.51358 | 0.4 | 0.4 | 0.4 | 0 | 0.062753 | 0.312935 | 719 | 28 | 54 | 25.678571 | 0.757085 | 0.062587 | 0 | 0.545455 | 1 | 0 | 0.125 | 0.034226 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.045455 | 0 | 0.181818 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
091779d4a3220139baaa8d0f21ee1690811fd3bf | 197 | py | Python | enote/__init__.py | tkjacobsen/enote | b8150885733599016b2d0b1d36f03e62ca8e3cdc | [
"MIT"
] | 16 | 2015-04-30T22:36:57.000Z | 2021-04-29T16:38:17.000Z | enote/__init__.py | tkjacobsen/enote | b8150885733599016b2d0b1d36f03e62ca8e3cdc | [
"MIT"
] | 1 | 2017-02-18T18:42:31.000Z | 2017-02-18T18:48:47.000Z | enote/__init__.py | tkjacobsen/enote | b8150885733599016b2d0b1d36f03e62ca8e3cdc | [
"MIT"
] | 2 | 2017-06-03T08:00:28.000Z | 2017-07-15T16:50:47.000Z | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Troels Agergaard Jacobsen
__version__ = '0.2.0'
__description__ = 'Command line utility to backup Evernote notes and notebooks.'
| 32.833333 | 80 | 0.725888 | 27 | 197 | 5 | 0.962963 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.053254 | 0.142132 | 197 | 5 | 81 | 39.4 | 0.745562 | 0.446701 | 0 | 0 | 0 | 0 | 0.613208 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
094be0cf0f33e0827cc74563503d2f32fbf9ae51 | 1,787 | py | Python | solver.py | tamnguyen820/SudokuSolver | a4adf311fca7bdbf7d2e5f7a676197e39218e53a | [
"MIT"
] | null | null | null | solver.py | tamnguyen820/SudokuSolver | a4adf311fca7bdbf7d2e5f7a676197e39218e53a | [
"MIT"
] | null | null | null | solver.py | tamnguyen820/SudokuSolver | a4adf311fca7bdbf7d2e5f7a676197e39218e53a | [
"MIT"
] | null | null | null | '''
For testing with the text version
'''
b = [
[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
]
def print_board(board):
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - -")
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
print(board[i][j], end="")
if j == 8:
print()
else:
print(" ", end="")
def find_empty_cell(board):
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] == 0:
return (row, col)
return False
def is_valid(board, target, pos):
# Check row and col
for i in range(len(board[0])):
if (pos[1] != i and target == board[pos[0]][i]) or \
(pos[0] != i and target == board[i][pos[1]]):
return False
# Check sub-grid
brow = pos[0]//3
bcol = pos[1]//3
for i in range(3):
for j in range(3):
if (i, j) != pos and target == board[brow*3+i][bcol*3+j]:
return False
return True
def solve(board):
empty = find_empty_cell(board)
if not empty:
return True
row, col = empty
for i in range(0, 10):
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False | 26.279412 | 70 | 0.409625 | 283 | 1,787 | 2.561837 | 0.155477 | 0.217931 | 0.322759 | 0.424828 | 0.266207 | 0.216552 | 0.110345 | 0.110345 | 0.110345 | 0.110345 | 0 | 0.102662 | 0.411304 | 1,787 | 68 | 71 | 26.279412 | 0.586502 | 0.037493 | 0 | 0.283019 | 0 | 0 | 0.016413 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.075472 | false | 0 | 0 | 0 | 0.226415 | 0.113208 | 0 | 0 | 0 | null | 1 | 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 | 3 |
11b7cee72a017b56ab9f447f74c1610717cfe52e | 8,784 | py | Python | tests/st/ops/gpu/test_scatter_nd_func_op.py | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 1 | 2021-12-27T13:42:29.000Z | 2021-12-27T13:42:29.000Z | tests/st/ops/gpu/test_scatter_nd_func_op.py | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | tests/st/ops/gpu/test_scatter_nd_func_op.py | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 numpy as np
import pytest
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor, Parameter
import mindspore.common.dtype as mstype
import mindspore.ops as ops
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
func_map = {
"update": ops.ScatterNdUpdate,
"add": ops.ScatterNdAdd,
"sub": ops.ScatterNdSub,
}
class TestScatterNdFuncNet(nn.Cell):
def __init__(self, func, lock, inputx, indices, updates):
super(TestScatterNdFuncNet, self).__init__()
self.scatter_func = func_map[func](use_locking=lock)
self.inputx = Parameter(inputx, name="inputx")
self.indices = Parameter(indices, name="indices")
self.updates = Parameter(updates, name="updates")
def construct(self):
out = self.scatter_func(self.inputx, self.indices, self.updates)
return out
def scatter_nd_func_net(func, inputx, indices, updates):
lock = True
net = TestScatterNdFuncNet(func, lock, inputx, indices, updates)
return net()
def scatter_nd_func_use_locking_false_net(func, inputx, indices, updates):
lock = False
net = TestScatterNdFuncNet(func, lock, inputx, indices, updates)
return net()
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_traning
@pytest.mark.env_onecard
def test_scatter_nd_func_small_float32():
inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mstype.float32)
indices = Tensor(np.array([[0, 0], [1, 1]]), mstype.int32)
updates = Tensor(np.array([1.0, 2.2]), mstype.float32)
# update
output = scatter_nd_func_net("update", inputx, indices, updates)
expected = np.array([[1.0, 0.3, 3.6], [0.4, 2.2, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
output = scatter_nd_func_net("add", inputx, indices, updates)
expected = np.array([[0.9, 0.3, 3.6], [0.4, 2.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
output = scatter_nd_func_net("sub", inputx, indices, updates)
expected = np.array([[-1.1, 0.3, 3.6], [0.4, -1.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_scatter_nd_func_input_updated():
inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mstype.float32)
indices = Tensor(np.array([[0, 0], [1, 1]]), mstype.int32)
updates = Tensor(np.array([1.0, 2.2]), mstype.float32)
lock = True
# update
net = TestScatterNdFuncNet("update", lock, inputx, indices, updates)
output = net()
expected = np.array([[1.0, 0.3, 3.6], [0.4, 2.2, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
net = TestScatterNdFuncNet("add", lock, inputx, indices, updates)
output = net()
expected = np.array([[0.9, 0.3, 3.6], [0.4, 2.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
net = TestScatterNdFuncNet("sub", lock, inputx, indices, updates)
output = net()
expected = np.array([[-1.1, 0.3, 3.6], [0.4, -1.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_traning
@pytest.mark.env_onecard
def test_scatter_nd_func_small_float32_using_locking_false():
inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mstype.float32)
indices = Tensor(np.array([[0, 0], [1, 1]]), mstype.int32)
updates = Tensor(np.array([1.0, 2.2]), mstype.float32)
# update
output = scatter_nd_func_use_locking_false_net("update", inputx, indices, updates)
expected = np.array([[1.0, 0.3, 3.6], [0.4, 2.2, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
output = scatter_nd_func_use_locking_false_net("add", inputx, indices, updates)
expected = np.array([[0.9, 0.3, 3.6], [0.4, 2.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
output = scatter_nd_func_use_locking_false_net("sub", inputx, indices, updates)
expected = np.array([[-1.1, 0.3, 3.6], [0.4, -1.7, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_traning
@pytest.mark.env_onecard
def test_scatter_nd_func_small_int32():
inputx = Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mstype.float32)
indices = Tensor(np.array([[4], [3], [1], [7]]), mstype.int32)
updates = Tensor(np.array([9, 10, 11, 12]), mstype.float32)
# update
output = scatter_nd_func_net("update", inputx, indices, updates)
expected = np.array([1, 11, 3, 10, 9, 6, 7, 12])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
output = scatter_nd_func_net("add", inputx, indices, updates)
expected = np.array([1, 13, 3, 14, 14, 6, 7, 20])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
output = scatter_nd_func_net("sub", inputx, indices, updates)
expected = np.array([1, -9, 3, -6, -4, 6, 7, -4])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_traning
@pytest.mark.env_onecard
def test_scatter_nd_func_multi_dims():
inputx = Tensor(np.zeros((4, 4, 4)), mstype.float32)
indices = Tensor(np.array([[0], [2]]), mstype.int32)
updates = Tensor(
np.array(
[
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
]
),
mstype.float32,
)
# update
output = scatter_nd_func_net("update", inputx, indices, updates)
expected = np.array(
[
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
]
)
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
output = scatter_nd_func_net("add", inputx, indices, updates)
expected = np.array(
[
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
]
)
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
output = scatter_nd_func_net("sub", inputx, indices, updates)
expected = np.array(
[
[[-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7], [-8, -8, -8, -8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
[[-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7], [-8, -8, -8, -8]],
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
]
)
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_traning
@pytest.mark.env_onecard
def test_scatter_nd_func_one_value():
inputx = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mstype.float32)
indices = Tensor(np.array([[0, 1]]), mstype.int32)
updates = Tensor(np.array([1.0]), mstype.float32)
# update
output = scatter_nd_func_net("update", inputx, indices, updates)
expected = np.array([[-0.1, 1.0, 3.6], [0.4, 0.5, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# add
output = scatter_nd_func_net("add", inputx, indices, updates)
expected = np.array([[-0.1, 1.3, 3.6], [0.4, 0.5, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
# sub
output = scatter_nd_func_net("sub", inputx, indices, updates)
expected = np.array([[-0.1, -0.7, 3.6], [0.4, 0.5, -3.2]])
np.testing.assert_array_almost_equal(output.asnumpy(), expected)
| 37.378723 | 86 | 0.612136 | 1,373 | 8,784 | 3.777859 | 0.11362 | 0.037016 | 0.048583 | 0.06015 | 0.746482 | 0.740891 | 0.712551 | 0.699826 | 0.690765 | 0.645845 | 0 | 0.080403 | 0.197177 | 8,784 | 234 | 87 | 37.538462 | 0.655133 | 0.082878 | 0 | 0.575 | 0 | 0 | 0.013337 | 0 | 0 | 0 | 0 | 0 | 0.1125 | 1 | 0.0625 | false | 0 | 0.04375 | 0 | 0.13125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
11bc0b3cb2807ff10941fab0ad8b5ff296d80b41 | 253 | py | Python | pages/wacs.py | irzaip/selevaporum | 05754f2a8152185f550e1135feb94fdc85e4046c | [
"MIT"
] | null | null | null | pages/wacs.py | irzaip/selevaporum | 05754f2a8152185f550e1135feb94fdc85e4046c | [
"MIT"
] | null | null | null | pages/wacs.py | irzaip/selevaporum | 05754f2a8152185f550e1135feb94fdc85e4046c | [
"MIT"
] | null | null | null | import collections
from numpy.core.defchararray import lower
import streamlit as st
import numpy as np
import pandas as pd
from pages import utils
def app():
st.title("WhatApp Customer Service")
st.subheader("Where automation matters") | 25.3 | 44 | 0.754941 | 36 | 253 | 5.305556 | 0.694444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.185771 | 253 | 10 | 44 | 25.3 | 0.927184 | 0 | 0 | 0 | 0 | 0 | 0.195918 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | true | 0 | 0.666667 | 0 | 0.777778 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
11d7cc28fca1672a8acd01df3e20ebc2577f0edc | 3,127 | py | Python | dipy/reconst/tests/test_odf.py | Garyfallidis/dipy | 4341b734995d6f51ac9c16df26a7de00c46f57ef | [
"BSD-3-Clause"
] | 3 | 2015-07-31T20:43:18.000Z | 2019-07-26T13:58:07.000Z | dipy/reconst/tests/test_odf.py | Garyfallidis/dipy | 4341b734995d6f51ac9c16df26a7de00c46f57ef | [
"BSD-3-Clause"
] | 9 | 2015-05-13T17:44:42.000Z | 2018-05-27T20:09:55.000Z | dipy/reconst/tests/test_odf.py | Garyfallidis/dipy | 4341b734995d6f51ac9c16df26a7de00c46f57ef | [
"BSD-3-Clause"
] | 3 | 2016-08-05T22:43:16.000Z | 2017-06-23T18:35:13.000Z | import numpy as np
from numpy.testing import assert_array_equal
from ..odf import OdfFit, OdfModel, gfa
from dipy.core.triangle_subdivide import (create_half_unit_sphere,
disperse_charges)
from nose.tools import (assert_almost_equal, assert_equal, assert_raises,
assert_true)
class SimpleOdfModel(OdfModel):
def __init__(self):
v, e, f = create_half_unit_sphere(4)
self.set_odf_vertices(v, e)
self.odf = (v * [1, 2, 3]).sum(-1)
def evaluate_odf(self, signal):
return self.odf
def test_OdfModelfit():
data = np.zeros((10,2))
# Test basic case
model = SimpleOdfModel()
odffit = model.fit(data, normalize_peaks=1)
assert_array_equal(odffit.gfa, gfa(model.odf))
assert_array_equal(odffit.peak_values[:, 0], 1.)
assert_array_equal(odffit.peak_values[:, 1:], 0.)
mn, mx = model.odf.min(), model.odf.max()
assert_array_equal(odffit.qa[:, 0], (mx - mn) / mx)
assert_array_equal(odffit.qa[:, 1:], 0.)
assert_array_equal(odffit.peak_indices[:, 0], 53)
assert_array_equal(odffit.peak_indices[:, 1:], -1)
# Test that odf array matches and is right shape
odffit = model.fit(data, return_odf=True)
expected_shape = (len(data), len(model.odf))
assert_equal(odffit.odf.shape, expected_shape)
assert_true((model.odf == odffit.odf).all())
assert_array_equal(odffit.peak_values[:, 0], model.odf.max())
# Test mask
mask = (np.arange(10) % 2) == 1
odffit = model.fit(data, mask=mask, normalize_peaks=True)
assert_array_equal(odffit.gfa[~mask], 0)
assert_array_equal(odffit.qa[~mask], 0)
assert_array_equal(odffit.peak_values[~mask], 0)
assert_array_equal(odffit.peak_indices[~mask], -1)
assert_array_equal(odffit.gfa[mask], gfa(model.odf))
assert_array_equal(odffit.peak_values[mask, 0], 1.)
assert_array_equal(odffit.peak_values[mask, 1:], 0.)
mn, mx = model.odf.min(), model.odf.max()
assert_array_equal(odffit.qa[mask, 0], (mx - mn) / mx)
assert_array_equal(odffit.qa[mask, 1:], 0.)
assert_array_equal(odffit.peak_indices[mask, 0], 53)
assert_array_equal(odffit.peak_indices[mask, 1:], -1)
def test_OdfModelgetpeaks():
model = SimpleOdfModel()
peaks = model.get_directions(None)
assert_array_equal(peaks, model.odf_vertices[[53]])
class TestOdfModel():
def test_angular_distance(self):
model = SimpleOdfModel()
assert_almost_equal(model.angular_distance_threshold, 45)
model.angular_distance_threshold = 60
assert_almost_equal(model.angular_distance_threshold, 60)
assert_almost_equal(model._cos_distance_threshold, .5)
def test_set_odf_vertices(self):
model = OdfModel()
v, e, f = create_half_unit_sphere(4)
model.set_odf_vertices(v, e)
assert_array_equal(v, model.odf_vertices)
assert_array_equal(e, model.odf_edges)
assert_array_equal(abs(v.dot(v.T)), model._distance_matrix)
assert_raises(ValueError, model.set_odf_vertices, v[:, :2], e)
assert_raises(ValueError, model.set_odf_vertices, v/2, e)
| 37.674699 | 73 | 0.688839 | 450 | 3,127 | 4.508889 | 0.213333 | 0.130113 | 0.189256 | 0.206013 | 0.507146 | 0.488911 | 0.445047 | 0.387876 | 0.217348 | 0.094628 | 0 | 0.021119 | 0.182283 | 3,127 | 82 | 74 | 38.134146 | 0.77239 | 0.023025 | 0 | 0.107692 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.507692 | 1 | 0.092308 | false | 0 | 0.076923 | 0.015385 | 0.215385 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
11e827caf9a2f6b79a2d0287af4086e1ef14f2b8 | 269 | py | Python | bindings/kepler.gl-jupyter/keplergl/__init__.py | sw1227/kepler.gl | 14c35fc048a745faab0c6770cab7a4625ccedda3 | [
"MIT"
] | 4,297 | 2019-05-04T01:29:14.000Z | 2022-03-31T19:28:10.000Z | bindings/kepler.gl-jupyter/keplergl/__init__.py | sw1227/kepler.gl | 14c35fc048a745faab0c6770cab7a4625ccedda3 | [
"MIT"
] | 968 | 2019-05-05T16:13:03.000Z | 2022-03-30T13:11:31.000Z | bindings/kepler.gl-jupyter/keplergl/__init__.py | sw1227/kepler.gl | 14c35fc048a745faab0c6770cab7a4625ccedda3 | [
"MIT"
] | 1,082 | 2019-05-04T15:55:24.000Z | 2022-03-30T16:27:53.000Z | from ._version import version_info, __version__
from .keplergl import *
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'keplergl-jupyter',
'require': 'keplergl-jupyter/extension'
}]
| 22.416667 | 47 | 0.624535 | 25 | 269 | 6.36 | 0.68 | 0.188679 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.237918 | 269 | 11 | 48 | 24.454545 | 0.77561 | 0 | 0 | 0 | 0 | 0 | 0.286245 | 0.096654 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | true | 0 | 0.222222 | 0.111111 | 0.444444 | 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 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 3 |
eeaca61d7f8a12d9407b89ba0d429021d517e4c0 | 179 | py | Python | problem0650.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | problem0650.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | problem0650.py | kmarcini/Project-Euler-Python | d644e8e1ec4fac70a9ab407ad5e1f0a75547c8d3 | [
"BSD-3-Clause"
] | null | null | null | ###########################
#
# #650 Divisors of Binomial Product - Project Euler
# https://projecteuler.net/problem=650
#
# Code by Kevin Marciniak
#
###########################
| 19.888889 | 51 | 0.502793 | 16 | 179 | 5.625 | 0.9375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.037975 | 0.117318 | 179 | 8 | 52 | 22.375 | 0.531646 | 0.608939 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
eef278f2f4e2c217a17b9bdf16a63771a1fe90a6 | 107 | py | Python | Guitarist.py | Stanels42/pythonic-garage-band | 7dfdec84073720998368cc2042bed011244c88ae | [
"MIT"
] | 1 | 2021-10-01T09:48:42.000Z | 2021-10-01T09:48:42.000Z | Guitarist.py | Stanels42/pythonic-garage-band | 7dfdec84073720998368cc2042bed011244c88ae | [
"MIT"
] | 1 | 2019-12-06T04:22:11.000Z | 2019-12-06T04:22:11.000Z | Guitarist.py | Stanels42/pythonic-garage-band | 7dfdec84073720998368cc2042bed011244c88ae | [
"MIT"
] | 1 | 2019-12-06T19:39:55.000Z | 2019-12-06T19:39:55.000Z | from Musician import Musician
class Guitarist(Musician):
solo = 'Guitar Sounds'
instrument = 'Guitar'
| 17.833333 | 29 | 0.747664 | 12 | 107 | 6.666667 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.168224 | 107 | 5 | 30 | 21.4 | 0.898876 | 0 | 0 | 0 | 0 | 0 | 0.17757 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 1 | 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 | 1 | 0 | 0 | 3 |
e10a689e78f45e04945a350aa7275406f0c3d7c2 | 72 | py | Python | numberstest.py | dreadnaught-ETES/school | 9faa2b6379db8f819872b8597896f5291812c5d6 | [
"CC0-1.0"
] | null | null | null | numberstest.py | dreadnaught-ETES/school | 9faa2b6379db8f819872b8597896f5291812c5d6 | [
"CC0-1.0"
] | null | null | null | numberstest.py | dreadnaught-ETES/school | 9faa2b6379db8f819872b8597896f5291812c5d6 | [
"CC0-1.0"
] | null | null | null | import math
result=(math.pow(3,2)+1)*(math.fmod(16,7))/7
print(result) | 24 | 45 | 0.680556 | 15 | 72 | 3.266667 | 0.733333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.104478 | 0.069444 | 72 | 3 | 46 | 24 | 0.626866 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0.333333 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
012152e2a37577150f9d63f073997bc92e0bc861 | 197 | py | Python | source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/setup.py | ebruun/python-samples | 746e5090f45659c60f01bf831a0308966d713b21 | [
"BSD-3-Clause"
] | 10 | 2020-12-03T22:59:39.000Z | 2022-03-27T07:31:42.000Z | source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/setup.py | ebruun/python-samples | 746e5090f45659c60f01bf831a0308966d713b21 | [
"BSD-3-Clause"
] | 55 | 2019-07-23T09:05:27.000Z | 2020-11-02T14:42:55.000Z | source/applications/advanced/hand_eye_calibration/ur_hand_eye_calibration/3rdParty/rtde-2.3.6/setup.py | ebruun/python-samples | 746e5090f45659c60f01bf831a0308966d713b21 | [
"BSD-3-Clause"
] | 4 | 2020-01-09T08:36:23.000Z | 2020-09-12T20:28:31.000Z | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="UrRtde",
packages=["rtde"],
version=1.0,
description="Real-Time Data Exchange (RTDE) python client + examples",
)
| 19.7 | 74 | 0.639594 | 24 | 197 | 5.25 | 0.916667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018987 | 0.19797 | 197 | 9 | 75 | 21.888889 | 0.778481 | 0.106599 | 0 | 0 | 0 | 0 | 0.373563 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.142857 | 0 | 0.142857 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
0124ac8c7a202aa897f92f830d9e99028d3f1d5a | 1,113 | py | Python | places/admin.py | moshthepitt/shulezote | e903a208948ab5294183e2a8c2dac9360a184654 | [
"MIT"
] | 2 | 2015-12-02T08:14:34.000Z | 2020-12-16T19:56:46.000Z | places/admin.py | moshthepitt/shulezote | e903a208948ab5294183e2a8c2dac9360a184654 | [
"MIT"
] | 4 | 2016-10-04T12:15:42.000Z | 2021-06-10T19:47:39.000Z | places/admin.py | moshthepitt/shulezote | e903a208948ab5294183e2a8c2dac9360a184654 | [
"MIT"
] | 1 | 2018-08-20T14:19:32.000Z | 2018-08-20T14:19:32.000Z | from django.contrib import admin
from places.models import County, Constituency, Province, District
from places.models import Division, Location, SubLocation, SchoolZone
class CountyAdmin(admin.ModelAdmin):
search_fields = ['name']
class ProvinceAdmin(admin.ModelAdmin):
search_fields = ['name']
class DistrictAdmin(admin.ModelAdmin):
search_fields = ['name']
class DivisionAdmin(admin.ModelAdmin):
search_fields = ['name']
class ConstituencyAdmin(admin.ModelAdmin):
search_fields = ['name']
class LocationAdmin(admin.ModelAdmin):
search_fields = ['name']
class SubLocationAdmin(admin.ModelAdmin):
search_fields = ['name']
class SchoolZoneAdmin(admin.ModelAdmin):
search_fields = ['name']
admin.site.register(County, CountyAdmin)
admin.site.register(Province, ProvinceAdmin)
admin.site.register(District, DistrictAdmin)
admin.site.register(Division, DivisionAdmin)
admin.site.register(Constituency, ConstituencyAdmin)
admin.site.register(Location, LocationAdmin)
admin.site.register(SubLocation, SubLocationAdmin)
admin.site.register(SchoolZone, SchoolZoneAdmin)
| 24.195652 | 69 | 0.779874 | 117 | 1,113 | 7.350427 | 0.25641 | 0.139535 | 0.195349 | 0.251163 | 0.32907 | 0.293023 | 0 | 0 | 0 | 0 | 0 | 0 | 0.111411 | 1,113 | 45 | 70 | 24.733333 | 0.869565 | 0 | 0 | 0.296296 | 0 | 0 | 0.028751 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.111111 | 0 | 0.703704 | 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 | 1 | 0 | 0 | 3 |
013d0a444d8fcc0b669cdc39b7c00090f97916cd | 110 | py | Python | iFarm/iFarmapp/urls.py | vmakar0v/smart-farm | 47bd7be4b40bbca57492ae5b8da09cc0635bfa2a | [
"Apache-2.0"
] | null | null | null | iFarm/iFarmapp/urls.py | vmakar0v/smart-farm | 47bd7be4b40bbca57492ae5b8da09cc0635bfa2a | [
"Apache-2.0"
] | null | null | null | iFarm/iFarmapp/urls.py | vmakar0v/smart-farm | 47bd7be4b40bbca57492ae5b8da09cc0635bfa2a | [
"Apache-2.0"
] | null | null | null | from django.urls import path
from . import views
urlpatterns = [
path('', views.home_P, name='home_P')
]
| 15.714286 | 41 | 0.681818 | 16 | 110 | 4.5625 | 0.625 | 0.136986 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | 110 | 6 | 42 | 18.333333 | 0.811111 | 0 | 0 | 0 | 0 | 0 | 0.054545 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.4 | 0 | 0.4 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
0145f0c317a0b7c0a803c27a724e95a60c8be847 | 226 | py | Python | example.py | austitech/Tokenizer | 005bd6772ef3298b222c05e3357bf22961978a57 | [
"MIT"
] | null | null | null | example.py | austitech/Tokenizer | 005bd6772ef3298b222c05e3357bf22961978a57 | [
"MIT"
] | null | null | null | example.py | austitech/Tokenizer | 005bd6772ef3298b222c05e3357bf22961978a57 | [
"MIT"
] | null | null | null | from tokenizer import StringTokenizer
from token import tokentype
text = open('test.ex', 'r').read()
t = StringTokenizer(text=text, tokentype=tokentype)
token_generator = t.create_token_generator()
print(token_generator)
| 18.833333 | 51 | 0.783186 | 29 | 226 | 5.965517 | 0.551724 | 0.242775 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.110619 | 226 | 11 | 52 | 20.545455 | 0.860697 | 0 | 0 | 0 | 0 | 0 | 0.035398 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0.166667 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
014640d43ebc7a1a3b58c97712655fc4e51f491b | 6,887 | py | Python | src/genie/libs/parser/iosxe/tests/ShowPlatformSoftwareFed/cli/equal/golden_output3_expected.py | balmasea/genieparser | d1e71a96dfb081e0a8591707b9d4872decd5d9d3 | [
"Apache-2.0"
] | 204 | 2018-06-27T00:55:27.000Z | 2022-03-06T21:12:18.000Z | src/genie/libs/parser/iosxe/tests/ShowPlatformSoftwareFed/cli/equal/golden_output3_expected.py | balmasea/genieparser | d1e71a96dfb081e0a8591707b9d4872decd5d9d3 | [
"Apache-2.0"
] | 468 | 2018-06-19T00:33:18.000Z | 2022-03-31T23:23:35.000Z | src/genie/libs/parser/iosxe/tests/ShowPlatformSoftwareFed/cli/equal/golden_output3_expected.py | balmasea/genieparser | d1e71a96dfb081e0a8591707b9d4872decd5d9d3 | [
"Apache-2.0"
] | 309 | 2019-01-16T20:21:07.000Z | 2022-03-30T12:56:41.000Z | expected_output ={
"lentry_label": {
24: {
"aal": {
"deagg_vrf_id": 0,
"eos0": {"adj_hdl": "0xf9000002", "hw_hdl": "0x7f02737e2ca8"},
"eos1": {"adj_hdl": "0xf9000002", "hw_hdl": "0x7f02737e2a98"},
"id": 1996488716,
"lbl": 24,
"lspa_handle": "0",
},
"adj": {
109: {
"adj": "0xdf000026",
"ifnum": "0x33",
"link_type": "MPLS",
"si": "0x7f0273423ab8",
},
139: {
"adj": "0x5c000037",
"ifnum": "0x36",
"link_type": "MPLS",
"si": "0x7f02737a2348",
},
},
"backwalk_cnt": 0,
"label": {
31: {
"adj_handle": "0x62000061",
"bwalk_cnt": 0,
"collapsed_oce": 0,
"flags": {"0x1": ["REAL"]},
"label_aal": {
1644167265: {
"adj_flags": "0",
"di_id": "0x526d",
"dmac": "0027.90bf.2ee7",
"label_type": 2,
"lbl": 0,
"link_type": 2,
"phdl": "0xab000447",
"ref_cnt": 1,
"rewrite_type": "PSH1(119)",
"ri": "0x7f02737e8a98",
"ri_id": "0x4e",
"si": "0x7f02737c1b08",
"si_id": "0x4034",
"smac": "00a7.42d6.c41f",
"sub_type": 0,
"vlan_id": 0,
"vrf_id": 0,
}
},
"link_type": "MPLS",
"local_adj": 0,
"local_label": 24,
"modify_cnt": 0,
"olbl_changed": 0,
"outlabel": "(34, 0)",
"pdflags": {"0": ["INSTALL_HW_OK"]},
"subwalk_cnt": 0,
"unsupported_recursion": 0,
},
32: {
"adj_handle": "0x89000062",
"bwalk_cnt": 0,
"collapsed_oce": 0,
"flags": {"0x1": ["REAL"]},
"label_aal": {
2298478690: {
"adj_flags": "0",
"di_id": "0x5268",
"dmac": "00a7.42ce.f69f",
"label_type": 2,
"lbl": 0,
"link_type": 2,
"phdl": "0x7c000442",
"ref_cnt": 1,
"rewrite_type": "PSH1(119)",
"ri": "0x7f027379b138",
"ri_id": "0x24",
"si": "0x7f02737a4d58",
"si_id": "0x4035",
"smac": "00a7.42d6.c41f",
"sub_type": 0,
"vlan_id": 0,
"vrf_id": 0,
}
},
"link_type": "MPLS",
"local_adj": 0,
"local_label": 24,
"modify_cnt": 0,
"olbl_changed": 0,
"outlabel": "(29, 0)",
"pdflags": {"0": ["INSTALL_HW_OK"]},
"subwalk_cnt": 0,
"unsupported_recursion": 0,
},
},
"lb": {
38: {
"aal": {
"af": 0,
"ecr_id": 4177526786,
"ecr_type": "0",
"ecrh": "0x7f02737e49f8(28:2)",
"hwhdl": ":1937656312 "
"::0x7f02737e11c8,0x7f02737e2728,0x7f02737e11c8,0x7f02737e2728",
"ref": 3,
},
"bwalk": {"in_prog": 0, "nested": 0, "req": 0},
"bwalk_cnt": 0,
"ecr_map_objid": 0,
"ecrh": "0xf9000002",
"finish_cnt": 0,
"flags": "0",
"link_type": "IP",
"local_label": 24,
"modify_cnt": 0,
"mpls_ecr": 1,
"num_choices": 2,
"old_ecrh": "0",
"path_inhw": 2,
"subwalk_cnt": 0,
}
},
"lentry_hdl": "0x7700000c",
"lspa_handle": "0",
"modify_cnt": 8,
"nobj": ["LB", " 38"],
"sw_enh_ecr_scale": {
38: {
"adjs": 2,
"ecr_adj": {
1644167265: {
"adj_lentry": "[eos0:0x7f02734123b8 "
"eos1:0x7f02737ec5e8]",
"di_id": 20499,
"is_mpls_adj": 1,
"l3adj_flags": "0x100000",
"recirc_adj_id": 3120562239,
"rih": "0x7f02737e0bf8(74)",
"sih": "0x7f02737e11c8(182)",
},
2298478690: {
"adj_lentry": "[eos0:0x7f02737e6dd8 "
"eos1:0x7f02737b21d8]",
"di_id": 20499,
"is_mpls_adj": 1,
"l3adj_flags": "0x100000",
"recirc_adj_id": 1442840640,
"rih": "0x7f02737dcbe8(75)",
"sih": "0x7f02737e2728(183)",
},
2483028067: {
"di_id": 20499,
"rih": "0x7f02737eaa18(52)",
"sih": "0x7f02737e4c08(170)",
},
},
"ecr_hwhdl": "0x7f02737e49f8",
"ecrhdl": "0xf9000002",
"eos": 1,
"llabel": 24,
"mixed_adj": "0",
"mod_cnt": 0,
"pmismatch": 0,
"pordermatch": 0,
"prev_npath": 0,
"reprogram_hw": "0",
}
},
}
}
}
| 38.909605 | 88 | 0.283287 | 425 | 6,887 | 4.350588 | 0.381176 | 0.02596 | 0.024337 | 0.029205 | 0.368848 | 0.332071 | 0.320173 | 0.320173 | 0.290968 | 0.261763 | 0 | 0.231616 | 0.591259 | 6,887 | 176 | 89 | 39.130682 | 0.425222 | 0 | 0 | 0.380682 | 0 | 0 | 0.262233 | 0.014956 | 0 | 0 | 0.073762 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
0146de801330617849875f5bc5ee04e2b90625fa | 3,610 | py | Python | tests/test_simulator_utility.py | tancheng/cache-sim | adfcbec961543a8424988cbadacb575c551f3cc3 | [
"MIT"
] | 27 | 2016-02-06T20:49:19.000Z | 2021-11-02T03:11:26.000Z | tests/test_simulator_utility.py | tancheng/cache-sim | adfcbec961543a8424988cbadacb575c551f3cc3 | [
"MIT"
] | 5 | 2020-02-24T18:57:11.000Z | 2021-09-01T00:27:18.000Z | tests/test_simulator_utility.py | tancheng/cache-sim | adfcbec961543a8424988cbadacb575c551f3cc3 | [
"MIT"
] | 16 | 2016-02-06T20:49:06.000Z | 2022-01-14T02:49:14.000Z | #!/usr/bin/env python3
import nose.tools as nose
from cachesimulator.bin_addr import BinaryAddress
from cachesimulator.word_addr import WordAddress
def test_get_bin_addr_unpadded():
"""get_bin_addr should return unpadded binary address of word address"""
nose.assert_equal(
BinaryAddress(word_addr=WordAddress(180)),
'10110100')
def test_get_bin_addr_padded():
"""get_bin_addr should return padded binary address of word address"""
nose.assert_equal(
BinaryAddress(word_addr=WordAddress(44), num_addr_bits=8),
'00101100')
def test_prettify_bin_addr_16_bit():
"""prettify_bin_addr should prettify 8-bit string into groups of 3"""
nose.assert_equal(
BinaryAddress.prettify('1010101110101011', min_bits_per_group=3),
'1010 1011 1010 1011')
def test_prettify_bin_addr_8_bit():
"""prettify_bin_addr should prettify 8-bit string into groups of 3"""
nose.assert_equal(
BinaryAddress.prettify('10101011', min_bits_per_group=3),
'1010 1011')
def test_prettify_bin_addr_7_bit():
"""prettify_bin_addr should prettify 7-bit string into groups of 3"""
nose.assert_equal(
BinaryAddress.prettify('1011010', min_bits_per_group=3),
'101 1010')
def test_prettify_bin_addr_6_bit():
"""prettify_bin_addr should prettify 6-bit string into groups of 3"""
nose.assert_equal(
BinaryAddress.prettify('101011', min_bits_per_group=3),
'101 011')
def test_prettify_bin_addr_5_bit():
"""prettify_bin_addr should prettify 5-bit string into groups of 3"""
nose.assert_equal(
BinaryAddress.prettify('10110', min_bits_per_group=3),
'10110')
def test_get_tag_5_bit():
"""get_tag should return correct 5 tag bits for an address"""
nose.assert_equal(
BinaryAddress('10110100').get_tag(num_tag_bits=5),
'10110')
def test_get_tag_0_bit():
"""get_tag should return None if no bits are allocated to a tag"""
nose.assert_is_none(
BinaryAddress('10110100').get_tag(num_tag_bits=0))
def test_get_index_2_bit():
"""get_index should return correct 2 index bits for an address"""
nose.assert_equal(
BinaryAddress('11111101').get_index(
num_offset_bits=1, num_index_bits=2), '10')
def test_get_index_0_bit():
"""get_index should return None if no bits are allocated to an index"""
nose.assert_is_none(
BinaryAddress('11111111').get_index(
num_offset_bits=1, num_index_bits=0))
def test_get_offset_2_bit():
"""get_offset should return correct 2 offset bits for an address"""
nose.assert_equal(
BinaryAddress('11111101').get_offset(num_offset_bits=2), '01')
def test_get_offset_0_bit():
"""get_offset should return None if no bits are allocated to an offset"""
nose.assert_is_none(
BinaryAddress('10110100').get_offset(num_offset_bits=0))
def test_get_consecutive_words_1_word():
"""get_consecutive_words should return same word for 1-word blocks"""
nose.assert_equal(
WordAddress(23).get_consecutive_words(num_words_per_block=1),
[23])
def test_get_consecutive_words_2_word():
"""get_consecutive_words should return correct words for 2-word blocks"""
nose.assert_equal(
WordAddress(22).get_consecutive_words(num_words_per_block=2),
[22, 23])
def test_get_consecutive_words_4_word():
"""get_consecutive_words should return correct words for 4-word blocks"""
nose.assert_equal(
WordAddress(21).get_consecutive_words(num_words_per_block=4),
[20, 21, 22, 23])
| 31.12069 | 77 | 0.713573 | 526 | 3,610 | 4.564639 | 0.163498 | 0.046647 | 0.081216 | 0.116618 | 0.835485 | 0.66389 | 0.525198 | 0.391087 | 0.372761 | 0.288213 | 0 | 0.078465 | 0.184488 | 3,610 | 115 | 78 | 31.391304 | 0.737092 | 0.289751 | 0 | 0.28125 | 0 | 0 | 0.065646 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0.25 | true | 0 | 0.046875 | 0 | 0.296875 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
0176442d3722d717b493ddc5a58d8dea96dab8d8 | 521 | py | Python | UNF/data/field.py | waterzxj/UNF | 5eda8e7c60116735f595f4b21b24547708b36cf5 | [
"Apache-2.0"
] | 86 | 2020-02-23T13:38:11.000Z | 2022-03-01T12:09:28.000Z | UNF/data/field.py | Dreamliking/UNF | 5eda8e7c60116735f595f4b21b24547708b36cf5 | [
"Apache-2.0"
] | 2 | 2020-04-20T08:33:05.000Z | 2020-05-13T13:43:08.000Z | UNF/data/field.py | Dreamliking/UNF | 5eda8e7c60116735f595f4b21b24547708b36cf5 | [
"Apache-2.0"
] | 14 | 2020-03-07T05:21:44.000Z | 2021-05-09T16:57:23.000Z | #coding:utf-8
"""
对处理数据域的抽象
"""
from torchtext.data.field import RawField, Field, LabelField
class WordField(Field):
"""
数据词域的抽象
"""
def __init__(self, **kwarg):
print(kwarg)
super(WordField, self).__init__(**kwarg)
class CharField(Field):
"""
数据字符域的抽象
"""
def __init__(self, **kwarg):
super(CharField, self).__init__(**kwarg)
class SiteField(Field):
"""
站点域的抽象
"""
def __init__(self, **kwarg):
super(SiteField, self).__init__(**kwarg)
| 17.965517 | 60 | 0.596929 | 53 | 521 | 5.415094 | 0.45283 | 0.073171 | 0.114983 | 0.167247 | 0.146341 | 0 | 0 | 0 | 0 | 0 | 0 | 0.002532 | 0.241843 | 521 | 28 | 61 | 18.607143 | 0.724051 | 0.088292 | 0 | 0.272727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.272727 | false | 0 | 0.090909 | 0 | 0.636364 | 0.090909 | 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 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 3 |
6d82b1a75112fd7c369738ca11d64f3111ccd886 | 234 | py | Python | Ch3/same_name3.py | dmdinh22/ATBS | 3ddd331757cc434faa5f27997b178f8a39e3b5d2 | [
"MIT"
] | null | null | null | Ch3/same_name3.py | dmdinh22/ATBS | 3ddd331757cc434faa5f27997b178f8a39e3b5d2 | [
"MIT"
] | null | null | null | Ch3/same_name3.py | dmdinh22/ATBS | 3ddd331757cc434faa5f27997b178f8a39e3b5d2 | [
"MIT"
] | null | null | null | def spam():
global eggs
eggs = "spam" # this is the global var
def bacon():
eggs = "bacon" # this is a local var
def ham():
print(eggs) # this is the global var
eggs = 42 # this is the global var
spam()
print(eggs)
| 16.714286 | 42 | 0.619658 | 39 | 234 | 3.717949 | 0.358974 | 0.165517 | 0.186207 | 0.310345 | 0.372414 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011696 | 0.269231 | 234 | 13 | 43 | 18 | 0.836257 | 0.376068 | 0 | 0.2 | 0 | 0 | 0.06383 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.3 | false | 0 | 0 | 0 | 0.3 | 0.2 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
6d86c4391d19b15cd170a51c7f4c70bd4a42f337 | 265 | py | Python | app/table.py | aamnv/fred-cli | 86810e93242a90dd8ed1fbbd8999275dbd1da1cc | [
"MIT"
] | 8 | 2020-08-28T15:15:14.000Z | 2021-02-02T07:54:02.000Z | app/table.py | aamnv/fred-cli | 86810e93242a90dd8ed1fbbd8999275dbd1da1cc | [
"MIT"
] | null | null | null | app/table.py | aamnv/fred-cli | 86810e93242a90dd8ed1fbbd8999275dbd1da1cc | [
"MIT"
] | 1 | 2021-03-05T10:27:32.000Z | 2021-03-05T10:27:32.000Z | from tabulate import tabulate
def make_table(series_data):
table = tabulate(series_data, headers='keys', tablefmt='github')
return table
def make_data_table_footer(series_metadata):
table = tabulate(series_metadata, headers='keys')
return table | 22.083333 | 68 | 0.754717 | 34 | 265 | 5.647059 | 0.441176 | 0.072917 | 0.197917 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.154717 | 265 | 12 | 69 | 22.083333 | 0.857143 | 0 | 0 | 0.285714 | 0 | 0 | 0.052632 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.285714 | false | 0 | 0.142857 | 0 | 0.714286 | 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 | 1 | 0 | 0 | 3 |
6dace628e580ac178333748655d75c5708c2a7c6 | 502 | py | Python | main/views/admin/dashboard/dashboard_controller.py | tiberiucorbu/av-website | f26f44a367d718316442506b130a7034697670b8 | [
"MIT"
] | null | null | null | main/views/admin/dashboard/dashboard_controller.py | tiberiucorbu/av-website | f26f44a367d718316442506b130a7034697670b8 | [
"MIT"
] | null | null | null | main/views/admin/dashboard/dashboard_controller.py | tiberiucorbu/av-website | f26f44a367d718316442506b130a7034697670b8 | [
"MIT"
] | null | null | null | # coding: utf-8
from flask.ext import wtf
import flask
import wtforms
import auth
import config
import model
import util
from main import app
###############################################################################
# Admin Stuff
###############################################################################
@app.route('/admin/')
@auth.admin_required
def admin():
return flask.render_template(
'admin/dashboard/dashboard.html',
title='Admin',
html_class='admin',
)
| 19.307692 | 79 | 0.482072 | 47 | 502 | 5.085106 | 0.574468 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.002299 | 0.133466 | 502 | 25 | 80 | 20.08 | 0.547126 | 0.049801 | 0 | 0 | 0 | 0 | 0.148734 | 0.094937 | 0 | 0 | 0 | 0 | 0 | 1 | 0.0625 | true | 0 | 0.5 | 0.0625 | 0.625 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
6db2c1ba2f0973e1c395b6375ee992a3997ea0f6 | 2,967 | py | Python | mlib/boot/lang.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
] | 1 | 2020-06-16T17:26:45.000Z | 2020-06-16T17:26:45.000Z | mlib/boot/lang.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
] | null | null | null | mlib/boot/lang.py | mgroth0/mlib | 0442ed51eab417b6972f885605afd351892a3a9a | [
"MIT"
] | null | null | null | import collections
import os
from pathlib import Path
def setter(f):
return property(None, f)
enum = enumerate
def esorted(l):
return enum(sorted(l))
def cn(o): return o.__class__.__name__
def strcmp(s1, s2, ignore_case=False):
if ignore_case:
return s1.lower() == s2.lower()
return s1 == s2
def inv_map(d): return {v: k for k, v in d.items()}
def num2str(num):
return str(num)
def isblank(s):
return len(s.replace(' ', '').replace('\t', '').replace('\n', '').replace('\r', '')) == 0
def notblank(s): return not isblank(s)
def isblankstr(s): return isstr(s) and isblank(s)
def composed(*decs):
# https://stackoverflow.com/questions/5409450/can-i-combine-two-decorators-into-a-single-one-in-python
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
def listkeys(d):
from mlib.boot.stream import li
return li(d.keys())
def listvalues(d):
from mlib.boot.stream import li
return li(d.values())
def all_or_break(li, lamb):
for o in li:
if not lamb(o):
return False
return True
def strrep(s, s1, s2):
return s.replace(s1, s2)
def classname(o):
return o.__class__.__name__
def simple_classname(o):
return classname(o).split('.')[-1]
def isa(o, name):
return classname(o) == name
def isnumber(o):
import numpy as np
return isinstsafe(o, int) or isinstsafe(o, float) or isinstsafe(o, np.long)
def will_break_numpy(o):
return not isnumber(o) and not isstr(o) and not isbool(o) and not islist(o)
def isinstsafe(o, c):
from mlib.inspect import all_superclasses
return isinstance(o, c) or c in all_superclasses(o.__class__)
def isslice(v):
return isinstance(v, slice)
def isint(v):
import numpy as np
return isinstance(v, int) or isinstance(v, np.int64)
def isdict(v):
return isinstance(v, dict)
def isdictsafe(v):
return isinstance(v, collections.Mapping)
def islistsafe(v):
return isinstance(v, collections.Sequence)
def iscls(v):
return isinstance(v, type)
def isfun(v):
return callable(v) and not iscls(v)
def isdigit(s):
return s.isdigit()
def isstr(v):
from mlib.str import StringExtension
return isinstance(v, str) or isinstance(v, StringExtension)
def istuple(v):
return isinstance(v, tuple)
def islist(v):
return isinstance(v, list)
def isbool(v):
return isinstance(v, bool)
def isitr(v):
import typing
return isinstance(v, collections.Iterable) or isinstance(v, typing.Iterable) # not sure if I need both
def is_non_str_itr(o):
return isitr(o) and not isstr(o)
def addpath(p):
import sys
sys.path.append(p)
def ismac():
import platform
return platform.system() == 'Darwin'
def islinux():
import platform
return platform.system() == 'Linux'
def pwd(): return os.getcwd()
HOME = str(Path.home())
DESKTOP = os.path.join(HOME, 'Desktop')
DEBUG = True
NORMAL = False
| 20.894366 | 107 | 0.664307 | 456 | 2,967 | 4.25 | 0.335526 | 0.079463 | 0.096491 | 0.074303 | 0.157895 | 0.057792 | 0.037152 | 0.037152 | 0.037152 | 0.037152 | 0 | 0.009334 | 0.205595 | 2,967 | 141 | 108 | 21.042553 | 0.812898 | 0.041793 | 0 | 0.061224 | 0 | 0 | 0.009155 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.397959 | false | 0 | 0.132653 | 0.255102 | 0.887755 | 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 | 1 | 0 | 0 | 3 |
6dea9c8146d56fa2b4a9cdd2da0bad21ab08f14c | 1,078 | py | Python | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | test/solutions/test_checkout.py | DPNT-Sourcecode/CHK-mxxq01 | 85be1ef3e87a6490d1490b64596de25d7e3cb60e | [
"Apache-2.0"
] | null | null | null | import unittest
from lib.solutions.checkout import checkout
class TestSum(unittest.TestCase):
def test_checkout(self):
self.assertEqual(checkout("ABC"), 50+30+20)
self.assertEqual(checkout("ABCCCD"), 50+30+20*3+15)
self.assertEqual(checkout("AAA"), 130)
self.assertEqual(checkout("AAAAB"), 130+50+30)
self.assertEqual(checkout("AAAAAAAAB"), 130+200+30)
self.assertEqual(checkout("EEBB"), 40*2+30)
self.assertEqual(checkout("EEBBB"), 40*2+45)
self.assertEqual(checkout("EEEEBBB"), 40*4+30)
self.assertEqual(checkout("FF"), 20)
self.assertEqual(checkout("FFF"), 20)
self.assertEqual(checkout("FFFFF"), 40)
self.assertEqual(checkout("FFFFFF"), 40)
def test_group_buy(self):
self.assertEqual(checkout("ZZTSR"), 50+20+45)
self.assertEqual(checkout("ZZZ"), 45)
self.assertEqual(checkout("ZZZZ"), 45+21)
self.assertEqual(checkout("ZZZX"), 45+17)
self.assertEqual(checkout("ZZZZXS"), 45*2)
if __name__ == '__main__':
unittest.main()
| 35.933333 | 59 | 0.646568 | 132 | 1,078 | 5.19697 | 0.363636 | 0.37172 | 0.569971 | 0.145773 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.085812 | 0.189239 | 1,078 | 29 | 60 | 37.172414 | 0.699085 | 0 | 0 | 0 | 0 | 0 | 0.081633 | 0 | 0 | 0 | 0 | 0 | 0.708333 | 1 | 0.083333 | false | 0 | 0.083333 | 0 | 0.208333 | 0 | 0 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
6df1e73647be403745ebe4c69e672889f9a73f91 | 162 | py | Python | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | 8 | 2018-12-15T16:41:21.000Z | 2021-10-03T21:19:11.000Z | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | null | null | null | obdlive/obd/urls.py | hoke-t/OBDLive | 524fb53fad5924b8371d2fce8d7a482bd8112362 | [
"MIT"
] | 1 | 2020-07-27T18:15:58.000Z | 2020-07-27T18:15:58.000Z | from django.urls import path
from . import views
urlpatterns = [
path('', views.dashboard, name='dashboard'),
path('dtcs/', views.dtcs, name='dtcs'),
]
| 18 | 48 | 0.654321 | 20 | 162 | 5.3 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.17284 | 162 | 8 | 49 | 20.25 | 0.791045 | 0 | 0 | 0 | 0 | 0 | 0.111111 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
6df6c6b55d592803eb12aa9541c59df303c76397 | 155 | py | Python | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | app/core/urls.py | kmnkit/web-todo | e06e42f5b68b2b9473fad820857634a9c5c0dadf | [
"MIT"
] | null | null | null | from django.urls import path
from teams.views import TeamListView
app_name = "core"
urlpatterns = [
path("", TeamListView.as_view(), name="home"),
]
| 17.222222 | 50 | 0.709677 | 20 | 155 | 5.4 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.154839 | 155 | 8 | 51 | 19.375 | 0.824427 | 0 | 0 | 0 | 0 | 0 | 0.051613 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
6df9c88395294e4e4698984383fb2662d33b928e | 2,617 | py | Python | qtum_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 5 | 2018-07-31T07:37:09.000Z | 2019-05-27T04:40:38.000Z | eth_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 4 | 2018-08-01T11:11:54.000Z | 2022-03-11T23:20:53.000Z | qtum_bridge/R8Blockchain/ethereumblockchain.py | Robin8Put/pmes | 338bec94162098f05b75bad035417317e1252fd2 | [
"Apache-2.0"
] | 5 | 2018-06-09T07:42:04.000Z | 2018-12-28T21:15:52.000Z | from web3 import Web3, IPCProvider, HTTPProvider
from web3.middleware import geth_poa_middleware
from R8Blockchain.blockchain_handler import BlockchainHandler
from hashlib import sha256
import codecs
from web3.contract import ConciseContract
class EthereumBlockchain(BlockchainHandler):
def __init__(self, eth_rpc):
self.w3 = eth_rpc
self.w3.middleware_stack.inject(geth_poa_middleware, layer=0)
self.decode_hex = codecs.getdecoder("hex_codec")
self.encode_hex = codecs.getencoder("hex_codec")
@classmethod
def from_ipc_path(cls, ipc_path):
return cls(Web3(IPCProvider(ipc_path)))
@classmethod
def from_http_provider(cls, http_provider):
return cls(Web3(HTTPProvider(http_provider)))
def reload_http_provider(self, http_provider):
self.w3 = Web3(HTTPProvider(http_provider))
def reload_ipc_path(self, ipc_path):
self.w3 = Web3(IPCProvider(ipc_path))
def get_last_block_hash(self):
return self.encode_hex(self.w3.eth.getBlock('latest').hash)[0].decode()
def get_second_last_block_hash(self):
return self.encode_hex(self.w3.eth.getBlock(self.get_block_count()-1).hash)[0].decode()
def get_last_block_id(self):
return self.get_block_id(self.get_block_count())
def get_second_last_block_id(self):
return self.get_block_id(self.get_block_count()-1)
def get_block_id(self, height):
block_hash = self.get_block_hash(height)
l = sha256(self.decode_hex(block_hash)[0]).hexdigest()
r = hex(height)
return l[0:10] + r[2:].rjust(10, '0')
def get_block_hash(self, height):
return self.encode_hex(self.w3.eth.getBlock(height).hash)[0].decode()
def get_block_count(self):
return self.w3.eth.blockNumber
def get_unspent(self):
accounts = self.w3.personal.listAccounts
return {acc: self.w3.eth.getBalance(acc) for acc in accounts}
def get_accounts(self):
return self.w3.personal.listAccounts
def get_balance(self):
res = 0
for account in self.get_accounts():
res += self.w3.eth.getBalance(account)
return res
def from_hex_address(self, address):
return address
if __name__ == '__main__':
eth_blockchain = EthereumBlockchain.from_ipc_path(ipc_path='/home/artem/.ethereum/rinkeby/geth.ipc')
res = eth_blockchain.get_last_block_hash()
print(eth_blockchain.get_block_count())
res = eth_blockchain.get_block_hash(1200)
print(res)
print(eth_blockchain.get_balance())
print(eth_blockchain.get_unspent())
| 30.788235 | 104 | 0.704241 | 361 | 2,617 | 4.822715 | 0.227147 | 0.041356 | 0.036186 | 0.03274 | 0.234348 | 0.183802 | 0.141298 | 0.141298 | 0.12062 | 0.12062 | 0 | 0.021678 | 0.189148 | 2,617 | 84 | 105 | 31.154762 | 0.798775 | 0 | 0 | 0.033898 | 0 | 0 | 0.027141 | 0.014526 | 0 | 0 | 0 | 0 | 0 | 1 | 0.271186 | false | 0 | 0.101695 | 0.169492 | 0.610169 | 0.067797 | 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 | 1 | 0 | 0 | 3 |
09735c1ad6c8d9ce147599ce6ceedfef6549b227 | 116 | py | Python | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p04st05С05_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p04st05С05_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p04st05С05_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | n = float(input())
m = float(input())
max = max(n, m)
min = min(n, m)
time = max - min
print(time // 60, time % 60)
| 16.571429 | 28 | 0.560345 | 22 | 116 | 2.954545 | 0.409091 | 0.307692 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.043956 | 0.215517 | 116 | 6 | 29 | 19.333333 | 0.67033 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.166667 | 1 | 0 | 0 | null | 1 | 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 | 3 |
097d4bce40bb327df22e412c466f7654eaea0ad3 | 282 | py | Python | code/chapter-2/exercise2_8.py | Kevin-Oudai/python-solutions | d67f6b14723b000fec0011c3e8156b805eb288f7 | [
"MIT"
] | null | null | null | code/chapter-2/exercise2_8.py | Kevin-Oudai/python-solutions | d67f6b14723b000fec0011c3e8156b805eb288f7 | [
"MIT"
] | null | null | null | code/chapter-2/exercise2_8.py | Kevin-Oudai/python-solutions | d67f6b14723b000fec0011c3e8156b805eb288f7 | [
"MIT"
] | null | null | null | mass = eval(input("Enter the amount of water in kilograms: "))
initial_temp = eval(input("Enter the initial temperature: "))
final_temp = eval(input("Enter the final temperature: "))
energy = mass * (final_temp - initial_temp) * 4184
print("The energy needed is {}".format(energy))
| 47 | 62 | 0.72695 | 40 | 282 | 5.025 | 0.5 | 0.134328 | 0.208955 | 0.253731 | 0.208955 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016393 | 0.134752 | 282 | 5 | 63 | 56.4 | 0.807377 | 0 | 0 | 0 | 0 | 0 | 0.43617 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 0 | 0 | 0 | null | 0 | 1 | 1 | 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 | 3 |
097f69d052a1e922b006db68fee1c80d1a486da1 | 1,482 | py | Python | kaggle-lung-cancer-approach2/modules/ctscan.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | 2 | 2017-06-05T17:25:55.000Z | 2018-02-04T04:01:13.000Z | kaggle-lung-cancer-approach2/modules/ctscan.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | null | null | null | kaggle-lung-cancer-approach2/modules/ctscan.py | flaviostutz/datascience-snippets | 768083c4eda972bc1f6548baa86751e0405bda9b | [
"MIT"
] | null | null | null | import glob
import SimpleITK as sitk
import numpy as np
class CTScanMhd(object):
def __init__(self, base_dir, filename):
self.filename = filename
self.coords = None
self.base_dir = base_dir
path = glob.glob(self.base_dir + '/*/' + self.filename + '.mhd')
self.ds = sitk.ReadImage(path[0])
self.image = sitk.GetArrayFromImage(self.ds)
def set_coords(self, coords):
self.coords = (coords[2], coords[1], coords[0])
def get_resolution(self):
return self.ds.GetSpacing()
def get_origin(self):
return self.ds.GetOrigin()
def get_ds(self):
return self.ds
def get_voxel_coords(self):
origin = self.get_origin()
resolution = self.get_resolution()
voxel_coords = [np.absolute(self.coords[j]-origin[j])/resolution[j] \
for j in range(len(self.coords))]
return tuple(voxel_coords)
def get_image(self):
return self.image
def get_subimage(self, center, dims):
self.set_coords(center)
x, y, z = self.get_voxel_coords()
subImage = self.image[int(z-dims[0]/2):int(z+dims[0]/2), int(y-dims[1]/2):int(y+dims[1]/2), int(x-dims[2]/2):int(x+dims[2]/2)]
return subImage
def get_normalized_image(self, minHU, maxHU):
#maxHU = 400.
#minHU = -1000.
img = (self.image - minHU) / (maxHU - minHU)
img[img>1] = 1.
img[img<0] = 0.
return img
| 30.244898 | 134 | 0.593117 | 208 | 1,482 | 4.105769 | 0.264423 | 0.04918 | 0.065574 | 0.056206 | 0.070258 | 0.070258 | 0.028103 | 0 | 0 | 0 | 0 | 0.024885 | 0.267881 | 1,482 | 49 | 135 | 30.244898 | 0.762212 | 0.017544 | 0 | 0 | 0 | 0 | 0.004811 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.243243 | false | 0 | 0.081081 | 0.108108 | 0.540541 | 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 | 1 | 0 | 0 | 3 |
09871d53ff57c8147e01e850c7f2f9d9467db849 | 89,305 | py | Python | tests/unit/pywbemcli/test_class_cmds.py | pywbem/pywbemtools | 6b7c3f124324fd3ab7cffb82bc98c8f9555317e4 | [
"Apache-2.0"
] | 8 | 2017-04-01T13:55:00.000Z | 2022-03-15T18:28:47.000Z | tests/unit/pywbemcli/test_class_cmds.py | pywbem/pywbemtools | 6b7c3f124324fd3ab7cffb82bc98c8f9555317e4 | [
"Apache-2.0"
] | 918 | 2017-03-03T14:29:03.000Z | 2022-03-29T15:32:16.000Z | tests/unit/pywbemcli/test_class_cmds.py | pywbem/pywbemtools | 6b7c3f124324fd3ab7cffb82bc98c8f9555317e4 | [
"Apache-2.0"
] | 2 | 2020-01-17T15:56:46.000Z | 2020-02-12T18:49:30.000Z | # Copyright 2018 IBM Corp. 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.
"""
Tests the class command
"""
from __future__ import absolute_import, print_function
import sys
import os
from packaging.version import parse as parse_version
import pytest
from pywbem import __version__ as pywbem_version
from .cli_test_extensions import CLITestsBase, PYWBEM_0, \
FAKEURL_STR
from .common_options_help_lines import CMD_OPTION_NAMES_ONLY_HELP_LINE, \
CMD_OPTION_HELP_HELP_LINE, CMD_OPTION_SUMMARY_HELP_LINE, \
CMD_OPTION_NAMESPACE_HELP_LINE, CMD_OPTION_PROPERTYLIST_HELP_LINE, \
CMD_OPTION_INCLUDE_CLASSORIGIN_HELP_LINE, \
CMD_OPTION_LOCAL_ONLY_CLASS_HELP_LINE, CMD_OPTION_NO_QUALIFIERS_HELP_LINE, \
CMD_OPTION_MULTIPLE_NAMESPACE_HELP_LINE, \
CMD_OPTION_ASSOCIATION_FILTER_HELP_LINE, \
CMD_OPTION_INDICATION_FILTER_HELP_LINE, \
CMD_OPTION_EXPERIMENTAL_FILTER_HELP_LINE, \
CMD_OPTION_DEPRECATED_FILTER_HELP_LINE, \
CMD_OPTION_SINCE_FILTER_HELP_LINE, \
CMD_OPTION_SCHEMA_FILTER_HELP_LINE, \
CMD_OPTION_SUBCLASSOF_FILTER_HELP_LINE, \
CMD_OPTION_LEAFCLASSES_FILTER_HELP_LINE
_PYWBEM_VERSION = parse_version(pywbem_version)
# pywbem 1.0.0 or later
PYWBEM_1_0_0 = _PYWBEM_VERSION.release >= (1, 0, 0)
# Mock scripts with setup() function are supported
MOCK_SETUP_SUPPORTED = sys.version_info >= (3, 5)
TEST_DIR = os.path.dirname(__file__)
# A mof file that defines basic qualifier decls, classes, and instances
# but not tied to the DMTF classes.
SIMPLE_MOCK_FILE = 'simple_mock_model.mof'
INVOKE_METHOD_MOCK_FILE_0 = 'simple_mock_invokemethod_v0.py'
INVOKE_METHOD_MOCK_FILE_1 = 'simple_mock_invokemethod_v1old.py'
INVOKE_METHOD_MOCK_FILE = INVOKE_METHOD_MOCK_FILE_0 if PYWBEM_0 else \
INVOKE_METHOD_MOCK_FILE_1
SIMPLE_ASSOC_MOCK_FILE = 'simple_assoc_mock_model.mof'
QUALIFIER_FILTER_MODEL = 'qualifier_filter_model.mof'
TREE_TEST_MOCK_FILE = 'tree_test_mock_model.mof'
SIMPLE_INTEROP_MOCK_FILE = 'simple_interop_mock_script.py'
#
# The following list defines the help for each command in terms of particular
# parts of lines that are to be tested.//FakedUrl:5988
# For each test, try to include:
# 1. The usage line and in particular the argument component
# 2. The single
# 2. The last line CMD_OPTION_HELP_HELP_LINE
#
CLASS_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class COMMAND [ARGS] [COMMAND-OPTIONS]',
'Command group for CIM classes.',
CMD_OPTION_HELP_HELP_LINE,
'associators List the classes associated with a class.',
'delete Delete a class.',
'enumerate List top classes or subclasses of a class in a namespace.',
'find List the classes with matching class names on the server.',
'get Get a class.',
'invokemethod Invoke a method on a class.',
'references List the classes referencing a class.',
'tree Show the subclass or superclass hierarchy for a class.',
]
CLASS_ASSOCIATORS_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class associators CLASSNAME '
'[COMMAND-OPTIONS]',
'List the classes associated with a class.',
'--ac, --assoc-class CLASSNAME Filter the result set by association class',
'--rc, --result-class CLASSNAME Filter the result set by result class',
'-r, --role PROPERTYNAME Filter the result set by source end role',
'--rr, --result-role PROPERTYNAME Filter the result set by far end role',
CMD_OPTION_NO_QUALIFIERS_HELP_LINE,
CMD_OPTION_INCLUDE_CLASSORIGIN_HELP_LINE,
CMD_OPTION_PROPERTYLIST_HELP_LINE,
CMD_OPTION_NAMES_ONLY_HELP_LINE,
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_SUMMARY_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_DELETE_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class delete CLASSNAME '
'[COMMAND-OPTIONS]',
'Delete a class.',
'-f, --force Same as --include-instances.',
'--include-instances Delete any instances of the class as well.',
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_ENUMERATE_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class enumerate CLASSNAME '
'[COMMAND-OPTIONS]',
'List top classes or subclasses of a class in a namespace.',
'--di, --deep-inheritance Include the complete subclass hierarchy',
CMD_OPTION_LOCAL_ONLY_CLASS_HELP_LINE,
CMD_OPTION_NO_QUALIFIERS_HELP_LINE,
CMD_OPTION_INCLUDE_CLASSORIGIN_HELP_LINE,
CMD_OPTION_NAMES_ONLY_HELP_LINE,
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_SUMMARY_HELP_LINE,
# NOTE: The FILTER options are a group. Define all of them.
CMD_OPTION_ASSOCIATION_FILTER_HELP_LINE,
CMD_OPTION_INDICATION_FILTER_HELP_LINE,
CMD_OPTION_EXPERIMENTAL_FILTER_HELP_LINE,
CMD_OPTION_DEPRECATED_FILTER_HELP_LINE,
CMD_OPTION_SINCE_FILTER_HELP_LINE,
CMD_OPTION_SCHEMA_FILTER_HELP_LINE,
CMD_OPTION_SUBCLASSOF_FILTER_HELP_LINE,
CMD_OPTION_LEAFCLASSES_FILTER_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_FIND_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class find CLASSNAME-GLOB '
'[COMMAND-OPTIONS]',
'List the classes with matching class names on the server.',
'-s, --sort Sort by namespace. Default is to sort by',
CMD_OPTION_MULTIPLE_NAMESPACE_HELP_LINE,
# FILTER OPTIONS
CMD_OPTION_ASSOCIATION_FILTER_HELP_LINE,
CMD_OPTION_INDICATION_FILTER_HELP_LINE,
CMD_OPTION_EXPERIMENTAL_FILTER_HELP_LINE,
CMD_OPTION_DEPRECATED_FILTER_HELP_LINE,
CMD_OPTION_SINCE_FILTER_HELP_LINE,
CMD_OPTION_SCHEMA_FILTER_HELP_LINE,
CMD_OPTION_SUBCLASSOF_FILTER_HELP_LINE,
CMD_OPTION_LEAFCLASSES_FILTER_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_GET_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class get CLASSNAME [COMMAND-OPTIONS]',
'Get a class.',
CMD_OPTION_LOCAL_ONLY_CLASS_HELP_LINE,
CMD_OPTION_NO_QUALIFIERS_HELP_LINE,
CMD_OPTION_INCLUDE_CLASSORIGIN_HELP_LINE,
CMD_OPTION_PROPERTYLIST_HELP_LINE,
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_INVOKEMETHOD_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class invokemethod CLASSNAME '
'METHODNAME [COMMAND-OPTIONS]',
'Invoke a method on a class.',
'-p, --parameter PARAMETERNAME=VALUE Specify a method input parameter',
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_REFERENCES_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class references CLASSNAME '
'[COMMAND-OPTIONS]',
'List the classes referencing a class.',
'--rc, --result-class CLASSNAME Filter the result set by result class',
'-r, --role PROPERTYNAME Filter the result set by source end role',
CMD_OPTION_NO_QUALIFIERS_HELP_LINE,
CMD_OPTION_INCLUDE_CLASSORIGIN_HELP_LINE,
CMD_OPTION_PROPERTYLIST_HELP_LINE,
CMD_OPTION_NAMES_ONLY_HELP_LINE,
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_SUMMARY_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
CLASS_TREE_HELP_LINES = [
'Usage: pywbemcli [GENERAL-OPTIONS] class tree CLASSNAME [COMMAND-OPTIONS]',
'Show the subclass or superclass hierarchy for a class.',
'-s, --superclasses Show the superclass hierarchy.',
' -d, --detail Show details about the class: the Version',
CMD_OPTION_NAMESPACE_HELP_LINE,
CMD_OPTION_HELP_HELP_LINE,
]
# pylint: disable=line-too-long
CIMFOO_SUB_SUB = """
[Description ( "Subclass of CIM_Foo_sub" )]
class CIM_Foo_sub_sub : CIM_Foo_sub {
string cimfoo_sub_sub;
string cimfoo_sub;
[Key ( true ),
Description ( "This is key property." )]
string InstanceID;
[Description ( "This is Uint32 property." )]
uint32 IntegerProp;
[Description ( "Embedded instance property" ),
EmbeddedInstance ( "CIM_FooEmb3" )]
string cimfoo_emb3;
[Description ( "Sample method with input and output parameters" )]
uint32 Method1(
[IN ( false ),
OUT ( true ),
Description ( "Response param 2" )]
string OutputParam2);
[Description ( "Method with in and out parameters" )]
uint32 Fuzzy(
[IN ( true ),
OUT ( true ),
Description ( "Define data to be returned in output parameter" )]
string TestInOutParameter,
[IN ( true ),
OUT ( true ),
Description ( "Test of ref in/out parameter" )]
CIM_FooRef1 REF TestRef,
[IN ( false ),
OUT ( true ),
Description ( "Rtns method name if exists on input" )]
string OutputParam,
[IN ( true ),
Description ( "Defines return value if provided." )]
uint32 OutputRtnValue);
[Description ( "Static method with in and out parameters" ),
Static ( true )]
uint32 FuzzyStatic(
[IN ( true ),
OUT ( true ),
Description ( "Define data to be returned in output parameter" )]
string TestInOutParameter,
[IN ( true ),
OUT ( true ),
Description ( "Test of ref in/out parameter" )]
CIM_Foo REF TestRef,
[IN ( false ),
OUT ( true ),
Description ( "Rtns method name if exists on input" )]
string OutputParam,
[IN ( true ),
Description ( "Defines return value if provided." )]
uint32 OutputRtnValue,
[IN ( true ),
Description ( "Embedded instance parameter" ),
EmbeddedInstance ( "CIM_FooEmb1" )]
string cimfoo_emb1);
[Description ( "Method with no parameters but embedded instance return" ),
EmbeddedInstance ( "CIM_FooEmb2" )]
string DeleteNothing();
};
""" # noqa: E501
# pylint: enable=line-too-long
CIMFOO_SUB_SUB_NO_QUALS = """
class CIM_Foo_sub_sub : CIM_Foo_sub {
string cimfoo_sub_sub;
string cimfoo_sub;
string InstanceID;
uint32 IntegerProp;
string cimfoo_emb3;
uint32 Method1(
string OutputParam2);
uint32 Fuzzy(
string TestInOutParameter,
CIM_FooRef1 REF TestRef,
string OutputParam,
uint32 OutputRtnValue);
uint32 FuzzyStatic(
string TestInOutParameter,
CIM_Foo REF TestRef,
string OutputParam,
uint32 OutputRtnValue,
string cimfoo_emb1);
string DeleteNothing();
};
"""
# TODO: This never referenced
REFERENCES_CLASS_RTN = [
FAKEURL_STR + '/root/cimv2:TST_Lineage',
'class TST_Lineage {',
'',
' string InstanceID;',
'',
' TST_Person REF parent;',
'',
' TST_Person REF child;',
'',
'};',
'',
FAKEURL_STR + '/root/cimv2:TST_MemberOfFamilyCollection',
'class TST_MemberOfFamilyCollection {',
'',
' TST_Person REF family;',
'',
' TST_Person REF member;',
'',
'};',
'']
# TODO: This never referenced
REFERENCES_CLASS_RTN2 = [
FAKEURL_STR + '/root/cimv2:TST_MemberOfFamilyCollection',
'class TST_MemberOfFamilyCollection {',
'',
' TST_Person REF family;',
'',
' TST_Person REF member;',
'',
'};',
'',
'']
REFERENCES_CLASS_RTN_QUALS2 = [
FAKEURL_STR + '/root/cimv2:TST_MemberOfFamilyCollection',
' [Association ( true ),',
' Description ( " Family gathers person to family." )]',
'class TST_MemberOfFamilyCollection {',
' [key ( true )]',
' TST_Person REF family;',
' [key ( true )]',
' TST_Person REF member;',
'};']
OK = True # mark tests OK when they execute correctly
RUN = True # Mark OK = False and current test case being created RUN
FAIL = False # Any test currently FAILING or not tested yet
TEST_CASES = [
# List of testcases.
# Each testcase is a list with the following items:
# * desc: Description of testcase.
# * inputs: String, or tuple/list of strings, or dict of 'env', 'args',
# 'general', and 'stdin'. See the 'inputs' parameter of
# CLITestsBase.command_test() in cli_test_extensions.py for detailed
# documentation.
# * exp_response: Dictionary of expected responses (stdout, stderr, rc) and
# test definition (test: <testname>). See the 'exp_response' parameter
# of CLITestsBase.command_test() in cli_test_extensions.py for
# detailed documentation.
# * mock: None, name of file (.mof or .py), or list thereof.
# * condition: If True the test is executed, if 'pdb' the test breaks in the
# the debugger, if 'verbose' print verbose messages, if False the test
# is skipped.
['Verify class command --help response',
['--help'],
{'stdout': CLASS_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command --help command order',
['--help'],
{'stdout': r'Commands:'
'.*\n enumerate'
'.*\n get'
'.*\n delete'
'.*\n invokemethod'
'.*\n references'
'.*\n associators'
'.*\n find'
'.*\n tree',
'test': 'regex'},
None, OK],
['Verify class command -h response',
['-h'],
{'stdout': CLASS_HELP_LINES,
'test': 'innows'},
None, OK],
#
# Enumerate command and its options
#
['Verify class command enumerate --help response',
['enumerate', '--help'],
{'stdout': CLASS_ENUMERATE_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command enumerate -h response',
['enumerate', '-h'],
{'stdout': CLASS_ENUMERATE_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command enumerate CIM_Foo',
['enumerate', 'CIM_Foo'],
{'stdout': ['[Description ( "Subclass of CIM_Foo" )]'],
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --lo',
['enumerate', 'CIM_Foo', '--lo'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --lo',
['enumerate', 'CIM_Foo', '--local-only'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo_sub',
['enumerate', 'CIM_Foo_sub'],
{'stdout': CIMFOO_SUB_SUB,
'test': 'linesnows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo local-only',
['enumerate', 'CIM_Foo', '--local-only'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo -no-qualifiers',
['enumerate', 'CIM_Foo_sub', '--no-qualifiers'],
{'stdout': CIMFOO_SUB_SUB_NO_QUALS,
'test': 'linesnows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --di',
['enumerate', 'CIM_Foo', '--di'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --deep-inheritance',
['enumerate', 'CIM_Foo', '--deep-inheritance'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --ico',
['enumerate', 'CIM_Foo', '--ico'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --include-classorigin',
['enumerate', 'CIM_Foo', '--include-classorigin'],
{'stdout':
' [Description ( "Subclass of CIM_Foo" )]',
'test': 'startswith'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --no names only',
['enumerate', 'CIM_Foo', '--no'],
{'stdout': ['CIM_Foo', 'CIM_Foo_sub', 'CIM_Foo_sub2'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --names only',
['enumerate', 'CIM_Foo', '--names-only'],
{'stdout': ['CIM_Foo', 'CIM_Foo_sub', 'CIM_Foo_sub2'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate --no names only - table',
{'args': ['enumerate', '--no'],
'general': ['--output-format', 'table']},
{'stdout': """Classnames:
+--------------+
| Class Name |
|--------------|
| CIM_BaseEmb |
| CIM_BaseRef |
| CIM_Foo |
| CIM_FooAssoc |
+--------------+
""",
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --no names only - table',
{'args': ['enumerate', 'CIM_Foo', '--no'],
'general': ['--output-format', 'table']},
{'stdout': """Classnames:
+--------------+
| Class Name |
|--------------|
| CIM_Foo_sub |
| CIM_Foo_sub2 |
+--------------+
""",
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo --names-only',
['enumerate', 'CIM_Foo', '--names-only'],
{'stdout': ['CIM_Foo', 'CIM_Foo_sub', 'CIM_Foo_sub2'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo summary table',
['enumerate', 'CIM_Foo', '-s'],
{'stdout': ['2 CIMClass(s) returned'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo summary, table',
['enumerate', 'CIM_Foo', '--summary'],
{'stdout': ['2 CIMClass(s) returned'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo summary table output',
{'args': ['enumerate', 'CIM_Foo', '--summary'],
'general': ['--output-format', 'table']},
{'stdout': ["""Summary of CIMClass returned
+---------+------------+
| Count | CIM Type |
|---------+------------|
| 2 | CIMClass |
+---------+------------+
"""],
'test': 'linesnows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo names and --di --no',
['enumerate', 'CIM_Foo', '--di', '--no'],
{'stdout': ['CIM_Foo_sub', 'CIM_Foo_sub2', 'CIM_Foo_sub_sub'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo names and --deep-inheritance '
'--names-only',
['enumerate', 'CIM_Foo', '--names-only', '--deep-inheritance'],
{'stdout': ['CIM_Foo_sub', 'CIM_Foo_sub2', 'CIM_Foo_sub_sub'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate CIM_Foo include qualifiers',
['enumerate', 'CIM_Foo'],
{'stdout': ['Key ( true )', '[Description (', 'class CIM_Foo'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get with xml output format).',
{'args': ['enumerate'],
'general': ['--output-format', 'repr']},
{'stdout': [r"CIMClass\(classname='CIM_Foo', superclass=None,",
r"'InstanceID': CIMProperty\(name='InstanceID', value=None,"],
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get with repr output format).',
{'args': ['enumerate'],
'general': ['--output-format', 'txt']},
{'stdout': ["CIMClass(classname='CIM_BaseEmb', ...)",
"CIMClass(classname='CIM_BaseRef', ...)",
"CIMClass(classname='CIM_Foo', ...)",
"CIMClass(classname='CIM_FooAssoc', ...)"],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate with repr output format).',
{'args': ['enumerate'],
'general': ['--output-format', 'xml']},
{'stdout': ['<CLASS( | .+ )NAME="CIM_Foo">',
'<PROPERTY( | .+ )NAME="InstanceID"',
'<PROPERTY( | .+ )NAME="IntegerProp"',
'<METHOD( | .+ )NAME="DeleteNothing"'],
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate --di --no --namespace',
['enumerate', '--di', '--no', '-n', 'interop'],
{'stdout': ['CIM_Namespace', 'CIM_ObjectManager'],
'test': 'in'},
SIMPLE_INTEROP_MOCK_FILE, OK],
#
# Enumerate commands with the filter options
#
['Verify class command enumerate with --association filter.',
['enumerate', '--association', '--names-only'],
{'stdout': ['TST_Lineage', 'TST_MemberOfFamilyCollection'],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command enumerate with --association filter --summary.',
['enumerate', '--association', '--summary'],
{'stdout': ['2 CIMClass(s) returned'],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command enumerate with --association filter.',
['enumerate', '--association', '--names-only'],
{'stdout': ['TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_MemberOfFamilyCollectionExp'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --association filter --summary.',
['enumerate', '--association', '--summary'],
{'stdout': ['4 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --association filter and no '
'qualifiers.',
['enumerate', '--association', '--nq'],
{'stdout': ['class TST_Lineage {',
'string InstanceID;',
'TST_Person REF parent;',
'TST_Person REF child;',
'class TST_MemberOfFamilyCollection {',
'TST_Person REF family;',
'TST_Person REF member;', '};'],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command enumerate with --no-association filter and '
'no-qualifiers. Tests no qualifiers on parameters',
['enumerate', '--no-association', '--no-qualifiers'],
{'stdout': ['class CIM_Foo {',
'string InstanceID;',
'uint32 IntegerProp;',
'string cimfoo_emb3;',
'uint32 Fuzzy(',
'string TestInOutParameter,',
'CIM_FooRef1 REF TestRef,',
'string OutputParam,',
'uint32 OutputRtnValue);',
'uint32 FuzzyStatic(',
'string TestInOutParameter,',
'CIM_Foo REF TestRef,',
'string OutputParam,',
'uint32 OutputRtnValue,',
'string cimfoo_emb1);',
'string DeleteNothing();',
'};'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate with --no-association filter, simple mod.',
['enumerate', '--no-association', '--names-only'],
{'stdout': ['TST_FamilyCollection', 'TST_Person'],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command enumerate with --no-association, --summary.',
['enumerate', '--no-association', '--summary'],
{'stdout': ['2 CIMClass(s) returned'],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command enumerate with --no-association filter qual filt.',
['enumerate', '--no-association', '--names-only'],
{'stdout': ['BLA_Person', 'EXP_TestExperimental1',
'EXP_TestExperimental2', 'EXP_TestExperimental3',
'EXP_TestExperimental4', 'TST_FamilyCollection',
'TST_Indication', 'TST_IndicationDeprecated',
'TST_IndicationExperimental', 'TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-association, --summary.',
['enumerate', '--no-association', '--summary'],
{'stdout': ['10 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --indication filter.',
['enumerate', '--indication', '--names-only'],
{'stdout': ['TST_Indication', 'TST_IndicationDeprecated',
'TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --indication filter --summary.',
['enumerate', '--indication', '--summary'],
{'stdout': ['3 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-indication filter.',
['enumerate', '--no-indication', '--names-only'],
{'stdout': ['BLA_Person', 'EXP_TestExperimental1',
'EXP_TestExperimental2', 'EXP_TestExperimental3',
'EXP_TestExperimental4', 'TST_FamilyCollection',
'TST_FamilyCollection',
'TST_Lineage',
'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionExp',
'TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-indication filter, --summary.',
['enumerate', '--no-indication', '--summary'],
{'stdout': ['11 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimentat filter.',
['enumerate', '--experimental', '--names-only'],
{'stdout': ['EXP_TestExperimental1', ' EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4',
'TST_IndicationExperimental',
'TST_MemberOfFamilyCollectionExp'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimentat filter -- summary.',
['enumerate', '--experimental', '--summary'],
{'stdout': ['6 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-experimental filter.',
['enumerate', '--no-experimental', '--names-only'],
{'stdout': ['BLA_Person',
'TST_FamilyCollection',
'TST_Indication',
'TST_IndicationDeprecated',
'TST_Lineage',
'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-experimental, --summary.',
['enumerate', '--no-experimental', '--summary'],
{'stdout': ['8 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental, --association.',
['enumerate', '--experimental', '--association', '--names-only'],
{'stdout': ['EXP_TestExperimental1',
'EXP_TestExperimental2',
'EXP_TestExperimental3',
'EXP_TestExperimental4',
'TST_IndicationExperimental',
'TST_MemberOfFamilyCollectionExp'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental, --association, '
'--summary',
['enumerate', '--experimental', '--association', '--summary'],
{'stdout': ['6 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental , --no-association.',
['enumerate', '--experimental', '--no-association', '--names-only'],
{'stdout': ['EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4',
'TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --indication and --experimental.',
['enumerate', '--experimental', '--indication', '--names-only'],
{'stdout': ['TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --indication, --no-experimental.',
['enumerate', '--no-experimental', '--indication', '--names-only'],
{'stdout': ['TST_Indication', 'TST_IndicationDeprecated'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-indication, --no-experimental, '
'--no-association',
['enumerate', '--no-experimental', '--no-indication', '--no-association',
'--names-only'],
{'stdout': ['BLA_Person',
'TST_FamilyCollection',
'TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --deprecated, --no-association.',
['enumerate', '--deprecated', '--no-association', '--names-only'],
{'stdout': ['TST_IndicationDeprecated',
'TST_MemberOfFamilyCollectionDep'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --deprecated, --no-association, '
'--summary',
['enumerate', '--deprecated', '--no-association', '--summary'],
{'stdout': ['2 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-deprecated, --association',
['enumerate', '--no-deprecated', '--association', '--names-only'],
{'stdout': ['BLA_Person', 'EXP_TestExperimental1',
'EXP_TestExperimental2', 'EXP_TestExperimental3',
'EXP_TestExperimental4', 'TST_FamilyCollection',
'TST_Indication', 'TST_IndicationExperimental',
'TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionExp', 'TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --no-deprecated, --no-association'
'--summary',
['enumerate', '--no-deprecated', '--association', '--summary'],
{'stdout': ['12 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental, --since 2.42.0.',
['enumerate', '--experimental', '--since', '2.42.0', '--names-only'],
{'stdout': ['TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental and --since 2.42.0'
'--summary',
['enumerate', '--experimental', '--since', '2.42.0', '--summary'],
{'stdout': ['3 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental and --since 2.45.0.',
['enumerate', '--experimental', '--since', '2.45.0', '--names-only'],
{'stdout': [],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --experimental and --since 2.45.x.',
['enumerate', '--experimental', '--since', '2.45.x', '--names-only'],
{'stderr': ['--since option value invalid. ',
'Must contain 3 integer elements',
'2.45.x'],
'rc': 1,
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --indication and --since 2.45.',
['enumerate', '--experimental', '--since', '2.45', '--names-only'],
{'stderr': ['Version value must contain 3 integer elements (int.int.int)',
'2.45'],
'rc': 1,
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "TST".',
['enumerate', '--schema', 'TST', '--names-only'],
{'stdout': ['TST_FamilyCollection', 'TST_Indication',
'TST_IndicationDeprecated', 'TST_IndicationExperimental',
'TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_MemberOfFamilyCollectionExp', 'TST_Person', ],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "BLA".',
['enumerate', '--schema', 'BLA', '--names-only'],
{'stdout': ['BLA_Person', ],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP".',
['enumerate', '--schema', 'EXP', '--names-only'],
{'stdout': ['EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP" --summary',
['enumerate', '--schema', 'EXP', '--summary'],
{'stdout': ['4 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP" and --experimental.',
['enumerate', '--schema', 'EXP', '--experimental', '--names-only'],
{'stdout': ['EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP" and --experimental.',
['enumerate', '--schema', 'EXP', '--experimental', '--summary'],
{'stdout': ['4 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP",--experimental, '
'--summary.',
['enumerate', '--schema', 'EXP', '--experimental', '--summary'],
{'stdout': ['4 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP" , --no-experimental.',
['enumerate', '--schema', 'EXP', '--no-experimental', '--names-only'],
{'stdout': [],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "EXP" , --no-experimental '
'--summary',
['enumerate', '--schema', 'EXP', '--no-experimental', '--summary'],
{'stdout': ['0 objects returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --schema "NOT_EXIST".',
['enumerate', '--schema', 'NOT_EXIST', '--names-only'],
{'stdout': [],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of TST_Person.',
['enumerate', '--subclass-of', 'TST_Person', '--di', '--names-only'],
{'stdout': ['TST_PersonClsDep', 'TST_PersonDep',
'TST_PersonExp', 'TST_PersonExpProperty',
'TST_PersonPropDep', 'TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of TST_Person --summary.',
['enumerate', '--subclass-of', 'TST_Person', '--di', '--summary'],
{'stdout': ['6 CIMClass(s) returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of TST_Person '
'-- association--summary .',
['enumerate', '--association', '--subclass-of', 'TST_Person', '--di',
'--summary'],
{'stdout': ['0 objects returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of TST_PersonDep.',
['enumerate', '--subclass-of', 'TST_PersonDep', '--di', '--names-only'],
{'stdout': [],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of TST_PersonDep '
'--summary.',
['enumerate', '--subclass-of', 'TST_PersonDep', '--di', '--summary'],
{'stdout': ['0 objects returned'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --subclass-of NOT_EXIST excepts.',
['enumerate', '--subclass-of', 'NOT_EXIST', '--names-only'],
{'stderr': ['Classname NOT_EXIST for "subclass-of" not found'],
'rc': 1,
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify instance command enumerate CIM_Foo_sub2, w --verbose rtns msg.',
{'args': ['enumerate', 'CIM_Foo_sub2'],
'general': ['--verbose']},
{'stdout': 'No objects returned',
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
#
# Enumerate errors
#
['Verify class command enumerate nonexistent class name',
['enumerate', 'CIM_FClassDoesNotExist'],
{'stderr': ['CIMError', 'CIM_ERR_INVALID_CLASS'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate table output fails).',
{'args': ['enumerate'],
'general': ['--output-format', 'table']},
{'stderr': ['Output format "table"', 'not allowed', 'Only CIM formats:'],
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
#
# Test class get
#
['Verify class command get --help response',
['get', '--help'],
{'stdout': CLASS_GET_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command get -h response',
['get', '-h'],
{'stdout': CLASS_GET_HELP_LINES,
'test': 'innows'},
None, OK],
# command get local-only option
['Verify class command get not local-only. Tests for property names',
['get', 'CIM_Foo_sub2'],
{'stdout': ['string cimfoo_sub2;', 'InstanceID', 'IntegerProp', 'Fuzzy',
'Key ( true )', 'IN ( false )'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get local-only(--lo)).',
['get', 'CIM_Foo_sub2', '--lo'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' string cimfoo_sub2;',
'',
'};', ''],
'test': 'patterns'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get local-only. Tests whole response',
['get', 'CIM_Foo_sub2', '--local-only'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' string cimfoo_sub2;',
'',
'};', ''],
'test': 'patterns'},
SIMPLE_MOCK_FILE, OK],
# includequalifiers. Test the flag that excludes qualifiers
['Verify class command get without qualifiers. Tests whole response',
['get', 'CIM_Foo_sub2', '--nq'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' string cimfoo_sub2;',
'',
' string InstanceID;',
'',
' uint32 IntegerProp;',
'',
' string cimfoo_emb3;',
'',
' uint32 Fuzzy(',
' string TestInOutParameter,',
' CIM_FooRef1 REF TestRef,',
' string OutputParam,',
' uint32 OutputRtnValue);',
'',
' uint32 FuzzyStatic(',
' string TestInOutParameter,',
' CIM_Foo REF TestRef,',
' string OutputParam,',
' uint32 OutputRtnValue,',
' string cimfoo_emb1);',
'',
' string DeleteNothing();',
'',
'};',
''],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get without qualifiers. Tests whole response',
['get', 'CIM_Foo_sub2', '--no-qualifiers'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' string cimfoo_sub2;',
'',
' string InstanceID;',
'',
' uint32 IntegerProp;',
'',
' string cimfoo_emb3;',
'',
' uint32 Fuzzy(',
' string TestInOutParameter,',
' CIM_FooRef1 REF TestRef,',
' string OutputParam,',
' uint32 OutputRtnValue);',
'',
' uint32 FuzzyStatic(',
' string TestInOutParameter,',
' CIM_Foo REF TestRef,',
' string OutputParam,',
' uint32 OutputRtnValue,',
' string cimfoo_emb1);',
'',
' string DeleteNothing();',
'',
'};',
''],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
# pylint: disable=line-too-long
['Verify class command get with propertylist. Tests whole response',
['get', 'CIM_Foo_sub2', '--pl', 'InstanceID'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' [Key ( true ),',
' Description ( "This is key property." )]',
' string InstanceID;',
'',
' [Description ( "Method with in and out parameters" )]',
' uint32 Fuzzy(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in output parameter" )]', # noqa: E501
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_FooRef1 REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on input" )]', # noqa: E501
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if provided." )]', # noqa: E501
' uint32 OutputRtnValue);',
'',
' [Description ( "Static method with in and out parameters" ),', # noqa: E501
' Static ( true )]',
' uint32 FuzzyStatic(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in output parameter" )]', # noqa: E501
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_Foo REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on input" )]', # noqa: E501
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if provided." )]', # noqa: E501
' uint32 OutputRtnValue,',
' [IN ( true ),',
' Description ( "Embedded instance parameter" ),',
' EmbeddedInstance ( "CIM_FooEmb1" )]',
' string cimfoo_emb1);',
'',
' [Description ( "Method with no parameters but embedded instance return" ),', # noqa: E501
' EmbeddedInstance ( "CIM_FooEmb2" )]',
' string DeleteNothing();',
'',
'};',
''],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get with empty propertylist. Tests whole '
'response',
['get', 'CIM_Foo_sub2', '--pl', '""'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
'',
' [Description ( "Method with in and out parameters" )]',
' uint32 Fuzzy(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in output parameter" )]', # noqa: E501
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_FooRef1 REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on input" )]', # noqa: E501
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if provided." )]', # noqa: E501
' uint32 OutputRtnValue);',
'',
' [Description ( "Static method with in and out parameters" ),', # noqa: E501
' Static ( true )]',
' uint32 FuzzyStatic(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in output parameter" )]', # noqa: E501
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_Foo REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on input" )]', # noqa: E501
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if provided." )]', # noqa: E501
' uint32 OutputRtnValue,',
' [IN ( true ),',
' Description ( "Embedded instance parameter" ),',
' EmbeddedInstance ( "CIM_FooEmb1" )]',
' string cimfoo_emb1);',
'',
' [Description ( "Method with no parameters but embedded instance return" ),', # noqa: E501
' EmbeddedInstance ( "CIM_FooEmb2" )]',
' string DeleteNothing();',
'',
'};',
''],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
# pylint: enable=line-too-long
['Verify class command get with xml output format).',
{'args': ['get', 'CIM_Foo'],
'general': ['--output-format', 'repr']},
{'stdout': [r"CIMClass\(classname='CIM_Foo', superclass=None,",
r"'InstanceID': CIMProperty\(name='InstanceID', value=None,"],
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get with repr output format).',
{'args': ['get', 'CIM_Foo'],
'general': ['--output-format', 'txt']},
{'stdout': ["CIMClass(classname='CIM_Foo', ...)"],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get with repr output format).',
{'args': ['get', 'CIM_Foo'],
'general': ['--output-format', 'xml']},
{'stdout': ['<CLASS( | .+ )NAME="CIM_Foo">',
'<PROPERTY( | .+ )NAME="InstanceID"',
'<PROPERTY( | .+ )NAME="IntegerProp"',
'<METHOD( | .+ )NAME="DeleteNothing"'],
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
# pylint: disable=line-too-long
['Verify class command get with propertylist and classorigin,',
['get', 'CIM_Foo_sub2', '--pl', 'InstanceID', '--ico'],
{'stdout': ['class CIM_Foo_sub2 : CIM_Foo {',
' [Key ( true ),',
' Description ( "This is key property." )]',
' string InstanceID;',
' [Description ( "Method with in and out parameters" )]',
' uint32 Fuzzy(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in '
'output parameter" )]',
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_FooRef1 REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on '
'input" )]',
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if '
'provided." )]',
' uint32 OutputRtnValue);',
' [Description ( "Static method with in and out '
'parameters" ),',
' Static ( true )]',
' uint32 FuzzyStatic(',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Define data to be returned in '
'output parameter" )]',
' string TestInOutParameter,',
' [IN ( true ),',
' OUT ( true ),',
' Description ( "Test of ref in/out parameter" )]',
' CIM_Foo REF TestRef,',
' [IN ( false ),',
' OUT ( true ),',
' Description ( "Rtns method name if exists on '
'input" )]',
' string OutputParam,',
' [IN ( true ),',
' Description ( "Defines return value if '
'provided." )]',
' uint32 OutputRtnValue,',
' [IN ( true ),',
' Description ( "Embedded instance parameter" ),',
' EmbeddedInstance ( "CIM_FooEmb1" )]',
' string cimfoo_emb1);',
' [Description ( "Method with no parameters but embedded instance return" ),', # noqa: E501
' EmbeddedInstance ( "CIM_FooEmb2" )]',
' string DeleteNothing();',
'};', ''],
'test': 'linesnows'},
SIMPLE_MOCK_FILE, OK],
# pylint: enable=line-too-long
['Verify class command enumerate --di --no --namespace',
['get', 'CIM_Namespace', '-n', 'interop'],
{'stdout': ['class CIM_Namespace',
'string ObjectManagerCreationClassName;'],
'test': 'innows'},
SIMPLE_INTEROP_MOCK_FILE, OK],
# get command errors
['Verify class command get invalid classname',
['get', 'CIM_Argh'],
{'stderr': ['CIMError', 'CIM_ERR_NOT_FOUND', '6'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command get invalid namespace',
['get', 'CIM_Foo', '--namespace', 'Argh'],
{'stderr': ['CIMError', 'CIM_ERR_INVALID_NAMESPACE', '3'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command enumerate table output fails).',
{'args': ['get', 'CIM_Foo'],
'general': ['--output-format', 'table']},
{'stderr': ['Output format "table" ', 'not allowed', 'Only CIM formats:'],
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
#
# find command
#
['Verify class command find --help response',
['find', '--help'],
{'stdout': CLASS_FIND_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command find -h response',
['find', '-h'],
{'stdout': CLASS_FIND_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command find simple name in all namespaces',
['find', 'CIM_*'],
{'stdout': [" root/cimv2: CIM_Foo",
" root/cimv2: CIM_Foo_sub",
" root/cimv2: CIM_Foo_sub2",
" root/cimv2: CIM_Foo_sub_sub"],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in all namespaces wo case',
['find', 'cim_*'],
{'stdout': [" root/cimv2: CIM_Foo",
" root/cimv2: CIM_Foo_sub",
" root/cimv2: CIM_Foo_sub2",
" root/cimv2: CIM_Foo_sub_sub"],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in all namespaces lead wc',
['find', '*sub_sub*'],
{'stdout': [" root/cimv2: CIM_Foo_sub_sub"],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in all namespaces wo case',
['find', '*sub_su?*'],
{'stdout': [" root/cimv2: CIM_Foo_sub_sub"],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in known namespace',
['find', 'CIM_*', '-n', 'root/cimv2'],
{'stdout': [" root/cimv2: CIM_BaseEmb",
" root/cimv2: CIM_BaseRef",
" root/cimv2: CIM_Foo",
" root/cimv2: CIM_FooAssoc",
" root/cimv2: CIM_FooEmb1",
" root/cimv2: CIM_FooEmb2",
" root/cimv2: CIM_FooEmb3",
" root/cimv2: CIM_FooRef1",
" root/cimv2: CIM_FooRef2",
" root/cimv2: CIM_Foo_sub",
" root/cimv2: CIM_Foo_sub2",
" root/cimv2: CIM_Foo_sub_sub"],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in interop namespace',
['find', 'CIM_*'],
{'stdout': [" interop: CIM_Namespace",
" interop: CIM_ObjectManager"],
'test': 'in'},
SIMPLE_INTEROP_MOCK_FILE, OK],
['Verify class command find name in known namespace -o grid',
{'general': ['-o', 'grid'],
'args': ['find', 'CIM_*', '-n', 'root/cimv2']},
{'stdout': ['Find class CIM_*',
'+-------------+-----------------+',
'| Namespace | Classname |',
'+=============+=================+',
'| root/cimv2 | CIM_BaseEmb |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_BaseRef |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_Foo |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooAssoc |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooEmb1 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooEmb2 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooEmb3 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooRef1 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_FooRef2 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_Foo_sub |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_Foo_sub2 |',
'+-------------+-----------------+',
'| root/cimv2 | CIM_Foo_sub_sub |',
'+-------------+-----------------+'],
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command verify nothing found for BLAH_ regex',
['find', 'BLAH_*', '-n', 'root/cimv2'],
{'stdout': "",
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find simple name in known namespace with wildcard',
['find', '*sub2', '-n', 'root/cimv2'],
{'stdout': " root/cimv2: CIM_Foo_sub2",
'test': 'lines'},
SIMPLE_MOCK_FILE, OK],
['Verify class command find with --association filter',
['find', '*TST_*', '-n', 'root/cimv2', '--association'],
{'stdout': ['TST_Lineage',
'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionExp'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --indication filter',
['find', '*TST_*', '-n', 'root/cimv2', '--indication'],
{'stdout': ['TST_Indication', 'root/cimv2:TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --indication & -no-experimental filters',
['find', '*TST_*', '-n', 'root/cimv2', '--indication',
'--no-experimental'],
{'stdout': ['TST_Indication'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --association & --experimental filters',
['find', '*TST_*', '-n', 'root/cimv2', '--association', '--experimental'],
{'stdout': ['TST_MemberOfFamilyCollectionExp'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --no-association & --no-experimental, '
'filters',
['find', 'TST_*', '-n', 'root/cimv2', '--no-association',
'--no-experimental', '--no-indication'],
{'stdout': ['root/cimv2: TST_FamilyCollection', 'root/cimv2: TST_Person',
'root/cimv2: TST_PersonClsDep', 'root/cimv2: TST_PersonDep',
'root/cimv2: TST_PersonPropDep', 'root/cimv2: TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --no-association & --deprecated, ',
['find', 'TST_*', '-n', 'root/cimv2', '--no-association', '--deprecated'],
{'stdout': ['root/cimv2: TST_IndicationDeprecated',
'root/cimv2: TST_PersonClsDep',
'root/cimv2: TST_PersonDep',
'root/cimv2: TST_PersonExpProperty',
'root/cimv2: TST_PersonPropDep'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --experimental and --since 2.42.0.',
['find', "*", '--experimental', '--since', '2.42.0'],
{'stdout': ['TST_IndicationExperimental'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --experimental and --since 2.45.0.',
['find', "*", '--experimental', '--since', '2.45.0'],
{'stdout': [],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --experimental and --since 2.45.x.',
['find', "*", '--experimental', '--since', '2.45.x'],
{'stderr': ['--since option value invalid. ',
'Must contain 3 integer elements',
'2.45.x'],
'rc': 1,
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --schema "BLA".',
['find', '*', '--schema', 'BLA'],
{'stdout': ['BLA_Person', ],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --schema "EXP".',
['find', '*', '--schema', 'EXP'],
{'stdout': ['EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --schema "EXP". test not-innows',
['find', '*', '--schema', 'EXP'],
{'stdout': ['BLA_Person', 'TST_FamilyCollection', 'TST_Indication',
'TST_IndicationDeprecated', 'TST_IndicationExperimental',
'TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_MemberOfFamilyCollectionExp',
'TST_Person', 'TST_PersonClsDep', 'TST_PersonDep',
'TST_PersonExp', 'TST_PersonExpProperty',
'TST_PersonPropDep', 'TST_PersonSub'],
'test': 'not-innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --schema "EXP" and --experimental.',
['find', '*', '--schema', 'EXP', '--experimental'],
{'stdout': ['EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --subclass-of.',
['find', '*', '--subclass-of', 'TST_Person'],
{'stdout': ['root/cimv2: TST_PersonClsDep',
'root/cimv2: TST_PersonDep', 'root/cimv2: TST_PersonExp',
'root/cimv2: TST_PersonExpProperty',
'root/cimv2: TST_PersonPropDep', 'root/cimv2: TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command find with --subclass-of.',
['find', '*Sub', '--subclass-of', 'TST_Person'],
{'stdout': ['root/cimv2: TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
# Tests with --leaf-classes
['Verify class command enumerate with --leaf-classes. test innows',
['enumerate', '--di', '--no', '--leaf-classes'],
{'stdout': ['BLA_Person', 'EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4',
'TST_FamilyCollection', 'TST_Indication',
'TST_IndicationDeprecated', 'TST_IndicationExperimental',
'TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_MemberOfFamilyCollectionExp', 'TST_PersonClsDep',
'TST_PersonDep', 'TST_PersonExp', 'TST_PersonExpProperty',
'TST_PersonPropDep', 'TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --leaf-classes. test not-innows',
['enumerate', '--di', '--no', '--leaf-classes'],
{'stdout': ['TST_Person'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --leaf-classes & --subclass-of',
['enumerate', '--di', '--no', '--leaf-classes', '--subclass-of',
'TST_Person'],
{'stdout': ['TST_PersonClsDep', 'TST_PersonDep', 'TST_PersonExp'
'TST_PersonExpProperty', 'TST_PersonPropDep', 'TST_PersonSub'],
'test': 'innows'},
QUALIFIER_FILTER_MODEL, OK],
['Verify class command enumerate with --leaf-classes & --subclass-of, '
'not-innows',
['enumerate', '--di', '--no', '--leaf-classes', '--subclass-of',
'TST_Person'],
{'stdout': ['BLA_Person', 'EXP_TestExperimental1', 'EXP_TestExperimental2',
'EXP_TestExperimental3', 'EXP_TestExperimental4',
'TST_FamilyCollection', 'TST_Indication',
'TST_IndicationDeprecated', 'TST_IndicationExperimental',
'TST_Lineage', 'TST_MemberOfFamilyCollection',
'TST_MemberOfFamilyCollectionDep',
'TST_MemberOfFamilyCollectionExp'],
'test': 'not-innows'},
QUALIFIER_FILTER_MODEL, OK],
#
# command "class delete"
#
['Verify class command delete --help response',
['delete', '--help'],
{'stdout': CLASS_DELETE_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command delete -h response',
['delete', '-h'],
{'stdout': CLASS_DELETE_HELP_LINES,
'test': 'innows'},
None, OK],
# Class delete successful
['Verify class command delete successful with no subclasses, '
'--force (deprecated)',
{'args': ['delete', 'CIM_Foo_sub_sub', '--force'],
'general': ['--warn']},
{'stderr': ['DeprecationWarning: The --force / -f option has been '
'deprecated'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete successful with no subclasses, '
'-f (deprecated)',
{'args': ['delete', 'CIM_Foo_sub_sub', '-f'],
'general': ['--warn']},
{'stderr': ['DeprecationWarning: The --force / -f option has been '
'deprecated'],
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete successful with no subclasses, '
'--include-instances',
['delete', 'CIM_Foo_sub_sub', '--include-instances'],
{'stdout': ['Deleted instance root/cimv2:CIM_Foo_sub_sub.',
'Deleted class CIM_Foo_sub_sub'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete successful with no subclasses, --namespace '
'and --include-instances',
['delete', 'CIM_Foo_sub_sub', '--namespace', 'root/cimv2',
'--include-instances'],
{'stdout': ['Deleted instance root/cimv2:CIM_Foo_sub_sub.',
'Deleted class CIM_Foo_sub_sub'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete (interactive) successful with no subclasses, '
'--include-instances, --dry-run',
{'stdin': ['class delete CIM_Foo_sub_sub --include-instances --dry-run',
'class get CIM_Foo_sub_sub',
'instance count CIM_Foo_sub_sub']},
{'stdout': ['Dry run: Deleted instance root/cimv2:CIM_Foo_sub_sub.'
'InstanceID="CIM_Foo_sub_sub1"',
'Dry run: Deleted class CIM_Foo_sub_sub',
'class CIM_Foo_sub_sub : CIM_Foo_sub {',
'root/cimv2 CIM_Foo_sub_sub 3'],
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
# Class delete errors
['Verify class command delete no classname',
['delete'],
{'stderr': ['Error: Missing argument .CLASSNAME.'],
'rc': 2,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete nonexistent classname fails',
['delete', 'Argh'],
{'stderr': ['CIMError', 'CIM_ERR_INVALID_CLASS', '5'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail instances exist',
['delete', 'CIM_Foo_sub_sub'],
{'stderr': 'Cannot delete class CIM_Foo_sub_sub because it has '
'3 instances',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail subclasses exist',
['delete', 'CIM_Foo'],
{'stderr': 'Cannot delete class CIM_Foo because it has 12 instances',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail subclasses exist, --include-instances',
['delete', 'CIM_Foo', '--include-instances'],
{'stderr': 'Cannot delete class CIM_Foo because these classes depend on '
'it: CIM_Foo_sub, CIM_Foo_sub2',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail referencing class CIM_FooRef1 exist',
['delete', 'CIM_FooRef1'],
{'stderr': 'Cannot delete class CIM_FooRef1 because it has 1 instances',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail referencing class CIM_FooRef1 exist, '
'--include-instances',
['delete', 'CIM_FooRef1', '--include-instances'],
{'stderr': 'Cannot delete class CIM_FooRef1 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail referencing class CIM_FooRef2 exist',
['delete', 'CIM_FooRef2'],
{'stderr': 'Cannot delete class CIM_FooRef2 because it has 1 instances',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail referencing class CIM_FooRef2 exist, '
'--include-instances',
['delete', 'CIM_FooRef2', '--include-instances'],
{'stderr': 'Cannot delete class CIM_FooRef2 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail referencing class CIM_FooAssoc exist',
['delete', 'CIM_FooAssoc'],
{'stderr': 'Cannot delete class CIM_FooAssoc because it has 1 instances',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete succesd for referencing class CIM_FooAssoc, '
'--include-instances',
['delete', 'CIM_FooAssoc', '--include-instances'],
{'stdout': '',
'test': 'in'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb1 exist',
['delete', 'CIM_FooEmb1'],
{'stderr': 'Cannot delete class CIM_FooEmb1 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb1 exist, '
'--include-instances',
['delete', 'CIM_FooEmb1', '--include-instances'],
{'stderr': 'Cannot delete class CIM_FooEmb1 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb2 exist',
['delete', 'CIM_FooEmb2'],
{'stderr': 'Cannot delete class CIM_FooEmb2 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb2 exist, '
'--include-instances',
['delete', 'CIM_FooEmb2', '--include-instances'],
{'stderr': 'Cannot delete class CIM_FooEmb2 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb3 exist',
['delete', 'CIM_FooEmb3'],
{'stderr': 'Cannot delete class CIM_FooEmb3 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fail embedding class CIM_FooEmb3 exist, '
'--include-instances',
['delete', 'CIM_FooEmb3', '--include-instances'],
{'stderr': 'Cannot delete class CIM_FooEmb3 because these classes depend '
'on it: CIM_Foo',
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command delete fails if instance provider rejects delete',
{'args': ['delete', 'CIM_Foo_sub_sub', '--include-instances']},
{'stderr': ['CIM_ERR_FAILED',
'Deletion of CIM_Foo_sub_sub instances is rejected'],
'rc': 1,
'test': 'innows'},
[SIMPLE_MOCK_FILE, 'reject_deleteinstance_provider.py'],
MOCK_SETUP_SUPPORTED],
['Verify class command delete using --namespace interop fails because of '
'instances',
['delete', 'CIM_ObjectManager', '-n', 'interop'],
{'stderr': ['Cannot delete class', 'instances'],
'rc': 1,
'test': 'innows'},
SIMPLE_INTEROP_MOCK_FILE, OK],
#
# command "class tree"
#
['Verify class command tree --help response',
['tree', '--help'],
{'stdout': CLASS_TREE_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command tree -h response',
['tree', '-h'],
{'stdout': CLASS_TREE_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command tree top down. Uses simple mock, no argument',
['tree'],
{'stdout': """root
+-- CIM_BaseEmb
| +-- CIM_FooEmb1
| +-- CIM_FooEmb2
| +-- CIM_FooEmb3
+-- CIM_BaseRef
| +-- CIM_FooRef1
| +-- CIM_FooRef2
+-- CIM_Foo
| +-- CIM_Foo_sub
| | +-- CIM_Foo_sub_sub
| +-- CIM_Foo_sub2
+-- CIM_FooAssoc
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree top down starting at defined class ',
['tree', 'CIM_Foo_sub'],
{'stdout': """CIM_Foo_sub
+-- CIM_Foo_sub_sub
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree top down starting at leaf class',
['tree', 'CIM_Foo_sub'],
{'stdout': """CIM_Foo_sub_sub
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree bottom up. -s',
['tree', '-s', 'CIM_Foo_sub_sub'],
{'stdout': """root
+-- CIM_Foo
+-- CIM_Foo_sub
+-- CIM_Foo_sub_sub
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree -s from top class',
['tree', '-s', 'CIM_Foo'],
{'stdout': """root
+-- CIM_Foo
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree bottom up. --superclasses',
['tree', '--superclasses', 'CIM_Foo_sub_sub'],
{'stdout': """root
+-- CIM_Foo
+-- CIM_Foo_sub
+-- CIM_Foo_sub_sub
""",
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree with --detail',
['tree', '--detail'],
{'stdout': """root
+-- CIM_Foo (Version=2.30.0)
| +-- CIM_Foo_sub (Version=2.31.0)
| +-- CIM_Foo_sub_sub (Version=2.20.1)
+-- CIM_Foo_no_version ()
+-- CIM_Indication (Abstract,Indication,Version=2.24.0)
+-- CIM_Indication_no_version (Abstract,Indication)
+-- TST_Lineage (Association,Version=2.20.1)
+-- TST_Lineage_no_version (Association)
""",
'test': 'innows'},
TREE_TEST_MOCK_FILE, OK],
# class tree' error tests
['Verify class command tree with invalid CLASSNAME fails',
['tree', '-s', 'CIM_Foo_subx'],
{'stderr': ['CIMError:'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
['Verify class command tree with superclass option, CLASSNAME fails',
['tree', '-s'],
{'stderr': ['Error: CLASSNAME argument required for --superclasses '
'option'],
'rc': 1,
'test': 'regex'},
SIMPLE_MOCK_FILE, OK],
#
# associators command tests
#
#
['Verify class command associators --help response',
['associators', '--help'],
{'stdout': CLASS_ASSOCIATORS_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command associators -h response',
['associators', '-h'],
{'stdout': CLASS_ASSOCIATORS_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command associators simple request,',
['associators', 'TST_Person'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Person',
'class TST_Person {',
'',
' [Key ( true ),',
' Description ( "This is key prop" )]',
' string name;',
'',
' string extraProperty = "defaultvalue";',
'',
' [ValueMap { "1", "2" },',
' Values { "female", "male" }]',
' uint16 gender;',
'',
' [ValueMap { "1", "2" },',
' Values { "books", "movies" }]',
' uint16 likes[];',
'',
'};',
''],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command associators simple request names only,',
['associators', 'TST_Person', '--names-only'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Person'],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command associators simple request, one parameter',
['associators', 'TST_Person', '--ac', 'TST_MemberOfFamilyCollection'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Person',
'class TST_Person {',
'',
' [Key ( true ),',
' Description ( "This is key prop" )]',
' string name;',
'',
' string extraProperty = "defaultvalue";',
'',
' [ValueMap { "1", "2" },',
' Values { "female", "male" }]',
' uint16 gender;',
'',
' [ValueMap { "1", "2" },',
' Values { "books", "movies" }]',
' uint16 likes[];',
'',
'};',
''],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command associators request, all filters long',
['associators', 'TST_Person',
'--assoc-class', 'TST_MemberOfFamilyCollection',
'--role', 'member',
'--result-role', 'family',
'--result-class', 'TST_Person'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Person',
'class TST_Person {',
'',
' [Key ( true ),',
' Description ( "This is key prop" )]',
' string name;',
'',
' string extraProperty = "defaultvalue";',
'',
' [ValueMap { "1", "2" },',
' Values { "female", "male" }]',
' uint16 gender;',
'',
' [ValueMap { "1", "2" },',
' Values { "books", "movies" }]',
' uint16 likes[];',
'',
'};',
''],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command associators request, all filters short',
['associators', 'TST_Person',
'--ac', 'TST_MemberOfFamilyCollection',
'-r', 'member',
'--rr', 'family',
'--rc', 'TST_Person'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Person',
'class TST_Person {',
'',
' [Key ( true ),',
' Description ( "This is key prop" )]',
' string name;',
'',
' string extraProperty = "defaultvalue";',
'',
' [ValueMap { "1", "2" },',
' Values { "female", "male" }]',
' uint16 gender;',
'',
' [ValueMap { "1", "2" },',
' Values { "books", "movies" }]',
' uint16 likes[];',
'',
'};',
''],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
# Behavior changed pywbem 0.15.0 to exception rtn
['Verify class command associators request, all filters short, -ac '
'not valid class',
['associators', 'TST_Person',
'--ac', 'TST_MemberOfFamilyCollectionx',
'-r', 'member',
'--rr', 'family',
'--rc', 'TST_Person'],
{'stderr': ['CIM_ERR_INVALID_PARAMETER'],
'rc': 1,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
# Behavior changed pywbem 0.15.0 to exception rtn
['Verify class command associators request, all filters short, -r '
'not valid role',
['associators', 'TST_Person',
'--ac', 'TST_MemberOfFamilyCollection',
'-r', 'memberx',
'--rr', 'family',
'--rc', 'TST_Person'],
{'stdout': [],
'test': 'lines'},
SIMPLE_ASSOC_MOCK_FILE, OK],
# Behavior changed pywbem 0.15.0 to exception rtn
['Verify class command associators request, all filters short, --rc '
'does not valid class',
['associators', 'TST_Person',
'--ac', 'TST_MemberOfFamilyCollection',
'-r', 'member',
'--rr', 'family',
'--rc', 'TST_Personx'],
{'stderr': ['CIM_ERR_INVALID_PARAMETER'],
'rc': 1,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
# Behavior changed pywbem 0.15.0 to exception rtn
['Verify class command associators request, all filters long '
'does not pass test',
['associators', 'TST_Person',
'--assoc-class', 'TST_MemberOfFamilyCollection',
'--role', 'member',
'--result-role', 'family',
'--result-class', 'TST_Personx'],
{'stderr': ['CIM_ERR_INVALID_PARAMETER'],
'rc': 1,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
# Associator errors
['Verify class command associators no CLASSNAME',
['associators'],
{'stderr': ['Error: Missing argument .CLASSNAME.'],
'rc': 2,
'test': 'regex'},
None, OK],
# Behavior changed pywbem 0.15.0 to exception rtn
['Verify class command associators non-existent CLASSNAME rtns error',
['associators', 'CIM_Nonexistentclass'],
{'stderr': ["CIM_ERR_INVALID_PARAMETER"],
'rc': 1,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command associators non-existent namespace fails',
['associators', 'TST_Person', '--namespace', 'blah'],
{'stderr': ['CIMError', 'CIM_ERR_INVALID_NAMESPACE'],
'rc': 1,
'test': 'regex'},
SIMPLE_ASSOC_MOCK_FILE, OK],
#
# references command tests
#
['Verify class command references --help response',
['references', '--help'],
{'stdout': CLASS_REFERENCES_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command references -h response',
['references', '-h'],
{'stdout': CLASS_REFERENCES_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command references simple request',
['references', 'TST_Person'],
{'stdout': ['class TST_Lineage {',
'Lineage defines the relationship',
'string InstanceID;',
'TST_Person REF parent;',
'TST_Person REF child;',
'[Association ( true )',
'Description ( " Family gathers person to family." )',
'class TST_MemberOfFamilyCollection {',
'[key ( true )]',
'TST_Person REF family;',
'TST_Person REF member;',
],
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command references simple request -o',
['references', 'TST_Person', '--no'],
{'stdout': [FAKEURL_STR + '/root/cimv2:TST_Lineage',
FAKEURL_STR + '/root/cimv2:TST_MemberOfFamilyCollection'],
'test': 'linesnows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command references request, all filters long',
['references', 'TST_Person',
'--role', 'member',
'--result-class', 'TST_MemberOfFamilyCollection'],
{'stdout': REFERENCES_CLASS_RTN_QUALS2,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command references request, filters short',
['references', 'TST_Person',
'-r', 'member',
'--rc', 'TST_MemberOfFamilyCollection'],
{'stdout': REFERENCES_CLASS_RTN_QUALS2,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command refereces table output fails).',
{'args': ['associators', 'TST_Person'],
'general': ['--output-format', 'table']},
{'stderr': ['Output format "table" ', 'not allowed', 'Only CIM formats:'],
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
# Reference errors
['Verify class command references no CLASSNAME',
['references'],
{'stderr': ['Error: Missing argument .CLASSNAME.'],
'rc': 2,
'test': 'regex'},
None, OK],
# Behavior changed pywbem 0.15.0, references bad param rtns except.
['Verify class command references non-existent CLASSNAME rtns error',
['references', 'CIM_Nonexistentclass'],
{'stderr': ["CIM_ERR_INVALID_PARAMETER"],
'rc': 1,
'test': 'innows'},
SIMPLE_ASSOC_MOCK_FILE, OK],
['Verify class command references non-existent namespace fails',
['references', 'TST_Person', '--namespace', 'blah'],
{'stderr': ['CIMError', 'CIM_ERR_INVALID_NAMESPACE'],
'rc': 1,
'test': 'regex'},
SIMPLE_ASSOC_MOCK_FILE, OK],
#
# invokemethod command tests
#
['Verify class command invokemethod --help response',
['invokemethod', '--help'],
{'stdout': CLASS_INVOKEMETHOD_HELP_LINES,
'test': 'innows'},
None, OK],
['Verify class command invokemethod -h response',
['invokemethod', '-h'],
{'stdout': CLASS_INVOKEMETHOD_HELP_LINES,
'test': 'innows'},
None, OK],
#
# class invokemethod command without parameters
#
['Verify class command invokemethod CIM_Foo.FuzzyStatic() - no in parms',
['invokemethod', 'CIM_Foo', 'FuzzyStatic'],
{'stdout': ["ReturnValue=0"],
'rc': 0,
'test': 'lines'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
['Verify class command invokemethod CIM_Foo.FuzzyStatic() with --namespace',
['invokemethod', 'CIM_Foo', 'FuzzyStatic', '--namespace', 'root/cimv2'],
{'stdout': ["ReturnValue=0"],
'rc': 0,
'test': 'lines'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
# Cannot do a test with interop as default because of issue #991
['Verify class command invokemethod CIM_Foo.FuzzyStatic() with --namespace'
' interop not found to validate that --namspace used',
['invokemethod', 'CIM_Foo', 'FuzzyStatic', '--namespace', 'interop'],
{'stderr': ["CIM_ERR_NOT_FOUND", "not found in namespace 'interop'"],
'rc': 1,
'test': 'innows'},
[SIMPLE_INTEROP_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
['Verify class command invokemethod CIM_Foo.FuzzyStatic() - one in parm',
['invokemethod', 'CIM_Foo', 'FuzzyStatic',
'-p', 'TestInOutParameter="blah"'],
{'stdout': ['ReturnValue=0',
'TestInOutParameter=', 'blah'],
'rc': 0,
'test': 'innows'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
['Verify class command invokemethod fails Invalid Class',
['invokemethod', 'CIM_Foox', 'FuzzyStatic'],
{'stderr': ['CIMError', '6'],
'rc': 1,
'test': 'innows'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
['Verify class command invokemethod fails Invalid Method',
['invokemethod', 'CIM_Foo', 'Fuzzyx'],
{'stderr': ['Class CIM_Foo does not have a method Fuzzyx'],
'rc': 1,
'test': 'innows'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], OK],
['Verify class command invokemethod fails non-static method, pywbem 1.0',
['invokemethod', 'CIM_Foo', 'Fuzzy'],
{'stderr': ["Non-static method 'Fuzzy' in class 'CIM_Foo'"],
'rc': 1,
'test': 'innows'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], PYWBEM_1_0_0],
['Verify class command invokemethod succeeds non-static method, pywbem 0.x',
['invokemethod', 'CIM_Foo', 'Fuzzy'],
{'stdout': ['ReturnValue=0'],
'rc': 0,
'test': 'innows'},
[SIMPLE_MOCK_FILE, INVOKE_METHOD_MOCK_FILE], not PYWBEM_1_0_0],
['Verify class command invokemethod fails Method not registered',
['invokemethod', 'CIM_Foo', 'Fuzzy'],
{'stderr': ['CIMError'],
'rc': 1,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify --timestats gets stats output. Cannot test with lines,execution '
'time is variable.',
{'args': ['get', 'CIM_Foo'],
'general': ['--timestats']},
{'stdout': ['Operation Count Errors',
'GetClass 1 0'],
'rc': 0,
'test': 'innows'},
SIMPLE_MOCK_FILE, OK],
['Verify single command with stdin works',
{'stdin': ['class get -h']},
{'stdout': ['Usage: pywbemcli [GENERAL-OPTIONS] class get '],
'rc': 0,
'test': 'innows'},
None, OK],
['Verify multiple commands with stdin work',
{'stdin': ['class get -h', 'class enumerate -h']},
{'stdout': ['Usage: pywbemcli [GENERAL-OPTIONS] class enumerate ',
'Usage: pywbemcli [GENERAL-OPTIONS] class get '],
'rc': 0,
'test': 'innows'},
None, OK],
]
# TODO command class delete. Extend this test to use stdin (delete, test)
# namespace
# TODO: add test for errors: class invalid, namespace invalid
# other tests. Test local-only on top level
class TestSubcmdClass(CLITestsBase): # pylint: disable=too-few-public-methods
"""
Test all of the class command variations.
"""
command_group = 'class'
@pytest.mark.parametrize(
"desc, inputs, exp_response, mock, condition",
TEST_CASES)
def test_class(self, desc, inputs, exp_response, mock, condition):
"""
Common test method for those commands and options in the
class command that can be tested. This includes:
* Subcommands like help that do not require access to a server
* Subcommands that can be tested with a single execution of a
pywbemcli command.
"""
self.command_test(desc, self.command_group, inputs, exp_response,
mock, condition)
| 37.241451 | 114 | 0.554639 | 8,808 | 89,305 | 5.42223 | 0.063465 | 0.026257 | 0.075378 | 0.069097 | 0.795347 | 0.762495 | 0.727109 | 0.684416 | 0.663561 | 0.637786 | 0 | 0.010492 | 0.28602 | 89,305 | 2,397 | 115 | 37.256988 | 0.738528 | 0.043615 | 0 | 0.658706 | 0 | 0 | 0.562308 | 0.059667 | 0 | 0 | 0 | 0.000417 | 0 | 1 | 0.000498 | false | 0.000498 | 0.00398 | 0 | 0.005473 | 0.000498 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
099bd56c8872287f3abf2cdee5e4888979d01b99 | 86 | py | Python | bigGay/__init__.py | MayaValentia/byleth-bot-dev | d22290156fdac597aca2dd6d83020dbb49ad8ff0 | [
"MIT"
] | 1 | 2020-08-12T18:46:49.000Z | 2020-08-12T18:46:49.000Z | bigGay/__init__.py | MayaValentia/byleth-bot-dev | d22290156fdac597aca2dd6d83020dbb49ad8ff0 | [
"MIT"
] | null | null | null | bigGay/__init__.py | MayaValentia/byleth-bot-dev | d22290156fdac597aca2dd6d83020dbb49ad8ff0 | [
"MIT"
] | 2 | 2020-09-13T02:55:48.000Z | 2021-02-11T09:34:07.000Z | from .bigGay import bigGay
def setup(bot):
cog = bigGay(bot)
bot.add_cog(cog) | 17.2 | 26 | 0.674419 | 14 | 86 | 4.071429 | 0.571429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.209302 | 86 | 5 | 27 | 17.2 | 0.838235 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.25 | 0 | 0.5 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
09a28df0637d0c34e269ec275da4a8046d1b7543 | 385 | py | Python | python-framework/libs/crypto.py | huangxingx/python-framework | a62618b0ee5ecff9de426327892cdd690d10510d | [
"MIT"
] | 7 | 2019-10-24T03:26:22.000Z | 2019-10-27T14:55:07.000Z | python-framework/libs/crypto.py | PJoemu/python-framework | a62618b0ee5ecff9de426327892cdd690d10510d | [
"MIT"
] | 3 | 2021-06-08T19:13:10.000Z | 2022-01-13T00:38:48.000Z | python-framework/libs/crypto.py | PJoemu/python-framework | a62618b0ee5ecff9de426327892cdd690d10510d | [
"MIT"
] | 2 | 2019-10-25T03:54:51.000Z | 2020-06-28T08:50:12.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: x.huang
# @date:17-8-17
from Crypto.Hash import MD5
def encrypto(val):
# python3 需要把进行 encode
# todo 更改项目加密 key
m = MD5.new('python-framework'.encode('utf-8'))
m.update(val.encode('utf-8'))
return m.hexdigest()
def decrypto(val):
pass
if __name__ == '__main__':
print(encrypto('arhieason'))
| 15.4 | 51 | 0.623377 | 55 | 385 | 4.218182 | 0.709091 | 0.051724 | 0.086207 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.035714 | 0.2 | 385 | 24 | 52 | 16.041667 | 0.717532 | 0.285714 | 0 | 0 | 0 | 0 | 0.159851 | 0 | 0 | 0 | 0 | 0.041667 | 0 | 1 | 0.222222 | false | 0.111111 | 0.111111 | 0 | 0.444444 | 0.111111 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 3 |
09c972c8ee2252231ba255a8d7fd24be9200e9e4 | 445 | py | Python | chat/tests/factories.py | gurupratap-matharu/chatylon | d23ce4b9fa3954ad49fc18647ccf54cd0cc73cf8 | [
"MIT"
] | 4 | 2020-11-16T01:53:17.000Z | 2021-09-01T06:02:31.000Z | chat/tests/factories.py | gurupratap-matharu/chatylon | d23ce4b9fa3954ad49fc18647ccf54cd0cc73cf8 | [
"MIT"
] | null | null | null | chat/tests/factories.py | gurupratap-matharu/chatylon | d23ce4b9fa3954ad49fc18647ccf54cd0cc73cf8 | [
"MIT"
] | null | null | null | import factory
from chat.models import Chat, ChatRoom
from users.factories import UserFactory
class ChatRoomFactory(factory.django.DjangoModelFactory):
class Meta:
model = ChatRoom
name = factory.Faker('word')
class ChatFactory(factory.django.DjangoModelFactory):
class Meta:
model = Chat
body = factory.Faker('sentence')
author = factory.SubFactory(UserFactory)
room = factory.SubFactory(ChatRoom)
| 22.25 | 57 | 0.730337 | 47 | 445 | 6.914894 | 0.510638 | 0.08 | 0.190769 | 0.221538 | 0.276923 | 0.276923 | 0 | 0 | 0 | 0 | 0 | 0 | 0.186517 | 445 | 19 | 58 | 23.421053 | 0.89779 | 0 | 0 | 0.153846 | 0 | 0 | 0.026966 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.230769 | 0 | 0.846154 | 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 | 1 | 0 | 0 | 3 |
09cd5bd9b3afeaf12e00c4f547e27cdd27294e5a | 394 | py | Python | projecteuler/util/summation.py | Tenebrar/codebase | 59c9a35289fb29afedad0e3edd0519b67372ef9f | [
"Unlicense"
] | 1 | 2020-04-21T11:39:25.000Z | 2020-04-21T11:39:25.000Z | projecteuler/util/summation.py | Tenebrar/codebase | 59c9a35289fb29afedad0e3edd0519b67372ef9f | [
"Unlicense"
] | 7 | 2020-02-12T01:08:01.000Z | 2022-02-10T11:56:56.000Z | projecteuler/util/summation.py | Tenebrar/codebase | 59c9a35289fb29afedad0e3edd0519b67372ef9f | [
"Unlicense"
] | null | null | null | def sum_all_to(num: int) -> int:
""" Return the sum of all numbers up to and including the input number """
return num * (num + 1) // 2
def square_pyramidal_number(num: int) -> int:
""" Return the sum of the squares of all numbers up to and including the input number """
# https://en.wikipedia.org/wiki/Square_pyramidal_number
return num * (num + 1) * (2 * num + 1) // 6
| 39.4 | 93 | 0.649746 | 64 | 394 | 3.90625 | 0.40625 | 0.048 | 0.072 | 0.12 | 0.648 | 0.648 | 0.512 | 0.336 | 0.336 | 0.336 | 0 | 0.019672 | 0.225888 | 394 | 9 | 94 | 43.777778 | 0.8 | 0.520305 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 3 |
61e6e408c9d358e1ba90de75b214eb2a33ce5303 | 2,663 | py | Python | sourcecode/src/vx/lha/Main.py | ivarvb/LHA | b3b7613180d533468edf762195922b73c70c525c | [
"MIT"
] | null | null | null | sourcecode/src/vx/lha/Main.py | ivarvb/LHA | b3b7613180d533468edf762195922b73c70c525c | [
"MIT"
] | null | null | null | sourcecode/src/vx/lha/Main.py | ivarvb/LHA | b3b7613180d533468edf762195922b73c70c525c | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Ivar
"""
from Description import *
from Classification import *
if __name__ == "__main__":
inputdir = "../../../../data/LHA/dataset_1"
outputdir = inputdir+"/csv/exp/"+Util.now()
template = [
{
"name":"RAD",
"imagedir":"images_cleaned",
"maskdir":"seg/seg_window",
"masksubsetdir":"100",
"parameters":{"tile_size":100},
"erode":[30]
},
{
"name":"RAD",
"imagedir":"images_cleaned",
"maskdir":"seg/seg_window",
"masksubsetdir":"200",
"parameters":{"tile_size":200},
"erode":[30]
},
{
"name":"RAD",
"imagedir":"images_cleaned",
"maskdir":"seg/seg_window",
"masksubsetdir":"300",
"parameters":{"tile_size":300},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"100",
"parameters":{"tile_size":100, "radius":5},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"200",
"parameters":{"tile_size":200, "radius":5},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"300",
"parameters":{"tile_size":300, "radius":5},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"100",
"parameters":{"tile_size":100, "radius":10},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"200",
"parameters":{"tile_size":200, "radius":10},
"erode":[30]
},
{
"name":"LBP",
"imagedir":"images_cleaned",
"maskdir":"masks",
"masksubsetdir":"300",
"parameters":{"tile_size":300, "radius":10},
"erode":[30]
},
]
inputdir = "../../../../data/LHA/dataset_2"
outputdir = inputdir+"/csv/exp/"+Util.now()
Description.start(inputdir, outputdir, template)
Classification.start(outputdir, outputdir)
print("Complete in {}".format(outputdir))
| 23.156522 | 56 | 0.437852 | 208 | 2,663 | 5.456731 | 0.259615 | 0.111013 | 0.16652 | 0.222026 | 0.769163 | 0.769163 | 0.652863 | 0.652863 | 0.652863 | 0.652863 | 0 | 0.05099 | 0.374014 | 2,663 | 115 | 57 | 23.156522 | 0.629874 | 0.021029 | 0 | 0.559524 | 0 | 0 | 0.343209 | 0.023086 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.02381 | 0 | 0.02381 | 0.011905 | 0 | 0 | 0 | null | 0 | 0 | 1 | 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 | 3 |
61e83a0c30e6a67dbfeb574d16e0f027af82160b | 538 | py | Python | randutils/lists.py | JoelLefkowitz/randutils | 91bfb6a56676675edb241f11b602a46880520c72 | [
"MIT"
] | 1 | 2021-08-03T17:34:31.000Z | 2021-08-03T17:34:31.000Z | randutils/lists.py | JoelLefkowitz/randutils | 91bfb6a56676675edb241f11b602a46880520c72 | [
"MIT"
] | null | null | null | randutils/lists.py | JoelLefkowitz/randutils | 91bfb6a56676675edb241f11b602a46880520c72 | [
"MIT"
] | null | null | null | import numpy as np
from .chance import by_chance
from .exceptions import EmptyListError
def pop_random_entry(lst):
if not lst:
raise EmptyListError
index = np.random.randint(0, len(lst))
return lst.pop(index)
def pick_random_entry(lst):
if not lst:
raise EmptyListError
index = np.random.randint(0, len(lst))
return lst[index]
def randomly_filter(lst, weight=0.1):
return [i for i in lst if by_chance(weight)]
def scramble(lst):
return sorted(lst, key=lambda x: random.random())
| 18.551724 | 53 | 0.689591 | 82 | 538 | 4.439024 | 0.426829 | 0.041209 | 0.076923 | 0.087912 | 0.423077 | 0.423077 | 0.423077 | 0.423077 | 0.423077 | 0.423077 | 0 | 0.009456 | 0.213755 | 538 | 28 | 54 | 19.214286 | 0.851064 | 0 | 0 | 0.352941 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.235294 | false | 0 | 0.176471 | 0.117647 | 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 | 1 | 1 | 0 | 0 | 3 |
61f42117264c7b5f1ae0b590ff1b7ddfa85808ba | 11,119 | py | Python | test3.py | dg1223/GestureRecognition | 07078b0b8340c8b94f42414efe0ed36158e8c0ea | [
"MIT"
] | 2 | 2019-02-12T17:59:41.000Z | 2019-10-27T03:36:08.000Z | test3.py | dg1223/GestureRecognition | 07078b0b8340c8b94f42414efe0ed36158e8c0ea | [
"MIT"
] | null | null | null | test3.py | dg1223/GestureRecognition | 07078b0b8340c8b94f42414efe0ed36158e8c0ea | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 00:07:11 2015
@author: Shamir
"""
def CalculateValidData():
# Calculate the number of missing values in the array
number_of_nan = len(readFile.values[m][pandas.isnull(readFile.values[m])])
length_of_array = len(readFile.values[m])
valid_datapoints = length_of_array - number_of_nan
return valid_datapoints
for i in range(len(os.listdir(sourcePath))): # we have 6 files corresponding to 6 gestures
print 'i = ', i
gesture = os.listdir(sourcePath)[i] # Jab, Uppercut, Throw, Jets, Block, Asgard
#dataset = os.listdir(sourcePath + gesture)[0] # Train, Cross Validation, Test
copy = False
AngVel_array = []
for k in range(len(os.listdir(sourcePath + gesture))):
sensor = os.listdir(sourcePath + gesture)[k] # Sensor15, Sensor16, Sensor17, Sensor18, Sensor19
sensorFolder = os.listdir(sourcePath + gesture + backslash + sensor)
print sensorFolder
for l in range(len(sensorFolder)):
csvfile = sourcePath + gesture + backslash + sensor + backslash + sensorFolder[l] # full filepath
readFile = pandas.read_csv(csvfile, header = None)
readFile.values[1:] = readFile.values[1:].astype(float)
velocityAlpha = ['Precession_' + sensor[6:]]
velocityBeta = ['Nutation_' + sensor[6:]]
velocityGamma = ['Spin_' + sensor[6:]]
#print velocityAlpha
velocityAlpha = np.asarray(velocityAlpha)
velocityBeta = np.asarray(velocityBeta)
velocityGamma = np.asarray(velocityGamma)
#time = np.shape(readFile.values)[1] / frequency_euc
if copy == True:
print 'This is the If phase'
for m in range(1, len(readFile.values)): # for every two files ???
## need to add code to check if number_of_rows matches
precession, nutation, spin = 0, 0, 0
for n in range(0, np.shape(readFile.values)[1] - 5, 3):
alpha = n
beta = n + 1
gamma = n + 2
alphaNext = n + 3
betaNext = n + 4
gammaNext = n + 5
try:
precession += euclidean(readFile.values[m, alpha], readFile.values[m, alphaNext])
#print 'precession = ', precession
nutation += euclidean(readFile.values[m, beta], readFile.values[m, betaNext])
spin += euclidean(readFile.values[m, gamma], readFile.values[m, gammaNext])
except ValueError:
#print '1st catch (copy = True) at file, m, n = ', csvfile[-6:], m, n
break
valid_data = CalculateValidData() # Exclude missing values (we exclude 6 more values to remain within a safer margin)
time = valid_data / frequency_euc
precessionVelocity = precession/time
#print 'precessionVelocity = ', precessionVelocity
nutationVelocity = nutation/time
spinVelocity = spin/time
for n in range(0, np.shape(readFile.values)[1] - 3, 3):
alpha = n
beta = n + 1
gamma = n + 2
try:
readFile.values[m, alpha] = (precessionVelocity * np.sin(readFile.values[m, gamma]) * np.sin(readFile.values[m, beta])) + (nutationVelocity * np.cos(readFile.values[m, gamma])) # alpha component
readFile.values[m, beta] = (precessionVelocity * np.cos(readFile.values[m, gamma]) * np.sin(readFile.values[m, beta])) - (nutationVelocity * np.sin(readFile.values[m, gamma])) # beta component
readFile.values[m, beta] = (precessionVelocity * np.cos(readFile.values[m, beta])) * spinVelocity # gamma compomemt
except ValueError:
#print '2nd catch (copy = True) at file, m, n = ', csvfile[-6:], m, n
continue
averageAlpha = np.sum(readFile.values[m, range(0, valid_data, 3)]) / time
averageBeta = np.sum(readFile.values[m, range(1, valid_data, 3)]) / time
averageGamma = np.sum(readFile.values[m, range(2, valid_data, 3)]) / time
velocityAlpha = np.vstack((velocityAlpha, averageAlpha))
#print 'filename, m, velocityAlpha = ', csvfile[-6:], m, velocityAlpha
velocityBeta = np.vstack((velocityBeta, averageBeta))
velocityGamma = np.vstack((velocityGamma, averageGamma))
columnSize = len(velocityAlpha)
angular_velocity = np.zeros((len(velocityAlpha), 3))
angular_velocity = angular_velocity.astype(str) # to avoid string to float conversion error
# Return the column vectors in a single 2D array
angular_velocity[:,0] = velocityAlpha.reshape(1, columnSize)
angular_velocity[:,1] = velocityBeta.reshape (1, columnSize)
angular_velocity[:,2] = velocityGamma.reshape(1, columnSize)
AngVel_array = np.hstack((AngVel_array, angular_velocity))
#print 'AngVel_array = ', AngVel_array
else:
print 'This is the Else phase'
for m in range(1, len(readFile.values)): # for every two files
## need to add code to check if number_of_rows matches
precession, nutation, spin = 0, 0, 0
for n in range(0, np.shape(readFile.values)[1] - 5, 3):
alpha = n
beta = n + 1
gamma = n + 2
alphaNext = n + 3
betaNext = n + 4
gammaNext = n + 5
try:
precession += euclidean(readFile.values[m, alpha], readFile.values[m, alphaNext])
nutation += euclidean(readFile.values[m, beta], readFile.values[m, betaNext])
spin += euclidean(readFile.values[m, gamma], readFile.values[m, gammaNext])
except ValueError:
#print '1st catch (copy = False) at print file, m, n = ', csvfile[-6:], m, n
continue
valid_data = CalculateValidData()
time = valid_data / frequency_euc
precessionVelocity = precession/time
nutationVelocity = nutation/time
spinVelocity = spin/time
#print 'precession,nutation,spinVelocity = ', precessionVelocity, nutationVelocity, spinVelocity
for n in range(0, np.shape(readFile.values)[1] - 3, 3):
alpha = n
beta = n + 1
gamma = n + 2
try:
readFile.values[m, alpha] = (precessionVelocity * np.sin(readFile.values[m, gamma]) * np.sin(readFile.values[m, beta])) + (nutationVelocity * np.cos(readFile.values[m, gamma])) # alpha component
readFile.values[m, beta] = (precessionVelocity * np.cos(readFile.values[m, gamma]) * np.sin(readFile.values[m, beta])) - (nutationVelocity * np.sin(readFile.values[m, gamma])) # beta component
readFile.values[m, beta] = (precessionVelocity * np.cos(readFile.values[m, beta])) * spinVelocity # gamma compomemt
except ValueError:
#print '2nd catch (copy = True) at file, m, n = ', csvfile[-6:], m, n
continue
averageAlpha = np.sum(readFile.values[m, range(0, valid_data, 3)]) / time
#print 'averageAlpha = ', averageAlpha
averageBeta = np.sum(readFile.values[m, range(1, valid_data, 3)]) / time
averageGamma = np.sum(readFile.values[m, range(2, valid_data, 3)]) / time
velocityAlpha = np.vstack((velocityAlpha, averageAlpha))
#print 'filename, m, velocityAlpha = ', csvfile[-6:], m, velocityAlpha
velocityBeta = np.vstack((velocityBeta, averageBeta))
velocityGamma = np.vstack((velocityGamma, averageGamma))
columnSize = len(velocityAlpha)
angular_velocity = np.zeros((len(velocityAlpha), 3))
angular_velocity = angular_velocity.astype(str)
# Return the column vectors in a single 2D array
angular_velocity[:,0] = velocityAlpha.reshape(1, columnSize)
angular_velocity[:,1] = velocityBeta.reshape (1, columnSize)
angular_velocity[:,2] = velocityGamma.reshape(1, columnSize)
AngVel_array = angular_velocity.copy()
#print 'AngVel_array = ', AngVel_array
copy = True
# Create complete file structure/dataframe
if i == 0:
fullFile4 = DataFrame(AngVel_array)
else:
AngVel_array = DataFrame(AngVel_array)
fullFile4 = pandas.concat([fullFile4, AngVel_array], join = 'inner')
| 63.176136 | 229 | 0.461462 | 958 | 11,119 | 5.296451 | 0.183716 | 0.137958 | 0.121206 | 0.044935 | 0.683879 | 0.6689 | 0.638549 | 0.638549 | 0.611352 | 0.611352 | 0 | 0.018528 | 0.451479 | 11,119 | 175 | 230 | 63.537143 | 0.813412 | 0.153431 | 0 | 0.708333 | 0 | 0 | 0.00817 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.033333 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
1106ac76603f4bd71050edfab94366e8d6245198 | 43,058 | py | Python | tests/test_decision_maker/test_base.py | cyenyxe/agents-aea | c2aec9127028ae13def3f69fbc80d35400de1565 | [
"Apache-2.0"
] | null | null | null | tests/test_decision_maker/test_base.py | cyenyxe/agents-aea | c2aec9127028ae13def3f69fbc80d35400de1565 | [
"Apache-2.0"
] | 1 | 2020-02-21T14:28:13.000Z | 2020-03-05T14:53:53.000Z | tests/test_decision_maker/test_base.py | cyenyxe/agents-aea | c2aec9127028ae13def3f69fbc80d35400de1565 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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.
#
# ------------------------------------------------------------------------------
"""This module contains tests for decision_maker."""
import os
import time
from queue import Queue
from unittest import mock
import pytest
from web3.auto import Web3
import aea
import aea.decision_maker.base
from aea.configurations.base import PublicId
from aea.crypto.ethereum import ETHEREUM
from aea.crypto.fetchai import DEFAULT_FETCHAI_CONFIG
from aea.crypto.ledger_apis import LedgerApis
from aea.crypto.wallet import FETCHAI, Wallet
from aea.decision_maker.base import DecisionMaker, OwnershipState, Preferences
from aea.decision_maker.base import LedgerStateProxy
from aea.decision_maker.messages.base import InternalMessage
from aea.decision_maker.messages.state_update import StateUpdateMessage
from aea.decision_maker.messages.transaction import TransactionMessage
from aea.mail.base import Multiplexer, OutBox
from aea.protocols.default.message import DefaultMessage
from ..conftest import CUR_PATH, DUMMY_CONNECTION_PUBLIC_ID, DummyConnection
MAX_REACTIONS = 10
class TestOwnershipState:
"""Test the base.py for DecisionMaker."""
@classmethod
def setup_class(cls):
"""Initialise the class."""
cls.ownership_state = OwnershipState()
def test_properties(self):
"""Test the assertion error for *_holdings."""
with pytest.raises(AssertionError):
self.ownership_state.amount_by_currency_id
with pytest.raises(AssertionError):
self.ownership_state.quantities_by_good_id
def test_initialisation(self):
"""Test the initialisation of the ownership_state."""
currency_endowment = {"FET": 100}
good_endowment = {"good_id": 2}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
assert self.ownership_state.amount_by_currency_id is not None
assert self.ownership_state.quantities_by_good_id is not None
assert self.ownership_state.is_initialized
def test_body(self):
"""Test the setter for the body."""
msg = InternalMessage()
msg.body = {"test_key": "test_value"}
other_msg = InternalMessage(body={"test_key": "test_value"})
assert msg == other_msg, "Messages should be equal."
assert str(msg) == "InternalMessage(test_key=test_value)"
assert msg._body is not None
msg.body = {"Test": "My_test"}
assert msg._body == {
"Test": "My_test"
}, "Message body must be equal with the above dictionary."
msg.set("Test", 2)
assert msg._body["Test"] == 2, "body['Test'] should be equal to 2."
msg.unset("Test")
assert "Test" not in msg._body.keys(), "Test should not exist."
def test_transaction_is_affordable_agent_is_buyer(self):
"""Check if the agent has the money to cover the sender_amount (the agent=sender is the buyer)."""
currency_endowment = {"FET": 100}
good_endowment = {"good_id": 20}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": -1},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
assert self.ownership_state.is_affordable_transaction(
tx_message=tx_message
), "We should have the money for the transaction!"
def test_transaction_is_affordable_there_is_no_wealth(self):
"""Reject the transaction when there is no wealth exchange."""
currency_endowment = {"FET": 0}
good_endowment = {"good_id": 0}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": 0},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
assert not self.ownership_state.is_affordable_transaction(
tx_message=tx_message
), "We must reject the transaction."
def tests_transaction_is_affordable_agent_is_the_seller(self):
"""Check if the agent has the goods (the agent=sender is the seller)."""
currency_endowment = {"FET": 0}
good_endowment = {"good_id": 0}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": 10},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
assert self.ownership_state.is_affordable_transaction(
tx_message=tx_message
), "We must reject the transaction."
def tests_transaction_is_affordable_else_statement(self):
"""Check that the function returns false if we cannot satisfy any if/elif statements."""
currency_endowment = {"FET": 0}
good_endowment = {"good_id": 0}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": 10},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 50},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
assert not self.ownership_state.is_affordable_transaction(
tx_message=tx_message
), "We must reject the transaction."
def test_apply(self):
"""Test the apply function."""
currency_endowment = {"FET": 100}
good_endowment = {"good_id": 2}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=5,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
list_of_transactions = [tx_message]
state = self.ownership_state
new_state = self.ownership_state.apply_transactions(
transactions=list_of_transactions
)
assert (
state != new_state
), "after applying a list_of_transactions must have a different state!"
def test_transaction_update(self):
"""Test the transaction update when sending tokens."""
currency_endowment = {"FET": 100}
good_endowment = {"good_id": 20}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
assert self.ownership_state.amount_by_currency_id == currency_endowment
assert self.ownership_state.quantities_by_good_id == good_endowment
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=5,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
self.ownership_state._update(tx_message=tx_message)
expected_amount_by_currency_id = {"FET": 75}
expected_quantities_by_good_id = {"good_id": 30}
assert (
self.ownership_state.amount_by_currency_id == expected_amount_by_currency_id
)
assert (
self.ownership_state.quantities_by_good_id == expected_quantities_by_good_id
)
def test_transaction_update_receive(self):
"""Test the transaction update when receiving tokens."""
currency_endowment = {"FET": 75}
good_endowment = {"good_id": 30}
self.ownership_state.init(
amount_by_currency_id=currency_endowment,
quantities_by_good_id=good_endowment,
)
assert self.ownership_state.amount_by_currency_id == currency_endowment
assert self.ownership_state.quantities_by_good_id == good_endowment
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": 20},
tx_sender_fee=5,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": -10},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
self.ownership_state._update(tx_message=tx_message)
expected_amount_by_currency_id = {"FET": 90}
expected_quantities_by_good_id = {"good_id": 20}
assert (
self.ownership_state.amount_by_currency_id == expected_amount_by_currency_id
)
assert (
self.ownership_state.quantities_by_good_id == expected_quantities_by_good_id
)
class TestPreferencesDecisionMaker:
"""Test the preferences."""
@classmethod
def setup_class(cls):
"""Initialise the class."""
cls.preferences = Preferences()
cls.ownership_state = OwnershipState()
cls.good_holdings = {"good_id": 2}
cls.currency_holdings = {"FET": 100}
cls.utility_params = {"good_id": 20.0}
cls.exchange_params = {"FET": 10.0}
cls.tx_fee = 9
def test_preferences_properties(self):
"""Test the properties of the preferences class."""
with pytest.raises(AssertionError):
self.preferences.exchange_params_by_currency_id
with pytest.raises(AssertionError):
self.preferences.utility_params_by_good_id
def test_preferences_init(self):
"""Test the preferences init()."""
self.preferences.init(
exchange_params_by_currency_id=self.exchange_params,
utility_params_by_good_id=self.utility_params,
tx_fee=self.tx_fee,
)
assert self.preferences.utility_params_by_good_id is not None
assert self.preferences.exchange_params_by_currency_id is not None
assert self.preferences.transaction_fees["seller_tx_fee"] == 4
assert self.preferences.transaction_fees["buyer_tx_fee"] == 5
assert self.preferences.is_initialized
def test_logarithmic_utility(self):
"""Calculate the logarithmic utility and checks that it is not none.."""
self.preferences.init(
utility_params_by_good_id=self.utility_params,
exchange_params_by_currency_id=self.exchange_params,
tx_fee=self.tx_fee,
)
log_utility = self.preferences.logarithmic_utility(
quantities_by_good_id=self.good_holdings
)
assert log_utility is not None, "Log_utility must not be none."
def test_linear_utility(self):
"""Calculate the linear_utility and checks that it is not none."""
linear_utility = self.preferences.linear_utility(
amount_by_currency_id=self.currency_holdings
)
assert linear_utility is not None, "Linear utility must not be none."
def test_get_score(self):
"""Calculate the score."""
score = self.preferences.get_score(
quantities_by_good_id=self.good_holdings,
amount_by_currency_id=self.currency_holdings,
)
linear_utility = self.preferences.linear_utility(
amount_by_currency_id=self.currency_holdings
)
log_utility = self.preferences.logarithmic_utility(
quantities_by_good_id=self.good_holdings
)
assert (
score == log_utility + linear_utility
), "The score must be equal to the sum of log_utility and linear_utility."
def test_marginal_utility(self):
"""Test the marginal utility."""
delta_good_holdings = {"good_id": 1}
delta_currency_holdings = {"FET": -5}
self.ownership_state.init(
amount_by_currency_id=self.currency_holdings,
quantities_by_good_id=self.good_holdings,
)
marginal_utility = self.preferences.marginal_utility(
ownership_state=self.ownership_state,
delta_quantities_by_good_id=delta_good_holdings,
delta_amount_by_currency_id=delta_currency_holdings,
)
assert marginal_utility is not None, "Marginal utility must not be none."
def test_score_diff_from_transaction(self):
"""Test the difference between the scores."""
good_holdings = {"good_id": 2}
currency_holdings = {"FET": 100}
utility_params = {"good_id": 20.0}
exchange_params = {"FET": 10.0}
tx_fee = 3
self.ownership_state.init(
amount_by_currency_id=currency_holdings, quantities_by_good_id=good_holdings
)
self.preferences.init(
utility_params_by_good_id=utility_params,
exchange_params_by_currency_id=exchange_params,
tx_fee=tx_fee,
)
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=self.preferences.transaction_fees["seller_tx_fee"],
tx_counterparty_fee=self.preferences.transaction_fees["buyer_tx_fee"],
tx_quantities_by_good_id={"good_id": 10},
info={"some_info_key": "some_info_value"},
ledger_id="fetchai",
tx_nonce="transaction nonce",
)
cur_score = self.preferences.get_score(
quantities_by_good_id=good_holdings, amount_by_currency_id=currency_holdings
)
new_state = self.ownership_state.apply_transactions([tx_message])
new_score = self.preferences.get_score(
quantities_by_good_id=new_state.quantities_by_good_id,
amount_by_currency_id=new_state.amount_by_currency_id,
)
dif_scores = new_score - cur_score
score_difference = self.preferences.get_score_diff_from_transaction(
ownership_state=self.ownership_state, tx_message=tx_message
)
assert (
score_difference == dif_scores
), "The calculated difference must be equal to the return difference from the function."
@classmethod
def teardown_class(cls):
"""Teardown any state that was previously setup with a call to setup_class."""
class TestDecisionMaker:
"""Test the decision maker."""
@classmethod
def _patch_logger(cls):
cls.patch_logger_warning = mock.patch.object(
aea.decision_maker.base.logger, "warning"
)
cls.mocked_logger_warning = cls.patch_logger_warning.__enter__()
@classmethod
def _unpatch_logger(cls):
cls.mocked_logger_warning.__exit__()
@classmethod
def setup_class(cls):
"""Initialise the decision maker."""
cls._patch_logger()
cls.multiplexer = Multiplexer(
[DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)]
)
cls.outbox = OutBox(cls.multiplexer)
private_key_pem_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
eth_private_key_pem_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
cls.wallet = Wallet(
{FETCHAI: private_key_pem_path, ETHEREUM: eth_private_key_pem_path}
)
cls.ledger_apis = LedgerApis({FETCHAI: DEFAULT_FETCHAI_CONFIG}, FETCHAI)
cls.agent_name = "test"
cls.ownership_state = OwnershipState()
cls.preferences = Preferences()
cls.decision_maker = DecisionMaker(
agent_name=cls.agent_name,
max_reactions=MAX_REACTIONS,
outbox=cls.outbox,
wallet=cls.wallet,
ledger_apis=cls.ledger_apis,
)
cls.multiplexer.connect()
cls.tx_id = "transaction0"
cls.tx_sender_addr = "agent_1"
cls.tx_counterparty_addr = "pk"
cls.info = {"some_info_key": "some_info_value"}
cls.ledger_id = "fetchai"
cls.decision_maker.start()
def test_properties(self):
"""Test the properties of the decision maker."""
assert self.decision_maker.outbox.empty()
assert isinstance(self.decision_maker.message_in_queue, Queue)
assert isinstance(self.decision_maker.message_out_queue, Queue)
assert isinstance(self.decision_maker.ledger_apis, LedgerApis)
assert isinstance(self.outbox, OutBox)
def test_decision_maker_execute(self):
"""Test the execute method."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id=self.ledger_id,
tx_nonce="Transaction nonce",
)
self.decision_maker.message_in_queue.put_nowait(tx_message)
# test that after a while the queue has been consumed.
time.sleep(0.5)
assert self.decision_maker.message_in_queue.empty()
time.sleep(0.5)
assert not self.decision_maker.message_out_queue.empty()
# TODO test the content of the response.
response = self.decision_maker.message_out_queue.get() # noqa
def test_decision_maker_handle_state_update_initialize(self):
"""Test the handle method for a stateUpdate message with Initialize performative."""
good_holdings = {"good_id": 2}
currency_holdings = {"FET": 100}
utility_params = {"good_id": 20.0}
exchange_params = {"FET": 10.0}
tx_fee = 1
state_update_message = StateUpdateMessage(
performative=StateUpdateMessage.Performative.INITIALIZE,
amount_by_currency_id=currency_holdings,
quantities_by_good_id=good_holdings,
exchange_params_by_currency_id=exchange_params,
utility_params_by_good_id=utility_params,
tx_fee=tx_fee,
)
self.decision_maker.handle(state_update_message)
assert self.decision_maker.ownership_state.amount_by_currency_id is not None
assert self.decision_maker.ownership_state.quantities_by_good_id is not None
assert (
self.decision_maker.preferences.exchange_params_by_currency_id is not None
)
assert self.decision_maker.preferences.utility_params_by_good_id is not None
def test_decision_maker_handle_update_apply(self):
"""Test the handle method for a stateUpdate message with APPLY performative."""
good_holdings = {"good_id": 2}
currency_holdings = {"FET": 100}
currency_deltas = {"FET": -10}
good_deltas = {"good_id": 1}
state_update_message = StateUpdateMessage(
performative=StateUpdateMessage.Performative.APPLY,
amount_by_currency_id=currency_deltas,
quantities_by_good_id=good_deltas,
)
self.decision_maker.handle(state_update_message)
expected_amount_by_currency_id = {
key: currency_holdings.get(key, 0) + currency_deltas.get(key, 0)
for key in set(currency_holdings) | set(currency_deltas)
}
expected_quantities_by_good_id = {
key: good_holdings.get(key, 0) + good_deltas.get(key, 0)
for key in set(good_holdings) | set(good_deltas)
}
assert (
self.decision_maker.ownership_state.amount_by_currency_id
== expected_amount_by_currency_id
), "The amount_by_currency_id must be equal with the expected amount."
assert (
self.decision_maker.ownership_state.quantities_by_good_id
== expected_quantities_by_good_id
)
# TODO this used to work with the testnet
def test_decision_maker_handle_tx_message(self):
"""Test the handle tx message method."""
assert self.decision_maker.message_out_queue.empty()
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id=self.ledger_id,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker.ledger_apis, "token_balance", return_value=1000000
):
with mock.patch.object(
self.decision_maker.ledger_apis,
"transfer",
return_value="This is a test digest",
):
self.decision_maker.handle(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_decision_maker_handle_unknown_tx_message(self):
"""Test the handle tx message method."""
patch_logger_error = mock.patch.object(aea.decision_maker.base.logger, "error")
mocked_logger_error = patch_logger_error.__enter__()
with mock.patch(
"aea.decision_maker.messages.transaction.TransactionMessage._is_consistent",
return_value=True,
):
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id="bitcoin",
)
self.decision_maker.handle(tx_message)
mocked_logger_error.assert_called_with(
"[test]: ledger_id=bitcoin is not supported"
)
def test_decision_maker_handle_tx_message_not_ready(self):
"""Test that the decision maker is not ready to pursuit the goals.Cannot handle the message."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id=self.ledger_id,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker.ledger_apis, "token_balance", return_value=1000000
):
with mock.patch.object(
self.decision_maker.ledger_apis,
"transfer",
return_value="This is a test digest",
):
with mock.patch(
"aea.decision_maker.base.GoalPursuitReadiness.Status"
) as mocked_status:
mocked_status.READY.value = False
self.decision_maker.handle(tx_message)
assert not self.decision_maker.goal_pursuit_readiness.is_ready
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id=self.ledger_id,
tx_nonce="transaction nonce",
)
self.decision_maker.handle(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_decision_maker_hand_tx_ready_for_signing(self):
"""Test that the decision maker can handle a message that is ready for signing."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
ledger_id=self.ledger_id,
info=self.info,
signing_payload={"key": b"some_bytes"},
)
self.decision_maker.handle(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_decision_maker_handle_tx_message_acceptable_for_settlement(self):
"""Test that a tx_message is acceptable for settlement."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
info=self.info,
ledger_id=self.ledger_id,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker, "_is_acceptable_for_settlement", return_value=True
):
with mock.patch.object(
self.decision_maker, "_settle_tx", return_value="tx_digest"
):
self.decision_maker.handle(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_decision_maker_tx_message_is_not_acceptable_for_settlement(self):
"""Test that a tx_message is not acceptable for settlement."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -2},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id=self.ledger_id,
info=self.info,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker, "_is_acceptable_for_settlement", return_value=True
):
with mock.patch.object(
self.decision_maker, "_settle_tx", return_value=None
):
self.decision_maker.handle(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_decision_maker_execute_w_wrong_input(self):
"""Test the execute method with wrong input."""
default_message = DefaultMessage(
type=DefaultMessage.Type.BYTES, content=b"hello"
)
self.decision_maker.message_in_queue.put_nowait(default_message)
time.sleep(0.5)
self.mocked_logger_warning.assert_called_with(
"[{}]: Message received by the decision maker is not of protocol_id=internal.".format(
self.agent_name
)
)
def test_is_affordable_off_chain(self):
"""Test the off_chain message."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="off_chain",
info=self.info,
tx_nonce="Transaction nonce",
)
assert self.decision_maker._is_affordable(tx_message)
def test_is_not_affordable_ledger_state_proxy(self):
"""Test that the tx_message is not affordable with initialized ledger_state_proxy."""
with mock.patch(
"aea.decision_maker.messages.transaction.TransactionMessage._is_consistent",
return_value=True,
):
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="bitcoin",
info=self.info,
)
var = self.decision_maker._is_affordable(tx_message)
assert not var
def test_is_affordable_ledger_state_proxy(self):
"""Test that the tx_message is affordable with initialized ledger_state_proxy."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id=self.ledger_id,
info=self.info,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker, "_is_acceptable_for_settlement", return_value=True
):
with mock.patch.object(
self.decision_maker, "_settle_tx", return_value="tx_digest"
):
self.decision_maker._is_affordable(tx_message)
assert not self.decision_maker.message_out_queue.empty()
def test_settle_tx_off_chain(self):
"""Test the off_chain message."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="off_chain",
info=self.info,
tx_nonce="Transaction nonce",
)
tx_digest = self.decision_maker._settle_tx(tx_message)
assert tx_digest == "off_chain_settlement"
def test_settle_tx_known_chain(self):
"""Test the off_chain message."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id=self.ledger_id,
info=self.info,
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.decision_maker.ledger_apis, "transfer", return_value="tx_digest"
):
tx_digest = self.decision_maker._settle_tx(tx_message)
assert tx_digest == "tx_digest"
def test_is_utility_enhancing(self):
"""Test the utility enhancing for off_chain message."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="off_chain",
info=self.info,
tx_nonce="Transaction nonce",
)
self.decision_maker.ownership_state._quantities_by_good_id = None
assert self.decision_maker._is_utility_enhancing(tx_message)
def test_sign_tx_fetchai(self):
"""Test the private function sign_tx of the decision maker for fetchai ledger_id."""
tx_hash = Web3.keccak(text="some_bytes")
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
ledger_id=self.ledger_id,
info=self.info,
signing_payload={"tx_hash": tx_hash},
)
tx_signature = self.decision_maker._sign_tx(tx_message)
assert tx_signature is not None
def test_sign_tx_fetchai_is_acceptable_for_signing(self):
"""Test the private function sign_tx of the decision maker for fetchai ledger_id."""
tx_hash = Web3.keccak(text="some_bytes")
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
ledger_id=self.ledger_id,
info=self.info,
signing_payload={"tx_hash": tx_hash},
)
tx_signature = self.decision_maker._sign_tx(tx_message)
assert tx_signature is not None
def test_sing_tx_offchain(self):
"""Test the private function sign_tx for the offchain ledger_id."""
tx_hash = Web3.keccak(text="some_bytes")
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SIGNING,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id=self.tx_id,
tx_sender_addr=self.tx_sender_addr,
tx_counterparty_addr=self.tx_counterparty_addr,
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 0},
ledger_id="off_chain",
info=self.info,
signing_payload={"tx_hash": tx_hash},
)
tx_signature = self.decision_maker._sign_tx(tx_message)
assert tx_signature is not None
@classmethod
def teardown_class(cls):
"""Tear the tests down."""
cls._unpatch_logger()
cls.multiplexer.disconnect()
cls.decision_maker.stop()
class TestLedgerStateProxy:
"""Test the Ledger State Proxy."""
@classmethod
def setup_class(cls):
"""Set up the test."""
cls.ledger_apis = LedgerApis({FETCHAI: DEFAULT_FETCHAI_CONFIG}, FETCHAI)
cls.ledger_state_proxy = LedgerStateProxy(ledger_apis=cls.ledger_apis)
def test_ledger_apis(self):
"""Test the returned ledger_apis."""
assert self.ledger_state_proxy.ledger_apis == self.ledger_apis, "Must be equal."
def test_transaction_is_not_affordable(self):
"""Test if the transaction is affordable on the ledger."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": -20},
tx_sender_fee=0,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="off_chain",
info={"some_info_key": "some_info_value"},
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.ledger_state_proxy.ledger_apis, "token_balance", return_value=0
):
result = self.ledger_state_proxy.is_affordable_transaction(
tx_message=tx_message
)
assert not result
def test_transaction_is_affordable(self):
"""Test if the transaction is affordable on the ledger."""
tx_message = TransactionMessage(
performative=TransactionMessage.Performative.PROPOSE_FOR_SETTLEMENT,
skill_callback_ids=[PublicId("author", "a_skill", "0.1.0")],
tx_id="transaction0",
tx_sender_addr="agent_1",
tx_counterparty_addr="pk",
tx_amount_by_currency_id={"FET": 20},
tx_sender_fee=5,
tx_counterparty_fee=0,
tx_quantities_by_good_id={"good_id": 10},
ledger_id="off_chain",
info={"some_info_key": "some_info_value"},
tx_nonce="Transaction nonce",
)
with mock.patch.object(
self.ledger_state_proxy.ledger_apis, "token_balance", return_value=0
):
result = self.ledger_state_proxy.is_affordable_transaction(
tx_message=tx_message
)
assert result
| 41.925998 | 106 | 0.641042 | 5,119 | 43,058 | 5.013675 | 0.070326 | 0.026651 | 0.031794 | 0.042782 | 0.788116 | 0.742451 | 0.714202 | 0.662186 | 0.631327 | 0.608455 | 0 | 0.011945 | 0.265084 | 43,058 | 1,026 | 107 | 41.966862 | 0.799109 | 0.077407 | 0 | 0.650867 | 0 | 0 | 0.089586 | 0.009177 | 0 | 0 | 0 | 0.000975 | 0.080925 | 1 | 0.055491 | false | 0 | 0.024277 | 0 | 0.084393 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
1112cf8fd2ea3b082bd270c70d54466062312420 | 8,338 | py | Python | personnages3d/filtre.py | mxbossard/personnages3d | 87c2ab8dc9b502c0074f1dec04b832803dee1462 | [
"Apache-2.0"
] | null | null | null | personnages3d/filtre.py | mxbossard/personnages3d | 87c2ab8dc9b502c0074f1dec04b832803dee1462 | [
"Apache-2.0"
] | null | null | null | personnages3d/filtre.py | mxbossard/personnages3d | 87c2ab8dc9b502c0074f1dec04b832803dee1462 | [
"Apache-2.0"
] | 1 | 2021-10-01T02:03:42.000Z | 2021-10-01T02:03:42.000Z |
"""Ce script est un exemple de matplotlib"""
import numpy as np
def moving_average(x, n, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
x = np.asarray(x)
if type == 'simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
a = np.convolve(x, weights, mode='full')[:len(x)]
a[:n] = a[n]
return a[-1]
if __name__ == '__main__':
data = [[1.0], [1.12], [1.17], [1.18], [1.26], [1.33], [1.37], [1.4], [1.46],
[1.49], [1.51], [1.52], [1.53], [1.51], [1.52], [1.52], [1.52], [1.51],
[1.52], [1.51], [1.51], [1.51], [1.51], [1.52], [1.52], [1.54], [1.56],
[1.59], [1.64], [1.69], [1.71], [1.73], [1.78], [1.83], [1.88], [1.94],
[1.96], [2.01], [2.04], [2.1], [2.13], [2.16], [2.2], [2.27], [2.3],
[2.37], [2.41], [2.46], [2.54], [2.58], [2.64], [2.67], [2.72], [2.76],
[2.84], [2.89], [2.93], [2.97], [3.03], [3.08], [3.1], [3.15], [3.18],
[3.24], [3.31], [3.33], [3.37], [3.42], [3.42], [3.44], [3.46], [3.51],
[3.51], [3.55], [3.59], [3.6], [3.64], [3.63], [3.66], [3.65], [3.66],
[3.69], [3.69], [3.71], [3.77], [3.76], [3.79], [3.84], [3.86], [3.94],
[4.0], [4.08], [4.05], [4.11], [4.16], [4.24], [4.27], [4.35], [4.35],
[4.42], [4.43], [4.47], [4.54], [4.57], [4.62], [4.64], [4.68], [4.74],
[4.79], [4.84], [4.93], [4.95], [5.08], [5.15], [5.21], [5.25], [5.3],
[5.35], [5.39], [5.46], [5.55], [5.57], [5.6], [5.7], [5.73], [5.77],
[5.95], [5.93], [6.06], [6.1], [6.08], [6.13], [6.14], [6.17], [6.25],
[6.36], [6.44], [6.61], [6.58], [6.59], [6.71], [6.75], [6.78], [6.8],
[6.85], [6.84], [6.95], [6.9], [7.03], [7.03], [7.12], [7.17], [7.13],
[7.11], [7.22], [7.25], [7.29], [7.4], [7.42], [7.44], [7.48], [7.46],
[7.49], [7.39], [7.56], [7.64], [7.6], [7.64], [7.65], [7.63], [7.66],
[7.6], [7.66], [7.62], [7.54], [7.44], [7.43], [7.38], [7.39], [7.22],
[7.19], [7.04], [6.97], [6.92], [6.83], [6.83], [6.64], [6.58], [6.52],
[6.44], [6.24], [6.24], [6.08], [5.99], [5.93], [5.89], [5.74], [5.65],
[5.6], [5.51], [5.46], [5.39], [5.26], [5.2], [5.08], [4.94], [4.81],
[4.75], [4.71], [4.66], [4.56], [4.44], [4.39], [4.33], [4.18], [4.15],
[4.04], [3.96], [3.84], [3.75], [3.65], [3.58], [3.52], [3.46], [3.34],
[3.29], [3.18], [3.11], [3.01], [2.97], [2.87], [2.79], [2.69], [2.59],
[2.52], [2.44], [2.39], [2.29], [2.22], [2.15], [2.08], [2.03], [1.92],
[1.82], [1.74], [1.68], [1.62], [1.55], [1.46], [1.42], [1.33], [1.27],
[1.19], [1.14], [1.08], [1.03], [1.0], [0.93], [0.9], [0.85], [0.81],
[0.78], [0.77], [0.73], [0.72], [0.69], [0.68], [0.66], [0.66], [0.65],
[0.64], [0.64], [0.63], [0.63], [0.62], [0.61], [0.59], [0.59], [0.57],
[0.56], [0.57], [0.56], [0.56], [0.55], [0.61], [0.61], [0.61], [0.61],
[0.59], [0.61], [0.61], [0.61], [0.59], [0.59], [0.57], [0.55], [0.56],
[0.56], [0.57], [0.57], [0.6], [0.56], [0.57], [0.57], [0.57], [0.56],
[0.56], [0.57], [0.58], [0.57], [0.56], [0.55], [0.58], [0.57], [0.75],
[0.74], [0.56], [0.56], [0.61], [0.55], [0.68], [0.55], [0.93], [0.71],
[0.7], [0.74], [0.7], [0.69], [0.69], [0.52], [0.69], [0.52], [0.67],
[0.52], [0.52], [0.52], [0.72], [0.65], [0.7], [0.71], [0.82], [0.93],
[0.55], [0.74], [0.72], [0.75], [0.57], [0.58], [0.63], [0.63], [0.65],
[0.69], [0.72], [0.79], [0.82], [0.83], [0.89], [0.94], [0.96], [1.03],
[1.07], [1.11], [1.13], [1.17], [1.21], [1.23], [1.29], [1.32], [1.36],
[1.41], [1.46], [1.5], [1.55], [1.58], [1.62], [1.65], [1.72], [1.74],
[1.78], [1.82], [1.88], [1.91], [1.96], [2.01], [2.06], [2.11], [2.17],
[2.24], [2.27], [2.31], [2.35], [2.4], [2.45], [2.48], [2.56], [2.59],
[2.65], [2.68], [2.74], [2.78], [2.83], [2.86], [2.92], [2.98], [3.01],
[3.1], [3.11], [3.18], [3.24], [3.26], [3.31], [3.42], [3.51], [3.56],
[3.61], [3.68], [3.67], [3.78], [3.82], [3.83], [3.89], [3.93], [4.03],
[4.06], [4.11], [4.19], [4.25], [4.27], [4.36], [4.42], [4.48], [4.53],
[4.6], [4.62], [4.66], [4.76], [4.81], [4.91], [5.04], [4.96], [5.07],
[5.23], [5.26], [5.33], [5.34], [5.43], [5.43], [5.53], [5.58], [5.61],
[5.68], [5.72], [5.77], [5.9], [5.95], [6.04], [6.17], [6.15], [6.27],
[6.21], [6.3], [6.36], [6.39], [6.45], [6.54], [6.7], [6.84], [6.78],
[6.95], [6.83], [6.91], [6.89], [7.04], [7.22], [7.39], [7.42], [7.38],
[7.36], [7.38], [7.45], [7.49], [7.51], [7.38], [7.44], [7.43], [7.43],
[7.37], [7.4], [7.36], [7.43], [7.29], [7.26], [7.12], [7.08], [6.96],
[6.84], [6.91], [6.78], [6.77], [6.72], [6.63], [6.62], [6.55], [6.51],
[6.39], [6.26], [6.07], [6.02], [5.87], [5.85], [5.79], [5.74], [5.72],
[5.63], [5.58], [5.51], [5.47], [5.38], [5.3], [5.25], [5.14], [5.08],
[5.06], [4.95], [4.98], [4.96], [4.84], [4.83], [4.78], [4.75], [4.69],
[4.65], [4.54], [4.47], [4.4], [4.35], [4.5], [4.21], [4.14], [4.1],
[4.01], [3.95], [3.86], [3.74], [3.69], [3.63], [3.58], [3.5], [3.46],
[3.4], [3.34], [3.27], [3.21], [3.15], [3.02], [2.99], [2.94], [2.85],
[2.78], [2.7], [2.65], [2.61], [2.54], [2.5], [2.45], [2.4], [2.31],
[2.24], [2.19], [2.16], [2.09], [2.01], [1.95], [1.91], [1.89], [1.83],
[1.77], [1.73], [1.7], [1.64], [1.58], [1.52], [1.48], [1.43], [1.4],
[1.36], [1.34], [1.31], [1.27], [1.27], [1.23], [1.22], [1.2], [1.2],
[1.29], [1.27], [1.26], [1.3], [1.35], [1.4], [1.42], [1.45], [1.49],
[1.54], [1.64], [1.69], [1.78], [1.82], [1.88], [1.93], [1.96], [1.98],
[2.04], [2.1], [2.13], [2.19], [2.26], [2.3], [2.35], [2.42], [2.47],
[2.52], [2.62], [2.68], [2.71], [2.76], [2.79], [2.8], [2.85], [2.89],
[2.94], [3.03], [3.1], [3.17], [3.24], [3.25], [3.3], [3.33], [3.37],
[3.42], [3.45], [3.5], [3.54], [3.59], [3.66], [3.69], [3.78], [3.84],
[3.87], [3.91], [4.01], [4.02], [4.05], [4.1], [4.18], [4.24], [4.32],
[4.41], [4.51], [4.54], [4.67], [4.69], [4.7], [4.73], [4.79], [4.87],
[4.94], [5.07], [5.14], [5.17], [5.22], [5.32], [5.42], [5.49], [5.52],
[5.59], [5.64], [5.68], [5.79], [5.91], [5.83], [5.92], [5.99], [6.05],
[6.09], [6.16], [6.23], [6.43], [6.44], [6.51], [6.52], [6.74], [6.65],
[6.66], [6.62], [6.77], [6.67], [6.84], [6.88], [6.97], [6.87], [6.88],
[7.01], [7.16], [7.16], [7.31], [7.44], [7.4], [7.47], [7.51], [7.55],
[7.49], [7.54], [7.61], [7.6], [7.57], [7.5], [7.71], [7.62], [7.53],
[7.56], [7.53], [7.54], [7.48], [7.49], [7.41], [7.32], [7.22], [7.12],
[7.1], [7.02], [6.91], [6.9], [6.93], [6.85], [6.8], [6.75], [6.6],
[6.62], [6.48], [6.35], [6.27], [6.2], [6.09], [6.14], [5.95], [5.89],
[5.67], [5.62], [5.52], [5.47], [5.39], [5.33], [5.18], [5.11], [5.05],
[4.92], [4.89], [4.75], [4.71], [4.58], [4.49], [4.39], [4.29], [4.22],
[4.13], [4.07], [4.0], [3.88], [3.8], [3.75], [3.63], [3.59], [3.52],
[3.44], [3.34], [3.25], [3.15], [3.06], [3.0], [2.94], [2.83], [2.75],
[2.65], [2.56], [2.51], [2.44], [2.34], [2.27], [2.21], [2.15], [2.09],
[2.01], [1.95], [1.89], [1.83], [1.76], [1.68], [1.64], [1.55], [1.46],
[1.41], [1.34], [1.26], [1.24], [1.15], [1.11], [1.06], [0.99], [0.95],
[0.9], [0.83], [0.79], [0.75], [0.71], [0.67], [0.6], [0.56], [0.55],
[0.56], [0.61], [0.53], [2.49], [1000]]
print(len(data)) # 824
for i in range(750):
d = []
for j in range(10):
d.append(data[i + j])
d = np.ravel(d)
m = moving_average(d, 8, type='simple')
print(m)
| 63.166667 | 83 | 0.333173 | 1,751 | 8,338 | 1.580811 | 0.087379 | 0.01409 | 0.018786 | 0.010838 | 0.150289 | 0.071893 | 0.071893 | 0.015896 | 0.015896 | 0 | 0 | 0.390055 | 0.257136 | 8,338 | 131 | 84 | 63.648855 | 0.056829 | 0.013552 | 0 | 0 | 0 | 0 | 0.003659 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.008929 | false | 0 | 0.008929 | 0 | 0.026786 | 0.017857 | 0 | 0 | 1 | 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 | 3 |
111b82803ba6219820d34735a4253abbca5f8527 | 1,785 | py | Python | tests/test_grizzly/steps/scenario/test_results.py | boffman/grizzly | eabe7b8f6cd7098914a1473928135c1e05758af7 | [
"MIT"
] | null | null | null | tests/test_grizzly/steps/scenario/test_results.py | boffman/grizzly | eabe7b8f6cd7098914a1473928135c1e05758af7 | [
"MIT"
] | 9 | 2022-01-05T08:53:41.000Z | 2022-03-31T07:26:05.000Z | tests/test_grizzly/steps/scenario/test_results.py | boffman/grizzly | eabe7b8f6cd7098914a1473928135c1e05758af7 | [
"MIT"
] | null | null | null | from typing import cast
from grizzly.context import GrizzlyContext
from grizzly.steps import * # pylint: disable=unused-wildcard-import # noqa: F403
from ....fixtures import BehaveFixture
def test_step_results_fail_ratio(behave_fixture: BehaveFixture) -> None:
behave = behave_fixture.context
grizzly = cast(GrizzlyContext, behave.grizzly)
assert grizzly.scenario.validation.fail_ratio is None
assert not grizzly.scenario.should_validate()
step_results_fail_ratio(behave, 10)
assert grizzly.scenario.validation.fail_ratio == 0.1
assert grizzly.scenario.should_validate()
def test_step_results_avg_response_time(behave_fixture: BehaveFixture) -> None:
behave = behave_fixture.context
grizzly = cast(GrizzlyContext, behave.grizzly)
assert grizzly.scenario.validation.avg_response_time is None
assert not grizzly.scenario.should_validate()
step_results_avg_response_time(behave, 200)
assert grizzly.scenario.validation.avg_response_time == 200
assert grizzly.scenario.should_validate()
def test_step_results_response_time_percentile(behave_fixture: BehaveFixture) -> None:
behave = behave_fixture.context
grizzly = cast(GrizzlyContext, behave.grizzly)
assert grizzly.scenario.validation.response_time_percentile is None
assert not grizzly.scenario.should_validate()
step_results_response_time_percentile(behave, 95, 800)
assert getattr(grizzly.scenario.validation, 'response_time_percentile', None) is not None
response_time_percentile = grizzly.scenario.validation.response_time_percentile
assert getattr(response_time_percentile, 'percentile', None) == 0.95
assert getattr(response_time_percentile, 'response_time', None) == 800
assert grizzly.scenario.should_validate()
| 36.428571 | 93 | 0.791036 | 218 | 1,785 | 6.220183 | 0.197248 | 0.143805 | 0.123894 | 0.128319 | 0.809735 | 0.70649 | 0.521386 | 0.476401 | 0.476401 | 0.39823 | 0 | 0.015504 | 0.132773 | 1,785 | 48 | 94 | 37.1875 | 0.860465 | 0.028571 | 0 | 0.387097 | 0 | 0 | 0.027152 | 0.013865 | 0 | 0 | 0 | 0 | 0.451613 | 1 | 0.096774 | false | 0 | 0.129032 | 0 | 0.225806 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
112006d175386d520393db8a5fbf90e3082f8290 | 39 | py | Python | orbit/__init__.py | CrossNox/orbit | 1c803596b3477a91c122093c1f6e34333b6db42e | [
"Apache-2.0"
] | null | null | null | orbit/__init__.py | CrossNox/orbit | 1c803596b3477a91c122093c1f6e34333b6db42e | [
"Apache-2.0"
] | null | null | null | orbit/__init__.py | CrossNox/orbit | 1c803596b3477a91c122093c1f6e34333b6db42e | [
"Apache-2.0"
] | null | null | null | name = 'orbit'
__version__ = '1.0.10'
| 9.75 | 22 | 0.615385 | 6 | 39 | 3.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | 0.179487 | 39 | 3 | 23 | 13 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0.289474 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 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 | 3 |
11534d93e39e29332cbc56c2467f77183e5bab66 | 2,028 | py | Python | tests/test_redirector.py | lawliet89/flask-redirector | 8637c2bd0025bb48db8694c83ad64825a85825a5 | [
"Apache-2.0"
] | null | null | null | tests/test_redirector.py | lawliet89/flask-redirector | 8637c2bd0025bb48db8694c83ad64825a85825a5 | [
"Apache-2.0"
] | 1 | 2016-09-27T03:23:38.000Z | 2016-09-27T03:23:38.000Z | tests/test_redirector.py | lawliet89/flask-redirector | 8637c2bd0025bb48db8694c83ad64825a85825a5 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
"""
Redirector tests
"""
from redirector import views
def test_redirects_correctly(client):
response = client.get('/foo/bar.html?foo=bar')
assert response.status_code == 301
assert response.headers['Location'] == 'https://www.example.com/foo/bar.html?foo=bar'
def test_normalize_port_normalizes_properly():
assert views.normalize_port('http', 80) == None
assert views.normalize_port('https', 443) == None
assert views.normalize_port('http', 8080) == 8080
assert views.normalize_port('http', '8080') == 8080
def test_make_base_url_with_root_base_path():
scheme = 'https'
host = 'foo.bar'
port = 80
base_path = '/'
assert views.make_base_url(scheme, host, port, base_path) == 'https://foo.bar:80/'
def test_make_base_url_with_non_root_base_path():
scheme = 'https'
host = 'foo.bar'
port = 80
base_path = '/fooooooooo/'
assert views.make_base_url(scheme, host, port, base_path) == 'https://foo.bar:80/fooooooooo/'
def test_make_redirect_url_with_root():
scheme = 'https'
host = 'foo.bar'
port = 80
base_path = '/aye/aye/captain/'
path = ''
expected = 'https://foo.bar:80/aye/aye/captain/'
assert views.make_redirect_url(path, scheme, host, port, base_path) == expected
def test_make_redirect_url_with_root_base_path():
scheme = 'https'
host = 'foo.bar'
port = 80
base_path = '/'
path = 'aye/aye/captain?jump_overboard=true&depth=199'
expected = 'https://foo.bar:80/aye/aye/captain?jump_overboard=true&depth=199'
assert views.make_redirect_url(path, scheme, host, port, base_path) == expected
def test_make_redirect_url_with_non_root_base_path():
scheme = 'https'
host = 'foo.bar'
port = 80
base_path = '/fooooooooo/'
path = 'aye/aye/captain?jump_overboard=true&depth=199'
expected = 'https://foo.bar:80/fooooooooo/aye/aye/captain?jump_overboard=true&depth=199'
assert views.make_redirect_url(path, scheme, host, port, base_path) == expected
| 28.56338 | 97 | 0.688363 | 288 | 2,028 | 4.604167 | 0.194444 | 0.063348 | 0.067873 | 0.067873 | 0.821267 | 0.736802 | 0.714178 | 0.637255 | 0.611614 | 0.585219 | 0 | 0.033888 | 0.170611 | 2,028 | 70 | 98 | 28.971429 | 0.754459 | 0.014793 | 0 | 0.521739 | 0 | 0.043478 | 0.256281 | 0.055779 | 0 | 0 | 0 | 0 | 0.23913 | 1 | 0.152174 | false | 0 | 0.021739 | 0 | 0.173913 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 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 | 3 |
1166eafac1780fdb1b04815e3dcee64d69f82e8c | 314 | py | Python | imgbase/filters.py | olajir/projbase | c434bf5ef0627e7161fe026885a778e8240a26a0 | [
"MIT"
] | null | null | null | imgbase/filters.py | olajir/projbase | c434bf5ef0627e7161fe026885a778e8240a26a0 | [
"MIT"
] | null | null | null | imgbase/filters.py | olajir/projbase | c434bf5ef0627e7161fe026885a778e8240a26a0 | [
"MIT"
] | null | null | null |
import numpy as np
import skimage
import skimage.morphology as morph
import skimage.filters as filt
import skimage.exposure as expo
def get_corrected_image(iimage, gamma=0.25):
"""Return filtered image to detect spots."""
image = skimage.util.img_as_float(iimage)
image **= gamma
return image
| 19.625 | 48 | 0.745223 | 46 | 314 | 5 | 0.586957 | 0.226087 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011628 | 0.178344 | 314 | 15 | 49 | 20.933333 | 0.879845 | 0.121019 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.555556 | 0 | 0.777778 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
11677e2c59bc64a37229b6462c616546dac9135c | 398 | py | Python | packages/python/yap_kernel/yap_ipython/utils/tests/test_sysinfo.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 90 | 2015-03-09T01:24:15.000Z | 2022-02-24T13:56:25.000Z | packages/python/yap_kernel/yap_ipython/utils/tests/test_sysinfo.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 52 | 2016-02-14T08:59:37.000Z | 2022-03-14T16:39:35.000Z | packages/python/yap_kernel/yap_ipython/utils/tests/test_sysinfo.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 27 | 2015-11-19T02:45:49.000Z | 2021-11-25T19:47:58.000Z | # coding: utf-8
"""Test suite for our sysinfo utilities."""
# Copyright (c) yap_ipython Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import nose.tools as nt
from yap_ipython.utils import sysinfo
def test_json_getsysinfo():
"""
test that it is easily jsonable and don't return bytes somewhere.
"""
json.dumps(sysinfo.get_sys_info())
| 22.111111 | 70 | 0.728643 | 59 | 398 | 4.813559 | 0.813559 | 0.070423 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003077 | 0.183417 | 398 | 17 | 71 | 23.411765 | 0.870769 | 0.552764 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | true | 0 | 0.6 | 0 | 0.8 | 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 | 0 | 1 | 0 | 1 | 0 | 0 | 3 |
fec502d06e7f6b4c2323778a4f480e3ca87b83f7 | 243 | py | Python | appointment_booking/appointment_booking/doctype/visitor_appointment/tasks.py | smarty-india/appointment_booking | 781b8883b749d78d543b21f39f9c1a12f16033ae | [
"MIT"
] | 1 | 2021-02-10T05:13:29.000Z | 2021-02-10T05:13:29.000Z | appointment_booking/appointment_booking/doctype/visitor_appointment/tasks.py | smarty-india/appointment_booking | 781b8883b749d78d543b21f39f9c1a12f16033ae | [
"MIT"
] | null | null | null | appointment_booking/appointment_booking/doctype/visitor_appointment/tasks.py | smarty-india/appointment_booking | 781b8883b749d78d543b21f39f9c1a12f16033ae | [
"MIT"
] | 7 | 2020-09-23T13:10:29.000Z | 2021-12-28T19:03:34.000Z | import frappe
def set_appointment_as_pending():
frappe.db.sql("""update `tabVisitor Appointment` set `status`='Pending'
where appointment_date is not null
and appointment_date < CURDATE()
and `status` not in ('Closed', 'Cancelled')""") | 34.714286 | 72 | 0.740741 | 32 | 243 | 5.46875 | 0.6875 | 0.171429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.127572 | 243 | 7 | 73 | 34.714286 | 0.825472 | 0 | 0 | 0 | 0 | 0 | 0.704918 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | true | 0 | 0.166667 | 0 | 0.333333 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
fecbabb08af60d46436a84bbcfcf8d984bfc2f0d | 301 | py | Python | import_descendants/test_example/__init__.py | ZumatechLtd/import-descendants | ad3dd65ae74dd98ae1eec68fad3b1fa775a5d74f | [
"Unlicense"
] | null | null | null | import_descendants/test_example/__init__.py | ZumatechLtd/import-descendants | ad3dd65ae74dd98ae1eec68fad3b1fa775a5d74f | [
"Unlicense"
] | null | null | null | import_descendants/test_example/__init__.py | ZumatechLtd/import-descendants | ad3dd65ae74dd98ae1eec68fad3b1fa775a5d74f | [
"Unlicense"
] | 1 | 2020-03-23T13:59:40.000Z | 2020-03-23T13:59:40.000Z | # -*- coding: utf-8 -*-
# (c) 2013 Bright Interactive Limited. All rights reserved.
# http://www.bright-interactive.com | info@bright-interactive.com
from import_descendants import import_descendants
import sys
this_module = sys.modules[__name__]
import_descendants(this_module, globals(), locals())
| 33.444444 | 65 | 0.774086 | 39 | 301 | 5.74359 | 0.641026 | 0.227679 | 0.178571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018519 | 0.10299 | 301 | 8 | 66 | 37.625 | 0.811111 | 0.475083 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.75 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 3 |
fed8fa9a87db15241481aa01020912d1d1d9aa17 | 91 | py | Python | client/const.py | math2001/nine43 | 7749dc63b9717a6ee4ddc1723d6c59e16046fc01 | [
"MIT"
] | null | null | null | client/const.py | math2001/nine43 | 7749dc63b9717a6ee4ddc1723d6c59e16046fc01 | [
"MIT"
] | 3 | 2019-04-27T06:34:34.000Z | 2019-04-27T21:29:31.000Z | client/const.py | math2001/nine43 | 7749dc63b9717a6ee4ddc1723d6c59e16046fc01 | [
"MIT"
] | null | null | null | MONO = "FiraMono-Medium"
PORT = 9999
ISSUES = "https://github.com/math2001/nine43/issues"
| 18.2 | 52 | 0.725275 | 12 | 91 | 5.5 | 0.916667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.123457 | 0.10989 | 91 | 4 | 53 | 22.75 | 0.691358 | 0 | 0 | 0 | 0 | 0 | 0.615385 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
fef4d3e2153fde18995213ace718d0a7d41c56ac | 55 | py | Python | test.py | SquarerFive/ursina | 8d2a86a702a96fe2d3d3b608b87e755bf28cb2ae | [
"MIT"
] | null | null | null | test.py | SquarerFive/ursina | 8d2a86a702a96fe2d3d3b608b87e755bf28cb2ae | [
"MIT"
] | null | null | null | test.py | SquarerFive/ursina | 8d2a86a702a96fe2d3d3b608b87e755bf28cb2ae | [
"MIT"
] | null | null | null | import ursina
app = ursina.Ursina(init_showbase=True)
| 13.75 | 39 | 0.8 | 8 | 55 | 5.375 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.109091 | 55 | 3 | 40 | 18.333333 | 0.877551 | 0 | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 3 |
3a0e24a4de9a8532f6e0fffca390853480dadb10 | 5,460 | py | Python | PoPs/warning.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 14 | 2019-08-29T23:46:24.000Z | 2022-03-21T10:16:25.000Z | PoPs/warning.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 1 | 2020-08-04T16:14:45.000Z | 2021-12-01T01:54:34.000Z | PoPs/warning.py | brown170/fudge | 4f818b0e0b0de52bc127dd77285b20ce3568c97a | [
"BSD-3-Clause"
] | 2 | 2022-03-03T22:41:41.000Z | 2022-03-03T22:54:43.000Z | # <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
Store and report warnings and errors in a PoPs database.
PoPs.check() returns a nested list of warning objects:
>>> warnings = PoPs.check()
>>> print( warnings )
May include or exclude specific classes of warning using the filter command.
filter() returns a new context instance:
>>> warnings2 = warnings.filter( exclude=[warning.unnormalizedGammas] )
Or, for easier searching you may wish to flatten the list (to get warnings alone without context messages):
>>> flat = warnings.flatten()
"""
# FIXME context class and base warning class are both identical to stuff in fudge.warning. Move to external utility?
__metaclass__ = type
class context:
"""
Store warnings in context. This class contains location information (reactionSuite, reaction, etc)
plus a nested list of warnings or other context instances
"""
def __init__( self, message='', warningList=None ):
self.message = message
self.warningList = warningList or []
def __len__( self ):
return len(self.warningList)
def __getitem__( self, idx ):
return self.warningList[idx]
def __str__( self ):
if len(self.warningList) == 0:
return self.message + ": no problems encountered"
return '\n'.join(self.toStringList())
def __eq__( self, other ):
return self.message == other.message and self.warningList == other.warningList
def filter( self, include=None, exclude=None ):
"""
Filter warning list to only include (or exclude) specific classes of warning. For example:
>>> newWarnings = warnings.filter( exclude=[warning.discreteLevelsOutOfOrder] )
Note that if both 'include' and 'exclude' lists are provided, exclude is ignored.
"""
if include is None and exclude is None: return self
newWarningList = []
for warning in self.warningList:
if isinstance(warning, context):
newContext = warning.filter(include, exclude)
if newContext: newWarningList.append(newContext)
elif include is not None:
if warning.__class__ in include:
newWarningList.append(warning)
else: # exclude is not None:
if warning.__class__ not in exclude:
newWarningList.append(warning)
return context(self.message, newWarningList)
def flatten( self ):
"""
From a nested hierarchy of warnings, get back a flat list for easier searching:
>>> w = PoPs.check()
>>> warningList = w.flatten()
:return: list containing all of warnings
"""
List = []
for val in self.warningList:
if isinstance(val, warning):
List.append(val)
else:
List += val.flatten()
return List
def toStringList( self, indent='', dIndent=' ' ):
""" Format warnings for printing. Returns a list of warning strings with indentation. """
s = ['%s%s' % (indent, self.message)]
for warning in self.warningList:
s += warning.toStringList(indent + dIndent)
return s
class warning: # FIXME make abstract base class?
"""
General warning class. Contains link to problem object,
xpath in case the object leaves memory,
and information about the warning or error.
"""
def __init__( self, obj=None ):
self.obj = obj
self.xpath = ''
if hasattr(obj, 'toXLink'):
self.xpath = obj.toXLink()
def __str__( self ):
return "Generic warning for %s" % self.xpath
def __eq__( self, other ):
return self.xpath == other.xpath
def toStringList( self, indent='' ):
return ['%sWARNING: %s' % (indent, self)]
#
# specific warning classes:
#
class NotImplemented(warning):
def __init__( self, form, obj=None ):
warning.__init__(self, obj)
self.form = form
def __str__( self ):
return "Checking not yet implemented for %s type data" % self.form
def __eq__( self, other ):
return (self.form == other.form and self.xpath == other.xpath)
class discreteLevelsOutOfOrder( warning ):
def __init__(self, lidx, obj=None):
warning.__init__(self, obj)
self.lidx = lidx
def __str__(self):
return "Discrete level %s is out of order" % self.lidx
def __eq__(self, other):
return (self.lidx == other.lidx)
class unnormalizedDecayProbabilities( warning ):
def __init__(self, branchingSum, obj=None):
warning.__init__(self, obj)
self.branchingSum = branchingSum
def __str__(self):
return "Sum of decay probabilities = %s, should be 1.0!" % (self.branchingSum)
def __eq__(self, other):
return (self.xpath == other.xpath and self.branchingSum == other.branchingSum)
class AliasToNonExistentParticle(warning):
def __init__( self, id, pid, obj=None ):
warning.__init__(self, obj)
self.id = id
self.pid = pid
def __str__(self):
return "Alias '%s' points to non-existant particle '%s'" % (self.id, self.pid)
def __eq__(self, other):
return (self.id == other.id and self.pid == other.pid)
| 31.37931 | 116 | 0.630952 | 640 | 5,460 | 5.214063 | 0.284375 | 0.023974 | 0.019778 | 0.025172 | 0.153132 | 0.124663 | 0.08211 | 0.023374 | 0.023374 | 0 | 0 | 0.002255 | 0.269048 | 5,460 | 173 | 117 | 31.560694 | 0.833876 | 0.310623 | 0 | 0.252874 | 0 | 0 | 0.068975 | 0 | 0 | 0 | 0 | 0.011561 | 0 | 1 | 0.275862 | false | 0 | 0 | 0.16092 | 0.563218 | 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 | 1 | 0 | 0 | 0 | 3 |
3a1a4878173988f64e8012e0966e1a78c639eef8 | 4,116 | py | Python | ToDo/settings/common.py | adarsh9780/2Do | b0f3067b34c49987a4bbb7b56813d73805d83918 | [
"MIT"
] | null | null | null | ToDo/settings/common.py | adarsh9780/2Do | b0f3067b34c49987a4bbb7b56813d73805d83918 | [
"MIT"
] | 10 | 2020-01-03T16:56:27.000Z | 2022-01-13T00:41:57.000Z | ToDo/settings/common.py | adarsh9780/2Do | b0f3067b34c49987a4bbb7b56813d73805d83918 | [
"MIT"
] | null | null | null | """
Django settings for ToDo project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4@_rz2!t@z1jvzsw84+42xxr1v2yz7qhop$khg($i@8s5@73yd'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
ALLOWED_HOSTS = ['10.10.131.76', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Custom Apps
'CreateCard',
#Crispy forms
'crispy_forms',
]
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 = 'ToDo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "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 = 'ToDo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# This is where static files will be collected.
STATIC_ROOT = os.path.join(BASE_DIR, 'Static_Root')
# apart from looking in 'my_app/static', this setting will also
# look for static files mentioned in below directories.
# Remove the contents if you have one.
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
# ]
# Media settings
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "Media_Root")
# TWILIO_ACCOUNT_SID = os.environ['TWILIO_ACCOUNT_SID']
# TWILIO_AUTH_TOKEN = os.environ['TWILIO_AUTH_TOKEN']
# TWILIO_CALLER_ID = os.environ['TWILIO_CALLER_ID']
#for Twilio
TWILIO_ACCOUNT_SID='ACf444eea774e6a2e4e0b81cd4b8cb3a8d'
TWILIO_AUTH_TOKEN='4dd33e0cf293066f9df8d7d385d454f7'
TWILIO_CALLER_ID='+18042943446'
#Crispy form
CRISPY_TEMPLATE_PACK = 'bootstrap4'
| 27.078947 | 91 | 0.710641 | 485 | 4,116 | 5.898969 | 0.4 | 0.068158 | 0.053827 | 0.061167 | 0.211465 | 0.199581 | 0.111499 | 0.111499 | 0.042992 | 0 | 0 | 0.031503 | 0.159378 | 4,116 | 151 | 92 | 27.258278 | 0.795376 | 0.3569 | 0 | 0 | 1 | 0 | 0.534304 | 0.433883 | 0 | 0 | 0 | 0.006623 | 0 | 1 | 0 | false | 0.065789 | 0.013158 | 0 | 0.013158 | 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 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 3 |
3a1ad1cbd5fa6fd57f60b6cfe90e8e847de62504 | 89 | py | Python | openamundsen/modules/__init__.py | openamundsen/openamundsen | 2ac09eb34b0c72c84c421a0dac08d114a05b7b1c | [
"MIT"
] | 3 | 2021-05-28T06:46:36.000Z | 2021-06-14T13:39:25.000Z | openamundsen/modules/__init__.py | openamundsen/openamundsen | 2ac09eb34b0c72c84c421a0dac08d114a05b7b1c | [
"MIT"
] | 22 | 2021-04-28T12:31:58.000Z | 2022-03-09T18:29:12.000Z | openamundsen/modules/__init__.py | openamundsen/openamundsen | 2ac09eb34b0c72c84c421a0dac08d114a05b7b1c | [
"MIT"
] | 1 | 2021-06-01T12:48:54.000Z | 2021-06-01T12:48:54.000Z | from . import (
canopy,
evapotranspiration,
radiation,
snow,
soil,
)
| 11.125 | 23 | 0.573034 | 7 | 89 | 7.285714 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.337079 | 89 | 7 | 24 | 12.714286 | 0.864407 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.142857 | 0 | 0.142857 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.