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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
504c74ad2e8fb640182e7226e466f1adb28baec7 | 1,242 | py | Python | src/msrcPenTest/PythonEx.py | lacioffi/MSRC-Microsoft-Engage-API | f5577348b9174250a3f61acf6ae753eaa4f901bf | [
"MIT"
] | 1 | 2019-03-12T18:49:26.000Z | 2019-03-12T18:49:26.000Z | src/msrcPenTest/PythonEx.py | lacioffi/MSRC-Microsoft-Engage-API | f5577348b9174250a3f61acf6ae753eaa4f901bf | [
"MIT"
] | null | null | null | src/msrcPenTest/PythonEx.py | lacioffi/MSRC-Microsoft-Engage-API | f5577348b9174250a3f61acf6ae753eaa4f901bf | [
"MIT"
] | 1 | 2020-07-30T12:07:02.000Z | 2020-07-30T12:07:02.000Z | ########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'api-key': '{subscription key}',
}
params = urllib.urlencode({
})
try:
conn = httplib.HTTPSConnection('api.msrc.microsoft.com')
conn.request("POST", "/engagebeta/pentest?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'api-key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('api.msrc.microsoft.com')
conn.request("POST", "/engagebeta/pentest?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
| 25.875 | 79 | 0.560386 | 130 | 1,242 | 5.353846 | 0.376923 | 0.037356 | 0.057471 | 0.077586 | 0.798851 | 0.798851 | 0.798851 | 0.798851 | 0.798851 | 0.798851 | 0 | 0.011976 | 0.193237 | 1,242 | 47 | 80 | 26.425532 | 0.682635 | 0.044283 | 0 | 0.75 | 0 | 0 | 0.239921 | 0.086529 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.0625 | 0 | 0.0625 | 0.125 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
acb2b1db0b7562adf9b3b8bbcf83bf61f3767cf6 | 88 | py | Python | modules/TexturePacker/config.py | sersoong/SpritePacker | 35e0086e7864aa0402516bbac5f37651f7995ba5 | [
"MIT"
] | null | null | null | modules/TexturePacker/config.py | sersoong/SpritePacker | 35e0086e7864aa0402516bbac5f37651f7995ba5 | [
"MIT"
] | null | null | null | modules/TexturePacker/config.py | sersoong/SpritePacker | 35e0086e7864aa0402516bbac5f37651f7995ba5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
def can_build(platform):
return True
def configure(env):
pass
| 11 | 24 | 0.727273 | 14 | 88 | 4.5 | 0.857143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147727 | 88 | 7 | 25 | 12.571429 | 0.84 | 0.227273 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | false | 0.25 | 0 | 0.25 | 0.75 | 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 | 1 | 0 | 1 | 1 | 0 | 0 | 6 |
acc4bebd37f8e35e99670db0be561d4d8e687691 | 462 | py | Python | pyirobot/test/util.py | cseelye/python-roomba | 2a0b789e1f443cf4f1c3ad5c15a1b01b9bd071d9 | [
"MIT"
] | 30 | 2016-12-23T23:26:59.000Z | 2021-05-07T19:40:01.000Z | pyirobot/test/util.py | cseelye/python-roomba | 2a0b789e1f443cf4f1c3ad5c15a1b01b9bd071d9 | [
"MIT"
] | 3 | 2017-01-18T01:12:38.000Z | 2019-03-26T00:00:06.000Z | pyirobot/test/util.py | cseelye/python-roomba | 2a0b789e1f443cf4f1c3ad5c15a1b01b9bd071d9 | [
"MIT"
] | 9 | 2017-01-29T19:47:31.000Z | 2021-05-17T08:01:49.000Z | #!/usr/bin/env python
#pylint: skip-file
import random
import string
def RandomIP():
return "{}.{}.{}.{}".format(random.randint(1,254),
random.randint(1,254),
random.randint(1,254),
random.randint(1,254))
def RandomComplexString(length):
return "".join(random.choice(string.ascii_letters + string.digits + string.punctuation + " ") for i in range(length)) | 33 | 121 | 0.560606 | 50 | 462 | 5.16 | 0.58 | 0.20155 | 0.217054 | 0.263566 | 0.263566 | 0.263566 | 0.263566 | 0.263566 | 0.263566 | 0.263566 | 0 | 0.04908 | 0.294372 | 462 | 14 | 121 | 33 | 0.742331 | 0.080087 | 0 | 0.222222 | 0 | 0 | 0.028302 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.222222 | 0.222222 | 0.666667 | 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 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
acdd6093a64d5ef0e855683a94c035b8c58462bd | 9,635 | py | Python | tests/ws/test_ws.py | tclh123/aio-openapi | 7c63eb628b7735501508aea6c83e458715fb070b | [
"BSD-3-Clause"
] | 19 | 2019-03-04T22:50:38.000Z | 2022-03-02T09:28:17.000Z | tests/ws/test_ws.py | tclh123/aio-openapi | 7c63eb628b7735501508aea6c83e458715fb070b | [
"BSD-3-Clause"
] | 116 | 2018-05-17T21:55:02.000Z | 2019-02-14T08:35:31.000Z | tests/ws/test_ws.py | tclh123/aio-openapi | 7c63eb628b7735501508aea6c83e458715fb070b | [
"BSD-3-Clause"
] | 3 | 2020-05-20T17:43:08.000Z | 2021-10-06T10:47:41.000Z | from typing import Dict
import aiohttp
from async_timeout import timeout
from openapi.testing import json_body
async def server_info(ws) -> Dict:
await ws.send_json(dict(id="abc", method="server_info"))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
return data["response"]
async def test_invalid_ws_protocol(cli):
resp = await cli.get("/stream")
await json_body(resp, 400)
async def test_invalid_protocol(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_str("hkjhkhk")
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["error"]
assert data["error"]["message"] == "JSON string expected"
async def test_invalid_protocol2(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json([1])
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["error"]
assert data["error"]["message"] == (
"Malformed message; expected dictionary, got list"
)
async def test_invalid_rpc(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(dict(method="echo", payload=dict(message="hello")))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["error"]
assert data["error"]["message"] == "Invalid RPC parameters"
async def test_rpc_echo(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(dict(id="abc", method="echo", payload=dict(message="hello")))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["method"] == "echo"
assert data["response"] == dict(message="hello")
#
# test internals
sockets = cli.app["web_sockets"]
assert len(sockets.sockets) == 1
ws = tuple(sockets.sockets)[0]
assert str(ws) == ws.socket_id
async def test_invalid_rpc_method(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(dict(id="abc", method="wtf", payload=dict(message="hello")))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["error"]
assert data["error"]["message"] == "Invalid RPC parameters"
assert data["error"]["errors"] == dict(method="wtf method not available")
async def test_rpc_publish_error(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="abc", method="publish", payload=dict(message="hello"))
)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["error"]
assert data["error"]["message"] == "Invalid RPC parameters"
assert data["error"]["errors"]["channel"] == "required"
await ws.send_json(
dict(id="abc", method="publish", payload=dict(channel="Test", data="hello"))
)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["error"]
assert data["error"]["message"] == "Invalid RPC parameters"
assert data["error"]["errors"]["channel"] == "Cannot publish to channel"
async def test_rpc_publish(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="abc", method="publish", payload=dict(channel="test", data="hello"))
)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["response"] == dict(channel="test", data="hello", event=None)
async def test_rpc_subscribe(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="abc", method="subscribe", payload=dict(channel="test"))
)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["response"] == dict(subscribed={"test": ["*"]})
await ws.send_json(
dict(id="abcd", method="subscribe", payload=dict(channel="foo"))
)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abcd"
assert data["response"] == dict(subscribed={"test": ["*"], "foo": ["*"]})
#
# server info
await ws.send_json(dict(id="abc", method="server_info"))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
response = data["response"]
assert response["connections"] == 1
assert len(response["channels"]) == 2
#
# invalid channel
await ws.send_json(
dict(id="abc", method="subscribe", payload=dict(channel="Test"))
)
msg = await ws.receive()
data = msg.json()
assert data["error"]["message"] == "Invalid RPC parameters"
assert data["error"]["errors"]["channel"] == "Invalid channel"
async def test_rpc_unsubscribe(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="abc", method="subscribe", payload=dict(channel="test"))
)
await ws.receive()
await ws.send_json(
dict(id="abcd", method="subscribe", payload=dict(channel="foo"))
)
msg = await ws.receive()
data = msg.json()
assert data["response"] == dict(subscribed={"test": ["*"], "foo": ["*"]})
await ws.send_json(
dict(id="xyz", method="unsubscribe", payload=dict(channel="test"))
)
msg = await ws.receive()
data = msg.json()
assert data["response"] == dict(subscribed={"foo": ["*"]})
#
# server info
await ws.send_json(dict(id="abc", method="server_info"))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
response = data["response"]
assert response["connections"] == 1
assert len(response["channels"]) == 1
async def test_rpc_pubsub(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="abc", method="subscribe", payload=dict(channel="test"))
)
await ws.receive()
await ws.send_json(
dict(
id="abc",
method="publish",
payload=dict(channel="test", data="hello again"),
)
)
msg = await ws.receive()
data = msg.json()
assert data["response"] == dict(channel="test", data="hello again", event=None)
#
# now receive the message
msg = await ws.receive()
data = msg.json()
assert data["channel"] == "test"
assert data["data"] == "hello again"
#
await ws.send_json(
dict(
id="abc",
method="publish",
payload=dict(channel="test", data="error"),
)
)
msg = await ws.receive()
data = msg.json()
assert data["response"] == dict(channel="test", data="error", event=None)
# now receive the message
async with timeout(2):
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
async with cli.ws_connect("/stream") as ws:
info = await server_info(ws)
assert info["connections"] == 1
assert info["channels"] == {}
#
await ws.send_json(
dict(id="abc", method="subscribe", payload=dict(channel="test"))
)
await ws.receive()
#
await ws.send_json(
dict(
id="abc",
method="publish",
payload=dict(channel="test", data="runtime_error"),
)
)
msg = await ws.receive()
data = msg.json()
assert data["response"] == dict(
channel="test", data="runtime_error", event=None
)
# now receive the message
async with timeout(2):
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
async def test_cancelled(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(dict(id="abc", method="cancel"))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
async def test_badjson(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(dict(id="abc", method="badjson"))
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.TEXT
data = msg.json()
assert data["id"] == "abc"
assert data["error"]
assert data["error"]["message"] == "JSON object expected"
async def test_rpc_unsubscribe_error(cli):
async with cli.ws_connect("/stream") as ws:
await ws.send_json(
dict(id="xyz", method="unsubscribe", payload=dict(channel="whazaaa"))
)
msg = await ws.receive()
data = msg.json()
assert data["error"]["message"] == "Invalid RPC parameters"
assert data["error"]["errors"]["channel"] == "Invalid channel"
| 34.53405 | 88 | 0.566373 | 1,143 | 9,635 | 4.703412 | 0.08399 | 0.06901 | 0.072917 | 0.079055 | 0.855097 | 0.827753 | 0.81529 | 0.807292 | 0.796317 | 0.789249 | 0 | 0.002027 | 0.283031 | 9,635 | 278 | 89 | 34.658273 | 0.776202 | 0.013077 | 0 | 0.626087 | 0 | 0 | 0.140735 | 0 | 0 | 0 | 0 | 0 | 0.286957 | 1 | 0 | false | 0 | 0.017391 | 0 | 0.021739 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
acef00d7c918772e98db37d5facd1d1e4103f36c | 191 | py | Python | __main__.py | chen-charles/sysbd | c30fc85f8f9ef3e8a8a5474001abfd8ad5fb9e4a | [
"MIT"
] | null | null | null | __main__.py | chen-charles/sysbd | c30fc85f8f9ef3e8a8a5474001abfd8ad5fb9e4a | [
"MIT"
] | null | null | null | __main__.py | chen-charles/sysbd | c30fc85f8f9ef3e8a8a5474001abfd8ad5fb9e4a | [
"MIT"
] | null | null | null | import pkg_resources
DEFAULTPYBUILD = pkg_resources.resource_string(__name__, 'pybuild.default')
exec(pkg_resources.resource_string(__name__, 'build.py'), {"DEFAULTPYBUILD": DEFAULTPYBUILD})
| 47.75 | 93 | 0.827225 | 21 | 191 | 6.904762 | 0.571429 | 0.248276 | 0.275862 | 0.358621 | 0.413793 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.052356 | 191 | 3 | 94 | 63.666667 | 0.801105 | 0 | 0 | 0 | 0 | 0 | 0.193717 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 6 |
acfdd577d2b484e79f8a017fff259f7160ae51d0 | 8,506 | py | Python | tests/test_cache_control.py | obendidi/httpx-cache | 897dd8da5bb377ed7f61b367716976bdc0d581b1 | [
"BSD-3-Clause"
] | 16 | 2021-12-13T01:27:44.000Z | 2022-02-28T02:58:46.000Z | tests/test_cache_control.py | obendidi/httpx-cache | 897dd8da5bb377ed7f61b367716976bdc0d581b1 | [
"BSD-3-Clause"
] | 23 | 2022-01-03T15:57:39.000Z | 2022-03-28T22:25:08.000Z | tests/test_cache_control.py | obendidi/httpx-cache | 897dd8da5bb377ed7f61b367716976bdc0d581b1 | [
"BSD-3-Clause"
] | 2 | 2022-01-21T17:57:19.000Z | 2022-01-21T18:18:47.000Z | from datetime import datetime, timedelta, timezone
from email.utils import format_datetime
import httpx
import pytest
import httpx_cache
from httpx_cache.cache_control import _PERMANENT_REDIRECT_STATUSES, CacheControl
def test_is_request_cacheable(httpx_request):
controller = httpx_cache.CacheControl()
assert controller.is_request_cacheable(httpx_request) is True
def test_is_request_cacheable_with_relative_url():
request = httpx.Request("GET", "/path")
controller = httpx_cache.CacheControl()
assert controller.is_request_cacheable(request) is False
@pytest.mark.parametrize(
"cacheable_methods,method,expected",
[
(("GET",), "POST", False),
(("GET", "POST"), "POST", True),
],
)
def test_is_request_cacheable_with_method(cacheable_methods, method, expected):
request = httpx.Request(method, "http://testurl/path")
controller = httpx_cache.CacheControl(cacheable_methods=cacheable_methods)
assert controller.is_request_cacheable(request) is expected
def test_is_request_cacheable_with_no_cache_headers():
request = httpx.Request(
"GET", "http://testurl/path", headers={"cache-control": "no-cache"}
)
controller = httpx_cache.CacheControl()
assert controller.is_request_cacheable(request) is False
def test_is_request_cacheable_with_max_age_0_headers():
request = httpx.Request(
"GET", "http://testurl/path", headers={"cache-control": "max-age=0"}
)
controller = httpx_cache.CacheControl()
assert controller.is_request_cacheable(request) is False
def test_is_response_cacheable(httpx_request, httpx_response):
controller = httpx_cache.CacheControl()
assert (
controller.is_response_cacheable(request=httpx_request, response=httpx_response)
is True
)
@pytest.mark.parametrize(
"cacheable_status_codes,code,expected",
[
((200, 203, 300, 301, 308), 200, True),
((500, 404), 400, False),
],
)
def test_is_response_cacheable_with_status_code(
cacheable_status_codes, code, expected, httpx_request
):
response = httpx.Response(code)
controller = httpx_cache.CacheControl(cacheable_status_codes=cacheable_status_codes)
assert (
controller.is_response_cacheable(request=httpx_request, response=response)
is expected
)
def test_is_response_cacheable_with_response_no_store_header(
httpx_request,
):
response = httpx.Response(200, headers={"cache-control": "no-store"})
controller = httpx_cache.CacheControl()
assert (
controller.is_response_cacheable(request=httpx_request, response=response)
is False
)
def test_is_response_cacheable_with_request_no_store_header():
request = httpx.Request(
"GET", "http://testurl", headers={"cache-control": "no-store"}
)
response = httpx.Response(200)
controller = httpx_cache.CacheControl()
assert controller.is_response_cacheable(request=request, response=response) is False
def test_is_response_fresh(httpx_request, httpx_response):
controller = httpx_cache.CacheControl()
assert (
controller.is_response_fresh(request=httpx_request, response=httpx_response)
is True
)
@pytest.mark.parametrize("code", _PERMANENT_REDIRECT_STATUSES)
def test_is_response_fresh_with_permanent_redirect(httpx_request, code):
controller = httpx_cache.CacheControl()
response = httpx.Response(code)
assert (
controller.is_response_fresh(request=httpx_request, response=response) is True
)
def test_is_response_fresh_with_expires_header_no_date():
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(200, headers={"expires": "Tue, 15 Nov 1994 12:45:26 GMT"})
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_invalid_expires_header():
date = datetime.now(tz=timezone.utc)
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"expires": "lala",
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_expires_header_fresh():
date = datetime.now(tz=timezone.utc)
expires = datetime.now(tz=timezone.utc) + timedelta(hours=1)
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"expires": format_datetime(expires, usegmt=True),
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is True
def test_is_response_fresh_with_expires_header_not_fresh():
expires = datetime.now(tz=timezone.utc) - timedelta(minutes=5)
date = expires - timedelta(minutes=5)
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"expires": format_datetime(expires, usegmt=True),
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_max_age_response_header_fresh():
expires = datetime.now(tz=timezone.utc) - timedelta(minutes=5)
date = expires - timedelta(minutes=5)
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"expires": format_datetime(expires, usegmt=True),
"cache-control": "max-age=900",
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is True
def test_is_response_fresh_with_max_age_response_header_not_fresh():
date = datetime.now(tz=timezone.utc) - timedelta(days=1)
expires = datetime.now(tz=timezone.utc) + timedelta(hours=1)
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"expires": format_datetime(expires, usegmt=True),
"cache-control": "max-age=900",
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_max_age_response_header_no_date():
request = httpx.Request("GET", "http://testurl")
response = httpx.Response(
200,
headers={"cache-control": "max-age=900"},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_max_age_request_header_fresh():
date = datetime.now(tz=timezone.utc) - timedelta(days=1)
request = httpx.Request(
"GET", "http://testurl", headers={"cache-control": "max-age=100000"}
)
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"cache-control": "max-age=900",
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is True
def test_is_response_fresh_with_max_age_request_header_not_fresh():
date = datetime.now(tz=timezone.utc) - timedelta(days=1)
request = httpx.Request(
"GET", "http://testurl", headers={"cache-control": "max-age=900"}
)
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
"cache-control": "max-age=100000",
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
def test_is_response_fresh_with_max_age_request_header_fresh_with_min_fresh_header():
date = datetime.now(tz=timezone.utc) - timedelta(minutes=51)
request = httpx.Request(
"GET", "http://testurl", headers={"cache-control": "max-age=3600,min-fresh=600"}
)
response = httpx.Response(
200,
headers={
"date": format_datetime(date, usegmt=True),
},
)
controller = CacheControl()
assert controller.is_response_fresh(request=request, response=response) is False
| 32.841699 | 88 | 0.695862 | 991 | 8,506 | 5.713421 | 0.086781 | 0.056517 | 0.063582 | 0.095373 | 0.875132 | 0.815436 | 0.796362 | 0.7432 | 0.735076 | 0.701872 | 0 | 0.017691 | 0.189278 | 8,506 | 258 | 89 | 32.968992 | 0.803364 | 0 | 0 | 0.550725 | 0 | 0 | 0.088643 | 0.011169 | 0 | 0 | 0 | 0 | 0.101449 | 1 | 0.101449 | false | 0 | 0.028986 | 0 | 0.130435 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
4a0d91d6a70d5b99f1624591197c9d1689445c67 | 60 | py | Python | operators/selection/__init__.py | f4nku4n/MOENAS-TF-PSI | 5e25df9143a09ffdcfbb4d03851b919aed60003a | [
"MIT"
] | null | null | null | operators/selection/__init__.py | f4nku4n/MOENAS-TF-PSI | 5e25df9143a09ffdcfbb4d03851b919aed60003a | [
"MIT"
] | null | null | null | operators/selection/__init__.py | f4nku4n/MOENAS-TF-PSI | 5e25df9143a09ffdcfbb4d03851b919aed60003a | [
"MIT"
] | null | null | null | from .RankAndCrowdingSurvival import RankAndCrowdingSurvival | 60 | 60 | 0.933333 | 4 | 60 | 14 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.05 | 60 | 1 | 60 | 60 | 0.982456 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 0 | 6 |
4a275ccb627103219fac829dcd23cad8a7cedfe1 | 50,319 | py | Python | BtS/Assets/Python/CvAdvisorUtils.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | BtS/Assets/Python/CvAdvisorUtils.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | BtS/Assets/Python/CvAdvisorUtils.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | ## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
##
## CvAdvisorUtils
from CvPythonExtensions import *
import PyHelpers
gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer
g_iAdvisorNags = 0
g_listNoLiberateCities = []
def resetAdvisorNags():
global g_iAdvisorNags
g_iAdvisorNags = 0
def resetNoLiberateCities():
global g_listNoLiberateCities
g_listNoLiberateCities = []
def featPopup(iPlayer):
if (not gc.getPlayer(iPlayer).isOption(PlayerOptionTypes.PLAYEROPTION_ADVISOR_POPUPS)):
return False
if (not gc.getPlayer(iPlayer).isHuman()):
return False
if (gc.getGame().isNetworkMultiPlayer()):
return False
if (gc.getGame().getElapsedGameTurns() == 0):
return False
return True
def populationFeat(iPlayer, eFeat, szText):
if (not gc.getPlayer(iPlayer).isFeatAccomplished(eFeat)):
gc.getPlayer(iPlayer).setFeatAccomplished(eFeat, True)
if (featPopup(iPlayer)):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(eFeat)
popupInfo.setText(localText.getText(szText, (gc.getPlayer(iPlayer).getCivilizationDescriptionKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
def unitBuiltFeats(pCity, pUnit):
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_ARCHER)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_ARCHER")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_ARCHER, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_ARCHER)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_ARCHER", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_MOUNTED)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_MOUNTED")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_MOUNTED, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_MOUNTED)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_MOUNTED", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_MELEE)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_MELEE")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_MELEE, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_MELEE)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_MELEE", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_SIEGE)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_SIEGE")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_SIEGE, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_SIEGE)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_SIEGE", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_GUN)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_GUN")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_GUN, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_GUN)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_GUN", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_ARMOR)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_ARMOR")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_ARMOR, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_ARMOR)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_ARMOR", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_HELICOPTER)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_HELICOPTER")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_HELICOPTER, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_HELICOPTER)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_HELICOPTER", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_NAVAL)):
if (pUnit.getUnitCombatType() == gc.getInfoTypeForString("UNITCOMBAT_NAVAL")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNITCOMBAT_NAVAL, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNITCOMBAT_NAVAL)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNITCOMBAT_NAVAL", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNIT_PRIVATEER)):
if (pUnit.getUnitType() == gc.getInfoTypeForString("UNIT_PRIVATEER")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNIT_PRIVATEER, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNIT_PRIVATEER)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNIT_PRIVATEER", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_UNIT_SPY)):
if (pUnit.getUnitType() == gc.getInfoTypeForString("UNIT_SPY")):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_UNIT_SPY, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_UNIT_SPY)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_UNIT_SPY", (pUnit.getNameKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
def buildingBuiltFeats(pCity, iBuildingType):
if (not gc.getPlayer(pCity.getOwner()).isFeatAccomplished(FeatTypes.FEAT_NATIONAL_WONDER)):
if (isNationalWonderClass(gc.getBuildingInfo(iBuildingType).getBuildingClassType())):
gc.getPlayer(pCity.getOwner()).setFeatAccomplished(FeatTypes.FEAT_NATIONAL_WONDER, True)
if (featPopup(pCity.getOwner()) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_NATIONAL_WONDER)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_NATIONAL_WONDER", (gc.getBuildingInfo(iBuildingType).getTextKey(), pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(pCity.getOwner())
def endTurnFeats(iPlayer):
lRealPopulation = gc.getPlayer(iPlayer).getRealPopulation()
if (lRealPopulation > 500000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_HALF_MILLION, "TXT_KEY_FEAT_HALF_MILLION")
if (lRealPopulation > 1000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_1_MILLION, "TXT_KEY_FEAT_1_MILLION")
if (lRealPopulation > 2000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_2_MILLION, "TXT_KEY_FEAT_2_MILLION")
if (lRealPopulation > 5000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_5_MILLION, "TXT_KEY_FEAT_5_MILLION")
if (lRealPopulation > 10000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_10_MILLION, "TXT_KEY_FEAT_10_MILLION")
if (lRealPopulation > 20000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_20_MILLION, "TXT_KEY_FEAT_20_MILLION")
if (lRealPopulation > 50000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_50_MILLION, "TXT_KEY_FEAT_50_MILLION")
if (lRealPopulation > 100000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_100_MILLION, "TXT_KEY_FEAT_100_MILLION")
if (lRealPopulation > 200000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_200_MILLION, "TXT_KEY_FEAT_200_MILLION")
if (lRealPopulation > 500000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_500_MILLION, "TXT_KEY_FEAT_500_MILLION")
if (lRealPopulation > 1000000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_1_BILLION, "TXT_KEY_FEAT_1_BILLION")
if (lRealPopulation > 2000000000):
populationFeat(iPlayer, FeatTypes.FEAT_POPULATION_2_BILLION, "TXT_KEY_FEAT_2_BILLION")
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_TRADE_ROUTE)):
apCityList = PyPlayer(iPlayer).getCityList()
for pCity in apCityList:
if (not pCity.isCapital()):
if (pCity.isConnectedToCapital(iPlayer)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_TRADE_ROUTE, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_TRADE_ROUTE)
popupInfo.setData2(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_TRADE_ROUTE", (pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
break
pCapitalCity = gc.getPlayer(iPlayer).getCapitalCity()
if (not pCapitalCity.isNone()):
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_COPPER_CONNECTED)):
iBonus = gc.getInfoTypeForString("BONUS_COPPER")
if (iBonus != BonusTypes.NO_BONUS):
if (pCapitalCity.hasBonus(iBonus)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_COPPER_CONNECTED, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_COPPER_CONNECTED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_COPPER_CONNECTED", ()))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_HORSE_CONNECTED)):
iBonus = gc.getInfoTypeForString("BONUS_HORSE")
if (iBonus != BonusTypes.NO_BONUS):
if (pCapitalCity.hasBonus(iBonus)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_HORSE_CONNECTED, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_HORSE_CONNECTED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_HORSE_CONNECTED", ()))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_IRON_CONNECTED)):
iBonus = gc.getInfoTypeForString("BONUS_IRON")
if (iBonus != BonusTypes.NO_BONUS):
if (pCapitalCity.hasBonus(iBonus)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_IRON_CONNECTED, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_IRON_CONNECTED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_IRON_CONNECTED", ()))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_LUXURY_CONNECTED)):
for iI in range(gc.getNumBonusInfos()):
if (gc.getBonusInfo(iI).getHappiness() > 0):
if (pCapitalCity.hasBonus(iI)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_LUXURY_CONNECTED, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_LUXURY_CONNECTED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_LUXURY_CONNECTED", (gc.getBonusInfo(iI).getTextKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
break
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_FOOD_CONNECTED)):
for iI in range(gc.getNumBonusInfos()):
if (gc.getBonusInfo(iI).getHealth() > 0):
if (pCapitalCity.hasBonus(iI)):
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_FOOD_CONNECTED, True)
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_FOOD_CONNECTED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_FOOD_CONNECTED", (gc.getBonusInfo(iI).getTextKey(), )))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
break
if (not gc.getPlayer(iPlayer).isFeatAccomplished(FeatTypes.FEAT_CORPORATION_ENABLED)):
for iI in range(gc.getNumBuildingInfos()):
eCorporation = gc.getBuildingInfo(iI).getFoundsCorporation()
if eCorporation != -1 and not gc.getGame().isCorporationFounded(eCorporation):
bValid = true
eTeam = gc.getPlayer(iPlayer).getTeam()
if not gc.getTeam(eTeam).isHasTech(gc.getBuildingInfo(iI).getPrereqAndTech()):
bValid = false
if bValid:
for iPrereq in range(gc.getDefineINT("NUM_BUILDING_AND_TECH_PREREQS")):
if not gc.getTeam(eTeam).isHasTech(gc.getBuildingInfo(iI).getPrereqAndTechs(iPrereq)):
bValid = false
break
if bValid:
gc.getPlayer(iPlayer).setFeatAccomplished(FeatTypes.FEAT_CORPORATION_ENABLED, True)
szBonusList = u""
bFirst = true
for iPrereq in range(gc.getDefineINT("NUM_CORPORATION_PREREQ_BONUSES")):
eBonus = gc.getCorporationInfo(eCorporation).getPrereqBonus(iPrereq)
if eBonus != -1:
if bFirst:
bFirst = false
else:
szBonusList += localText.getText("TXT_KEY_OR", ())
szBonusList += gc.getBonusInfo(eBonus).getDescription()
szFounder = u""
for iUnit in range(gc.getNumUnitInfos()):
if gc.getUnitInfo(iUnit).getBuildings(iI) or gc.getUnitInfo(iUnit).getForceBuildings(iI):
szFounder = gc.getUnitInfo(iUnit).getTextKey()
break
if (featPopup(iPlayer) and (gc.getGame().getStartYear() == gc.getDefineINT("START_YEAR"))):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(FeatTypes.FEAT_CORPORATION_ENABLED)
popupInfo.setData2(pCapitalCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_FEAT_CORPORATION_ENABLED", (gc.getCorporationInfo(eCorporation).getTextKey(), szFounder, szBonusList)))
popupInfo.setOnClickedPythonCallback("featAccomplishedOnClickedCallback")
popupInfo.setOnFocusPythonCallback("featAccomplishedOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_MORE", ()), "")
popupInfo.addPopup(iPlayer)
break
def cityAdvise(pCity, iPlayer):
global g_iAdvisorNags
if (g_iAdvisorNags >= 2):
return
if (pCity.isDisorder()):
return
if (gc.getPlayer(iPlayer).isOption(PlayerOptionTypes.PLAYEROPTION_ADVISOR_POPUPS) and gc.getPlayer(iPlayer).isHuman() and not gc.getGame().isNetworkMultiPlayer()):
if (gc.getGame().getGameTurn() % 40 == pCity.getGameTurnFounded() % 40):
if (not pCity.getID() in g_listNoLiberateCities):
eLiberationPlayer = pCity.getLiberationPlayer(false)
if (eLiberationPlayer != -1):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_POPUP_LIBERATION_DEMAND", (pCity.getNameKey(), gc.getPlayer(eLiberationPlayer).getCivilizationDescriptionKey(), gc.getPlayer(eLiberationPlayer).getNameKey())))
popupInfo.setOnClickedPythonCallback("liberateOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_listNoLiberateCities.append(pCity.getID())
g_iAdvisorNags += 1
elif (gc.getPlayer(iPlayer).canSplitEmpire() and gc.getPlayer(iPlayer).canSplitArea(pCity.area().getID()) and pCity.AI_cityValue() < 0):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setText(localText.getText("TXT_KEY_POPUP_COLONY_DEMAND", (pCity.getNameKey(), )))
popupInfo.setOnClickedPythonCallback("colonyOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_listNoLiberateCities.append(pCity.getID())
g_iAdvisorNags += 1
if (pCity.isProduction()):
if (not pCity.isProductionUnit() and (pCity.getOrderQueueLength() <= 1)):
if (gc.getGame().getGameTurn() + 1) % 40 == pCity.getGameTurnFounded() % 40:
if ((gc.getGame().getElapsedGameTurns() < 200) and (pCity.getPopulation() > 2) and (gc.getPlayer(iPlayer).AI_totalAreaUnitAIs(pCity.area(), UnitAITypes.UNITAI_SETTLE) == 0) and not gc.getPlayer(iPlayer).AI_isFinancialTrouble() and (pCity.area().getBestFoundValue(iPlayer) > 0)):
iBestValue = 0
eBestUnit = UnitTypes.NO_UNIT
for iI in range(gc.getNumUnitClassInfos()):
if (not isLimitedUnitClass(iI)):
eLoopUnit = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationUnits(iI)
if (eLoopUnit != UnitTypes.NO_UNIT):
if (gc.getUnitInfo(eLoopUnit).getDomainType() == DomainTypes.DOMAIN_LAND):
if pCity.canTrain(eLoopUnit, False, False):
if (pCity.getFirstUnitOrder(eLoopUnit) == -1):
iValue = gc.getPlayer(iPlayer).AI_unitValue(eLoopUnit, UnitAITypes.UNITAI_SETTLE, pCity.area())
if (iValue > iBestValue):
iBestValue = iValue
eBestUnit = eLoopUnit
if (eBestUnit != UnitTypes.NO_UNIT):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_TRAIN)
popupInfo.setData3(eBestUnit)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_UNIT_SETTLE_DEMAND", (gc.getUnitInfo(eBestUnit).getTextKey(), )))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (gc.getGame().getGameTurn() + 5) % 40 == pCity.getGameTurnFounded() % 40:
if ((pCity.getPopulation() > 1) and (pCity.countNumImprovedPlots() == 0) and (pCity.AI_countBestBuilds(pCity.area()) > 3)):
iBestValue = 0
eBestUnit = UnitTypes.NO_UNIT
for iI in range(gc.getNumUnitClassInfos()):
if (not isLimitedUnitClass(iI)):
eLoopUnit = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationUnits(iI)
if (eLoopUnit != UnitTypes.NO_UNIT):
if (gc.getUnitInfo(eLoopUnit).getDomainType() == DomainTypes.DOMAIN_LAND):
if pCity.canTrain(eLoopUnit, False, False):
if (pCity.getFirstUnitOrder(eLoopUnit) == -1):
iValue = gc.getPlayer(iPlayer).AI_unitValue(eLoopUnit, UnitAITypes.UNITAI_WORKER, pCity.area())
if (iValue > iBestValue):
iBestValue = iValue
eBestUnit = eLoopUnit
if (eBestUnit != UnitTypes.NO_UNIT):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_TRAIN)
popupInfo.setData3(eBestUnit)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_UNIT_WORKER_DEMAND", (pCity.getNameKey(), gc.getUnitInfo(eBestUnit).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (gc.getGame().getGameTurn() + 9) % 40 == pCity.getGameTurnFounded() % 40:
if (pCity.plot().getNumDefenders(iPlayer) == 0):
iBestValue = 0
eBestUnit = UnitTypes.NO_UNIT
for iI in range(gc.getNumUnitClassInfos()):
if (not isLimitedUnitClass(iI)):
eLoopUnit = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationUnits(iI)
if (eLoopUnit != UnitTypes.NO_UNIT):
if (gc.getUnitInfo(eLoopUnit).getDomainType() == DomainTypes.DOMAIN_LAND):
if pCity.canTrain(eLoopUnit, False, False):
iValue = (gc.getPlayer(iPlayer).AI_unitValue(eLoopUnit, UnitAITypes.UNITAI_CITY_DEFENSE, pCity.area()) * 2)
iValue += gc.getPlayer(iPlayer).AI_unitValue(eLoopUnit, UnitAITypes.UNITAI_ATTACK, pCity.area())
if (iValue > iBestValue):
iBestValue = iValue
eBestUnit = eLoopUnit
if (eBestUnit != UnitTypes.NO_UNIT):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_TRAIN)
popupInfo.setData3(eBestUnit)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_UNIT_DEFENSE_DEMAND", (pCity.getNameKey(), gc.getUnitInfo(eBestUnit).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (gc.getGame().getGameTurn() + 12) % 40 == pCity.getGameTurnFounded() % 40:
if ((gc.getPlayer(iPlayer).AI_totalAreaUnitAIs(pCity.area(), UnitAITypes.UNITAI_MISSIONARY) == 0) and (gc.getTeam(gc.getPlayer(iPlayer).getTeam()).getAtWarCount(True) == 0)):
eStateReligion = gc.getPlayer(iPlayer).getStateReligion()
if (eStateReligion != ReligionTypes.NO_RELIGION):
if (gc.getPlayer(iPlayer).getHasReligionCount(eStateReligion) < (gc.getPlayer(iPlayer).getNumCities() / 2)):
iBestValue = 0
eBestUnit = UnitTypes.NO_UNIT
for iI in range(gc.getNumUnitClassInfos()):
eLoopUnit = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationUnits(iI)
if (eLoopUnit != UnitTypes.NO_UNIT):
if (gc.getUnitInfo(eLoopUnit).getDomainType() == DomainTypes.DOMAIN_LAND):
if (gc.getUnitInfo(eLoopUnit).getReligionSpreads(eStateReligion)):
if pCity.canTrain(eLoopUnit, False, False):
iValue = gc.getPlayer(iPlayer).AI_unitValue(eLoopUnit, UnitAITypes.UNITAI_MISSIONARY, pCity.area())
if (iValue > iBestValue):
iBestValue = iValue
eBestUnit = eLoopUnit
if (eBestUnit != UnitTypes.NO_UNIT):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_TRAIN)
popupInfo.setData3(eBestUnit)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_MISSIONARY_DEMAND", (gc.getReligionInfo(eStateReligion).getTextKey(), gc.getUnitInfo(eBestUnit).getTextKey(), pCity.getNameKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (not pCity.isProductionBuilding() and (pCity.getOrderQueueLength() <= 1)):
if (pCity.healthRate(False, 0) < 0):
if (gc.getGame().getGameTurn() + 2) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getHealth() > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getHealth()
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_UNHEALTHY_CITIZENS_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHEALTHY_DO_SO_NEXT", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHEALTHY_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHEALTHY_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.angryPopulation(0) > 0):
if (gc.getGame().getGameTurn() + 3) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getHappiness() > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getHappiness()
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_UNHAPPY_CITIZENS_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHAPPY_DO_SO_NEXT", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHAPPY_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_UNHEALTHY_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if ((gc.getGame().getGameTurn < 100) and (gc.getTeam(gc.getPlayer(iPlayer).getTeam()).getHasMetCivCount(True) > 0) and (pCity.getBuildingDefense() == 0)):
if (gc.getGame().getGameTurn() + 4) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getDefenseModifier() > pCity.getNaturalDefense()):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getDefenseModifier()
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_BUILDING_DEFENSE_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.getMaintenance() >= 8):
if (gc.getGame().getGameTurn() + 6) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getMaintenanceModifier() < 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getMaintenanceModifier()
if (iValue < iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_MAINTENANCE_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.getCommerceRate(CommerceTypes.COMMERCE_CULTURE) == 0 and not pCity.isOccupation()):
if (gc.getGame().getGameTurn() + 7) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getObsoleteSafeCommerceChange(CommerceTypes.COMMERCE_CULTURE) > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getObsoleteSafeCommerceChange(CommerceTypes.COMMERCE_CULTURE)
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_CULTURE_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.getBaseCommerceRate(CommerceTypes.COMMERCE_GOLD) > 10):
if (gc.getGame().getGameTurn() + 8) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getCommerceModifier(CommerceTypes.COMMERCE_GOLD) > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getCommerceModifier(CommerceTypes.COMMERCE_GOLD)
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_GOLD_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.getBaseCommerceRate(CommerceTypes.COMMERCE_RESEARCH) > 10):
if (gc.getGame().getGameTurn() + 10) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getCommerceModifier(CommerceTypes.COMMERCE_RESEARCH) > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getCommerceModifier(CommerceTypes.COMMERCE_RESEARCH)
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_RESEARCH_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
if (pCity.countNumWaterPlots() > 10):
if (gc.getGame().getGameTurn() + 11) % 40 == pCity.getGameTurnFounded() % 40:
iBestValue = 0
eBestBuilding = BuildingTypes.NO_BUILDING
for iI in range(gc.getNumBuildingClassInfos()):
if (not isLimitedWonderClass(iI)):
eLoopBuilding = gc.getCivilizationInfo(gc.getPlayer(iPlayer).getCivilizationType()).getCivilizationBuildings(iI)
if (eLoopBuilding != BuildingTypes.NO_BUILDING):
if (gc.getBuildingInfo(eLoopBuilding).getSeaPlotYieldChange(YieldTypes.YIELD_FOOD) > 0):
if pCity.canConstruct(eLoopBuilding, False, False, False):
iValue = gc.getBuildingInfo(eLoopBuilding).getSeaPlotYieldChange(YieldTypes.YIELD_FOOD)
if (iValue > iBestValue):
iBestValue = iValue
eBestBuilding = eLoopBuilding
if (eBestBuilding != BuildingTypes.NO_BUILDING):
popupInfo = CyPopupInfo()
popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
popupInfo.setData1(pCity.getID())
popupInfo.setData2(OrderTypes.ORDER_CONSTRUCT)
popupInfo.setData3(eBestBuilding)
popupInfo.setText(localText.getText("TXT_KEY_POPUP_WATER_FOOD_DEMAND", (pCity.getNameKey(), gc.getBuildingInfo(eBestBuilding).getTextKey())))
popupInfo.setOnClickedPythonCallback("cityWarningOnClickedCallback")
popupInfo.setOnFocusPythonCallback("cityWarningOnFocusCallback")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_AGREE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_REFUSE", ()), "")
popupInfo.addPythonButton(localText.getText("TXT_KEY_POPUP_DEMAND_EXAMINE", ()), "")
popupInfo.addPopup(iPlayer)
g_iAdvisorNags += 1
| 49.722332 | 284 | 0.717522 | 4,450 | 50,319 | 7.925169 | 0.071461 | 0.021266 | 0.060878 | 0.070491 | 0.864888 | 0.841665 | 0.81158 | 0.799785 | 0.773584 | 0.76108 | 0 | 0.008672 | 0.168088 | 50,319 | 1,011 | 285 | 49.771513 | 0.833807 | 0.001411 | 0 | 0.66891 | 0 | 0 | 0.119688 | 0.112416 | 0 | 0 | 0 | 0 | 0 | 1 | 0.010767 | false | 0 | 0.002692 | 0 | 0.02288 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
c57e49d452a4187c1a5d1e9dda2fed5232308d91 | 48 | py | Python | je_editor/ui/ui_event/tag_keyword/__init__.py | JE-Chen/je_editor | 2f18dedb6f0eb27c38668dc53f520739c8d5c6c6 | [
"MIT"
] | 1 | 2021-12-10T14:57:15.000Z | 2021-12-10T14:57:15.000Z | je_editor/ui/ui_event/tag_keyword/__init__.py | JE-Chen/je_editor | 2f18dedb6f0eb27c38668dc53f520739c8d5c6c6 | [
"MIT"
] | null | null | null | je_editor/ui/ui_event/tag_keyword/__init__.py | JE-Chen/je_editor | 2f18dedb6f0eb27c38668dc53f520739c8d5c6c6 | [
"MIT"
] | null | null | null | from je_editor.ui.ui_event.tag_keyword import *
| 24 | 47 | 0.833333 | 9 | 48 | 4.111111 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.083333 | 48 | 1 | 48 | 48 | 0.840909 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c58cf6707ef4719d1aac7b6abf9dd13c619164d7 | 159 | py | Python | blog/admin.py | 29chandu/Blog_django_graphql_api | d5ccbd7008dadc86228d40f2e0927eb23c4c61f8 | [
"MIT"
] | null | null | null | blog/admin.py | 29chandu/Blog_django_graphql_api | d5ccbd7008dadc86228d40f2e0927eb23c4c61f8 | [
"MIT"
] | null | null | null | blog/admin.py | 29chandu/Blog_django_graphql_api | d5ccbd7008dadc86228d40f2e0927eb23c4c61f8 | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Post, Author, Comment
admin.site.register(Post)
admin.site.register(Author)
admin.site.register(Comment) | 22.714286 | 41 | 0.811321 | 23 | 159 | 5.608696 | 0.478261 | 0.209302 | 0.395349 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.08805 | 159 | 7 | 42 | 22.714286 | 0.889655 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.4 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
c596a02ec7cbeb8117212f55fed2e80383552a2d | 13,867 | py | Python | docs.py | martinMutuma/def-politico | 8edec74e23d5e4a9fe0faf02843bbc89187008ce | [
"MIT"
] | null | null | null | docs.py | martinMutuma/def-politico | 8edec74e23d5e4a9fe0faf02843bbc89187008ce | [
"MIT"
] | 9 | 2019-03-19T11:23:29.000Z | 2019-03-22T08:01:52.000Z | docs.py | martinMutuma/def-politico | 8edec74e23d5e4a9fe0faf02843bbc89187008ce | [
"MIT"
] | 4 | 2019-03-19T09:58:53.000Z | 2019-03-21T19:35:35.000Z | from app import create_app
from flasgger import Swagger
from flask_cors import CORS
app = create_app('production')
app.config['SWAGGER'] = {
"swagger": "2.0",
"uiversion": "3",
"info": {
"title": "Premier voting",
"description": """
This is the official documentation of the Kura Yangu API.
Use these endpoints to create a voting system
""",
"version": "2.0",
"license": {
"name": "MIT license",
"url": "https://opensource.org/licenses/MIT"
}
},
'securityDefinitions': {
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
}
}
swagger = Swagger(app)
# introduce CORS
CORS(app)
@app.route('/api/v2/auth/signup', methods=['POST'])
def signup():
""" Endpoint for registering a User.
---
tags:
- Users
parameters:
-
name: authorization
in: header
type: string
required: false
example: Bearer
- in: body
name: Users
required: true
schema:
type: object
properties:
firstname:
type: string
example: "Governor"
lastname:
type: string
example: "Mani"
othername:
type: string
example: "Mili"
email:
type: string
example: "bedank6@gmail.com"
phoneNumber:
type: string
example: "0700000000"
passportUrl:
type: string
example: "federal"
isAdmin:
type: bool
example: True
password:
type: string
example: "jivutie"
responses:
'201':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/auth/signup', methods=['PUT'])
def set_admin():
""" Endpoint for changing a user's Admin status.
---
tags:
- Users
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: body
name: Users
required: true
schema:
type: object
properties:
email:
type: string
example: "james@gmail.com"
responses:
'200':
description: Updated
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/auth/login', methods=['POST'])
def login():
""" Endpoint for log in.
---
tags:
- Users
parameters:
- in: body
name: Users
required: true
schema:
type: object
properties:
email:
type: string
example: "bedank6@gmail.com"
password:
type: string
example: "jivunie"
responses:
'200':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/auth/reset', methods=['POST'])
def reset():
""" Endpoint for resetting password.
---
tags:
- Users
parameters:
- in: body
name: Users
required: true
schema:
type: object
properties:
email:
type: string
example: "bedank6@gmail.com"
responses:
'200':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/offices', methods=['POST'])
def offices():
""" Endpoint for creating an office.
---
tags:
- Offices
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: body
name: Offices
required: true
schema:
type: object
properties:
name:
type: string
example: "Governor"
type:
type: string
example: "federal"
responses:
'201':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/offices', methods=['GET'])
def get_offices():
""" Endpoint for getting all offices.
---
tags:
- Offices
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/offices/<office_id>', methods=['GET'])
def get_single_office(office_id):
""" Endpoint for getting a specific office.
---
tags:
- Offices
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: office_id
required: true
type: integer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/offices/<office_id>', methods=['DELETE'])
def delete_single_office(office_id):
""" Endpoint for deleting an office.
---
tags:
- Offices
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: office_id
required: true
type: integer
responses:
'200':
description: Success
'404':
description: Not found
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/parties', methods=['POST'])
def parties():
""" Endpoint for creating a party.
---
tags:
- Parties
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: body
name: Parties
required: true
schema:
type: object
properties:
name:
type: string
example: "SOME PARTY"
hq_address:
type: string
example: "federal"
logo_url:
type: string
example: "..."
slogan:
type: string
example: "federal"
responses:
'201':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/parties', methods=['GET'])
def get_parties():
""" Endpoint for getting a list of parties.
---
tags:
- Parties
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/parties/<party_id>', methods=['GET'])
def get_single_party(party_id):
""" Endpoint for getting a single party.
---
tags:
- Parties
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: party_id
required: true
type: integer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/parties/<party_id>', methods=['DELETE'])
def delete_single_party(office_id):
""" Endpoint for deleting a party.
---
tags:
- Parties
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: party_id
required: true
type: integer
responses:
'200':
description: Success
'404':
description: Not found
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/parties/<party_id>/name', methods=['PATCH'])
def patch_single_party(party_id):
""" Endpoint for editting the name of a party.
---
tags:
- Parties
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: party_id
required: true
type: integer
- in: body
name: Party
required: true
schema:
type: object
properties:
name:
type: string
example: New name
responses:
'200':
description: Success
'404':
description: Not found
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/office/<id>/register', methods=['POST'])
def candidates(id):
""" Endpoint for creating a candidate.
---
tags:
- Candidates
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: id
required: true
type: integer
- in: body
name: Candidate
required: true
schema:
type: object
properties:
party:
type: int
example: 1
candidate:
type: int
example: 1
responses:
'201':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/candidates', methods=['GET'])
def get_candidates():
""" Endpoint for getting a list of all candidates.
---
tags:
- Candidates
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/candidates/<candidate_id>', methods=['GET'])
def get_single_candidate(candidate_id):
""" Endpoint for getting a specific candidate.
---
tags:
- Candidates
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: candidate_id
required: true
type: integer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/votes', methods=['POST'])
def votes(id):
""" Endpoint for casting a vote.
---
tags:
- Votes
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: body
name: Candidate
required: true
schema:
type: object
properties:
candidate:
type: int
example: 1
office:
type: int
example: 1
responses:
'201':
description: Created
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/office/<office_id>/result', methods=['GET'])
def get_votes(office_id):
""" Endpoint for getting election results for an office.
---
tags:
- Votes
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
- in: path
name: office_id
required: true
type: integer
responses:
'200':
description: Success
'409':
description: Duplicate
'422':
description: Unprocessable
'400':
description: Bad Request
"""
@app.route('/api/v2/voting-history', methods=['GET'])
def get_voting_history():
""" Endpoint for getting voting history
---
tags:
- Votes
parameters:
-
name: authorization
in: header
type: string
required: true
example: Bearer
responses:
'200':
description: Success
'404':
description: Not Found
'422':
description: Unprocessable
'400':
description: Bad Request
"""
if __name__ == '__main__':
app.run()
| 21.235835 | 65 | 0.498666 | 1,202 | 13,867 | 5.708819 | 0.133111 | 0.051006 | 0.030458 | 0.035995 | 0.779948 | 0.760565 | 0.717867 | 0.706208 | 0.701108 | 0.701108 | 0 | 0.032075 | 0.401961 | 13,867 | 652 | 66 | 21.268405 | 0.79537 | 0.666186 | 0 | 0 | 0 | 0 | 0.343426 | 0.104936 | 0 | 0 | 0 | 0 | 0 | 1 | 0.275362 | false | 0 | 0.043478 | 0 | 0.318841 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
c5d5b7459338c994c52a1c52e96b42e400721976 | 166 | py | Python | ibsng/handler/util/afe_get_all_groups.py | ParspooyeshFanavar/pyibsng | d48bcf4f25e3f23461528bf0ff8870cc3d537444 | [
"MIT"
] | 6 | 2018-03-06T10:16:36.000Z | 2021-12-05T12:43:10.000Z | ibsng/handler/util/afe_get_all_groups.py | ParspooyeshFanavar/pyibsng | d48bcf4f25e3f23461528bf0ff8870cc3d537444 | [
"MIT"
] | 3 | 2018-03-06T10:27:08.000Z | 2022-01-02T15:21:27.000Z | ibsng/handler/util/afe_get_all_groups.py | ParspooyeshFanavar/pyibsng | d48bcf4f25e3f23461528bf0ff8870cc3d537444 | [
"MIT"
] | 3 | 2018-01-06T16:28:31.000Z | 2018-09-17T19:47:19.000Z | """AFE get all groups API method."""
from ibsng.handler.handler import Handler
class afeGetAllGroups(Handler):
"""AFE get all groups method class."""
pass
| 18.444444 | 42 | 0.704819 | 22 | 166 | 5.318182 | 0.590909 | 0.102564 | 0.153846 | 0.25641 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.180723 | 166 | 8 | 43 | 20.75 | 0.860294 | 0.379518 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 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 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 6 |
c5f1027ca27d0338d27c2143e6ce95dbb9ee5fb9 | 49 | py | Python | unit_test/simplest_test.py | leehosung/pycon-testing | 7487e5e1b893cb09425720aa8e7c5615bb1b9146 | [
"MIT"
] | null | null | null | unit_test/simplest_test.py | leehosung/pycon-testing | 7487e5e1b893cb09425720aa8e7c5615bb1b9146 | [
"MIT"
] | null | null | null | unit_test/simplest_test.py | leehosung/pycon-testing | 7487e5e1b893cb09425720aa8e7c5615bb1b9146 | [
"MIT"
] | null | null | null | def add(x):
return x + 1
assert add(1) == 3
| 9.8 | 18 | 0.530612 | 10 | 49 | 2.6 | 0.7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.088235 | 0.306122 | 49 | 4 | 19 | 12.25 | 0.676471 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.333333 | false | 0 | 0 | 0.333333 | 0.666667 | 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 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
c5fd0551f03857ccadd19e6c407e7aadbdbd7375 | 904 | py | Python | tests/datasets/test_oaei_kg.py | dobraczka/forayer | df6783f85fb063f58e8b96acef924f9fd2532227 | [
"MIT"
] | 5 | 2021-09-06T13:50:44.000Z | 2022-02-14T09:39:09.000Z | tests/datasets/test_oaei_kg.py | dobraczka/forayer | df6783f85fb063f58e8b96acef924f9fd2532227 | [
"MIT"
] | 5 | 2021-09-07T06:53:41.000Z | 2022-01-17T09:51:53.000Z | tests/datasets/test_oaei_kg.py | dobraczka/forayer | df6783f85fb063f58e8b96acef924f9fd2532227 | [
"MIT"
] | null | null | null | from forayer.datasets import OAEIKGDataset
def test_open_ea_dataset():
ds = OAEIKGDataset(task="memoryalpha-memorybeta", force=True)
assert (
ds.er_task.kgs["memoryalpha"].entities[
"http://dbkwik.webdatacommons.org/memory-alpha.wikia.com/resource/Verillian"
]["http://www.w3.org/2000/01/rdf-schema#label"]
== "Verillian"
)
assert (
ds.er_task.kgs["memorybeta"].entities[
"http://dbkwik.webdatacommons.org/memory-beta.wikia.com/resource/Verillian"
]["http://www.w3.org/2000/01/rdf-schema#label"]
== "Verillian"
)
assert (
ds.er_task.clusters.elements[
"http://dbkwik.webdatacommons.org/memory-alpha.wikia.com/resource/Verillian"
]
== ds.er_task.clusters.elements[
"http://dbkwik.webdatacommons.org/memory-beta.wikia.com/resource/Verillian"
]
)
| 32.285714 | 88 | 0.631637 | 102 | 904 | 5.529412 | 0.392157 | 0.028369 | 0.056738 | 0.191489 | 0.77305 | 0.737589 | 0.70922 | 0.70922 | 0.70922 | 0.70922 | 0 | 0.019774 | 0.216814 | 904 | 27 | 89 | 33.481481 | 0.776836 | 0 | 0 | 0.478261 | 0 | 0 | 0.485619 | 0.024336 | 0 | 0 | 0 | 0 | 0.130435 | 1 | 0.043478 | false | 0 | 0.043478 | 0 | 0.086957 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 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 | 6 |
68084c742132507c81997f2e189f128c1cb82d08 | 10,004 | py | Python | tests/hooks/s3/test_dbt_s3_hook.py | tomasfarias/airflow-dbt-python | 1cffdcafd8841b96ee622a49d9ae8f6716c55831 | [
"MIT"
] | 37 | 2021-06-15T23:23:28.000Z | 2022-03-22T08:16:49.000Z | tests/hooks/s3/test_dbt_s3_hook.py | tomasfarias/airflow-dbt-python | 1cffdcafd8841b96ee622a49d9ae8f6716c55831 | [
"MIT"
] | 29 | 2021-06-01T21:03:39.000Z | 2022-03-12T15:09:33.000Z | tests/hooks/s3/test_dbt_s3_hook.py | tomasfarias/airflow-dbt-python | 1cffdcafd8841b96ee622a49d9ae8f6716c55831 | [
"MIT"
] | 5 | 2021-08-04T08:48:31.000Z | 2022-02-07T19:14:56.000Z | """Unit test module for DbtS3Hook."""
import io
import shutil
from pathlib import Path
from zipfile import ZipFile
import pytest
try:
from airflow_dbt_python.hooks.s3 import DbtS3Hook
except ImportError:
pytest.skip(
"S3Hook not available, consider installing amazon extras",
allow_module_level=True,
)
def test_pull_dbt_profiles(s3_bucket, tmpdir, profiles_file):
"""Test pulling dbt profile from S3 path."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(profiles_file) as pf:
profiles_content = pf.read()
bucket.put_object(Key="profiles/profiles.yml", Body=profiles_content.encode())
profiles_path = hook.pull_dbt_profiles(
f"s3://{s3_bucket}/profiles/",
profiles_dir=str(tmpdir),
)
assert profiles_path.exists()
with open(profiles_path) as f:
result = f.read()
assert result == profiles_content
def test_pull_dbt_profiles_sub_dir(s3_bucket, tmpdir, profiles_file):
"""Test pulling dbt profile from S3 path sub-directory."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(profiles_file) as pf:
profiles_content = pf.read()
bucket.put_object(
Key="profiles/v0.0.1/profiles.yml", Body=profiles_content.encode()
)
profiles_path = hook.pull_dbt_profiles(
f"s3://{s3_bucket}/profiles/v0.0.1",
profiles_dir=str(tmpdir),
)
assert profiles_path.exists()
with open(profiles_path) as f:
result = f.read()
assert result == profiles_content
def test_pull_dbt_profiles_sub_dir_trailing_slash(s3_bucket, tmpdir, profiles_file):
"""Test whether an S3 path without a trailing slash pulls a dbt project."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(profiles_file) as pf:
profiles_content = pf.read()
bucket.put_object(
Key="profiles/v0.0.1/profiles.yml", Body=profiles_content.encode()
)
profiles_path = hook.pull_dbt_profiles(
f"s3://{s3_bucket}/profiles/v0.0.1/",
profiles_dir=str(tmpdir),
)
assert profiles_path.exists()
with open(profiles_path) as f:
result = f.read()
assert result == profiles_content
def test_pull_dbt_project(s3_bucket, tmpdir, dbt_project_file):
"""Test pulling dbt project from S3 path."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(dbt_project_file) as pf:
project_content = pf.read()
bucket.put_object(Key="project/dbt_project.yml", Body=project_content.encode())
bucket.put_object(Key="project/models/a_model.sql", Body=b"SELECT 1")
bucket.put_object(Key="project/models/another_model.sql", Body=b"SELECT 2")
bucket.put_object(Key="project/data/a_seed.csv", Body=b"col1,col2\n1,2")
project_path = hook.pull_dbt_project(
f"s3://{s3_bucket}/project/",
project_dir=str(tmpdir),
)
assert project_path.exists()
dir_contents = [f for f in project_path.iterdir()]
assert sorted(str(f.name) for f in dir_contents) == [
"data",
"dbt_project.yml",
"models",
]
with open(project_path / "dbt_project.yml") as f:
result = f.read()
assert result == project_content
with open(project_path / "models" / "a_model.sql") as f:
result = f.read()
assert result == "SELECT 1"
with open(project_path / "models" / "another_model.sql") as f:
result = f.read()
assert result == "SELECT 2"
with open(project_path / "data" / "a_seed.csv") as f:
result = f.read()
assert result == "col1,col2\n1,2"
def test_pull_dbt_project_no_trailing_slash(s3_bucket, tmpdir, dbt_project_file):
"""Test whether an S3 path without a trailing slash pulls a dbt project."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(dbt_project_file) as pf:
project_content = pf.read()
bucket.put_object(Key="project/dbt_project.yml", Body=project_content.encode())
bucket.put_object(Key="project/models/a_model.sql", Body=b"SELECT 1")
bucket.put_object(Key="project/models/another_model.sql", Body=b"SELECT 2")
bucket.put_object(Key="project/data/a_seed.csv", Body=b"col1,col2\n1,2")
project_path = hook.pull_dbt_project(
f"s3://{s3_bucket}/project",
project_dir=str(tmpdir),
)
assert project_path.exists()
dir_contents = [f for f in project_path.iterdir()]
assert sorted(str(f.name) for f in dir_contents) == [
"data",
"dbt_project.yml",
"models",
]
with open(project_path / "dbt_project.yml") as f:
result = f.read()
assert result == project_content
with open(project_path / "models" / "a_model.sql") as f:
result = f.read()
assert result == "SELECT 1"
with open(project_path / "models" / "another_model.sql") as f:
result = f.read()
assert result == "SELECT 2"
with open(project_path / "data" / "a_seed.csv") as f:
result = f.read()
assert result == "col1,col2\n1,2"
@pytest.fixture
def test_files(tmp_path_factory, dbt_project_file):
"""Create test files to upload to S3."""
d = tmp_path_factory.mktemp("test_s3")
seed_dir = d / "seeds"
seed_dir.mkdir(exist_ok=True)
f1 = seed_dir / "a_seed.csv"
with open(f1, "w+") as f:
f.write("col1,col2\n1,2")
models_dir = d / "models"
models_dir.mkdir(exist_ok=True)
f2 = models_dir / "a_model.sql"
with open(f2, "w+") as f:
f.write("SELECT 1")
f3 = models_dir / "another_model.sql"
with open(f3, "w+") as f:
f.write("SELECT 2")
shutil.copyfile(dbt_project_file, d / "dbt_project.yml")
yield [f1, f2, f3]
f1.unlink()
f2.unlink()
f3.unlink()
def test_pull_dbt_project_from_zip_file(
s3_bucket, tmpdir, dbt_project_file, test_files
):
"""Test pulling dbt project from ZipFile in S3 path."""
with open(dbt_project_file) as pf:
project_content = pf.read()
# Prepare a zip file to upload to S3
zip_buffer = io.BytesIO()
with ZipFile(zip_buffer, "a") as zf:
zf.write(dbt_project_file, "dbt_project.yml")
for f in test_files:
# Since files are in a different temporary directory, we need to zip them
# with their direct parent, e.g. models/a_model.sql
zf.write(f, arcname="/".join([f.parts[-2], f.parts[-1]]))
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
bucket.put_object(Key="project/project.zip", Body=zip_buffer.getvalue())
project_path = hook.pull_dbt_project(
f"s3://{s3_bucket}/project/project.zip",
project_dir=str(tmpdir),
)
assert project_path.exists()
dir_contents = [f for f in project_path.iterdir()]
assert sorted(str(f.name) for f in dir_contents) == [
"dbt_project.yml",
"models",
"seeds",
]
with open(project_path / "dbt_project.yml") as f:
result = f.read()
assert result == project_content
with open(project_path / "models" / "a_model.sql") as f:
result = f.read()
assert result == "SELECT 1"
with open(project_path / "models" / "another_model.sql") as f:
result = f.read()
assert result == "SELECT 2"
with open(project_path / "seeds" / "a_seed.csv") as f:
result = f.read()
assert result == "col1,col2\n1,2"
def test_pull_dbt_project_with_empty_file(s3_bucket, tmpdir, dbt_project_file):
"""Test whether an S3 path without a trailing slash pulls a dbt project."""
hook = DbtS3Hook()
bucket = hook.get_bucket(s3_bucket)
with open(dbt_project_file) as pf:
project_content = pf.read()
bucket.put_object(Key="project/dbt_project.yml", Body=project_content.encode())
bucket.put_object(Key="project/models/a_model.sql", Body=b"SELECT 1")
bucket.put_object(Key="project/data/a_seed.csv", Body=b"col1,col2\n1,2")
bucket.put_object(Key="project/data//", Body=b"")
project_path = hook.pull_dbt_project(
f"s3://{s3_bucket}/project",
project_dir=str(tmpdir),
)
assert project_path.exists()
dir_contents = [f for f in project_path.iterdir()]
assert sorted(str(f.name) for f in dir_contents) == [
"data",
"dbt_project.yml",
"models",
]
with open(project_path / "dbt_project.yml") as f:
result = f.read()
assert result == project_content
with open(project_path / "models" / "a_model.sql") as f:
result = f.read()
assert result == "SELECT 1"
def test_push_dbt_project_to_zip_file(s3_bucket, tmpdir, test_files):
"""Test pushing a dbt project to a ZipFile in S3 path."""
hook = DbtS3Hook()
# Ensure zip file is not already present.
hook.delete_objects(
s3_bucket,
[f"s3://{s3_bucket}/project/project.zip"],
)
key = hook.check_for_key(
f"s3://{s3_bucket}/project/project.zip",
s3_bucket,
)
assert key is False
hook.push_dbt_project(
f"s3://{s3_bucket}/project/project.zip", test_files[0].parent.parent
)
key = hook.check_for_key(
f"s3://{s3_bucket}/project/project.zip",
s3_bucket,
)
assert key is True
def test_push_dbt_project_to_files(s3_bucket, tmpdir, test_files):
"""Test pushing a dbt project to a S3 path."""
hook = DbtS3Hook()
# Ensure we are working with an empty S3 prefix.
keys = hook.list_keys(
s3_bucket,
f"s3://{s3_bucket}/project/",
)
if keys is not None and len(keys) > 0:
hook.delete_objects(
s3_bucket,
keys,
)
keys = hook.list_keys(
s3_bucket,
f"s3://{s3_bucket}/project/",
)
assert keys is None or len(keys) == 0
hook.push_dbt_project(f"s3://{s3_bucket}/project/", test_files[0].parent.parent)
keys = hook.list_keys(
s3_bucket,
f"s3://{s3_bucket}/project/",
)
assert len(keys) == 4
| 29.510324 | 86 | 0.643243 | 1,438 | 10,004 | 4.269124 | 0.107789 | 0.070044 | 0.024923 | 0.027692 | 0.825705 | 0.77081 | 0.75452 | 0.73872 | 0.725688 | 0.711842 | 0 | 0.019689 | 0.228309 | 10,004 | 338 | 87 | 29.597633 | 0.775518 | 0.079568 | 0 | 0.642276 | 0 | 0 | 0.167687 | 0.08756 | 0 | 0 | 0 | 0 | 0.130081 | 1 | 0.04065 | false | 0 | 0.028455 | 0 | 0.069106 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
a850f303ffe970275de0cd48b41cd32119bcb1a1 | 9,466 | py | Python | tests/testcases/messages_tests.py | merretbuurman/esgf-pid | df511387904ad215cd84ef29ef0c902ce6cec826 | [
"Apache-2.0"
] | null | null | null | tests/testcases/messages_tests.py | merretbuurman/esgf-pid | df511387904ad215cd84ef29ef0c902ce6cec826 | [
"Apache-2.0"
] | 7 | 2017-02-22T15:24:54.000Z | 2021-05-06T22:43:15.000Z | tests/testcases/messages_tests.py | merretbuurman/esgf-pid | df511387904ad215cd84ef29ef0c902ce6cec826 | [
"Apache-2.0"
] | 5 | 2016-08-23T08:52:00.000Z | 2020-03-25T21:28:31.000Z | import unittest
import logging
import copy
import tests.utils as utils
from tests.utils import compare_json_return_errormessage as error_message
import esgfpid.exceptions
import esgfpid.assistant.messages as messages
# Logging
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.NullHandler())
# Test resources:
from resources.TESTVALUES import *
class MessageCreationTestcase(unittest.TestCase):
def setUp(self):
LOGGER.info('######## Next test (%s) ##########', __name__)
esgfpid.utils.routingkeys.add_prefix_to_routing_keys(PREFIX_WITH_HDL)
def tearDown(self):
LOGGER.info('#############################')
def __get_args_dict_file(self):
return dict(
file_handle='123/456',
is_replica='mightbe',
file_size='333bytes',
file_name='filey.nc',
checksum='xyz',
data_url='myurl.de',
data_node='dkrz.de',
parent_dataset='abc/def',
timestamp='todayish',
checksum_type='SHA999',
file_version='v7'
)
def __get_args_dict_dataset(self):
return dict(
dataset_handle='abc/def',
is_replica='mightbe',
drs_id='drs/id/foo',
version_number='201699',
list_of_files='listof_files',
data_node='dkrz.de',
timestamp='todayish'
)
### Actual test cases: ###
def test_make_message_publication_file_ok(self):
# Test variables
args_dict = self.__get_args_dict_file()
# Run code to be tested:
received_message = messages.publish_file(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.publi-file-orig'
expected['aggregation_level'] = 'file'
expected['operation'] = 'publish'
# Rename some:
expected['handle'] = expected['file_handle']
del expected['file_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_publication_file_replica_ok(self):
# Test variables
args_dict = self.__get_args_dict_file()
args_dict['is_replica'] = True
# Run code to be tested:
received_message = messages.publish_file(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.publi-file-repli'
expected['aggregation_level'] = 'file'
expected['operation'] = 'publish'
# Rename some:
expected['handle'] = expected['file_handle']
del expected['file_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_publication_dataset_ok(self):
# Test variables
args_dict = self.__get_args_dict_dataset()
# Run code to be tested:
received_message = messages.publish_dataset(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.publi-ds-orig'
expected['aggregation_level'] = 'dataset'
expected['operation'] = 'publish'
# Rename some:
expected['handle'] = expected['dataset_handle']
del expected['dataset_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
expected['files'] = expected['list_of_files']
del expected['list_of_files']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_publication_dataset_replica_ok(self):
# Test variables
args_dict = self.__get_args_dict_dataset()
args_dict['is_replica'] = True
# Run code to be tested:
received_message = messages.publish_dataset(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.publi-ds-repli'
expected['aggregation_level'] = 'dataset'
expected['operation'] = 'publish'
# Rename some:
expected['handle'] = expected['dataset_handle']
del expected['dataset_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
expected['files'] = expected['list_of_files']
del expected['list_of_files']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_publication_dataset_missing_args(self):
# Test variables
args_dict = self.__get_args_dict_dataset()
# Run code to be tested:
for k,v in args_dict.items():
args = copy.deepcopy(args_dict)
LOGGER.debug('Deleting %s and trying...', k)
del args[k]
with self.assertRaises(esgfpid.exceptions.ArgumentError):
received_message = messages.publish_dataset(**args)
def test_make_message_unpublish_allversions_consumer_must_find_versions_ok(self):
# Test variables
args_dict = dict(
drs_id = 'abc',
data_node = 'dkrz.de',
timestamp = 'todayish'
)
# Run code to be tested:
received_message = messages.unpublish_allversions_consumer_must_find_versions(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.unpubli-allvers'
expected['aggregation_level'] = 'dataset'
expected['operation'] = 'unpublish_all_versions'
# Rename some:
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_unpublish_one_version_ok(self):
# Test variables
args_dict = dict(
dataset_handle = 'abc/def',
data_node = 'dkrz.de',
timestamp = 'todayish',
drs_id = 'mytest'
)
# Run code to be tested:
received_message = messages.unpublish_one_version(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.unpubli-onevers'
expected['aggregation_level'] = 'dataset'
expected['operation'] = 'unpublish_one_version'
# Rename some:
expected['handle'] = expected['dataset_handle']
del expected['dataset_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_add_errata_ids_ok(self):
# Test variables
args_dict = dict(
dataset_handle = 'abc/def',
errata_ids = 'dkrz.de',
timestamp = 'todayish',
drs_id = 'drs_foo',
version_number = 'vers_foo'
)
# Run code to be tested:
received_message = messages.add_errata_ids_message(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.errata-add'
expected['operation'] = 'add_errata_ids'
expected['drs_id'] = 'drs_foo'
expected['version_number'] = 'vers_foo'
# Rename some:
expected['handle'] = expected['dataset_handle']
del expected['dataset_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message))
def test_make_message_remove_errata_ids_ok(self):
# Test variables
args_dict = dict(
dataset_handle = 'abc/def',
errata_ids = 'dkrz.de',
timestamp = 'todayish',
drs_id = 'drs_foo',
version_number = 'vers_foo'
)
# Run code to be tested:
received_message = messages.remove_errata_ids_message(**args_dict)
# Check result:
expected = copy.deepcopy(args_dict)
expected['ROUTING_KEY'] = PREFIX_FOR_ROUTINGKEY+'.HASH.fresh.errata-rem'
expected['operation'] = 'remove_errata_ids'
expected['drs_id'] = 'drs_foo'
expected['version_number'] = 'vers_foo'
# Rename some:
expected['handle'] = expected['dataset_handle']
del expected['dataset_handle']
expected['message_timestamp'] = expected['timestamp']
del expected['timestamp']
same = utils.is_json_same(expected, received_message)
self.assertTrue(same, error_message(expected, received_message)) | 34.673993 | 98 | 0.635643 | 1,024 | 9,466 | 5.567383 | 0.142578 | 0.050517 | 0.06455 | 0.028416 | 0.810384 | 0.801614 | 0.756885 | 0.731451 | 0.731451 | 0.714261 | 0 | 0.00269 | 0.25375 | 9,466 | 273 | 99 | 34.673993 | 0.80436 | 0.06349 | 0 | 0.620112 | 0 | 0 | 0.181118 | 0.031282 | 0 | 0 | 0 | 0 | 0.050279 | 1 | 0.072626 | false | 0 | 0.044693 | 0.011173 | 0.134078 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
a85391a2bb2b9fdcab69e33909bee454bc84b96a | 7,251 | py | Python | lib10x/sample.py | antonybholmes/lib10x | 95700512e3a5e10fe7b1655f686065348243c8e7 | [
"MIT"
] | null | null | null | lib10x/sample.py | antonybholmes/lib10x | 95700512e3a5e10fe7b1655f686065348243c8e7 | [
"MIT"
] | null | null | null | lib10x/sample.py | antonybholmes/lib10x | 95700512e3a5e10fe7b1655f686065348243c8e7 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 09:43:43 2018
@author: antony
"""
import pandas as pd
import numpy as np
import collections
def get_tsne_plot_name(name, t1=1, t2=2):
return 'tsne_sample_{}.pdf'.format(name)
def create_sample_clusters(tsne, labels):
"""
Create a cluster data frame from samples.
Parameters
----------
tsne : pandas.DataFrame
t-sne table
labels : list or tuple
String labels for sample names
Returns
-------
pandas.DataFrame
Cells with cluster label for which sample they belong to.
"""
id = -1
clusters = np.array(['' for i in range(0, tsne.shape[0])], dtype=object)
for label in labels:
clusters[tsne.index.str.contains('{}'.format(id))] = label
id -= 1
df = pd.DataFrame({'Barcode':tsne.index, 'Cluster':clusters})
df = df.set_index('Barcode')
return df
def create_merge_cluster_info(clusters, name, sample_names=('RK10001', 'RK10002'), dir='.'):
"""
Summarizes how many samples are in each cluster and from which experiment
they came.
Parameters
----------
clusters : DataFrame
table of clusters.
name : str
prefix for file output
"""
cids = list(sorted(set(clusters['Cluster'].tolist())))
samples = np.array(['' for i in range(0, clusters.shape[0])], dtype=object)
for i in range(0, len(sample_names)):
id = '-{}'.format(i + 1)
samples[clusters.index.str.contains(id)] = sample_names[i]
id = '.{}'.format(i + 1)
samples[clusters.index.str.contains(id)] = sample_names[i]
size_map = {}
cluster_sample_sizes = collections.defaultdict(lambda : collections.defaultdict(int))
for cid in cids:
size_map[cid] = clusters[clusters['Cluster'] == cid]['Cluster'].shape[0]
for i in range(0, len(sample_names)):
id = '-{}'.format(i + 1)
# count how many cells are in each cluster for each sample
cluster_sample_sizes[cid][sample_names[i]] = clusters[(clusters['Cluster'] == cid) & clusters.index.str.contains(id)].shape[0]
id = '.{}'.format(i + 1)
cluster_sample_sizes[cid][sample_names[i]] = clusters[(clusters['Cluster'] == cid) & clusters.index.str.contains(id)].shape[0]
sample_counts = np.zeros((clusters.shape[0], len(sample_names)), dtype=int)
sizes = np.zeros(clusters.shape[0], dtype=int)
for i in range(0, clusters.shape[0]):
cs = cluster_sample_sizes[clusters['Cluster'][i]]
for j in range(0, len(sample_names)):
sample_counts[i, j] = cs[sample_names[j]]
sizes[i] = size_map[clusters['Cluster'][i]]
df = pd.DataFrame({'Barcode':clusters.index, 'Cluster':clusters['Cluster'], 'Sample':samples, 'Size':sizes})
for i in range(0, len(sample_names)):
df['Count {}'.format(sample_names[i])] = sample_counts[:, i]
#df = df[['Barcode', 'Cluster', 'Sample', '{} count'.format(sample_names[0]), '{} count'.format(sample_names[1]), 'Size']]
df.to_csv('{}/{}_cell_cluster_info.txt'.format(dir, name), sep='\t', header=True, index=False)
# table of cluster sizes
sample_counts = np.zeros((len(cids), len(sample_names)), dtype=int)
sizes = np.zeros(len(cids), dtype=int)
for i in range(0, len(cids)):
c = cids[i]
cs = cluster_sample_sizes[c]
for j in range(0, len(sample_names)):
sample_counts[i, j] = cs[sample_names[j]]
sizes[i] = size_map[c]
df = pd.DataFrame({'Cluster':cids, 'Size':sizes})
for i in range(0, len(sample_names)):
df['Count {}'.format(sample_names[i])] = sample_counts[:, i]
#df = df[['Barcode', 'Cluster', 'Sample', '{} count'.format(sample_names[0]), '{} count'.format(sample_names[1]), 'Size']]
df.to_csv('{}/{}_cluster_info.txt'.format(dir, name), sep='\t', header=True, index=False)
def create_origin_cluster_info(clusters, name, dir='.'):
"""
Summarizes how many samples are in each cluster and from which experiment
they came.
Parameters
----------
clusters : DataFrame
table of clusters.
name : str
prefix for file output
"""
cids = list(sorted(set(clusters['Cluster'].tolist())))
sample_names = list(sorted(set(clusters['origin'].tolist())))
samples = clusters['origin'] #np.array(['' for i in range(0, clusters.shape[0])], dtype=object)
# for i in range(0, len(sample_names)):
# id = '-{}'.format(i + 1)
# samples[clusters.index.str.contains(id)] = sample_names[i]
#
size_map = {}
cluster_sample_sizes = collections.defaultdict(lambda : collections.defaultdict(int))
for cid in cids:
size_map[cid] = clusters[clusters['Cluster'] == cid]['Cluster'].shape[0]
for sample_name in sample_names:
if cid == 6 and sample_name == '1_4_gc_b_c11':
print(sample_name)
hmm = clusters[(clusters['Cluster'] == cid) & (clusters['origin'] == sample_name)]
print(hmm.index.values.size)
# count how many cells are in each cluster for each sample
cluster_sample_sizes[cid][sample_name] = clusters[(clusters['Cluster'] == cid) & (clusters['origin'] == sample_name)].shape[0]
print('---')
sample_counts = np.zeros((clusters.shape[0], len(sample_names)), dtype=int)
sizes = np.zeros(clusters.shape[0], dtype=int)
for i in range(0, clusters.shape[0]):
cs = cluster_sample_sizes[clusters['Cluster'][i]]
for j in range(0, len(sample_names)):
sample_counts[i, j] = cs[sample_names[j]]
sizes[i] = size_map[clusters['Cluster'][i]]
df = pd.DataFrame({'Barcode':clusters.index, 'Cluster':clusters['Cluster'], 'Sample':samples, 'Size':sizes})
for i in range(0, len(sample_names)):
df['Count {}'.format(sample_names[i])] = sample_counts[:, i]
#df = df[['Barcode', 'Cluster', 'Sample', '{} count'.format(sample_names[0]), '{} count'.format(sample_names[1]), 'Size']]
df.to_csv('{}/{}_cell_origin_info.txt'.format(dir, name), sep='\t', header=True, index=False)
# table of cluster sizes
sample_counts = np.zeros((len(cids), len(sample_names)), dtype=int)
sizes = np.zeros(len(cids), dtype=int)
for i in range(0, len(cids)):
c = cids[i]
cs = cluster_sample_sizes[c]
for j in range(0, len(sample_names)):
sample_counts[i, j] = cs[sample_names[j]]
sizes[i] = size_map[c]
df = pd.DataFrame({'Cluster':cids, 'Size':sizes})
for i in range(0, len(sample_names)):
df['Count {}'.format(sample_names[i])] = sample_counts[:, i]
#df = df[['Barcode', 'Cluster', 'Sample', '{} count'.format(sample_names[0]), '{} count'.format(sample_names[1]), 'Size']]
df.to_csv('{}/{}_origin_info.txt'.format(dir, name), sep='\t', header=True, index=False)
| 33.725581 | 138 | 0.585712 | 948 | 7,251 | 4.35865 | 0.138186 | 0.106486 | 0.03485 | 0.03727 | 0.802033 | 0.797193 | 0.797193 | 0.792594 | 0.768393 | 0.768393 | 0 | 0.014676 | 0.248242 | 7,251 | 214 | 139 | 33.883178 | 0.74335 | 0.219004 | 0 | 0.673913 | 0 | 0 | 0.077681 | 0.017505 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043478 | false | 0 | 0.032609 | 0.01087 | 0.097826 | 0.032609 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
a89023c9b55e8f936e44520085bda21ca0427e16 | 7,114 | py | Python | src/ppl/nn/engines/cuda/impls/src/nn/conv/gene_header.py | tangyanf/ppl.nn | 744ac02e7d6e363522dc629b35db8a5eca2e7c3c | [
"Apache-2.0"
] | 764 | 2021-06-30T13:36:15.000Z | 2022-03-31T02:29:38.000Z | src/ppl/nn/engines/cuda/impls/src/nn/conv/gene_header.py | FeiGeChuanShu/ppl.nn | 6f3477f00d174c9c2e36cfffea42d22bc357e0a5 | [
"Apache-2.0"
] | 66 | 2021-06-30T14:03:32.000Z | 2022-03-30T02:41:00.000Z | src/ppl/nn/engines/cuda/impls/src/nn/conv/gene_header.py | FeiGeChuanShu/ppl.nn | 6f3477f00d174c9c2e36cfffea42d22bc357e0a5 | [
"Apache-2.0"
] | 151 | 2021-06-30T13:43:11.000Z | 2022-03-27T07:43:55.000Z | # -*- coding: utf-8 -*-
"""
Init all include file into gene_header.cc
"""
import os
import sys
def write_head(file):
template = """// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "gene_header.h"
#include <fstream>
#include <sstream>
std::string GeneHeader::Find(const std::string& path) {
auto header_ref = header_code_.find(path);
if (header_ref != header_code_.end()) {
return header_ref->second;
}
return "";
}
GeneHeader::GeneHeader() {
std::string code_str;
"""
file.write(template)
def write_tail(file):
template = """}
"""
file.write(template)
def init_include_file(file, path, name):
with open(path + name, "r", encoding='UTF-8') as header_file:
code = header_file.read()
code = code.replace('\\', '\\\\')
code = code.replace('\"', '\\\"')
code = code.replace('\n', '\\n";\n code_str += \"')
template = """ code_str = "{code}";
header_code_.emplace("{name}", code_str);
"""
file.write(template.format(name = name,
code = code))
def main():
if len(sys.argv) != 3:
print(__doc__)
sys.exit(1)
sourse_pwd = sys.argv[1]
tail_pwd = sys.argv[2]
with open(tail_pwd + "/gene_header.cc", "w+", encoding='UTF-8') as f:
write_head(f)
init_include_file(f, sourse_pwd, "/2spk/common/const_macros.h")
init_include_file(f, sourse_pwd, "/2spk/f1/bound_macros.h")
init_include_file(f, sourse_pwd, "/2spk/f3/bound_macros.h")
init_include_file(f, sourse_pwd, "/2spk/fn/bound_macros.h")
init_include_file(f, sourse_pwd, "/2spk/fs/bound_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/ldsm_macros.h")
init_include_file(f, sourse_pwd, "/2spk/f1/dmem_macros.h")
init_include_file(f, sourse_pwd, "/2spk/f3/dmem_macros.h")
init_include_file(f, sourse_pwd, "/2spk/fn/dmem_macros.h")
init_include_file(f, sourse_pwd, "/2spk/fs/dmem_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/hmma_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/reduce_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/smem_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/output_macros.h")
init_include_file(f, sourse_pwd, "/2spk/common/main_body.h")
init_include_file(f, sourse_pwd, "/2spk/common/uni_undefs.h")
init_include_file(f, sourse_pwd, "/swzl/common/const_macros.h")
init_include_file(f, sourse_pwd, "/swzl/f1/bound_macros.h")
init_include_file(f, sourse_pwd, "/swzl/f3/bound_macros.h")
init_include_file(f, sourse_pwd, "/swzl/fn/bound_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/ldsm_macros.h")
init_include_file(f, sourse_pwd, "/swzl/f1/dmem_macros.h")
init_include_file(f, sourse_pwd, "/swzl/f3/dmem_macros.h")
init_include_file(f, sourse_pwd, "/swzl/fn/dmem_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/hmma_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/reduce_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/smem_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/output_macros.h")
init_include_file(f, sourse_pwd, "/swzl/common/main_body.h")
init_include_file(f, sourse_pwd, "/swzl/common/uni_undefs.h")
init_include_file(f, sourse_pwd, "/idxn/common/const_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/dmem_i1_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/hmma_i1_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/dmem_i2_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/hmma_i2_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/dmem_i4_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/hmma_i4_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/output_macros.h")
init_include_file(f, sourse_pwd, "/idxn/common/main_body.h")
init_include_file(f, sourse_pwd, "/idxn/common/uni_undefs.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/const_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/f1/bound_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/f3/bound_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/fn/bound_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/fs/bound_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/ldsm_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/f1/dmem_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/f3/dmem_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/fn/dmem_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/fs/dmem_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/imma_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/reduce_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/smem_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/output_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/quant_macros.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/main_body.h")
init_include_file(f, sourse_pwd, "/int8_2spk/common/uni_undefs.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/const_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/dmem_i1_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/imma_i1_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/dmem_i2_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/imma_i2_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/dmem_i4_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/imma_i4_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/output_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/quant_macros.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/main_body.h")
init_include_file(f, sourse_pwd, "/int8_idxn/common/uni_undefs.h")
write_tail(f)
if __name__ == "__main__":
main() | 49.062069 | 79 | 0.685409 | 1,078 | 7,114 | 4.197588 | 0.14193 | 0.170166 | 0.228729 | 0.240442 | 0.725746 | 0.712928 | 0.702983 | 0.702983 | 0.697459 | 0.694807 | 0 | 0.016385 | 0.176413 | 7,114 | 145 | 80 | 49.062069 | 0.755931 | 0.008996 | 0 | 0.055118 | 0 | 0 | 0.446543 | 0.28042 | 0 | 0 | 0 | 0 | 0 | 1 | 0.031496 | false | 0 | 0.015748 | 0 | 0.062992 | 0.007874 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 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 | 6 |
7658b7d770361cf509a505314cae2745915a6143 | 24 | py | Python | docker/app/__init__.py | dr666m1/project_distribution_app | 7d5d13e49ceeb7b9b82c26ab73828cc2c3dfde7b | [
"MIT"
] | null | null | null | docker/app/__init__.py | dr666m1/project_distribution_app | 7d5d13e49ceeb7b9b82c26ab73828cc2c3dfde7b | [
"MIT"
] | 1 | 2020-11-16T15:08:00.000Z | 2020-11-16T15:08:07.000Z | docker/app/__init__.py | dr666m1/project_distribution_app | 7d5d13e49ceeb7b9b82c26ab73828cc2c3dfde7b | [
"MIT"
] | null | null | null | from app.utils import *
| 12 | 23 | 0.75 | 4 | 24 | 4.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 24 | 1 | 24 | 24 | 0.9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
76a68ebdd454479ef53af4552a8946f90112a0ca | 115 | py | Python | 24-class-metaprog/qualname/fakedjango.py | SeirousLee/example-code-2e | 81ec1669a4b8fd098db44a78a3d551287eec7bc9 | [
"MIT"
] | 990 | 2019-03-21T21:17:34.000Z | 2022-03-31T00:55:07.000Z | 24-class-metaprog/qualname/fakedjango.py | FerMatPy/example-code-2e | 980f75032685921e08d5200513a261e83ef5f858 | [
"MIT"
] | 17 | 2019-12-18T18:00:05.000Z | 2022-01-12T14:23:47.000Z | 24-class-metaprog/qualname/fakedjango.py | FerMatPy/example-code-2e | 980f75032685921e08d5200513a261e83ef5f858 | [
"MIT"
] | 276 | 2019-04-06T12:32:00.000Z | 2022-03-29T11:50:47.000Z | class models:
class Model:
"nothing to see here"
class IntegerField:
"nothing to see here"
| 19.166667 | 29 | 0.608696 | 14 | 115 | 5 | 0.571429 | 0.257143 | 0.342857 | 0.457143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.330435 | 115 | 5 | 30 | 23 | 0.909091 | 0.33913 | 0 | 0.4 | 0 | 0 | 0.330435 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0.6 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
4f2fb67cef67eb24bb2b2733aafb61be32e369ca | 41 | py | Python | app_driver_client.py | nathantreid/app-driver-client-python | 6419093632d5cad5a58acf19c602831ad8383e71 | [
"MIT"
] | 1 | 2018-04-10T00:01:55.000Z | 2018-04-10T00:01:55.000Z | app_driver_client.py | nathantreid/app-driver-client-python | 6419093632d5cad5a58acf19c602831ad8383e71 | [
"MIT"
] | null | null | null | app_driver_client.py | nathantreid/app-driver-client-python | 6419093632d5cad5a58acf19c602831ad8383e71 | [
"MIT"
] | 1 | 2018-04-10T03:24:36.000Z | 2018-04-10T03:24:36.000Z | from client.connection3 import connection | 41 | 41 | 0.902439 | 5 | 41 | 7.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.026316 | 0.073171 | 41 | 1 | 41 | 41 | 0.947368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
4f38759c8d5fd4e91473c9f9291ba9f3b1fe2f59 | 37 | py | Python | tests/test_syllabus_check.py | MatsLanGoH/tku_syllabus_check | 0f2d80e45f64e9b3e4a0c3698fcab9b4d252929b | [
"MIT"
] | 1 | 2018-04-17T15:38:00.000Z | 2018-04-17T15:38:00.000Z | tests/test_syllabus_check.py | MatsLanGoH/tku_syllabus_check | 0f2d80e45f64e9b3e4a0c3698fcab9b4d252929b | [
"MIT"
] | null | null | null | tests/test_syllabus_check.py | MatsLanGoH/tku_syllabus_check | 0f2d80e45f64e9b3e4a0c3698fcab9b4d252929b | [
"MIT"
] | null | null | null | from .context import syllabus_check
| 12.333333 | 35 | 0.837838 | 5 | 37 | 6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135135 | 37 | 2 | 36 | 18.5 | 0.9375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
4f6dc0f67d71e882aa00a16f5d19be1bfb57b138 | 77 | py | Python | src/nodeset/core/interfaces/routing.py | selfsk/nodeset.core | 706743779a777b993110b4af1405fd1a7706874e | [
"MIT"
] | 1 | 2015-11-05T10:29:49.000Z | 2015-11-05T10:29:49.000Z | src/nodeset/core/interfaces/routing.py | selfsk/nodeset.core | 706743779a777b993110b4af1405fd1a7706874e | [
"MIT"
] | null | null | null | src/nodeset/core/interfaces/routing.py | selfsk/nodeset.core | 706743779a777b993110b4af1405fd1a7706874e | [
"MIT"
] | null | null | null | from zope import interface
class IRouteEntry(interface.Interface):
pass
| 15.4 | 39 | 0.792208 | 9 | 77 | 6.777778 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.155844 | 77 | 4 | 40 | 19.25 | 0.938462 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 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 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
4fad9a6e87762d579c5f8bfa2ff2429d56541c6e | 1,797 | py | Python | tests/tokenization/test_line_segment_tokenizer.py | johnml1135/machine.py | 7bfb668b81d6af476f7ee797900e111c3027d542 | [
"MIT"
] | 2 | 2021-09-14T15:41:14.000Z | 2021-09-14T15:53:46.000Z | tests/tokenization/test_line_segment_tokenizer.py | johnml1135/machine.py | 7bfb668b81d6af476f7ee797900e111c3027d542 | [
"MIT"
] | 2 | 2021-11-04T09:12:26.000Z | 2021-11-08T08:35:36.000Z | tests/tokenization/test_line_segment_tokenizer.py | johnml1135/machine.py | 7bfb668b81d6af476f7ee797900e111c3027d542 | [
"MIT"
] | 1 | 2021-11-03T14:45:11.000Z | 2021-11-03T14:45:11.000Z | from machine.tokenization import LineSegmentTokenizer
def test_tokenize_empty() -> None:
tokenizer = LineSegmentTokenizer()
assert not any(tokenizer.tokenize(""))
def test_tokenize_single_line() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is a test.")) == ["This is a test."]
def test_tokenize_multiple_lines() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is the first sentence.\nThis is the second sentence.")) == [
"This is the first sentence.",
"This is the second sentence.",
]
def test_tokenize_ends_with_newline() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is a test.\n")) == ["This is a test."]
def test_tokenize_ends_with_newline_and_space() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is a test.\n ")) == ["This is a test.", " "]
def test_tokenize_ends_with_text_and_space() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is the first sentence.\nThis is a partial sentence ")) == [
"This is the first sentence.",
"This is a partial sentence ",
]
def test_tokenize_empty_line() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is the first sentence.\n\nThis is the third sentence.")) == [
"This is the first sentence.",
"",
"This is the third sentence.",
]
def test_tokenize_line_ends_with_space() -> None:
tokenizer = LineSegmentTokenizer()
assert list(tokenizer.tokenize("This is the first sentence. \nThis is the second sentence.")) == [
"This is the first sentence. ",
"This is the second sentence.",
]
| 32.672727 | 102 | 0.681135 | 217 | 1,797 | 5.493088 | 0.165899 | 0.090604 | 0.083054 | 0.261745 | 0.774329 | 0.774329 | 0.743289 | 0.721477 | 0.691275 | 0.658557 | 0 | 0 | 0.20089 | 1,797 | 54 | 103 | 33.277778 | 0.830084 | 0 | 0 | 0.421053 | 0 | 0 | 0.302727 | 0 | 0 | 0 | 0 | 0 | 0.210526 | 1 | 0.210526 | false | 0 | 0.026316 | 0 | 0.236842 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 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 | 6 |
96c7464b8470dff3f948c5ad51be61fdf3285abe | 49 | py | Python | configuration/__init__.py | dgkncelik/clausius | 917bd02e888a2e8fb7dbccdd797b0a73a60ec7ba | [
"WTFPL"
] | null | null | null | configuration/__init__.py | dgkncelik/clausius | 917bd02e888a2e8fb7dbccdd797b0a73a60ec7ba | [
"WTFPL"
] | null | null | null | configuration/__init__.py | dgkncelik/clausius | 917bd02e888a2e8fb7dbccdd797b0a73a60ec7ba | [
"WTFPL"
] | null | null | null | from .base_configuration import BaseConfiguration | 49 | 49 | 0.918367 | 5 | 49 | 8.8 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.061224 | 49 | 1 | 49 | 49 | 0.956522 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
96d3c39de2dec2cca6acf15b27c8967b0ed94b37 | 133 | py | Python | kwat/probability/__init__.py | KwatME/ccal | d96dfa811482eee067f346386a2181ec514625f4 | [
"MIT"
] | 5 | 2017-05-05T17:50:28.000Z | 2019-01-30T19:23:02.000Z | kwat/probability/__init__.py | KwatME/ccal | d96dfa811482eee067f346386a2181ec514625f4 | [
"MIT"
] | 5 | 2017-05-05T01:52:31.000Z | 2019-04-20T21:06:05.000Z | kwat/probability/__init__.py | KwatME/ccal | d96dfa811482eee067f346386a2181ec514625f4 | [
"MIT"
] | 5 | 2017-07-17T18:55:54.000Z | 2019-02-02T04:46:19.000Z | from .get_posterior_probability import get_posterior_probability
from .get_probability import get_probability
from .plot import plot
| 33.25 | 64 | 0.887218 | 18 | 133 | 6.222222 | 0.333333 | 0.125 | 0.410714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.090226 | 133 | 3 | 65 | 44.333333 | 0.92562 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8c60d219f900e037eca13ae2f459e9ebad6c0ddf | 4,852 | py | Python | TestModule/EndOfGameTest.py | INYEONGKIM/Quattro | 0fd70b08716f71404f520941791cd314d90de83a | [
"MIT"
] | null | null | null | TestModule/EndOfGameTest.py | INYEONGKIM/Quattro | 0fd70b08716f71404f520941791cd314d90de83a | [
"MIT"
] | null | null | null | TestModule/EndOfGameTest.py | INYEONGKIM/Quattro | 0fd70b08716f71404f520941791cd314d90de83a | [
"MIT"
] | null | null | null | import unittest
from TestModule.GetMethodName import get_method_name_decorator
from QuattroComponents.Player import Player
from QuattroComponents.Card import Card
from QuattroComponents.View.EndOfGame import EndOfGame
def reset_players_attributes(player1: Player, player2: Player):
player1.total_score = 0
player2.total_score = 0
player1.top_card = -1
player2.top_card = -1
class EndOfGameTest(unittest.TestCase):
method_names = set()
@get_method_name_decorator
def test_get_winner(self):
surrender_flag = False
###### Made Quattro Case
# Both Made Quattro (sum)
player1 = Player(user_name="player1", user_deck=[
Card(number=6, color="red", isOpen=True),
Card(number=6, color="blue", isOpen=True),
Card(number=6, color="yellow", isOpen=True),
Card(number=6, color="green", isOpen=True)
])
player2 = Player(user_name="player2", user_deck=[
Card(number=5, color="red", isOpen=True),
Card(number=5, color="blue", isOpen=True),
Card(number=5, color="yellow", isOpen=True),
Card(number=5, color="green", isOpen=True)
])
self.assertEqual(EndOfGame(surrender_flag=surrender_flag,
winner="", player1=player1, player2=player2),
"player1", msg="Normal Test Case Fail!")
# Both Made Quattro (Top number)
reset_players_attributes(player1=player1, player2=player2)
player1.user_deck = [
Card(number=3, color="red", isOpen=True),
Card(number=3, color="blue", isOpen=True),
Card(number=3, color="yellow", isOpen=True),
Card(number=3, color="green", isOpen=True)
]
player2.user_deck = [
Card(number=2, color="red", isOpen=True),
Card(number=4, color="blue", isOpen=True),
Card(number=2, color="yellow", isOpen=True),
Card(number=4, color="green", isOpen=True)
]
self.assertEqual(EndOfGame(surrender_flag=surrender_flag,
winner="", player1=player1, player2=player2),
"player2", msg="Both Quattro Top number Test Case Fail!")
# Both Made Quattro (Top color)
reset_players_attributes(player1=player1, player2=player2)
player1.user_deck = [
Card(number=2, color="red", isOpen=True),
Card(number=4, color="blue", isOpen=True),
Card(number=5, color="yellow", isOpen=True),
Card(number=6, color="green", isOpen=True)
]
player2.user_deck = [
Card(number=6, color="red", isOpen=True),
Card(number=5, color="blue", isOpen=True),
Card(number=4, color="yellow", isOpen=True),
Card(number=2, color="green", isOpen=True)
]
self.assertEqual(EndOfGame(surrender_flag=surrender_flag,
winner="", player1=player1, player2=player2),
"player2", msg="Normal Test Case Fail!")
###### Made Quattro Case
# Both Didn't Made Quattro (Top number)
reset_players_attributes(player1=player1, player2=player2)
player1.user_deck = [
Card(number=6, color="red", isOpen=True),
Card(number=5, color="red", isOpen=True),
Card(number=6, color="yellow", isOpen=True),
Card(number=6, color="green", isOpen=True)
]
player2.user_deck = [
Card(number=5, color="red", isOpen=True),
Card(number=5, color="blue", isOpen=True),
Card(number=4, color="blue", isOpen=True),
Card(number=5, color="green", isOpen=True)
]
self.assertEqual(EndOfGame(surrender_flag=surrender_flag,
winner="", player1=player1, player2=player2),
"player1", msg="Number Top Case Fail!")
# Both Didn't Made Quattro (color)
reset_players_attributes(player1=player1, player2=player2)
player1.user_deck = [
Card(number=6, color="red", isOpen=True),
Card(number=5, color="red", isOpen=True),
Card(number=6, color="yellow", isOpen=True),
Card(number=6, color="green", isOpen=True)
]
player2.user_deck = [
Card(number=5, color="red", isOpen=True),
Card(number=5, color="blue", isOpen=True),
Card(number=6, color="blue", isOpen=True),
Card(number=5, color="green", isOpen=True)
]
self.assertEqual(EndOfGame(surrender_flag=surrender_flag,
winner="", player1=player1, player2=player2),
"player1", msg="color Top Case Fail!")
| 38.816 | 82 | 0.574815 | 541 | 4,852 | 5.07024 | 0.114603 | 0.145826 | 0.153117 | 0.218739 | 0.798031 | 0.778709 | 0.72366 | 0.70689 | 0.70689 | 0.697047 | 0 | 0.030091 | 0.294518 | 4,852 | 124 | 83 | 39.129032 | 0.771253 | 0.039365 | 0 | 0.595745 | 0 | 0 | 0.074752 | 0 | 0 | 0 | 0 | 0 | 0.053191 | 1 | 0.021277 | false | 0 | 0.053191 | 0 | 0.095745 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 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 | 6 |
4fe4d88eeb5ae18c85fbc3ac31a7ed374040fb5e | 126 | py | Python | build/repo/__init__.py | fifoforlifo/nstd | 68f5b370e10b2d1e078027ecbc040b7eaa9e08aa | [
"BSL-1.0"
] | null | null | null | build/repo/__init__.py | fifoforlifo/nstd | 68f5b370e10b2d1e078027ecbc040b7eaa9e08aa | [
"BSL-1.0"
] | null | null | null | build/repo/__init__.py | fifoforlifo/nstd | 68f5b370e10b2d1e078027ecbc040b7eaa9e08aa | [
"BSL-1.0"
] | null | null | null | # This directory is a Python package.
from .cpp import *
from .java import *
from .root_paths import *
from .deploy import *
| 18 | 37 | 0.730159 | 19 | 126 | 4.789474 | 0.684211 | 0.32967 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | 126 | 6 | 38 | 21 | 0.892157 | 0.277778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
4ffcb7da2f579e8e54caa32c6a9af4f49a9af69f | 28 | py | Python | acq4/analysis/modules/IVCurve_mbk/__init__.py | ablot/acq4 | ba7cd340d9d0282640adb501d3788f8c0837e4c4 | [
"MIT"
] | null | null | null | acq4/analysis/modules/IVCurve_mbk/__init__.py | ablot/acq4 | ba7cd340d9d0282640adb501d3788f8c0837e4c4 | [
"MIT"
] | null | null | null | acq4/analysis/modules/IVCurve_mbk/__init__.py | ablot/acq4 | ba7cd340d9d0282640adb501d3788f8c0837e4c4 | [
"MIT"
] | null | null | null | from IVCurve import IVCurve
| 14 | 27 | 0.857143 | 4 | 28 | 6 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | 28 | 1 | 28 | 28 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8b07d8beaef4f8b8ec4222441662dd31a6fc32f0 | 123 | py | Python | app/api/encryption/routes.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | app/api/encryption/routes.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | app/api/encryption/routes.py | shoulderhu/heroku-ctf-www | f1e136f8d93034d34a60702517b32fc0245dac38 | [
"MIT"
] | null | null | null | from .. import api
from flask import request, jsonify
@api.route("/rot13", methods=["GET", "POST"])
def rot13():
pass | 17.571429 | 45 | 0.658537 | 17 | 123 | 4.764706 | 0.764706 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.038835 | 0.162602 | 123 | 7 | 46 | 17.571429 | 0.747573 | 0 | 0 | 0 | 0 | 0 | 0.104839 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | true | 0.2 | 0.4 | 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 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
8b3a783df9dde290b50b42a272d8e65c9b9a469f | 10,916 | py | Python | lfs/catalog/migrations/0008_auto_20210406_1809.py | michael-hahn/django-lfs | 26c3471a8f8d88269c84f714f507b952dfdb6397 | [
"BSD-3-Clause"
] | null | null | null | lfs/catalog/migrations/0008_auto_20210406_1809.py | michael-hahn/django-lfs | 26c3471a8f8d88269c84f714f507b952dfdb6397 | [
"BSD-3-Clause"
] | null | null | null | lfs/catalog/migrations/0008_auto_20210406_1809.py | michael-hahn/django-lfs | 26c3471a8f8d88269c84f714f507b952dfdb6397 | [
"BSD-3-Clause"
] | null | null | null | # Generated by Django 3.1.2 on 2021-04-06 18:09
from django.db import migrations, models
import django.splice.splicefields
import lfs.catalog.models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0007_auto_20210405_1816'),
]
operations = [
migrations.RemoveField(
model_name='category',
name='synthesized',
),
migrations.RemoveField(
model_name='category',
name='taints',
),
migrations.RemoveField(
model_name='category',
name='trusted',
),
migrations.RemoveField(
model_name='deliverytime',
name='synthesized',
),
migrations.RemoveField(
model_name='deliverytime',
name='taints',
),
migrations.RemoveField(
model_name='deliverytime',
name='trusted',
),
migrations.RemoveField(
model_name='file',
name='synthesized',
),
migrations.RemoveField(
model_name='file',
name='taints',
),
migrations.RemoveField(
model_name='file',
name='trusted',
),
migrations.RemoveField(
model_name='filterstep',
name='synthesized',
),
migrations.RemoveField(
model_name='filterstep',
name='taints',
),
migrations.RemoveField(
model_name='filterstep',
name='trusted',
),
migrations.RemoveField(
model_name='groupspropertiesrelation',
name='synthesized',
),
migrations.RemoveField(
model_name='groupspropertiesrelation',
name='taints',
),
migrations.RemoveField(
model_name='groupspropertiesrelation',
name='trusted',
),
migrations.RemoveField(
model_name='image',
name='synthesized',
),
migrations.RemoveField(
model_name='image',
name='taints',
),
migrations.RemoveField(
model_name='image',
name='trusted',
),
migrations.RemoveField(
model_name='product',
name='synthesized',
),
migrations.RemoveField(
model_name='product',
name='taints',
),
migrations.RemoveField(
model_name='product',
name='trusted',
),
migrations.RemoveField(
model_name='productaccessories',
name='synthesized',
),
migrations.RemoveField(
model_name='productaccessories',
name='taints',
),
migrations.RemoveField(
model_name='productaccessories',
name='trusted',
),
migrations.RemoveField(
model_name='productattachment',
name='synthesized',
),
migrations.RemoveField(
model_name='productattachment',
name='taints',
),
migrations.RemoveField(
model_name='productattachment',
name='trusted',
),
migrations.RemoveField(
model_name='productpropertyvalue',
name='synthesized',
),
migrations.RemoveField(
model_name='productpropertyvalue',
name='taints',
),
migrations.RemoveField(
model_name='productpropertyvalue',
name='trusted',
),
migrations.RemoveField(
model_name='productspropertiesrelation',
name='synthesized',
),
migrations.RemoveField(
model_name='productspropertiesrelation',
name='taints',
),
migrations.RemoveField(
model_name='productspropertiesrelation',
name='trusted',
),
migrations.RemoveField(
model_name='property',
name='synthesized',
),
migrations.RemoveField(
model_name='property',
name='taints',
),
migrations.RemoveField(
model_name='property',
name='trusted',
),
migrations.RemoveField(
model_name='propertygroup',
name='synthesized',
),
migrations.RemoveField(
model_name='propertygroup',
name='taints',
),
migrations.RemoveField(
model_name='propertygroup',
name='trusted',
),
migrations.RemoveField(
model_name='propertyoption',
name='synthesized',
),
migrations.RemoveField(
model_name='propertyoption',
name='taints',
),
migrations.RemoveField(
model_name='propertyoption',
name='trusted',
),
migrations.RemoveField(
model_name='staticblock',
name='synthesized',
),
migrations.RemoveField(
model_name='staticblock',
name='taints',
),
migrations.RemoveField(
model_name='staticblock',
name='trusted',
),
migrations.AddField(
model_name='category',
name='category_cols_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='category_cols_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='level_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='level_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='meta_title_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='meta_title_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='name_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='name_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='position_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='position_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='product_cols_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='product_cols_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='product_rows_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='product_rows_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='slug_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='slug_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='template_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='template_taint',
field=models.BigIntegerField(default=0),
),
migrations.AddField(
model_name='category',
name='uid_synthesized',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='category',
name='uid_taint',
field=models.BigIntegerField(default=0),
),
migrations.AlterField(
model_name='category',
name='category_cols',
field=django.splice.splicefields.SpliceIntegerField(default=3, verbose_name='Category cols'),
),
migrations.AlterField(
model_name='category',
name='level',
field=django.splice.splicefields.SplicePositiveSmallIntegerField(default=1),
),
migrations.AlterField(
model_name='category',
name='meta_title',
field=django.splice.splicefields.SpliceCharField(default='<name>', max_length=100, verbose_name='Meta title'),
),
migrations.AlterField(
model_name='category',
name='name',
field=django.splice.splicefields.SpliceCharField(max_length=50, verbose_name='Name'),
),
migrations.AlterField(
model_name='category',
name='position',
field=django.splice.splicefields.SpliceIntegerField(default=1000, verbose_name='Position'),
),
migrations.AlterField(
model_name='category',
name='product_cols',
field=django.splice.splicefields.SpliceIntegerField(default=3, verbose_name='Product cols'),
),
migrations.AlterField(
model_name='category',
name='product_rows',
field=django.splice.splicefields.SpliceIntegerField(default=3, verbose_name='Product rows'),
),
migrations.AlterField(
model_name='category',
name='slug',
field=django.splice.splicefields.SpliceSlugField(unique=True, verbose_name='Slug'),
),
migrations.AlterField(
model_name='category',
name='template',
field=django.splice.splicefields.SplicePositiveSmallIntegerField(blank=True, choices=[(0, 'Category with products'), (1, 'Category with subcategories')], null=True, verbose_name='Category template'),
),
migrations.AlterField(
model_name='category',
name='uid',
field=django.splice.splicefields.SpliceCharField(default=lfs.catalog.models.get_unique_id_str, editable=False, max_length=50, unique=True),
),
]
| 31.549133 | 211 | 0.544888 | 821 | 10,916 | 7.093788 | 0.109622 | 0.1159 | 0.200893 | 0.231799 | 0.906422 | 0.872768 | 0.370021 | 0.325721 | 0.311813 | 0.311813 | 0 | 0.008121 | 0.345731 | 10,916 | 345 | 212 | 31.64058 | 0.807337 | 0.004122 | 0 | 0.855457 | 1 | 0 | 0.163124 | 0.024657 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.00885 | 0 | 0.017699 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8c70901fc62f0c33ed43c796b3a080bfe972003d | 6,620 | py | Python | web/tests/test_event_search.py | ercchy/coding-events | 38db125b351f190e3ff13be7b27d2a4e777cec40 | [
"MIT"
] | null | null | null | web/tests/test_event_search.py | ercchy/coding-events | 38db125b351f190e3ff13be7b27d2a4e777cec40 | [
"MIT"
] | null | null | null | web/tests/test_event_search.py | ercchy/coding-events | 38db125b351f190e3ff13be7b27d2a4e777cec40 | [
"MIT"
] | 1 | 2015-09-22T14:56:49.000Z | 2015-09-22T14:56:49.000Z | # -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from web.tests import EventFactory, ApprovedEventFactory, PastEventFactory
@pytest.mark.django_db
def test_search_show_only_approved(db, client):
approved_event = ApprovedEventFactory.create()
unapproved_event = EventFactory.create()
response = client.get('/search/')
assert approved_event.get_absolute_url() in response.content
assert unapproved_event.get_absolute_url() not in response.content
map(lambda x: x.delete(), [approved_event, unapproved_event])
def test_search_do_not_show_past_events(db, client):
future_event = ApprovedEventFactory.create()
past_event = PastEventFactory.create(status='APPROVED')
response = client.get('/search/')
assert future_event.get_absolute_url() in response.content
assert past_event.get_absolute_url() not in response.content
map(lambda x: x.delete(), [future_event, past_event])
def test_search_show_past_events(db, client):
future_event = ApprovedEventFactory.create()
past_event = PastEventFactory.create(status='APPROVED')
response = client.get('/search/?past=yes')
assert future_event.get_absolute_url() in response.content
assert past_event.get_absolute_url() in response.content
map(lambda x: x.delete(), [future_event, past_event])
def test_search_events_with_search_query_all_countries_multiple_results(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI")
approved2 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="AT")
response = client.get(reverse('web.search_events'), {'q':'arglebargle', 'country':'00'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
assert approved2.get_absolute_url() in response.content
map(lambda x: x.delete(), [approved1, approved2])
def test_search_events_with_search_query(db, client):
approved1 = ApprovedEventFactory.create(title='Event Arglebargle - Approved')
response = client.get(reverse('web.search_events'), {'q':'arglebargle'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
approved1.delete()
def test_search_events_search_in_location(db, client):
approved1 = ApprovedEventFactory.create(title='Event Arglebargle - Approved')
response = client.get(reverse('web.search_events'), {'q':'kersnikova'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
approved1.delete()
def test_search_events_search_in_wrong_location(db, client):
approved1 = ApprovedEventFactory.create(title='Event Arglebargle - Approved')
response = client.get(reverse('web.search_events'), {'q':'celovška'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() not in response.content
approved1.delete()
def test_search_events_search_in_wrong_location_again(db, client):
approved1 = ApprovedEventFactory.create(title='Event Arglebargle - Approved')
response = client.get(reverse('web.search_events'), {'q':'Celovška 1'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() not in response.content
approved1.delete()
def test_search_events_with_unicode_tag_in_search_query(db, client):
approved1 = ApprovedEventFactory.create(tags=[u"jabolčna čežana",u"José", "Django"])
response = client.get(reverse('web.search_events'), {'q':'čežana'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
approved1.delete()
def test_search_events_with_search_query_multiple_events_current_country_only(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI")
approved2 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="AT")
response = client.get(reverse('web.search_events'), {'q':'arglebargle'}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
assert approved2.get_absolute_url() not in response.content
map(lambda x: x.delete(), [approved1, approved2])
def test_search_with_audience(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI")
response = client.get(reverse('web.search_events'), {'audience':1}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
approved1.delete()
def test_search_with_audience_multiple_events(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI") #default audience 1
approved2 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI", audience=[1,2])
approved3 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="AT", audience=[1,2])
approved4 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI", audience=[3])
response = client.get(reverse('web.search_events'), {'audience':1}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
assert approved2.get_absolute_url() in response.content
assert approved3.get_absolute_url() not in response.content
assert approved4.get_absolute_url() not in response.content
map(lambda x: x.delete(), [approved1, approved2, approved3, approved4])
def test_search_with_theme(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI", theme=[2])
response = client.get(reverse('web.search_events'), {'theme':2}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
approved1.delete()
def test_search_with_theme_multiple_events(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI")
approved2 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI", theme=[2])
response = client.get(reverse('web.search_events'), {'theme':1}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
assert approved2.get_absolute_url() not in response.content
map(lambda x: x.delete(), [approved1, approved2])
def test_search_with_theme_multiple_events_all_countries(db, client):
approved1 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="SI")
approved2 = ApprovedEventFactory.create(title="Event Arglebargle - Approved", country="AT")
response = client.get(reverse('web.search_events'), {'country':'00', 'theme':1}, REMOTE_ADDR='93.103.53.11')
assert approved1.get_absolute_url() in response.content
assert approved2.get_absolute_url() in response.content
map(lambda x: x.delete(), [approved1, approved2]) | 40.864198 | 117 | 0.780967 | 867 | 6,620 | 5.755479 | 0.100346 | 0.05511 | 0.07014 | 0.12986 | 0.886373 | 0.872946 | 0.872946 | 0.838677 | 0.809419 | 0.778758 | 0 | 0.030494 | 0.08852 | 6,620 | 162 | 118 | 40.864198 | 0.796487 | 0.005891 | 0 | 0.555556 | 0 | 0 | 0.163703 | 0 | 0 | 0 | 0 | 0 | 0.252525 | 1 | 0.151515 | false | 0 | 0.030303 | 0 | 0.181818 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
8c83a703e1572a441ec0226107b12a4f9da2cf73 | 385 | py | Python | ontonotes_srl/__init__.py | Michael-Dyq/SRL-English | 2187b692515fb00c8f78428fa007266129d1a6b8 | [
"MIT"
] | null | null | null | ontonotes_srl/__init__.py | Michael-Dyq/SRL-English | 2187b692515fb00c8f78428fa007266129d1a6b8 | [
"MIT"
] | null | null | null | ontonotes_srl/__init__.py | Michael-Dyq/SRL-English | 2187b692515fb00c8f78428fa007266129d1a6b8 | [
"MIT"
] | null | null | null | # from ontonotes_srl.srl_bert import SrlBert
from ontonotes_srl.srl_bert_bilstm import SrlBertBilstm
# from ontonotes_srl.semantic_role_labeler import SemanticRoleLabelerPredictor
from ontonotes_srl.nn_semantic_role_labeler import NNSemanticRoleLabelerPredictor
# from ontonotes_srl.semantic_role_labeling import SrlReader
from ontonotes_srl.ontonotes_srl_nn_reader import SrlNNReader
| 55 | 81 | 0.906494 | 49 | 385 | 6.734694 | 0.367347 | 0.254545 | 0.290909 | 0.115152 | 0.309091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.07013 | 385 | 6 | 82 | 64.166667 | 0.921788 | 0.462338 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
8ca92064eb2a21a7494590adf50a94a408dfeeaa | 26 | py | Python | start.py | coloras/fire | 6523dff829dc8f719a69b679877da3ac0374da8b | [
"MIT"
] | null | null | null | start.py | coloras/fire | 6523dff829dc8f719a69b679877da3ac0374da8b | [
"MIT"
] | null | null | null | start.py | coloras/fire | 6523dff829dc8f719a69b679877da3ac0374da8b | [
"MIT"
] | null | null | null | print("Welcome to Fire!")
| 13 | 25 | 0.692308 | 4 | 26 | 4.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.115385 | 26 | 1 | 26 | 26 | 0.782609 | 0 | 0 | 0 | 0 | 0 | 0.615385 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
8cc4d8c56b92d63ebc300b1f292a5ee6168d1dda | 96 | py | Python | venv/lib/python3.8/site-packages/future/builtins/iterators.py | Retraces/UkraineBot | 3d5d7f8aaa58fa0cb8b98733b8808e5dfbdb8b71 | [
"MIT"
] | 2 | 2022-03-13T01:58:52.000Z | 2022-03-31T06:07:54.000Z | venv/lib/python3.8/site-packages/future/builtins/iterators.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | 19 | 2021-11-20T04:09:18.000Z | 2022-03-23T15:05:55.000Z | venv/lib/python3.8/site-packages/future/builtins/iterators.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | null | null | null | /home/runner/.cache/pip/pool/97/56/5a/c26db1f36a2a3ae186b4265113be848fdf2c3251d0c2ef5f64b2b946b0 | 96 | 96 | 0.895833 | 9 | 96 | 9.555556 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | 0 | 96 | 1 | 96 | 96 | 0.479167 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
8cd5415b9dee0360ddae877aab8280e1e12acff0 | 204 | py | Python | wsgitest/__init__.py | jonashaag/WSGITest | fb6f6981f8cc8192b2207a803c078a03bab31a84 | [
"BSD-2-Clause"
] | 1 | 2015-11-05T03:13:53.000Z | 2015-11-05T03:13:53.000Z | wsgitest/__init__.py | jonashaag/WSGITest | fb6f6981f8cc8192b2207a803c078a03bab31a84 | [
"BSD-2-Clause"
] | null | null | null | wsgitest/__init__.py | jonashaag/WSGITest | fb6f6981f8cc8192b2207a803c078a03bab31a84 | [
"BSD-2-Clause"
] | null | null | null | from os import pardir
from os.path import abspath, join, dirname, realpath
DEFAULT_TESTS_DIR = abspath(join((dirname(realpath(__file__))), pardir, 'tests'))
del pardir, abspath, join, dirname, realpath
| 29.142857 | 81 | 0.769608 | 28 | 204 | 5.392857 | 0.5 | 0.218543 | 0.357616 | 0.516556 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 204 | 6 | 82 | 34 | 0.838889 | 0 | 0 | 0 | 0 | 0 | 0.02451 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 6 |
8ce3ed60ccc6666448aa552898574f6dad08b387 | 2,156 | py | Python | data/data_process.py | vmeta42/metaai | 7800549f34bc9c041a07bddfb8d4c6e72248961c | [
"Apache-2.0"
] | null | null | null | data/data_process.py | vmeta42/metaai | 7800549f34bc9c041a07bddfb8d4c6e72248961c | [
"Apache-2.0"
] | null | null | null | data/data_process.py | vmeta42/metaai | 7800549f34bc9c041a07bddfb8d4c6e72248961c | [
"Apache-2.0"
] | null | null | null | import os
import random
import shutil
def split_train_test(data_path):
battery_room_dirs = os.listdir(data_path)
for battery_room_dir in battery_room_dirs:
if battery_room_dir.split('-')[0] == '12':
battery_dirs = os.listdir(os.path.join(data_path, battery_room_dir))
random.shuffle(battery_dirs)
n_sample = len(battery_dirs)
ratio = int(n_sample*0.8)
train_battery_dirs = battery_dirs[:ratio]
test_battery_dirs = battery_dirs[ratio:]
for train_battery_dir in train_battery_dirs:
train_battery = os.path.join(data_path, battery_room_dir, train_battery_dir)
shutil.copyfile(train_battery,
os.path.join('.', 'm6_train', train_battery_dir.split('.')[0]+'_' + battery_room_dir.split('-')[1]+'.csv'))
for test_battery_dir in test_battery_dirs:
test_battery = os.path.join(data_path, battery_room_dir, test_battery_dir)
shutil.copyfile(test_battery,
os.path.join('.', 'm6_test', test_battery_dir.split('.')[0]+'_' + battery_room_dir.split('-')[1]+'.csv'))
else:
battery_dirs = os.listdir(os.path.join(data_path, battery_room_dir))
random.shuffle(battery_dirs)
n_sample = len(battery_dirs)
ratio = int(n_sample * 0.8)
train_battery_dirs = battery_dirs[:ratio]
test_battery_dirs = battery_dirs[ratio:]
for train_battery_dir in train_battery_dirs:
train_battery = os.path.join(data_path, battery_room_dir, train_battery_dir)
shutil.copyfile(train_battery, os.path.join('.', 'm6_train', train_battery_dir))
for test_battery_dir in test_battery_dirs:
test_battery = os.path.join(data_path, battery_room_dir, test_battery_dir)
shutil.copyfile(test_battery, os.path.join('.', 'm6_test', test_battery_dir))
if __name__ == '__main__':
data_path = os.path.join('.', 'M6_v5')
split_train_test(data_path)
| 46.869565 | 140 | 0.616883 | 276 | 2,156 | 4.402174 | 0.130435 | 0.162963 | 0.090535 | 0.111934 | 0.86749 | 0.831276 | 0.831276 | 0.831276 | 0.831276 | 0.831276 | 0 | 0.010856 | 0.273655 | 2,156 | 45 | 141 | 47.911111 | 0.765006 | 0 | 0 | 0.540541 | 0 | 0 | 0.03082 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.027027 | false | 0 | 0.081081 | 0 | 0.108108 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
5076f5aa0d32849a06d88617c635dfd71a8771c7 | 94 | py | Python | app/controller/controller.py | Shady2320/dbms-project | 95e85d77f3624299a4d1fb6de19a6ce8249c7b0d | [
"MIT"
] | null | null | null | app/controller/controller.py | Shady2320/dbms-project | 95e85d77f3624299a4d1fb6de19a6ce8249c7b0d | [
"MIT"
] | null | null | null | app/controller/controller.py | Shady2320/dbms-project | 95e85d77f3624299a4d1fb6de19a6ce8249c7b0d | [
"MIT"
] | 1 | 2022-03-20T04:03:43.000Z | 2022-03-20T04:03:43.000Z | from flask import Blueprint
controller_blueprint = Blueprint('controller_blueprint',__name__) | 31.333333 | 65 | 0.861702 | 10 | 94 | 7.5 | 0.6 | 0.506667 | 0.746667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.074468 | 94 | 3 | 65 | 31.333333 | 0.862069 | 0 | 0 | 0 | 0 | 0 | 0.210526 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 1 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 1 | 0 | 6 |
507cd5e9607dddd8d3500252b6c5af5f4dae8657 | 123 | py | Python | tests/condition/test_true.py | LeeeeT/valtypes | 0c5df3cbab296bf9ca34544604fbb9496a41e01a | [
"MIT"
] | 3 | 2022-02-22T12:59:59.000Z | 2022-03-10T14:12:25.000Z | tests/condition/test_true.py | LeeeeT/valtypes | 0c5df3cbab296bf9ca34544604fbb9496a41e01a | [
"MIT"
] | 3 | 2022-03-08T13:33:38.000Z | 2022-03-25T03:31:56.000Z | tests/condition/test_true.py | LeeeeT/valtypes | 0c5df3cbab296bf9ca34544604fbb9496a41e01a | [
"MIT"
] | null | null | null | from valtypes.condition import true
def test() -> None:
"""
It always returns True
"""
assert true(...)
| 12.3 | 35 | 0.577236 | 14 | 123 | 5.071429 | 0.857143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.284553 | 123 | 9 | 36 | 13.666667 | 0.806818 | 0.178862 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
50b881e5ba62f1482a9efc5dfda95af8af342a24 | 21 | py | Python | rgn/__init__.py | RogerZhangsc/Porto-Seguros-Safe-Driver-Prediction | 0346539945486908096070dc14fe6225c16a4bd7 | [
"MIT"
] | 1 | 2020-10-20T14:26:33.000Z | 2020-10-20T14:26:33.000Z | rgn/__init__.py | RogerZhangsc/Porto-Seguros-Safe-Driver-Prediction | 0346539945486908096070dc14fe6225c16a4bd7 | [
"MIT"
] | null | null | null | rgn/__init__.py | RogerZhangsc/Porto-Seguros-Safe-Driver-Prediction | 0346539945486908096070dc14fe6225c16a4bd7 | [
"MIT"
] | null | null | null | from .rgn import RGN
| 10.5 | 20 | 0.761905 | 4 | 21 | 4 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | 21 | 1 | 21 | 21 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
50c0b2bb2dd5bbc954d50fe66d17bab6759638d3 | 28 | py | Python | tests/python/class_init.py | jacereda/py2nim | 56fc2699d31241c60bed726f59efea4bf46be238 | [
"MIT"
] | 10 | 2020-03-10T12:01:01.000Z | 2021-05-23T19:47:06.000Z | tests/python/class_init.py | jacereda/py2nim | 56fc2699d31241c60bed726f59efea4bf46be238 | [
"MIT"
] | null | null | null | tests/python/class_init.py | jacereda/py2nim | 56fc2699d31241c60bed726f59efea4bf46be238 | [
"MIT"
] | 1 | 2020-07-17T11:20:56.000Z | 2020-07-17T11:20:56.000Z | class A:
a = 2
a = A()
| 5.6 | 9 | 0.357143 | 6 | 28 | 1.666667 | 0.5 | 0.4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.066667 | 0.464286 | 28 | 4 | 10 | 7 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0.666667 | 0 | 1 | 1 | 1 | 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 | 1 | 0 | 0 | 6 |
50c7d485b0ccc46fae70ad8187f6d6e813206973 | 35 | py | Python | Reacher-PyBullet/ddpg.py | hyunjun529/Learn-OpenAI-GYM | 51e1f3dc4cdfa7582690fc8338918aeb9671f4e3 | [
"MIT"
] | null | null | null | Reacher-PyBullet/ddpg.py | hyunjun529/Learn-OpenAI-GYM | 51e1f3dc4cdfa7582690fc8338918aeb9671f4e3 | [
"MIT"
] | null | null | null | Reacher-PyBullet/ddpg.py | hyunjun529/Learn-OpenAI-GYM | 51e1f3dc4cdfa7582690fc8338918aeb9671f4e3 | [
"MIT"
] | null | null | null | import gym
import tensorflow as tf
| 11.666667 | 23 | 0.828571 | 6 | 35 | 4.833333 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.171429 | 35 | 2 | 24 | 17.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
0fa51a6c0d6ec2cc00596a7974c94d860d373059 | 143 | py | Python | ezai_util/__init__.py | armando-fandango/ezai_util | 261a0b752a66ac0357e6576b7113ac8e2fff5396 | [
"Apache-2.0"
] | null | null | null | ezai_util/__init__.py | armando-fandango/ezai_util | 261a0b752a66ac0357e6576b7113ac8e2fff5396 | [
"Apache-2.0"
] | null | null | null | ezai_util/__init__.py | armando-fandango/ezai_util | 261a0b752a66ac0357e6576b7113ac8e2fff5396 | [
"Apache-2.0"
] | null | null | null | from . import pytorch_util
from . import log_util
from .dict import DictObj
from .dict import ObjDict
from .resources import ResourceCounter
| 17.875 | 38 | 0.811189 | 20 | 143 | 5.7 | 0.5 | 0.175439 | 0.245614 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | 143 | 7 | 39 | 20.428571 | 0.942149 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ba17e3d88d6e7135a01a455d8f151079f7611e30 | 94 | py | Python | pymenu/__init__.py | feftio/pymenu | 846b916ce55548c53f43f3642d69e6c64fd9d774 | [
"MIT"
] | null | null | null | pymenu/__init__.py | feftio/pymenu | 846b916ce55548c53f43f3642d69e6c64fd9d774 | [
"MIT"
] | null | null | null | pymenu/__init__.py | feftio/pymenu | 846b916ce55548c53f43f3642d69e6c64fd9d774 | [
"MIT"
] | null | null | null | from pymenu.main import PyMenu
from pymenu import page as page
# __all__ = ['PyMenu', 'page'] | 23.5 | 31 | 0.734043 | 14 | 94 | 4.642857 | 0.5 | 0.307692 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.159574 | 94 | 4 | 32 | 23.5 | 0.822785 | 0.297872 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ba25d3e297db2ea8c9763c35d8dfaf27b1c20056 | 156 | py | Python | exwaypyramid/core/routes.py | ivancrneto/exway-pyramid | 2700b7ff19aba2d6c29ab552126128857afda0ab | [
"MIT"
] | null | null | null | exwaypyramid/core/routes.py | ivancrneto/exway-pyramid | 2700b7ff19aba2d6c29ab552126128857afda0ab | [
"MIT"
] | null | null | null | exwaypyramid/core/routes.py | ivancrneto/exway-pyramid | 2700b7ff19aba2d6c29ab552126128857afda0ab | [
"MIT"
] | null | null | null | def includeme(config):
config.add_route('core:views.home', '/')
config.add_route('core:views.expenses', '/expenses')
config.scan('core.views')
| 26 | 56 | 0.673077 | 20 | 156 | 5.15 | 0.5 | 0.262136 | 0.271845 | 0.349515 | 0.446602 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.128205 | 156 | 5 | 57 | 31.2 | 0.757353 | 0 | 0 | 0 | 0 | 0 | 0.346154 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
e85ce1f1977fae238dac3a1ac1d187c4c2f23c4e | 23,445 | py | Python | tccli/services/iotcloud/iotcloud_client.py | ivandksun/tencentcloud-cli-intl-en | 41b84e339918961b8bc92f7498e56347d21e16d3 | [
"Apache-2.0"
] | null | null | null | tccli/services/iotcloud/iotcloud_client.py | ivandksun/tencentcloud-cli-intl-en | 41b84e339918961b8bc92f7498e56347d21e16d3 | [
"Apache-2.0"
] | null | null | null | tccli/services/iotcloud/iotcloud_client.py | ivandksun/tencentcloud-cli-intl-en | 41b84e339918961b8bc92f7498e56347d21e16d3 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import os
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError
from tencentcloud.common import credential
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.iotcloud.v20210408 import iotcloud_client as iotcloud_client_v20210408
from tencentcloud.iotcloud.v20210408 import models as models_v20210408
def doUpdateDeviceLogLevel(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.UpdateDeviceLogLevelRequest()
model.from_json_string(json.dumps(args))
rsp = client.UpdateDeviceLogLevel(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDeleteProduct(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DeleteProductRequest()
model.from_json_string(json.dumps(args))
rsp = client.DeleteProduct(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDeleteDevice(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DeleteDeviceRequest()
model.from_json_string(json.dumps(args))
rsp = client.DeleteDevice(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doCreateDevice(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.CreateDeviceRequest()
model.from_json_string(json.dumps(args))
rsp = client.CreateDevice(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDeletePrivateCA(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DeletePrivateCARequest()
model.from_json_string(json.dumps(args))
rsp = client.DeletePrivateCA(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribePrivateCA(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribePrivateCARequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribePrivateCA(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doCreatePrivateCA(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.CreatePrivateCARequest()
model.from_json_string(json.dumps(args))
rsp = client.CreatePrivateCA(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribeDevices(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribeDevicesRequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribeDevices(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doSetProductsForbiddenStatus(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.SetProductsForbiddenStatusRequest()
model.from_json_string(json.dumps(args))
rsp = client.SetProductsForbiddenStatus(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribePrivateCAs(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribePrivateCAsRequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribePrivateCAs(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribeProductCA(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribeProductCARequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribeProductCA(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribeDevice(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribeDeviceRequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribeDevice(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doUpdateDevicesEnableState(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.UpdateDevicesEnableStateRequest()
model.from_json_string(json.dumps(args))
rsp = client.UpdateDevicesEnableState(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribePrivateCABindedProducts(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribePrivateCABindedProductsRequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribePrivateCABindedProducts(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doDescribeProduct(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.DescribeProductRequest()
model.from_json_string(json.dumps(args))
rsp = client.DescribeProduct(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
def doUpdatePrivateCA(args, parsed_globals):
g_param = parse_global_arg(parsed_globals)
cred = credential.Credential(
g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey], g_param[OptionsDefine.Token]
)
http_profile = HttpProfile(
reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
reqMethod="POST",
endpoint=g_param[OptionsDefine.Endpoint]
)
profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
client = mod.IotcloudClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.UpdatePrivateCARequest()
model.from_json_string(json.dumps(args))
rsp = client.UpdatePrivateCA(model)
result = rsp.to_json_string()
try:
json_obj = json.loads(result)
except TypeError as e:
json_obj = json.loads(result.decode('utf-8')) # python3.3
FormatOutput.output("action", json_obj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter])
CLIENT_MAP = {
"v20210408": iotcloud_client_v20210408,
}
MODELS_MAP = {
"v20210408": models_v20210408,
}
ACTION_MAP = {
"UpdateDeviceLogLevel": doUpdateDeviceLogLevel,
"DeleteProduct": doDeleteProduct,
"DeleteDevice": doDeleteDevice,
"CreateDevice": doCreateDevice,
"DeletePrivateCA": doDeletePrivateCA,
"DescribePrivateCA": doDescribePrivateCA,
"CreatePrivateCA": doCreatePrivateCA,
"DescribeDevices": doDescribeDevices,
"SetProductsForbiddenStatus": doSetProductsForbiddenStatus,
"DescribePrivateCAs": doDescribePrivateCAs,
"DescribeProductCA": doDescribeProductCA,
"DescribeDevice": doDescribeDevice,
"UpdateDevicesEnableState": doUpdateDevicesEnableState,
"DescribePrivateCABindedProducts": doDescribePrivateCABindedProducts,
"DescribeProduct": doDescribeProduct,
"UpdatePrivateCA": doUpdatePrivateCA,
}
AVAILABLE_VERSION_LIST = [
"v20210408",
]
def action_caller():
return ACTION_MAP
def parse_global_arg(parsed_globals):
g_param = parsed_globals
is_exist_profile = True
if not parsed_globals["profile"]:
is_exist_profile = False
g_param["profile"] = "default"
configure_path = os.path.join(os.path.expanduser("~"), ".tccli")
is_conf_exist, conf_path = Utils.file_existed(configure_path, g_param["profile"] + ".configure")
is_cred_exist, cred_path = Utils.file_existed(configure_path, g_param["profile"] + ".credential")
conf = {}
cred = {}
if is_conf_exist:
conf = Utils.load_json_msg(conf_path)
if is_cred_exist:
cred = Utils.load_json_msg(cred_path)
if not (isinstance(conf, dict) and isinstance(cred, dict)):
raise ConfigurationError(
"file: %s or %s is not json format"
% (g_param["profile"] + ".configure", g_param["profile"] + ".credential"))
if OptionsDefine.Token not in cred:
cred[OptionsDefine.Token] = None
if not is_exist_profile:
if os.environ.get(OptionsDefine.ENV_SECRET_ID) and os.environ.get(OptionsDefine.ENV_SECRET_KEY):
cred[OptionsDefine.SecretId] = os.environ.get(OptionsDefine.ENV_SECRET_ID)
cred[OptionsDefine.SecretKey] = os.environ.get(OptionsDefine.ENV_SECRET_KEY)
cred[OptionsDefine.Token] = os.environ.get(OptionsDefine.ENV_TOKEN)
if os.environ.get(OptionsDefine.ENV_REGION):
conf[OptionsDefine.Region] = os.environ.get(OptionsDefine.ENV_REGION)
for param in g_param.keys():
if g_param[param] is None:
if param in [OptionsDefine.SecretKey, OptionsDefine.SecretId, OptionsDefine.Token]:
if param in cred:
g_param[param] = cred[param]
else:
raise ConfigurationError("%s is invalid" % param)
elif param in [OptionsDefine.Region, OptionsDefine.Output]:
if param in conf:
g_param[param] = conf[param]
else:
raise ConfigurationError("%s is invalid" % param)
try:
if g_param[OptionsDefine.ServiceVersion]:
g_param[OptionsDefine.Version] = "v" + g_param[OptionsDefine.ServiceVersion].replace('-', '')
else:
version = conf["iotcloud"][OptionsDefine.Version]
g_param[OptionsDefine.Version] = "v" + version.replace('-', '')
if g_param[OptionsDefine.Endpoint] is None:
g_param[OptionsDefine.Endpoint] = conf["iotcloud"][OptionsDefine.Endpoint]
except Exception as err:
raise ConfigurationError("config file:%s error, %s" % (conf_path, str(err)))
if g_param[OptionsDefine.Version] not in AVAILABLE_VERSION_LIST:
raise Exception("available versions: %s" % " ".join(AVAILABLE_VERSION_LIST))
return g_param
| 42.243243 | 105 | 0.723182 | 2,669 | 23,445 | 6.115774 | 0.064069 | 0.077192 | 0.213012 | 0.05575 | 0.79581 | 0.784353 | 0.779942 | 0.775531 | 0.769773 | 0.717331 | 0 | 0.010326 | 0.169759 | 23,445 | 554 | 106 | 42.319495 | 0.828256 | 0.00772 | 0 | 0.648536 | 0 | 0 | 0.04345 | 0.003485 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037657 | false | 0 | 0.025105 | 0.002092 | 0.066946 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 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 | 6 |
e860c29240ca90ed0db52c0a1e8bd9508b2fc597 | 2,702 | py | Python | Petal-Length.py | darrenkeenan/Iris-Flower-Data-Set | 7c6e58d7fb2da04f3abc420b0e7bcd4330c8052e | [
"Apache-2.0"
] | null | null | null | Petal-Length.py | darrenkeenan/Iris-Flower-Data-Set | 7c6e58d7fb2da04f3abc420b0e7bcd4330c8052e | [
"Apache-2.0"
] | null | null | null | Petal-Length.py | darrenkeenan/Iris-Flower-Data-Set | 7c6e58d7fb2da04f3abc420b0e7bcd4330c8052e | [
"Apache-2.0"
] | null | null | null | # Calculating min & max petal length per species of iris data set
# Darren Keenan - finalized 2018-04-29
columnname = "Petal Length", "Species/Class" # naming two columns
print(columnname) # printing named columns
with open("data/iris.csv") as iris: # opening file iris.csv saved on computer
for cmandname in iris:
i = cmandname.split(",") # aligning data
print(i[2],i[4]) # listing column 3 in file, petal length & column 5, spcies/class of iris
listset = (1.4,1.4,1.3,1.5,1.4,1.7,1.4,1.5,1.4,1.5,1.5,1.6,1.4,1.1,1.2,1.5,1.3,1.4,1.7,1.5,1.7,1.5,1,1.7,1.9,1.6,1.6,1.5,1.4,1.6,1.6,1.5,1.5,1.4,1.5,1.2,1.3,1.5,1.3,1.5,1.3,1.3,1.3,1.6,1.9,1.4,1.6,1.4,1.5,1.4)
print("Min Iris-Setosa Petal Length is:", min(listset)) # printing minimum value of listset
# Min Iris-Setosa Petal Length is: 1
listset = (1.4,1.4,1.3,1.5,1.4,1.7,1.4,1.5,1.4,1.5,1.5,1.6,1.4,1.1,1.2,1.5,1.3,1.4,1.7,1.5,1.7,1.5,1,1.7,1.9,1.6,1.6,1.5,1.4,1.6,1.6,1.5,1.5,1.4,1.5,1.2,1.3,1.5,1.3,1.5,1.3,1.3,1.3,1.6,1.9,1.4,1.6,1.4,1.5,1.4)
print("Max Iris-Setosa Petal Length is:", max(listset)) # printing maximum value of listset
# Max Iris-Setosa Petal Length is: 1.9
listset = (4.7,4.5,4.9,4,4.6,4.5,4.7,3.3,4.6,3.9,3.5,4.2,4,4.7,3.6,4.4,4.5,4.1,4.5,3.9,4.8,4,4.9,4.7,4.3,4.4,4.8,5,4.5,3.5,3.8,3.7,3.9,5.1,4.5,4.5,4.7,4.4,4.1,4,4.4,4.6,4,3.3,4.2,4.2,4.2,4.3,3,4.1)
print("Min Iris-Versicolor Petal Length is:", min(listset)) # printing minimum value of listset
# Min Iris-Versicolor Petal Length is: 3
listset = (4.7,4.5,4.9,4,4.6,4.5,4.7,3.3,4.6,3.9,3.5,4.2,4,4.7,3.6,4.4,4.5,4.1,4.5,3.9,4.8,4,4.9,4.7,4.3,4.4,4.8,5,4.5,3.5,3.8,3.7,3.9,5.1,4.5,4.5,4.7,4.4,4.1,4,4.4,4.6,4,3.3,4.2,4.2,4.2,4.3,3,4.1)
print("Max Iris-Versicolor Petal Length is:", max(listset)) # printing maximum value of listset
# Max Iris-Versicolor Petal Length is: 5.1
listset = (6,5.1,5.9,5.6,5.8,6.6,4.5,6.3,5.8,6.1,5.1,5.3,5.5,5,5.1,5.3,5.5,6.7,6.9,5,5.7,4.9,6.7,4.9,5.7,6,4.8,4.9,5.6,5.8,6.1,6.4,5.6,5.1,5.6,6.1,5.6,5.5,4.8,5.4,5.6,5.1,5.1,5.9,5.7,5.2,5,5.2,5.4,5.1)
print("Min Iris-Virginica Petal Length is:", min(listset)) # printing minimum value of listset
# Min Iris-Virginica Petal Length is: 4.5
listset = (6,5.1,5.9,5.6,5.8,6.6,4.5,6.3,5.8,6.1,5.1,5.3,5.5,5,5.1,5.3,5.5,6.7,6.9,5,5.7,4.9,6.7,4.9,5.7,6,4.8,4.9,5.6,5.8,6.1,6.4,5.6,5.1,5.6,6.1,5.6,5.5,4.8,5.4,5.6,5.1,5.1,5.9,5.7,5.2,5,5.2,5.4,5.1)
print("Max Iris-Virginica Petal Length is:", max(listset)) # printing maximum value of listset
# Max Iris-Virginica Petal Length is: 6.9
| 77.2 | 209 | 0.57772 | 781 | 2,702 | 1.99872 | 0.076825 | 0.057655 | 0.061499 | 0.025625 | 0.782832 | 0.782832 | 0.640615 | 0.640615 | 0.640615 | 0.640615 | 0 | 0.261863 | 0.157661 | 2,702 | 34 | 210 | 79.470588 | 0.423989 | 0.260548 | 0 | 0.333333 | 0 | 0 | 0.123862 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.444444 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 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 | 1 | 0 | 6 |
e87313a8a6f7556299843beb90d1a43721eb0c76 | 37 | py | Python | climodels/__init__.py | wy2136/wython | 0eaa9db335d57052806ae956afe6a34705407628 | [
"MIT"
] | 1 | 2022-03-21T21:24:40.000Z | 2022-03-21T21:24:40.000Z | climodels/__init__.py | wy2136/wython | 0eaa9db335d57052806ae956afe6a34705407628 | [
"MIT"
] | null | null | null | climodels/__init__.py | wy2136/wython | 0eaa9db335d57052806ae956afe6a34705407628 | [
"MIT"
] | null | null | null | from .advection1d import Advection1D
| 18.5 | 36 | 0.864865 | 4 | 37 | 8 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.060606 | 0.108108 | 37 | 1 | 37 | 37 | 0.909091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
e87323ca3cb9b56ea0b7060d28b09c526594c592 | 136 | py | Python | tests/settings.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/settings.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/settings.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 os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
CRAFT_CFG = {"token": os.environ.get("CRAFT_TOKEN")}
| 19.428571 | 52 | 0.772059 | 21 | 136 | 4.714286 | 0.52381 | 0.20202 | 0.282828 | 0.40404 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.102941 | 136 | 6 | 53 | 22.666667 | 0.811475 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 6 |
e87545f29b01b36404b8c119568a0c4e8c11a506 | 2,268 | py | Python | tests/datasets/test_conll.py | ChristophAlt/pytorch-quasar | 7b957b1b4cba83677b415d752dcac6acf682f15b | [
"BSD-3-Clause"
] | 4 | 2018-10-02T20:20:26.000Z | 2019-07-26T12:57:26.000Z | tests/datasets/test_conll.py | ChristophAlt/pytorch-quasar | 7b957b1b4cba83677b415d752dcac6acf682f15b | [
"BSD-3-Clause"
] | null | null | null | tests/datasets/test_conll.py | ChristophAlt/pytorch-quasar | 7b957b1b4cba83677b415d752dcac6acf682f15b | [
"BSD-3-Clause"
] | null | null | null | import mock
from quasar.datasets import conll2003_dataset
from tests.datasets.utils import urlretrieve_side_effect
directory = 'tests/_test_data/conll'
@mock.patch("urllib.request.urlretrieve")
def test_conll2003_row(mock_urlretrieve):
mock_urlretrieve.side_effect = urlretrieve_side_effect
train = conll2003_dataset(directory=directory, train=True, check_files=['eng.train'])
assert len(train) > 0
assert train[0:2] == [{
'text': ['token', 'TOKEN', 'Token', 'token4321', 'token'],
'pos': ['NNP', ':', 'NNP', 'NNP', 'IN'],
'chunk': ['I-NP', 'O', 'I-NP', 'I-NP', 'I-PP'],
'entity': ['O', 'B-ORG', 'I-ORG', 'I-ORG', 'O']
}, {
'text': ['Token', 'token1234'],
'pos': ['NNP', 'CD'],
'chunk': ['I-NP', 'I-NP'],
'entity': ['I-LOC', 'O']
}
]
@mock.patch("urllib.request.urlretrieve")
def test_conll2003_tag_scheme(mock_urlretrieve):
mock_urlretrieve.side_effect = urlretrieve_side_effect
train = conll2003_dataset(directory=directory, train=True,
check_files=['eng.train'], tag_scheme='iob')
assert len(train) > 0
assert train[0:2] == [{
'text': ['token', 'TOKEN', 'Token', 'token4321', 'token'],
'pos': ['NNP', ':', 'NNP', 'NNP', 'IN'],
'chunk': ['I-NP', 'O', 'I-NP', 'I-NP', 'I-PP'],
'entity': ['O', 'B-ORG', 'I-ORG', 'I-ORG', 'O']
}, {
'text': ['Token', 'token1234'],
'pos': ['NNP', 'CD'],
'chunk': ['I-NP', 'I-NP'],
'entity': ['B-LOC', 'O']
}
]
train = conll2003_dataset(directory=directory, train=True,
check_files=['eng.train'], tag_scheme='iobes')
assert len(train) > 0
assert train[0:2] == [{
'text': ['token', 'TOKEN', 'Token', 'token4321', 'token'],
'pos': ['NNP', ':', 'NNP', 'NNP', 'IN'],
'chunk': ['I-NP', 'O', 'I-NP', 'I-NP', 'I-PP'],
'entity': ['O', 'B-ORG', 'I-ORG', 'E-ORG', 'O']
}, {
'text': ['Token', 'token1234'],
'pos': ['NNP', 'CD'],
'chunk': ['I-NP', 'I-NP'],
'entity': ['S-LOC', 'O']
}
]
| 33.850746 | 89 | 0.481922 | 256 | 2,268 | 4.160156 | 0.207031 | 0.042254 | 0.033803 | 0.033803 | 0.847887 | 0.847887 | 0.847887 | 0.847887 | 0.755869 | 0.755869 | 0 | 0.035229 | 0.286596 | 2,268 | 66 | 90 | 34.363636 | 0.622991 | 0 | 0 | 0.648148 | 0 | 0 | 0.238536 | 0.032628 | 0 | 0 | 0 | 0 | 0.111111 | 1 | 0.037037 | false | 0 | 0.055556 | 0 | 0.092593 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
e885b941d2e12589c5cfdf07bafe99dbfb22dc19 | 366 | py | Python | conversion_encoding_bytes_chr_funcs/get_preferred_encoding.py | SecTraversl/Toolbox_Python_3.8 | 0ad1d92d3a12225ea60e4eef3f263aecfffd1b65 | [
"MIT"
] | null | null | null | conversion_encoding_bytes_chr_funcs/get_preferred_encoding.py | SecTraversl/Toolbox_Python_3.8 | 0ad1d92d3a12225ea60e4eef3f263aecfffd1b65 | [
"MIT"
] | null | null | null | conversion_encoding_bytes_chr_funcs/get_preferred_encoding.py | SecTraversl/Toolbox_Python_3.8 | 0ad1d92d3a12225ea60e4eef3f263aecfffd1b65 | [
"MIT"
] | null | null | null | # %%
#######################################
def get_preferred_encoding():
"""Shows the preferred encoding of the local machine (often it is "UTF-8").
Examples:
>>> get_preferred_encoding()\n
'UTF-8'
References:
https://realpython.com/python-encodings-guide/
"""
import locale
return locale.getpreferredencoding()
| 21.529412 | 79 | 0.565574 | 36 | 366 | 5.638889 | 0.75 | 0.251232 | 0.197044 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006993 | 0.218579 | 366 | 16 | 80 | 22.875 | 0.702797 | 0.538251 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 1 | 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 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
e89c6214aca3fce95509b09a61ffa30b7b65f011 | 109 | py | Python | imlist.py | ashishchopra778/Matching-Geotagged-Images | efa7f5d7e5856ef632c967e4091eb66613aabcd3 | [
"MIT"
] | null | null | null | imlist.py | ashishchopra778/Matching-Geotagged-Images | efa7f5d7e5856ef632c967e4091eb66613aabcd3 | [
"MIT"
] | 1 | 2016-08-21T15:57:20.000Z | 2016-08-24T14:17:58.000Z | imlist.py | ashishchopra778/Matching-Geotagged-Images | efa7f5d7e5856ef632c967e4091eb66613aabcd3 | [
"MIT"
] | null | null | null | import os
def get_imlist(path):
return [os.path.join(f) for f in os.listdir(path) if f.endswith('.jpg')]
| 18.166667 | 73 | 0.688073 | 21 | 109 | 3.52381 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.146789 | 109 | 5 | 74 | 21.8 | 0.795699 | 0 | 0 | 0 | 0 | 0 | 0.036697 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.333333 | 0.333333 | 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 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
e8a773070953ca0e9f014d42362924b6bf3a7f94 | 6,821 | py | Python | loldib/getratings/models/NA/na_katarina/na_katarina_mid.py | koliupy/loldib | c9ab94deb07213cdc42b5a7c26467cdafaf81b7f | [
"Apache-2.0"
] | null | null | null | loldib/getratings/models/NA/na_katarina/na_katarina_mid.py | koliupy/loldib | c9ab94deb07213cdc42b5a7c26467cdafaf81b7f | [
"Apache-2.0"
] | null | null | null | loldib/getratings/models/NA/na_katarina/na_katarina_mid.py | koliupy/loldib | c9ab94deb07213cdc42b5a7c26467cdafaf81b7f | [
"Apache-2.0"
] | null | null | null | from getratings.models.ratings import Ratings
class NA_Katarina_Mid_Aatrox(Ratings):
pass
class NA_Katarina_Mid_Ahri(Ratings):
pass
class NA_Katarina_Mid_Akali(Ratings):
pass
class NA_Katarina_Mid_Alistar(Ratings):
pass
class NA_Katarina_Mid_Amumu(Ratings):
pass
class NA_Katarina_Mid_Anivia(Ratings):
pass
class NA_Katarina_Mid_Annie(Ratings):
pass
class NA_Katarina_Mid_Ashe(Ratings):
pass
class NA_Katarina_Mid_AurelionSol(Ratings):
pass
class NA_Katarina_Mid_Azir(Ratings):
pass
class NA_Katarina_Mid_Bard(Ratings):
pass
class NA_Katarina_Mid_Blitzcrank(Ratings):
pass
class NA_Katarina_Mid_Brand(Ratings):
pass
class NA_Katarina_Mid_Braum(Ratings):
pass
class NA_Katarina_Mid_Caitlyn(Ratings):
pass
class NA_Katarina_Mid_Camille(Ratings):
pass
class NA_Katarina_Mid_Cassiopeia(Ratings):
pass
class NA_Katarina_Mid_Chogath(Ratings):
pass
class NA_Katarina_Mid_Corki(Ratings):
pass
class NA_Katarina_Mid_Darius(Ratings):
pass
class NA_Katarina_Mid_Diana(Ratings):
pass
class NA_Katarina_Mid_Draven(Ratings):
pass
class NA_Katarina_Mid_DrMundo(Ratings):
pass
class NA_Katarina_Mid_Ekko(Ratings):
pass
class NA_Katarina_Mid_Elise(Ratings):
pass
class NA_Katarina_Mid_Evelynn(Ratings):
pass
class NA_Katarina_Mid_Ezreal(Ratings):
pass
class NA_Katarina_Mid_Fiddlesticks(Ratings):
pass
class NA_Katarina_Mid_Fiora(Ratings):
pass
class NA_Katarina_Mid_Fizz(Ratings):
pass
class NA_Katarina_Mid_Galio(Ratings):
pass
class NA_Katarina_Mid_Gangplank(Ratings):
pass
class NA_Katarina_Mid_Garen(Ratings):
pass
class NA_Katarina_Mid_Gnar(Ratings):
pass
class NA_Katarina_Mid_Gragas(Ratings):
pass
class NA_Katarina_Mid_Graves(Ratings):
pass
class NA_Katarina_Mid_Hecarim(Ratings):
pass
class NA_Katarina_Mid_Heimerdinger(Ratings):
pass
class NA_Katarina_Mid_Illaoi(Ratings):
pass
class NA_Katarina_Mid_Irelia(Ratings):
pass
class NA_Katarina_Mid_Ivern(Ratings):
pass
class NA_Katarina_Mid_Janna(Ratings):
pass
class NA_Katarina_Mid_JarvanIV(Ratings):
pass
class NA_Katarina_Mid_Jax(Ratings):
pass
class NA_Katarina_Mid_Jayce(Ratings):
pass
class NA_Katarina_Mid_Jhin(Ratings):
pass
class NA_Katarina_Mid_Jinx(Ratings):
pass
class NA_Katarina_Mid_Kalista(Ratings):
pass
class NA_Katarina_Mid_Karma(Ratings):
pass
class NA_Katarina_Mid_Karthus(Ratings):
pass
class NA_Katarina_Mid_Kassadin(Ratings):
pass
class NA_Katarina_Mid_Katarina(Ratings):
pass
class NA_Katarina_Mid_Kayle(Ratings):
pass
class NA_Katarina_Mid_Kayn(Ratings):
pass
class NA_Katarina_Mid_Kennen(Ratings):
pass
class NA_Katarina_Mid_Khazix(Ratings):
pass
class NA_Katarina_Mid_Kindred(Ratings):
pass
class NA_Katarina_Mid_Kled(Ratings):
pass
class NA_Katarina_Mid_KogMaw(Ratings):
pass
class NA_Katarina_Mid_Leblanc(Ratings):
pass
class NA_Katarina_Mid_LeeSin(Ratings):
pass
class NA_Katarina_Mid_Leona(Ratings):
pass
class NA_Katarina_Mid_Lissandra(Ratings):
pass
class NA_Katarina_Mid_Lucian(Ratings):
pass
class NA_Katarina_Mid_Lulu(Ratings):
pass
class NA_Katarina_Mid_Lux(Ratings):
pass
class NA_Katarina_Mid_Malphite(Ratings):
pass
class NA_Katarina_Mid_Malzahar(Ratings):
pass
class NA_Katarina_Mid_Maokai(Ratings):
pass
class NA_Katarina_Mid_MasterYi(Ratings):
pass
class NA_Katarina_Mid_MissFortune(Ratings):
pass
class NA_Katarina_Mid_MonkeyKing(Ratings):
pass
class NA_Katarina_Mid_Mordekaiser(Ratings):
pass
class NA_Katarina_Mid_Morgana(Ratings):
pass
class NA_Katarina_Mid_Nami(Ratings):
pass
class NA_Katarina_Mid_Nasus(Ratings):
pass
class NA_Katarina_Mid_Nautilus(Ratings):
pass
class NA_Katarina_Mid_Nidalee(Ratings):
pass
class NA_Katarina_Mid_Nocturne(Ratings):
pass
class NA_Katarina_Mid_Nunu(Ratings):
pass
class NA_Katarina_Mid_Olaf(Ratings):
pass
class NA_Katarina_Mid_Orianna(Ratings):
pass
class NA_Katarina_Mid_Ornn(Ratings):
pass
class NA_Katarina_Mid_Pantheon(Ratings):
pass
class NA_Katarina_Mid_Poppy(Ratings):
pass
class NA_Katarina_Mid_Quinn(Ratings):
pass
class NA_Katarina_Mid_Rakan(Ratings):
pass
class NA_Katarina_Mid_Rammus(Ratings):
pass
class NA_Katarina_Mid_RekSai(Ratings):
pass
class NA_Katarina_Mid_Renekton(Ratings):
pass
class NA_Katarina_Mid_Rengar(Ratings):
pass
class NA_Katarina_Mid_Riven(Ratings):
pass
class NA_Katarina_Mid_Rumble(Ratings):
pass
class NA_Katarina_Mid_Ryze(Ratings):
pass
class NA_Katarina_Mid_Sejuani(Ratings):
pass
class NA_Katarina_Mid_Shaco(Ratings):
pass
class NA_Katarina_Mid_Shen(Ratings):
pass
class NA_Katarina_Mid_Shyvana(Ratings):
pass
class NA_Katarina_Mid_Singed(Ratings):
pass
class NA_Katarina_Mid_Sion(Ratings):
pass
class NA_Katarina_Mid_Sivir(Ratings):
pass
class NA_Katarina_Mid_Skarner(Ratings):
pass
class NA_Katarina_Mid_Sona(Ratings):
pass
class NA_Katarina_Mid_Soraka(Ratings):
pass
class NA_Katarina_Mid_Swain(Ratings):
pass
class NA_Katarina_Mid_Syndra(Ratings):
pass
class NA_Katarina_Mid_TahmKench(Ratings):
pass
class NA_Katarina_Mid_Taliyah(Ratings):
pass
class NA_Katarina_Mid_Talon(Ratings):
pass
class NA_Katarina_Mid_Taric(Ratings):
pass
class NA_Katarina_Mid_Teemo(Ratings):
pass
class NA_Katarina_Mid_Thresh(Ratings):
pass
class NA_Katarina_Mid_Tristana(Ratings):
pass
class NA_Katarina_Mid_Trundle(Ratings):
pass
class NA_Katarina_Mid_Tryndamere(Ratings):
pass
class NA_Katarina_Mid_TwistedFate(Ratings):
pass
class NA_Katarina_Mid_Twitch(Ratings):
pass
class NA_Katarina_Mid_Udyr(Ratings):
pass
class NA_Katarina_Mid_Urgot(Ratings):
pass
class NA_Katarina_Mid_Varus(Ratings):
pass
class NA_Katarina_Mid_Vayne(Ratings):
pass
class NA_Katarina_Mid_Veigar(Ratings):
pass
class NA_Katarina_Mid_Velkoz(Ratings):
pass
class NA_Katarina_Mid_Vi(Ratings):
pass
class NA_Katarina_Mid_Viktor(Ratings):
pass
class NA_Katarina_Mid_Vladimir(Ratings):
pass
class NA_Katarina_Mid_Volibear(Ratings):
pass
class NA_Katarina_Mid_Warwick(Ratings):
pass
class NA_Katarina_Mid_Xayah(Ratings):
pass
class NA_Katarina_Mid_Xerath(Ratings):
pass
class NA_Katarina_Mid_XinZhao(Ratings):
pass
class NA_Katarina_Mid_Yasuo(Ratings):
pass
class NA_Katarina_Mid_Yorick(Ratings):
pass
class NA_Katarina_Mid_Zac(Ratings):
pass
class NA_Katarina_Mid_Zed(Ratings):
pass
class NA_Katarina_Mid_Ziggs(Ratings):
pass
class NA_Katarina_Mid_Zilean(Ratings):
pass
class NA_Katarina_Mid_Zyra(Ratings):
pass
| 16.357314 | 46 | 0.776133 | 972 | 6,821 | 5.020576 | 0.151235 | 0.197951 | 0.42418 | 0.509016 | 0.814139 | 0.814139 | 0 | 0 | 0 | 0 | 0 | 0 | 0.162879 | 6,821 | 416 | 47 | 16.396635 | 0.854641 | 0 | 0 | 0.498195 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.498195 | 0.00361 | 0 | 0.501805 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 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 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 6 |
e8afa8b6929be5a5fd0e641467f8bfdcf1faa38c | 27 | py | Python | rosstat/validators/control/parser/__init__.py | WoolenSweater/rosstat_flc | cfec24376b74f5e8c698ccfa664245842035417a | [
"MIT"
] | 148 | 2015-12-23T15:00:17.000Z | 2022-02-16T07:38:55.000Z | rosstat/validators/control/parser/__init__.py | WoolenSweater/rosstat_flc | cfec24376b74f5e8c698ccfa664245842035417a | [
"MIT"
] | 8 | 2016-01-06T17:35:52.000Z | 2020-06-10T09:51:53.000Z | rosstat/validators/control/parser/__init__.py | WoolenSweater/rosstat-flc | 4fc7b7aa8ac1413d0a8057b525a03b17b6a1af30 | [
"MIT"
] | 26 | 2016-01-04T10:33:46.000Z | 2020-12-07T18:29:00.000Z | from .parser import parser
| 13.5 | 26 | 0.814815 | 4 | 27 | 5.5 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.148148 | 27 | 1 | 27 | 27 | 0.956522 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
e8d388a274dbe59f12d00f4d0beacec11e06c7ec | 58 | py | Python | mylib/__init__.py | fKunstner/python-lib-template | ebb71f692efc9720552435d005a55cb9bdad4e2b | [
"MIT"
] | 2 | 2020-07-04T09:51:37.000Z | 2020-07-23T18:15:14.000Z | mylib/__init__.py | fKunstner/python-lib-template | ebb71f692efc9720552435d005a55cb9bdad4e2b | [
"MIT"
] | null | null | null | mylib/__init__.py | fKunstner/python-lib-template | ebb71f692efc9720552435d005a55cb9bdad4e2b | [
"MIT"
] | null | null | null | """MyLib"""
def hello_world():
print("Hello world")
| 9.666667 | 24 | 0.586207 | 7 | 58 | 4.714286 | 0.714286 | 0.606061 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.189655 | 58 | 5 | 25 | 11.6 | 0.702128 | 0.086207 | 0 | 0 | 0 | 0 | 0.234043 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | true | 0 | 0 | 0 | 0.5 | 0.5 | 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 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
2cdd32a6e082588cab0feceac50dd35bb8147906 | 2,007 | py | Python | tests_local/not_auth_user/banners_adaptive_test.py | manifiko/AdCampaign_tests | 39d88f3282f26e8976e795f2733491671bd1e028 | [
"MIT"
] | null | null | null | tests_local/not_auth_user/banners_adaptive_test.py | manifiko/AdCampaign_tests | 39d88f3282f26e8976e795f2733491671bd1e028 | [
"MIT"
] | null | null | null | tests_local/not_auth_user/banners_adaptive_test.py | manifiko/AdCampaign_tests | 39d88f3282f26e8976e795f2733491671bd1e028 | [
"MIT"
] | null | null | null | import config
from tests_steps.banners_steps import *
from tests_steps.browser_config import *
def test_banners_adaptive_in_full_hd():
browser = setup_local_browser(size='Full HD', polling_time=5)
try:
browser.get(config.BASE_URL)
check_banner_visibility_by_css_selector(browser=browser,
css_selector='body > div.container > main > div > div.row.position-relative.d-none.d-lg-flex > div.col-12.d-none.d-lg-flex',
visibility=True)
small_banners = browser.find_elements_by_css_selector('body > div.container > main > div > div:nth-child(2) > div')
for banner_number in range(0, len(small_banners)):
if banner_number == 0:
check_banner_visibility_by_banner_object(banner=small_banners[banner_number], visibility=False)
else:
check_banner_visibility_by_banner_object(banner=small_banners[banner_number], visibility=True)
save_screenshot(browser=browser, test_name='banners_in_full_hd_test')
finally:
browser.quit()
def test_banners_adaptive_in_mobile_view():
browser = setup_local_browser(size='Tablet', polling_time=5)
try:
browser.get(config.BASE_URL)
check_banner_visibility_by_css_selector(browser=browser,
css_selector='body > div.container > main > div > div.row.position-relative.d-none.d-lg-flex > div.col-12.d-none.d-lg-flex',
visibility=False)
small_banners = browser.find_elements_by_css_selector(
'body > div.container > main > div > div:nth-child(2) > div')
for banner_number in range(0, len(small_banners)):
check_banner_visibility_by_banner_object(banner=small_banners[banner_number], visibility=True)
save_screenshot(browser=browser, test_name='banners_in_mobile_view_test')
finally:
browser.quit() | 52.815789 | 172 | 0.655207 | 253 | 2,007 | 4.873518 | 0.26087 | 0.068127 | 0.085158 | 0.093268 | 0.839416 | 0.755069 | 0.755069 | 0.755069 | 0.755069 | 0.755069 | 0 | 0.007324 | 0.251619 | 2,007 | 38 | 173 | 52.815789 | 0.813582 | 0 | 0 | 0.484848 | 0 | 0.060606 | 0.196713 | 0.093626 | 0 | 0 | 0 | 0 | 0 | 1 | 0.060606 | false | 0 | 0.090909 | 0 | 0.151515 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
2cea8a55258f0b845c29e9d405fb2fbef49745dd | 244 | py | Python | tests/test_deepl-scripts.py | utecx/py-algorithms-4-automotive-engineering | 45fa443b721efe6d887aaeeeae9b6867d71f2677 | [
"MIT"
] | 47 | 2020-04-20T14:12:20.000Z | 2022-03-02T15:26:59.000Z | tests/test_deepl-scripts.py | utecx/py-algorithms-4-automotive-engineering | 45fa443b721efe6d887aaeeeae9b6867d71f2677 | [
"MIT"
] | 6 | 2019-08-08T05:15:44.000Z | 2020-03-27T09:39:06.000Z | tests/test_deepl-scripts.py | utecx/py-algorithms-4-automotive-engineering | 45fa443b721efe6d887aaeeeae9b6867d71f2677 | [
"MIT"
] | 65 | 2019-07-01T06:09:48.000Z | 2022-03-08T18:37:45.000Z | import subprocess
def test_regression():
subprocess.run("pytest 04_mini-projects/deepl_files/regression.py", shell=True)
def test_classification():
subprocess.run("pytest 04_mini-projects/deepl_files/classification.py", shell=True)
| 24.4 | 87 | 0.786885 | 32 | 244 | 5.8125 | 0.5 | 0.075269 | 0.204301 | 0.225806 | 0.462366 | 0.462366 | 0.462366 | 0.462366 | 0 | 0 | 0 | 0.018182 | 0.098361 | 244 | 9 | 88 | 27.111111 | 0.827273 | 0 | 0 | 0 | 0 | 0 | 0.418033 | 0.360656 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | true | 0 | 0.2 | 0 | 0.6 | 0 | 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 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
2cef28d9e032a99cfe4709b5e1a0dbea9b31fec5 | 5,868 | py | Python | unit_tests/caseworker/advice/views/test_edit_advice.py | code-review-doctor/lite-frontend-1 | cb3b885bb389ea33ef003c916bea7b03a36d86bb | [
"MIT"
] | null | null | null | unit_tests/caseworker/advice/views/test_edit_advice.py | code-review-doctor/lite-frontend-1 | cb3b885bb389ea33ef003c916bea7b03a36d86bb | [
"MIT"
] | null | null | null | unit_tests/caseworker/advice/views/test_edit_advice.py | code-review-doctor/lite-frontend-1 | cb3b885bb389ea33ef003c916bea7b03a36d86bb | [
"MIT"
] | null | null | null | import pytest
from copy import deepcopy
from django.urls import reverse
from core import client
@pytest.fixture(autouse=True)
def setup(mock_queue, mock_case, mock_denial_reasons):
yield
@pytest.fixture
def url(data_queue, data_standard_case):
return reverse(f"cases:edit_advice", kwargs={"queue_pk": data_queue["id"], "pk": data_standard_case["case"]["id"]})
def test_edit_approve_advice_post(authorized_client, requests_mock, data_standard_case, standard_case_with_advice, url):
user_advice_create_url = f"/cases/{data_standard_case['case']['id']}/user-advice/"
requests_mock.post(user_advice_create_url, json={})
case_data = deepcopy(data_standard_case)
case_data["case"]["data"]["goods"] = standard_case_with_advice["data"]["goods"]
case_data["case"]["advice"] = standard_case_with_advice["advice"]
requests_mock.get(client._build_absolute_uri(f"/cases/{data_standard_case['case']['id']}"), json=case_data)
requests_mock.get(
client._build_absolute_uri(f"/gov_users/{data_standard_case['case']['id']}"),
json={"user": {"id": "58e62718-e889-4a01-b603-e676b794b394"}},
)
data = {
"approval_reasons": "meets the requirements updated",
"instructions_to_exporter": "no specific instructions",
}
response = authorized_client.post(url, data=data)
assert response.status_code == 302
history = [item for item in requests_mock.request_history if user_advice_create_url in item.url]
assert len(history) == 1
history = history[0]
assert history.method == "POST"
assert history.json() == [
{
"denial_reasons": [],
"end_user": "95d3ea36-6ab9-41ea-a744-7284d17b9cc5",
"footnote": "",
"footnote_required": False,
"note": "no specific instructions",
"proviso": "",
"text": "meets the requirements updated",
"type": "approve",
},
{
"consignee": "cd2263b4-a427-4f14-8552-505e1d192bb8",
"denial_reasons": [],
"footnote": "",
"footnote_required": False,
"note": "no specific instructions",
"proviso": "",
"text": "meets the requirements updated",
"type": "approve",
},
{
"denial_reasons": [],
"footnote": "",
"footnote_required": False,
"note": "no specific instructions",
"proviso": "",
"text": "meets the requirements updated",
"third_party": "95c2d6b7-5cfd-47e8-b3c8-dc76e1ac9747",
"type": "approve",
},
{
"denial_reasons": [],
"footnote": "",
"footnote_required": False,
"good": "9fbffa7f-ef50-402e-93ac-2f3f37d09030",
"note": "no specific instructions",
"proviso": "",
"text": "meets the requirements updated",
"type": "approve",
},
{
"denial_reasons": [],
"footnote": "",
"footnote_required": False,
"good": "d4feac1e-851d-41a5-b833-eb28addb8547",
"note": "",
"proviso": "",
"text": "",
"type": "no_licence_required",
},
]
def test_edit_refuse_advice_post(
authorized_client,
requests_mock,
data_standard_case,
standard_case_with_advice,
refusal_advice,
url,
mock_denial_reasons,
):
user_advice_create_url = f"/cases/{data_standard_case['case']['id']}/user-advice/"
requests_mock.post(user_advice_create_url, json={})
case_data = deepcopy(data_standard_case)
case_data["case"]["data"]["goods"] = standard_case_with_advice["data"]["goods"]
case_data["case"]["advice"] = refusal_advice
requests_mock.get(client._build_absolute_uri(f"/cases/{data_standard_case['case']['id']}"), json=case_data)
requests_mock.get(
client._build_absolute_uri(f"/gov_users/{data_standard_case['case']['id']}"),
json={"user": {"id": "58e62718-e889-4a01-b603-e676b794b394"}},
)
data = {
"refusal_reasons": "doesn't meet the requirement",
"denial_reasons": ["3", "4", "5", "5a", "5b"],
}
response = authorized_client.post(url, data=data)
assert response.status_code == 302
history = requests_mock.request_history.pop()
assert user_advice_create_url in history.url
assert history.method == "POST"
assert history.json() == [
{
"denial_reasons": ["3", "4", "5", "5a", "5b"],
"end_user": "95d3ea36-6ab9-41ea-a744-7284d17b9cc5",
"footnote_required": False,
"text": "doesn't meet the requirement",
"type": "refuse",
},
{
"consignee": "cd2263b4-a427-4f14-8552-505e1d192bb8",
"denial_reasons": ["3", "4", "5", "5a", "5b"],
"footnote_required": False,
"text": "doesn't meet the requirement",
"type": "refuse",
},
{
"denial_reasons": ["3", "4", "5", "5a", "5b"],
"footnote_required": False,
"text": "doesn't meet the requirement",
"third_party": "95c2d6b7-5cfd-47e8-b3c8-dc76e1ac9747",
"type": "refuse",
},
{
"denial_reasons": ["3", "4", "5", "5a", "5b"],
"footnote_required": False,
"good": "9fbffa7f-ef50-402e-93ac-2f3f37d09030",
"text": "doesn't meet the requirement",
"type": "refuse",
},
{
"denial_reasons": [],
"footnote": "",
"footnote_required": False,
"good": "d4feac1e-851d-41a5-b833-eb28addb8547",
"note": "",
"proviso": "",
"text": "",
"type": "no_licence_required",
},
]
| 35.349398 | 120 | 0.567485 | 606 | 5,868 | 5.247525 | 0.211221 | 0.064151 | 0.060377 | 0.056604 | 0.818868 | 0.791195 | 0.791195 | 0.782704 | 0.705975 | 0.633333 | 0 | 0.064599 | 0.27454 | 5,868 | 165 | 121 | 35.563636 | 0.682405 | 0 | 0 | 0.629139 | 0 | 0 | 0.343729 | 0.125426 | 0 | 0 | 0 | 0 | 0.05298 | 1 | 0.02649 | false | 0 | 0.02649 | 0.006623 | 0.059603 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
fa65df41ea077c320db56ef5136ce8cebf976459 | 96 | py | Python | venv/lib/python3.8/site-packages/numpy/distutils/fcompiler/compaq.py | GiulianaPola/select_repeats | 17a0d053d4f874e42cf654dd142168c2ec8fbd11 | [
"MIT"
] | 2 | 2022-03-13T01:58:52.000Z | 2022-03-31T06:07:54.000Z | venv/lib/python3.8/site-packages/numpy/distutils/fcompiler/compaq.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | 19 | 2021-11-20T04:09:18.000Z | 2022-03-23T15:05:55.000Z | venv/lib/python3.8/site-packages/numpy/distutils/fcompiler/compaq.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | null | null | null | /home/runner/.cache/pip/pool/b2/35/36/18a1c91ae0a1b516ff3219e8b8caaf9083907e59a8c0513a12b0966611 | 96 | 96 | 0.895833 | 9 | 96 | 9.555556 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | 0 | 96 | 1 | 96 | 96 | 0.4375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
3afa593aab7a84fc95cc1c6e3971de4b608a50cc | 31 | py | Python | app/backend/env/__init__.py | SummaLabs/DLS | 2adba47430b456ad0f324e4c8883a896a23b3fbf | [
"MIT"
] | 32 | 2017-09-04T17:40:39.000Z | 2021-02-16T23:08:34.000Z | app/backend/env/__init__.py | AymanNabih/DLS | 2adba47430b456ad0f324e4c8883a896a23b3fbf | [
"MIT"
] | 3 | 2017-10-09T12:52:54.000Z | 2020-06-29T02:48:38.000Z | app/backend/env/__init__.py | AymanNabih/DLS | 2adba47430b456ad0f324e4c8883a896a23b3fbf | [
"MIT"
] | 20 | 2017-10-07T17:29:50.000Z | 2021-01-23T22:01:54.000Z | from app.backend.env import api | 31 | 31 | 0.83871 | 6 | 31 | 4.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.096774 | 31 | 1 | 31 | 31 | 0.928571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
d711a0f847055d709793d1776481589da27d74b6 | 3,703 | py | Python | aminator/util/metrics.py | nhamplify/aminator | dad4d94af833752d2b2323b367e4fec80125be4d | [
"Apache-2.0"
] | 1 | 2019-11-17T08:00:33.000Z | 2019-11-17T08:00:33.000Z | aminator/util/metrics.py | nhamplify/aminator | dad4d94af833752d2b2323b367e4fec80125be4d | [
"Apache-2.0"
] | null | null | null | aminator/util/metrics.py | nhamplify/aminator | dad4d94af833752d2b2323b367e4fec80125be4d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
#
# Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
"""
aminator.util.metrics
===================
Metrics utility functions
"""
from time import time
def timer(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
start = time()
try:
retval = func(obj, *args, **kwargs)
(context_obj or obj)._config.metrics.timer(metric_name, time() - start)
except:
(context_obj or obj)._config.metrics.timer(metric_name, time() - start)
raise
return retval
return func_2
return func_1
def lapse(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
(context_obj or obj)._config.metrics.start_timer(metric_name)
try:
retval = func(obj, *args, **kwargs)
(context_obj or obj)._config.metrics.stop_timer(metric_name)
except:
(context_obj or obj)._config.metrics.stop_timer(metric_name)
raise
return retval
return func_2
return func_1
def fails(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
try:
retval = func(obj, *args, **kwargs)
except:
(context_obj or obj)._config.metrics.increment(metric_name)
raise
if not retval:
(context_obj or obj)._config.metrics.increment(metric_name)
return retval
return func_2
return func_1
def cmdfails(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
try:
retval = func(obj, *args, **kwargs)
except:
(context_obj or obj)._config.metrics.increment(metric_name)
raise
if not retval or not retval.success:
(context_obj or obj)._config.metrics.increment(metric_name)
return retval
return func_2
return func_1
def cmdsucceeds(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
retval = func(obj, *args, **kwargs)
if retval and retval.success:
(context_obj or obj)._config.metrics.increment(metric_name)
return retval
return func_2
return func_1
def succeeds(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
retval = func(obj, *args, **kwargs)
if retval:
(context_obj or obj)._config.metrics.increment(metric_name)
return retval
return func_2
return func_1
def raises(metric_name, context_obj=None):
def func_1(func):
def func_2(obj, *args, **kwargs):
try:
return func(obj, *args, **kwargs)
except:
(context_obj or obj)._config.metrics.increment(metric_name)
raise
return func_2
return func_1
| 31.922414 | 87 | 0.586281 | 460 | 3,703 | 4.543478 | 0.219565 | 0.090909 | 0.087081 | 0.086124 | 0.711483 | 0.711483 | 0.700957 | 0.695215 | 0.695215 | 0.681818 | 0 | 0.014636 | 0.31731 | 3,703 | 115 | 88 | 32.2 | 0.812104 | 0.183095 | 0 | 0.814815 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.259259 | false | 0 | 0.012346 | 0 | 0.530864 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
d715e4b24bfedab021b9fe0d20b0e30d2f73b05b | 14,298 | py | Python | Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py | PAM360/content | 928aac9c586c6e593b2a452c402a37cb5df28dac | [
"MIT"
] | null | null | null | Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py | PAM360/content | 928aac9c586c6e593b2a452c402a37cb5df28dac | [
"MIT"
] | 60 | 2022-02-24T14:54:47.000Z | 2022-03-31T10:38:41.000Z | Packs/CommonScripts/Scripts/ParseEmailFilesV2/ParseEmailFilesV2_test.py | PAM360/content | 928aac9c586c6e593b2a452c402a37cb5df28dac | [
"MIT"
] | null | null | null | import demistomock as demisto
from CommonServerPython import *
from ParseEmailFilesV2 import main, data_to_md
def exec_command_for_file(
file_path,
info="RFC 822 mail text, with CRLF line terminators",
file_name=None,
file_type="",
):
"""
Return a executeCommand function which will return the passed path as an entry to the call 'getFilePath'
Arguments:
file_path {string} -- file name of file residing in test_data dir
Raises:
ValueError: if call with differed name from getFilePath or getEntry
Returns:
[function] -- function to be used for mocking
"""
if not file_name:
file_name = file_path
path = 'test_data/' + file_path
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Type': entryTypes['note'],
'Contents': {
'path': path,
'name': file_name
}
}
]
elif name == 'getEntry':
return [
{
'Type': entryTypes['file'],
'FileMetadata': {
'info': info,
'type': file_type
}
}
]
else:
raise ValueError('Unimplemented command called: {}'.format(name))
return executeCommand
def test_eml_type(mocker):
"""
Given:
- A eml file
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure its was parsed successfully
"""
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Type': entryTypes['note'],
'Contents': {
'path': 'test_data/smtp_email_type.eml',
'name': 'smtp_email_type.eml'
}
}
]
elif name == 'getEntry':
return [
{
'Type': entryTypes['file'],
'FileMetadata': {
'info': 'SMTP mail, UTF-8 Unicode text, with CRLF terminators'
}
}
]
else:
raise ValueError('Unimplemented command called: {}'.format(name))
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand', side_effect=executeCommand)
mocker.patch.object(demisto, 'results')
# validate our mocks are good
assert demisto.args()['entryid'] == 'test'
# assert demisto.executeCommand('getFilePath', {})[0]['Type'] == entryTypes['note']
main()
assert demisto.results.call_count == 1
# call_args is tuple (args list, kwargs). we only need the first one
results = demisto.results.call_args[0]
assert len(results) == 1
assert results[0]['Type'] == entryTypes['note']
assert results[0]['EntryContext']['Email']['Subject'] == 'Test Smtp Email'
def test_eml_contains_eml(mocker):
"""
Given:
- A eml file contains eml
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure the was parsed successfully
- Ensure both files was parsed
- Ensure the attachments was returned
"""
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Type': entryTypes['note'],
'Contents': {
'path': 'test_data/Fwd_test-inner_attachment_eml.eml',
'name': 'Fwd_test-inner_attachment_eml.eml'
}
}
]
elif name == 'getEntry':
return [
{
'Type': entryTypes['file'],
'FileMetadata': {
'info': 'news or mail text, ASCII text'
}
}
]
else:
raise ValueError('Unimplemented command called: {}'.format(name))
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand', side_effect=executeCommand)
mocker.patch.object(demisto, 'results')
# validate our mocks are good
assert demisto.args()['entryid'] == 'test'
main()
assert demisto.results.call_count == 4
# call_args is tuple (args list, kwargs). we only need the first one
results = demisto.results.call_args_list
assert len(results) == 4
assert results[0].args[0]['File'] == 'ArcSight_ESM_fixes.yml'
assert results[1].args[0]['File'] == 'test - inner attachment eml.eml'
assert results[2].args[0]['EntryContext']['Email']['Subject'] == 'Fwd: test - inner attachment eml'
assert 'ArcSight_ESM_fixes.yml' in results[2].args[0]['EntryContext']['Email']['Attachments']
assert 'ArcSight_ESM_fixes.yml' in results[2].args[0]['EntryContext']['Email']['AttachmentsData'][0]['Name']
assert 'test - inner attachment eml.eml' in results[2].args[0]['EntryContext']['Email']['Attachments']
assert 'test - inner attachment eml.eml' in results[2].args[0]['EntryContext']['Email']['AttachmentsData'][1]['Name']
assert results[2].args[0]['EntryContext']['Email']['Depth'] == 0
assert results[3].args[0]['EntryContext']['Email']["Subject"] == 'test - inner attachment eml'
assert results[3].args[0]['EntryContext']['Email']['Depth'] == 1
def test_eml_contains_msg(mocker):
"""
Given:
- A eml file contains msg
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure the was parsed successfully
- Ensure both files was parsed
- Ensure the attachments was returned
"""
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Type': entryTypes['note'],
'Contents': {
'path': 'test_data/DONT_OPEN-MALICIOUS.eml',
'name': 'DONT_OPEN-MALICIOUS.eml'
}
}
]
elif name == 'getEntry':
return [
{
'Type': entryTypes['file'],
'FileMetadata': {
'info': 'news or mail text, ASCII text'
}
}
]
else:
raise ValueError('Unimplemented command called: {}'.format(name))
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand', side_effect=executeCommand)
mocker.patch.object(demisto, 'results')
# validate our mocks are good
assert demisto.args()['entryid'] == 'test'
main()
results = demisto.results.call_args_list
assert demisto.results.call_count == 3
assert len(results) == 3
assert results[0].args[0]['File'] == 'Attacker+email+.msg'
assert results[1].args[0]['EntryContext']['Email']['Subject'] == 'DONT OPEN - MALICIOS'
assert 'Attacker+email+.msg' in results[1].args[0]['EntryContext']['Email']['Attachments']
assert 'Attacker+email+.msg' in results[1].args[0]['EntryContext']['Email']['AttachmentsData'][0]['Name']
assert results[1].args[0]['EntryContext']['Email']['Depth'] == 0
assert results[2].args[0]['EntryContext']['Email']["Subject"] == 'Attacker email'
assert results[2].args[0]['EntryContext']['Email']['Depth'] == 1
def test_eml_contains_eml_depth(mocker):
"""
Given:
- A eml file contains eml
- depth = 1
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure only the first mail is parsed
- Ensure the attachments of the first mail was returned
"""
def executeCommand(name, args=None):
if name == 'getFilePath':
return [
{
'Type': entryTypes['note'],
'Contents': {
'path': 'test_data/Fwd_test-inner_attachment_eml.eml',
'name': 'Fwd_test-inner_attachment_eml.eml'
}
}
]
elif name == 'getEntry':
return [
{
'Type': entryTypes['file'],
'FileMetadata': {
'info': 'news or mail text, ASCII text'
}
}
]
else:
raise ValueError('Unimplemented command called: {}'.format(name))
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test', 'max_depth': '1'})
mocker.patch.object(demisto, 'executeCommand', side_effect=executeCommand)
mocker.patch.object(demisto, 'results')
# validate our mocks are good
assert demisto.args()['entryid'] == 'test'
main()
assert demisto.results.call_count == 3
# call_args is tuple (args list, kwargs). we only need the first one
results = demisto.results.call_args_list
assert len(results) == 3
assert results[0].args[0]['File'] == 'ArcSight_ESM_fixes.yml'
assert results[1].args[0]['File'] == 'test - inner attachment eml.eml'
assert results[2].args[0]['EntryContext']['Email']['Depth'] == 0
assert 'ArcSight_ESM_fixes.yml' in results[2].args[0]['EntryContext']['Email']['Attachments']
assert 'ArcSight_ESM_fixes.yml' in results[2].args[0]['EntryContext']['Email']['AttachmentsData'][0]['Name']
assert 'test - inner attachment eml.eml' in results[2].args[0]['EntryContext']['Email']['Attachments']
assert 'test - inner attachment eml.eml' in results[2].args[0]['EntryContext']['Email']['AttachmentsData'][1]['Name']
def test_msg(mocker):
"""
Given:
- A msg file
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure its was parsed successfully
"""
info = 'CDFV2 Microsoft Outlook Message'
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand', side_effect=exec_command_for_file('smime-p7s.msg', info=info))
mocker.patch.object(demisto, 'results')
# validate our mocks are good
assert demisto.args()['entryid'] == 'test'
main()
# assert demisto.results.call_count == 1
# call_args is tuple (args list, kwargs). we only need the first one
results = demisto.results.call_args[0]
assert len(results) == 1
assert results[0]['Type'] == entryTypes['note']
assert results[0]['EntryContext']['Email']['Subject'] == 'test'
def test_no_content_type_file(mocker):
"""
Given:
- A eml with no_content_type
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure its was parsed successfully
"""
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand',
side_effect=exec_command_for_file('no_content_type.eml', info="ascii text"))
mocker.patch.object(demisto, 'results')
main()
results = demisto.results.call_args[0]
assert len(results) == 1
assert results[0]['Type'] == entryTypes['note']
assert results[0]['EntryContext']['Email']['Subject'] == 'No content type'
def test_no_content_file(mocker):
"""
Given:
- A eml without content
When:
- run the ParseEmailFilesV2 script
Then:
- Ensure a error is returned
"""
mocker.patch.object(demisto, 'args', return_value={'entryid': 'test'})
mocker.patch.object(demisto, 'executeCommand',
side_effect=exec_command_for_file('no_content.eml', info="ascii text"))
mocker.patch.object(demisto, 'results')
try:
main()
except SystemExit:
gotexception = True
assert gotexception
results = demisto.results.call_args[0]
assert len(results) == 1
assert 'Could not extract email from file' in results[0]['Contents']
def test_md_output_empty_body_text():
"""
Given:
- The input email_data where the value of the 'Text' field is None.
When:
- Running the data_to_md command on this email_data.
Then:
- Validate that output the md doesn't contain a row for the 'Text' field.
"""
email_data = {
'To': 'email1@paloaltonetworks.com',
'From': 'email2@paloaltonetworks.com',
'Text': None
}
expected = u'### Results:\n' \
u'* From:\temail2@paloaltonetworks.com\n' \
u'* To:\temail1@paloaltonetworks.com\n' \
u'* CC:\t\n' \
u'* Subject:\t\n' \
u'* Attachments:\t\n\n\n' \
u'### HeadersMap\n' \
u'**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
email_data = {
'To': 'email1@paloaltonetworks.com',
'From': 'email2@paloaltonetworks.com',
}
expected = u'### Results:\n' \
u'* From:\temail2@paloaltonetworks.com\n' \
u'* To:\temail1@paloaltonetworks.com\n' \
u'* CC:\t\n' \
u'* Subject:\t\n' \
u'* Attachments:\t\n\n\n' \
u'### HeadersMap\n' \
u'**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
def test_md_output_with_body_text():
"""
Given:
- The input email_data with a value in the 'Text' field.
When:
- Running the data_to_md command on this email_data.
Then:
- Validate that the output md contains a row for the 'Text' field.
"""
email_data = {
'To': 'email1@paloaltonetworks.com',
'From': 'email2@paloaltonetworks.com',
'Text': '<email text>'
}
expected = u'### Results:\n' \
u'* From:\temail2@paloaltonetworks.com\n' \
u'* To:\temail1@paloaltonetworks.com\n' \
u'* CC:\t\n' \
u'* Subject:\t\n' \
u'* Body/Text:\t[email text]\n' \
u'* Attachments:\t\n\n\n' \
u'### HeadersMap\n' \
u'**No entries.**\n'
md = data_to_md(email_data)
assert expected == md
| 34.042857 | 121 | 0.556232 | 1,551 | 14,298 | 5.031593 | 0.118633 | 0.01794 | 0.050743 | 0.064582 | 0.832394 | 0.81471 | 0.806125 | 0.764352 | 0.741287 | 0.722066 | 0 | 0.011121 | 0.308225 | 14,298 | 419 | 122 | 34.124105 | 0.777879 | 0.166387 | 0 | 0.614232 | 0 | 0 | 0.283955 | 0.064267 | 0 | 0 | 0 | 0 | 0.191011 | 1 | 0.05618 | false | 0 | 0.011236 | 0 | 0.108614 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
d7941ade79223b2bbb7237ce102a5ac28b8a34d5 | 98 | py | Python | src/gfl/core/net/standalone/callback.py | mingt2019/GFL | b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3 | [
"MIT"
] | 123 | 2020-06-05T13:30:38.000Z | 2022-03-30T08:39:43.000Z | src/gfl/core/net/standalone/callback.py | GalaxyLearning/PFL | b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3 | [
"MIT"
] | 13 | 2020-06-19T13:09:47.000Z | 2021-12-22T03:09:24.000Z | src/gfl/core/net/standalone/callback.py | GalaxyLearning/GFL | b8e027d2e8cdcc27c85a00744f8790d6db3cc4a3 | [
"MIT"
] | 35 | 2020-06-08T15:52:21.000Z | 2022-03-25T11:52:42.000Z |
from gfl.core.net.abstract import NetCallback
class StandaloneCallback(NetCallback):
pass
| 12.25 | 45 | 0.785714 | 11 | 98 | 7 | 0.909091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.153061 | 98 | 7 | 46 | 14 | 0.927711 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 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 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
ad50f8f763074e3c3cb09d3fd3bfc6a0524e2db5 | 23 | py | Python | SimPEG/flow/__init__.py | Prithwijit-Chak/simpeg | d93145d768b5512621cdd75566b4a8175fee9ed3 | [
"MIT"
] | 358 | 2015-03-11T05:48:41.000Z | 2022-03-26T02:04:12.000Z | SimPEG/flow/__init__.py | thast/simpeg | 8021082b8b53f3c08fa87fc085547bdd56437c6b | [
"MIT"
] | 885 | 2015-01-19T09:23:48.000Z | 2022-03-29T12:08:34.000Z | SimPEG/flow/__init__.py | thast/simpeg | 8021082b8b53f3c08fa87fc085547bdd56437c6b | [
"MIT"
] | 214 | 2015-03-11T05:48:43.000Z | 2022-03-02T01:05:11.000Z | from . import richards
| 11.5 | 22 | 0.782609 | 3 | 23 | 6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | 23 | 1 | 23 | 23 | 0.947368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
ad570f65edf0df92dad4e17649421c39777082b0 | 1,417 | py | Python | stream/tanium/src/intel_cache.py | tiiibs/connectors | 65349790813a1d49f4536662725d99d8bfa08481 | [
"Apache-2.0"
] | 132 | 2019-06-28T23:23:18.000Z | 2022-03-30T07:47:55.000Z | stream/tanium/src/intel_cache.py | tiiibs/connectors | 65349790813a1d49f4536662725d99d8bfa08481 | [
"Apache-2.0"
] | 472 | 2019-06-26T12:14:54.000Z | 2022-03-31T13:49:53.000Z | stream/tanium/src/intel_cache.py | tiiibs/connectors | 65349790813a1d49f4536662725d99d8bfa08481 | [
"Apache-2.0"
] | 185 | 2019-07-01T09:32:14.000Z | 2022-03-28T05:29:12.000Z | ###############
# INTEL CACHE #
###############
class IntelCache:
def __init__(self, helper):
self.helper = helper
def get(self, type, opencti_entity_id):
current_state = self.helper.get_state()
if current_state is not None:
if type in current_state:
if opencti_entity_id in current_state[type]:
return current_state[type][opencti_entity_id]
return None
def set(self, type, opencti_entity_id, tanium_intel_id):
current_state = self.helper.get_state()
if current_state is not None:
if type in current_state:
current_state[type][opencti_entity_id] = tanium_intel_id
else:
current_state[type] = {}
current_state[type][opencti_entity_id] = tanium_intel_id
else:
current_state = {}
current_state[opencti_entity_id] = tanium_intel_id
self.helper.set_state(current_state)
return tanium_intel_id
def delete(self, type, opencti_entity_id):
current_state = self.helper.get_state()
if current_state is None:
return
if current_state is not None:
if type in current_state and opencti_entity_id in current_state[type]:
del current_state[type][opencti_entity_id]
self.helper.set_state(current_state)
return
| 34.560976 | 82 | 0.611856 | 174 | 1,417 | 4.637931 | 0.155172 | 0.312268 | 0.185874 | 0.164808 | 0.82404 | 0.819083 | 0.712515 | 0.593556 | 0.49938 | 0.49938 | 0 | 0 | 0.302752 | 1,417 | 40 | 83 | 35.425 | 0.816802 | 0.007763 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0 | 0 | 0.3125 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 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 | 6 |
d101f48920ed6145da238d0160cd8c4206fa201a | 155 | py | Python | sodium/model/loss.py | Keerthi001/PySodium | 761598d8a129ce95a42404898b7f16ddcae568d9 | [
"MIT"
] | 22 | 2020-05-16T08:15:48.000Z | 2021-12-30T14:38:31.000Z | sodium/model/loss.py | Keerthi001/PySodium | 761598d8a129ce95a42404898b7f16ddcae568d9 | [
"MIT"
] | 1 | 2020-07-01T14:14:50.000Z | 2020-07-01T16:04:13.000Z | sodium/model/loss.py | Keerthi001/PySodium | 761598d8a129ce95a42404898b7f16ddcae568d9 | [
"MIT"
] | 43 | 2020-03-07T22:08:41.000Z | 2022-03-16T21:07:30.000Z | import torch.nn.functional as F
import torch.nn as nn
def nll_loss():
return F.nll_loss
def cross_entropy_loss():
return nn.CrossEntropyLoss()
| 14.090909 | 32 | 0.735484 | 25 | 155 | 4.4 | 0.52 | 0.2 | 0.236364 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.180645 | 155 | 10 | 33 | 15.5 | 0.866142 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0.333333 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 6 |
d12731763c1f7c12586bb86b31a5890f11da3ee3 | 18,889 | py | Python | tests/test_Control.py | zanachka/python3-anticaptcha | a078455ce013a873936495ba2dc3e25c0aeb9c48 | [
"MIT"
] | 125 | 2017-11-15T14:38:51.000Z | 2022-03-01T08:51:09.000Z | tests/test_Control.py | zanachka/python3-anticaptcha | a078455ce013a873936495ba2dc3e25c0aeb9c48 | [
"MIT"
] | 31 | 2018-03-07T00:57:46.000Z | 2022-02-10T17:38:17.000Z | tests/test_Control.py | zanachka/python3-anticaptcha | a078455ce013a873936495ba2dc3e25c0aeb9c48 | [
"MIT"
] | 44 | 2017-10-13T06:09:28.000Z | 2022-03-21T10:50:47.000Z | import random
import inspect
import pytest
import requests_mock
from tests.main import MainAntiCaptcha
from python3_anticaptcha import AntiCaptchaControl, config
class TestControl(MainAntiCaptcha):
WRONG_MODE = WRONG_CAPTCHA_TYPE = WRONG_QUEUE = "qwerty"
WRONG_SOFT_ID = "-1" + config.app_key
REPORT_ID = WRONG_QUEUE_ID = -1
QUEUE_STATUS_KEYS = ("waiting", "load", "bid", "speed", "total")
"""
Params check
"""
def test_params(self):
default_init_params = ["self", "anticaptcha_key"]
default_get_balance_params = ["self"]
default_app_stats_params = ["self", "softId", "mode"]
default_complaint_params = ["self", "reported_id", "captcha_type"]
default_queue_status_params = ["queue_id"]
# get aiocaptchacontrol init and other params
aio_init_params = inspect.getfullargspec(AntiCaptchaControl.aioAntiCaptchaControl.__init__)
aio_balance_params = inspect.getfullargspec(AntiCaptchaControl.aioAntiCaptchaControl.get_balance)
aio_app_stats_params = inspect.getfullargspec(AntiCaptchaControl.aioAntiCaptchaControl.get_app_stats)
aio_complaint_params = inspect.getfullargspec(
AntiCaptchaControl.aioAntiCaptchaControl.complaint_on_result
)
aio_queue_status_params = inspect.getfullargspec(
AntiCaptchaControl.aioAntiCaptchaControl.get_queue_status
)
# get captchacontrol init and other params
init_params = inspect.getfullargspec(AntiCaptchaControl.AntiCaptchaControl.__init__)
balance_params = inspect.getfullargspec(AntiCaptchaControl.AntiCaptchaControl.get_balance)
app_stats_params = inspect.getfullargspec(AntiCaptchaControl.AntiCaptchaControl.get_app_stats)
complaint_params = inspect.getfullargspec(AntiCaptchaControl.AntiCaptchaControl.complaint_on_result)
queue_status_params = inspect.getfullargspec(AntiCaptchaControl.AntiCaptchaControl.get_queue_status)
# check aio module params
assert default_init_params == aio_init_params[0]
assert default_get_balance_params == aio_balance_params[0]
assert default_app_stats_params == aio_app_stats_params[0]
assert default_complaint_params == aio_complaint_params[0]
assert default_queue_status_params == aio_queue_status_params[0]
# check sync module params
assert default_init_params == init_params[0]
assert default_get_balance_params == balance_params[0]
assert default_app_stats_params == app_stats_params[0]
assert default_complaint_params == complaint_params[0]
assert default_queue_status_params == queue_status_params[0]
"""
Request payload test MOCK
"""
def test_balance_payload(self):
control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
# check response type
assert isinstance(control, AntiCaptchaControl.AntiCaptchaControl)
with requests_mock.Mocker() as req_mock:
req_mock.post(AntiCaptchaControl.get_balance_url, json=self.ERROR_RESPONSE_JSON)
control.get_balance()
history = req_mock.request_history
assert len(history) == 1
request_payload = history[0].json()
# check all dict keys
assert [
"clientKey",
] == list(request_payload.keys())
assert request_payload["clientKey"] == self.anticaptcha_key_true
def test_stats_payload(self):
control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
# check response type
assert isinstance(control, AntiCaptchaControl.AntiCaptchaControl)
mode = random.choice(AntiCaptchaControl.mods)
with requests_mock.Mocker() as req_mock:
req_mock.post(AntiCaptchaControl.get_app_stats_url, json=self.ERROR_RESPONSE_JSON)
control.get_app_stats(softId=config.app_key, mode=mode)
history = req_mock.request_history
assert len(history) == 1
request_payload = history[0].json()
# check all dict keys
assert ["clientKey", "softId", "mode"] == list(request_payload.keys())
assert request_payload["clientKey"] == self.anticaptcha_key_true
assert request_payload["softId"] == config.app_key
assert request_payload["mode"] == mode
def test_complaint_image_payload(self):
control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
# check response type
assert isinstance(control, AntiCaptchaControl.AntiCaptchaControl)
task_id = 123456
with requests_mock.Mocker() as req_mock:
req_mock.post(AntiCaptchaControl.incorrect_imagecaptcha_url, json=self.ERROR_RESPONSE_JSON)
control.complaint_on_result(
reported_id=task_id, captcha_type=AntiCaptchaControl.complaint_types[0]
)
history = req_mock.request_history
assert len(history) == 1
request_payload = history[0].json()
# check all dict keys
assert ["clientKey", "taskId"] == list(request_payload.keys())
assert request_payload["clientKey"] == self.anticaptcha_key_true
assert request_payload["taskId"] == task_id
def test_complaint_re_payload(self):
control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
# check response type
assert isinstance(control, AntiCaptchaControl.AntiCaptchaControl)
task_id = 123456
with requests_mock.Mocker() as req_mock:
req_mock.post(AntiCaptchaControl.incorrect_recaptcha_url, json=self.ERROR_RESPONSE_JSON)
control.complaint_on_result(
reported_id=task_id, captcha_type=AntiCaptchaControl.complaint_types[1]
)
history = req_mock.request_history
assert len(history) == 1
request_payload = history[0].json()
# check all dict keys
assert ["clientKey", "taskId"] == list(request_payload.keys())
assert request_payload["clientKey"] == self.anticaptcha_key_true
assert request_payload["taskId"] == task_id
def test_queue_payload(self):
queue_id = random.choice(AntiCaptchaControl.queue_ids)
with requests_mock.Mocker() as req_mock:
req_mock.post(AntiCaptchaControl.get_queue_status_url, json=self.ERROR_RESPONSE_JSON)
AntiCaptchaControl.AntiCaptchaControl.get_queue_status(queue_id)
history = req_mock.request_history
assert len(history) == 1
request_payload = history[0].json()
# check all dict keys
assert [
"queueId",
] == list(request_payload.keys())
assert request_payload["queueId"] == queue_id
"""
Response checking
"""
def test_response_control(self):
control_captcha = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
# check response type
assert isinstance(control_captcha, AntiCaptchaControl.AntiCaptchaControl)
@pytest.mark.asyncio
async def test_response_aiocontrol(self):
control_captcha = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
# check response type
assert isinstance(control_captcha, AntiCaptchaControl.aioAntiCaptchaControl)
"""
Fail tests
"""
def test_fail_balance(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = captcha_control.get_balance()
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_balance_context(self):
with AntiCaptchaControl.AntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_fail
) as captcha_control:
response = captcha_control.get_balance()
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_key_app_stats(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = captcha_control.get_app_stats(softId=self.WRONG_SOFT_ID)
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_app_stats_context(self):
with AntiCaptchaControl.AntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_fail
) as captcha_control:
response = captcha_control.get_app_stats(softId=config.app_key)
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_id_app_stats(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = captcha_control.get_app_stats(softId=self.WRONG_SOFT_ID)
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_mode_app_stats(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
with pytest.raises(ValueError):
assert captcha_control.get_app_stats(softId=config.app_key, mode=self.WRONG_MODE)
def test_fail_key_complaint(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=AntiCaptchaControl.complaint_types[0]
)
assert isinstance(response, dict)
assert 1 == response["errorId"]
def test_fail_id_complaint(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=AntiCaptchaControl.complaint_types[0]
)
assert isinstance(response, dict)
assert 16 == response["errorId"]
def test_fail_type_complaint(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
with pytest.raises(ValueError):
assert captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=self.WRONG_CAPTCHA_TYPE
)
def test_fail_id_queue_status(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl
with pytest.raises(ValueError):
assert captcha_control.get_queue_status(queue_id=self.WRONG_QUEUE_ID)
@pytest.mark.asyncio
async def test_fail_aiobalance(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = await captcha_control.get_balance()
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aiobalance_context(self):
with AntiCaptchaControl.aioAntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_fail
) as captcha_control:
response = await captcha_control.get_balance()
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aioapp_stats_context(self):
with AntiCaptchaControl.aioAntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_fail
) as captcha_control:
response = await captcha_control.get_app_stats(softId=config.app_key)
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aiokey_app_stats(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = await captcha_control.get_app_stats(softId=self.WRONG_SOFT_ID)
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aioid_app_stats(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = await captcha_control.get_app_stats(softId=self.WRONG_SOFT_ID)
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aiomode_app_stats(self):
with AntiCaptchaControl.aioAntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_fail
) as captcha_control:
response = await captcha_control.get_balance()
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aiokey_complaint(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
response = await captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=AntiCaptchaControl.complaint_types[0]
)
assert isinstance(response, dict)
assert 1 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aioid_complaint(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = await captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=AntiCaptchaControl.complaint_types[0]
)
assert isinstance(response, dict)
assert 16 == response["errorId"]
@pytest.mark.asyncio
async def test_fail_aiotype_complaint(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_fail)
with pytest.raises(ValueError):
assert await captcha_control.complaint_on_result(
reported_id=self.REPORT_ID, captcha_type=self.WRONG_CAPTCHA_TYPE
)
@pytest.mark.asyncio
async def test_fail_aioid_queue_status(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl
with pytest.raises(ValueError):
assert await captcha_control.get_queue_status(queue_id=self.WRONG_QUEUE_ID)
def test_fail_spend_stats_queue(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
with pytest.raises(ValueError):
captcha_control.get_spend_stats(queue=self.WRONG_QUEUE)
@pytest.mark.asyncio
async def test_fail_aiospend_stats_queue(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
with pytest.raises(ValueError):
await captcha_control.get_spend_stats(queue=self.WRONG_QUEUE)
"""
True tests
"""
def test_true_mode_app_stats(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
for mode in AntiCaptchaControl.mods:
response = captcha_control.get_app_stats(softId=config.app_key, mode=mode)
assert isinstance(response, dict)
assert 0 == response["errorId"]
def test_true_mode_app_stats_context(self):
with AntiCaptchaControl.AntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_true
) as captcha_control:
for mode in AntiCaptchaControl.mods:
response = captcha_control.get_app_stats(softId=config.app_key, mode=mode)
assert isinstance(response, dict)
assert 0 == response["errorId"]
def test_true_balance(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = captcha_control.get_balance()
assert isinstance(response, dict)
assert 0 == response["errorId"]
def test_true_balance_context(self):
with AntiCaptchaControl.AntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_true
) as captcha_control:
response = captcha_control.get_balance()
assert isinstance(response, dict)
assert 0 == response["errorId"]
def test_true_queue_status(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl
for queue_id in AntiCaptchaControl.queue_ids:
response = captcha_control.get_queue_status(queue_id=queue_id)
assert isinstance(response, dict)
assert self.QUEUE_STATUS_KEYS == tuple(response.keys())
def test_true_spend_stats(self):
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = captcha_control.get_spend_stats()
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
def test_true_spend_stats_queues(self):
queues = AntiCaptchaControl.queues_names
captcha_control = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
for queue in queues:
response = captcha_control.get_spend_stats(queue=queue)
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
def test_true_spend_stats_context(self):
with AntiCaptchaControl.AntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_true
) as captcha_control:
response = captcha_control.get_spend_stats()
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
@pytest.mark.asyncio
async def test_true_aiospend_stats(self):
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
response = await captcha_control.get_spend_stats()
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
@pytest.mark.asyncio
async def test_true_aiospend_stats_context(self):
with AntiCaptchaControl.aioAntiCaptchaControl(
anticaptcha_key=self.anticaptcha_key_true
) as captcha_control:
response = await captcha_control.get_spend_stats()
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
@pytest.mark.asyncio
async def test_true_aiospend_stats_queues(self):
queues = AntiCaptchaControl.queues_names
captcha_control = AntiCaptchaControl.aioAntiCaptchaControl(anticaptcha_key=self.anticaptcha_key_true)
for queue in queues:
response = await captcha_control.get_spend_stats(queue=queue)
assert isinstance(response, dict)
assert ("errorId", "data") == tuple(response.keys())
| 37.183071 | 109 | 0.711208 | 2,024 | 18,889 | 6.319664 | 0.059289 | 0.084278 | 0.057697 | 0.08162 | 0.896724 | 0.861074 | 0.807286 | 0.787663 | 0.734501 | 0.724728 | 0 | 0.004167 | 0.212293 | 18,889 | 507 | 110 | 37.25641 | 0.855501 | 0.018688 | 0 | 0.613497 | 0 | 0 | 0.023576 | 0 | 0 | 0 | 0 | 0 | 0.282209 | 1 | 0.079755 | false | 0 | 0.018405 | 0 | 0.122699 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
0f0002cd411a52e905b1647c6d6778b544bd0353 | 140 | py | Python | 02_numpy/solutions/21_solutions.py | HirahTang/datascience_starter_course | a4429db9ae1795eaf52b795d16897466d769c40c | [
"CC0-1.0"
] | 3 | 2020-09-06T06:01:41.000Z | 2020-09-23T19:03:04.000Z | 01_numpy/solutions/21_solutions.py | glemaitre/smob_paristech_12_2018 | b669206f204a3e57e71efb3dd22e2ffbc4e0a309 | [
"CC0-1.0"
] | 4 | 2019-02-22T21:37:20.000Z | 2019-03-12T13:20:29.000Z | 01_numpy/solutions/21_solutions.py | glemaitre/smob_paristech_12_2018 | b669206f204a3e57e71efb3dd22e2ffbc4e0a309 | [
"CC0-1.0"
] | 5 | 2020-10-26T05:03:09.000Z | 2022-03-24T04:22:09.000Z | X = np.random.randn(5, 2)
Y = np.random.randn(5, 2)
print(np.concatenate((X, Y), axis=0).shape)
print(np.concatenate((X, Y), axis=1).shape)
| 28 | 43 | 0.657143 | 28 | 140 | 3.285714 | 0.464286 | 0.173913 | 0.282609 | 0.304348 | 0.847826 | 0.521739 | 0 | 0 | 0 | 0 | 0 | 0.047619 | 0.1 | 140 | 4 | 44 | 35 | 0.68254 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | null | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
0f4b31c8531f7c88f1321c598a94b55082e1e483 | 4,124 | py | Python | code/Chp3/03_mlr_cofounding.py | nathanbraun/BAP | 0aa549dd1da4c4cb545d8929197684aaad77739e | [
"MIT"
] | 1 | 2021-07-01T06:19:44.000Z | 2021-07-01T06:19:44.000Z | code/Chp3/03_mlr_cofounding.py | nathanbraun/BAP | 0aa549dd1da4c4cb545d8929197684aaad77739e | [
"MIT"
] | null | null | null | code/Chp3/03_mlr_cofounding.py | nathanbraun/BAP | 0aa549dd1da4c4cb545d8929197684aaad77739e | [
"MIT"
] | null | null | null | import pandas as pd
import scipy.stats as stats
from pandas import DataFrame, Series
import numpy as np
import matplotlib.pyplot as plt
import arviz as az
import pymc3 as pm
import seaborn as sns
################################################
## Confounding variables and redundant variables
################################################
np.random.seed(42)
N = 100
x_1 = np.random.normal(size=N)
x_2 = x_1 + np.random.normal(size=N, scale=1)
# x_2 = x_1 + np.random.normal(size=N, scale=0.01)
y = x_1 + np.random.normal(size=N)
X = np.vstack((x_1, x_2)).T
df = DataFrame(X, columns=['x0', 'x1'])
df['y'] = y
sns.pairplot(df)
# model 1: two independent variables x1 and x2
with pm.Model() as m_x1x2:
b0 = pm.Normal('b0', mu=0, sd=10)
b1 = pm.Normal('b1', mu=0, sd=10)
b2 = pm.Normal('b2', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b1 * X[:, 0] + b2 * X[:, 1]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x1x2 = pm.sample(2000)
# model 2: just x1
with pm.Model() as m_x1:
b0 = pm.Normal('b0', mu=0, sd=10)
b1 = pm.Normal('b1', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b1 * X[:, 0]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x1 = pm.sample(2000)
# model 3: just x2
with pm.Model() as m_x2:
b0 = pm.Normal('b0', mu=0, sd=10)
b2 = pm.Normal('b2', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b2 * X[:, 1]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x2 = pm.sample(2000)
az.plot_forest([trace_x1x2, trace_x1, trace_x2],
model_names=['m_x1x2', 'm_x1', 'm_x2'],
var_names=['b1', 'b2'],
combined=False, colors='cycle', figsize=(8, 3))
##################################################################
# repeating the code from above, but with a lower value of `scale`
##################################################################
np.random.seed(42)
N = 100
x_1 = np.random.normal(size=N)
# x_2 = x_1 + np.random.normal(size=N, scale=1)
x_2 = x_1 + np.random.normal(size=N, scale=0.01)
y = x_1 + np.random.normal(size=N)
X = np.vstack((x_1, x_2)).T
df = DataFrame(X, columns=['x0', 'x1'])
df['y'] = y
sns.pairplot(df)
with pm.Model() as model_red:
b0 = pm.Normal('b0', mu=0, sd=10)
b = pm.Normal('b', mu=0, sd=10, shape=2)
e = pm.HalfCauchy('e', 5)
mu = b0 + pm.math.dot(X, b)
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_red = pm.sample(2000)
az.plot_forest(trace_red, var_names=['b'], combined=True, figsize=(8, 2))
az.plot_pair(trace_red, var_names=['b'])
##########################
# Masking effect variables
##########################
np.random.seed(42)
N = 126
r = 0.8
x_1 = np.random.normal(size=N)
x_2 = np.random.normal(x_1, scale=(1 - r ** 2) ** 0.5)
y = np.random.normal(x_1 - x_2)
X = np.vstack((x_1, x_2)).T
df = DataFrame(X, columns=['x0', 'x1'])
df['y'] = y
sns.pairplot(df)
# model 1: two independent variables x1 and x2
with pm.Model() as m_x1x2:
b0 = pm.Normal('b0', mu=0, sd=10)
b1 = pm.Normal('b1', mu=0, sd=10)
b2 = pm.Normal('b2', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b1 * X[:, 0] + b2 * X[:, 1]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x1x2 = pm.sample(1000)
# model 2: just x1
with pm.Model() as m_x1:
b0 = pm.Normal('b0', mu=0, sd=10)
b1 = pm.Normal('b1', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b1 * X[:, 0]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x1 = pm.sample(1000)
# model 3: just x2
with pm.Model() as m_x2:
b0 = pm.Normal('b0', mu=0, sd=10)
b2 = pm.Normal('b2', mu=0, sd=10)
e = pm.HalfCauchy('e', 5)
mu = b0 + b2 * X[:, 1]
y_pred = pm.Normal('y_pred', mu=mu, sd=e, observed=y)
trace_x2 = pm.sample(1000)
# In[54]:
az.plot_forest([trace_x1x2, trace_x1, trace_x2],
model_names=['m_x1x2', 'm_x1', 'm_x2'],
var_names=['b1', 'b2'],
combined=True, colors='cycle', figsize=(8, 3))
plt.savefig('b11197_03_27.png', dpi=300, bbox_inches='tight')
| 25.300613 | 73 | 0.550679 | 731 | 4,124 | 3 | 0.151847 | 0.083903 | 0.03648 | 0.051072 | 0.799362 | 0.753306 | 0.738258 | 0.714546 | 0.705882 | 0.695394 | 0 | 0.080655 | 0.200291 | 4,124 | 162 | 74 | 25.45679 | 0.584294 | 0.096023 | 0 | 0.704082 | 0 | 0 | 0.047758 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.081633 | 0 | 0.081633 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
0f73105ddb8efd254bc30f9a31d790eb9c5f6970 | 152 | py | Python | plugins/komand/komand_komand/actions/__init__.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 46 | 2019-06-05T20:47:58.000Z | 2022-03-29T10:18:01.000Z | plugins/komand/komand_komand/actions/__init__.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 386 | 2019-06-07T20:20:39.000Z | 2022-03-30T17:35:01.000Z | plugins/komand/komand_komand/actions/__init__.py | lukaszlaszuk/insightconnect-plugins | 8c6ce323bfbb12c55f8b5a9c08975d25eb9f8892 | [
"MIT"
] | 43 | 2019-07-09T14:13:58.000Z | 2022-03-28T12:04:46.000Z | # GENERATED BY KOMAND SDK - DO NOT EDIT
from .run_asynchronously.action import RunAsynchronously
from .run_synchronously.action import RunSynchronously
| 38 | 56 | 0.848684 | 19 | 152 | 6.684211 | 0.789474 | 0.110236 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.111842 | 152 | 3 | 57 | 50.666667 | 0.940741 | 0.243421 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 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 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
0f75641044614b70c600ce37525215fb9098baf3 | 2,319 | py | Python | epytope/Data/pssms/smmpmbec/mat/C_06_02_9.py | christopher-mohr/epytope | 8ac9fe52c0b263bdb03235a5a6dffcb72012a4fd | [
"BSD-3-Clause"
] | 7 | 2021-02-01T18:11:28.000Z | 2022-01-31T19:14:07.000Z | epytope/Data/pssms/smmpmbec/mat/C_06_02_9.py | christopher-mohr/epytope | 8ac9fe52c0b263bdb03235a5a6dffcb72012a4fd | [
"BSD-3-Clause"
] | 22 | 2021-01-02T15:25:23.000Z | 2022-03-14T11:32:53.000Z | epytope/Data/pssms/smmpmbec/mat/C_06_02_9.py | christopher-mohr/epytope | 8ac9fe52c0b263bdb03235a5a6dffcb72012a4fd | [
"BSD-3-Clause"
] | 4 | 2021-05-28T08:50:38.000Z | 2022-03-14T11:45:32.000Z | C_06_02_9 = {0: {'A': -0.01, 'C': 0.227, 'E': 0.321, 'D': 0.291, 'G': 0.123, 'F': -0.636, 'I': 0.272, 'H': 0.263, 'K': 0.528, 'M': -0.521, 'L': 0.006, 'N': -0.379, 'Q': 0.185, 'P': 0.456, 'S': -0.3, 'R': 0.178, 'T': -0.142, 'W': -0.011, 'V': -0.231, 'Y': -0.62}, 1: {'A': -0.525, 'C': 0.513, 'E': 0.95, 'D': 1.031, 'G': -0.086, 'F': -0.135, 'I': -0.158, 'H': 0.161, 'K': -0.031, 'M': -0.148, 'L': 0.135, 'N': 0.421, 'Q': -0.251, 'P': 0.928, 'S': -0.697, 'R': -1.782, 'T': -0.151, 'W': 0.83, 'V': -0.392, 'Y': -0.613}, 2: {'A': 0.376, 'C': 0.052, 'E': 0.237, 'D': -0.258, 'G': 0.192, 'F': -0.636, 'I': 0.092, 'H': -0.439, 'K': 0.092, 'M': -0.392, 'L': 0.369, 'N': -0.442, 'Q': 0.311, 'P': 0.245, 'S': -0.143, 'R': -0.194, 'T': 0.238, 'W': 0.03, 'V': 0.648, 'Y': -0.377}, 3: {'A': -0.117, 'C': 0.063, 'E': -0.429, 'D': -0.328, 'G': -0.156, 'F': 0.349, 'I': 0.536, 'H': 0.205, 'K': 0.218, 'M': 0.119, 'L': 0.206, 'N': -0.198, 'Q': -0.356, 'P': -0.193, 'S': -0.065, 'R': 0.226, 'T': -0.164, 'W': 0.038, 'V': -0.066, 'Y': 0.111}, 4: {'A': 0.096, 'C': -0.094, 'E': 0.104, 'D': -0.002, 'G': 0.105, 'F': 0.071, 'I': 0.382, 'H': -0.595, 'K': -0.141, 'M': 0.144, 'L': 0.341, 'N': -0.114, 'Q': 0.046, 'P': 0.061, 'S': 0.036, 'R': -0.427, 'T': 0.062, 'W': -0.227, 'V': 0.461, 'Y': -0.309}, 5: {'A': -0.047, 'C': 0.188, 'E': 0.172, 'D': 0.32, 'G': -0.143, 'F': 0.284, 'I': -0.202, 'H': 0.188, 'K': -0.059, 'M': 0.008, 'L': -0.015, 'N': -0.179, 'Q': -0.165, 'P': -0.055, 'S': -0.276, 'R': -0.203, 'T': -0.074, 'W': 0.192, 'V': -0.268, 'Y': 0.333}, 6: {'A': 0.191, 'C': 0.134, 'E': 0.032, 'D': 0.114, 'G': 0.18, 'F': 0.32, 'I': 0.105, 'H': -0.155, 'K': -0.175, 'M': -0.139, 'L': -0.041, 'N': -0.012, 'Q': -0.272, 'P': -0.023, 'S': -0.069, 'R': -0.572, 'T': 0.045, 'W': 0.066, 'V': 0.13, 'Y': 0.142}, 7: {'A': 0.372, 'C': 0.046, 'E': -0.276, 'D': -0.229, 'G': 0.223, 'F': -0.017, 'I': -0.156, 'H': 0.023, 'K': 0.201, 'M': -0.361, 'L': -0.453, 'N': -0.039, 'Q': -0.037, 'P': 0.834, 'S': 0.085, 'R': 0.285, 'T': -0.039, 'W': -0.093, 'V': 0.061, 'Y': -0.43}, 8: {'A': -0.139, 'C': -0.006, 'E': -0.198, 'D': -0.083, 'G': 0.03, 'F': -0.036, 'I': -0.419, 'H': 0.486, 'K': 1.053, 'M': -0.499, 'L': -0.462, 'N': -0.082, 'Q': -0.028, 'P': 0.053, 'S': 0.089, 'R': 1.456, 'T': -0.201, 'W': -0.043, 'V': -0.641, 'Y': -0.331}, -1: {'con': 4.45257}} | 2,319 | 2,319 | 0.394567 | 557 | 2,319 | 1.637343 | 0.330341 | 0.019737 | 0.010965 | 0.013158 | 0.015351 | 0 | 0 | 0 | 0 | 0 | 0 | 0.374101 | 0.160845 | 2,319 | 1 | 2,319 | 2,319 | 0.094553 | 0 | 0 | 0 | 0 | 0 | 0.078879 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
0f887959941034cbf129bd213df2d82c32a794be | 27 | py | Python | spikebinning/__init__.py | wueric/spikebinning | d368d4885be5cbfe4c86f9003edef4cd2b748e98 | [
"MIT"
] | null | null | null | spikebinning/__init__.py | wueric/spikebinning | d368d4885be5cbfe4c86f9003edef4cd2b748e98 | [
"MIT"
] | null | null | null | spikebinning/__init__.py | wueric/spikebinning | d368d4885be5cbfe4c86f9003edef4cd2b748e98 | [
"MIT"
] | null | null | null | from .spikebinning import * | 27 | 27 | 0.814815 | 3 | 27 | 7.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | 27 | 1 | 27 | 27 | 0.916667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7e56e2502777dc1a449c88d3b42ec81b7b1bb80b | 70 | py | Python | privacy_evaluator/models/__init__.py | chen-yuxuan/privacy-evaluator | ed4852408108c3e6a01216af4183261945fd7e67 | [
"MIT"
] | 7 | 2021-04-10T15:01:19.000Z | 2022-02-08T14:45:21.000Z | privacy_evaluator/models/__init__.py | chen-yuxuan/privacy-evaluator | ed4852408108c3e6a01216af4183261945fd7e67 | [
"MIT"
] | 175 | 2021-04-13T08:32:27.000Z | 2021-08-30T09:44:51.000Z | privacy_evaluator/models/__init__.py | chen-yuxuan/privacy-evaluator | ed4852408108c3e6a01216af4183261945fd7e67 | [
"MIT"
] | 21 | 2021-04-13T08:03:36.000Z | 2021-10-05T15:35:01.000Z | """
Module providing models.
"""
from . import torch
from . import tf
| 11.666667 | 24 | 0.685714 | 9 | 70 | 5.333333 | 0.777778 | 0.416667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.185714 | 70 | 5 | 25 | 14 | 0.842105 | 0.342857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
0e322463f4284227ec433536d3d61facc47be1ad | 8,044 | py | Python | pyLMS8001/LMS8001_HLMIX.py | myriadrf/pyLMS8001 | 7d50b6078c1028ecc2be4bf123063190c028b337 | [
"Apache-2.0"
] | null | null | null | pyLMS8001/LMS8001_HLMIX.py | myriadrf/pyLMS8001 | 7d50b6078c1028ecc2be4bf123063190c028b337 | [
"Apache-2.0"
] | null | null | null | pyLMS8001/LMS8001_HLMIX.py | myriadrf/pyLMS8001 | 7d50b6078c1028ecc2be4bf123063190c028b337 | [
"Apache-2.0"
] | 1 | 2018-10-26T03:54:24.000Z | 2018-10-26T03:54:24.000Z |
from LMS8001_HLMIX_CFG import *
class LMS8001_HLMIX(object):
def __init__(self, chip, channel):
if channel not in ['A','B','C','D']:
raise ValueError("Channel must be ['A','B','C','D']")
self.chip = chip
self.channel = channel
self.CFG = { 0 : LMS8001_HLMIX_CFG(chip, channel, 0),
1 : LMS8001_HLMIX_CFG(chip, channel, 1),
2 : LMS8001_HLMIX_CFG(chip, channel, 2),
3 : LMS8001_HLMIX_CFG(chip, channel, 3)}
#
# Channel settings select signals from CHx_CONF_SEL0
#
@property
def CONF_SEL0_INTERNAL(self):
"""
Get the value written to CONF_SEL0_INTERNAL
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_INTERNAL"]
@CONF_SEL0_INTERNAL.setter
def CONF_SEL0_INTERNAL(self, value):
"""
Write the value to CONF_SEL0_INTERNAL
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_INTERNAL"] = value
@property
def CONF_SEL0_INVERT(self):
"""
Get the value written to CONF_SEL0_INVERT
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_INVERT"]
@CONF_SEL0_INVERT.setter
def CONF_SEL0_INVERT(self, value):
"""
Write the value to CONF_SEL0_INVERT
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_INVERT"] = value
@property
def CONF_SEL0_MASK(self):
"""
Get the value written to CONF_SEL0_MASK
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_MASK<8:0>"]
@CONF_SEL0_MASK.setter
def CONF_SEL0_MASK(self, value):
"""
Write the value to CONF_SEL0_MASK
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL0"]["HLMIX"+self.channel+"_CONF_SEL0_MASK<8:0>"] = value
#
# Channel settings select signals from CHx_CONF_SEL1
#
@property
def CONF_SEL1_INTERNAL(self):
"""
Get the value written to CONF_SEL1_INTERNAL
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_INTERNAL"]
@CONF_SEL1_INTERNAL.setter
def CONF_SEL1_INTERNAL(self, value):
"""
Write the value to CONF_SEL1_INTERNAL
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_INTERNAL"] = value
@property
def CONF_SEL1_INVERT(self):
"""
Get the value written to CONF_SEL1_INVERT
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_INVERT"]
@CONF_SEL1_INVERT.setter
def CONF_SEL1_INVERT(self, value):
"""
Write the value to CONF_SEL1_INVERT
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_INVERT"] = value
@property
def CONF_SEL1_MASK(self):
"""
Get the value written to CONF_SEL1_MASK
"""
return self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_MASK<8:0>"]
@CONF_SEL1_MASK.setter
def CONF_SEL1_MASK(self, value):
"""
Write the value to CONF_SEL1_MASK
"""
self.chip["HLMIX"+self.channel+"_CONF_SEL1"]["HLMIX"+self.channel+"_CONF_SEL1_MASK<8:0>"] = value
#
# Channel settings select signals from CHx_LOSS_SEL0
#
@property
def LOSS_SEL0_INTERNAL(self):
"""
Get the value written to LOSS_SEL0_INTERNAL
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_INTERNAL"]
@LOSS_SEL0_INTERNAL.setter
def LOSS_SEL0_INTERNAL(self, value):
"""
Write the value to LOSS_SEL0_INTERNAL
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_INTERNAL"] = value
@property
def LOSS_SEL0_INVERT(self):
"""
Get the value written to LOSS_SEL0_INVERT
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_INVERT"]
@LOSS_SEL0_INVERT.setter
def LOSS_SEL0_INVERT(self, value):
"""
Write the value to LOSS_SEL0_INVERT
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_INVERT"] = value
@property
def LOSS_SEL0_MASK(self):
"""
Get the value written to LOSS_SEL0_MASK
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_MASK<8:0>"]
@LOSS_SEL0_MASK.setter
def LOSS_SEL0_MASK(self, value):
"""
Write the value to LOSS_SEL0_MASK
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL0"]["HLMIX"+self.channel+"_LOSS_SEL0_MASK<8:0>"] = value
#
# Channel settings select signals from CHx_LOSS_SEL1
#
@property
def LOSS_SEL1_INTERNAL(self):
"""
Get the value written to LOSS_SEL1_INTERNAL
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_INTERNAL"]
@LOSS_SEL1_INTERNAL.setter
def LOSS_SEL1_INTERNAL(self, value):
"""
Write the value to LOSS_SEL1_INTERNAL
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_INTERNAL"] = value
@property
def LOSS_SEL1_INVERT(self):
"""
Get the value written to LOSS_SEL1_INVERT
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_INVERT"]
@LOSS_SEL1_INVERT.setter
def LOSS_SEL1_INVERT(self, value):
"""
Write the value to LOSS_SEL1_INVERT
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_INVERT"] = value
@property
def LOSS_SEL1_MASK(self):
"""
Get the value written to LOSS_SEL1_MASK
"""
return self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_MASK<8:0>"]
@LOSS_SEL1_MASK.setter
def LOSS_SEL1_MASK(self, value):
"""
Write the value to LOSS_SEL1_MASK
"""
self.chip["HLMIX"+self.channel+"_LOSS_SEL1"]["HLMIX"+self.channel+"_LOSS_SEL1_MASK<8:0>"] = value
#
# HLMIXx_INT_SEL
#
@property
def LOSS_INT_SEL(self):
"""
Get the value written to LOSS_INT_SEL
"""
return self.chip["HLMIX"+self.channel+"_INT_SEL"]["HLMIX"+self.channel+"_LOSS_INT_SEL<1:0>"]
@LOSS_INT_SEL.setter
def LOSS_INT_SEL(self, value):
"""
Write the value to LOSS_INT_SEL
"""
self.chip["HLMIX"+self.channel+"_INT_SEL"]["HLMIX"+self.channel+"_LOSS_INT_SEL<1:0>"] = value
@property
def CONF_INT_SEL(self):
"""
Get the value written to CONF_INT_SEL
"""
return self.chip["HLMIX"+self.channel+"_INT_SEL"]["HLMIX"+self.channel+"_CONF_INT_SEL<1:0>"]
@CONF_INT_SEL.setter
def CONF_INT_SEL(self, value):
"""
Write the value to CONF_INT_SEL
"""
self.chip["HLMIX"+self.channel+"_INT_SEL"]["HLMIX"+self.channel+"_CONF_INT_SEL<1:0>"] = value
#
# Readback values
#
@property
def VGCAS(self):
return self.chip["HLMIX"+self.channel+"_CONFIG_RB"]["HLMIX"+self.channel+"_VGCAS_RB<6:0>"]
@property
def ICT_BIAS(self):
return self.chip["HLMIX"+self.channel+"_CONFIG_RB"]["HLMIX"+self.channel+"_ICT_BIAS_RB<4:0>"]
@property
def BIAS_PD(self):
return self.chip["HLMIX"+self.channel+"_CONFIG_RB"]["HLMIX"+self.channel+"_BIAS_PD_RB"]
@property
def LOBUF_PD(self):
return self.chip["HLMIX"+self.channel+"_CONFIG_RB"]["HLMIX"+self.channel+"_LOBUF_PD_RB"]
@property
def MIXLOSS(self):
return self.chip["HLMIX"+self.channel+"_LOSS_RB"]["HLMIX"+self.channel+"_MIXLOSS_RB<3:0>"]
| 31.057915 | 113 | 0.621954 | 1,051 | 8,044 | 4.44529 | 0.059943 | 0.157748 | 0.226027 | 0.120077 | 0.855308 | 0.765625 | 0.765625 | 0.729452 | 0.472603 | 0.472603 | 0 | 0.028497 | 0.240925 | 8,044 | 258 | 114 | 31.178295 | 0.736652 | 0.162979 | 0 | 0.172727 | 0 | 0 | 0.210483 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.309091 | false | 0 | 0.009091 | 0.045455 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 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 | 6 |
0e6fb055e333c79d0903132e382740fc8901d1ff | 9 | py | Python | libuvs/__init__.py | kouritron/uvs | 42a4241445360fd64fc09f39fb9a4b5e596d622c | [
"BSD-3-Clause"
] | 1 | 2022-01-09T11:20:22.000Z | 2022-01-09T11:20:22.000Z | libuvs/__init__.py | kouritron/uvs | 42a4241445360fd64fc09f39fb9a4b5e596d622c | [
"BSD-3-Clause"
] | 3 | 2021-12-20T03:35:32.000Z | 2021-12-20T03:38:49.000Z | librf/__init__.py | kouritron/redfile | d235445261c0f864f467f39b15fa6e534ea45001 | [
"BSD-3-Clause"
] | null | null | null |
# hi
| 1.5 | 4 | 0.222222 | 1 | 9 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | 9 | 5 | 5 | 1.8 | 0.666667 | 0.222222 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
7eb84a5abc8e1cf7c3a62556314d71eb6100df28 | 312 | py | Python | src/livecoding/__init__.py | ashwoods/python-qt-live-coding | b87e6fed021c5a9af72dee3b7b32f9c799816b8e | [
"MIT"
] | 37 | 2018-07-08T04:53:12.000Z | 2022-03-17T07:33:21.000Z | src/livecoding/__init__.py | ashwoods/python-qt-live-coding | b87e6fed021c5a9af72dee3b7b32f9c799816b8e | [
"MIT"
] | 2 | 2020-01-07T22:03:29.000Z | 2020-09-28T12:15:57.000Z | src/livecoding/__init__.py | ashwoods/python-qt-live-coding | b87e6fed021c5a9af72dee3b7b32f9c799816b8e | [
"MIT"
] | 6 | 2020-02-12T18:55:13.000Z | 2021-12-31T03:54:40.000Z | # -*- coding: utf-8 -*-
from .register_qml_types import register_types # noqa: F401
from .pythonreloader import PythonReloader # noqa: F401
from .moduleloader import recursively_register_types # noqa: F401
from .filewatcher import FileWatcher # noqa: F401
from .gui import start_livecoding_gui # noqa: F401
| 44.571429 | 66 | 0.778846 | 40 | 312 | 5.9 | 0.425 | 0.169492 | 0.20339 | 0.177966 | 0.211864 | 0 | 0 | 0 | 0 | 0 | 0 | 0.059925 | 0.144231 | 312 | 6 | 67 | 52 | 0.82397 | 0.24359 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7d0728c1506cdcb610f3952d6941d9f3577878f2 | 137 | py | Python | test11.py | JarkJiao/Python_learning_TestCase | cc77a7a20b01e230e0edd818532570a7d8853b03 | [
"MIT"
] | null | null | null | test11.py | JarkJiao/Python_learning_TestCase | cc77a7a20b01e230e0edd818532570a7d8853b03 | [
"MIT"
] | null | null | null | test11.py | JarkJiao/Python_learning_TestCase | cc77a7a20b01e230e0edd818532570a7d8853b03 | [
"MIT"
] | null | null | null | f1 = 1
f2 = 1
for i in range(1,21):
print '%12ld %12ld' % (f1,f2)
if(i % 3 ==0):
print ' '
f1 = f1+f2
f2 = f1+f2 | 15.222222 | 33 | 0.430657 | 26 | 137 | 2.269231 | 0.5 | 0.20339 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.247059 | 0.379562 | 137 | 9 | 34 | 15.222222 | 0.447059 | 0 | 0 | 0 | 0 | 0 | 0.086957 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.25 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
7d332b0b0a8aedf6f4e36dcf5bd210ab23a084a6 | 37 | py | Python | fast_knn_nmt/custom_fairseq/tasks/__init__.py | Crazy-Chick/fast-knn-nmt | 7336bbe0be1240e70d3c3ac71c4e7cfb4f4ea4ff | [
"Apache-2.0"
] | 22 | 2021-05-31T15:14:37.000Z | 2022-03-18T06:26:21.000Z | fast_knn_nmt/custom_fairseq/tasks/__init__.py | Crazy-Chick/fast-knn-nmt | 7336bbe0be1240e70d3c3ac71c4e7cfb4f4ea4ff | [
"Apache-2.0"
] | 3 | 2021-10-06T09:54:03.000Z | 2021-10-13T12:11:53.000Z | fast_knn_nmt/custom_fairseq/tasks/__init__.py | Crazy-Chick/fast-knn-nmt | 7336bbe0be1240e70d3c3ac71c4e7cfb4f4ea4ff | [
"Apache-2.0"
] | 4 | 2021-06-02T16:12:02.000Z | 2022-02-28T12:18:24.000Z | from .knmt_task import KNNNMTDataset
| 18.5 | 36 | 0.864865 | 5 | 37 | 6.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.108108 | 37 | 1 | 37 | 37 | 0.939394 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7d41cec3fadbf4f36f7f1de1c47a1db8d8e053ad | 40 | py | Python | kerastuner/engine/oracle.py | haifeng-jin/kt-legacy | 15686b5e2d25b7094134d68956b2edce5dffa7a0 | [
"Apache-2.0"
] | 1 | 2022-03-29T21:49:22.000Z | 2022-03-29T21:49:22.000Z | kerastuner/engine/oracle.py | haifeng-jin/kt-legacy | 15686b5e2d25b7094134d68956b2edce5dffa7a0 | [
"Apache-2.0"
] | null | null | null | kerastuner/engine/oracle.py | haifeng-jin/kt-legacy | 15686b5e2d25b7094134d68956b2edce5dffa7a0 | [
"Apache-2.0"
] | 1 | 2022-02-14T18:57:19.000Z | 2022-02-14T18:57:19.000Z | from keras_tuner.engine.oracle import *
| 20 | 39 | 0.825 | 6 | 40 | 5.333333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 40 | 1 | 40 | 40 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
7d426c39967c1137fcfaebd0a2b735f3a0916739 | 262 | py | Python | 72.py | lycantropos/Project-Euler | df6c5a7e118ddd3fe3c39f4b30ad57e7d3ea853b | [
"MIT"
] | null | null | null | 72.py | lycantropos/Project-Euler | df6c5a7e118ddd3fe3c39f4b30ad57e7d3ea853b | [
"MIT"
] | null | null | null | 72.py | lycantropos/Project-Euler | df6c5a7e118ddd3fe3c39f4b30ad57e7d3ea853b | [
"MIT"
] | null | null | null | from utils import phi
def reduced_proper_fractions_count(max_denominator: int) -> int:
return sum(map(phi, range(max_denominator, 1, -1)))
assert reduced_proper_fractions_count(8) == 21
assert reduced_proper_fractions_count(1_000_000) == 303_963_552_391
| 26.2 | 67 | 0.793893 | 41 | 262 | 4.682927 | 0.609756 | 0.203125 | 0.34375 | 0.421875 | 0.34375 | 0 | 0 | 0 | 0 | 0 | 0 | 0.103448 | 0.114504 | 262 | 9 | 68 | 29.111111 | 0.724138 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | 1 | 0.2 | false | 0 | 0.2 | 0.2 | 0.6 | 0 | 0 | 0 | 0 | null | 1 | 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 | 1 | 1 | 0 | 0 | 6 |
adf67de029354e0ac23c68a862c9c623cd516284 | 7,353 | py | Python | utils/utils_for_custom.py | glory20h/DistilW2V2 | 5befe2fae857165d8f8e9e13596fa553e7aa4d6f | [
"Apache-2.0"
] | 5 | 2021-12-17T13:09:57.000Z | 2022-01-03T07:12:55.000Z | utils/utils_for_custom.py | glory20h/DistilW2V2 | 5befe2fae857165d8f8e9e13596fa553e7aa4d6f | [
"Apache-2.0"
] | null | null | null | utils/utils_for_custom.py | glory20h/DistilW2V2 | 5befe2fae857165d8f8e9e13596fa553e7aa4d6f | [
"Apache-2.0"
] | null | null | null | from argparse import Namespace
import contextlib
import os
import yaml
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dataclasses import dataclass, field
from omegaconf import MISSING, II, open_dict
from typing import Any, Optional
from datetime import datetime
from pytz import timezone
from fairseq import checkpoint_utils, tasks, utils
from fairseq.dataclass import FairseqDataclass
from fairseq.dataclass.utils import convert_namespace_to_omegaconf
from fairseq.tasks import FairseqTask
from fairseq.models import (
BaseFairseqModel,
FairseqEncoder,
FairseqEncoderDecoderModel,
FairseqIncrementalDecoder,
register_model,
)
from fairseq.models.wav2vec.wav2vec2 import MASKING_DISTRIBUTION_CHOICES
from fairseq.modules import (
LayerNorm,
PositionalEmbedding,
TransformerDecoderLayer,
)
from modules.Wav2Vec2Model import Wav2Vec2Config
from modules.CustomWav2Vec2Model import CustomWav2Vec2Config
def convert_dict_to_config(cfg):
# Input : cfg; Config for wav2vec2 model
config = Wav2Vec2Config()
conv_layer_config = config.conv_layer_setting
encoder_config = config.encoder_setting
encoder_layer_config = encoder_config.layer_setting
# Feature Extractor Config
conv_layer_config.extractor_mode = cfg.extractor_mode
conv_layer_config.conv_feature_layers = cfg.conv_feature_layers
conv_layer_config.conv_bias = cfg.conv_bias
conv_layer_config.conv_dropout = 0.0 # by default
# Encoder Layer each Config
encoder_layer_config.encoder_embed_dim = cfg.encoder_embed_dim
encoder_layer_config.encoder_ffn_embed_dim = cfg.encoder_ffn_embed_dim
encoder_layer_config.encoder_attention_heads = cfg.encoder_attention_heads
encoder_layer_config.dropout = cfg.dropout
encoder_layer_config.attention_dropout = cfg.attention_dropout
encoder_layer_config.activation_dropout = cfg.activation_dropout
encoder_layer_config.activation_fn = cfg.activation_fn
encoder_layer_config.layer_norm_first = cfg.layer_norm_first
# Encoder Config
encoder_config.layer_setting = encoder_layer_config
encoder_config.encoder_layers = cfg.encoder_layers
encoder_config.conv_pos = cfg.conv_pos
encoder_config.conv_pos_groups = cfg.conv_pos_groups
encoder_config.encoder_layerdrop = cfg.encoder_layerdrop
# Wav2vec2 Model Config
config.conv_layer_setting = conv_layer_config
config.encoder_setting = encoder_config
config.dropout_input = cfg.dropout_input
config.dropout_features = cfg.dropout_features
config.final_dim = cfg.final_dim
config.logit_temp = cfg.logit_temp
config.quantize_targets = cfg.quantize_targets
config.quantize_input = cfg.quantize_input
config.same_quantizer = cfg.same_quantizer
config.target_glu = cfg.target_glu
config.feature_grad_mult = cfg.feature_grad_mult
config.quantizer_depth = cfg.quantizer_depth
config.quantizer_factor = cfg.quantizer_factor
config.latent_vars = cfg.latent_vars
config.latent_groups = cfg.latent_groups
config.latent_dim = cfg.latent_dim
config.mask_length = cfg.mask_length
config.mask_prob = cfg.mask_prob
config.mask_selection = cfg.mask_selection
config.mask_other = cfg.mask_other
config.no_mask_overlap = cfg.no_mask_overlap
config.mask_channel_length = cfg.mask_channel_length
config.mask_min_space = cfg.mask_min_space
config.mask_channel_prob = cfg.mask_channel_prob
config.mask_channel_before = cfg.mask_channel_before
config.mask_channel_selection = cfg.mask_channel_selection
config.mask_channel_other = cfg.mask_channel_other
config.no_mask_channel_overlap = cfg.no_mask_channel_overlap
config.mask_channel_min_space = cfg.mask_channel_min_space
config.num_negatives = cfg.num_negatives
config.negatives_from_everywhere = cfg.negatives_from_everywhere
config.cross_sample_negatives = cfg.cross_sample_negatives
config.codebook_negatives = cfg.codebook_negatives
config.latent_temp = cfg.latent_temp
return config
def convert_dict_to_custom_config(cfg):
# Input : cfg; Config for CustomWav2Vec2 model
config = CustomWav2Vec2Config()
conv_layer_config = config.conv_layer_setting
encoder_config = config.encoder_setting
encoder_layer_config = encoder_config.layer_setting
# Feature Extractor Config
conv_layer_config.extractor_mode = cfg.extractor_mode
conv_layer_config.conv_feature_layers = cfg.conv_feature_layers
conv_layer_config.conv_bias = cfg.conv_bias
conv_layer_config.conv_dropout = 0.0 # by default
# Encoder Layer each Config
encoder_layer_config.encoder_embed_dim = cfg.encoder_embed_dim
encoder_layer_config.encoder_ffn_embed_dim = cfg.encoder_ffn_embed_dim
encoder_layer_config.encoder_attention_heads = cfg.encoder_attention_heads
encoder_layer_config.dropout = cfg.dropout
encoder_layer_config.attention_dropout = cfg.attention_dropout
encoder_layer_config.activation_dropout = cfg.activation_dropout
encoder_layer_config.activation_fn = cfg.activation_fn
encoder_layer_config.layer_norm_first = cfg.layer_norm_first
# Encoder Config
encoder_config.layer_setting = encoder_layer_config
encoder_config.encoder_layers = cfg.encoder_layers
encoder_config.conv_pos = cfg.conv_pos
encoder_config.conv_pos_groups = cfg.conv_pos_groups
encoder_config.encoder_layerdrop = cfg.encoder_layerdrop
# Please define time-reduction layer explicitly in train.py
# Wav2vec2 Model Config
config.conv_layer_setting = conv_layer_config
config.encoder_setting = encoder_config
config.dropout_input = cfg.dropout_input
config.dropout_features = cfg.dropout_features
config.final_dim = cfg.final_dim
config.logit_temp = cfg.logit_temp
# config.quantize_targets = cfg.quantize_targets
# config.quantize_input = cfg.quantize_input
# config.same_quantizer = cfg.same_quantizer
config.target_glu = cfg.target_glu
config.feature_grad_mult = cfg.feature_grad_mult
# config.quantizer_depth = cfg.quantizer_depth
# config.quantizer_factor = cfg.quantizer_factor
# config.latent_vars = cfg.latent_vars
# config.latent_groups = cfg.latent_groups
# config.latent_dim = cfg.latent_dim
config.mask_length = cfg.mask_length
config.mask_prob = cfg.mask_prob
config.mask_selection = cfg.mask_selection
config.mask_other = cfg.mask_other
config.no_mask_overlap = cfg.no_mask_overlap
config.mask_channel_length = cfg.mask_channel_length
config.mask_min_space = cfg.mask_min_space
config.mask_channel_prob = cfg.mask_channel_prob
# config.mask_channel_before = cfg.mask_channel_before
config.mask_channel_selection = cfg.mask_channel_selection
config.mask_channel_other = cfg.mask_channel_other
config.no_mask_channel_overlap = cfg.no_mask_channel_overlap
config.mask_channel_min_space = cfg.mask_channel_min_space
# config.num_negatives = cfg.num_negatives
# config.negatives_from_everywhere = cfg.negatives_from_everywhere
# config.cross_sample_negatives = cfg.cross_sample_negatives
# config.codebook_negatives = cfg.codebook_negatives
config.latent_temp = cfg.latent_temp
return config | 41.542373 | 78 | 0.797362 | 974 | 7,353 | 5.628337 | 0.13655 | 0.06421 | 0.065669 | 0.045604 | 0.819044 | 0.819044 | 0.809559 | 0.809559 | 0.809559 | 0.809559 | 0 | 0.004319 | 0.149871 | 7,353 | 177 | 79 | 41.542373 | 0.87266 | 0.128655 | 0 | 0.622222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.014815 | false | 0 | 0.177778 | 0 | 0.207407 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
adfb5d93f62859821dca1c6c3647943f3cb4a981 | 2,033 | py | Python | app/tests/admins_tests/test_forms.py | njmhendrix/grand-challenge.org | 9bc36f5e26561a78bd405e8ea5e4c0f86c95f011 | [
"Apache-2.0"
] | 1 | 2021-02-09T10:30:44.000Z | 2021-02-09T10:30:44.000Z | app/tests/admins_tests/test_forms.py | njmhendrix/grand-challenge.org | 9bc36f5e26561a78bd405e8ea5e4c0f86c95f011 | [
"Apache-2.0"
] | null | null | null | app/tests/admins_tests/test_forms.py | njmhendrix/grand-challenge.org | 9bc36f5e26561a78bd405e8ea5e4c0f86c95f011 | [
"Apache-2.0"
] | null | null | null | import pytest
from django.core import mail
from grandchallenge.admins.forms import AdminsForm
from tests.factories import UserFactory
from tests.utils import get_view_for_user
@pytest.mark.django_db
def test_admins_add(client, two_challenge_sets):
user = UserFactory()
assert not two_challenge_sets.challenge_set_1.challenge.is_admin(user=user)
assert not two_challenge_sets.challenge_set_2.challenge.is_admin(user=user)
response = get_view_for_user(
viewname="admins:update",
client=client,
method=client.post,
challenge=two_challenge_sets.challenge_set_1.challenge,
data={"user": user.pk, "action": AdminsForm.ADD},
user=two_challenge_sets.challenge_set_1.admin,
)
assert response.status_code == 302
email = mail.outbox[-1]
assert (
two_challenge_sets.challenge_set_1.challenge.short_name
in email.subject
)
assert user.email in email.to
assert two_challenge_sets.challenge_set_1.challenge.is_admin(user=user)
assert not two_challenge_sets.challenge_set_2.challenge.is_admin(user=user)
@pytest.mark.django_db
def test_admins_remove(client, two_challenge_sets):
assert two_challenge_sets.challenge_set_1.challenge.is_admin(
user=two_challenge_sets.admin12
)
assert two_challenge_sets.challenge_set_2.challenge.is_admin(
user=two_challenge_sets.admin12
)
response = get_view_for_user(
viewname="admins:update",
client=client,
method=client.post,
challenge=two_challenge_sets.challenge_set_1.challenge,
data={
"user": two_challenge_sets.admin12.pk,
"action": AdminsForm.REMOVE,
},
user=two_challenge_sets.challenge_set_1.admin,
)
assert response.status_code == 302
assert not two_challenge_sets.challenge_set_1.challenge.is_admin(
user=two_challenge_sets.admin12
)
assert two_challenge_sets.challenge_set_2.challenge.is_admin(
user=two_challenge_sets.admin12
)
| 34.457627 | 79 | 0.733399 | 272 | 2,033 | 5.143382 | 0.198529 | 0.171551 | 0.228735 | 0.232309 | 0.766976 | 0.750536 | 0.750536 | 0.750536 | 0.671909 | 0.671909 | 0 | 0.018138 | 0.186424 | 2,033 | 58 | 80 | 35.051724 | 0.82769 | 0 | 0 | 0.45283 | 0 | 0 | 0.022627 | 0 | 0 | 0 | 0 | 0 | 0.226415 | 1 | 0.037736 | false | 0 | 0.09434 | 0 | 0.132075 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 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 | 6 |
bc328ff5d2604ce89b348b84f86fbe414f785289 | 33 | py | Python | module/src/breath_data/bd_acess_point/__init__.py | Joao-Pedro-MB/projeto-final-MC536 | 675197fc92ef59d6bc3abcebba36ad9ecd942a26 | [
"MIT"
] | null | null | null | module/src/breath_data/bd_acess_point/__init__.py | Joao-Pedro-MB/projeto-final-MC536 | 675197fc92ef59d6bc3abcebba36ad9ecd942a26 | [
"MIT"
] | 2 | 2021-11-05T20:37:58.000Z | 2021-11-19T00:39:41.000Z | module/src/breath_data/bd_acess_point/__init__.py | BReATH-Brazilian-Research/breath_data | 675197fc92ef59d6bc3abcebba36ad9ecd942a26 | [
"MIT"
] | null | null | null | from .service import BDAcessPoint | 33 | 33 | 0.878788 | 4 | 33 | 7.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.090909 | 33 | 1 | 33 | 33 | 0.966667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
bc3d80f8fdc295999d422120bec3102698a61161 | 463 | py | Python | qmla/exploration_strategies/__init__.py | flynnbr11/QMD | ac8cfe1603658ee9b916452f29b99460ee5e3d44 | [
"MIT"
] | 9 | 2021-01-08T12:49:01.000Z | 2021-12-29T06:59:32.000Z | qmla/exploration_strategies/__init__.py | flynnbr11/QMD | ac8cfe1603658ee9b916452f29b99460ee5e3d44 | [
"MIT"
] | 2 | 2021-02-22T20:42:25.000Z | 2021-02-22T22:22:59.000Z | qmla/exploration_strategies/__init__.py | flynnbr11/QMD | ac8cfe1603658ee9b916452f29b99460ee5e3d44 | [
"MIT"
] | 9 | 2021-02-15T14:18:48.000Z | 2021-12-17T04:02:07.000Z | from qmla.exploration_strategies.exploration_strategy import *
from qmla.exploration_strategies.template import *
from qmla.exploration_strategies.nv_centre_spin_characterisation import *
from qmla.exploration_strategies.lattice_sets import *
from qmla.exploration_strategies.genetic_algorithms import *
from qmla.exploration_strategies.open_systems import *
from qmla.exploration_strategies.demos import *
from qmla.exploration_strategies.thesis_demos import *
| 46.3 | 73 | 0.87689 | 56 | 463 | 6.964286 | 0.339286 | 0.164103 | 0.389744 | 0.594872 | 0.628205 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.071274 | 463 | 9 | 74 | 51.444444 | 0.906977 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
70d44e5480b0d659339633860d08267fbee40084 | 151 | py | Python | src/qtt/utilities/markup.py | VandersypenQutech/qtt | 94366c5a4a8fe1c14fc89a8129fca49ea36d16a0 | [
"MIT"
] | null | null | null | src/qtt/utilities/markup.py | VandersypenQutech/qtt | 94366c5a4a8fe1c14fc89a8129fca49ea36d16a0 | [
"MIT"
] | null | null | null | src/qtt/utilities/markup.py | VandersypenQutech/qtt | 94366c5a4a8fe1c14fc89a8129fca49ea36d16a0 | [
"MIT"
] | null | null | null | import keyword
raise DeprecationWarning(
'this modue has been deprecated. the functionality can be found at https://pypi.org/project/markup.py/')
| 30.2 | 108 | 0.774834 | 21 | 151 | 5.571429 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.139073 | 151 | 4 | 109 | 37.75 | 0.9 | 0 | 0 | 0 | 0 | 0.333333 | 0.668874 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 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 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
cb089767a69dbaaed76809299384ba1e1f93cb27 | 101 | py | Python | terrascript/icinga2/__init__.py | hugovk/python-terrascript | 08fe185904a70246822f5cfbdc9e64e9769ec494 | [
"BSD-2-Clause"
] | 507 | 2017-07-26T02:58:38.000Z | 2022-01-21T12:35:13.000Z | terrascript/icinga2/__init__.py | hugovk/python-terrascript | 08fe185904a70246822f5cfbdc9e64e9769ec494 | [
"BSD-2-Clause"
] | 135 | 2017-07-20T12:01:59.000Z | 2021-10-04T22:25:40.000Z | terrascript/icinga2/__init__.py | hugovk/python-terrascript | 08fe185904a70246822f5cfbdc9e64e9769ec494 | [
"BSD-2-Clause"
] | 81 | 2018-02-20T17:55:28.000Z | 2022-01-31T07:08:40.000Z | # terrascript/icinga2/__init__.py
import terrascript
class icinga2(terrascript.Provider):
pass
| 14.428571 | 36 | 0.792079 | 11 | 101 | 6.909091 | 0.727273 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.022727 | 0.128713 | 101 | 6 | 37 | 16.833333 | 0.840909 | 0.306931 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 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 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
cb308a33349e94caf40e300011834b955ba93c4c | 105 | py | Python | backend/project/apps/core/tests/conftest.py | Nikita-Boyarskikh/DreamSim | d2982f99646bedc8e956f4a2be282d777cc4f7fa | [
"MIT"
] | null | null | null | backend/project/apps/core/tests/conftest.py | Nikita-Boyarskikh/DreamSim | d2982f99646bedc8e956f4a2be282d777cc4f7fa | [
"MIT"
] | null | null | null | backend/project/apps/core/tests/conftest.py | Nikita-Boyarskikh/DreamSim | d2982f99646bedc8e956f4a2be282d777cc4f7fa | [
"MIT"
] | null | null | null | import pytest
from apps.core.tests.fixtures import *
pytest.register_assert_rewrite('lib.test.utils')
| 15 | 48 | 0.8 | 15 | 105 | 5.466667 | 0.866667 | 0.292683 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.095238 | 105 | 6 | 49 | 17.5 | 0.863158 | 0 | 0 | 0 | 0 | 0 | 0.133333 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0 | true | 0 | 0.666667 | 0 | 0.666667 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
cbcf40442cf7cc46c9783aa5fff03777a5d7a7fe | 254 | py | Python | src/collective/eeafaceted/z3ctable/setuphandlers.py | collective/collective.eeafaceted.z3ctable | e19c47a1e4ed96149e3e899f70c073ea82d86f0a | [
"BSD-3-Clause"
] | 1 | 2017-10-18T10:58:33.000Z | 2017-10-18T10:58:33.000Z | src/collective/eeafaceted/z3ctable/setuphandlers.py | collective/collective.eeafaceted.z3ctable | e19c47a1e4ed96149e3e899f70c073ea82d86f0a | [
"BSD-3-Clause"
] | 3 | 2020-04-30T17:55:09.000Z | 2020-12-16T17:19:02.000Z | src/collective/eeafaceted/z3ctable/setuphandlers.py | collective/collective.eeafaceted.z3ctable | e19c47a1e4ed96149e3e899f70c073ea82d86f0a | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
def isNotCurrentProfile(context):
return context.readDataFile("collectiveeeafacetedz3ctable_marker.txt") is None
def post_install(context):
"""Post install script"""
if isNotCurrentProfile(context):
return
| 21.166667 | 82 | 0.712598 | 25 | 254 | 7.16 | 0.68 | 0.290503 | 0.357542 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009479 | 0.169291 | 254 | 11 | 83 | 23.090909 | 0.838863 | 0.165354 | 0 | 0 | 0 | 0 | 0.18932 | 0.18932 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 0 | 0 | 0.2 | 0.8 | 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 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
cbd77a0a618c68e907d25d93bafd6e5c515ba800 | 16 | py | Python | ybw/s/__init__.py | you-bowen/ybwNB | 57cd8925657db807543685d044e3446fa221ad1d | [
"MIT"
] | 4 | 2020-12-27T16:18:54.000Z | 2021-04-04T02:19:16.000Z | ybw/s/__init__.py | you-bowen/ybwNB | 57cd8925657db807543685d044e3446fa221ad1d | [
"MIT"
] | null | null | null | ybw/s/__init__.py | you-bowen/ybwNB | 57cd8925657db807543685d044e3446fa221ad1d | [
"MIT"
] | null | null | null | from .s import * | 16 | 16 | 0.6875 | 3 | 16 | 3.666667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | 16 | 1 | 16 | 16 | 0.846154 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
cbe576b3bd4a81f063fc441d29271a64b88889ac | 10,543 | py | Python | tests/test_fieldpath.py | originalpkbims/subgrounds-pkbims | 03271135d985bc4a53129edb0cb2391555012270 | [
"Apache-2.0"
] | null | null | null | tests/test_fieldpath.py | originalpkbims/subgrounds-pkbims | 03271135d985bc4a53129edb0cb2391555012270 | [
"Apache-2.0"
] | null | null | null | tests/test_fieldpath.py | originalpkbims/subgrounds-pkbims | 03271135d985bc4a53129edb0cb2391555012270 | [
"Apache-2.0"
] | null | null | null | import unittest
from subgrounds.query import Argument, DataRequest, Document, InputValue, Query, Selection, VariableDefinition
from subgrounds.schema import TypeMeta, TypeRef
from subgrounds.subgraph import FieldPath, Subgraph
from subgrounds.subgrounds import Subgrounds
from tests.utils import schema
class TestQueryString(unittest.TestCase):
def setUp(self):
self.schema = schema()
self.subgraph = Subgraph("", self.schema)
def test_query_building_1(self):
expected = FieldPath(
self.subgraph,
TypeRef.Named('Query'),
TypeRef.Named('String'),
[
(
{
'first': 100,
'where': {
'reserveUSD_lt': 10
},
'orderBy': 'reserveUSD',
'orderDirection': 'desc'
},
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
),
(
None, TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))
)
]
)
pairs = self.subgraph.Query.pairs(
first=100,
where={'reserveUSD_lt': 10},
orderBy='reserveUSD',
orderDirection='desc'
)
query = pairs.id
FieldPath.test_mode = True
self.assertEqual(query, expected)
def test_query_building_2(self):
expected = [
FieldPath(
self.subgraph,
TypeRef.Named('Query'),
TypeRef.Named('String'),
[
(
{
'first': 100,
'where': {
'reserveUSD_lt': 10
},
'orderBy': 'reserveUSD',
'orderDirection': 'desc'
},
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
),
(
None, TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))
)
]
),
FieldPath(
self.subgraph,
TypeRef.Named('Query'),
TypeRef.Named('BigDecimal'),
[
(
{
'first': 100,
'where': {
'reserveUSD_lt': 10
},
'orderBy': 'reserveUSD',
'orderDirection': 'desc'
},
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
),
(
None, TypeMeta.FieldMeta('reserveUSD', '', [], TypeRef.Named('BigDecimal'))
)
]
)
]
query = self.subgraph.Query.pairs(
first=100,
where={'reserveUSD_lt': 10},
orderBy='reserveUSD',
orderDirection='desc',
selection=[
self.subgraph.Pair.id,
self.subgraph.Pair.reserveUSD
]
)
FieldPath.test_mode = True
self.assertEqual(query, expected)
def test_query_building_3(self):
expected = [
FieldPath(
self.subgraph,
TypeRef.Named('Query'),
TypeRef.Named('String'),
[
(
{
'first': 100,
'where': {
'reserveUSD_lt': 10
},
'orderBy': 'reserveUSD',
'orderDirection': 'desc'
},
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
),
(
None, TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))
)
]
),
FieldPath(
self.subgraph,
TypeRef.Named('Query'),
TypeRef.Named('BigDecimal'),
[
(
{
'first': 100,
'where': {
'reserveUSD_lt': 10
},
'orderBy': 'reserveUSD',
'orderDirection': 'desc'
},
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
),
(
None, TypeMeta.FieldMeta('reserveUSD', '', [], TypeRef.Named('BigDecimal'))
)
]
)
]
pairs = self.subgraph.Query.pairs(
first=100,
where={'reserveUSD_lt': 10},
orderBy='reserveUSD',
orderDirection='desc',
)
query = [
pairs.id,
pairs.reserveUSD
]
FieldPath.test_mode = True
self.assertEqual(query, expected)
class TestQueryString(unittest.TestCase):
def setUp(self):
self.schema = schema()
self.subgraph1 = Subgraph('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', self.schema)
self.subgraph2 = Subgraph('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v1', self.schema)
def test_mk_request_1(self):
expected = DataRequest.single_query('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
Query(selection=[
Selection(
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
alias='x7ecb1bc5fd9e0dcf',
arguments=[
Argument("first", InputValue.Int(10))
],
selection=[
Selection(TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))),
Selection(TypeMeta.FieldMeta('reserveUSD', '', [], TypeRef.Named('BigDecimal')))
]
)
])
)
app = Subgrounds()
pairs = self.subgraph1.Query.pairs(first=10)
req = app.mk_request([
pairs.id,
pairs.reserveUSD
])
self.assertEqual(req, expected)
def test_mk_request_2(self):
expected = DataRequest(documents=[
Document(
'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v1',
Query(selection=[
Selection(
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
alias='x7ecb1bc5fd9e0dcf',
arguments=[
Argument("first", InputValue.Int(10))
],
selection=[
Selection(TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))),
Selection(TypeMeta.FieldMeta('token0Id', '', [], TypeRef.Named('String')))
]
)
])
),
Document(
'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
Query(selection=[
Selection(
TypeMeta.FieldMeta('pairs', '', [
TypeMeta.ArgumentMeta('first', '', TypeRef.Named('Int'), None),
TypeMeta.ArgumentMeta('where', '', TypeRef.Named('Pair_filter'), None),
TypeMeta.ArgumentMeta('orderBy', '', TypeRef.Named('Pair_orderBy'), None),
TypeMeta.ArgumentMeta('orderDirection', '', TypeRef.Named('OrderDirection'), None),
], TypeRef.non_null_list('Pair')),
alias='x7ecb1bc5fd9e0dcf',
arguments=[
Argument("first", InputValue.Int(10))
],
selection=[
Selection(TypeMeta.FieldMeta('id', '', [], TypeRef.Named('String'))),
Selection(TypeMeta.FieldMeta('reserveUSD', '', [], TypeRef.Named('BigDecimal')))
]
)
])
)
])
pairs = self.subgraph1.Query.pairs(first=10)
Pair = self.subgraph2.Pair
Pair.token0Id = Pair.token0.id
self.subgraph2.Query.pairs(first=10).id,
self.subgraph2.Query.pairs.token0Id
app = Subgrounds()
req = app.mk_request([
pairs.id,
pairs.reserveUSD,
*self.subgraph2.Query.pairs(first=10, selection=[
self.subgraph2.Pair.id,
self.subgraph2.Pair.token0Id
]),
])
self.assertEqual(req, expected)
class TestData(unittest.TestCase):
def setUp(self):
self.sg = Subgrounds()
self.subgraph = self.sg.load_subgraph('https://api.thegraph.com/subgraphs/name/aave/protocol-v2')
def test_extract_data_1(self):
expected = [1, 2, 3, 4]
repays = self.subgraph.Query.repays(
orderBy=self.subgraph.Repay.timestamp,
orderDirection='desc',
first=100
)
fpath = repays.amount
data = {
'x84d7be5e0ed4ef8a': [
{'amount': 1},
{'amount': 2},
{'amount': 3},
{'amount': 4}
]
}
self.assertEqual(fpath.extract_data(data), expected)
| 31.948485 | 110 | 0.545101 | 903 | 10,543 | 6.291251 | 0.101883 | 0.111952 | 0.101391 | 0.032389 | 0.823799 | 0.819046 | 0.803556 | 0.785777 | 0.784193 | 0.726633 | 0 | 0.015451 | 0.300199 | 10,543 | 329 | 111 | 32.045593 | 0.754541 | 0 | 0 | 0.619048 | 0 | 0 | 0.158683 | 0 | 0 | 0 | 0 | 0 | 0.020408 | 1 | 0.030612 | false | 0 | 0.020408 | 0 | 0.061224 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
1dc9f15cce429be488d78402dd5057e6d8b3ea71 | 33 | py | Python | src/consul_vault_api/__init__.py | barskykd/py-consul-vault-api | f4c5d2615221a0c69d3de8a503e8c49a4b82b8c6 | [
"MIT"
] | null | null | null | src/consul_vault_api/__init__.py | barskykd/py-consul-vault-api | f4c5d2615221a0c69d3de8a503e8c49a4b82b8c6 | [
"MIT"
] | null | null | null | src/consul_vault_api/__init__.py | barskykd/py-consul-vault-api | f4c5d2615221a0c69d3de8a503e8c49a4b82b8c6 | [
"MIT"
] | null | null | null | from ._impl import ConsulClientV1 | 33 | 33 | 0.878788 | 4 | 33 | 7 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.033333 | 0.090909 | 33 | 1 | 33 | 33 | 0.9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3839efbc424cc58c1cb67ca1a723c589ccef8722 | 4,465 | py | Python | python/ora/test/test_parse_daytime.py | alexhsamuel/ora | 89358d9193d86fbc7752270f1e35ee6ddcdcd206 | [
"BSD-3-Clause"
] | 10 | 2018-03-03T02:02:19.000Z | 2020-04-02T22:47:55.000Z | python/ora/test/test_parse_daytime.py | alexhsamuel/ora | 89358d9193d86fbc7752270f1e35ee6ddcdcd206 | [
"BSD-3-Clause"
] | 13 | 2018-01-28T15:20:55.000Z | 2022-01-27T23:32:41.000Z | python/ora/test/test_parse_daytime.py | alexhsamuel/ora | 89358d9193d86fbc7752270f1e35ee6ddcdcd206 | [
"BSD-3-Clause"
] | null | null | null | import pytest
from ora import parse_daytime, Daytime
#-------------------------------------------------------------------------------
def test_hms():
assert parse_daytime("%H:%M:%S", "23:06:09") == Daytime(23, 6, 9)
assert parse_daytime("%H:%M:%S", "3:06:09" ) == Daytime( 3, 6, 9)
assert parse_daytime("%H:%M:%S", "03:06:09") == Daytime( 3, 6, 9)
assert parse_daytime("%H-%M=%S", "23-06=09") == Daytime(23, 6, 9)
assert parse_daytime("%H%M%S" , "230609" ) == Daytime(23, 6, 9)
assert parse_daytime("%M:%S:%H", "06:09:23") == Daytime(23, 6, 9)
assert parse_daytime("it is %H:%M:%S now", "it is 23:06:09 now") == Daytime(23, 6, 9)
assert parse_daytime("%H:%M:%S", "00:00:00") == Daytime( 0, 0, 0)
assert parse_daytime("%H:%M:%S", "23:59:59") == Daytime(23, 59, 59)
# Literal '%' in pattern.
assert parse_daytime("%H%M%S%%", "230609%" ) == Daytime(23, 6, 9)
def test_hm():
assert parse_daytime("%H:%M", "23:06") == Daytime(23, 6, 0)
def test_hms_fractional():
assert parse_daytime("%H:%M:%S", "23:06:09." ) == Daytime(23, 6, 9.0)
assert parse_daytime("%H:%M:%S", "23:06:09.0" ) == Daytime(23, 6, 9.0)
assert parse_daytime("%H:%M:%S", "23:06:09.0000000") == Daytime(23, 6, 9.0)
assert parse_daytime("%H:%M:%S", "23:06:09.125") == Daytime(23, 6, 9.125)
def test_hms_invalid():
with pytest.raises(ValueError):
parse_daytime("%H:M:%S", "24:00:00")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "102:00:00")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "23:60:05")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "23:00:60")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "99:99:99")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "233009")
with pytest.raises(ValueError):
parse_daytime("%H%M%S", "23:30:09")
with pytest.raises(ValueError):
parse_daytime("%H:%M", "23:30:09")
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "23:30")
# Missing digits.
with pytest.raises(ValueError):
parse_daytime("%H:%M:%S", "23:6:9")
with pytest.raises(ValueError):
parse_daytime("%H%M%S", "2369")
def test_usec():
# FIXME: %S consumes the frational part if we use '.'.
assert parse_daytime("%H:%M:%S/%f", "23:06:09/123456") == Daytime(23, 6, 9.123456)
assert parse_daytime("%H:%M:%S/%f", "23:06:09/1") == Daytime(23, 6, 9.1)
assert parse_daytime("%H:%M:%S/%f", "23:06:09/123") == Daytime(23, 6, 9.123)
def test_12hour():
assert parse_daytime("%I:%M", "1:00" ) == Daytime( 1, 0, 0)
assert parse_daytime("%I:%M", "11:00" ) == Daytime(11, 0, 0)
assert parse_daytime("%I:%M:%S", "11:23:45" ) == Daytime(11, 23, 45)
assert parse_daytime("%I:%M %p", "1:00 am" ) == Daytime( 1, 0, 0)
assert parse_daytime("%I:%M %p", "11:00 am" ) == Daytime(11, 0, 0)
assert parse_daytime("%I:%M %p", "1:00 AM" ) == Daytime( 1, 0, 0)
assert parse_daytime("%I:%M %p", "11:00 AM" ) == Daytime(11, 0, 0)
assert parse_daytime("it's %I:%M %p now", "it's 11:00 AM now") == Daytime(11, 0, 0)
assert parse_daytime("%I:%M %p", "1:00 pm" ) == Daytime(13, 0, 0)
assert parse_daytime("%I:%M %p", "11:00 pm" ) == Daytime(23, 0, 0)
assert parse_daytime("%I:%M %p", "1:00 PM" ) == Daytime(13, 0, 0)
assert parse_daytime("%I:%M %p", "11:00 PM" ) == Daytime(23, 0, 0)
assert parse_daytime("%I:%M %p", "12:00 AM" ) == Daytime( 0, 0, 0)
assert parse_daytime("%I:%M %p", "12:15 AM" ) == Daytime( 0, 15, 0)
assert parse_daytime("%I:%M %p", "1:15 AM" ) == Daytime( 1, 15, 0)
assert parse_daytime("%I:%M %p", "11:15 AM" ) == Daytime(11, 15, 0)
assert parse_daytime("%I:%M %p", "12:15 PM" ) == Daytime(12, 15, 0)
assert parse_daytime("%I:%M %p", "1:15 PM" ) == Daytime(13, 15, 0)
assert parse_daytime("%I:%M %p", "11:15 PM" ) == Daytime(23, 15, 0)
assert parse_daytime("%I:%M %p", "11:59 PM" ) == Daytime(23, 59, 0)
@pytest.mark.parametrize("fmt", (
"%H%M%.3S",
"%H:%M:%.3S",
"%.3C",
"%~.3C",
"%.4~C",
"%.5C",
"%I:%M:%.3S %p",
"%I:%M:%.3S %_p",
"%I:%M:%.3S %^p",
))
def test_parse_roundtrip(fmt):
y = Daytime(12, 30, 45.125)
str = format(y, fmt)
print(f"{fmt} → {str}")
assert parse_daytime(fmt, str) == y
| 39.866071 | 91 | 0.53841 | 733 | 4,465 | 3.196453 | 0.115962 | 0.261204 | 0.299616 | 0.161332 | 0.729407 | 0.711481 | 0.711481 | 0.684166 | 0.666667 | 0.536065 | 0 | 0.127576 | 0.206495 | 4,465 | 111 | 92 | 40.225225 | 0.533446 | 0.038522 | 0 | 0.130952 | 0 | 0 | 0.210637 | 0 | 0 | 0 | 0 | 0.009009 | 0.464286 | 1 | 0.083333 | false | 0 | 0.02381 | 0 | 0.107143 | 0.011905 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 1 | 1 | 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 | 6 |
384344eabef21550fd050af6d8a96a8e0f91de36 | 173 | py | Python | ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/anonymization/data/classes_and_methods/out_3.py | JetBrains-Research/ast-transformations | 0ab408af3275b520cc87a473f418c4b4dfcb0284 | [
"MIT"
] | 8 | 2021-01-19T21:15:54.000Z | 2022-02-23T19:16:25.000Z | ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/anonymization/data/classes_and_methods/out_3.py | JetBrains-Research/ast-transformations | 0ab408af3275b520cc87a473f418c4b4dfcb0284 | [
"MIT"
] | 4 | 2020-11-17T14:28:25.000Z | 2022-02-24T07:54:28.000Z | ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/anonymization/data/classes_and_methods/out_3.py | nbirillo/ast-transformations | 717706765a2da29087a0de768fc851698886dd65 | [
"MIT"
] | 1 | 2022-02-23T19:16:30.000Z | 2022-02-23T19:16:30.000Z | class c1:
def c1_f1(self):
c1_f1_v1, c1_f1_v2 = 1, 2
class c2(c1):
def c1_f1(self):
c1_f1_v1, c1_f1_v2 = 3, 4
(c1() if input() else c2()).c1_f1() | 15.727273 | 35 | 0.554913 | 36 | 173 | 2.361111 | 0.416667 | 0.329412 | 0.164706 | 0.211765 | 0.588235 | 0.588235 | 0.588235 | 0.588235 | 0.588235 | 0.588235 | 0 | 0.219512 | 0.289017 | 173 | 11 | 35 | 15.727273 | 0.471545 | 0 | 0 | 0.285714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.285714 | false | 0 | 0 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 1 | 0 | 1 | 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 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
0e079dc06b1192394d53cfd1a2533ed7a213cf2e | 31 | py | Python | practice.py | Astayonix/PythonBible | cab0bc77d17d6939fcf9527a387ad08b99d6f175 | [
"MIT"
] | null | null | null | practice.py | Astayonix/PythonBible | cab0bc77d17d6939fcf9527a387ad08b99d6f175 | [
"MIT"
] | null | null | null | practice.py | Astayonix/PythonBible | cab0bc77d17d6939fcf9527a387ad08b99d6f175 | [
"MIT"
] | null | null | null | print("Hello there everyone!")
| 15.5 | 30 | 0.741935 | 4 | 31 | 5.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.096774 | 31 | 1 | 31 | 31 | 0.821429 | 0 | 0 | 0 | 0 | 0 | 0.677419 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 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 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
0e08afa1110f670fd745f26ca31a06689edc033a | 134 | py | Python | space_game/events/update_events/UpdateStatefulsEvent.py | Iwomichu/probable-giggle | 2af5ed83a60d65ec9d509c217cb5fcb880d5dbcc | [
"MIT"
] | 1 | 2020-11-30T11:21:21.000Z | 2020-11-30T11:21:21.000Z | space_game/events/update_events/UpdateStatefulsEvent.py | Iwomichu/probable-giggle | 2af5ed83a60d65ec9d509c217cb5fcb880d5dbcc | [
"MIT"
] | 5 | 2020-11-03T16:46:49.000Z | 2021-01-24T14:29:24.000Z | space_game/events/update_events/UpdateStatefulsEvent.py | Iwomichu/probable-giggle | 2af5ed83a60d65ec9d509c217cb5fcb880d5dbcc | [
"MIT"
] | null | null | null | from dataclasses import dataclass
from space_game.events.Event import Event
@dataclass
class UpdateStatefulsEvent(Event):
pass
| 14.888889 | 41 | 0.813433 | 16 | 134 | 6.75 | 0.6875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.141791 | 134 | 8 | 42 | 16.75 | 0.93913 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.2 | 0.4 | 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 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
386d6b171351c05fd4e217683388c1f84cf7d300 | 33,869 | py | Python | src/JetRecognizer/JetRecognizerPreprocessing.py | albertinopadin/PlaneRecognizer | 399eddd8d58ec47219804f23cec1503b01ea6c4d | [
"MIT"
] | 1 | 2022-02-24T23:39:12.000Z | 2022-02-24T23:39:12.000Z | src/JetRecognizer/JetRecognizerPreprocessing.py | albertinopadin/PlaneRecognizer | 399eddd8d58ec47219804f23cec1503b01ea6c4d | [
"MIT"
] | null | null | null | src/JetRecognizer/JetRecognizerPreprocessing.py | albertinopadin/PlaneRecognizer | 399eddd8d58ec47219804f23cec1503b01ea6c4d | [
"MIT"
] | null | null | null | from Common.DL_FilePaths import FIGHTER_JET, IMG_SIZE, get_fighter_jet_dir
from ImagePreprocessing.ImagePreprocessing import *
from ImagePreprocessing.TrainTestSeparator import copy_images_to_train_validation_test, \
TRAIN_FOLDER_NAME, VALIDATION_FOLDER_NAME, TEST_FOLDER_NAME
from Common.TimerDecorator import timer
import numpy as np
from enum import Enum
class Label(Enum):
F22 = 'F-22'
F14 = 'F-14'
F15 = 'F-15'
F16 = 'F-16'
F18 = 'F-18'
F35 = 'F-35'
@timer
def preprocess_all_images(size=IMG_SIZE.IS_960):
img_directories = list()
for fighter in FIGHTER_JET:
fdir = get_fighter_jet_dir(fighter, size=size)
img_directories.append(fdir)
preprocess_images(img_directories)
def get_f22_preprocessed_images(size=IMG_SIZE.IS_960):
f22_preprocessed_folder = f'{get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)}/{PREPROCESSED_FOLDER_NAME}'
image_generator = load_images_in_dir_generator(f22_preprocessed_folder)
return image_generator
# def get_f22_images_as_pixel_values():
# print('Getting F-22 preprocessed images...')
# pp_start = time.time()
# image_generator = get_f22_preprocessed_images()
# pp_end = time.time()
# print(f'Took {pp_end - pp_start} time to get preprocessed images.')
#
# print('Normalizing pixels in F-22 images...')
# np_start = time.time()
# normalized_images = [normalize_pixels_in_img_obj(img) for img in image_generator]
# np_end = time.time()
# print(f'Took {np_end - np_start} time to get normalized pixel images.')
# return normalized_images
# --------------------- LOOP METHODS --------------------- #
@timer
def get_f22_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F22.value)
# TODO: Can't do a batch load like this because need to attach labels:
# @timer
# def get_non_f22_preprocessed_images_as_pixel_values():
# return [load_normalized_images_in_dir(f'{folder}/{PREPROCESSED_FOLDER_NAME}') for folder in NON_F22_IMAGE_FOLDERS]
@timer
def get_f14_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F14.value)
@timer
def get_f15_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F15.value)
@timer
def get_f16_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F16.value)
@timer
def get_f18_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F18.value)
@timer
def get_f35_preprocessed_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images(normalized_imgs, Label.F35.value)
# ----------- VALIDATION ----------- #
def get_normalized_imgs_from_dir(jet_dir, folder_name, label):
normalized_imgs = load_normalized_images_in_dir(f'{jet_dir}/{folder_name}')
return add_labels_to_images(normalized_imgs, label.value)
@timer
def get_f14_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F14)
@timer
def get_f15_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F15)
@timer
def get_f16_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F16)
@timer
def get_f18_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F18)
@timer
def get_f22_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F22)
@timer
def get_f35_validation_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_normalized_imgs_from_dir(jet_dir, VALIDATION_FOLDER_NAME, Label.F35)
# ----------- TEST ----------- #
@timer
def get_f14_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F14)
@timer
def get_f15_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F15)
@timer
def get_f16_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F16)
@timer
def get_f18_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F18)
@timer
def get_f22_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F22)
@timer
def get_f35_test_images_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_normalized_imgs_from_dir(jet_dir, TEST_FOLDER_NAME, Label.F35)
# --------------------- THREADED METHODS --------------------- #
@timer
def get_f22_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F22.value)
@timer
def get_f14_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F14.value)
@timer
def get_f15_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F15.value)
@timer
def get_f16_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F16.value)
@timer
def get_f18_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F18.value)
@timer
def get_f35_preprocessed_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{PREPROCESSED_FOLDER_NAME}')
return add_labels_to_images_threaded(normalized_imgs, Label.F35.value)
# ----------- VALIDATION ----------- #
def get_normalized_imgs_from_dir_threaded(jet_dir, folder_name, label):
normalized_imgs = load_normalized_images_in_dir_threaded(f'{jet_dir}/{folder_name}')
return add_labels_to_images_threaded(normalized_imgs, label.value)
@timer
def get_f22_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F22)
@timer
def get_f14_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F14)
@timer
def get_f15_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F15)
@timer
def get_f16_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F16)
@timer
def get_f18_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F18)
@timer
def get_f35_validation_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, VALIDATION_FOLDER_NAME, Label.F35)
# ----------- TEST ----------- #
@timer
def get_f22_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F22)
@timer
def get_f14_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F14)
@timer
def get_f15_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F15)
@timer
def get_f16_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F16)
@timer
def get_f18_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F18)
@timer
def get_f35_test_images_as_pixel_values_threaded(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_normalized_imgs_from_dir_threaded(jet_dir, TEST_FOLDER_NAME, Label.F35)
# --------------------- GENERATOR METHODS --------------------- #
def get_random_normalized_images_generator(jet_dir, folder_name, label):
normalized_img_generator = load_normalized_rand_images_in_dir_generator(f'{jet_dir}/{folder_name}')
return add_labels_to_images_generator(normalized_img_generator, label.value)
def get_f22_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
print(f'Getting F-22 preprocessed images from: {jet_dir}')
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F22)
def get_f14_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F14)
def get_f15_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F15)
def get_f16_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F16)
def get_f18_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F18)
def get_f35_preprocessed_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_images_generator(jet_dir, PREPROCESSED_FOLDER_NAME, Label.F35)
# --------------------- GET SINGLE RANDOM IMG --------------------- #
def get_random_normalized_image(jet_dir, folder_name, label):
normalized_img = load_random_normalized_image_in_dir(f'{jet_dir}/{folder_name}')
return add_image_label(normalized_img, label.value)
@timer
def get_random_f22_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F22)
@timer
def get_random_f14_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F14)
@timer
def get_random_f15_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F15)
@timer
def get_random_f16_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F16)
@timer
def get_random_f18_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F18)
@timer
def get_random_f35_validation_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_image(jet_dir, VALIDATION_FOLDER_NAME, Label.F35)
# ----------- TEST ----------- #
@timer
def get_random_f22_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F22)
@timer
def get_random_f14_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F14)
@timer
def get_random_f15_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F15)
@timer
def get_random_f16_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F16)
@timer
def get_random_f18_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F18)
@timer
def get_random_f35_test_image_as_pixel_values(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_image(jet_dir, TEST_FOLDER_NAME, Label.F35)
def get_random_preprocessed_fighter_images_as_pixel_values_generator(num_batches=1):
f22_gen = get_f22_preprocessed_images_as_pixel_values_generator()
f14_gen = get_f14_preprocessed_images_as_pixel_values_generator()
f15_gen = get_f15_preprocessed_images_as_pixel_values_generator()
f16_gen = get_f16_preprocessed_images_as_pixel_values_generator()
f18_gen = get_f18_preprocessed_images_as_pixel_values_generator()
f35_gen = get_f35_preprocessed_images_as_pixel_values_generator()
fighter_img_generator_list = [
f22_gen,
f14_gen,
f15_gen,
f16_gen,
f18_gen,
f35_gen
]
while True:
img_batch_list = []
for _ in range(num_batches):
img_list = [next(gen) for gen in fighter_img_generator_list]
img_list = [img for img in img_list if img is not None]
img_batch_list.extend(img_list)
if len(img_batch_list) == 0:
# TODO: Perhaps raise StopIteration here?
break
np.random.shuffle(img_batch_list)
yield img_batch_list
# --------------------- TRAIN --------------------- #
def get_f22_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
print(f'Getting F-22 preprocessed images from: {jet_dir}')
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F22)
def get_f14_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F14)
def get_f15_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F15)
def get_f16_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F16)
def get_f18_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F18)
def get_f35_train_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_images_generator(jet_dir, TRAIN_FOLDER_NAME, Label.F35)
# --------------------- VALIDATION --------------------- #
def get_f22_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F22)
def get_f14_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F14)
def get_f15_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F15)
def get_f16_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F16)
def get_f18_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F18)
def get_f35_validation_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_images_generator(jet_dir, VALIDATION_FOLDER_NAME, Label.F35)
# --------------------- TEST --------------------- #
def get_f22_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_22, size=size)
print(f'Getting F-22 preprocessed images from: {jet_dir}')
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F22)
def get_f14_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_14, size=size)
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F14)
def get_f15_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_15, size=size)
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F15)
def get_f16_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_16, size=size)
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F16)
def get_f18_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_18, size=size)
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F18)
def get_f35_test_images_as_pixel_values_generator(size=IMG_SIZE.IS_960):
jet_dir = get_fighter_jet_dir(FIGHTER_JET.F_35, size=size)
return get_random_normalized_images_generator(jet_dir, TEST_FOLDER_NAME, Label.F35)
@timer
def resize_fighter_images(from_size=IMG_SIZE.IS_1920, to_size=IMG_SIZE.IS_960):
for fighter in FIGHTER_JET:
from_dir = get_fighter_jet_dir(fighter, size=from_size)
resized_save_dir = get_fighter_jet_dir(fighter, size=to_size) + '/resized'
if not os.path.exists(resized_save_dir):
os.makedirs(resized_save_dir)
resize_images(source_dir=from_dir, save_dir=resized_save_dir, size=to_size.value)
preprocessed_save_dir = get_fighter_jet_dir(fighter, size=to_size) + '/preprocessed'
if not os.path.exists(preprocessed_save_dir):
os.makedirs(preprocessed_save_dir)
if to_size == IMG_SIZE.IS_960:
add_padding_to_images_in_dir(960, resized_save_dir, preprocessed_save_dir)
def get_all_fighter_img_dirs(size=IMG_SIZE.IS_960):
img_directories = []
for fighter in FIGHTER_JET:
fdir = get_fighter_jet_dir(fighter, size=size)
img_directories.append(fdir)
return img_directories
def create_train_validation_test_split():
train_valid_test_dirs = []
img_dirs = get_all_fighter_img_dirs()
for img_dir in img_dirs:
train_dir, valid_dir, test_dir = copy_images_to_train_validation_test(base_dir=img_dir,
source_dir=img_dir+f'/{PREPROCESSED_FOLDER_NAME}')
train_valid_test_dirs.append((train_dir, valid_dir, test_dir))
return train_valid_test_dirs
def shuffle_and_return_generator(num_batches, generator_list):
caught_exception = False
while True:
if caught_exception:
break
img_batch_list = []
for _ in range(num_batches):
try:
img_list = [next(gen) for gen in generator_list]
img_list = [img for img in img_list if img is not None]
img_batch_list.extend(img_list)
except StopIteration as e:
print("No more images; caught StopIteration")
caught_exception = True
break
if len(img_batch_list) == 0:
# TODO: Perhaps raise StopIteration here?
break
np.random.shuffle(img_batch_list)
yield img_batch_list
def get_random_train_fighter_images_as_pixel_values_generator(num_batches=1):
f22_gen = get_f22_train_images_as_pixel_values_generator()
f14_gen = get_f14_train_images_as_pixel_values_generator()
f15_gen = get_f15_train_images_as_pixel_values_generator()
f16_gen = get_f16_train_images_as_pixel_values_generator()
f18_gen = get_f18_train_images_as_pixel_values_generator()
f35_gen = get_f35_train_images_as_pixel_values_generator()
fighter_img_generator_list = [
f22_gen,
f14_gen,
f15_gen,
f16_gen,
f18_gen,
f35_gen
]
return shuffle_and_return_generator(num_batches, fighter_img_generator_list)
def get_random_validation_fighter_images_as_pixel_values_generator(num_batches=1):
f22_gen = get_f22_validation_images_as_pixel_values_generator()
f14_gen = get_f14_validation_images_as_pixel_values_generator()
f15_gen = get_f15_validation_images_as_pixel_values_generator()
f16_gen = get_f16_validation_images_as_pixel_values_generator()
f18_gen = get_f18_validation_images_as_pixel_values_generator()
f35_gen = get_f35_validation_images_as_pixel_values_generator()
fighter_img_generator_list = [
f22_gen,
f14_gen,
f15_gen,
f16_gen,
f18_gen,
f35_gen
]
return shuffle_and_return_generator(num_batches, fighter_img_generator_list)
def get_random_test_fighter_images_as_pixel_values_generator(num_batches=1):
f22_gen = get_f22_test_images_as_pixel_values_generator()
f14_gen = get_f14_test_images_as_pixel_values_generator()
f15_gen = get_f15_test_images_as_pixel_values_generator()
f16_gen = get_f16_test_images_as_pixel_values_generator()
f18_gen = get_f18_test_images_as_pixel_values_generator()
f35_gen = get_f35_test_images_as_pixel_values_generator()
fighter_img_generator_list = [
f22_gen,
f14_gen,
f15_gen,
f16_gen,
f18_gen,
f35_gen
]
return shuffle_and_return_generator(num_batches, fighter_img_generator_list)
def get_jet_validation_images_as_pixel_values(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_f14_validation_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_15:
return get_f15_validation_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_16:
return get_f16_validation_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_18:
return get_f18_validation_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_22:
return get_f22_validation_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_35:
return get_f35_validation_images_as_pixel_values()
def get_jet_validation_images_as_pixel_values_threaded(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_f14_validation_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_15:
return get_f15_validation_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_16:
return get_f16_validation_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_18:
return get_f18_validation_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_22:
return get_f22_validation_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_35:
return get_f35_validation_images_as_pixel_values_threaded()
def get_jet_test_images_as_pixel_values(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_f14_test_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_15:
return get_f15_test_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_16:
return get_f16_test_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_18:
return get_f18_test_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_22:
return get_f22_test_images_as_pixel_values()
elif jet_type == FIGHTER_JET.F_35:
return get_f35_test_images_as_pixel_values()
def get_jet_test_images_as_pixel_values_threaded(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_f14_test_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_15:
return get_f15_test_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_16:
return get_f16_test_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_18:
return get_f18_test_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_22:
return get_f22_test_images_as_pixel_values_threaded()
elif jet_type == FIGHTER_JET.F_35:
return get_f35_test_images_as_pixel_values_threaded()
def get_random_jet_validation_image_as_pixel_values(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_random_f14_validation_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_15:
return get_random_f15_validation_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_16:
return get_random_f16_validation_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_18:
return get_random_f18_validation_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_22:
return get_random_f22_validation_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_35:
return get_random_f35_validation_image_as_pixel_values()
def get_random_jet_test_image_as_pixel_values(jet_type):
if jet_type == FIGHTER_JET.F_14:
return get_random_f14_test_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_15:
return get_random_f15_test_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_16:
return get_random_f16_test_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_18:
return get_random_f18_test_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_22:
return get_random_f22_test_image_as_pixel_values()
elif jet_type == FIGHTER_JET.F_35:
return get_random_f35_test_image_as_pixel_values()
def get_validation_fighter_images_as_pixel_values(jet_types=None, use_threads=False):
fighter_img_list = []
if jet_types is None: # Get all:
if use_threads:
f22 = get_f22_validation_images_as_pixel_values_threaded()
f14 = get_f14_validation_images_as_pixel_values_threaded()
f15 = get_f15_validation_images_as_pixel_values_threaded()
f16 = get_f16_validation_images_as_pixel_values_threaded()
f18 = get_f18_validation_images_as_pixel_values_threaded()
f35 = get_f35_validation_images_as_pixel_values_threaded()
else:
f22 = get_f22_validation_images_as_pixel_values()
f14 = get_f14_validation_images_as_pixel_values()
f15 = get_f15_validation_images_as_pixel_values()
f16 = get_f16_validation_images_as_pixel_values()
f18 = get_f18_validation_images_as_pixel_values()
f35 = get_f35_validation_images_as_pixel_values()
fighter_img_list.extend(f14)
fighter_img_list.extend(f15)
fighter_img_list.extend(f16)
fighter_img_list.extend(f18)
fighter_img_list.extend(f22)
fighter_img_list.extend(f35)
else:
for t in FIGHTER_JET:
if t in jet_types:
# fighter_img_list.extend(get_jet_validation_images_as_pixel_values_threaded(t))
fighter_img_list.extend(get_jet_validation_images_as_pixel_values(t))
else:
# Nasty hack to make label encoder work properly:
# Basically just add single image of jet not in jet_types:
fighter_img_list.append(get_random_jet_validation_image_as_pixel_values(t))
return fighter_img_list
def get_test_fighter_images_as_pixel_values(jet_types=None, use_threads=False):
fighter_img_list = []
if jet_types is None: # Get all:
if use_threads:
f22 = get_f22_test_images_as_pixel_values_threaded()
f14 = get_f14_test_images_as_pixel_values_threaded()
f15 = get_f15_test_images_as_pixel_values_threaded()
f16 = get_f16_test_images_as_pixel_values_threaded()
f18 = get_f18_test_images_as_pixel_values_threaded()
f35 = get_f35_test_images_as_pixel_values_threaded()
else:
f22 = get_f22_test_images_as_pixel_values()
f14 = get_f14_test_images_as_pixel_values()
f15 = get_f15_test_images_as_pixel_values()
f16 = get_f16_test_images_as_pixel_values()
f18 = get_f18_test_images_as_pixel_values()
f35 = get_f35_test_images_as_pixel_values()
fighter_img_list.extend(f14)
fighter_img_list.extend(f15)
fighter_img_list.extend(f16)
fighter_img_list.extend(f18)
fighter_img_list.extend(f22)
fighter_img_list.extend(f35)
else:
for t in FIGHTER_JET:
if t in jet_types:
# fighter_img_list.extend(get_jet_test_images_as_pixel_values_threaded(t))
fighter_img_list.extend(get_jet_test_images_as_pixel_values(t))
else:
# Nasty hack to make label encoder work properly:
# Basically just add single image of jet not in jet_types:
fighter_img_list.append(get_random_jet_test_image_as_pixel_values(t))
return fighter_img_list
| 41.153098 | 128 | 0.776787 | 5,271 | 33,869 | 4.441282 | 0.029406 | 0.059974 | 0.097736 | 0.12012 | 0.920162 | 0.912516 | 0.896711 | 0.882358 | 0.81965 | 0.769885 | 0 | 0.039017 | 0.14187 | 33,869 | 822 | 129 | 41.203163 | 0.766446 | 0.05415 | 0 | 0.455497 | 0 | 0 | 0.02667 | 0.019604 | 0 | 0 | 0 | 0.001217 | 0 | 1 | 0.164049 | false | 0 | 0.010471 | 0 | 0.396161 | 0.006981 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 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 | 6 |
3872dd386dd9067f6febc9ba9c0a67fa194d8e9d | 71 | py | Python | lib/__init__.py | Joey61Liuyi/TAS | 19699f2a12c8c7ab09f9aef0562cd58ea79c2826 | [
"MIT"
] | null | null | null | lib/__init__.py | Joey61Liuyi/TAS | 19699f2a12c8c7ab09f9aef0562cd58ea79c2826 | [
"MIT"
] | null | null | null | lib/__init__.py | Joey61Liuyi/TAS | 19699f2a12c8c7ab09f9aef0562cd58ea79c2826 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# @Time : 2021/7/3 16:13
# @Author : LIU YI | 23.666667 | 27 | 0.492958 | 12 | 71 | 2.916667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.207547 | 0.253521 | 71 | 3 | 28 | 23.666667 | 0.45283 | 0.915493 | 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 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
2a2bf62400f59d133466b092802b3a3bbf560501 | 128 | py | Python | matchzoo/generators/__init__.py | JacobPolloreno/MatchZoo | e49d619a52b2e96b6f0e8e76164d76f623210198 | [
"Apache-2.0"
] | null | null | null | matchzoo/generators/__init__.py | JacobPolloreno/MatchZoo | e49d619a52b2e96b6f0e8e76164d76f623210198 | [
"Apache-2.0"
] | null | null | null | matchzoo/generators/__init__.py | JacobPolloreno/MatchZoo | e49d619a52b2e96b6f0e8e76164d76f623210198 | [
"Apache-2.0"
] | null | null | null | from .point_generator import PointGenerator
from .pair_generator import PairGenerator
from .list_generator import ListGenerator
| 32 | 43 | 0.882813 | 15 | 128 | 7.333333 | 0.6 | 0.409091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.09375 | 128 | 3 | 44 | 42.666667 | 0.948276 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
2a5c5e796485feb1805bd938df78a5022345bd39 | 257 | py | Python | guillotina/tests/redis_session/settings.py | rboixaderg/guillotina | fcae65c2185222272f3b8fee4bc2754e81e0e983 | [
"BSD-2-Clause"
] | 173 | 2017-03-10T18:26:12.000Z | 2022-03-03T06:48:56.000Z | guillotina/tests/redis_session/settings.py | rboixaderg/guillotina | fcae65c2185222272f3b8fee4bc2754e81e0e983 | [
"BSD-2-Clause"
] | 921 | 2017-03-08T14:04:43.000Z | 2022-03-30T10:28:56.000Z | guillotina/tests/redis_session/settings.py | rboixaderg/guillotina | fcae65c2185222272f3b8fee4bc2754e81e0e983 | [
"BSD-2-Clause"
] | 60 | 2017-03-16T19:59:44.000Z | 2022-03-03T06:48:59.000Z | DEFAULT_SETTINGS = {
"applications": ["guillotina", "guillotina.contrib.redis_session"],
"auth_token_validators": [
"guillotina.auth.validators.JWTSessionValidator",
"guillotina.auth.validators.SaltedHashPasswordValidator",
],
}
| 32.125 | 71 | 0.712062 | 19 | 257 | 9.421053 | 0.631579 | 0.156425 | 0.268156 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.155642 | 257 | 7 | 72 | 36.714286 | 0.824885 | 0 | 0 | 0 | 0 | 0 | 0.680934 | 0.595331 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.142857 | 0 | 0 | 0 | 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 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 6 |
2a8d171799c69dd9abddc56ed3b7a77880b69b92 | 82 | py | Python | pyqecc/__init__.py | shim98a/pyqecc | 69965b4cab947718bf42adfaf79f63b25da61f66 | [
"MIT"
] | null | null | null | pyqecc/__init__.py | shim98a/pyqecc | 69965b4cab947718bf42adfaf79f63b25da61f66 | [
"MIT"
] | 12 | 2022-01-17T13:57:22.000Z | 2022-02-23T06:39:45.000Z | pyqecc/__init__.py | shim98a/pyqecc | 69965b4cab947718bf42adfaf79f63b25da61f66 | [
"MIT"
] | 2 | 2022-02-11T14:51:45.000Z | 2022-03-26T13:20:28.000Z | from .qecc import *
from .util import *
from .channel import *
from .sim import *
| 16.4 | 22 | 0.707317 | 12 | 82 | 4.833333 | 0.5 | 0.517241 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.195122 | 82 | 4 | 23 | 20.5 | 0.878788 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 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 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.