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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d5cbfe046bd1ac8daa44f547c895de99159a7d8 | 698 | py | Python | kabutobashi/domain/method/__init__.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | null | null | null | kabutobashi/domain/method/__init__.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | 65 | 2020-06-20T00:33:12.000Z | 2022-03-30T14:41:50.000Z | kabutobashi/domain/method/__init__.py | gsy0911/kabutobashi | 0be36a41333c3fd0cb59b1d35edee7db4de4a989 | [
"MIT"
] | null | null | null | """
Method modules provide technical analysis for stock chart.
- technical analysis
- ADX
- BollingerBands
- Fitting
- Ichimoku
- MACD
- Momentum
- PsychoLogical
- SMA
- Stochastics
- other
- Basic: only used `parameterize`
"""
from .adx import ADX
from .basic import Basic
from .bollinger_bands import BollingerBands
from .fitting import Fitting
from .ichimoku import Ichimoku
from .industry_cat import IndustryCategories
from .macd import MACD
from .method import Method
from .momentum import Momentum
from .pct_change import PctChange
from .psycho_logical import PsychoLogical
from .sma import SMA
from .stochastics import Stochastics
from .volatility import Volatility
| 19.942857 | 58 | 0.777937 | 84 | 698 | 6.416667 | 0.416667 | 0.06308 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.170487 | 698 | 34 | 59 | 20.529412 | 0.930915 | 0.348138 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
19b5934addf9367ffc7cfc4bbb2f3ba54c91a35e | 505 | py | Python | src/matches/urls.py | codingforentrepreneurs/matchmaker-2 | c90a20a50d33f2492831426d042c526fb3c574bc | [
"MIT"
] | 80 | 2015-07-23T19:01:46.000Z | 2022-03-27T09:38:29.000Z | src/matches/urls.py | codingforentrepreneurs/matchmaker-2 | c90a20a50d33f2492831426d042c526fb3c574bc | [
"MIT"
] | 1 | 2018-09-19T19:13:25.000Z | 2018-09-24T20:09:26.000Z | src/matches/urls.py | codingforentrepreneurs/matchmaker-2 | c90a20a50d33f2492831426d042c526fb3c574bc | [
"MIT"
] | 56 | 2015-07-24T02:59:55.000Z | 2021-08-24T11:53:43.000Z | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^position/(?P<slug>[\w-]+)/$', 'matches.views.position_match_view', name='position_match_view_url'),
url(r'^employer/(?P<slug>[\w-]+)/$', 'matches.views.employer_match_view', name='employer_match_view_url'),
url(r'^location/(?P<slug>[\w-]+)/$', 'matches.views.location_match_view', name='location_match_view_url'),
]
| 38.846154 | 110 | 0.722772 | 73 | 505 | 4.794521 | 0.328767 | 0.154286 | 0.12 | 0.111429 | 0.245714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.089109 | 505 | 12 | 111 | 42.083333 | 0.76087 | 0 | 0 | 0 | 0 | 0 | 0.5 | 0.5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.444444 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
19cd97c0ea18ae1d488f76174d13032b7173ac84 | 251 | py | Python | output/models/nist_data/list_pkg/g_month/schema_instance/nistschema_sv_iv_list_g_month_max_length_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 1 | 2021-08-14T17:59:21.000Z | 2021-08-14T17:59:21.000Z | output/models/nist_data/list_pkg/g_month/schema_instance/nistschema_sv_iv_list_g_month_max_length_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 4 | 2020-02-12T21:30:44.000Z | 2020-04-15T20:06:46.000Z | output/models/nist_data/list_pkg/g_month/schema_instance/nistschema_sv_iv_list_g_month_max_length_2_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | null | null | null | from output.models.nist_data.list_pkg.g_month.schema_instance.nistschema_sv_iv_list_g_month_max_length_2_xsd.nistschema_sv_iv_list_g_month_max_length_2 import NistschemaSvIvListGMonthMaxLength2
__all__ = [
"NistschemaSvIvListGMonthMaxLength2",
]
| 41.833333 | 193 | 0.89243 | 34 | 251 | 5.852941 | 0.617647 | 0.090452 | 0.140704 | 0.180905 | 0.341709 | 0.341709 | 0.341709 | 0.341709 | 0.341709 | 0 | 0 | 0.016878 | 0.055777 | 251 | 5 | 194 | 50.2 | 0.822785 | 0 | 0 | 0 | 0 | 0 | 0.135458 | 0.135458 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 0 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
19ce7aec631c4f15665cf038dec7467247786028 | 183 | py | Python | Modules/Request/audiotest.py | code243031/StockAdvisorSystem | 1e85d184d97e2bf0d3617ecd60529bcb106c8d0e | [
"Unlicense"
] | null | null | null | Modules/Request/audiotest.py | code243031/StockAdvisorSystem | 1e85d184d97e2bf0d3617ecd60529bcb106c8d0e | [
"Unlicense"
] | 3 | 2020-08-26T08:34:09.000Z | 2021-02-22T03:19:04.000Z | Modules/Request/audiotest.py | code243031/StockAdvisorSystem | 1e85d184d97e2bf0d3617ecd60529bcb106c8d0e | [
"Unlicense"
] | null | null | null | import winsound as ws
def beepsound():
freq = 2000 # range : 37 ~ 32767
dur = 1000 # ms
ws.Beep(freq, dur) # winsound.Beep(frequency, duration)
print(beepsound()) | 22.875 | 59 | 0.628415 | 24 | 183 | 4.791667 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.109489 | 0.251366 | 183 | 8 | 60 | 22.875 | 0.729927 | 0.306011 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.166667 | 0 | 0.333333 | 0.166667 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
19d0605010a2de2c7400efa0883cfb32414e2074 | 137 | py | Python | iftest2/ipstatic.py | OneOfaKindGeek/mycode | bbb4391b333aaa1667314b76393f2102c05a2571 | [
"Apache-2.0"
] | null | null | null | iftest2/ipstatic.py | OneOfaKindGeek/mycode | bbb4391b333aaa1667314b76393f2102c05a2571 | [
"Apache-2.0"
] | null | null | null | iftest2/ipstatic.py | OneOfaKindGeek/mycode | bbb4391b333aaa1667314b76393f2102c05a2571 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
ipchk = "192.168.0.1"
# a string tests as True
if ipchk:
print("Looks like the IP address was set: " + ipchk)
| 19.571429 | 55 | 0.664234 | 25 | 137 | 3.64 | 0.92 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.081818 | 0.19708 | 137 | 6 | 56 | 22.833333 | 0.745455 | 0.321168 | 0 | 0 | 0 | 0 | 0.505495 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
19f72dba394c2bbc73c12a20229c7a09492d2494 | 243 | py | Python | task/twosum.py | dhaneeshgk/share_food | ee7549377abe0c6a47d88931226c3ba29a706c42 | [
"MIT"
] | 1 | 2018-05-30T11:42:26.000Z | 2018-05-30T11:42:26.000Z | task/twosum.py | dhaneeshgk/share_food | ee7549377abe0c6a47d88931226c3ba29a706c42 | [
"MIT"
] | null | null | null | task/twosum.py | dhaneeshgk/share_food | ee7549377abe0c6a47d88931226c3ba29a706c42 | [
"MIT"
] | null | null | null | num1=int(input("enter a num"))
num2=int(input("enter a num"))
if num1<0 and num2<0:
print("enter a positive number")
else:
sum=0
while(num1>0 and num2>0):
sum = num1+num2
print("the sum is",sum)
break
| 18.692308 | 36 | 0.576132 | 41 | 243 | 3.414634 | 0.463415 | 0.128571 | 0.185714 | 0.2 | 0.428571 | 0 | 0 | 0 | 0 | 0 | 0 | 0.074286 | 0.279835 | 243 | 12 | 37 | 20.25 | 0.725714 | 0 | 0 | 0 | 0 | 0 | 0.226337 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c20eba23debc37962753e11386ab495151572722 | 320 | py | Python | Algorithms/DynamicProgramming/longest-subsequence-such-that-difference-between-adjacents-is-one.py | Sangeerththan/pythonDSA | d126b3a7a8acc1e202107e20a21ed96fb4ab144e | [
"MIT"
] | 1 | 2021-09-12T20:40:37.000Z | 2021-09-12T20:40:37.000Z | Algorithms/DynamicProgramming/longest-subsequence-such-that-difference-between-adjacents-is-one.py | Sangeerththan/pythonDataStructure | d126b3a7a8acc1e202107e20a21ed96fb4ab144e | [
"MIT"
] | null | null | null | Algorithms/DynamicProgramming/longest-subsequence-such-that-difference-between-adjacents-is-one.py | Sangeerththan/pythonDataStructure | d126b3a7a8acc1e202107e20a21ed96fb4ab144e | [
"MIT"
] | null | null | null | def longestSubsequence(A, N):
L = [1]*N
hm = {}
for i in range(1,N):
if abs(A[i]-A[i-1]) == 1:
L[i] = 1 + L[i-1]
elif hm.get(A[i]+1,0) or hm.get(A[i]-1,0):
L[i] = 1+max(hm.get(A[i]+1,0), hm.get(A[i]-1,0))
hm[A[i]] = L[i]
return max(L)
A = [1, 2, 3, 4, 5, 3, 2]
N = len(A)
print(longestSubsequence(A, N))
| 22.857143 | 51 | 0.5 | 81 | 320 | 1.975309 | 0.308642 | 0.1 | 0.09375 | 0.175 | 0.2375 | 0.2375 | 0.125 | 0 | 0 | 0 | 0 | 0.086275 | 0.203125 | 320 | 13 | 52 | 24.615385 | 0.541176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0 | 0 | 0.153846 | 0.076923 | 0 | 0 | 1 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c23bc095190bd53dce89bf81da5842ea5fd81084 | 221 | py | Python | runserver.py | ramaneswaran/octo-spam | 8ce232632fec3e9bb03e4d7b4ab392604876871d | [
"Apache-2.0"
] | null | null | null | runserver.py | ramaneswaran/octo-spam | 8ce232632fec3e9bb03e4d7b4ab392604876871d | [
"Apache-2.0"
] | null | null | null | runserver.py | ramaneswaran/octo-spam | 8ce232632fec3e9bb03e4d7b4ab392604876871d | [
"Apache-2.0"
] | null | null | null | import yaml
import uvicorn
if __name__ == "__main__":
stream = open("config.yaml", "r")
cfg = yaml.load(stream, Loader=yaml.FullLoader)
uvicorn.run("main:app",reload=True,port=cfg['port'], host=cfg['host']) | 24.555556 | 74 | 0.669683 | 31 | 221 | 4.516129 | 0.645161 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.144796 | 221 | 9 | 74 | 24.555556 | 0.740741 | 0 | 0 | 0 | 0 | 0 | 0.162162 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
c23ffe7f808c91f9a9528e048e62d1f7fe6047bc | 297 | py | Python | tests/test_order_product.py | Tasari/Restaurant_system | bc0127e0060c54c17abb7aa78800da7bd5bc12cb | [
"MIT"
] | null | null | null | tests/test_order_product.py | Tasari/Restaurant_system | bc0127e0060c54c17abb7aa78800da7bd5bc12cb | [
"MIT"
] | null | null | null | tests/test_order_product.py | Tasari/Restaurant_system | bc0127e0060c54c17abb7aa78800da7bd5bc12cb | [
"MIT"
] | null | null | null | from tables.order_product import Order_Product
def test_order_product_creation():
'''
Tests valid creation of object from table
'''
order_product = Order_Product('HambUrger', 5)
assert order_product.amount == 5
assert order_product.ordered_product.name == 'Hamburger'
| 29.7 | 60 | 0.727273 | 37 | 297 | 5.567568 | 0.513514 | 0.407767 | 0.116505 | 0.184466 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008299 | 0.188552 | 297 | 10 | 61 | 29.7 | 0.846473 | 0.138047 | 0 | 0 | 0 | 0 | 0.074689 | 0 | 0 | 0 | 0 | 0 | 0.4 | 1 | 0.2 | false | 0 | 0.2 | 0 | 0.4 | 0 | 0 | 0 | 0 | null | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
c2464886eeb74509060cb50adacbd6e018a67b93 | 980 | py | Python | tests/test_train_valid_test_split.py | matthewconnell/PrepPy | de1dc48f6517277a4aade32b446c8c9b63e613f0 | [
"MIT"
] | 3 | 2020-03-14T19:22:59.000Z | 2021-06-25T04:35:58.000Z | tests/test_train_valid_test_split.py | matthewconnell/PrepPy | de1dc48f6517277a4aade32b446c8c9b63e613f0 | [
"MIT"
] | 66 | 2020-02-25T18:37:39.000Z | 2020-03-27T03:26:54.000Z | tests/test_train_valid_test_split.py | matthewconnell/PrepPy | de1dc48f6517277a4aade32b446c8c9b63e613f0 | [
"MIT"
] | null | null | null | from preppy524 import train_valid_test_split
import numpy as np
import pytest
# Check data input types and parameters
X, y = np.arange(16).reshape((8, 2)), list(range(8))
def test_train_test_valid_split():
"""
This script will test the output of the train_valid_test_split function
which splits dataframes into random train, validation and test subsets.
The proportion of the train set relative to the input data will be
equal to valid_size * (1 - test_size).
"""
X_train, X_valid, X_test, y_train, y_valid, y_test =\
train_valid_test_split.train_valid_test_split(X, y)
assert(len(X_train) == 4)
assert(len(X_valid) == 2)
assert(len(X_test) == 2)
def check_exception():
with pytest.raises(Exception):
train_valid_test_split.train_valid_test_split("test", y)
with pytest.raises(Exception):
train_valid_test_split.train_valid_test_split(X, "test")
test_train_test_valid_split()
check_exception()
| 25.128205 | 75 | 0.722449 | 154 | 980 | 4.305195 | 0.357143 | 0.120664 | 0.168929 | 0.229261 | 0.319759 | 0.250377 | 0.250377 | 0.250377 | 0.250377 | 0.190045 | 0 | 0.015056 | 0.186735 | 980 | 38 | 76 | 25.789474 | 0.816813 | 0.293878 | 0 | 0.117647 | 0 | 0 | 0.012048 | 0 | 0 | 0 | 0 | 0 | 0.176471 | 1 | 0.117647 | true | 0 | 0.176471 | 0 | 0.294118 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
dfb5bbec6afe4fa1c94203078bd16d6722b92fc7 | 5,338 | py | Python | src/utils/http_exception.py | fred-yu-2013/Elastos.Hive.Node | 1dcc9178c12efefc786bc653bacec50a1f79161b | [
"MIT"
] | 5 | 2020-11-18T09:14:24.000Z | 2021-08-17T13:55:49.000Z | src/utils/http_exception.py | fred-yu-2013/Elastos.Hive.Node | 1dcc9178c12efefc786bc653bacec50a1f79161b | [
"MIT"
] | 45 | 2020-11-09T03:40:53.000Z | 2021-11-02T08:43:49.000Z | src/utils/http_exception.py | fred-yu-2013/Elastos.Hive.Node | 1dcc9178c12efefc786bc653bacec50a1f79161b | [
"MIT"
] | 5 | 2021-01-25T16:25:59.000Z | 2021-09-23T20:18:12.000Z | # -*- coding: utf-8 -*-
"""
Http exceptions definition.
"""
import json
from bson import json_util
from flask import jsonify, request
class HiveException(Exception):
NO_INTERNAL_CODE = -1
def __init__(self, code, internal_code, msg):
self.code = code
self.internal_code = internal_code
self.msg = msg
def get_error_response(self):
return jsonify(self._get_error_dict()), self.code
def _get_error_dict(self):
error = {"message": self.msg}
if self.internal_code > 0:
error['internal_code'] = self.internal_code
return {"error": error}
@staticmethod
def get_success_response(data, is_download=False, is_code=False):
code = HiveException.__get_success_http_code()
if is_code:
# Support user-defined http status code.
assert type(data) is tuple and len(data) == 2
data, code = data[0], data[1]
json_data = data if is_download else (json.dumps(data, default=json_util.default) if data else '')
return json_data, code
@staticmethod
def __get_success_http_code():
codes = {
'GET': 200,
'PUT': 200,
'PATCH': 200,
'POST': 201,
'DELETE': 204,
}
assert request.method in codes
return codes[request.method]
def __str__(self):
return json.dumps(self._get_error_dict())
# BadRequestException
# TODO: refine default and INVALID_PARAMETER for more specific ones.
class BadRequestException(HiveException):
INVALID_PARAMETER = 1
BACKUP_IS_IN_PROCESSING = 2
def __init__(self, internal_code=INVALID_PARAMETER, msg='Invalid parameter'):
super().__init__(400, internal_code, msg)
class InvalidParameterException(BadRequestException):
def __init__(self, msg='Invalid parameter'):
super().__init__(super().INVALID_PARAMETER, msg=msg)
class BackupIsInProcessingException(BadRequestException):
def __init__(self, msg='Backup is in processing.'):
super().__init__(super().BACKUP_IS_IN_PROCESSING, msg=msg)
# UnauthorizedException
class UnauthorizedException(HiveException):
def __init__(self, msg='You are unauthorized to make this request.'):
super().__init__(401, super().NO_INTERNAL_CODE, msg)
# ForbiddenException
# TODO: remove for vault accessing because no need active before using vault.
class ForbiddenException(HiveException):
def __init__(self, msg='Forbidden.'):
super().__init__(403, super().NO_INTERNAL_CODE, msg)
# NotFoundException
class NotFoundException(HiveException):
VAULT_NOT_FOUND = 1
BACKUP_NOT_FOUND = 2
SCRIPT_NOT_FOUND = 3
COLLECTION_NOT_FOUND = 4
PRICE_PLAN_NOT_FOUND = 5
FILE_NOT_FOUND = 6
ORDER_NOT_FOUND = 7
RECEIPT_NOT_FOUND = 8
def __init__(self, internal_code=VAULT_NOT_FOUND, msg='The vault does not found or not activate.'):
super().__init__(404, internal_code, msg)
class VaultNotFoundException(NotFoundException):
def __init__(self, msg='The vault does not found.'):
super().__init__(internal_code=NotFoundException.VAULT_NOT_FOUND, msg=msg)
class BackupNotFoundException(NotFoundException):
def __init__(self, msg='The backup service does not found.'):
super().__init__(internal_code=NotFoundException.BACKUP_NOT_FOUND, msg=msg)
class ScriptNotFoundException(NotFoundException):
def __init__(self, msg='The script does not found.'):
super().__init__(internal_code=NotFoundException.SCRIPT_NOT_FOUND, msg=msg)
class CollectionNotFoundException(NotFoundException):
def __init__(self, msg='The collection does not found.'):
super().__init__(internal_code=NotFoundException.COLLECTION_NOT_FOUND, msg=msg)
class PricePlanNotFoundException(NotFoundException):
def __init__(self, msg='The price plan does not found.'):
super().__init__(internal_code=NotFoundException.PRICE_PLAN_NOT_FOUND, msg=msg)
class FileNotFoundException(NotFoundException):
def __init__(self, msg='The file does not found.'):
super().__init__(internal_code=NotFoundException.FILE_NOT_FOUND, msg=msg)
class OrderNotFoundException(NotFoundException):
def __init__(self, msg='The order does not found.'):
super().__init__(internal_code=NotFoundException.ORDER_NOT_FOUND, msg=msg)
class ReceiptNotFoundException(NotFoundException):
def __init__(self, msg='The receipt does not found.'):
super().__init__(internal_code=NotFoundException.RECEIPT_NOT_FOUND, msg=msg)
# AlreadyExistsException
class AlreadyExistsException(HiveException):
def __init__(self, msg='Already exists.'):
super().__init__(455, super().NO_INTERNAL_CODE, msg)
# InternalServerErrorException
class InternalServerErrorException(HiveException):
def __init__(self, msg='Internal server error.'):
super().__init__(500, super().NO_INTERNAL_CODE, msg)
# NotImplementedException
class NotImplementedException(HiveException):
def __init__(self, msg='Not implemented yet.'):
super().__init__(501, super().NO_INTERNAL_CODE, msg)
# InsufficientStorageException
class InsufficientStorageException(HiveException):
def __init__(self, msg='Insufficient storage.'):
super().__init__(507, super().NO_INTERNAL_CODE, msg)
| 29.491713 | 106 | 0.714125 | 617 | 5,338 | 5.755267 | 0.228525 | 0.058575 | 0.058857 | 0.063081 | 0.363841 | 0.197128 | 0.112644 | 0.112644 | 0 | 0 | 0 | 0.012641 | 0.184901 | 5,338 | 180 | 107 | 29.655556 | 0.803493 | 0.077932 | 0 | 0.019802 | 0 | 0 | 0.101163 | 0 | 0 | 0 | 0 | 0.005556 | 0.019802 | 1 | 0.237624 | false | 0 | 0.029703 | 0.019802 | 0.613861 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
dfdae299944050a6fdef525329e6faa9196e1465 | 540 | py | Python | omicexperiment/transforms/filters/taxonomy.py | bassio/omicexperiment | 323de49bb528e91658b38ed748a47c062e371048 | [
"BSD-3-Clause"
] | 7 | 2016-06-16T14:30:43.000Z | 2021-11-09T10:15:03.000Z | omicexperiment/transforms/filters/taxonomy.py | bassio/omicexperiment | 323de49bb528e91658b38ed748a47c062e371048 | [
"BSD-3-Clause"
] | 1 | 2019-03-18T21:32:06.000Z | 2019-03-18T22:16:19.000Z | omicexperiment/transforms/filters/taxonomy.py | bassio/omicexperiment | 323de49bb528e91658b38ed748a47c062e371048 | [
"BSD-3-Clause"
] | 2 | 2019-08-23T09:11:58.000Z | 2022-03-26T10:05:55.000Z | import pandas as pd
from omicexperiment.transforms.transform import Filter, AttributeFilter, AttributeFlexibleOperatorMixin
class TaxonomyAttributeFilter(AttributeFilter, AttributeFlexibleOperatorMixin):
def __dapply__(self, experiment):
_op = self._op_function(experiment._counts_with_tax())
criteria = _op(self.value)
return experiment.data_df[criteria]
def __eapply__(self, experiment):
filtered_df = self.__dapply__(experiment)
return experiment.with_data_df(filtered_df)
| 36 | 103 | 0.753704 | 53 | 540 | 7.226415 | 0.54717 | 0.234987 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.177778 | 540 | 14 | 104 | 38.571429 | 0.862613 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.2 | 0 | 0.7 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
dfde4e79b20e512e9f6be943f7987bab3af3401d | 633 | py | Python | dictionary.py | leonarddepaula/Projetos | 6908f875a181e42e554f46171d946713ba88ef58 | [
"MIT"
] | null | null | null | dictionary.py | leonarddepaula/Projetos | 6908f875a181e42e554f46171d946713ba88ef58 | [
"MIT"
] | null | null | null | dictionary.py | leonarddepaula/Projetos | 6908f875a181e42e554f46171d946713ba88ef58 | [
"MIT"
] | null | null | null | # DICTIONARY
cod_uf = {
21 : 'Maranhรฃo',
22 : 'Piauรญ',
23 : 'Cearรก',
24 : 'Rio grande Do Norte',
25 : 'Paraรญba',
26 : 'Pernanbuco',
27 : 'Alagoas',
28 : 'Sergipe',
29 : 'Bahia'}
print(type(cod_uf))
print(cod_uf)
print('\n/******************************/\n')
# Valores Ordenados.
print(cod_uf.values())
print('\n/******************************/\n')
# Duplicados Nรฃo Sรฃo permitidos.
# Acessando os Valores.
print(cod_uf.get(29))
print(cod_uf.get(23))
print(cod_uf.keys())
print('\n/******************************/\n')
# Adicionando Novos Valores.
cod_uf[30] = 'Lรฉo De Paula'
print(cod_uf) | 17.108108 | 45 | 0.516588 | 79 | 633 | 4.025316 | 0.556962 | 0.141509 | 0.188679 | 0.081761 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.046065 | 0.176935 | 633 | 37 | 46 | 17.108108 | 0.564299 | 0.172196 | 0 | 0.238095 | 0 | 0 | 0.371869 | 0.208092 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.47619 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
dffa15382ad81e025fbf33b72e7f59d0fca090a3 | 225 | py | Python | Python/data_structures_and_algorihms_with_python/Chapter01/conditions_looping.py | qixia1998/Data-Structures-and-Algorithms | 501f53822c24977a176704cc24f2f6dc1d55892f | [
"MIT"
] | null | null | null | Python/data_structures_and_algorihms_with_python/Chapter01/conditions_looping.py | qixia1998/Data-Structures-and-Algorithms | 501f53822c24977a176704cc24f2f6dc1d55892f | [
"MIT"
] | null | null | null | Python/data_structures_and_algorihms_with_python/Chapter01/conditions_looping.py | qixia1998/Data-Structures-and-Algorithms | 501f53822c24977a176704cc24f2f6dc1d55892f | [
"MIT"
] | null | null | null |
# example to understand variables
a = [2, 4, 6]
b = a
a.append(8)
print(b)
# example to understand variables scope
a = 15; b = 25
def my_function():
global a
a = 11; b = 21
my_function()
print(a) #11
print(b) #25 | 12.5 | 39 | 0.626667 | 41 | 225 | 3.390244 | 0.512195 | 0.129496 | 0.273381 | 0.402878 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.093567 | 0.24 | 225 | 18 | 40 | 12.5 | 0.719298 | 0.324444 | 0 | 0.181818 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0 | 0 | 0.090909 | 0.272727 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5f02a80f57ee8423dabe3f0d4105d5bf049922a3 | 5,161 | py | Python | tests/unit/io/test_carto.py | manmorjim/cartoframes | 4172e3dcdaedf207c10772a6dffe4f43b1993230 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/io/test_carto.py | manmorjim/cartoframes | 4172e3dcdaedf207c10772a6dffe4f43b1993230 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/io/test_carto.py | manmorjim/cartoframes | 4172e3dcdaedf207c10772a6dffe4f43b1993230 | [
"BSD-3-Clause"
] | null | null | null | import pytest
from pandas import Index
from geopandas import GeoDataFrame
from shapely.geometry import Point
from cartoframes import CartoDataFrame
from cartoframes.auth import Credentials
from cartoframes.io.carto import read_carto
from cartoframes.core.managers.context_manager import ContextManager
CREDENTIALS = Credentials('fake_user', 'fake_api_key')
def test_read_carto(mocker):
# Given
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
cm_mock.return_value = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
'010100000000000000000000000000000000000000',
'010100000000000000000024400000000000002e40',
'010100000000000000000034400000000000003e40'
]
})
expected = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
Point([0, 0]),
Point([10, 15]),
Point([20, 30])
]
}, geometry='the_geom')
# When
cdf = read_carto('__source__', CREDENTIALS)
# Then
cm_mock.assert_called_once_with('__source__', None, None, 3)
assert expected.equals(cdf)
assert cdf.crs == 'epsg:4326'
def test_read_carto_wrong_source(mocker):
# Given
mocker.patch.object(ContextManager, 'copy_to')
# When
with pytest.raises(ValueError) as e:
read_carto(1234, CREDENTIALS)
# Then
assert str(e.value) == 'Wrong source. You should provide a valid table_name or SQL query.'
def test_read_carto_wrong_credentials(mocker):
# Given
mocker.patch.object(ContextManager, 'copy_to')
# When
with pytest.raises(AttributeError) as e:
read_carto('__source__', 1234)
# Then
assert str(e.value) == 'Credentials attribute is required. Please pass a `Credentials` ' + \
'instance or use the `set_default_credentials` function.'
def test_read_carto_limit(mocker):
# Given
mocker.patch.object(CartoDataFrame, 'set_geometry')
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
# When
read_carto('__source__', CREDENTIALS, limit=1)
# Then
cm_mock.assert_called_once_with('__source__', None, 1, 3)
def test_read_carto_retry_times(mocker):
# Given
mocker.patch.object(CartoDataFrame, 'set_geometry')
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
# When
read_carto('__source__', CREDENTIALS, retry_times=1)
# Then
cm_mock.assert_called_once_with('__source__', None, None, 1)
def test_read_carto_schema(mocker):
# Given
mocker.patch.object(CartoDataFrame, 'set_geometry')
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
# When
read_carto('__source__', CREDENTIALS, schema='__schema__')
# Then
cm_mock.assert_called_once_with('__source__', '__schema__', None, 3)
def test_read_carto_index_col_exists(mocker):
# Given
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
cm_mock.return_value = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
'010100000000000000000000000000000000000000',
'010100000000000000000024400000000000002e40',
'010100000000000000000034400000000000003e40'
]
})
expected = GeoDataFrame({
'the_geom': [
Point([0, 0]),
Point([10, 15]),
Point([20, 30])
]
}, geometry='the_geom', index=Index([1, 2, 3], 'cartodb_id'))
# When
cdf = read_carto('__source__', CREDENTIALS, index_col='cartodb_id')
# Then
assert expected.equals(cdf)
def test_read_carto_index_col_not_exists(mocker):
# Given
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
cm_mock.return_value = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
'010100000000000000000000000000000000000000',
'010100000000000000000024400000000000002e40',
'010100000000000000000034400000000000003e40'
]
})
expected = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
Point([0, 0]),
Point([10, 15]),
Point([20, 30])
]
}, geometry='the_geom', index=Index([0, 1, 2], 'rename_index'))
# When
cdf = read_carto('__source__', CREDENTIALS, index_col='rename_index')
# Then
assert expected.equals(cdf)
def test_read_carto_decode_geom_false(mocker):
# Given
cm_mock = mocker.patch.object(ContextManager, 'copy_to')
cm_mock.return_value = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
'010100000000000000000000000000000000000000',
'010100000000000000000024400000000000002e40',
'010100000000000000000034400000000000003e40'
]
})
expected = GeoDataFrame({
'cartodb_id': [1, 2, 3],
'the_geom': [
'010100000000000000000000000000000000000000',
'010100000000000000000024400000000000002e40',
'010100000000000000000034400000000000003e40'
]
})
# When
cdf = read_carto('__source__', CREDENTIALS, decode_geom=False)
# Then
assert expected.equals(cdf)
| 28.048913 | 96 | 0.650262 | 533 | 5,161 | 5.962477 | 0.196998 | 0.053807 | 0.064191 | 0.045312 | 0.756765 | 0.717432 | 0.686595 | 0.686595 | 0.649465 | 0.622404 | 0 | 0.177009 | 0.238132 | 5,161 | 183 | 97 | 28.202186 | 0.631231 | 0.027708 | 0 | 0.586207 | 0 | 0 | 0.257315 | 0.131263 | 0 | 0 | 0 | 0 | 0.094828 | 1 | 0.077586 | false | 0.008621 | 0.068966 | 0 | 0.146552 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5f19e47313d4a9586ddc9ee7d4e9ddbc5cde8c12 | 316 | py | Python | users/admin.py | thiagoferreiraw/mixapp | 67ced5b26d5c4baf6d46a9630d001da8e30800fd | [
"MIT"
] | 4 | 2017-10-17T16:00:44.000Z | 2021-05-26T19:35:58.000Z | users/admin.py | thiagoferreiraw/mixapp | 67ced5b26d5c4baf6d46a9630d001da8e30800fd | [
"MIT"
] | 5 | 2020-06-05T17:23:55.000Z | 2021-09-07T23:42:12.000Z | users/admin.py | thiagoferreiraw/mixapp | 67ced5b26d5c4baf6d46a9630d001da8e30800fd | [
"MIT"
] | 3 | 2017-10-10T22:37:34.000Z | 2017-10-18T22:47:55.000Z | from django.contrib import admin
from users.models import SignupInvitation, UserCategory
class SignupInvitationAdmin(admin.ModelAdmin):
pass
class UserCategoryAdmin(admin.ModelAdmin):
pass
admin.site.register(SignupInvitation, SignupInvitationAdmin)
admin.site.register(UserCategory, UserCategoryAdmin)
| 22.571429 | 60 | 0.832278 | 31 | 316 | 8.483871 | 0.516129 | 0.197719 | 0.144487 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.101266 | 316 | 13 | 61 | 24.307692 | 0.926056 | 0 | 0 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.25 | 0.25 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
5f237d51180908b31ae53cb59789bb872cd2ce43 | 2,556 | py | Python | stocks/helper.py | arminbhy/stock-market-analysis | 3b560674c1da29aa8ebbf3b56b975c787f0e5fd8 | [
"WTFPL"
] | 1 | 2017-02-27T13:11:46.000Z | 2017-02-27T13:11:46.000Z | stocks/helper.py | arminbhy/stock-market-analysis | 3b560674c1da29aa8ebbf3b56b975c787f0e5fd8 | [
"WTFPL"
] | null | null | null | stocks/helper.py | arminbhy/stock-market-analysis | 3b560674c1da29aa8ebbf3b56b975c787f0e5fd8 | [
"WTFPL"
] | null | null | null | #!/usr/bin/env python
import numpy
import pystache
def _direction_to_str(direction):
if direction == 1:
return "Positive"
if direction == -1:
return "Negative"
return "None"
def _direction(a,b):
if a > b:
return 1
if a == b:
return 0
return -1
def _rsi(v):
if v > 70:
return 'Over-Bought'
if v < 30:
return 'Over-Sold'
if v > 60:
return 'Almost-Over-Bought'
if v < 40:
return 'Almost-Over-Sold'
return 'Avearge'
class Helper:
'Class for everything related to ticker'
def __init__(self, data):
self.data = data
def len(self):
return len(self.data)
def last_value(self):
return self.data[len(self.data) - 1]
def min(self, n=14):
return min(self.data[len(self.data) - n:])
def max(self, n=14):
return max(self.data[len(self.data) - n:])
def days_since_min(self, n=14):
group = self.data[len(self.data) - n:]
group.reverse()
return group.index(self.min(n))
def days_since_max(self, n=14):
group = self.data[len(self.data) - n:]
group.reverse()
return group.index(self.max(n))
def direction(self):
return _direction(
self.data[len(self.data) - 1],
self.data[len(self.data) - 2] )
def direction_str(self):
return _direction_to_str(self.direction())
def direction_compareto_average(self, n=14):
return _direction(
self.data[len(self.data) - 1],
numpy.mean(self.data[len(self.data) - n:]))
def direction_since_max_or_min(self, n=14):
return self.direction_compareto_average(
min(self.days_since_max(n),
self.days_since_min(n)) + 1)
def report(self, n=14):
return pystache.render('Direction {{direction}}, Value {{value}}, {{n}}D Min {{min}}, Max {{max}}, Days Since Min {{since_min}}, Max {{since_max}}', {
'n' : n,
'direction' : _direction_to_str(self.direction()),
'value' : round(self.data[len(self.data) - 1],2),
'min' : round(self.min(n),2),
'max' : round(self.max(n),2),
'since_min' : self.days_since_min(n),
'since_max' : self.days_since_max(n)
})
class RSIHelper(Helper):
def status(self):
return _rsi(self.data[len(self.data) - 1])
def min_status(self, n=14):
return _rsi(self.min(n))
def max_status(self, n=14):
return _rsi(self.max(n))
| 26.350515 | 158 | 0.564945 | 356 | 2,556 | 3.921348 | 0.176966 | 0.143266 | 0.094556 | 0.118195 | 0.401862 | 0.280086 | 0.265759 | 0.179083 | 0.091691 | 0.091691 | 0 | 0.022577 | 0.289515 | 2,556 | 96 | 159 | 26.625 | 0.746145 | 0.023083 | 0 | 0.106667 | 0 | 0.013333 | 0.110497 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.24 | false | 0 | 0.026667 | 0.16 | 0.626667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
5f29e844d4f640ffadbbda2480b24e7b1dff3c1d | 1,283 | py | Python | src/data/order_era5.py | ecohydro/rhone-ecostress | fa72f4c2716f40a860551ef4073fbaa5b004c7f5 | [
"MIT"
] | 2 | 2020-10-12T21:46:17.000Z | 2022-02-12T03:51:10.000Z | src/data/order_era5.py | ecohydro/rhone-ecostress | fa72f4c2716f40a860551ef4073fbaa5b004c7f5 | [
"MIT"
] | null | null | null | src/data/order_era5.py | ecohydro/rhone-ecostress | fa72f4c2716f40a860551ef4073fbaa5b004c7f5 | [
"MIT"
] | 2 | 2020-07-31T19:35:54.000Z | 2022-02-04T13:25:24.000Z | import cdsapi
c = cdsapi.Client()
c.retrieve(
'reanalysis-era5-land',
{
'format':'netcdf',
'variable':[
'2m_dewpoint_temperature','2m_temperature','evaporation_from_bare_soil',
'evaporation_from_vegetation_transpiration','evapotranspiration','potential_evaporation',
'surface_pressure','total_precipitation'
],
'year':[
'2019'
],
'month':[
'01','02','03',
'04','05','06',
'07','08','09',
'10','11','12'
],
'day':[
'01','02','03',
'04','05','06',
'07','08','09',
'10','11','12',
'13','14','15',
'16','17','18',
'19','20','21',
'22','23','24',
'25','26','27',
'28','29','30',
'31'
],
'time':[
'00:00','01:00','02:00',
'03:00','04:00','05:00',
'06:00','07:00','08:00',
'09:00','10:00','11:00',
'12:00','13:00','14:00',
'15:00','16:00','17:00',
'18:00','19:00','20:00',
'21:00','22:00','23:00'
]
},
'/mnt/ecostress/rhone-ecostress-data/era5-download2.nc')
| 26.183673 | 101 | 0.387373 | 137 | 1,283 | 3.540146 | 0.50365 | 0.061856 | 0.024742 | 0.03299 | 0.098969 | 0.098969 | 0.098969 | 0.098969 | 0.098969 | 0.098969 | 0 | 0.237562 | 0.373344 | 1,283 | 48 | 102 | 26.729167 | 0.365672 | 0 | 0 | 0.222222 | 0 | 0 | 0.387676 | 0.127925 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.022222 | 0 | 0.022222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
5f3451e59cc126c5158c8b25db5f21b13f8311b2 | 579 | py | Python | icon-pycon/home/<USERNAME>/Desktop/DTbkp.d/2-RESTORING/RESTORE_desktop_layout.py | moof-moof/Icon-pycon | 3f14af7d0a3e30bea1b67ea6c34ff71c9ebedcf8 | [
"Unlicense"
] | null | null | null | icon-pycon/home/<USERNAME>/Desktop/DTbkp.d/2-RESTORING/RESTORE_desktop_layout.py | moof-moof/Icon-pycon | 3f14af7d0a3e30bea1b67ea6c34ff71c9ebedcf8 | [
"Unlicense"
] | null | null | null | icon-pycon/home/<USERNAME>/Desktop/DTbkp.d/2-RESTORING/RESTORE_desktop_layout.py | moof-moof/Icon-pycon | 3f14af7d0a3e30bea1b67ea6c34ff71c9ebedcf8 | [
"Unlicense"
] | null | null | null |
import sys
sys.path.append('/home/user/path/to/0-defs/')
# sys.path.append('/home/xneb/Skrivbord/DTbkp.d/0-defs/')
import icons_pycons
icons_pycons.RESTORE_saved_layout()
# ---------------------------------------------------------------------#
## Finally, to refresh the desktop simply hit F5 while "touching" the
## desktop with the pointer.
##
## To more drastically restart caja run in separate terminal:
## caja -q && caja -n &
##
## or:
## killall -9 caja (Oy Gevald!)
# ---------------------------------------------------------------------#
| 20.678571 | 72 | 0.495682 | 63 | 579 | 4.492063 | 0.698413 | 0.04947 | 0.091873 | 0.120141 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008147 | 0.151986 | 579 | 27 | 73 | 21.444444 | 0.568228 | 0.725389 | 0 | 0 | 0 | 0 | 0.192593 | 0.192593 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
5f37ab305b8be6a06ceeef43488178b10f55544e | 165 | py | Python | BOJwithDongbinNa/1904/1904.py | jiyolla/StudyForCodingTestWithDongbinNa | c070829dd9c7b02b139e56511832c4a3b9f5982f | [
"MIT"
] | null | null | null | BOJwithDongbinNa/1904/1904.py | jiyolla/StudyForCodingTestWithDongbinNa | c070829dd9c7b02b139e56511832c4a3b9f5982f | [
"MIT"
] | null | null | null | BOJwithDongbinNa/1904/1904.py | jiyolla/StudyForCodingTestWithDongbinNa | c070829dd9c7b02b139e56511832c4a3b9f5982f | [
"MIT"
] | null | null | null | def solve():
n = int(input())
f = [1, 2] + [0] * (n - 2)
for i in range(2, n):
f[i] = (f[i - 2] + f[i - 1]) % 15746
print(f[n - 1])
solve()
| 18.333333 | 44 | 0.375758 | 31 | 165 | 2 | 0.483871 | 0.096774 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.12381 | 0.363636 | 165 | 8 | 45 | 20.625 | 0.466667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0 | 0 | 0.142857 | 0.142857 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a034b7bcb2e8d3daba74e84f95923a7635acca9d | 316 | py | Python | Python3/1261.py | Di-Ca-N/URI-Online-Judge | 160797b534fe8c70e719b1ea41690157dbdbb52e | [
"MIT"
] | null | null | null | Python3/1261.py | Di-Ca-N/URI-Online-Judge | 160797b534fe8c70e719b1ea41690157dbdbb52e | [
"MIT"
] | null | null | null | Python3/1261.py | Di-Ca-N/URI-Online-Judge | 160797b534fe8c70e719b1ea41690157dbdbb52e | [
"MIT"
] | null | null | null | m, n = map(int, input().split())
dicionario = {}
for i in range(m):
cargo, valor = input().split()
dicionario[cargo] = int(valor)
for i in range(n):
a = input().split()
total = 0
while a != ["."]:
for word in a:
if word in dicionario:
total += dicionario[word]
a = input().split()
print(total)
| 15.8 | 32 | 0.588608 | 48 | 316 | 3.875 | 0.416667 | 0.215054 | 0.215054 | 0.11828 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004065 | 0.221519 | 316 | 19 | 33 | 16.631579 | 0.752033 | 0 | 0 | 0.142857 | 0 | 0 | 0.003165 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.071429 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a036d04ec7acd96a911e3d6bed5c6d667d35305c | 352 | py | Python | employee_management/employee_management/page/category/category.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | employee_management/employee_management/page/category/category.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | employee_management/employee_management/page/category/category.py | Vivekananthan112599/Frappe-Vivek | 6a2b70c736e17e9748c6a30e5722341acfb3b5c5 | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
import frappe
@frappe.whitelist()
def get_list():
orders = frappe.db.sql('''select name,category_name from `tabCategoryb`''')
return orders
@frappe.whitelist()
def get_insert(name,cname):
result = frappe.db.set_value('Categoryb',name,'category_name',cname)
return result
| 16.761905 | 77 | 0.696023 | 43 | 352 | 5.465116 | 0.55814 | 0.12766 | 0.153191 | 0.178723 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | 352 | 20 | 78 | 17.6 | 0.821678 | 0 | 0 | 0.2 | 0 | 0 | 0.201807 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.2 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
a042fd42d3eb242a1fdfed3c98010eac579118cd | 152 | py | Python | example/django_example/foo/a_plugin_folder/dynaconf_hooks.py | sephiartlist/dynaconf | 9c5f60b289c1f0fa3f899f1962a8fe5712c74eab | [
"MIT"
] | 2,293 | 2015-08-14T22:39:31.000Z | 2022-03-31T12:44:49.000Z | example/django_example/foo/a_plugin_folder/dynaconf_hooks.py | sephiartlist/dynaconf | 9c5f60b289c1f0fa3f899f1962a8fe5712c74eab | [
"MIT"
] | 676 | 2015-08-20T19:29:56.000Z | 2022-03-31T13:45:51.000Z | example/django_example/foo/a_plugin_folder/dynaconf_hooks.py | sephiartlist/dynaconf | 9c5f60b289c1f0fa3f899f1962a8fe5712c74eab | [
"MIT"
] | 255 | 2015-12-02T21:16:33.000Z | 2022-03-20T22:03:46.000Z | def post(settings):
data = {"dynaconf_merge": True}
if settings.get("ADD_BEATLES") is True:
data["BANDS"] = ["Beatles"]
return data
| 25.333333 | 43 | 0.611842 | 19 | 152 | 4.789474 | 0.736842 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.230263 | 152 | 5 | 44 | 30.4 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0.243421 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a044ca6f0bb5153e01427d999ad36a4f0c809c66 | 569 | py | Python | generators/app/templates/auth/jwt/urls.py | pratheeshrussell1992/generator-djangoacs | c78d95ce322429d1416c42a2134a8227394fdfd6 | [
"Apache-2.0"
] | null | null | null | generators/app/templates/auth/jwt/urls.py | pratheeshrussell1992/generator-djangoacs | c78d95ce322429d1416c42a2134a8227394fdfd6 | [
"Apache-2.0"
] | null | null | null | generators/app/templates/auth/jwt/urls.py | pratheeshrussell1992/generator-djangoacs | c78d95ce322429d1416c42a2134a8227394fdfd6 | [
"Apache-2.0"
] | null | null | null | from django.urls import path, re_path
from .conf import *
from .controllers.registerController import OauthRegister as registerHandler
from .controllers.jwtLoginController import JwtLogin as jwtHandler
from .controllers.jwtLoginController import JwtRenewLogin as jwtRefreshHandler
app_name = Config.app_name
urlpatterns = [
re_path(r'^register/?$', registerHandler.as_view(), name="register"),
re_path(r'^login/jwt/token/?$', jwtHandler.as_view(), name='token_obtain_pair'),
re_path(r'^login/jwt/renew/?$', jwtRefreshHandler.as_view(), name='token_refresh')
] | 43.769231 | 84 | 0.787346 | 71 | 569 | 6.140845 | 0.43662 | 0.055046 | 0.048165 | 0.178899 | 0.068807 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.091388 | 569 | 13 | 85 | 43.769231 | 0.843327 | 0 | 0 | 0 | 0 | 0 | 0.154386 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.454545 | 0 | 0.454545 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
a04c6a747ea3580d8d3ae7c900cd22274649c871 | 118 | py | Python | detector/effdet_cfg.py | HwangToeMat/tmp | a4f48443b16b5e07a9cf95f54651ade8c7669134 | [
"Apache-2.0"
] | 10 | 2020-08-28T08:03:28.000Z | 2022-03-26T21:20:44.000Z | detector/effdet_cfg.py | HwangToeMat/PoseEstimation_Scoring-Your-Video | 16c49b00007135d9b274b6c1e23d6e6c942ec951 | [
"Apache-2.0"
] | null | null | null | detector/effdet_cfg.py | HwangToeMat/PoseEstimation_Scoring-Your-Video | 16c49b00007135d9b274b6c1e23d6e6c942ec951 | [
"Apache-2.0"
] | null | null | null | from easydict import EasyDict as edict
cfg = edict()
cfg.NMS_THRES = 0.6
cfg.CONFIDENCE = 0.1
cfg.NUM_CLASSES = 80
| 14.75 | 38 | 0.728814 | 21 | 118 | 4 | 0.714286 | 0.190476 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.061856 | 0.177966 | 118 | 7 | 39 | 16.857143 | 0.804124 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.2 | 0 | 0.2 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a05a3b5b6930fabaaa1541235a6d82a8b361d3d2 | 122 | py | Python | examples/chunking/udf/tags.py | feiranwang/deepdive | 53c03edba643d53fbb6d9d382870fe5dfb2e47a1 | [
"Apache-2.0"
] | 1 | 2015-04-06T16:20:00.000Z | 2015-04-06T16:20:00.000Z | examples/chunking/udf/tags.py | feiranwang/deepdive | 53c03edba643d53fbb6d9d382870fe5dfb2e47a1 | [
"Apache-2.0"
] | null | null | null | examples/chunking/udf/tags.py | feiranwang/deepdive | 53c03edba643d53fbb6d9d382870fe5dfb2e47a1 | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/env python
tagNames = ['NP', 'VP', 'PP', 'ADJP', 'ADVP', 'SBAR', 'O', 'PRT', 'CONJP', 'INTJ', 'LST', 'B', ''] | 40.666667 | 98 | 0.47541 | 17 | 122 | 3.411765 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147541 | 122 | 3 | 98 | 40.666667 | 0.557692 | 0.172131 | 0 | 0 | 0 | 0 | 0.346535 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a05b68e940e554ec4ad9b7601e2400c462b90e5b | 5,242 | py | Python | unit_test/model/sklearn_like_model/test_SemanticSegmentation.py | demetoir/MLtools | 8c42fcd4cc71728333d9c116ade639fe57d50d37 | [
"MIT"
] | null | null | null | unit_test/model/sklearn_like_model/test_SemanticSegmentation.py | demetoir/MLtools | 8c42fcd4cc71728333d9c116ade639fe57d50d37 | [
"MIT"
] | null | null | null | unit_test/model/sklearn_like_model/test_SemanticSegmentation.py | demetoir/MLtools | 8c42fcd4cc71728333d9c116ade639fe57d50d37 | [
"MIT"
] | null | null | null | import numpy as np
from pprint import pprint
from script.data_handler.ImgMaskAug import ActivatorMask, ImgMaskAug
from script.data_handler.TGS_salt import HEAD_PATH, collect_images
from script.model.sklearn_like_model.BaseModel import BaseDatasetCallback
from script.model.sklearn_like_model.SemanticSegmentation import SemanticSegmentation
from script.util.PlotTools import PlotTools
from script.util.misc_util import path_join
from imgaug import augmenters as iaa
plot = PlotTools(save=True, show=False)
class mask_label_encoder:
@staticmethod
def to_label(x):
return np.array(x / 255, dtype=int)
@staticmethod
def from_label(x):
return np.array(x * 255, dtype=float)
def test_SemanticSegmentation_toy_set():
x = np.zeros([100, 128, 128, 1])
y = np.ones([100, 128, 128, 1])
y_gt = y
y_encode = mask_label_encoder.to_label(y)
print(x.shape)
print(y_encode.shape)
Unet = SemanticSegmentation(stage=4, batch_size=10)
Unet.train(x, y_encode, epoch=100)
score = Unet.score(x, y_encode)
pprint(score)
predict = Unet.predict(x)
pprint(predict[0])
pprint(predict.shape)
proba = Unet.predict_proba(x)
pprint(proba[0])
pprint(proba.shape)
metric = Unet.metric(x, y_encode)
print(metric)
predict = mask_label_encoder.from_label(predict)
plot.plot_image_tile(np.concatenate([x, predict, y_gt], axis=0), title='predict', column=10)
def test_SemanticSegmentation():
sample_IMAGE_PATH = path_join(HEAD_PATH, 'sample/images')
sample_MASK_PATH = path_join(HEAD_PATH, 'sample/masks')
sample_size = 7
limit = None
print(f'collect sample images')
train_images, _, _ = collect_images(sample_IMAGE_PATH, limit=limit)
train_images = train_images.reshape([-1, 101, 101])
print(f'collect sample images')
train_mask_images, _, _ = collect_images(sample_MASK_PATH, limit=limit)
train_mask_images = train_mask_images.reshape([-1, 101, 101])
x = train_images
y = train_mask_images
import cv2
x = np.array([cv2.resize(a, (128, 128)) for a in x]).reshape([-1, 128, 128, 1])
y = np.array([cv2.resize(a, (128, 128)) for a in y]).reshape([-1, 128, 128, 1])
y_gt = y
y_encode = mask_label_encoder.to_label(y)
print(x.shape)
print(y_encode.shape)
Unet = SemanticSegmentation(stage=4, batch_size=7)
Unet.train(x, y_encode, epoch=100, early_stop=True, patience=10)
score = Unet.score(x, y_encode)
pprint(score)
predict = Unet.predict(x)
pprint(predict[0])
pprint(predict.shape)
proba = Unet.predict_proba(x)
pprint(proba[0])
pprint(proba.shape)
metric = Unet.metric(x, y_encode)
print(metric)
predict = mask_label_encoder.from_label(predict)
plot.plot_image_tile(np.concatenate([x, predict, y_gt], axis=0), title='predict', column=sample_size)
class dataset_callback(BaseDatasetCallback):
def __init__(self, x, y, batch_size):
super().__init__(x, y, batch_size)
self.seq = iaa.Sequential([
iaa.Fliplr(0.5, name="Flipper"),
])
self.activator = ActivatorMask([])
self.aug = ImgMaskAug(self.x, self.y, self.seq, self.activator, self.batch_size, n_jobs=1)
@property
def size(self):
return len(self.x)
def shuffle(self):
pass
def next_batch(self, batch_size, batch_keys=None, update_cursor=True, balanced_class=False, out_type='concat'):
x, y = self.aug.get_batch()
return x, y
def test_train_dataset_callback():
sample_IMAGE_PATH = path_join(HEAD_PATH, 'sample/images')
sample_MASK_PATH = path_join(HEAD_PATH, 'sample/masks')
sample_size = 7
limit = None
print(f'collect sample images')
train_images, _, _ = collect_images(sample_IMAGE_PATH, limit=limit)
train_images = train_images.reshape([-1, 101, 101])
print(f'collect sample images')
train_mask_images, _, _ = collect_images(sample_MASK_PATH, limit=limit)
train_mask_images = train_mask_images.reshape([-1, 101, 101])
x = train_images
y = train_mask_images
import cv2
x = np.array([cv2.resize(a, (128, 128)) for a in x]).reshape([-1, 128, 128, 1])
y = np.array([cv2.resize(a, (128, 128)) for a in y]).reshape([-1, 128, 128, 1])
y_gt = y
y_encode = mask_label_encoder.to_label(y)
print(x.shape)
print(y_encode.shape)
Unet = SemanticSegmentation(stage=4, batch_size=7)
# Unet.train(x, y_encode, epoch=100)
Unet.train(x, y_encode, epoch=1000, dataset_callback=dataset_callback)
Unet.train(x, y_encode, epoch=1000, dataset_callback=dataset_callback)
score = Unet.score(x, y_encode)
pprint(score)
predict = Unet.predict(x)
pprint(predict[0])
pprint(predict.shape)
proba = Unet.predict_proba(x)
pprint(proba[0])
pprint(proba.shape)
metric = Unet.metric(x, y_encode)
print(metric)
predict = mask_label_encoder.from_label(predict)
plot.plot_image_tile(np.concatenate([x, predict, y_gt], axis=0), title='predict', column=sample_size)
| 30.835294 | 116 | 0.667303 | 743 | 5,242 | 4.487214 | 0.169583 | 0.035693 | 0.026395 | 0.014397 | 0.719856 | 0.715057 | 0.696461 | 0.688962 | 0.672166 | 0.672166 | 0 | 0.03835 | 0.21404 | 5,242 | 169 | 117 | 31.017751 | 0.770874 | 0.006486 | 0 | 0.674797 | 0 | 0 | 0.033353 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.073171 | false | 0.00813 | 0.089431 | 0.02439 | 0.211382 | 0.235772 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a05f45127f2edba2b2b47a084cd3a42c9f88bc53 | 700 | py | Python | logbunker/apps/backoffice/backend/routes/status_routes.py | parada3desu/logbunker | 1cc3f197c0d1662946ef65bb9f97a89f625d0c1b | [
"MIT"
] | null | null | null | logbunker/apps/backoffice/backend/routes/status_routes.py | parada3desu/logbunker | 1cc3f197c0d1662946ef65bb9f97a89f625d0c1b | [
"MIT"
] | null | null | null | logbunker/apps/backoffice/backend/routes/status_routes.py | parada3desu/logbunker | 1cc3f197c0d1662946ef65bb9f97a89f625d0c1b | [
"MIT"
] | 1 | 2021-12-28T15:20:20.000Z | 2021-12-28T15:20:20.000Z | import sys
from dependency_injector.wiring import inject, Provide
from fastapi import APIRouter
from starlette.requests import Request
from logbunker.apps.backoffice.backend.dependencies.BackofficeContainer import BackofficeContainer, backoffice_container
from logbunker.apps.bunker.controllers.StatusGetController import StatusGetController
@inject
def register(
router: APIRouter,
status_get_controller: StatusGetController = Provide[BackofficeContainer.status_get_controller]
):
@router.get('/status', tags=['Health'])
async def run_wrapper(req: Request):
return await status_get_controller.run(req)
backoffice_container.wire(modules=[sys.modules[__name__]])
| 31.818182 | 120 | 0.807143 | 76 | 700 | 7.25 | 0.526316 | 0.049002 | 0.103448 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117143 | 700 | 21 | 121 | 33.333333 | 0.891586 | 0 | 0 | 0 | 0 | 0 | 0.018571 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.4 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
a06964e3556af93bdd88e62259ae7b0a459b8f82 | 169 | py | Python | tests/test_pages.py | eoranged/squash | 9fb088e419ab0b0a16dbde126b12051ea2dc4bab | [
"MIT"
] | null | null | null | tests/test_pages.py | eoranged/squash | 9fb088e419ab0b0a16dbde126b12051ea2dc4bab | [
"MIT"
] | 13 | 2019-08-06T00:39:44.000Z | 2019-10-28T21:55:16.000Z | tests/test_pages.py | eoranged/squash | 9fb088e419ab0b0a16dbde126b12051ea2dc4bab | [
"MIT"
] | 1 | 2019-08-21T17:20:22.000Z | 2019-08-21T17:20:22.000Z | async def test_index(test_cli):
resp = await test_cli.get('/')
assert resp.status == 200
data = await resp.text()
assert '<title>squash</title>' in data
| 28.166667 | 42 | 0.650888 | 25 | 169 | 4.28 | 0.64 | 0.130841 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.022388 | 0.207101 | 169 | 5 | 43 | 33.8 | 0.776119 | 0 | 0 | 0 | 0 | 0 | 0.130178 | 0.12426 | 0 | 0 | 0 | 0 | 0.4 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a0830701c04ccda3c8b0b52e36f1a9eeae920660 | 659 | py | Python | block/migrations/0003_auto_20191226_0841.py | tiantian-commits/fcexplorer | 492f9a5d9cd538d37b4c172248fc3b1818bde1d8 | [
"Apache-2.0"
] | null | null | null | block/migrations/0003_auto_20191226_0841.py | tiantian-commits/fcexplorer | 492f9a5d9cd538d37b4c172248fc3b1818bde1d8 | [
"Apache-2.0"
] | 7 | 2020-02-12T03:22:53.000Z | 2022-03-12T00:11:02.000Z | block/migrations/0003_auto_20191226_0841.py | tiantian-commits/fcexplorer | 492f9a5d9cd538d37b4c172248fc3b1818bde1d8 | [
"Apache-2.0"
] | null | null | null | # Generated by Django 2.1 on 2019-12-26 08:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('block', '0002_auto_20191226_0812'),
]
operations = [
migrations.RenameField(
model_name='block',
old_name='pre',
new_name='method',
),
migrations.RemoveField(
model_name='block',
name='prove',
),
migrations.RemoveField(
model_name='block',
name='slash',
),
migrations.RemoveField(
model_name='block',
name='submit',
),
]
| 21.258065 | 45 | 0.517451 | 59 | 659 | 5.627119 | 0.59322 | 0.108434 | 0.168675 | 0.271084 | 0.35241 | 0.35241 | 0 | 0 | 0 | 0 | 0 | 0.071942 | 0.367223 | 659 | 30 | 46 | 21.966667 | 0.724221 | 0.06525 | 0 | 0.458333 | 1 | 0 | 0.118893 | 0.037459 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.041667 | 0 | 0.166667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a083dbe331458c0350cc41b115714d760de910c4 | 963 | py | Python | leetcode/H0224_Basic_Calculator.py | jjmoo/daily | fb8cf0e64606a2a76a6141bb0e9ccd143c30f07c | [
"MIT"
] | 1 | 2020-03-27T16:42:02.000Z | 2020-03-27T16:42:02.000Z | leetcode/H0224_Basic_Calculator.py | jjmoo/daily | fb8cf0e64606a2a76a6141bb0e9ccd143c30f07c | [
"MIT"
] | null | null | null | leetcode/H0224_Basic_Calculator.py | jjmoo/daily | fb8cf0e64606a2a76a6141bb0e9ccd143c30f07c | [
"MIT"
] | null | null | null | from M0227_Basic_Calculator_II import Solution as Basic_Calculator
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
return Basic_Calculator().calculate(s)
print(2, Solution().calculate('1 + 1'))
print(3, Solution().calculate(' 2-1 + 2 '))
print(23, Solution().calculate('(1+(4+5+2)-3)+(6+8)'))
# Implement a basic calculator to evaluate a simple expression string.
# The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
# Example 1:
# Input: "1 + 1"
# Output: 2
# Example 2:
# Input: " 2-1 + 2 "
# Output: 3
# Example 3:
# Input: "(1+(4+5+2)-3)+(6+8)"
# Output: 23
# Note:
# You may assume that the given expression is always valid.
# Do not use the eval built-in library function.
# ๆฅๆบ๏ผๅๆฃ๏ผLeetCode๏ผ
# ้พๆฅ๏ผhttps://leetcode-cn.com/problems/basic-calculator
# ่ไฝๆๅฝ้ขๆฃ็ฝ็ปๆๆใๅไธ่ฝฌ่ฝฝ่ฏท่็ณปๅฎๆนๆๆ๏ผ้ๅไธ่ฝฌ่ฝฝ่ฏทๆณจๆๅบๅคใ
| 24.075 | 138 | 0.661475 | 142 | 963 | 4.450704 | 0.570423 | 0.118671 | 0.056962 | 0.012658 | 0.022152 | 0.022152 | 0.022152 | 0 | 0 | 0 | 0 | 0.050064 | 0.19107 | 963 | 39 | 139 | 24.692308 | 0.761232 | 0.595016 | 0 | 0 | 0 | 0 | 0.096491 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.142857 | 0 | 0.571429 | 0.428571 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 2 |
a08d3cb77266519189f8aaa444876e8b28d0ada6 | 8,202 | py | Python | stream/utils/utils.py | cajohnst/prod_sample | 02d332eb58fa872aafecb0de92ecceb48ca94d5f | [
"MIT"
] | null | null | null | stream/utils/utils.py | cajohnst/prod_sample | 02d332eb58fa872aafecb0de92ecceb48ca94d5f | [
"MIT"
] | null | null | null | stream/utils/utils.py | cajohnst/prod_sample | 02d332eb58fa872aafecb0de92ecceb48ca94d5f | [
"MIT"
] | null | null | null | import pandas as pd
import requests
import pytz
from datetime import timedelta as td
from dateutil.relativedelta import relativedelta as rd
"""
DESCRIPTION
-----------
Utils used for all streaming applications.
MODIFICATIONS
-------------
Created : 4/24/19
AUTHORS
-------
CJ
"""
def reverse_key_value(orig_dict):
"""
DESCRIPTION
-----------
Reverse the key value pairs of a dictionary object.
PARAMETERS
----------
orig_dict : dict
A dictionary object.
RETURNS
-------
rev_dict : dict
A dictionary with the values of the original dictionary stored as keys
and the keys of the oriinal dictionary stored as values.
MODIFICATIONS
-------------
Created : 4/24/19
"""
rev_dict = {}
for j, k in orig_dict.items():
rev_dict[k] = j
return rev_dict
def strip_tzinfo(ts):
"""
DESCRIPTION
-----------
Strip the timezone info from a timestamp instance
RETURNS
-------
A timestamp object with nullified timezone information.
MODIFICATIONS
-------------
Created : 4/22/19
"""
return ts.replace(tzinfo=None)
def round_down_to_nearest_day(ts):
"""
DESCRIPTION
-----------
Round a timestamp to the nearest day by replacing hour, minute, second,
and microsecond values to 0.
RETURNS
-------
A rounded datetime object
MODIFICATIONS
-------------
Created : 4/22/19
"""
return ts.replace(hour=0, minute=0, second=0, microsecond=0)
def round_down_to_nearest_week(ts):
"""
DESCRIPTION
-----------
Round a timestamp to the nearest day by replacing hour, minute, second,
and microsecond values to 0.
RETURNS
-------
A rounded datetime object
MODIFICATIONS
-------------
Created : 4/22/19
"""
return ts.replace(hour=0, minute=0, second=0, microsecond=0) - td(days=ts.weekday())
def round_down_to_nearest_month(ts):
"""
DESCRIPTION
-----------
Round a timestamp to the nearest month by replacing day, hour, minute, second,
and microsecond values to 0.
RETURNS
-------
A rounded datetime object
MODIFICATIONS
-------------
Created : 4/22/19
"""
return ts.replace(day=0, hour=0, minute=0, second=0, microsecond=0)
def concat_rows(df1, df2):
"""
DESCRIPTION
-----------
A basic concatenation of two pandas dataframes adding rows of df2 to df1
ignoring indicies and outer joining on columns.
PARAMETERS
----------
df1 : pd.DataFrame
A pandas dataframe instance.
df2 : pd.DataFrame
A pandas dataframe instance.
RETURNS
-------
A pandas dataframe containing the results of the outer-joined concatenation.
MODFICATIONS
------------
Created : 4/24/19
"""
return pd.concat([df1, df2], axis=0, sort=True, ignore_index=True)
def drop_first_df_row(df):
"""
DESCRIPTION
-----------
Drop the first row of a pandas dataframe in place.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
NOTES
-----
Drop first row in place.
MODIFICATIONS
-------------
Created : 4/25/19
"""
df.drop(df.index[:1], inplace=True)
def drop_last_df_row(df):
"""
DESCRIPTION
-----------
Drop the last row of a pandas dataframe in place
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
NOTES
-----
Drop last row in place.
MODIFICATIONS
-------------
Created : 4/25/19
"""
df.drop(df.index[-1:], inplace=True)
def drop_df_cols(df, col_names):
"""
DESCRIPTION
-----------
Drop specified columns from a pandas dataframe given a list of the column names
in place.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
col_names : list
A list of column names (str) for which to drop from the dataframe
NOTES
-----
Drop columns in place.
MODIFICATIONS
-------------
Created : 4/26/19
"""
df.drop(col_names, axis=1, inplace=True)
def set_null_vals_to_none(df):
"""
DESCRIPTION
-----------
Set null values to None to be SQL readable upon database insertion.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
RETURNS
-------
A pandas dataframe instance in which null values are converted to `None`
MODIFICATIONS
-------------
Created ; 4/26/19
"""
return df.where(pd.notnull(df), None)
def copy_df(df):
"""
DESCRIPTION
-----------
Deep copy a pandas dataframe.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
RETURNS
-------
A deep copy of a given pandas dataframe
MODIFICATIONS
-------------
Created : 4/26/19
"""
return df.copy(deep=True)
def make_request(url):
"""
DESCRIPTION
-----------
Make a request to a given url and return a response
PARAMETERS
----------
url : str
A url formatted as a string, the location to submit a request
RETURNS
-------
response : a request response instance
MODIFICATIONS
-------------
Created ; 4/26/19
"""
return requests.get(url, stream=True)
def set_index(df, ix_cols):
"""
DESCRIPTION
Set the index of a pandas dataframe from existing columns.
If multiple columns are passed in the ix_cols list, a multi-index
will be formed.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
ix_cols : list
A list of column names formatted as strings referencing existing
columns in the dataframe for which to make a (multi) index.
RETURNS
-------
Creates a (multi) index in place
NOTES
-----
To set a datetime index, a column with a dtype datetime must be passed.
MODIFICATIONS
-------------
Created : 4/26/19
"""
df.set_index(ix_cols, inplace=True)
def reset_index(df, drop=True):
"""
DESCRIPTION
-----------
Reset the index of a pandas dataframe to a standard monotonic index.
PARAMETERS
----------
df : pd.DataFrame
A pandas dataframe instance
drop : bool (default=True)
A boolean flag for whether to drop the current index or return the index
as a dataframe column.
NOTES
-----
Modifies the dataframe in place.
MODIFICATIONS
-------------
Created : 4/28/19
"""
df.reset_index(drop=drop, inplace=True)
def merge(df1, df2, on=None, how="left"):
"""
DESCRIPTION
-----------
Merge two pandas dataframes on a common field name or specified fields in
each frame.
PARAMETERS
----------
df1 : pd.DataFrame
A pandas dataframe instance
df2 : pd.DataFrame
A pandas dataframe instance
on : str, list
A string or list representing the field(s) to join on. If a list is passed,
it is assumed multiple values are passed for separate fields. Otherwise,
it is assumed that a common field name is present between the two dataframes.
how : str
The method of joining the two frames (left, right, outer, inner)
RETURNS
-------
A pandas dataframe instance merged from two provided dataframes
MODIFICATIONS
-------------
Created : 4/29/19
"""
if isinstance(on, list):
return pd.merge(df1, df2, left_on=on[0], right_on=on[1], how=how)
elif isinstance(on, str):
return pd.merge(df1, df2, on=on, how=how)
else:
raise ValueError(f"merge_df function expected a list or string object, got {type(on)}")
def convert_ts_to_utc(ts):
"""
DESCRIPTION
-----------
Return a timestamp or datetime object converted to UTC timezone
PARAMETERS
----------
ts : dt.datetime
A datetime or timestamp instance
RETURNS
-------
A datetime or timestamp instance with added UTC tz_info
MODIFICATIONS
-------------
Created : 4/29/19
"""
return ts.astimezone(pytz.timezone("UTC"))
| 21.81383 | 95 | 0.589247 | 1,014 | 8,202 | 4.711045 | 0.217949 | 0.065941 | 0.066988 | 0.065313 | 0.419929 | 0.351266 | 0.30291 | 0.289094 | 0.252669 | 0.244924 | 0 | 0.02069 | 0.275177 | 8,202 | 375 | 96 | 21.872 | 0.782843 | 0.631919 | 0 | 0 | 0 | 0 | 0.040398 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.355556 | false | 0 | 0.111111 | 0 | 0.733333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
a09d12aee97a4ee5944b255fe66f73706d6abef1 | 14,355 | py | Python | espeleo_planner/test/scripts/obstacle_detection_3d_lidar_v2.py | ITVRoC/espeleo_planner | f29d01c09aba339a30a76d05e80641181172ec8a | [
"MIT"
] | 6 | 2021-06-14T12:53:06.000Z | 2021-11-12T01:14:43.000Z | espeleo_planner/test/scripts/obstacle_detection_3d_lidar_v2.py | ITVRoC/espeleo_planner | f29d01c09aba339a30a76d05e80641181172ec8a | [
"MIT"
] | null | null | null | espeleo_planner/test/scripts/obstacle_detection_3d_lidar_v2.py | ITVRoC/espeleo_planner | f29d01c09aba339a30a76d05e80641181172ec8a | [
"MIT"
] | 2 | 2021-09-17T06:58:23.000Z | 2022-03-02T12:15:29.000Z | #!/usr/bin/env python
import os
import sys
import rospy
import pymesh
import rospkg
import traceback
from visualization_msgs.msg import Marker
import sensor_msgs.msg
import sensor_msgs.point_cloud2 as pc2
from scipy import spatial
from sklearn.cluster import DBSCAN
import numpy as np
import matplotlib.pyplot as plt
from mayavi import mlab
lidar_msg = None
import numpy as np
from scipy.spatial import distance
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import get_test_data
from mpl_toolkits.mplot3d import Axes3D
import math
from math import pi
from recon_surface.srv import MeshFromPointCloud2
import pcl
import pcl.pcl_visualization
from random import randint
import time
from visualization_msgs.msg import Marker, MarkerArray
viewer = pcl.pcl_visualization.PCLVisualizering(b"3D Viewer")
viewer.InitCameraParameters()
# viewer.setCameraPosition(0, 30, 0, 0, 0, 0, 0, 0, 1)
# viewer.setCameraFieldOfView(0.523599)
# viewer.setCameraClipDistances(0.00522511, 50)
pub_closest_obstacle_pt = rospy.Publisher('/closest_obstacle_point', Marker, latch=True, queue_size=1)
pub_obstacles_pts = rospy.Publisher('/obstacles_points', MarkerArray, latch=True, queue_size=1)
color_list = []
def create_marker(pos, orientation=1.0, color=(1.0, 1.0, 1.0), m_scale=0.5, frame_id="/velodyneVPL", duration=10,
marker_id=0, mesh_resource=None, marker_type=2, marker_text=""):
"""Create marker object using the map information and the node position
:param pos: list of 3d postion for the marker
:param orientation: orientation of the maker (1 for no orientation)
:param color: a 3 vector of 0-1 rgb values
:param m_scale: scale of the marker (1.0) for normal scale
:param frame_id: ROS frame id
:param duration: duration in seconds for this marker dissapearance
:param marker_id:
:param mesh_resource:
:param marker_type: one of the following types (use the int value)
http://wiki.ros.org/rviz/DisplayTypes/Marker
ARROW = 0
CUBE = 1
SPHERE = 2
CYLINDER = 3
LINE_STRIP = 4
LINE_LIST = 5
CUBE_LIST = 6
SPHERE_LIST = 7
POINTS = 8
TEXT_VIEW_FACING = 9
MESH_RESOURCE = 10
TRIANGLE_LIST = 11
:param marker_text: text string used for the marker
:return:
"""
marker = Marker()
marker.header.frame_id = frame_id
marker.id = marker_id
if mesh_resource:
marker.type = marker.MESH_RESOURCE
marker.mesh_resource = mesh_resource
else:
marker.type = marker_type
marker.action = marker.ADD
marker.scale.x = m_scale
marker.scale.y = m_scale
marker.scale.z = m_scale
marker.color.a = 1.0
marker.color.r = color[0]
marker.color.g = color[1]
marker.color.b = color[2]
marker.pose.orientation.w = orientation
marker.text = marker_text
marker.pose.position.x = pos[0]
marker.pose.position.y = pos[1]
marker.pose.position.z = pos[2]
d = rospy.Duration.from_sec(duration)
marker.lifetime = d
return marker
def hv_in_range(x, y, z, fov, fov_type='h'):
"""
Extract filtered in-range velodyne coordinates based on azimuth & elevation angle limit
Args:
`x`:velodyne points x array
`y`:velodyne points y array
`z`:velodyne points z array
`fov`:a two element list, e.g.[-45,45]
`fov_type`:the fov type, could be `h` or 'v',defualt in `h`
Return:
`cond`:condition of points within fov or not
Raise:
`NameError`:"fov type must be set between 'h' and 'v' "
"""
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
if fov_type == 'h':
# print "np.arctan2(y, x):", np.arctan2(y, x)
# print "np.deg2rad(-fov[1]):", np.deg2rad(-fov[1])
# print "np.deg2rad(-fov[0]):", np.deg2rad(-fov[0])
return np.logical_and(np.arctan2(y, x) > np.deg2rad(-fov[1]), np.arctan2(y, x) < np.deg2rad(-fov[0]))
elif fov_type == 'v':
return np.logical_and(np.arctan2(z, d) < np.deg2rad(fov[1]), np.arctan2(z, d) > np.deg2rad(fov[0]))
else:
raise NameError("fov type must be set between 'h' and 'v' ")
def random_color_gen():
""" Generates a random color
Args: None
Returns:
list: 3 elements, R, G, and B
"""
r = randint(50, 255)
g = randint(50, 255)
b = randint(50, 255)
return [r, g, b]
def get_color_list(cluster_count):
global color_list
""" Returns a list of randomized colors
Args:
cluster_count (int): Number of random colors to generate
Returns:
(list): List containing 3-element color lists
"""
if (cluster_count > len(color_list)):
for i in xrange(len(color_list), cluster_count):
color_list.append(random_color_gen())
return color_list
def get_centroid_of_pts(arr):
length = arr.shape[0]
sum_x = np.sum(arr[:, 0])
sum_y = np.sum(arr[:, 1])
sum_z = np.sum(arr[:, 2])
return np.array([[sum_x/length, sum_y/length, sum_z/length]])
def lidar_callback(msg):
global lidar_msg
if lidar_msg is None:
rospy.loginfo("lidar_callback")
lidar_msg = msg
def find_max_list_idx(list):
list_len = [len(i) for i in list]
return np.argmax(np.array(list_len))
def process_lidar_msg(n_bins=72, z_std_thresh=0.1):
global lidar_msg
if not lidar_msg:
return
rospy.loginfo("process_lidar_msg")
points = pc2.read_points_list(lidar_msg, field_names=("x", "y", "z"), skip_nans=True)
print "size points:", len(points)
#points = [p for p in points if p[2] < -0.39 or p[2] > -0.35 and math.sqrt(p[0] ** 2 + p[1] ** 2 + p[2] ** 2) < 3.0]
#print "size points after Z basic cleanout:", len(points)
#points = [p for p in points if math.sqrt(p[0] ** 2 + p[1] ** 2 + p[2] ** 2) < 3.0]
#print "size points after distance cleanout:", len(points)
cloud = pcl.PointCloud(np.array(points, dtype=np.float32))
clip_distance = 2.5
passthrough = cloud.make_passthrough_filter()
passthrough.set_filter_field_name('x')
passthrough.set_filter_limits(-clip_distance, clip_distance)
cloud_filtered = passthrough.filter()
passthrough = cloud_filtered.make_passthrough_filter()
passthrough.set_filter_field_name('y')
passthrough.set_filter_limits(-clip_distance, clip_distance)
cloud_filtered = passthrough.filter()
passthrough = cloud_filtered.make_passthrough_filter()
passthrough.set_filter_field_name('z')
passthrough.set_filter_limits(-clip_distance, clip_distance)
cloud_filtered = passthrough.filter()
vg = cloud_filtered.make_voxel_grid_filter()
vg.set_leaf_size(0.01, 0.01, 0.01)
cloud_filtered = vg.filter()
# divide the pointcloud in bins
bin_size = 360/float(n_bins)
colors = get_color_list(n_bins)
np_p = cloud_filtered.to_array()
bin_idx = -1
#viewer.InitCameraParameters()
marker_array = MarkerArray()
closest_p_dist = float("inf")
closest_p = None
for i in xrange((n_bins / 2)):
for sign in [1, -1]:
bin_idx += 1
bin_start = (i * bin_size) * sign
bin_end = ((i + 1) * bin_size) * sign
if sign > 0:
fov = [bin_start, bin_end]
else:
fov = [bin_end, bin_start]
cond = hv_in_range(x=np_p[:, 0],
y=np_p[:, 1],
z=np_p[:, 2],
fov=fov,
fov_type='h')
np_p_ranged = np_p[cond]
z_std = np.std(np_p_ranged[:, 2])
if z_std < z_std_thresh:
cloud_cluster = pcl.PointCloud()
cloud_cluster.from_array(np_p_ranged)
pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud_cluster, 255, 0, 0)
viewer.AddPointCloud_ColorHandler(cloud_cluster, pccolor, b'cluster_{}'.format(bin_idx), 0)
print "\tz_std:", z_std
continue
color = colors[bin_idx]
cloud_bin = pcl.PointCloud(np_p_ranged)
tree = cloud_bin.make_kdtree()
ec = cloud_bin.make_EuclideanClusterExtraction()
ec.set_ClusterTolerance(0.15)
ec.set_MinClusterSize(20)
ec.set_MaxClusterSize(25000)
ec.set_SearchMethod(tree)
cluster_indices = ec.Extract()
if len(cluster_indices) <= 0:
cloud_cluster = pcl.PointCloud()
cloud_cluster.from_array(np_p_ranged)
pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud_cluster, 255, 0, 0)
viewer.AddPointCloud_ColorHandler(cloud_cluster, pccolor, b'cluster_{}'.format(bin_idx), 0)
print "\tlen(cluster_indices)", len(cluster_indices)
continue
max_cluster_idx = find_max_list_idx(cluster_indices)
len_max_cluster = len(cluster_indices[max_cluster_idx])
#print 'cluster_indices :', len(cluster_indices), " count."
#print 'max_cluster_idx :', max_cluster_idx, " len:", len_max_cluster
if len(cluster_indices[max_cluster_idx]) < 100:
continue
cluster_points = np.zeros((len_max_cluster, 3), dtype=np.float32)
for j, indice in enumerate(cluster_indices[max_cluster_idx]):
cluster_points[j][0] = cloud_bin[indice][0]
cluster_points[j][1] = cloud_bin[indice][1]
cluster_points[j][2] = cloud_bin[indice][2]
cloud_cluster = pcl.PointCloud()
cloud_cluster.from_array(cluster_points)
#
#
pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud_cluster, color[0], color[1], color[2])
viewer.AddPointCloud_ColorHandler(cloud_cluster, pccolor, b'cluster_{}'.format(bin_idx), 0)
print "z_std:", z_std, "bin_start:", bin_start, "bin_end:", bin_end, "bin_idx:", bin_idx, "color:", color
centroid = get_centroid_of_pts(cluster_points)[0]
#print "centroid:", centroid
x, y, z = centroid
f_marker = create_marker((x,
y,
z),
color=(0.6, 0.1, 0.0), duration=2, m_scale=0.25, marker_id=bin_idx)
marker_array.markers.append(f_marker)
d = math.sqrt(x ** 2 + y ** 2 + z ** 2)
if d < closest_p_dist:
closest_p_dist = d
closest_p = centroid
# pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud_bin, color[0], color[1], color[2])
# viewer.AddPointCloud_ColorHandler(cloud_bin, pccolor, b'cluster_{}'.format(bin_idx), 0)
viewer.AddCube(-0.25, 0.25, -0.15, 0.15, -0.4, -0.2, 255, 255, 255, "robot")
# color = colors[0]
# pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud_filtered, color[0], color[1], color[2])
# viewer.AddPointCloud_ColorHandler(cloud_filtered, pccolor, b'cluster_{}'.format(0), 0)
# seg = cloud_filtered.make_segmenter()
# seg.set_optimize_coefficients(True)
# seg.set_model_type(pcl.SACMODEL_PLANE)
# seg.set_method_type(pcl.SAC_RANSAC)
# seg.set_MaxIterations(100)
# seg.set_distance_threshold(0.25)
#
# indices, model = seg.segment()
# tmp = cloud_filtered.to_array()
# tmp = np.delete(tmp, indices, 0)
# cloud_filtered.from_array(tmp)
# tree = cloud_filtered.make_kdtree()
# ec = cloud_filtered.make_EuclideanClusterExtraction()
# ec.set_ClusterTolerance(0.25)
# ec.set_MinClusterSize(2)
# ec.set_MaxClusterSize(25000)
# ec.set_SearchMethod(tree)
# cluster_indices = ec.Extract()
#
# print 'cluster_indices :', len(cluster_indices), " count."
#
# colors = get_color_list(len(cluster_indices))
#
# cloud_cluster = pcl.PointCloud()
#
# for j, indices in enumerate(cluster_indices):
# # cloudsize = indices
# print 'j:', j, 'indices:', str(len(indices))
#
# points = np.zeros((len(indices), 3), dtype=np.float32)
#
# for i, indice in enumerate(indices):
# points[i][0] = cloud_filtered[indice][0]
# points[i][1] = cloud_filtered[indice][1]
# points[i][2] = cloud_filtered[indice][2]
#
# z_std = np.std(points[:, 2])
# print "z std:", z_std
#
# cloud_cluster.from_array(points)
# ss = "/tmp/cluster/cloud_cluster_" + str(j) + ".pcd"
# pcl.save(cloud_cluster, ss)
#
# color = colors[j]
# pccolor = pcl.pcl_visualization.PointCloudColorHandleringCustom(cloud, color[0], color[1], color[2])
# viewer.AddPointCloud_ColorHandler(cloud_cluster, pccolor, b'cluster_{}'.format(j), 0)
if closest_p is not None:
closest_p_marker = create_marker((closest_p[0],
closest_p[1],
closest_p[2]),
color=(0.9, 0.1, 0.0), duration=2, m_scale=0.5, marker_id=0)
pub_closest_obstacle_pt.publish(closest_p_marker)
pub_obstacles_pts.publish(marker_array)
v = True
while v:
v = not (viewer.WasStopped())
viewer.SpinOnce()
#time.sleep(0.5)
#break
# for j, indices in enumerate(cluster_indices):
# viewer.RemovePointCloud(b'cluster_{}'.format(j), 0)
# for i in xrange(n_bins):
# viewer.RemovePointCloud(b'cluster_{}'.format(i), 0)
viewer.remove_all_pointclouds()
viewer.remove_all_shapes()
if __name__ == '__main__':
rospy.init_node('obstacle_detection_3d_lidar')
rospy.loginfo("init node...")
rospy.Subscriber('/velodyne/points2', sensor_msgs.msg.PointCloud2, lidar_callback)
rate_slow = rospy.Rate(1.0)
while not rospy.is_shutdown():
try:
process_lidar_msg()
except Exception as e:
tb = traceback.format_exc()
rospy.logerr("Main Exception: %s", str(tb))
rate_slow.sleep()
rospy.loginfo("obstacle_detection_3d_lidar node stop")
3 | 34.016588 | 120 | 0.622153 | 1,923 | 14,355 | 4.433177 | 0.185647 | 0.027449 | 0.01783 | 0.018299 | 0.323988 | 0.293138 | 0.227918 | 0.187683 | 0.173607 | 0.161877 | 0 | 0.031058 | 0.262069 | 14,355 | 422 | 121 | 34.016588 | 0.773718 | 0.202926 | 0 | 0.139535 | 0 | 0 | 0.039509 | 0.010293 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.055814 | 0.125581 | null | null | 0.018605 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
a0a88e5af872f4e8e52ce13bb4b58260947c31bb | 362 | py | Python | Sergeant-RANK/DAY-10/412A.py | rohansaini886/Peer-Programming-Hub-CP-Winter_Camp | d27fb6aa7e726e6d2cb95270c9e644d38d64dd1c | [
"MIT"
] | 2 | 2021-12-09T18:07:46.000Z | 2022-01-26T16:51:18.000Z | Sergeant-RANK/DAY-10/412A.py | rohansaini886/Peer-Programming-Hub-CP-Winter_Camp | d27fb6aa7e726e6d2cb95270c9e644d38d64dd1c | [
"MIT"
] | null | null | null | Sergeant-RANK/DAY-10/412A.py | rohansaini886/Peer-Programming-Hub-CP-Winter_Camp | d27fb6aa7e726e6d2cb95270c9e644d38d64dd1c | [
"MIT"
] | null | null | null | n,k = map(int,input().split())
s = input()
if n//2 >= k:
for i in range(k-1):
print("LEFT")
for i in range(n-1):
print("PRINT",s[i])
print("RIGHT")
print("PRINT",s[n-1])
else:
for i in range(n-k):
print("RIGHT")
for i in range(1,n):
print("PRINT",s[-i])
print("LEFT")
print("PRINT",s[0])
| 19.052632 | 30 | 0.475138 | 62 | 362 | 2.774194 | 0.306452 | 0.093023 | 0.139535 | 0.255814 | 0.337209 | 0 | 0 | 0 | 0 | 0 | 0 | 0.023715 | 0.301105 | 362 | 18 | 31 | 20.111111 | 0.656126 | 0 | 0 | 0.25 | 0 | 0 | 0.105263 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.5 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
a0b0499b8715889aaff0878f603c5afb4365f885 | 13,425 | py | Python | nova/virt/xenapi_conn.py | tqrg-bot/nova | 321f581660aad3fc9da5f88276bfdf11f6960d97 | [
"Apache-2.0"
] | null | null | null | nova/virt/xenapi_conn.py | tqrg-bot/nova | 321f581660aad3fc9da5f88276bfdf11f6960d97 | [
"Apache-2.0"
] | null | null | null | nova/virt/xenapi_conn.py | tqrg-bot/nova | 321f581660aad3fc9da5f88276bfdf11f6960d97 | [
"Apache-2.0"
] | null | null | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2010 OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
A connection to XenServer or Xen Cloud Platform.
The concurrency model for this class is as follows:
All XenAPI calls are on a green thread (using eventlet's "tpool"
thread pool). They are remote calls, and so may hang for the usual
reasons.
All long-running XenAPI calls (VM.start, VM.reboot, etc) are called async
(using XenAPI.VM.async_start etc). These return a task, which can then be
polled for completion.
This combination of techniques means that we don't block the main thread at
all, and at the same time we don't hold lots of threads waiting for
long-running operations.
FIXME: get_info currently doesn't conform to these rules, and will block the
reactor thread if the VM.get_by_name_label or VM.get_record calls block.
**Related Flags**
:xenapi_connection_url: URL for connection to XenServer/Xen Cloud Platform.
:xenapi_connection_username: Username for connection to XenServer/Xen Cloud
Platform (default: root).
:xenapi_connection_password: Password for connection to XenServer/Xen Cloud
Platform.
:xenapi_task_poll_interval: The interval (seconds) used for polling of
remote tasks (Async.VM.start, etc)
(default: 0.5).
:target_host: the iSCSI Target Host IP address, i.e. the IP
address for the nova-volume host
:target_port: iSCSI Target Port, 3260 Default
:iqn_prefix: IQN Prefix, e.g. 'iqn.2010-10.org.openstack'
"""
import sys
import urlparse
import xmlrpclib
from eventlet import event
from eventlet import tpool
from nova import context
from nova import db
from nova import utils
from nova import flags
from nova import log as logging
from nova.virt.xenapi.vmops import VMOps
from nova.virt.xenapi.volumeops import VolumeOps
LOG = logging.getLogger("nova.virt.xenapi")
FLAGS = flags.FLAGS
flags.DEFINE_string('xenapi_connection_url',
None,
'URL for connection to XenServer/Xen Cloud Platform.'
' Required if connection_type=xenapi.')
flags.DEFINE_string('xenapi_connection_username',
'root',
'Username for connection to XenServer/Xen Cloud Platform.'
' Used only if connection_type=xenapi.')
flags.DEFINE_string('xenapi_connection_password',
None,
'Password for connection to XenServer/Xen Cloud Platform.'
' Used only if connection_type=xenapi.')
flags.DEFINE_float('xenapi_task_poll_interval',
0.5,
'The interval used for polling of remote tasks '
'(Async.VM.start, etc). Used only if '
'connection_type=xenapi.')
flags.DEFINE_string('xenapi_image_service',
'glance',
'Where to get VM images: glance or objectstore.')
flags.DEFINE_float('xenapi_vhd_coalesce_poll_interval',
5.0,
'The interval used for polling of coalescing vhds.'
' Used only if connection_type=xenapi.')
flags.DEFINE_integer('xenapi_vhd_coalesce_max_attempts',
5,
'Max number of times to poll for VHD to coalesce.'
' Used only if connection_type=xenapi.')
flags.DEFINE_string('target_host',
None,
'iSCSI Target Host')
flags.DEFINE_string('target_port',
'3260',
'iSCSI Target Port, 3260 Default')
flags.DEFINE_string('iqn_prefix',
'iqn.2010-10.org.openstack',
'IQN Prefix')
# NOTE(sirp): This is a work-around for a bug in Ubuntu Maverick, when we pull
# support for it, we should remove this
flags.DEFINE_bool('xenapi_remap_vbd_dev', False,
'Used to enable the remapping of VBD dev '
'(Works around an issue in Ubuntu Maverick)')
flags.DEFINE_string('xenapi_remap_vbd_dev_prefix', 'sd',
'Specify prefix to remap VBD dev to '
'(ex. /dev/xvdb -> /dev/sdb)')
def get_connection(_):
"""Note that XenAPI doesn't have a read-only connection mode, so
the read_only parameter is ignored."""
url = FLAGS.xenapi_connection_url
username = FLAGS.xenapi_connection_username
password = FLAGS.xenapi_connection_password
if not url or password is None:
raise Exception(_('Must specify xenapi_connection_url, '
'xenapi_connection_username (optionally), and '
'xenapi_connection_password to use '
'connection_type=xenapi'))
return XenAPIConnection(url, username, password)
class XenAPIConnection(object):
"""A connection to XenServer or Xen Cloud Platform"""
def __init__(self, url, user, pw):
session = XenAPISession(url, user, pw)
self._vmops = VMOps(session)
self._volumeops = VolumeOps(session)
def init_host(self, host):
#FIXME(armando): implement this
#NOTE(armando): would we need a method
#to call when shutting down the host?
#e.g. to do session logout?
pass
def list_instances(self):
"""List VM instances"""
return self._vmops.list_instances()
def spawn(self, instance):
"""Create VM instance"""
self._vmops.spawn(instance)
def snapshot(self, instance, image_id):
""" Create snapshot from a running VM instance """
self._vmops.snapshot(instance, image_id)
def reboot(self, instance):
"""Reboot VM instance"""
self._vmops.reboot(instance)
def set_admin_password(self, instance, new_pass):
"""Set the root/admin password on the VM instance"""
self._vmops.set_admin_password(instance, new_pass)
def destroy(self, instance):
"""Destroy VM instance"""
self._vmops.destroy(instance)
def pause(self, instance, callback):
"""Pause VM instance"""
self._vmops.pause(instance, callback)
def unpause(self, instance, callback):
"""Unpause paused VM instance"""
self._vmops.unpause(instance, callback)
def suspend(self, instance, callback):
"""suspend the specified instance"""
self._vmops.suspend(instance, callback)
def resume(self, instance, callback):
"""resume the specified instance"""
self._vmops.resume(instance, callback)
def get_info(self, instance_id):
"""Return data about VM instance"""
return self._vmops.get_info(instance_id)
def get_diagnostics(self, instance):
"""Return data about VM diagnostics"""
return self._vmops.get_diagnostics(instance)
def get_console_output(self, instance):
"""Return snapshot of console"""
return self._vmops.get_console_output(instance)
def get_ajax_console(self, instance):
"""Return link to instance's ajax console"""
return self._vmops.get_ajax_console(instance)
def attach_volume(self, instance_name, device_path, mountpoint):
"""Attach volume storage to VM instance"""
return self._volumeops.attach_volume(instance_name,
device_path,
mountpoint)
def detach_volume(self, instance_name, mountpoint):
"""Detach volume storage to VM instance"""
return self._volumeops.detach_volume(instance_name, mountpoint)
def get_console_pool_info(self, console_type):
xs_url = urlparse.urlparse(FLAGS.xenapi_connection_url)
return {'address': xs_url.netloc,
'username': FLAGS.xenapi_connection_username,
'password': FLAGS.xenapi_connection_password}
class XenAPISession(object):
"""The session to invoke XenAPI SDK calls"""
def __init__(self, url, user, pw):
self.XenAPI = self.get_imported_xenapi()
self._session = self._create_session(url)
self._session.login_with_password(user, pw)
self.loop = None
def get_imported_xenapi(self):
"""Stubout point. This can be replaced with a mock xenapi module."""
return __import__('XenAPI')
def get_xenapi(self):
"""Return the xenapi object"""
return self._session.xenapi
def get_xenapi_host(self):
"""Return the xenapi host"""
return self._session.xenapi.session.get_this_host(self._session.handle)
def call_xenapi(self, method, *args):
"""Call the specified XenAPI method on a background thread."""
f = self._session.xenapi
for m in method.split('.'):
f = f.__getattr__(m)
return tpool.execute(f, *args)
def call_xenapi_request(self, method, *args):
"""Some interactions with dom0, such as interacting with xenstore's
param record, require using the xenapi_request method of the session
object. This wraps that call on a background thread.
"""
f = self._session.xenapi_request
return tpool.execute(f, method, *args)
def async_call_plugin(self, plugin, fn, args):
"""Call Async.host.call_plugin on a background thread."""
return tpool.execute(self._unwrap_plugin_exceptions,
self._session.xenapi.Async.host.call_plugin,
self.get_xenapi_host(), plugin, fn, args)
def wait_for_task(self, id, task):
"""Return the result of the given task. The task is polled
until it completes. Not re-entrant."""
done = event.Event()
self.loop = utils.LoopingCall(self._poll_task, id, task, done)
self.loop.start(FLAGS.xenapi_task_poll_interval, now=True)
rv = done.wait()
self.loop.stop()
return rv
def _stop_loop(self):
"""Stop polling for task to finish."""
#NOTE(sandy-walsh) Had to break this call out to support unit tests.
if self.loop:
self.loop.stop()
def _create_session(self, url):
"""Stubout point. This can be replaced with a mock session."""
return self.XenAPI.Session(url)
def _poll_task(self, id, task, done):
"""Poll the given XenAPI task, and fire the given action if we
get a result.
"""
try:
name = self._session.xenapi.task.get_name_label(task)
status = self._session.xenapi.task.get_status(task)
action = dict(
instance_id=int(id),
action=name[0:255], # Ensure action is never > 255
error=None)
if status == "pending":
return
elif status == "success":
result = self._session.xenapi.task.get_result(task)
LOG.info(_("Task [%(name)s] %(task)s status:"
" success %(result)s") % locals())
done.send(_parse_xmlrpc_value(result))
else:
error_info = self._session.xenapi.task.get_error_info(task)
action["error"] = str(error_info)
LOG.warn(_("Task [%(name)s] %(task)s status:"
" %(status)s %(error_info)s") % locals())
done.send_exception(self.XenAPI.Failure(error_info))
db.instance_action_create(context.get_admin_context(), action)
except self.XenAPI.Failure, exc:
LOG.warn(exc)
done.send_exception(*sys.exc_info())
self._stop_loop()
def _unwrap_plugin_exceptions(self, func, *args, **kwargs):
"""Parse exception details"""
try:
return func(*args, **kwargs)
except self.XenAPI.Failure, exc:
LOG.debug(_("Got exception: %s"), exc)
if (len(exc.details) == 4 and
exc.details[0] == 'XENAPI_PLUGIN_EXCEPTION' and
exc.details[2] == 'Failure'):
params = None
try:
params = eval(exc.details[3])
except:
raise exc
raise self.XenAPI.Failure(params)
else:
raise
except xmlrpclib.ProtocolError, exc:
LOG.debug(_("Got exception: %s"), exc)
raise
def _parse_xmlrpc_value(val):
"""Parse the given value as if it were an XML-RPC value. This is
sometimes used as the format for the task.result field."""
if not val:
return val
x = xmlrpclib.loads(
'<?xml version="1.0"?><methodResponse><params><param>' +
val +
'</param></params></methodResponse>')
return x[0][0]
| 38.577586 | 79 | 0.619888 | 1,652 | 13,425 | 4.886199 | 0.239104 | 0.029732 | 0.018954 | 0.016477 | 0.217914 | 0.168979 | 0.147919 | 0.141229 | 0.080154 | 0.056863 | 0 | 0.006479 | 0.287225 | 13,425 | 347 | 80 | 38.688761 | 0.837078 | 0.074562 | 0 | 0.108911 | 0 | 0 | 0.17099 | 0.060157 | 0 | 0 | 0 | 0.005764 | 0 | 0 | null | null | 0.054455 | 0.074257 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
39ff7e8ae4b95de34d6709bb4cbec6f4eb0587ba | 63 | py | Python | lang/py/cookbook/v2/source/cb2_1_6_exm_2.py | ch1huizong/learning | 632267634a9fd84a5f5116de09ff1e2681a6cc85 | [
"MIT"
] | null | null | null | lang/py/cookbook/v2/source/cb2_1_6_exm_2.py | ch1huizong/learning | 632267634a9fd84a5f5116de09ff1e2681a6cc85 | [
"MIT"
] | null | null | null | lang/py/cookbook/v2/source/cb2_1_6_exm_2.py | ch1huizong/learning | 632267634a9fd84a5f5116de09ff1e2681a6cc85 | [
"MIT"
] | null | null | null | largeString = ''
for piece in pieces:
largeString += piece
| 15.75 | 24 | 0.68254 | 7 | 63 | 6.142857 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | 63 | 3 | 25 | 21 | 0.877551 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
260803e707f972b3036591c281656b6a93e05a06 | 669 | py | Python | members/migrations/0002_auto_20200409_2207.py | duplxey/NForum | 990215e5a841ac054fd3c0a167dee37298a70fb8 | [
"MIT"
] | 7 | 2019-11-12T14:01:17.000Z | 2022-01-29T19:17:09.000Z | members/migrations/0002_auto_20200409_2207.py | duplxey/NForum | 990215e5a841ac054fd3c0a167dee37298a70fb8 | [
"MIT"
] | 4 | 2019-12-08T10:03:21.000Z | 2020-04-07T20:27:53.000Z | members/migrations/0002_auto_20200409_2207.py | duplxey/NForum | 990215e5a841ac054fd3c0a167dee37298a70fb8 | [
"MIT"
] | 1 | 2022-01-29T13:44:24.000Z | 2022-01-29T13:44:24.000Z | # Generated by Django 3.0.5 on 2020-04-09 20:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='alert',
options={'ordering': ['-datetime']},
),
migrations.AlterModelOptions(
name='userachievement',
options={'ordering': ['-datetime']},
),
migrations.AlterField(
model_name='userprofile',
name='avatar',
field=models.ImageField(blank=True, null=True, upload_to='avatars/'),
),
]
| 24.777778 | 81 | 0.560538 | 58 | 669 | 6.413793 | 0.741379 | 0.145161 | 0.166667 | 0.177419 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.040773 | 0.303438 | 669 | 26 | 82 | 25.730769 | 0.757511 | 0.067265 | 0 | 0.35 | 1 | 0 | 0.157556 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.05 | 0 | 0.2 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
2611b740220bd2513273d982f6a8db0ccee68181 | 2,120 | py | Python | indset/generate/randgen.py | skyman/independent-set | e2b6a2dc231aba5d9391f305d61d556b928e4d3e | [
"MIT"
] | null | null | null | indset/generate/randgen.py | skyman/independent-set | e2b6a2dc231aba5d9391f305d61d556b928e4d3e | [
"MIT"
] | null | null | null | indset/generate/randgen.py | skyman/independent-set | e2b6a2dc231aba5d9391f305d61d556b928e4d3e | [
"MIT"
] | null | null | null | # coding=utf-8
import numpy as np
import random
import itertools
from indset.simulate import Grid, Particle, AlignmentSimulator
def generate_random_grid(n_particles, simulator_type, weighted_particle_types, size=None):
# weighted particle types is a list of particle types in (single-param initializer, weight) format
if n_particles <= 0:
raise ValueError("At least 1 particle needs to be generated.")
if size is None:
width_height = int(n_particles ** 0.5) * 4
size = (width_height, width_height)
grid = Grid(size)
print "Initialized a grid of size %d, %d" % size
total_weight = float(sum(wp[1] for wp in weighted_particle_types))
# Choose the classes for our particles:
particle_types = list(np.random.choice([wt[0] for wt in weighted_particle_types], n_particles, True,
[wt[1] / total_weight for wt in weighted_particle_types]))
# Make a list of valid positions:
valid_x = xrange(grid.min[0], grid.max[0] + 1)
valid_y = xrange(grid.min[0], grid.max[0] + 1)
valid_positions = [x for x in itertools.product(valid_x, valid_y) if grid.is_position_in_bounds(x)]
i = 0
for particle_type in particle_types:
while True:
# Choose a random position for the particle
coords = random.choice(list(valid_positions))
if grid.get_particle(coords) is not None:
continue
particle = particle_type(coords, i)
grid.add_particle(particle)
try:
simulator_type.validate_grid(grid)
except ValueError:
grid.remove_particle(particle)
continue
print "Successfully inserted %s #%d" % (type(particle).__name__, i)
i += 1
break
print "Random grid generation successful"
return grid
def generate_random_alignment_grid(n_particles, size=None, simulator_type=AlignmentSimulator, base_class=Particle):
classes = [(base_class, 1)]
return generate_random_grid(n_particles, simulator_type, classes, size)
| 33.125 | 115 | 0.65566 | 281 | 2,120 | 4.758007 | 0.352313 | 0.077786 | 0.078534 | 0.051608 | 0.145101 | 0.145101 | 0.103216 | 0.041885 | 0.041885 | 0 | 0 | 0.011509 | 0.262264 | 2,120 | 63 | 116 | 33.650794 | 0.84335 | 0.104245 | 0 | 0.051282 | 1 | 0 | 0.071844 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.102564 | null | null | 0.076923 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
262b97798d77f89816f22be0690cb76b380e53fa | 3,317 | py | Python | capa/features/extractors/dnfile/insn.py | Stevemaster92/capa | e0786df2ff0e9212f66fa4fdf0ee96adcba21583 | [
"Apache-2.0"
] | null | null | null | capa/features/extractors/dnfile/insn.py | Stevemaster92/capa | e0786df2ff0e9212f66fa4fdf0ee96adcba21583 | [
"Apache-2.0"
] | null | null | null | capa/features/extractors/dnfile/insn.py | Stevemaster92/capa | e0786df2ff0e9212f66fa4fdf0ee96adcba21583 | [
"Apache-2.0"
] | null | null | null | # Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at: [package root]/LICENSE.txt
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Tuple, Iterator, Optional
from itertools import chain
if TYPE_CHECKING:
from dncil.cil.instruction import Instruction
from dncil.cil.body import CilMethodBody
from capa.features.common import Feature
from dncil.clr.token import StringToken
from dncil.cil.opcode import OpCodes
import capa.features.extractors.helpers
from capa.features.insn import API, Number
from capa.features.common import String
from capa.features.extractors.dnfile.helpers import (
read_dotnet_user_string,
get_dotnet_managed_imports,
get_dotnet_unmanaged_imports,
)
def get_imports(ctx: Dict) -> Dict:
if "imports_cache" not in ctx:
ctx["imports_cache"] = {
token: imp
for (token, imp) in chain(get_dotnet_managed_imports(ctx["pe"]), get_dotnet_unmanaged_imports(ctx["pe"]))
}
return ctx["imports_cache"]
def extract_insn_api_features(f: CilMethodBody, bb: CilMethodBody, insn: Instruction) -> Iterator[Tuple[API, int]]:
"""parse instruction API features"""
if insn.opcode not in (OpCodes.Call, OpCodes.Callvirt, OpCodes.Jmp, OpCodes.Calli):
return
name: str = get_imports(f.ctx).get(insn.operand.value, "")
if not name:
return
if "::" in name:
# like System.IO.File::OpenRead
yield API(name), insn.offset
else:
# like kernel32.CreateFileA
dll, _, symbol = name.rpartition(".")
for name_variant in capa.features.extractors.helpers.generate_symbols(dll, symbol):
yield API(name_variant), insn.offset
def extract_insn_number_features(
f: CilMethodBody, bb: CilMethodBody, insn: Instruction
) -> Iterator[Tuple[Number, int]]:
"""parse instruction number features"""
if insn.is_ldc():
yield Number(insn.get_ldc()), insn.offset
def extract_insn_string_features(
f: CilMethodBody, bb: CilMethodBody, insn: Instruction
) -> Iterator[Tuple[String, int]]:
"""parse instruction string features"""
if not insn.is_ldstr():
return
if not isinstance(insn.operand, StringToken):
return
user_string: Optional[str] = read_dotnet_user_string(f.ctx["pe"], insn.operand)
if user_string is None:
return
yield String(user_string), insn.offset
def extract_features(f: CilMethodBody, bb: CilMethodBody, insn: Instruction) -> Iterator[Tuple[Feature, int]]:
"""extract instruction features"""
for inst_handler in INSTRUCTION_HANDLERS:
for (feature, offset) in inst_handler(f, bb, insn):
yield feature, offset
INSTRUCTION_HANDLERS = (
extract_insn_api_features,
extract_insn_number_features,
extract_insn_string_features,
)
| 34.195876 | 117 | 0.719325 | 436 | 3,317 | 5.330275 | 0.341743 | 0.025818 | 0.027539 | 0.041308 | 0.156627 | 0.111876 | 0.111876 | 0.111876 | 0.111876 | 0 | 0 | 0.002974 | 0.189026 | 3,317 | 96 | 118 | 34.552083 | 0.860967 | 0.224299 | 0 | 0.114754 | 0 | 0 | 0.018868 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.081967 | false | 0 | 0.327869 | 0 | 0.508197 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
262c0bc0d993d31592f0d2386487ba298492f7b8 | 2,000 | py | Python | CsvAnalyzer.py | nimrodkre/graphAnalyzer | 04778d4bbeed9dd09a10a513e9ae5fb7f08a25aa | [
"MIT"
] | 1 | 2020-12-12T09:30:48.000Z | 2020-12-12T09:30:48.000Z | CsvAnalyzer.py | nimrodkre/graphAnalyzer | 04778d4bbeed9dd09a10a513e9ae5fb7f08a25aa | [
"MIT"
] | null | null | null | CsvAnalyzer.py | nimrodkre/graphAnalyzer | 04778d4bbeed9dd09a10a513e9ae5fb7f08a25aa | [
"MIT"
] | null | null | null | import pandas as pd
from GraphAnalyzerError import GraphAnalyzerError
import math
class CsvAnalyzer:
def __init__(self, filename, x_column_name, y_column_name, x_error_name,
y_error_name):
print(filename)
self.data = pd.read_csv(filename)
self.x_column_name = x_column_name
self.y_column_name = y_column_name
self.x_error_name = x_error_name
self.y_error_name = y_error_name
def get_x_data(self):
try:
return [data for data in self.data[self.x_column_name] if
not math.isnan(data)]
except KeyError:
raise GraphAnalyzerError(
"The following column does not exist in given csv: {}".format(
self.x_column_name))
def get_y_data(self):
try:
return [data for data in self.data[self.y_column_name] if
not math.isnan(data)]
except KeyError:
raise GraphAnalyzerError(
"The following column does not exist in given csv: {}".format(
self.x_column_name))
def get_x_error_data(self):
if not self.x_error_name:
return [0 for i in range(len(self.get_x_data()))]
try:
return [data if not math.isnan(data) else 0 for data in
self.data[self.x_error_name]]
except KeyError:
raise GraphAnalyzerError(
"The following column does not exist in given csv: {}".format(
self.x_error_name))
def get_y_error_data(self):
if not self.y_error_name:
return [0 for i in range(len(self.get_x_data()))]
try:
return [data if not math.isnan(data) else 0 for data in
self.data[self.y_error_name]]
except KeyError:
raise GraphAnalyzerError(
"The following column does not exist in given csv: {}".format(
self.y_error_name))
| 36.363636 | 78 | 0.587 | 264 | 2,000 | 4.208333 | 0.166667 | 0.09721 | 0.059406 | 0.054005 | 0.780378 | 0.708371 | 0.668767 | 0.665167 | 0.665167 | 0.665167 | 0 | 0.00303 | 0.34 | 2,000 | 54 | 79 | 37.037037 | 0.838636 | 0 | 0 | 0.5 | 0 | 0 | 0.104 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.104167 | false | 0 | 0.0625 | 0 | 0.3125 | 0.020833 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
262f388f79df7b2fb57047f69a8ca61d4c20abbc | 727 | py | Python | account_verification_flask/services/twilio_services.py | TwilioDevEd/account-verification-flask | f2da4ccfe0ba16f71828058ca384de0c196143c3 | [
"MIT"
] | 8 | 2015-11-18T20:50:04.000Z | 2019-05-14T17:18:57.000Z | account_verification_flask/services/twilio_services.py | TwilioDevEd/account-verification-flask | f2da4ccfe0ba16f71828058ca384de0c196143c3 | [
"MIT"
] | 96 | 2015-11-23T21:31:26.000Z | 2021-08-02T05:52:44.000Z | account_verification_flask/services/twilio_services.py | TwilioDevEd/account-verification-flask | f2da4ccfe0ba16f71828058ca384de0c196143c3 | [
"MIT"
] | 9 | 2015-11-18T20:50:07.000Z | 2020-10-24T15:28:49.000Z | ๏ปฟimport account_verification_flask.utilities
from account_verification_flask.utilities.settings import TwilioSettings
from twilio.rest import Client
class TwilioServices:
twilio_client = None
def __init__(self):
if TwilioServices.twilio_client is None:
TwilioServices.twilio_client = Client(
TwilioSettings.api_key(),
TwilioSettings.api_secret(),
TwilioSettings.account_sid(),
)
def send_registration_success_sms(self, to_number):
self.twilio_client.messages.create(
body=account_verification_flask.utilities.Signup_Complete,
to=to_number,
from_=TwilioSettings.phone_number(),
)
| 31.608696 | 72 | 0.68088 | 73 | 727 | 6.452055 | 0.493151 | 0.101911 | 0.152866 | 0.210191 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.253095 | 727 | 22 | 73 | 33.045455 | 0.865562 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.166667 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
263c7b00a4f6a28434d6e1dd48536ccedabff5be | 256 | py | Python | setup.py | palash25/GitterPy | 95fc7230ce2ec0ad12566c4aa71af0cdb7b03725 | [
"MIT"
] | 3 | 2018-01-15T16:27:04.000Z | 2018-03-11T18:05:08.000Z | setup.py | palash25/gitter-cli | 95fc7230ce2ec0ad12566c4aa71af0cdb7b03725 | [
"MIT"
] | null | null | null | setup.py | palash25/gitter-cli | 95fc7230ce2ec0ad12566c4aa71af0cdb7b03725 | [
"MIT"
] | null | null | null | from setuptools import setup
setup(
name='GitterCLI',
version='1.0',
py_modules=['cli'],
install_requires=[
'Click',
'requests',
],
entry_points='''
[console_scripts]
gitterpy=cli:cli
''',
) | 16 | 28 | 0.527344 | 24 | 256 | 5.458333 | 0.875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011494 | 0.320313 | 256 | 16 | 29 | 16 | 0.741379 | 0 | 0 | 0 | 0 | 0 | 0.326848 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.071429 | 0 | 0.071429 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26401bd036a50bd140a56d1b48458b8ed688b803 | 361 | py | Python | ex0/application.py | hespinoza01/CS50x.ni-Week14 | 524c3396948e83462050f440ddcb2ddef0d2a572 | [
"MIT"
] | 2 | 2019-03-21T19:56:45.000Z | 2019-03-24T17:59:42.000Z | ex0/application.py | hespinoza01/CS50x.ni-Week14 | 524c3396948e83462050f440ddcb2ddef0d2a572 | [
"MIT"
] | null | null | null | ex0/application.py | hespinoza01/CS50x.ni-Week14 | 524c3396948e83462050f440ddcb2ddef0d2a572 | [
"MIT"
] | null | null | null | #Importar Framework y Utilidades
from flask import Flask,redirect, render_template, session,url_for
#Declarar que es una aplicacion web
app=Flask(__name__)
#Definir comportamiento con URL vacia
@app.route("/")
def main():
return render_template("index.html")
@app.route("/<string:name>")
def name(name):
return render_template("layout.html",name=name)
| 27.769231 | 66 | 0.761773 | 51 | 361 | 5.235294 | 0.647059 | 0.157303 | 0.149813 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.113573 | 361 | 12 | 67 | 30.083333 | 0.834375 | 0.279778 | 0 | 0 | 0 | 0 | 0.140078 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.125 | 0.25 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
264f01b08e0644d3f7aea42c69e1721df6dd3602 | 2,232 | py | Python | coursera_python_specialization/px6_1.py | missulmer/Pythonstudy | fc811570cafaa383ac98f489028583081932b3e5 | [
"CC0-1.0"
] | null | null | null | coursera_python_specialization/px6_1.py | missulmer/Pythonstudy | fc811570cafaa383ac98f489028583081932b3e5 | [
"CC0-1.0"
] | null | null | null | coursera_python_specialization/px6_1.py | missulmer/Pythonstudy | fc811570cafaa383ac98f489028583081932b3e5 | [
"CC0-1.0"
] | null | null | null | # comment on each line
# Here we are setting variables, in this case X, the x variable creates within it a formatted variable which is also set in this creation.
x = "There are %d types of people." % 10
# creating the variable binary
binary = "binary"
# creating variable do_not
do_not = "don't"
# creating variable y, like x we are creating a string that calls formatted variables into it.
# first example of string within string.
y = "Those who don't know %s and those who %s." % (binary, do_not)
# printing the strings created as variables which also call formatted variables into it.
print x
print y
# these strings call in a variable that has variables within in it.
# these are also 'string inside of string' examples
print "I said: %r." % x
print "I also said: '%s'." % y
# we again create variables, joke_evaluation calls a formatted variable within it.
# another string within a string example.
hilarious = False
joke_evaluation = "Isn't that joke funny?! %r"
# this sting calls the joke_evaluation variable and then calls the variable hilarious which
# returns false as an answer, the last string within string example.
print joke_evaluation % hilarious
# here we are introduced to formatters w and e. w which prints the left side of a string
# and e prints the right side. They will be printed together to create a complete sentence.
w = "This is the left side of..."
e = "a string with a right side."
# here is how they are placed together, and will print
# "This is the left side of...a string with a right side."
print w + e
# more on formatters. %r is best for debugging, and other formats are for actually displaying
# variables. It is for debugging because it displays a "raw" data variable.
# %s and %d the these are used to display actual variables to people.
# why single (') quotes inside the string and double (") outside.
# style choice. It makes neater looking code to read.
# Review of what was introduced in this lesson
# print
# variable creation
# placing variables within strings
# placing multipul variables within a string
# the formatter
# %r = raw data
# %d = pull a variable
# %s = pull a variable
# w = pull the left side of a string
# e = pull the right side of a string
| 36.590164 | 138 | 0.738351 | 373 | 2,232 | 4.399464 | 0.353887 | 0.034126 | 0.026813 | 0.031688 | 0.073126 | 0.073126 | 0 | 0 | 0 | 0 | 0 | 0.001117 | 0.197581 | 2,232 | 61 | 139 | 36.590164 | 0.915131 | 0.78629 | 0 | 0 | 0 | 0 | 0.427928 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.428571 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
2650631b7c5cdb9075aee7842270972befea683e | 971 | py | Python | envs/_interface.py | bryanlincoln/gvgai-rl-models | 9d1ca1ab35a911ba920c77b166b63ca6705895b4 | [
"MIT"
] | 1 | 2019-07-08T21:46:07.000Z | 2019-07-08T21:46:07.000Z | envs/_interface.py | bryanlincoln/gvgai-rl-models | 9d1ca1ab35a911ba920c77b166b63ca6705895b4 | [
"MIT"
] | null | null | null | envs/_interface.py | bryanlincoln/gvgai-rl-models | 9d1ca1ab35a911ba920c77b166b63ca6705895b4 | [
"MIT"
] | null | null | null | import gym
import logging
class EnvInterface:
def __init__(self, env_name, _img_size=84):
self._img_size = _img_size
self.env = gym.make(env_name)
self.n_actions = self.env.action_space.n
self.n_obs = self.env.observation_space.shape[0]
self.name = env_name
logging.info("Instantiated " + env_name)
def step(self, action):
state, reward, done, info = self.env.step(action)
state = self._preprocess(state)
return state, reward, done, info
def reset(self):
state = self._preprocess(self.env.reset())
return state
def render(self):
self.env.render()
def factory(env_name):
raise NotImplementedError()
return None
def _preprocess(self, state):
raise NotImplementedError()
return None
def close(self):
self.env.close()
def sample_action(self):
return self.env.action_space.sample() | 24.275 | 57 | 0.622039 | 121 | 971 | 4.793388 | 0.31405 | 0.108621 | 0.044828 | 0.062069 | 0.127586 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00428 | 0.278064 | 971 | 40 | 58 | 24.275 | 0.82311 | 0 | 0 | 0.137931 | 0 | 0 | 0.013374 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.275862 | false | 0 | 0.068966 | 0.034483 | 0.551724 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
267d46fae207da1fcf26a545ba4b71d2416ec82c | 231 | py | Python | Core/Block_1/R1105_Factory.py | BernardoB95/Extrator_SPEDFiscal | 10b4697833c561d24654251da5f22d044f03fc16 | [
"MIT"
] | 1 | 2021-04-25T13:53:20.000Z | 2021-04-25T13:53:20.000Z | Core/Block_1/R1105_Factory.py | BernardoB95/Extrator_SPEDFiscal | 10b4697833c561d24654251da5f22d044f03fc16 | [
"MIT"
] | null | null | null | Core/Block_1/R1105_Factory.py | BernardoB95/Extrator_SPEDFiscal | 10b4697833c561d24654251da5f22d044f03fc16 | [
"MIT"
] | null | null | null | from Core.IFactory import IFactory
from Regs.Block_1 import R1105
class R1105Factory(IFactory):
def create_block_object(self, line):
self.r1105 = _r1105 = R1105()
_r1105.reg_list = line
return _r1105
| 21 | 40 | 0.69697 | 30 | 231 | 5.133333 | 0.6 | 0.194805 | 0.194805 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.163842 | 0.233766 | 231 | 10 | 41 | 23.1 | 0.706215 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.285714 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
268f9091ca19a1a8965d32cf022173145ab42b50 | 223 | py | Python | snyk/test_utils.py | husband-inc/pysnyk | 6019690642cc9ca392df5cea964487ec300f3318 | [
"MIT"
] | 1 | 2020-03-02T02:46:23.000Z | 2020-03-02T02:46:23.000Z | snyk/test_utils.py | husband-inc/pysnyk | 6019690642cc9ca392df5cea964487ec300f3318 | [
"MIT"
] | null | null | null | snyk/test_utils.py | husband-inc/pysnyk | 6019690642cc9ca392df5cea964487ec300f3318 | [
"MIT"
] | 1 | 2020-02-15T03:51:06.000Z | 2020-02-15T03:51:06.000Z | from snyk.utils import snake_to_camel
class TestUtils(object):
def test_snake_case_to_camel(self):
snake = "testing_this_value"
camel = "testingThisValue"
assert camel == snake_to_camel(snake)
| 24.777778 | 45 | 0.70852 | 29 | 223 | 5.103448 | 0.655172 | 0.141892 | 0.162162 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.215247 | 223 | 8 | 46 | 27.875 | 0.845714 | 0 | 0 | 0 | 0 | 0 | 0.152466 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 1 | 0.166667 | false | 0 | 0.166667 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
2690a3a7ba6eb7027cbb85f1d0008dd01366d00f | 295 | py | Python | indicators/swing_index/swing_index_ind.py | pl-greenplum/trading-system-methods | 40d0186b300f962087140542a7e87cf9df1747b6 | [
"Apache-2.0"
] | 7 | 2021-06-26T12:19:43.000Z | 2022-01-23T16:14:46.000Z | indicators/swing_index/swing_index_ind.py | pl-greenplum/trading-system-methods | 40d0186b300f962087140542a7e87cf9df1747b6 | [
"Apache-2.0"
] | null | null | null | indicators/swing_index/swing_index_ind.py | pl-greenplum/trading-system-methods | 40d0186b300f962087140542a7e87cf9df1747b6 | [
"Apache-2.0"
] | 2 | 2021-03-07T16:38:32.000Z | 2021-03-11T06:05:16.000Z | import backtrader as bt
from backtrader.indicator import Indicator
import math
class SwingIndexIndication(Indicator):
lines=('swing_index_ind',)
params = dict(
period=10
)
def __init__(self):
self.addminperiod(self.p.period)
def next(self):
pass | 17.352941 | 43 | 0.667797 | 34 | 295 | 5.617647 | 0.705882 | 0.157068 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009009 | 0.247458 | 295 | 17 | 44 | 17.352941 | 0.851351 | 0 | 0 | 0 | 0 | 0 | 0.050676 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0.083333 | 0.25 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
13fbcfe9d19b62c6c4d59ce85c5106fab3bc567f | 1,879 | py | Python | ggpy/cruft/autocode/AbortRequest.py | hobson/ggpy | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | [
"MIT"
] | 1 | 2015-01-26T19:07:45.000Z | 2015-01-26T19:07:45.000Z | ggpy/cruft/autocode/AbortRequest.py | hobson/ggpy | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | [
"MIT"
] | null | null | null | ggpy/cruft/autocode/AbortRequest.py | hobson/ggpy | 4e6e6e876c3a4294cd711647051da2d9c1836b60 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
""" generated source for module AbortRequest """
# package: org.ggp.base.player.request.grammar
import org.ggp.base.player.gamer.Gamer
import org.ggp.base.player.gamer.event.GamerAbortedMatchEvent
import org.ggp.base.player.gamer.event.GamerUnrecognizedMatchEvent
import org.ggp.base.player.gamer.exception.AbortingException
import org.ggp.base.util.logging.GamerLogger
class AbortRequest(Request):
""" generated source for class AbortRequest """
gamer = Gamer()
matchId = str()
def __init__(self, gamer, matchId):
""" generated source for method __init__ """
super(AbortRequest, self).__init__()
self.gamer = gamer
self.matchId = matchId
def getMatchId(self):
""" generated source for method getMatchId """
return self.matchId
def process(self, receptionTime):
""" generated source for method process """
# First, check to ensure that this abort request is for the match
# we're currently playing. If we're not playing a match, or we're
# playing a different match, send back "busy".
if self.gamer.getMatch() == None or not self.gamer.getMatch().getMatchId() == self.matchId:
GamerLogger.logError("GamePlayer", "Got abort message not intended for current game: ignoring.")
self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId))
return "busy"
self.gamer.getMatch().markAborted()
self.gamer.notifyObservers(GamerAbortedMatchEvent())
try:
self.gamer.abort()
except AbortingException as e:
GamerLogger.logStackTrace("GamePlayer", e)
self.gamer.setRoleName(None)
self.gamer.setMatch(None)
return "aborted"
def __str__(self):
""" generated source for method toString """
return "abort"
| 36.134615 | 108 | 0.672698 | 212 | 1,879 | 5.886792 | 0.382075 | 0.072115 | 0.086538 | 0.064103 | 0.139423 | 0.094551 | 0.051282 | 0 | 0 | 0 | 0 | 0 | 0.222459 | 1,879 | 51 | 109 | 36.843137 | 0.854209 | 0.253858 | 0 | 0 | 1 | 0 | 0.069118 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.133333 | false | 0 | 0.166667 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
cd0c6f53ea0c585cd4a49bdc3e7fdcfe8368d06e | 429 | py | Python | ScoutingWebsite/Scouting2017/view/submissions/submit_pick_list.py | ArcticWarriors/scouting-app | 3411dfc6ddca3728889460cc372716847fff5939 | [
"MIT"
] | 4 | 2017-03-20T21:29:14.000Z | 2018-02-20T17:52:49.000Z | ScoutingWebsite/Scouting2017/view/submissions/submit_pick_list.py | ArcticWarriors/scouting-app | 3411dfc6ddca3728889460cc372716847fff5939 | [
"MIT"
] | 9 | 2016-03-04T01:09:41.000Z | 2016-09-29T00:04:53.000Z | ScoutingWebsite/Scouting2017/view/submissions/submit_pick_list.py | ArcticWarriors/scouting-app | 3411dfc6ddca3728889460cc372716847fff5939 | [
"MIT"
] | 3 | 2016-02-23T03:28:17.000Z | 2016-05-12T13:12:49.000Z | '''
Created on Mar 4, 2017
@author: PJ
'''
from BaseScouting.views.submissions.submit_pick_list import BaseSubmitPickList
from Scouting2017.model.reusable_models import PickList, Competition, Team
class SubmitPickList2017(BaseSubmitPickList):
def __init__(self):
groupings = ["Overall", "Fuel", "Gear", "Defense", "Do Not Pick"]
BaseSubmitPickList.__init__(self, groupings, Competition, PickList, Team)
| 25.235294 | 81 | 0.745921 | 46 | 429 | 6.717391 | 0.76087 | 0.05178 | 0.110032 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.035519 | 0.146853 | 429 | 16 | 82 | 26.8125 | 0.808743 | 0.081585 | 0 | 0 | 0 | 0 | 0.085492 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
cd234a4802dc3318047e4950e2500111363ab932 | 523 | py | Python | MUNDO 2/ex039.py | athavus/Curso-em-video-Python-3 | a32be95adbccfcbe512a1ed30d3859141a230b5e | [
"MIT"
] | 1 | 2020-11-12T14:03:32.000Z | 2020-11-12T14:03:32.000Z | MUNDO 2/ex039.py | athavus/Curso-em-video-Python-3 | a32be95adbccfcbe512a1ed30d3859141a230b5e | [
"MIT"
] | null | null | null | MUNDO 2/ex039.py | athavus/Curso-em-video-Python-3 | a32be95adbccfcbe512a1ed30d3859141a230b5e | [
"MIT"
] | 1 | 2021-01-05T22:18:46.000Z | 2021-01-05T22:18:46.000Z | from datetime import date
ano = int(input('Informe o seu ano de nascimento: '))
anoatual = date.today().year
cont = (anoatual - ano)
if cont < 18:
print('Vocรช ainda vai se alistar ao serviรงo de alistamento!')
print(f'Faltam {18 - cont} anos para vocรช se alistar')
elif cont == 18:
print('ร a hora de se alistar ao serviรงo de alistamento!')
else:
print('Jรก passou da hora de se alistar ao o seviรงo de alistamento!')
print(f'Jรก passaram {cont - 18} anos do tempo que vocรช deveria se alistar')
| 40.230769 | 80 | 0.680688 | 85 | 523 | 4.188235 | 0.529412 | 0.126404 | 0.092697 | 0.101124 | 0.238764 | 0.174157 | 0 | 0 | 0 | 0 | 0 | 0.019608 | 0.219885 | 523 | 12 | 81 | 43.583333 | 0.852941 | 0 | 0 | 0 | 0 | 0 | 0.590998 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.166667 | 0.083333 | 0 | 0.083333 | 0.416667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 2 |
cd23aa4894c6248cbe4433035f8fead919d9620c | 546 | py | Python | src/core/migrations/0005_auto_20200119_1205.py | creyD/asiimov | a819962d8f2a7ce9921e0f3cbe9b44ab10967c6f | [
"MIT"
] | 1 | 2021-06-09T20:27:15.000Z | 2021-06-09T20:27:15.000Z | src/core/migrations/0005_auto_20200119_1205.py | creyD/asiimov | a819962d8f2a7ce9921e0f3cbe9b44ab10967c6f | [
"MIT"
] | 8 | 2020-09-26T11:24:13.000Z | 2021-06-10T18:08:07.000Z | src/core/migrations/0005_auto_20200119_1205.py | creyD/asiimov | a819962d8f2a7ce9921e0f3cbe9b44ab10967c6f | [
"MIT"
] | null | null | null | # Generated by Django 3.0.2 on 2020-01-19 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20200119_1201'),
]
operations = [
migrations.AlterField(
model_name='iteminstance',
name='float',
field=models.FloatField(null=True),
),
migrations.AlterField(
model_name='iteminstance',
name='paintseed',
field=models.IntegerField(null=True),
),
]
| 22.75 | 49 | 0.578755 | 53 | 546 | 5.867925 | 0.698113 | 0.128617 | 0.160772 | 0.186495 | 0.289389 | 0.289389 | 0 | 0 | 0 | 0 | 0 | 0.082011 | 0.307692 | 546 | 23 | 50 | 23.73913 | 0.740741 | 0.082418 | 0 | 0.352941 | 1 | 0 | 0.130261 | 0.046092 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.058824 | 0 | 0.235294 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
cd2f58ed683ae62a30047cb312c44dcf9bcd51fa | 7,621 | py | Python | crowdsourcing/migrations/0000_get_worker_ratings_fn.py | AKSHANSH47/crowdsource-platform2 | a31446d44bc10dca56a0d534cab226947a6bbb4e | [
"MIT"
] | null | null | null | crowdsourcing/migrations/0000_get_worker_ratings_fn.py | AKSHANSH47/crowdsource-platform2 | a31446d44bc10dca56a0d534cab226947a6bbb4e | [
"MIT"
] | null | null | null | crowdsourcing/migrations/0000_get_worker_ratings_fn.py | AKSHANSH47/crowdsource-platform2 | a31446d44bc10dca56a0d534cab226947a6bbb4e | [
"MIT"
] | 2 | 2020-01-27T05:35:50.000Z | 2020-02-29T12:55:39.000Z | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crowdsourcing', '0000_get_requester_ratings_fn'),
]
operations = [
migrations.RunSQL('''
CREATE OR REPLACE FUNCTION get_worker_ratings(IN worker_profile_id INTEGER, IN true_avg BOOLEAN DEFAULT FALSE)
RETURNS TABLE(requester_id INTEGER, worker_rating DOUBLE PRECISION,
worker_avg_rating DOUBLE PRECISION)
AS $$
SELECT
r.id requester_id,
worker_ratings.weight weight,
CASE WHEN worker_ratings.number_of_ratings = 1
THEN CASE WHEN $2 = TRUE
THEN worker_ratings.avg_rw_rating
ELSE NULL END
ELSE (worker_ratings.avg_rw_rating * worker_ratings.number_of_ratings - worker_ratings.weight) /
(worker_ratings.number_of_ratings - 1) END average_rating
FROM crowdsourcing_requester r LEFT OUTER JOIN (
SELECT
wrr.target_id,
wrr.origin_id,
wrr.weight,
avg_rw_rating,
number_of_ratings
FROM crowdsourcing_workerrequesterrating wrr
INNER JOIN (
SELECT
recent_req_rating.target_id,
AVG(recent_req_rating.weight) AS avg_rw_rating,
COUNT(
recent_req_rating.target_id) number_of_ratings
FROM (
SELECT
wrr.weight,
wrr.target_id
FROM
crowdsourcing_workerrequesterrating wrr
INNER JOIN (
SELECT
origin_id,
target_id,
MAX(
last_updated) AS max_date
FROM
crowdsourcing_workerrequesterrating
WHERE target_id=$1 AND origin_type='requester'
GROUP BY origin_id,
target_id
) most_recent
ON most_recent.origin_id =
wrr.origin_id AND
most_recent.target_id =
wrr.target_id
AND
wrr.last_updated =
most_recent.max_date
AND wrr.target_id = $1
AND wrr.origin_type =
'requester') recent_req_rating
GROUP BY recent_req_rating.target_id
) avg_rw_rating
ON wrr.target_id = avg_rw_rating.target_id
INNER JOIN (
SELECT
origin_id,
target_id,
MAX(last_updated) AS max_date
FROM crowdsourcing_workerrequesterrating
WHERE origin_type='requester'
GROUP BY origin_id, target_id
) most_recent
ON wrr.origin_id = most_recent.origin_id AND
wrr.target_id = most_recent.target_id AND
wrr.last_updated = most_recent.max_date AND
wrr.origin_type = 'requester') worker_ratings
ON r.profile_id = worker_ratings.origin_id
$$
LANGUAGE SQL
STABLE
RETURNS NULL ON NULL INPUT;
''')
]
| 84.677778 | 151 | 0.232122 | 335 | 7,621 | 4.955224 | 0.238806 | 0.081928 | 0.039759 | 0.038554 | 0.466867 | 0.364458 | 0.298193 | 0.239759 | 0.239759 | 0.239759 | 0 | 0.005203 | 0.747802 | 7,621 | 89 | 152 | 85.629213 | 0.858481 | 0.002756 | 0 | 0.247059 | 0 | 0 | 0.97631 | 0.091998 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.011765 | 0 | 0.047059 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
cd5a6bc0af0c294f3b59ad0373a168f95b2b6f80 | 6,293 | py | Python | skdist/distribute/_defaults.py | synapticarbors/sk-dist | e5729e62fbdb7b8513be1c4fd0d463d8aec5b837 | [
"Apache-2.0"
] | 292 | 2019-08-29T20:31:05.000Z | 2022-03-25T23:14:48.000Z | skdist/distribute/_defaults.py | synapticarbors/sk-dist | e5729e62fbdb7b8513be1c4fd0d463d8aec5b837 | [
"Apache-2.0"
] | 20 | 2019-09-05T08:39:05.000Z | 2021-07-18T23:35:14.000Z | skdist/distribute/_defaults.py | synapticarbors/sk-dist | e5729e62fbdb7b8513be1c4fd0d463d8aec5b837 | [
"Apache-2.0"
] | 61 | 2019-09-02T21:40:03.000Z | 2022-02-17T18:10:29.000Z | """
Default feature encoding functions and pipelines
for automated feature transformation.
"""
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_selection import VarianceThreshold
from sklearn.impute import SimpleImputer
from ..preprocessing import (
ImputeNull,
SelectField,
FeatureCast,
LabelEncoderPipe,
HashingVectorizerChunked,
MultihotEncoder,
)
def tokenizer(x):
""" Trivial tokenizer """
return x
dict_encoder = lambda c: [
(
"{0}_dict_encoder".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull({})),
("vec", DictVectorizer()),
]
),
)
]
onehot_encoder = lambda c: [
(
"{0}_onehot".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("cast", FeatureCast(cast_type=str)),
("fillna", ImputeNull("")),
(
"vec",
CountVectorizer(
token_pattern=None,
tokenizer=tokenizer,
binary=True,
decode_error="ignore",
),
),
]
),
)
]
multihot_encoder = lambda c: [
(
"{0}_multihot".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull([])),
("vec", MultihotEncoder()),
]
),
)
]
numeric_encoder = lambda c: [
(
"{0}_scaler".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c])),
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler(copy=False)),
]
),
)
]
_default_encoders = {
"small": {
"string_vectorizer": lambda c: [
(
"{0}_word_vec".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull(" ")),
(
"vec",
HashingVectorizerChunked(
ngram_range=(1, 2),
analyzer="word",
decode_error="ignore",
),
),
("var_thresh", VarianceThreshold()),
]
),
)
],
"onehotencoder": onehot_encoder,
"multihotencoder": multihot_encoder,
"numeric": numeric_encoder,
"dict": dict_encoder,
},
"medium": {
"string_vectorizer": lambda c: [
(
"{0}_word_vec".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull(" ")),
(
"vec",
HashingVectorizerChunked(
ngram_range=(1, 3),
analyzer="word",
decode_error="ignore",
),
),
("var_thresh", VarianceThreshold()),
]
),
),
(
"{0}_char_vec".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull(" ")),
(
"vec",
HashingVectorizerChunked(
ngram_range=(3, 4),
analyzer="char_wb",
decode_error="ignore",
),
),
("var_thresh", VarianceThreshold()),
]
),
),
],
"onehotencoder": onehot_encoder,
"multihotencoder": multihot_encoder,
"numeric": numeric_encoder,
"dict": dict_encoder,
},
"large": {
"string_vectorizer": lambda c: [
(
"{0}_word_vec".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull(" ")),
(
"vec",
HashingVectorizerChunked(
ngram_range=(1, 3),
analyzer="word",
decode_error="ignore",
),
),
("var_thresh", VarianceThreshold()),
]
),
),
(
"{0}_char_vec".format(c),
Pipeline(
steps=[
("var", SelectField(cols=[c], single_dimension=True)),
("fillna", ImputeNull(" ")),
(
"vec",
HashingVectorizerChunked(
ngram_range=(2, 5),
analyzer="char_wb",
decode_error="ignore",
),
),
("var_thresh", VarianceThreshold()),
]
),
),
],
"onehotencoder": onehot_encoder,
"multihotencoder": multihot_encoder,
"numeric": numeric_encoder,
"dict": dict_encoder,
},
}
| 30.697561 | 78 | 0.38233 | 367 | 6,293 | 6.373297 | 0.234332 | 0.026935 | 0.057717 | 0.076956 | 0.630611 | 0.630611 | 0.630611 | 0.630611 | 0.608807 | 0.608807 | 0 | 0.006123 | 0.506912 | 6,293 | 204 | 79 | 30.848039 | 0.747664 | 0.016685 | 0 | 0.57672 | 0 | 0 | 0.086006 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.005291 | false | 0 | 0.037037 | 0 | 0.047619 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
cd5e0da97aec827cfffd414291d6ad01fb88752e | 4,319 | py | Python | time_series_example.py | techBeck03/intersight-python-utils | ad8c909e73d345f88720a90de2587878d7403171 | [
"MIT"
] | 2 | 2021-10-05T19:57:14.000Z | 2022-03-08T00:56:45.000Z | time_series_example.py | techBeck03/intersight-python-utils | ad8c909e73d345f88720a90de2587878d7403171 | [
"MIT"
] | null | null | null | time_series_example.py | techBeck03/intersight-python-utils | ad8c909e73d345f88720a90de2587878d7403171 | [
"MIT"
] | 4 | 2021-01-13T15:38:31.000Z | 2021-10-04T21:58:38.000Z | import logging
from pprint import pformat
import traceback
import intersight.api.telemetry_api
import intersight.model.telemetry_druid_data_source
import intersight.model.telemetry_druid_period_granularity
import intersight.model.telemetry_druid_query_context
import intersight.model.telemetry_druid_time_series_request
import credentials
FORMAT = '%(asctime)-15s [%(levelname)s] [%(filename)s:%(lineno)s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
logger = logging.getLogger('openapi')
def get_time_series(api_client):
"""Query Druid time series"""
# Create an instance of the API telemetry service.
api_instance = intersight.api.telemetry_api.TelemetryApi(api_client)
logger.info("Query 'ucs_ether_port_stat' time series")
req = intersight.model.telemetry_druid_time_series_request.TelemetryDruidTimeSeriesRequest(
query_type="timeseries",
data_source=intersight.model.telemetry_druid_data_source.TelemetryDruidDataSource(
type="table",
name="ucs_ether_port_stat",
),
intervals=[
"2021-01-01T00:00:00.000Z/2021-01-15T00:00:00.000Z",
],
granularity=intersight.model.telemetry_druid_period_granularity.TelemetryDruidPeriodGranularity(
type="period",
period="P1D",
),
context=intersight.model.telemetry_druid_query_context.TelemetryDruidQueryContext(
timeout=30,
query_id="ucs_ether_port_stat-QueryIdentifier",
),
)
api_response = api_instance.query_telemetry_time_series(
telemetry_druid_time_series_request=req,
)
logger.info(pformat(api_response))
##########################
logger.info("Query 'device_connector' time series")
req = intersight.model.telemetry_druid_time_series_request.TelemetryDruidTimeSeriesRequest(
query_type="timeseries",
data_source=intersight.model.telemetry_druid_data_source.TelemetryDruidDataSource(
type="table",
name="device_connector",
),
intervals=[
"2021-01-01T00:00:00.000Z/2021-01-15T00:00:00.000Z",
],
granularity=intersight.model.telemetry_druid_period_granularity.TelemetryDruidPeriodGranularity(
type="period",
period="P1D",
),
context=intersight.model.telemetry_druid_query_context.TelemetryDruidQueryContext(
timeout=30,
query_id="device_connector-QueryIdentifier",
),
)
api_response = api_instance.query_telemetry_time_series(
telemetry_druid_time_series_request=req,
)
logger.info(pformat(api_response))
##########################
logger.info("Query 'PSU stat' time series")
req = intersight.model.telemetry_druid_time_series_request.TelemetryDruidTimeSeriesRequest(
aggregations=[
intersight.model.telemetry_druid_aggregator.TelemetryDruidAggregator(
field_name="sumEnergyConsumed",
type="doubleSum",
name="energyConsumed",
field_names=["sumEnergyConsumed"]
),
],
query_type="timeseries",
data_source=intersight.model.telemetry_druid_data_source.TelemetryDruidDataSource(
type="table",
name="psu_stat",
),
intervals=[
"2021-01-01T00:00:00.000Z/2021-01-15T00:00:00.000Z",
],
granularity=intersight.model.telemetry_druid_period_granularity.TelemetryDruidPeriodGranularity(
type="period",
period="P1D",
),
context=intersight.model.telemetry_druid_query_context.TelemetryDruidQueryContext(
timeout=30,
query_id="psu_stat-QueryIdentifier",
),
)
api_response = api_instance.query_telemetry_time_series(
telemetry_druid_time_series_request=req,
)
logger.info(pformat(api_response))
def main():
# Configure API key settings for authentication
api_client = credentials.config_credentials()
try:
# Get example time series data
get_time_series(api_client)
except intersight.OpenApiException as e:
logger.error("Exception when calling API: %s\n" % e)
traceback.print_exc()
if __name__ == "__main__":
main()
| 35.991667 | 104 | 0.679092 | 437 | 4,319 | 6.414188 | 0.237986 | 0.099893 | 0.145558 | 0.175883 | 0.706386 | 0.682126 | 0.637174 | 0.620763 | 0.620763 | 0.620763 | 0 | 0.033442 | 0.217643 | 4,319 | 119 | 105 | 36.294118 | 0.796094 | 0.034267 | 0 | 0.56 | 0 | 0.04 | 0.152761 | 0.069083 | 0 | 0 | 0 | 0 | 0 | 1 | 0.02 | false | 0 | 0.09 | 0 | 0.11 | 0.02 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
cd6b49e56d3bd274c107bdc5b303780623542c29 | 579 | py | Python | Optimizing_Python_Code/Exercise Files/Ch02/02_03/tasks.py | shaunryan/PythonReference | a4d1ba3e4f4279523463fdf7457effc2861d9144 | [
"MIT"
] | 3 | 2020-09-30T18:21:07.000Z | 2021-05-25T14:36:50.000Z | Optimizing_Python_Code/Exercise Files/Ch02/02_03/tasks.py | shaunryan/PythonReference | a4d1ba3e4f4279523463fdf7457effc2861d9144 | [
"MIT"
] | 1 | 2020-09-26T06:40:30.000Z | 2020-09-26T06:40:30.000Z | Optimizing_Python_Code/Exercise Files/Ch02/02_03/tasks.py | shaunryan/PythonReference | a4d1ba3e4f4279523463fdf7457effc2861d9144 | [
"MIT"
] | 2 | 2020-09-26T00:21:41.000Z | 2021-11-16T13:45:41.000Z | """Task queue - deque example"""
class TaskQueue:
"""Task queue using list"""
def __init__(self):
self._tasks = []
def push(self, task):
self._tasks.insert(0, task)
def pop(self):
return self._tasks.pop()
def __len__(self):
return len(self._tasks)
def test_queue(count=100):
tq = TaskQueue()
for i in range(count):
tq.push(i)
assert len(tq) == i + 1
for i in range(count):
assert tq.pop() == i
assert len(tq) == count - i - 1
if __name__ == '__main__':
test_queue()
| 17.545455 | 39 | 0.549223 | 78 | 579 | 3.794872 | 0.397436 | 0.121622 | 0.081081 | 0.074324 | 0.108108 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015 | 0.309154 | 579 | 32 | 40 | 18.09375 | 0.725 | 0.082902 | 0 | 0.105263 | 0 | 0 | 0.015385 | 0 | 0 | 0 | 0 | 0 | 0.157895 | 1 | 0.263158 | false | 0 | 0 | 0.105263 | 0.421053 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
cd77ceca11eeb9552ed9c15f94afe44a458b0111 | 1,084 | py | Python | tests/widgets/test_ui_hidden.py | amsico/pyqtschema | 27fdc3c56bcef6975f6cd2624859e43f446320a1 | [
"MIT"
] | 1 | 2022-02-17T09:04:13.000Z | 2022-02-17T09:04:13.000Z | tests/widgets/test_ui_hidden.py | amsico/pyqtschema | 27fdc3c56bcef6975f6cd2624859e43f446320a1 | [
"MIT"
] | 12 | 2022-01-28T22:31:46.000Z | 2022-02-09T23:06:07.000Z | tests/widgets/test_ui_hidden.py | amsico/pyqtschema | 27fdc3c56bcef6975f6cd2624859e43f446320a1 | [
"MIT"
] | null | null | null | import pytest
# see also issue https://github.com/amsico/pyqtschema/issues/12
from pydantic import BaseModel
from pyqtschema.utils import build_example_widget
class Simple(BaseModel):
string: str
integer: int
schema = Simple.schema()
def test_hide_widget(qtbot):
ui_schema = {'string': {'ui:hidden': True}}
widget = build_example_widget(schema, ui_schema=ui_schema)
widget.show()
qtbot.addWidget(widget)
assert not widget.widget.widgets['string'].isVisible()
assert widget.widget.widgets['integer'].isVisible()
assert widget.widget.widgets['string'].isEnabled()
assert widget.widget.widgets['integer'].isEnabled()
def test_disable_widget(qtbot):
ui_schema = {'integer': {'ui:disabled': True}}
widget = build_example_widget(schema, ui_schema=ui_schema)
widget.show()
qtbot.addWidget(widget)
assert widget.widget.widgets['string'].isVisible()
assert widget.widget.widgets['integer'].isVisible()
assert widget.widget.widgets['string'].isEnabled()
assert not widget.widget.widgets['integer'].isEnabled()
| 27.794872 | 63 | 0.72786 | 133 | 1,084 | 5.81203 | 0.315789 | 0.124191 | 0.196636 | 0.194049 | 0.633894 | 0.535576 | 0.535576 | 0.535576 | 0.535576 | 0.535576 | 0 | 0.002146 | 0.140221 | 1,084 | 38 | 64 | 28.526316 | 0.827253 | 0.056273 | 0 | 0.4 | 0 | 0 | 0.083252 | 0 | 0 | 0 | 0 | 0 | 0.32 | 1 | 0.08 | false | 0 | 0.12 | 0 | 0.32 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
cd91ac6f93e0904258a0755df83294d1fe7b0f1f | 6,019 | py | Python | test/test_processors.py | fkshom/ivs-alarm | d2d1069e0ce95d25cc1e1747cdaa6349412c9ded | [
"MIT"
] | null | null | null | test/test_processors.py | fkshom/ivs-alarm | d2d1069e0ce95d25cc1e1747cdaa6349412c9ded | [
"MIT"
] | null | null | null | test/test_processors.py | fkshom/ivs-alarm | d2d1069e0ce95d25cc1e1747cdaa6349412c9ded | [
"MIT"
] | null | null | null | import unittest
from unittest import mock
from logging import basicConfig, getLogger, DEBUG
import ivs_alarm.processors
from email.mime.text import MIMEText
from email import message_from_file
basicConfig(level=DEBUG, format="%(levelname)-5s - %(filename)s(L%(lineno) 3d) - %(name)s - %(message)s")
class TestProcessors_proc_nothing(unittest.TestCase):
def setUp(self):
self.mails = []
with open('test/fixtures/have_one_event.eml') as f:
self.mails.append(message_from_file(f))
def tearDown(self):
pass
def test_normal(self):
# ๆบๅ
# ใในใ
new_mails = ivs_alarm.processors.proc_nothing(self.mails)
# ็ตๆ็ขบ่ช
self.assertEqual(len(new_mails), len(self.mails))
self.assertEqual(new_mails[0]['Subject'], self.mails[0]['Subject'])
class TestProcessors_change_to_address(unittest.TestCase):
def setUp(self):
self.mails = []
with open('test/fixtures/have_one_event.eml') as f:
self.mails.append(message_from_file(f))
mock_get_config = mock.patch('ivs_alarm.processors.get_config')
self.mock_get_config = mock_get_config.start()
self.addCleanup(mock_get_config.stop)
def tearDown(self):
pass
def test_normal(self):
# ๆบๅ
self.mock_get_config.return_value = {
"global":{'new_to_address': 'new_to@example.com'}
}
# ใในใ
new_mails = ivs_alarm.processors.change_to_address(self.mails)
# ็ตๆ็ขบ่ช
self.assertEqual(len(new_mails), len(self.mails))
self.assertEqual(new_mails[0]['To'], 'new_to@example.com')
self.assertEqual(new_mails[0]['Cc'], None)
class TestProcessors_split_body_by_event(unittest.TestCase):
def setUp(self):
self.mails = []
with open('test/fixtures/have_many_events.eml') as f:
self.mails.append(message_from_file(f))
mock_get_config = mock.patch('ivs_alarm.processors.get_config')
self.mock_get_config = mock_get_config.start()
self.addCleanup(mock_get_config.stop)
def tearDown(self):
pass
def test_normal(self):
# ๆบๅ
self.mock_get_config.return_value = {
}
# ใในใ
new_mails = ivs_alarm.processors.split_body_by_event(self.mails)
# ็ตๆ็ขบ่ช
self.assertEqual(len(new_mails), 2)
self.assertEqual(new_mails[0]['To'], 'to@example.com')
self.assertEqual(new_mails[0]['Cc'], 'cc@example.com')
self.assertIn("event1", new_mails[0].get_payload())
self.assertEqual(new_mails[1]['To'], 'to@example.com')
self.assertEqual(new_mails[1]['Cc'], 'cc@example.com')
self.assertIn("event2", new_mails[1].get_payload())
class TestProcessors_add_tag_to_subject(unittest.TestCase):
def setUp(self):
self.mails = []
with open('test/fixtures/have_one_event.eml') as f:
self.mails.append(message_from_file(f))
with open('test/fixtures/have_one_event_for_default_tag.eml') as f:
self.mails.append(message_from_file(f))
mock_get_config = mock.patch('ivs_alarm.processors.get_config')
self.mock_get_config = mock_get_config.start()
self.addCleanup(mock_get_config.stop)
def tearDown(self):
pass
def test_normal(self):
# ๆบๅ
self.mock_get_config.return_value = {
"add_tag_to_subject":[
{
"name": "first tag rule",
"condition": "event1",
"prepend_tag": "[PREPENDTAG]",
"append_tag": "[APPENDTAG]"
},
{
"name": "default tag rule",
"condition": ".*",
"prepend_tag": "[DEFAULT]",
"append_tag": "[DEFAULT]"
}
]
}
# ใในใ
new_mails = ivs_alarm.processors.add_tag_to_subject(self.mails)
# ็ตๆ็ขบ่ช
self.assertEqual(len(new_mails), 2)
self.assertEqual(new_mails[0]['To'], 'to@example.com')
self.assertEqual(new_mails[0]['Cc'], 'cc@example.com')
self.assertIn('[PREPENDTAG]', new_mails[0]['Subject'])
self.assertIn('[APPENDTAG]', new_mails[0]['Subject'])
self.assertNotIn('[DEFAULT]', new_mails[0]['Subject'])
self.assertEqual(new_mails[1]['To'], 'to@example.com')
self.assertEqual(new_mails[1]['Cc'], 'cc@example.com')
self.assertNotIn('[PREPENDTAG]', new_mails[1]['Subject'])
self.assertNotIn('[APPENDTAG]', new_mails[1]['Subject'])
self.assertIn('[DEFAULT]', new_mails[1]['Subject'])
class TestProcessors_ignore_mail(unittest.TestCase):
def setUp(self):
self.mails = []
with open('test/fixtures/have_one_event_to_ignore.eml') as f:
self.mails.append(message_from_file(f))
with open('test/fixtures/have_one_event.eml') as f:
self.mails.append(message_from_file(f))
mock_get_config = mock.patch('ivs_alarm.processors.get_config')
self.mock_get_config = mock_get_config.start()
self.addCleanup(mock_get_config.stop)
def tearDown(self):
pass
def test_normal(self):
# ๆบๅ
self.mock_get_config.return_value = {
"ignore":{
"1": ["dummy pattern", "event to ignore"],
"2": ["dummy pattern"],
}
}
# ใในใ
new_mails = ivs_alarm.processors.ignore_mail(self.mails)
# ็ตๆ็ขบ่ช
self.assertEqual(len(new_mails), 1)
self.assertEqual(new_mails[0]['To'], 'to@example.com')
self.assertEqual(new_mails[0]['Cc'], 'cc@example.com')
self.assertIn('event1', new_mails[0].get_payload()) | 33.254144 | 106 | 0.583319 | 714 | 6,019 | 4.680672 | 0.140056 | 0.076601 | 0.077798 | 0.089467 | 0.737582 | 0.705566 | 0.659186 | 0.659186 | 0.647516 | 0.624776 | 0 | 0.007914 | 0.28626 | 6,019 | 181 | 107 | 33.254144 | 0.770019 | 0.009802 | 0 | 0.540984 | 0 | 0.008197 | 0.176583 | 0.069211 | 0 | 0 | 0 | 0 | 0.221311 | 1 | 0.122951 | false | 0.040984 | 0.04918 | 0 | 0.213115 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
269ebb29c548ddd7ff4be73d713877d5e65189e4 | 2,140 | py | Python | Python/String Validators.py | csendranshi/Hackerrank-Codes | cebb70ba3895f7f9e5a9aabcfe05d34bd9f11995 | [
"MIT"
] | 70 | 2020-10-04T09:23:15.000Z | 2022-02-01T09:44:39.000Z | Python/String Validators.py | csendranshi/Hackerrank-Codes | cebb70ba3895f7f9e5a9aabcfe05d34bd9f11995 | [
"MIT"
] | 148 | 2020-06-05T15:32:12.000Z | 2020-11-01T08:29:01.000Z | Python/String Validators.py | csendranshi/Hackerrank-Codes | cebb70ba3895f7f9e5a9aabcfe05d34bd9f11995 | [
"MIT"
] | 298 | 2020-10-04T04:27:01.000Z | 2022-03-07T04:02:59.000Z | '''
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False
str.isalpha()
This method checks if all the characters of a string are alphabetical (a-z and A-Z).
>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False
str.isdigit()
This method checks if all the characters of a string are digits (0-9).
>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False
str.islower()
This method checks if all the characters of a string are lowercase characters (a-z).
>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False
str.isupper()
This method checks if all the characters of a string are uppercase characters (A-Z).
>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False
Task
You are given a string
.
Your task is to find out if the string
contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
Input Format
A single line containing a string
.
Constraints
Output Format
In the first line, print True if
has any alphanumeric characters. Otherwise, print False.
In the second line, print True if has any alphabetical characters. Otherwise, print False.
In the third line, print True if has any digits. Otherwise, print False.
In the fourth line, print True if has any lowercase characters. Otherwise, print False.
In the fifth line, print True if
has any uppercase characters. Otherwise, print False.
Sample Input
qA2
Sample Output
True
True
True
True
True
'''
if __name__ == '__main__':
s = input()
v=False
for n in s:
if n.isalnum():
v=True
print(v)
v=False
for n in s:
if n.isalpha():
v=True
print(v)
v=False
for n in s:
if n.isdigit():
v=True
print(v)
v=False
for n in s:
if n.islower():
v=True
print(v)
v=False
for n in s:
if n.isupper():
v=True
print(v) | 19.279279 | 164 | 0.706075 | 340 | 2,140 | 4.420588 | 0.232353 | 0.05988 | 0.053227 | 0.05988 | 0.421158 | 0.373253 | 0.235529 | 0.235529 | 0.224884 | 0.224884 | 0 | 0.01795 | 0.192991 | 2,140 | 111 | 165 | 19.279279 | 0.852345 | 0.820093 | 0 | 0.740741 | 0 | 0 | 0.02122 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.185185 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26a01fa7b3e3ac897e15f472ab7f576d2d260c0b | 4,568 | py | Python | Famcy/_CONSOLE_FOLDER_/_management/checkin/page.py | nexuni/Famcy | 80f8f18fe1614ab3c203ca3466b9506b494470bf | [
"Apache-2.0"
] | null | null | null | Famcy/_CONSOLE_FOLDER_/_management/checkin/page.py | nexuni/Famcy | 80f8f18fe1614ab3c203ca3466b9506b494470bf | [
"Apache-2.0"
] | 12 | 2022-02-05T04:56:44.000Z | 2022-03-30T09:59:26.000Z | Famcy/_CONSOLE_FOLDER_/_management/checkin/page.py | nexuni/Famcy | 80f8f18fe1614ab3c203ca3466b9506b494470bf | [
"Apache-2.0"
] | null | null | null | """
This is the page definition file for Famcy.
There are two variables very important, which
defines the page content: PAGE_HEADER and PAGE_CONTENT.
PAGE_HEADER:
* title: a list of titles of the sections on the page. It is usually put
at the top of the section as a header.
* size: a list. defines section size. Options include half_inner_section
and inner_section -> half means share two sections on one page
* type: list of fblock type of the sections on the page. This should match the
defined fblock name.
PAGE_CONTENT:
* a list of dictionary that defines the fblock sections on the page.
example:
PAGE_HEADER = {
"title": ["Nexuni ๅกๅทฅๅพๅฐ"],
"size": ["inner_section"],
"type": ["display"]
}
PAGE_CONTENT = [
{
"values": [{
"type": "displayParagraph",
"title": "",
"content": '''
**Nexuni ไผ็คพใฆใงใใตใคใใฎๆกๅ
**
1. ๅธๆ่ฝ่ฎไพๅฐNexuni็ๆฐๆๅ้ฝ่ฝๅค ๅฟซ้ๅฐๅญธ็ฟไธฆ็ญ่งฃๆๅๅทฅไฝๆๆไฝฟ็จๅฐ็่ป้ซใ็จๅผ่ช่จใๅทฅๅ
ท็ญ็ญใ
2. ไฝ็บ่ฝๅ่ๆ ธ็ไพๆ
3. ๆดๅๆๆๅ
ฌๅธๅ
ง้จ็็ฎก็ๅทฅๅ
ท๏ผๅฆ็ผ็ฅจไธๅณใPO็ณ่ซใๅ ฑๅธณๅทฅๅ
ทใๆๅก่จ้็ญ
ๅฟซ้ๅ
ฅ้:
* ้ปๆ็ธฝ่ฆฝ -> ่จ็ทด็ถฒไป็ดน๏ผๅฏไปฅ็ๅฐๆฌ็ถฒ้ ็ๆๆ็ๅ
งๅฎน็ฐกไป
* ้ปๆ็ธ้่จ็ทดๅ
งๅฎน -> ้ๅง็ทด็ฟ
* ้ปๆ็ธฝ่ฆฝ -> ๅญธ็ฟ้ฒๅบฆ่ฃก้ข็้ฒๅบฆๅ ฑๅ๏ผๅฏไปฅ็ๅฐ็ทด็ฟ็ๆๆ๏ผ
๏ผ็ถฒ้ ๅ
งๅฎน็็ๆฌ็็บNexuni Co. ๆๆ๏ผ
''',
},{
"type": "displayTag",
"title": "ๆธฌ่ฉฆไธ็ฅ้้ๆฏ็จไพๅนนๅ็Layout",
"content": "ๅฐๅบDisplay Tagๆไป้บผไธไธๆจฃ๏ผ",
},
{
"type": "displayImage",
"title": "ไธ้ข้ๅ่งฃๆๅบฆไนๅคช็ณ็ณไบๅง",
"img_name": "test.jpg", # This is gathered from static folder or _images_ user folder
}]
}
]
"""
# import Famcy
# PAGE_HEADER = {
# "title": ["Nexuni ๅ้ค
ๅ", "Nexuni ๅ้ค
ๅ"],
# "size": ["inner_section", "inner_section"],
# "type": ["table", ["display", "input_form"]]
# }
# table_content = Famcy.table_block.generate_template_content()
# display_light_block = Famcy.display.generate_values_content("displayLight")
# list_form_content1 = Famcy.input_form.generate_values_content("inputList")
# list_form_content1.update({
# "value": ["1", "2", "3"]
# })
# list_form_content2 = Famcy.input_form.generate_values_content("inputList")
# list_form_content2.update({
# "value": ["5", "6", "7"]
# })
# input_form_content = Famcy.input_form.generate_template_content([list_form_content1, list_form_content2])
# input_form_content.update({
# "main_button_name": ["้ๅบ"], # btn name in same section must not be same
# "action_after_post": "save", # (clean / save)
# })
# PAGE_CONTENT = [table_content, [Famcy.display.generate_template_content([display_light_block]), input_form_content]]
# def after_submit(submission_list, **configs):
# submission_dict_handler = Famcy.SijaxSubmit(PAGE_CONTENT_OBJECT[0].context["submit_type"])
# table_content.update({
# "data": [
# {
# "col_title1": "row_content11",
# "col_title2": "row_content12",
# "col_title3": "row_content13"
# },
# {
# "col_title1": "row_content21",
# "col_title2": "row_content22",
# "col_title3": "row_content23"
# },
# {
# "col_title1": "row_content31",
# "col_title2": "row_content32",
# "col_title3": "row_content33"
# },
# {
# "col_title1": "row_content11",
# "col_title2": "row_content12",
# "col_title3": "row_content13"
# },
# {
# "col_title1": "row_content21",
# "col_title2": "row_content22",
# "col_title3": "row_content23"
# },
# {
# "col_title1": "row_content31",
# "col_title2": "row_content32",
# "col_title3": "row_content33"
# }
# ]
# })
# PAGE_CONTENT_OBJECT[0].update_page_context(table_content)
# content = submission_dict_handler.generate_block_html(PAGE_CONTENT_OBJECT[0])
# return submission_dict_handler.return_submit_info(msg=content, script="console.log('succeed')")
# def after_submit_2(submission_list, **configs):
# submission_dict_handler = Famcy.SijaxSubmit(PAGE_CONTENT_OBJECT[1][1].context["submit_type"])
# if submission_list[0][0] == "1":
# display_light_block.update({
# "status": {"red": "", "yellow": "bulb_yellow", "green": ""},
# })
# elif submission_list[0][0] == "2":
# display_light_block.update({
# "status": {"red": "", "yellow": "", "green": "bulb_green"},
# })
# elif submission_list[0][0] == "3":
# display_light_block.update({
# "status": {"red": "bulb_red", "yellow": "", "green": ""},
# })
# PAGE_CONTENT_OBJECT[1][0].update_page_context({
# "values": [display_light_block]
# })
# content = submission_dict_handler.generate_block_html(PAGE_CONTENT_OBJECT[1])
# return submission_dict_handler.return_submit_info(msg=content, script="console.log('succeed')")
# PAGE_CONTENT_OBJECT = Famcy.generate_content_obj(PAGE_HEADER, PAGE_CONTENT, [after_submit, [None, after_submit_2]]) | 29.470968 | 118 | 0.667469 | 546 | 4,568 | 5.28022 | 0.309524 | 0.049601 | 0.041276 | 0.01769 | 0.412764 | 0.412764 | 0.341311 | 0.31495 | 0.31495 | 0.278876 | 0 | 0.023244 | 0.171191 | 4,568 | 155 | 119 | 29.470968 | 0.738246 | 1.049037 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26a1805f6171f340ebb1904577e36eca6fc7ec26 | 471 | py | Python | print.py | mncoppola/Linux-Kernel-CTF | a6422693779359fd360c413d9cc7f8dcaa89439c | [
"MIT"
] | 87 | 2015-01-04T06:07:34.000Z | 2021-10-03T16:25:27.000Z | print.py | mncoppola/Linux-Kernel-CTF | a6422693779359fd360c413d9cc7f8dcaa89439c | [
"MIT"
] | null | null | null | print.py | mncoppola/Linux-Kernel-CTF | a6422693779359fd360c413d9cc7f8dcaa89439c | [
"MIT"
] | 11 | 2015-02-10T15:51:16.000Z | 2021-01-02T10:52:29.000Z | import json
DROPLETS_FILE = "droplets.json"
def get_droplets():
with open(DROPLETS_FILE, "r") as f:
data = f.read()
if not data:
return []
else:
return json.loads(data)
def main():
for droplet in get_droplets():
print droplet["name"]
print droplet["ip_address"]
print "%s:%s" % (droplet["username"], droplet["password"])
print
print
if __name__ == "__main__":
main()
| 20.478261 | 66 | 0.552017 | 55 | 471 | 4.490909 | 0.527273 | 0.097166 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.316348 | 471 | 22 | 67 | 21.409091 | 0.767081 | 0 | 0 | 0.111111 | 0 | 0 | 0.121019 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.055556 | 0.055556 | null | null | 0.277778 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
26ab6830f4c3db3cd6646a5161b2b068fe910195 | 12,626 | py | Python | terrascript/alicloud/r.py | GarnerCorp/python-terrascript | ec6c2d9114dcd3cb955dd46069f8ba487e320a8c | [
"BSD-2-Clause"
] | null | null | null | terrascript/alicloud/r.py | GarnerCorp/python-terrascript | ec6c2d9114dcd3cb955dd46069f8ba487e320a8c | [
"BSD-2-Clause"
] | null | null | null | terrascript/alicloud/r.py | GarnerCorp/python-terrascript | ec6c2d9114dcd3cb955dd46069f8ba487e320a8c | [
"BSD-2-Clause"
] | 1 | 2018-11-15T16:23:05.000Z | 2018-11-15T16:23:05.000Z | from terrascript import _resource
class alicloud_instance(_resource): pass
instance = alicloud_instance
class alicloud_ram_role_attachment(_resource): pass
ram_role_attachment = alicloud_ram_role_attachment
class alicloud_disk(_resource): pass
disk = alicloud_disk
class alicloud_disk_attachment(_resource): pass
disk_attachment = alicloud_disk_attachment
class alicloud_network_interface(_resource): pass
network_interface = alicloud_network_interface
class alicloud_network_interface_attachment(_resource): pass
network_interface_attachment = alicloud_network_interface_attachment
class alicloud_snapshot(_resource): pass
snapshot = alicloud_snapshot
class alicloud_snapshot_policy(_resource): pass
snapshot_policy = alicloud_snapshot_policy
class alicloud_launch_template(_resource): pass
launch_template = alicloud_launch_template
class alicloud_security_group(_resource): pass
security_group = alicloud_security_group
class alicloud_security_group_rule(_resource): pass
security_group_rule = alicloud_security_group_rule
class alicloud_db_database(_resource): pass
db_database = alicloud_db_database
class alicloud_db_account(_resource): pass
db_account = alicloud_db_account
class alicloud_db_account_privilege(_resource): pass
db_account_privilege = alicloud_db_account_privilege
class alicloud_db_backup_policy(_resource): pass
db_backup_policy = alicloud_db_backup_policy
class alicloud_db_connection(_resource): pass
db_connection = alicloud_db_connection
class alicloud_db_read_write_splitting_connection(_resource): pass
db_read_write_splitting_connection = alicloud_db_read_write_splitting_connection
class alicloud_db_instance(_resource): pass
db_instance = alicloud_db_instance
class alicloud_mongodb_instance(_resource): pass
mongodb_instance = alicloud_mongodb_instance
class alicloud_mongodb_sharding_instance(_resource): pass
mongodb_sharding_instance = alicloud_mongodb_sharding_instance
class alicloud_db_readonly_instance(_resource): pass
db_readonly_instance = alicloud_db_readonly_instance
class alicloud_ess_scaling_group(_resource): pass
ess_scaling_group = alicloud_ess_scaling_group
class alicloud_ess_scaling_configuration(_resource): pass
ess_scaling_configuration = alicloud_ess_scaling_configuration
class alicloud_ess_scaling_rule(_resource): pass
ess_scaling_rule = alicloud_ess_scaling_rule
class alicloud_ess_schedule(_resource): pass
ess_schedule = alicloud_ess_schedule
class alicloud_ess_scheduled_task(_resource): pass
ess_scheduled_task = alicloud_ess_scheduled_task
class alicloud_ess_attachment(_resource): pass
ess_attachment = alicloud_ess_attachment
class alicloud_ess_lifecycle_hook(_resource): pass
ess_lifecycle_hook = alicloud_ess_lifecycle_hook
class alicloud_ess_alarm(_resource): pass
ess_alarm = alicloud_ess_alarm
class alicloud_vpc(_resource): pass
vpc = alicloud_vpc
class alicloud_nat_gateway(_resource): pass
nat_gateway = alicloud_nat_gateway
class alicloud_nas_file_system(_resource): pass
nas_file_system = alicloud_nas_file_system
class alicloud_nas_mount_target(_resource): pass
nas_mount_target = alicloud_nas_mount_target
class alicloud_nas_access_group(_resource): pass
nas_access_group = alicloud_nas_access_group
class alicloud_nas_access_rule(_resource): pass
nas_access_rule = alicloud_nas_access_rule
class alicloud_subnet(_resource): pass
subnet = alicloud_subnet
class alicloud_vswitch(_resource): pass
vswitch = alicloud_vswitch
class alicloud_route_entry(_resource): pass
route_entry = alicloud_route_entry
class alicloud_route_table(_resource): pass
route_table = alicloud_route_table
class alicloud_route_table_attachment(_resource): pass
route_table_attachment = alicloud_route_table_attachment
class alicloud_snat_entry(_resource): pass
snat_entry = alicloud_snat_entry
class alicloud_forward_entry(_resource): pass
forward_entry = alicloud_forward_entry
class alicloud_eip(_resource): pass
eip = alicloud_eip
class alicloud_eip_association(_resource): pass
eip_association = alicloud_eip_association
class alicloud_slb(_resource): pass
slb = alicloud_slb
class alicloud_slb_listener(_resource): pass
slb_listener = alicloud_slb_listener
class alicloud_slb_attachment(_resource): pass
slb_attachment = alicloud_slb_attachment
class alicloud_slb_server_group(_resource): pass
slb_server_group = alicloud_slb_server_group
class alicloud_slb_rule(_resource): pass
slb_rule = alicloud_slb_rule
class alicloud_slb_acl(_resource): pass
slb_acl = alicloud_slb_acl
class alicloud_slb_ca_certificate(_resource): pass
slb_ca_certificate = alicloud_slb_ca_certificate
class alicloud_slb_server_certificate(_resource): pass
slb_server_certificate = alicloud_slb_server_certificate
class alicloud_oss_bucket(_resource): pass
oss_bucket = alicloud_oss_bucket
class alicloud_oss_bucket_object(_resource): pass
oss_bucket_object = alicloud_oss_bucket_object
class alicloud_dns_record(_resource): pass
dns_record = alicloud_dns_record
class alicloud_dns(_resource): pass
dns = alicloud_dns
class alicloud_dns_group(_resource): pass
dns_group = alicloud_dns_group
class alicloud_key_pair(_resource): pass
key_pair = alicloud_key_pair
class alicloud_key_pair_attachment(_resource): pass
key_pair_attachment = alicloud_key_pair_attachment
class alicloud_kms_key(_resource): pass
kms_key = alicloud_kms_key
class alicloud_ram_user(_resource): pass
ram_user = alicloud_ram_user
class alicloud_ram_access_key(_resource): pass
ram_access_key = alicloud_ram_access_key
class alicloud_ram_login_profile(_resource): pass
ram_login_profile = alicloud_ram_login_profile
class alicloud_ram_group(_resource): pass
ram_group = alicloud_ram_group
class alicloud_ram_role(_resource): pass
ram_role = alicloud_ram_role
class alicloud_ram_policy(_resource): pass
ram_policy = alicloud_ram_policy
class alicloud_ram_alias(_resource): pass
ram_alias = alicloud_ram_alias
class alicloud_ram_account_alias(_resource): pass
ram_account_alias = alicloud_ram_account_alias
class alicloud_ram_group_membership(_resource): pass
ram_group_membership = alicloud_ram_group_membership
class alicloud_ram_user_policy_attachment(_resource): pass
ram_user_policy_attachment = alicloud_ram_user_policy_attachment
class alicloud_ram_role_policy_attachment(_resource): pass
ram_role_policy_attachment = alicloud_ram_role_policy_attachment
class alicloud_ram_group_policy_attachment(_resource): pass
ram_group_policy_attachment = alicloud_ram_group_policy_attachment
class alicloud_container_cluster(_resource): pass
container_cluster = alicloud_container_cluster
class alicloud_cs_application(_resource): pass
cs_application = alicloud_cs_application
class alicloud_cs_swarm(_resource): pass
cs_swarm = alicloud_cs_swarm
class alicloud_cs_kubernetes(_resource): pass
cs_kubernetes = alicloud_cs_kubernetes
class alicloud_cs_managed_kubernetes(_resource): pass
cs_managed_kubernetes = alicloud_cs_managed_kubernetes
class alicloud_cr_namespace(_resource): pass
cr_namespace = alicloud_cr_namespace
class alicloud_cr_repo(_resource): pass
cr_repo = alicloud_cr_repo
class alicloud_cdn_domain(_resource): pass
cdn_domain = alicloud_cdn_domain
class alicloud_cdn_domain_new(_resource): pass
cdn_domain_new = alicloud_cdn_domain_new
class alicloud_cdn_domain_config(_resource): pass
cdn_domain_config = alicloud_cdn_domain_config
class alicloud_router_interface(_resource): pass
router_interface = alicloud_router_interface
class alicloud_router_interface_connection(_resource): pass
router_interface_connection = alicloud_router_interface_connection
class alicloud_ots_table(_resource): pass
ots_table = alicloud_ots_table
class alicloud_ots_instance(_resource): pass
ots_instance = alicloud_ots_instance
class alicloud_ots_instance_attachment(_resource): pass
ots_instance_attachment = alicloud_ots_instance_attachment
class alicloud_cms_alarm(_resource): pass
cms_alarm = alicloud_cms_alarm
class alicloud_pvtz_zone(_resource): pass
pvtz_zone = alicloud_pvtz_zone
class alicloud_pvtz_zone_attachment(_resource): pass
pvtz_zone_attachment = alicloud_pvtz_zone_attachment
class alicloud_pvtz_zone_record(_resource): pass
pvtz_zone_record = alicloud_pvtz_zone_record
class alicloud_log_project(_resource): pass
log_project = alicloud_log_project
class alicloud_log_store(_resource): pass
log_store = alicloud_log_store
class alicloud_log_store_index(_resource): pass
log_store_index = alicloud_log_store_index
class alicloud_log_machine_group(_resource): pass
log_machine_group = alicloud_log_machine_group
class alicloud_logtail_config(_resource): pass
logtail_config = alicloud_logtail_config
class alicloud_logtail_attachment(_resource): pass
logtail_attachment = alicloud_logtail_attachment
class alicloud_fc_service(_resource): pass
fc_service = alicloud_fc_service
class alicloud_fc_function(_resource): pass
fc_function = alicloud_fc_function
class alicloud_fc_trigger(_resource): pass
fc_trigger = alicloud_fc_trigger
class alicloud_vpn_gateway(_resource): pass
vpn_gateway = alicloud_vpn_gateway
class alicloud_vpn_customer_gateway(_resource): pass
vpn_customer_gateway = alicloud_vpn_customer_gateway
class alicloud_vpn_connection(_resource): pass
vpn_connection = alicloud_vpn_connection
class alicloud_ssl_vpn_server(_resource): pass
ssl_vpn_server = alicloud_ssl_vpn_server
class alicloud_ssl_vpn_client_cert(_resource): pass
ssl_vpn_client_cert = alicloud_ssl_vpn_client_cert
class alicloud_cen_instance(_resource): pass
cen_instance = alicloud_cen_instance
class alicloud_cen_instance_attachment(_resource): pass
cen_instance_attachment = alicloud_cen_instance_attachment
class alicloud_cen_bandwidth_package(_resource): pass
cen_bandwidth_package = alicloud_cen_bandwidth_package
class alicloud_cen_bandwidth_package_attachment(_resource): pass
cen_bandwidth_package_attachment = alicloud_cen_bandwidth_package_attachment
class alicloud_cen_bandwidth_limit(_resource): pass
cen_bandwidth_limit = alicloud_cen_bandwidth_limit
class alicloud_cen_route_entry(_resource): pass
cen_route_entry = alicloud_cen_route_entry
class alicloud_cen_instance_grant(_resource): pass
cen_instance_grant = alicloud_cen_instance_grant
class alicloud_kvstore_instance(_resource): pass
kvstore_instance = alicloud_kvstore_instance
class alicloud_kvstore_backup_policy(_resource): pass
kvstore_backup_policy = alicloud_kvstore_backup_policy
class alicloud_datahub_project(_resource): pass
datahub_project = alicloud_datahub_project
class alicloud_datahub_subscription(_resource): pass
datahub_subscription = alicloud_datahub_subscription
class alicloud_datahub_topic(_resource): pass
datahub_topic = alicloud_datahub_topic
class alicloud_mns_queue(_resource): pass
mns_queue = alicloud_mns_queue
class alicloud_mns_topic(_resource): pass
mns_topic = alicloud_mns_topic
class alicloud_havip(_resource): pass
havip = alicloud_havip
class alicloud_mns_topic_subscription(_resource): pass
mns_topic_subscription = alicloud_mns_topic_subscription
class alicloud_havip_attachment(_resource): pass
havip_attachment = alicloud_havip_attachment
class alicloud_api_gateway_api(_resource): pass
api_gateway_api = alicloud_api_gateway_api
class alicloud_api_gateway_group(_resource): pass
api_gateway_group = alicloud_api_gateway_group
class alicloud_api_gateway_app(_resource): pass
api_gateway_app = alicloud_api_gateway_app
class alicloud_api_gateway_app_attachment(_resource): pass
api_gateway_app_attachment = alicloud_api_gateway_app_attachment
class alicloud_api_gateway_vpc_access(_resource): pass
api_gateway_vpc_access = alicloud_api_gateway_vpc_access
class alicloud_common_bandwidth_package(_resource): pass
common_bandwidth_package = alicloud_common_bandwidth_package
class alicloud_common_bandwidth_package_attachment(_resource): pass
common_bandwidth_package_attachment = alicloud_common_bandwidth_package_attachment
class alicloud_drds_instance(_resource): pass
drds_instance = alicloud_drds_instance
class alicloud_elasticsearch_instance(_resource): pass
elasticsearch_instance = alicloud_elasticsearch_instance
class alicloud_actiontrail(_resource): pass
actiontrail = alicloud_actiontrail
class alicloud_cas_certificate(_resource): pass
cas_certificate = alicloud_cas_certificate
class alicloud_ddoscoo_instance(_resource): pass
ddoscoo_instance = alicloud_ddoscoo_instance
class alicloud_network_acl(_resource): pass
network_acl = alicloud_network_acl
class alicloud_network_acl_attachment(_resource): pass
network_acl_attachment = alicloud_network_acl_attachment
class alicloud_network_acl_entries(_resource): pass
network_acl_entries = alicloud_network_acl_entries
| 30.571429 | 82 | 0.880326 | 1,685 | 12,626 | 6.004748 | 0.079525 | 0.176023 | 0.041313 | 0.011366 | 0.106147 | 0.007511 | 0 | 0 | 0 | 0 | 0 | 0 | 0.076271 | 12,626 | 412 | 83 | 30.645631 | 0.86753 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.498182 | 0.003636 | 0 | 0.501818 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
26b3a577e167eff33103b0774a6e27f10d2aee07 | 305 | py | Python | FreeOnEpicBot/sample_config.py | ariel8462/FreeOnEpicBot | e6fc9d53b33f9d7993e495229e719fb2ae1e6516 | [
"MIT"
] | 8 | 2021-02-07T07:45:29.000Z | 2022-01-14T04:14:16.000Z | FreeOnEpicBot/sample_config.py | ariel8462/FreeOnEpicBot | e6fc9d53b33f9d7993e495229e719fb2ae1e6516 | [
"MIT"
] | null | null | null | FreeOnEpicBot/sample_config.py | ariel8462/FreeOnEpicBot | e6fc9d53b33f9d7993e495229e719fb2ae1e6516 | [
"MIT"
] | 1 | 2022-03-29T12:07:55.000Z | 2022-03-29T12:07:55.000Z | HELP_MESSAGE = """Hi there, I am a bot that shows the current free games on all the major game platforms out there.
You will get automatically notified when new games become free to collect.
If you would like to see the current free game please use the following command: /freegame
"""
BOT_TOKEN = '123' | 50.833333 | 115 | 0.770492 | 53 | 305 | 4.396226 | 0.773585 | 0.085837 | 0.120172 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012 | 0.180328 | 305 | 6 | 116 | 50.833333 | 0.92 | 0 | 0 | 0 | 0 | 0.2 | 0.875817 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26b3a9792e103b91c59af1773d9fe50dd044000a | 2,398 | py | Python | api/api.py | NikLeberg/remote | ff14a76a9950583940771173baa161748c095ae5 | [
"MIT"
] | null | null | null | api/api.py | NikLeberg/remote | ff14a76a9950583940771173baa161748c095ae5 | [
"MIT"
] | null | null | null | api/api.py | NikLeberg/remote | ff14a76a9950583940771173baa161748c095ae5 | [
"MIT"
] | null | null | null | # rest-api mittels Flask
# Verwaltung von docker images
# ToDo:
# [/] Auflistung verfรผgbarer apps/images
# [ ] Konfigurieren / erstellen / Dockerfile
# [ ] Einschalten
# [ ] Pausieren / commiten / weiterfahren
# [ ] Killen
# [ ] Connect
# [ ] Disconnect
# get - holen
# post - erstellen
# put - aktualisieren
# delete - lรถschen
from flask import Flask
from flask_restful import Resource, Api, reqparse
import werkzeug
import docker
import base64
import os
# Globals
app = Flask(__name__)
api = Api(app)
docker = docker.from_env()
class util():
def getImage(image):
return {
"name" : image.tags[0].split(":")[0],
"id" : image.short_id,
"comment" : image.attrs["Comment"],
"created" : image.attrs["Created"],
"parent" : image.attrs["Parent"],
"labels" : image.labels
}
class appList(Resource):
def get(self):
response = []
for image in docker.images.list():
response.append(util.getImage(image))
return response
def post(self):
response = []
parser = reqparse.RequestParser()
parser.add_argument("name", type=str, required=True, help="gebe den Name der App an")
parser.add_argument("dockerfile", type=str, required=True, help="es fehlt das Dockerfile enkodiert in Base64")
parser.add_argument("installfile", type=werkzeug.datastructures.FileStorage, location="files")
args = parser.parse_args()
# App-Pfad erstellen
path = f"/home/remote/remote/{args["name"]}"
os.makedirs(path, exist_ok=True)
# Dockerfile aus Base64 dekodieren und in Datei schreiben
dockerfile = open(f"{path}/Dockerfile", "w+")
dockerfile.write(base64.decodestring(args["dockerfile"]))
dockerfile.close()
# Optionale Installationsdateien abspeichern
if "installfile" in args:
installfile = args["installfile"]
installfile.save(f"{path}/installfile.zip")
return args
class appEntity(Resource):
def get(self, name):
try:
image = docker.images.get(name)
return util.getImage(image)
except:
return f"App '{name}' nicht gefunden.", 404
api.add_resource(appList, "/apps")
api.add_resource(appEntity, "/apps/<string:name>")
if __name__ == "__main__":
app.run(debug=True)
| 26.94382 | 118 | 0.626355 | 264 | 2,398 | 5.606061 | 0.462121 | 0.024324 | 0.034459 | 0.024324 | 0.031081 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00721 | 0.248123 | 2,398 | 88 | 119 | 27.25 | 0.813644 | 0.177231 | 0 | 0.038462 | 0 | 0 | 0.159161 | 0.024565 | 0 | 0 | 0 | 0.011364 | 0 | 0 | null | null | 0 | 0.115385 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26c2d943569b3d9a4ddf5dcc28a0a68f6f92f7ce | 511 | py | Python | timeseries_toolkit/transformations.py | alejio/timeseries_toolkit | 030ac84fcb96ec5bdc480a6b74075a737c30955a | [
"MIT"
] | null | null | null | timeseries_toolkit/transformations.py | alejio/timeseries_toolkit | 030ac84fcb96ec5bdc480a6b74075a737c30955a | [
"MIT"
] | null | null | null | timeseries_toolkit/transformations.py | alejio/timeseries_toolkit | 030ac84fcb96ec5bdc480a6b74075a737c30955a | [
"MIT"
] | null | null | null | import numpy as np
def target_transform(y: np.array, increment: float=0.01) -> np.array:
"""
Transform non-negative array to R using np.log
:param y: np.array
:param increment: float
:return:
"""
return np.log(y + increment)
def target_inverse_transform(y_trn: np.array, increment: float=0.01) -> np.array:
"""
Inverse transform of array in R to non-negative
:param y_trn: np.array
:param increment: float
:return:
"""
return np.exp(y_trn) - increment | 24.333333 | 81 | 0.649706 | 76 | 511 | 4.289474 | 0.342105 | 0.128834 | 0.04908 | 0.128834 | 0.435583 | 0.435583 | 0.435583 | 0.435583 | 0 | 0 | 0 | 0.015267 | 0.23092 | 511 | 21 | 82 | 24.333333 | 0.814249 | 0.395303 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 0 | 0.2 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
26c75b195bb079d3cdd49a7118228a060d5c09a9 | 716 | py | Python | python/mesh/generic/customExceptions.py | sqf-ice/meshNetwork | 3214f3e0fabe70e3e0e0d82926e0510a392a3352 | [
"NASA-1.3"
] | null | null | null | python/mesh/generic/customExceptions.py | sqf-ice/meshNetwork | 3214f3e0fabe70e3e0e0d82926e0510a392a3352 | [
"NASA-1.3"
] | null | null | null | python/mesh/generic/customExceptions.py | sqf-ice/meshNetwork | 3214f3e0fabe70e3e0e0d82926e0510a392a3352 | [
"NASA-1.3"
] | 1 | 2021-06-26T06:40:19.000Z | 2021-06-26T06:40:19.000Z | import serial
class NoSerialConnection(serial.SerialException):
"""Exception to raise if trying to read/write to invalid serial connection."""
class NoSocket(serial.SerialException):
"""Exception to raise if trying to read/write to invalid socket connection."""
class NoCommandHeader(Exception):
"""Exception to raise if required commmand header missing."""
class InvalidCmdCounter(Exception):
"""Exception to raise if attempt made to set command counter outside of allowable range."""
class NoCommandHeaderDefined(Exception):
"""Exception to raise if command does not define a header."""
class InvalidTDMASlotNumber(Exception):
"""Exception to raise if TDMA slot number is invalid."""
| 35.8 | 95 | 0.761173 | 87 | 716 | 6.264368 | 0.471264 | 0.121101 | 0.176147 | 0.198165 | 0.436697 | 0.238532 | 0.238532 | 0.238532 | 0.238532 | 0.238532 | 0 | 0 | 0.149441 | 716 | 19 | 96 | 37.684211 | 0.89491 | 0.550279 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.142857 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26ce089ff56787d4eeeec811399f240b2f601b86 | 525 | py | Python | api/todolist.py | groupwildman/todolist | 7ce990b91e208fdb5ca757e3508a2f0764c16798 | [
"Apache-2.0"
] | null | null | null | api/todolist.py | groupwildman/todolist | 7ce990b91e208fdb5ca757e3508a2f0764c16798 | [
"Apache-2.0"
] | null | null | null | api/todolist.py | groupwildman/todolist | 7ce990b91e208fdb5ca757e3508a2f0764c16798 | [
"Apache-2.0"
] | null | null | null | from app import app
from views import *
app.add_url_rule("/signup", view_func=signup, methods=["POST", "GET"])
app.add_url_rule("/login", view_func=login, methods=["POST", "GET", "OPTIONS"])
app.add_url_rule("/dashboard/create-list", view_func=dashboard_addList, methods=["POST", "GET"])
app.add_url_rule("/dashboard/api/load-list", view_func=dashboard_fetchlist, methods=["POST"])
app.add_url_rule("/dashboard/api/create-list", view_func=dashboard_addList, methods=["POST"])
if __name__ == "__main__":
app.run(debug=True) | 47.727273 | 96 | 0.744762 | 79 | 525 | 4.620253 | 0.35443 | 0.082192 | 0.123288 | 0.178082 | 0.526027 | 0.465753 | 0.364384 | 0.246575 | 0 | 0 | 0 | 0 | 0.064762 | 525 | 11 | 97 | 47.727273 | 0.743381 | 0 | 0 | 0 | 0 | 0 | 0.245247 | 0.136882 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.222222 | 0 | 0.222222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
26dc3f711be7fb7e28c37baf8ab83d8833744674 | 399 | py | Python | icekit/plugins/slideshow/content_plugins.py | ic-labs/django-icekit | c507ea5b1864303732c53ad7c5800571fca5fa94 | [
"MIT"
] | 52 | 2016-09-13T03:50:58.000Z | 2022-02-23T16:25:08.000Z | icekit/plugins/slideshow/content_plugins.py | ic-labs/django-icekit | c507ea5b1864303732c53ad7c5800571fca5fa94 | [
"MIT"
] | 304 | 2016-08-11T14:17:30.000Z | 2020-07-22T13:35:18.000Z | icekit/plugins/slideshow/content_plugins.py | ic-labs/django-icekit | c507ea5b1864303732c53ad7c5800571fca5fa94 | [
"MIT"
] | 12 | 2016-09-21T18:46:35.000Z | 2021-02-15T19:37:50.000Z | """
Definition of the plugin.
"""
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class SlideShowPlugin(ContentPlugin):
model = models.SlideShowItem
category = _('Assets')
render_template = 'icekit/plugins/slideshow/default.html'
raw_id_fields = ['slide_show', ]
| 24.9375 | 65 | 0.766917 | 46 | 399 | 6.434783 | 0.804348 | 0.067568 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.140351 | 399 | 15 | 66 | 26.6 | 0.862974 | 0.062657 | 0 | 0 | 0 | 0 | 0.144809 | 0.101093 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.888889 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
26faf6a82020be218b501960f0be01e61146519d | 1,287 | py | Python | examples/test_service_client.py | fakeNetflix/pinterest-repo-kingpin | baea08ae941a4e57edb9129658fe3e7d40e4d0c3 | [
"Apache-2.0"
] | 76 | 2016-01-27T21:16:53.000Z | 2021-09-23T02:23:49.000Z | examples/test_service_client.py | fakeNetflix/pinterest-repo-kingpin | baea08ae941a4e57edb9129658fe3e7d40e4d0c3 | [
"Apache-2.0"
] | 2 | 2016-02-26T02:37:46.000Z | 2018-02-23T09:03:41.000Z | examples/test_service_client.py | fakeNetflix/pinterest-repo-kingpin | baea08ae941a4e57edb9129658fe3e7d40e4d0c3 | [
"Apache-2.0"
] | 22 | 2016-01-27T21:16:58.000Z | 2020-12-24T11:26:01.000Z | #!/usr/bin/python
#
# Copyright 2016 Pinterest, 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.
from kingpin.thrift_utils.thrift_client_mixin import PooledThriftClientMixin
from kingpin.thrift_utils.base_thrift_exceptions import ThriftConnectionError
from kingpin.kazoo_utils.hosts import HostsProvider
import TestService
class TestServiceConnectionException(ThriftConnectionError):
pass
class TestServiceClient(TestService.Client, PooledThriftClientMixin):
def get_connection_exception_class(self):
return TestServiceConnectionException
testservice_client = TestServiceClient(
HostsProvider([], file_path="/var/serverset/discovery.test_service.prod"),
timeout=3000,
pool_size=10,
always_retry_on_new_host=True)
print testservice_client.ping()
| 32.175 | 78 | 0.796426 | 164 | 1,287 | 6.134146 | 0.670732 | 0.059642 | 0.025845 | 0.031809 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012601 | 0.136752 | 1,287 | 39 | 79 | 33 | 0.892889 | 0.441336 | 0 | 0 | 0 | 0 | 0.059659 | 0.059659 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.066667 | 0.266667 | null | null | 0.066667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
f8056d3de3457f7f8ed656ba38fed65f7e77c996 | 420 | py | Python | dapricot/blog/tokens.py | softapr/django_apricot | 911b6627a5ffaf3f7b13a099ca129f3a2ffda558 | [
"BSD-3-Clause"
] | null | null | null | dapricot/blog/tokens.py | softapr/django_apricot | 911b6627a5ffaf3f7b13a099ca129f3a2ffda558 | [
"BSD-3-Clause"
] | null | null | null | dapricot/blog/tokens.py | softapr/django_apricot | 911b6627a5ffaf3f7b13a099ca129f3a2ffda558 | [
"BSD-3-Clause"
] | null | null | null | from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, commenter, timestamp):
return (
six.text_type(commenter.pk) + six.text_type(timestamp) +
six.text_type(commenter.status)
)
account_activation_token = AccountActivationTokenGenerator() | 38.181818 | 68 | 0.761905 | 41 | 420 | 7.609756 | 0.634146 | 0.067308 | 0.105769 | 0.128205 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 420 | 11 | 69 | 38.181818 | 0.891429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0.222222 | 0.222222 | 0.111111 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 |
f80efd27f0e3589d4c5d1bef94d4a9e2c4a19723 | 13,014 | py | Python | test/test_constraints.py | ELIFE-ASU/randomneet | 5efbcd55ab838b53b287b49d13e14b0d42486a7d | [
"MIT"
] | null | null | null | test/test_constraints.py | ELIFE-ASU/randomneet | 5efbcd55ab838b53b287b49d13e14b0d42486a7d | [
"MIT"
] | null | null | null | test/test_constraints.py | ELIFE-ASU/randomneet | 5efbcd55ab838b53b287b49d13e14b0d42486a7d | [
"MIT"
] | null | null | null | import networkx as nx
import randomneet
import unittest
from neet.boolean import LogicNetwork
from neet.boolean.examples import s_pombe, myeloid
from randomneet.constraints import AbstractConstraint, TopologicalConstraint, DynamicalConstraint, \
HasExternalNodes, IsConnected, IsIrreducible, \
HasCanalizingNodes, GenericTopological, GenericDynamical, \
ConstraintError
class TestConstraints(unittest.TestCase):
"""
Unit tests for the various network constraints.
"""
def empty_graph(self, n=0):
"""
Create a directed graph with no edges and ``n`` nodes.
"""
g = nx.DiGraph()
g.add_nodes_from(range(n))
return g
def test_constraints_module(self):
"""
Ensure that constraints is exported from randomneet
"""
self.assertTrue('constraints' in dir(randomneet))
def test_abstract_constraint(self):
"""
The AbstractConstraint should be an abstract object
"""
self.assertTrue(issubclass(AbstractConstraint, object))
with self.assertRaises(TypeError):
AbstractConstraint() # type: ignore
def test_topological_constraint(self):
"""
The TopologicalConstraint should be an abstract subclass of
AbstractConstraint
"""
self.assertTrue(issubclass(TopologicalConstraint, AbstractConstraint))
with self.assertRaises(TypeError):
TopologicalConstraint() # type: ignore
def test_dynamical_constraint(self):
"""
The DynamicalConstraint should be an abstract subclass of
AbstractConstraint
"""
self.assertTrue(issubclass(DynamicalConstraint, AbstractConstraint))
with self.assertRaises(TypeError):
DynamicalConstraint() # type: ignore
def test_has_external_nodes_is_topological(self):
"""
The HasExternalNodes constraint is a TopologicalConstraint
"""
self.assertTrue(issubclass(HasExternalNodes, TopologicalConstraint))
def test_has_external_nodes_invalid_init(self):
"""
HasExternalNodes should raise a Value or TypeError for invalid
initialization parameters.
"""
with self.assertRaises(ValueError):
HasExternalNodes(-1)
with self.assertRaises(TypeError):
HasExternalNodes(nx.Graph())
def test_has_external_nodes_counts(self):
"""
HasExternalNodes properly counts the number of external nodes in a
directed graph.
"""
g = nx.DiGraph([(0, 1), (1, 2), (2, 1), (3, 1), (4, 5), (6, 6)])
constraint = HasExternalNodes(g)
self.assertEqual(constraint.num_external, 3)
def test_has_external_nodes_saves_target(self):
"""
HasExternalNodes properly stores the desired number of external edges.
"""
self.assertEqual(HasExternalNodes(7).num_external, 7)
def test_has_external_nodes_raises(self):
"""
HasExternalNodes.satisfies raises an error if the provided argument is
not a directed graph.
"""
constraint = HasExternalNodes(3)
with self.assertRaises(TypeError):
constraint.satisfies(3)
with self.assertRaises(TypeError):
constraint.satisfies(nx.Graph())
def test_has_external_nodes_satisfies(self):
"""
HasExternalNodes.satsifies correctly identifies directed graphs with
the desired number of external nodes.
"""
g = nx.DiGraph([(0, 1), (1, 2), (2, 1), (3, 1), (4, 5), (6, 6)])
constraint = HasExternalNodes(3)
self.assertFalse(constraint.satisfies(nx.DiGraph()))
self.assertFalse(constraint.satisfies(nx.DiGraph([(0, 1), (1, 2), (2, 1), (3, 2)])))
self.assertTrue(constraint.satisfies(g))
constraint = HasExternalNodes(g)
self.assertFalse(constraint.satisfies(nx.DiGraph()))
self.assertFalse(constraint.satisfies(nx.DiGraph([(0, 1), (1, 2), (2, 1), (3, 2)])))
self.assertTrue(constraint.satisfies(g))
self.assertTrue(constraint.satisfies(nx.DiGraph([(1, 2), (3, 4), (5, 6), (7, 7)])))
def test_is_connected_is_topological(self):
"""
The IsConnected constraint is a TopologicalConstraint
"""
self.assertTrue(issubclass(IsConnected, TopologicalConstraint))
def test_is_connected_raises(self):
"""
IsConnected.satisfies raises an error if the provided argument is not a
directed graph.
"""
constraint = HasExternalNodes(3)
with self.assertRaises(TypeError):
constraint.satisfies(3)
with self.assertRaises(TypeError):
constraint.satisfies(nx.Graph())
def test_is_connected_null_graph(self):
"""
IsConnected.satisfies raises an error if the provided argument is the
null graph.
"""
constraint = IsConnected()
with self.assertRaises(ConstraintError):
constraint.satisfies(nx.DiGraph())
def test_is_connected_satisfies(self):
"""
IsConnected.satisfies correctly identifies directed graphs that are
weakly connected.
"""
constraint = IsConnected()
self.assertTrue(constraint.satisfies(self.empty_graph(1)))
self.assertTrue(constraint.satisfies(nx.DiGraph([(0, 0)])))
self.assertFalse(constraint.satisfies(self.empty_graph(2)))
self.assertFalse(constraint.satisfies(nx.DiGraph([(0, 0), (1, 1)])))
self.assertTrue(constraint.satisfies(nx.DiGraph([(0, 1)])))
def test_is_irreducibile_is_dynamical(self):
"""
The IsIrreducible constraint is a DynamicalConstraint.
"""
self.assertTrue(issubclass(IsIrreducible, DynamicalConstraint))
def test_is_irreducible_raises(self):
"""
IsIrreducible.satisfies raises an error if the argument is not a Neet
network.
"""
constraint = IsIrreducible()
with self.assertRaises(TypeError):
constraint.satisfies(nx.DiGraph())
with self.assertRaises(TypeError):
constraint.satisfies(nx.Graph())
def test_is_irreducible_satisfies_non_logic(self):
"""
IsIrreducible.satisfies is not implemented for non-LogicNetworks
"""
constraint = IsIrreducible()
with self.assertRaises(NotImplementedError):
constraint.satisfies(s_pombe)
def test_is_irreducible_satisfies(self):
"""
IsIrreducible.satisfies correctly identifies networks that are
irreducible.
"""
constraint = IsIrreducible()
self.assertTrue(constraint.satisfies(myeloid))
reducible = LogicNetwork([((0,), {'0', '1'})])
self.assertFalse(constraint.satisfies(reducible))
reducible = LogicNetwork([((0, 1), {'01', '11'}),
((0, 1), {'00', '01', '11'})])
self.assertFalse(constraint.satisfies(reducible))
reducible = LogicNetwork([((1,), {'0'}),
((0, 1), {'01', '11'})])
self.assertFalse(constraint.satisfies(reducible))
irreducible = LogicNetwork([((0,), {'0'})])
self.assertTrue(constraint.satisfies(irreducible))
irreducible = LogicNetwork([((0, 1), {'01'}),
((0, 1), {'00', '01', '11'})])
self.assertTrue(constraint.satisfies(irreducible))
irreducible = LogicNetwork([((1,), {'0'}),
((0, 1), {'01', '11', '10'})])
self.assertTrue(constraint.satisfies(irreducible))
def test_has_canalizing_nodes_is_dynamical(self):
"""
The HasCanalizingNodes constraint is a DynamicalConstraint
"""
self.assertTrue(issubclass(HasCanalizingNodes, DynamicalConstraint))
def test_has_canalizing_nodes_invalid_init(self):
"""
HasCanalizingNodes should raise a ValueError or TypeError for invalid
initialization parameters.
"""
with self.assertRaises(ValueError):
HasCanalizingNodes(-1)
with self.assertRaises(TypeError):
HasCanalizingNodes(nx.Graph())
def test_has_canalizing_nodes_counts(self):
"""
HasCanalizingNodes properly counts the number of canalizing nodes in a
network.
"""
constraint = HasCanalizingNodes(myeloid)
self.assertEqual(constraint.num_canalizing, 11)
constraint = HasCanalizingNodes(s_pombe)
self.assertEqual(constraint.num_canalizing, 5)
def test_has_canalizing_nodes_saves_target(self):
"""
HasCanalizingNodes properly stores the desired number of external
edges.
"""
self.assertEqual(HasCanalizingNodes(7).num_canalizing, 7)
def test_has_canalizing_nodes_raises(self):
"""
HasCanalizingNodes.satisfies raises an error if the provided argument
is not a neet network
"""
constraint = HasCanalizingNodes(3)
with self.assertRaises(TypeError):
constraint.satisfies(3)
with self.assertRaises(TypeError):
constraint.satisfies(nx.Graph())
with self.assertRaises(TypeError):
constraint.satisfies(nx.DiGraph())
def test_has_canalizing_nodes_satisfies(self):
"""
HasCanalizingNodes.satsifies correctly identifies networks the desired
number of canalizing nodes.
"""
constraint = HasCanalizingNodes(myeloid)
self.assertTrue(constraint.satisfies(myeloid))
self.assertFalse(constraint.satisfies(s_pombe))
def test_generic_topological_is_topological(self):
"""
Ensure that GenericTopological is a subclass of TopologicalConstraint.
"""
self.assertTrue(issubclass(GenericTopological, TopologicalConstraint))
def test_generic_topological_raises(self):
"""
GenericTopological raises a TypeError if it's instantiated with
anything that is not callable.
"""
with self.assertRaises(TypeError):
GenericTopological(5)
with self.assertRaises(TypeError):
GenericTopological(IsConnected())
def test_generic_topological_satisfies_raises(self):
"""
GenericTopological.satisfies raises a TypeError when its argument is
not a directed graph.
"""
allpass = GenericTopological(lambda g: True)
with self.assertRaises(TypeError):
allpass.satisfies(nx.Graph())
with self.assertRaises(TypeError):
allpass.satisfies(s_pombe)
def test_generic_topological_satisfies(self):
"""
GenericTopological.satisfies correctly checks graphs.
"""
allpass = GenericTopological(lambda g: True)
self.assertTrue(allpass.satisfies(self.empty_graph()))
self.assertTrue(allpass.satisfies(nx.DiGraph([(0, 1), (1, 2), (2, 0)])))
allfail = GenericTopological(lambda g: False)
self.assertFalse(allfail.satisfies(self.empty_graph()))
self.assertFalse(allfail.satisfies(nx.DiGraph([(0, 1), (1, 2), (2, 0)])))
twonodes = GenericTopological(lambda g: len(g) == 2)
self.assertFalse(twonodes.satisfies(self.empty_graph()))
self.assertTrue(twonodes.satisfies(self.empty_graph(2)))
def test_generic_dynamical_is_dynamical(self):
"""
Ensure that GenericDynamical is a subclass of DynamicalConstraint.
"""
self.assertTrue(issubclass(GenericDynamical, DynamicalConstraint))
def test_generic_dynamical_raises(self):
"""
GenericDynamical raises a TypeError if it's instantiated with anything
that is not callable.
"""
with self.assertRaises(TypeError):
GenericDynamical(5)
with self.assertRaises(TypeError):
GenericDynamical(IsIrreducible())
def test_generic_dynamical_satisfies_raises(self):
"""
GenericDynamical.satisfies raises a TypeError when its argument is not
a network.
"""
allpass = GenericDynamical(lambda n: True)
with self.assertRaises(TypeError):
allpass.satisfies(nx.Graph())
with self.assertRaises(TypeError):
allpass.satisfies(nx.DiGraph())
def test_generic_dynamical_satisfies(self):
"""
GenericDynamical.satisfies correctly checks networks.
"""
allpass = GenericDynamical(lambda n: True)
self.assertTrue(allpass.satisfies(myeloid))
self.assertTrue(allpass.satisfies(s_pombe))
allfail = GenericDynamical(lambda g: False)
self.assertFalse(allfail.satisfies(myeloid))
self.assertFalse(allfail.satisfies(s_pombe))
ninenodes = GenericDynamical(lambda g: g.size == 9)
self.assertTrue(ninenodes.satisfies(s_pombe))
self.assertFalse(ninenodes.satisfies(myeloid))
| 36.971591 | 100 | 0.643461 | 1,272 | 13,014 | 6.472484 | 0.118711 | 0.027208 | 0.06316 | 0.077493 | 0.56067 | 0.40034 | 0.369367 | 0.265152 | 0.240617 | 0.234787 | 0 | 0.01463 | 0.254188 | 13,014 | 351 | 101 | 37.076923 | 0.833608 | 0.199554 | 0 | 0.388889 | 0 | 0 | 0.004641 | 0 | 0 | 0 | 0 | 0 | 0.411111 | 1 | 0.183333 | false | 0.066667 | 0.033333 | 0 | 0.227778 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
f86269ca3900b750757ff89130ea7dc133ae3a31 | 312 | py | Python | tools/train_test.py | stanley-king/cuda10-py3-faster-rcnn | 013f99c428874bfd3ddaeed264031143d10a8123 | [
"BSD-2-Clause"
] | null | null | null | tools/train_test.py | stanley-king/cuda10-py3-faster-rcnn | 013f99c428874bfd3ddaeed264031143d10a8123 | [
"BSD-2-Clause"
] | 1 | 2020-12-28T03:20:43.000Z | 2020-12-28T03:20:43.000Z | tools/train_test.py | stanley-king/cuda10-py3-faster-rcnn | 013f99c428874bfd3ddaeed264031143d10a8123 | [
"BSD-2-Clause"
] | null | null | null |
import unittest
import _init_paths
from datasets.pascal_voc import pascal_voc
class MyTestCase(unittest.TestCase):
def test_pascal_voc(self):
d = pascal_voc('trainval', '2007')
res = d.roidb
from IPython import embed
embed()
if __name__ == '__main__':
unittest.main()
| 19.5 | 42 | 0.676282 | 39 | 312 | 5.025641 | 0.615385 | 0.183673 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016736 | 0.233974 | 312 | 15 | 43 | 20.8 | 0.803347 | 0 | 0 | 0 | 0 | 0 | 0.064309 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0 | 0.363636 | 0 | 0.545455 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
f86dee4c4ea8ced242cebd65f69976a8d15696fc | 1,086 | py | Python | artascope/test/config/test_config.py | magus0219/icloud-photo-downloader | 6334530d971cf61089d031de99a38f204c201837 | [
"MIT"
] | 3 | 2020-09-24T16:19:28.000Z | 2022-02-09T21:10:11.000Z | artascope/test/config/test_config.py | magus0219/icloud-photo-downloader | 6334530d971cf61089d031de99a38f204c201837 | [
"MIT"
] | null | null | null | artascope/test/config/test_config.py | magus0219/icloud-photo-downloader | 6334530d971cf61089d031de99a38f204c201837 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Created by magus0219[magus0219@gmail.com] on 2020/4/23
class TestConfig:
def test_config_base(self):
from artascope.src.config import TZ
from artascope.src.config.base import TZ as TIMEZONE_BASE
assert TZ == TIMEZONE_BASE
def test_config_overwrite_by_file(self):
import os
import importlib
from artascope.src.config import SECONDS_WAIT_FOR_API_LIMIT
env = os.environ["ARTASCOPE_ENV"]
config_module_test = importlib.import_module(
"artascope.src.config.{}".format(env)
)
assert SECONDS_WAIT_FOR_API_LIMIT == getattr(
config_module_test, "SECONDS_WAIT_FOR_API_LIMIT"
)
def test_config_overwrite_by_env(self):
import os
import sys
import importlib
os.environ["SECONDS_WAIT_FOR_API_LIMIT"] = "-1"
importlib.reload(sys.modules["artascope.src.config"])
from artascope.src.config import SECONDS_WAIT_FOR_API_LIMIT
assert SECONDS_WAIT_FOR_API_LIMIT == "-1"
| 31.028571 | 67 | 0.671271 | 141 | 1,086 | 4.87234 | 0.340426 | 0.104803 | 0.157205 | 0.148472 | 0.404658 | 0.262009 | 0.14556 | 0.14556 | 0.14556 | 0.14556 | 0 | 0.023086 | 0.242173 | 1,086 | 34 | 68 | 31.941176 | 0.811665 | 0.090239 | 0 | 0.25 | 0 | 0 | 0.113821 | 0.07622 | 0 | 0 | 0 | 0 | 0.125 | 1 | 0.125 | false | 0 | 0.458333 | 0 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
f8819229eb71f136e7e9fa27d929bad4319f8b24 | 666 | py | Python | basic-programs/tensor_autograd.py | lcskrishna/my-pytorch-experiments | b846760bbf8dfa930fa914edcee8f1a71a43fc98 | [
"MIT"
] | null | null | null | basic-programs/tensor_autograd.py | lcskrishna/my-pytorch-experiments | b846760bbf8dfa930fa914edcee8f1a71a43fc98 | [
"MIT"
] | null | null | null | basic-programs/tensor_autograd.py | lcskrishna/my-pytorch-experiments | b846760bbf8dfa930fa914edcee8f1a71a43fc98 | [
"MIT"
] | null | null | null | import torch
x = torch.ones(2,2, requires_grad = True)
print (x)
y = x + 2
print (y)
print (y.grad_fn)
z = y * y * 3
out = z.mean()
print (z)
print (out)
a = torch.randn(2,2)
a = ((a * 3)/ (a - 1))
print (a.requires_grad)
a.requires_grad_(True)
print (a.requires_grad)
b = (a * a).sum()
print (b.grad_fn)
out.backward()
print (x.grad)
x = torch.randn(3, requires_grad = True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
print (y)
gradients = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(gradients)
print (x.grad)
print (x.requires_grad)
print ((x ** 2).requires_grad)
with torch.no_grad():
print ((x ** 2).requires_grad)
| 15.857143 | 63 | 0.623123 | 123 | 666 | 3.276423 | 0.268293 | 0.238213 | 0.096774 | 0.104218 | 0.114144 | 0.114144 | 0 | 0 | 0 | 0 | 0 | 0.048059 | 0.187688 | 666 | 41 | 64 | 16.243902 | 0.696858 | 0 | 0 | 0.258065 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.032258 | 0 | 0.032258 | 0.451613 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
f88741913de7f3a1ecb15d96b90ac119bde11b01 | 206 | py | Python | Linguagens/Python/Exercicios/cursos_em_video/aulas-01_a_21/025.py | rafaelvizu/Estudos | eef5e3e3706ff99959226c51b9907b6af4377bfe | [
"MIT"
] | null | null | null | Linguagens/Python/Exercicios/cursos_em_video/aulas-01_a_21/025.py | rafaelvizu/Estudos | eef5e3e3706ff99959226c51b9907b6af4377bfe | [
"MIT"
] | null | null | null | Linguagens/Python/Exercicios/cursos_em_video/aulas-01_a_21/025.py | rafaelvizu/Estudos | eef5e3e3706ff99959226c51b9907b6af4377bfe | [
"MIT"
] | null | null | null | print('Exercรญcio Python #025 - Procurando uma string dentro de outra')
print('By Guanabara')
name = str(input('Qual รฉ o seu nome? ')).title().strip()
print('Seu nome tem Silva? {}'.format('Silva' in name))
| 41.2 | 70 | 0.694175 | 32 | 206 | 4.46875 | 0.8125 | 0.097902 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.01676 | 0.131068 | 206 | 4 | 71 | 51.5 | 0.782123 | 0 | 0 | 0 | 0 | 0 | 0.57767 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.75 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
f888e8fb3dce5a5d84fb6da852c636bd18d117bd | 1,112 | py | Python | Test/LensCalibrationTest.py | thpe/voxelsdk | f308e4ce5d72e4fca88debc415d894d053193391 | [
"BSD-3-Clause"
] | 112 | 2016-01-04T09:25:56.000Z | 2022-03-18T17:28:05.000Z | Test/LensCalibrationTest.py | Metrilus/voxelsdk | 751641a08285c4a31e68491df8887f79e71d34d2 | [
"BSD-3-Clause"
] | 149 | 2015-10-09T08:28:07.000Z | 2021-07-09T20:48:09.000Z | Test/LensCalibrationTest.py | Metrilus/voxelsdk | 751641a08285c4a31e68491df8887f79e71d34d2 | [
"BSD-3-Clause"
] | 77 | 2015-10-21T22:14:59.000Z | 2022-03-18T17:26:18.000Z | import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
#parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#parser.add_argument("-f", "--file", type=str, help="Voxel file (.vxl)", required=True)
#args = parser.parse_args()
## Voxel-A lens
k1 = -0.1583968
k2 = 0.06113919
k3 = 0.09898978
p1 = 0.001591975
p2 = -0.0001962754
x = np.linspace(0, 0.9, 200)
y = 0
r2 = x*x
r4 = r2*r2
r6 = r4*r2
x1 = x*(1 + k1*r2 + k2*r4 + k3*r6) + 2*p1*x*y + p2*(r2 + 2*x*x)
y1 = y*(1 + k1*r2 + k2*r4 + k3*r6) + p1*(r2 + 2*y*y) + p2*x*y
## Tintin lens
k1 = 0.909882
k2 = -3.559455
k3 = 3.626591
p1 = 0.047604
p2 = -0.005546
x2 = x*(1 + k1*r2 + k2*r4 + k3*r6) + 2*p1*x*y + p2*(r2 + 2*x*x)
y2 = y*(1 + k1*r2 + k2*r4 + k3*r6) + p1*(r2 + 2*y*y) + p2*x*y
r2 = x1*x1 + y1*y1
r4 = r2*r2
r6 = r4*r2
x3 = x1*(1 + k1*r2 + k2*r4 + k3*r6) + 2*p1*x1*y1 + p2*(r2 + 2*x1*x1)
y3 = y1*(1 + k1*r2 + k2*r4 + k3*r6) + p1*(r2 + 2*y1*y1) + p2*x1*y1
plt.plot(x, x1, x, x2, 'r', x, x3, 'k')
plt.grid(True)
plt.legend(['Voxel-A', 'TintinCDK', 'Distorted to Corrected'])
plt.show() | 21.803922 | 89 | 0.590827 | 229 | 1,112 | 2.855895 | 0.318777 | 0.027523 | 0.045872 | 0.06422 | 0.244648 | 0.244648 | 0.207951 | 0.207951 | 0.207951 | 0.183486 | 0 | 0.227525 | 0.189748 | 1,112 | 51 | 90 | 21.803922 | 0.498335 | 0.202338 | 0 | 0.125 | 0 | 0 | 0.045403 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.125 | 0 | 0.125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
f89fbc55d5fdda33b1448ba8372bfc73bdac38ae | 160 | py | Python | Sem-07-T2-04.py | daianasousa/Atividade-Remota-Semana-07 | 1c4a28bf052057e921730ba79dfb0cdaa74576e0 | [
"MIT"
] | null | null | null | Sem-07-T2-04.py | daianasousa/Atividade-Remota-Semana-07 | 1c4a28bf052057e921730ba79dfb0cdaa74576e0 | [
"MIT"
] | null | null | null | Sem-07-T2-04.py | daianasousa/Atividade-Remota-Semana-07 | 1c4a28bf052057e921730ba79dfb0cdaa74576e0 | [
"MIT"
] | null | null | null | num = int(input('Digite um nรบmero: '))
total = 0
for c in range(1, num + 1):
if num % c == 0:
total += 1
if total == 2:
print(True)
else:
print(False) | 17.777778 | 38 | 0.56875 | 29 | 160 | 3.137931 | 0.655172 | 0.065934 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.05042 | 0.25625 | 160 | 9 | 39 | 17.777778 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0.111801 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.222222 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
f8a013a413eff01acb11edba4cd593518603d459 | 218 | py | Python | config.py | hhalim/TargetBanksJupyter | 665222d8338de773e36c5635861bc95a71ef6259 | [
"MIT"
] | null | null | null | config.py | hhalim/TargetBanksJupyter | 665222d8338de773e36c5635861bc95a71ef6259 | [
"MIT"
] | null | null | null | config.py | hhalim/TargetBanksJupyter | 665222d8338de773e36c5635861bc95a71ef6259 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Global Configuration
"""
mssql = {
'server' : 'localhost\SQL2016',
'database' : 'bkrob',
'username' : 'bkrob_adm',
'password' : 'bkrob_adm'
}
google_geocode_api = 'api key' | 16.769231 | 35 | 0.582569 | 22 | 218 | 5.590909 | 0.818182 | 0.130081 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.02907 | 0.211009 | 218 | 13 | 36 | 16.769231 | 0.686047 | 0.197248 | 0 | 0 | 0 | 0 | 0.458333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.142857 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
f8b1dd964e993cea289bee4b5d5ebddca6506854 | 1,406 | py | Python | videos/views.py | drewvpham/xclude.com | 103e89e2326c4c6fbfab819c43bc4e4634913bc9 | [
"MIT"
] | null | null | null | videos/views.py | drewvpham/xclude.com | 103e89e2326c4c6fbfab819c43bc4e4634913bc9 | [
"MIT"
] | 17 | 2019-12-26T06:20:07.000Z | 2022-02-10T09:04:51.000Z | videos/views.py | drewvpham/xclude.com | 103e89e2326c4c6fbfab819c43bc4e4634913bc9 | [
"MIT"
] | null | null | null | from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import render, get_object_or_404
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from memberships.models import UserMembership
from .models import Video
class VideoListView(ListView):
model = Video
class VideoDetailView(DetailView):
model = Video
template_name = "videos/video_detail.html"
class VideoCreateView(CreateView):
model = Video
fields = ['title','description', 'videofile','thumbnail', 'private', 'tags']
def form_valid(self, form):
form.instance.uploader = self.request.user
return super().form_valid(form)
class VideoUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Video
fields = ['description']
def form_valid(self, form):
form.instance.uploader = self.request.user
return super().form_valid(form)
def test_func(self):
video = self.get_object()
if self.request.user == video.uploader:
return True
return False
class VideoDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Video
success_url = '/'
def test_func(self):
video = self.get_object()
if self.request.user == video.uploader:
return True
return False
| 25.107143 | 80 | 0.692745 | 150 | 1,406 | 6.4 | 0.406667 | 0.052083 | 0.0625 | 0.033333 | 0.339583 | 0.339583 | 0.339583 | 0.339583 | 0.339583 | 0.339583 | 0 | 0.002722 | 0.216216 | 1,406 | 55 | 81 | 25.563636 | 0.868421 | 0 | 0 | 0.512195 | 0 | 0 | 0.05761 | 0.01707 | 0 | 0 | 0 | 0 | 0 | 1 | 0.097561 | false | 0.073171 | 0.121951 | 0 | 0.707317 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
f8cc90b8a16749124683ec2e928f44dd5f38f12c | 1,269 | py | Python | Arrays/Find_common_elements_in_three_sorted_arrays/solution.py | abhaydhiman/Pyalgo | 69efdd937041548234bf67a2bd0b962b6e60a556 | [
"MIT"
] | 1 | 2021-01-05T14:09:47.000Z | 2021-01-05T14:09:47.000Z | Arrays/Find_common_elements_in_three_sorted_arrays/solution.py | abhaydhiman/Pyalgo | 69efdd937041548234bf67a2bd0b962b6e60a556 | [
"MIT"
] | null | null | null | Arrays/Find_common_elements_in_three_sorted_arrays/solution.py | abhaydhiman/Pyalgo | 69efdd937041548234bf67a2bd0b962b6e60a556 | [
"MIT"
] | null | null | null | def my_func(arr1, arr2, arr3):
ln1 = len(arr1)
ln2 = len(arr2)
ln3 = len(arr3)
ptr1 = 0
ptr2 = 0
ptr3 = 0
while ptr1 < ln1 and ptr2 < ln2 and ptr3 < ln3:
if arr1[ptr1] < arr2[ptr2]:
if arr3[ptr3] < arr2[ptr2]:
arr1[ptr1] = -1
arr3[ptr3] = -1
ptr3 += 1
ptr1 += 1
else:
arr1[ptr1] = -1
ptr1 += 1
elif arr2[ptr2] < arr3[ptr3]:
if arr1[ptr1] < arr3[ptr3]:
arr1[ptr1] = -1
arr2[ptr2] = -1
ptr1 += 1
ptr2 += 1
else:
arr2[ptr2] = -1
ptr2 += 1
elif arr3[ptr3] < arr1[ptr1]:
if arr2[ptr2] < arr1[ptr1]:
arr2[ptr2] = -1
arr3[ptr3] = -1
ptr2 += 1
ptr3 += 1
else:
arr3[ptr3] = -1
ptr3 += 1
else:
ptr1 += 1
ptr2 += 1
ptr3 += 1
for i in arr1:
if i != -1:
print(i, end=' ')
ls1 = [1, 5, 5]
ls2 = [3, 4, 5, 5, 10]
ls3 = [5, 5, 10, 20]
my_func(ls1, ls2, ls3)
| 23.5 | 51 | 0.339638 | 145 | 1,269 | 2.958621 | 0.227586 | 0.130536 | 0.055944 | 0.074592 | 0.11655 | 0 | 0 | 0 | 0 | 0 | 0 | 0.203419 | 0.539007 | 1,269 | 53 | 52 | 23.943396 | 0.529915 | 0 | 0 | 0.543478 | 0 | 0 | 0.000788 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.021739 | false | 0 | 0 | 0 | 0.021739 | 0.021739 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6ef2ba10b8f2591bd0e124702b034ea464bd90b0 | 277 | py | Python | atv018.py | luismontei/Atividades-python-2 | baaec4f56f30bbef148201d96d5c947e525204a5 | [
"Apache-2.0"
] | null | null | null | atv018.py | luismontei/Atividades-python-2 | baaec4f56f30bbef148201d96d5c947e525204a5 | [
"Apache-2.0"
] | null | null | null | atv018.py | luismontei/Atividades-python-2 | baaec4f56f30bbef148201d96d5c947e525204a5 | [
"Apache-2.0"
] | null | null | null | n1 = float(input('Informe um nรบmero: '))
n2 = float(input('Informe um nรบmero: '))
n3 = float(input('Informe um nรบmero: '))
if (n1<n2) and (n1<n3) and (n2<n3):
print (n1,n2,n3)
elif (n2<n1) and (n2<n3) and (n1<n3):
print(n2,n1,n3)
else:
print(n3,n1,n2)
| 23.083333 | 41 | 0.577617 | 49 | 277 | 3.265306 | 0.265306 | 0.1875 | 0.31875 | 0.35625 | 0.46875 | 0 | 0 | 0 | 0 | 0 | 0 | 0.110599 | 0.216607 | 277 | 11 | 42 | 25.181818 | 0.626728 | 0 | 0 | 0 | 0 | 0 | 0.215094 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6efdd3681a7426735e4fca737ee42394f66d6d6a | 2,325 | py | Python | pysnmp/RAPTOR-SNMPv1-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/RAPTOR-SNMPv1-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/RAPTOR-SNMPv1-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module RAPTOR-SNMPv1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPTOR-SNMPv1-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:43:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibIdentifier, Gauge32, enterprises, Counter64, Bits, Unsigned32, Counter32, ModuleIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, NotificationType, NotificationType, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "enterprises", "Counter64", "Bits", "Unsigned32", "Counter32", "ModuleIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "NotificationType", "NotificationType", "iso", "TimeTicks")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
raptorSystems = MibIdentifier((1, 3, 6, 1, 4, 1, 1294))
raptorModules = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 1))
raptorObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 2))
raptorTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 3))
raptorNotifyMessage = MibScalar((1, 3, 6, 1, 4, 1, 1294, 2, 1), OctetString())
if mibBuilder.loadTexts: raptorNotifyMessage.setStatus('mandatory')
raptorNotifyTrap = NotificationType((1, 3, 6, 1, 4, 1, 1294) + (0,1)).setObjects(("RAPTOR-SNMPv1-MIB", "raptorNotifyMessage"))
mibBuilder.exportSymbols("RAPTOR-SNMPv1-MIB", raptorTraps=raptorTraps, raptorNotifyMessage=raptorNotifyMessage, raptorSystems=raptorSystems, raptorModules=raptorModules, raptorNotifyTrap=raptorNotifyTrap, raptorObjects=raptorObjects)
| 105.681818 | 543 | 0.776344 | 242 | 2,325 | 7.458678 | 0.429752 | 0.076454 | 0.009972 | 0.013296 | 0.38892 | 0.279224 | 0.279224 | 0.273684 | 0.216066 | 0.216066 | 0 | 0.065666 | 0.083011 | 2,325 | 21 | 544 | 110.714286 | 0.780957 | 0.141075 | 0 | 0 | 0 | 0 | 0.266097 | 0.022133 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.428571 | 0 | 0.428571 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
3e28790b361fd43b28fee22b773ac286abe25ffb | 164 | py | Python | webserver/createdb.py | BenjaminAtbi/leaguemate | 0df8ec895ff590c3441a06561ffa77df8d088cf0 | [
"MIT"
] | null | null | null | webserver/createdb.py | BenjaminAtbi/leaguemate | 0df8ec895ff590c3441a06561ffa77df8d088cf0 | [
"MIT"
] | null | null | null | webserver/createdb.py | BenjaminAtbi/leaguemate | 0df8ec895ff590c3441a06561ffa77df8d088cf0 | [
"MIT"
] | null | null | null | import sqlite3
conn = sqlite3.connect('leaguemate.db')
c = conn.cursor()
sql_file=open('Newdatabase.sql')
sql_as_str=sql_file.read()
c.executescript(sql_as_str)
| 16.4 | 39 | 0.768293 | 26 | 164 | 4.615385 | 0.615385 | 0.116667 | 0.133333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.013333 | 0.085366 | 164 | 9 | 40 | 18.222222 | 0.786667 | 0 | 0 | 0 | 0 | 0 | 0.170732 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3e41e59b0b53b9277fbe930b9694df6f8e1bdec4 | 508 | py | Python | scripts/demo_client.py | ogoodman/icegrid-starter | 3babe028ce8e896eb804e55b4c358d6e37e2a628 | [
"MIT"
] | null | null | null | scripts/demo_client.py | ogoodman/icegrid-starter | 3babe028ce8e896eb804e55b4c358d6e37e2a628 | [
"MIT"
] | null | null | null | scripts/demo_client.py | ogoodman/icegrid-starter | 3babe028ce8e896eb804e55b4c358d6e37e2a628 | [
"MIT"
] | 1 | 2022-03-09T12:56:10.000Z | 2022-03-09T12:56:10.000Z | import atexit
import sys
import Ice
import icegrid_config
from iceapp import idemo
ic = Ice.initialize(sys.argv)
atexit.register(ic.destroy)
reg_proxy = ic.stringToProxy('IceGrid/Locator:tcp -h %s -p 4061' % icegrid_config.ICE_REG_HOST)
registry = Ice.LocatorPrx.uncheckedCast(reg_proxy)
ic.setDefaultLocator(registry)
printer = idemo.PrinterPrx.uncheckedCast(ic.stringToProxy('printer@Printer-node1.Printer'))
printer.printString('Hello!')
n = 42
nn = printer.addOne(n)
print '%s + 1 = %s' % (n, nn)
| 22.086957 | 95 | 0.765748 | 72 | 508 | 5.319444 | 0.541667 | 0.067885 | 0.052219 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.01766 | 0.108268 | 508 | 22 | 96 | 23.090909 | 0.827815 | 0 | 0 | 0 | 0 | 0 | 0.155819 | 0.057199 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.333333 | null | null | 0.266667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
3e50d63c5caa5196cb9fe8dbe41c4b058f6853ee | 2,655 | py | Python | atlastk/__main__.py | splashelec/atlas-python | e6ced65dd10bb28a3857b2addcd0af7cc661a967 | [
"MIT"
] | 221 | 2019-04-08T16:58:19.000Z | 2022-03-11T22:08:56.000Z | atlastk/__main__.py | splashelec/atlas-python | e6ced65dd10bb28a3857b2addcd0af7cc661a967 | [
"MIT"
] | 5 | 2019-06-19T07:03:06.000Z | 2022-01-06T07:21:01.000Z | atlastk/__main__.py | splashelec/atlas-python | e6ced65dd10bb28a3857b2addcd0af7cc661a967 | [
"MIT"
] | 27 | 2019-05-25T14:58:28.000Z | 2022-03-03T01:16:43.000Z | """
MIT License
Copyright (c) 2018 Claude SIMON (https://q37.info/s/rmnmqd49)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# For 'python3 -m atlastk' to work.
from Atlas import *
if __name__ == "__main__":
HEAD = """
<title>"Hello, World !" example</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAMFBMVEUEAvyEhsxERuS8urQsKuycnsRkYtzc2qwUFvRUVtysrrx0ctTs6qTMyrSUksQ0NuyciPBdAAABHklEQVR42mNgwAa8zlxjDd2A4POfOXPmzZkFCAH2M8fNzyALzDlzg2ENssCbMwkMOsgCa858YOjBKxBzRoHhD7LAHiBH5swCT9HQ6A9ggZ4zp7YCrV0DdM6pBpAAG5Blc2aBDZA68wCsZPuZU0BDH07xvHOmAGKKvgMP2NA/Zw7ADIYJXGDgLQeBBSCBFu0aoAPYQUadMQAJAE29zwAVWMCWpgB08ZnDQGsbGhpsgCqBQHNfzRkDEIPlzFmo0T5nzoMovjPHoAK8Zw5BnA5yDosDSAVYQOYMKIDZzkoDzagAsjhqzjRAfXTmzAQgi/vMQZA6pjtAvhEk0E+ATWRRm6YBZuScCUCNN5szH1D4TGdOoSrggtiNAH3vBBjwAQCglIrSZkf1MQAAAABJRU5ErkJggg==" />
"""
BODY = """
<fieldset>
<input id="input" maxlength="20" placeholder="Enter a name here" type="text"
xdh:onevent="Submit" value="World"/>
<div style="display: flex; justify-content: space-around; margin: 5px auto auto auto;">
<button xdh:onevent="Submit">Submit</button>
<button xdh:onevent="Clear">Clear</button>
</div>
</fieldset>
"""
def ac_connect(dom):
dom.inner("", BODY )
dom.focus( "input")
def ac_submit(dom):
dom.alert("Hello, {}!".format(dom.get_value("input")))
dom.focus( "input")
def ac_clear(dom):
if dom.confirm("Are you sure?"):
dom.set_value("input", "" )
dom.focus( "input")
callbacks = {
"": ac_connect,
"Submit": ac_submit,
"Clear": ac_clear,
}
launch(callbacks, None, HEAD) | 40.846154 | 608 | 0.763465 | 309 | 2,655 | 6.508091 | 0.559871 | 0.043759 | 0.019393 | 0.015912 | 0.034311 | 0 | 0 | 0 | 0 | 0 | 0 | 0.029903 | 0.143503 | 2,655 | 65 | 609 | 40.846154 | 0.854442 | 0.426742 | 0 | 0.15625 | 0 | 0.09375 | 0.712021 | 0.422061 | 0 | 0 | 0 | 0 | 0 | 1 | 0.09375 | false | 0 | 0.03125 | 0 | 0.125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3e5441bbb1a6d66c791d5736df102678416e17e5 | 131 | py | Python | Boolean/Boolean27.py | liyuanyuan11/Python | d94cc7ab39e56c6e24bfc741a30da77590d1d220 | [
"MIT"
] | null | null | null | Boolean/Boolean27.py | liyuanyuan11/Python | d94cc7ab39e56c6e24bfc741a30da77590d1d220 | [
"MIT"
] | null | null | null | Boolean/Boolean27.py | liyuanyuan11/Python | d94cc7ab39e56c6e24bfc741a30da77590d1d220 | [
"MIT"
] | null | null | null | isWeekend=False
isAfterSchool=True
isFinishHomework=True
print(isWeekend or (not isWeekend and isAfterSchool and isFinishHomework)) | 32.75 | 74 | 0.870229 | 15 | 131 | 7.6 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.076336 | 131 | 4 | 74 | 32.75 | 0.942149 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3e55faa97fffa2b7cf246107038d7a860ecef4ff | 821 | py | Python | python_developer_tools/cv/utils/PIL_utils.py | carlsummer/python_developer_tools | a8c4365b7cc601cda55648cdfd8c0cb1faae132f | [
"Apache-2.0"
] | 32 | 2021-06-21T04:49:48.000Z | 2022-03-29T05:46:59.000Z | python_developer_tools/cv/utils/PIL_utils.py | HonestyBrave/python_developer_tools | fc0dcf5c4ef088e2e535206dc82f09bbfd01f280 | [
"Apache-2.0"
] | 1 | 2021-11-12T03:45:55.000Z | 2021-11-12T03:45:55.000Z | python_developer_tools/cv/utils/PIL_utils.py | HonestyBrave/python_developer_tools | fc0dcf5c4ef088e2e535206dc82f09bbfd01f280 | [
"Apache-2.0"
] | 10 | 2021-06-03T08:05:05.000Z | 2021-12-13T03:10:42.000Z | # !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:4/30/2021 2:04 PM
# @File:PIL_utils
import cv2
import numpy as np
import numpy
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
from PIL import Image, ImageOps
def PIL2cv2(image):
"""PIL่ฝฌcv"""
return cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
# ็จไบ็ปๅพ็ๆทปๅ ไธญๆๅญ็ฌฆ
if (isinstance(img, numpy.ndarray)): # ๅคๆญๆฏๅฆไธบOpenCVๅพ็็ฑปๅ
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("font/simhei.ttf", textSize, encoding="utf-8")
draw.text((left, top), text, textColor, font=fontText)
return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
| 31.576923 | 80 | 0.711328 | 116 | 821 | 4.991379 | 0.560345 | 0.056995 | 0.044905 | 0.062176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.044604 | 0.153471 | 821 | 25 | 81 | 32.84 | 0.788489 | 0.169306 | 0 | 0 | 0 | 0 | 0.029895 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.133333 | false | 0 | 0.4 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
3e5cb9af61c21639caf2af92ae4472cf6468c049 | 4,771 | py | Python | vertex/address.py | twisted/vertex | feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca | [
"MIT"
] | 56 | 2015-01-09T03:52:07.000Z | 2021-09-26T22:17:06.000Z | vertex/address.py | DalavanCloud/vertex | feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca | [
"MIT"
] | 34 | 2015-03-05T02:57:48.000Z | 2017-05-23T22:34:13.000Z | vertex/address.py | DalavanCloud/vertex | feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca | [
"MIT"
] | 17 | 2015-04-17T02:03:16.000Z | 2021-11-12T03:31:07.000Z | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from functools import total_ordering
@total_ordering
class Q2QAddress(object):
def __init__(self, domain, resource=None):
self.resource = resource
self.domain = domain
def domainAddress(self):
"""
Return an Address object which is the same as this one with ONLY
the 'domain' attribute set, not 'resource'.
May return 'self' if 'resource' is already None.
@return:
"""
if self.resource is None:
return self
else:
return Q2QAddress(self.domain)
def claimedAsIssuerOf(self, cert):
"""
Check if the information in a provided certificate *CLAIMS* to be
issued by this address.
PLEASE NOTE THAT THIS METHOD IS IN NO WAY AUTHORITATIVE. It does not
perform any cryptographic checks.
Currently this check is if L{Q2QAddress.__str__}C{(self)} is equivalent
to the commonName on the certificate's issuer.
@param cert:
@return:
"""
return cert.getIssuer().commonName == str(self)
def claimedAsSubjectOf(self, cert):
"""
Check if the information in a provided certificate *CLAIMS* to be
provided for use by this address.
PLEASE NOTE THAT THIS METHOD IS IN NO WAY AUTHORITATIVE. It does not
perform any cryptographic checks.
Currently this check is if L{Q2QAddress.__str__}C{(self)} is equivalent
to the commonName on the certificate's subject.
@param cert:
@return:
"""
return cert.getSubject().commonName == str(self)
def _tupleme(self):
"""
L{Q2QAddress}es sort by domain, then by resource.
"""
return (self.domain, self.resource)
def __lt__(self, other):
"""
Is this less than something?
@param other: the thing that this is maybe less than
@type other: maybe L{Q2QAddress}? who knows
@return: L{True} or L{False}
"""
if not isinstance(other, Q2QAddress):
return NotImplemented
return (self._tupleme() < other._tupleme())
def __eq__(self, other):
"""
Is this equal to something?
@param other: the thing that this is maybe equal to
@type other: maybe L{Q2QAddress}? who knows
@return: L{True} or L{False}
"""
if not isinstance(other, Q2QAddress):
return NotImplemented
return (self._tupleme() == other._tupleme())
def __iter__(self):
return iter((self.resource, self.domain))
def __str__(self):
"""
Return a string of the normalized form of this address. e.g.::
glyph@divmod.com # for a user
divmod.com # for a domain
"""
if self.resource:
resource = self.resource + '@'
else:
resource = ''
return (resource + self.domain).encode('utf-8')
def __repr__(self):
return '<Q2Q at %s>' % self.__str__()
def __hash__(self):
return hash(str(self))
def fromString(cls, string):
args = string.split("@", 1)
args.reverse()
return cls(*args)
fromString = classmethod(fromString)
class VirtualTransportAddress:
def __init__(self, underlying):
self.underlying = underlying
def __repr__(self):
return 'VirtualTransportAddress(%r)' % (self.underlying,)
class Q2QTransportAddress:
"""
The return value of getPeer() and getHost() for Q2Q-enabled transports.
Passed to buildProtocol of factories passed to listenQ2Q.
@ivar underlying: The return value of the underlying transport's getPeer()
or getHost(); an address which indicates the path which the bytes carrying
Q2Q traffic are travelling over. It is tempting to think of this as a
'physical' layer but that it not necessarily accurate; there are
potentially multiple layers of wrapping on any Q2Q transport, as an SSL
transport may be tunnelled over a UDP NAT-traversal layer. Implements
C{IAddress} from Twisted, for all the good that will do you.
@ivar logical: a L{Q2QAddress}, The logical peer; the user ostensibly
listening to data on the other end of this transport.
@ivar protocol: a L{str}, the name of the protocol that is connected.
"""
def __init__(self, underlying, logical, protocol):
self.underlying = underlying
self.logical = logical
self.protocol = protocol
def __repr__(self):
return 'Q2QTransportAddress(%r, %r, %r)' % (
self.underlying,
self.logical,
self.protocol)
| 27.738372 | 79 | 0.619786 | 576 | 4,771 | 5.024306 | 0.322917 | 0.024188 | 0.011403 | 0.017623 | 0.306842 | 0.289565 | 0.289565 | 0.289565 | 0.289565 | 0.260539 | 0 | 0.005656 | 0.295955 | 4,771 | 171 | 80 | 27.900585 | 0.85591 | 0.47118 | 0 | 0.192982 | 0 | 0 | 0.036173 | 0.023798 | 0 | 0 | 0 | 0 | 0 | 1 | 0.280702 | false | 0 | 0.017544 | 0.087719 | 0.649123 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
3e7e3fe5db1bc80f0933213c4c0534bb91c3225c | 1,782 | py | Python | usuals.py | eduardodsn/covid-19-tracker-brasil | d449b0e4908469d661cf8a16934738f1b1200c04 | [
"MIT"
] | null | null | null | usuals.py | eduardodsn/covid-19-tracker-brasil | d449b0e4908469d661cf8a16934738f1b1200c04 | [
"MIT"
] | null | null | null | usuals.py | eduardodsn/covid-19-tracker-brasil | d449b0e4908469d661cf8a16934738f1b1200c04 | [
"MIT"
] | null | null | null | import requests
from bs4 import BeautifulSoup
class UsualFunctions():
def __init__(self):
self.page = requests.get('https://www.worldometers.info/coronavirus/country/brazil/')
self.soup = BeautifulSoup(self.page.content, 'html.parser')
self.main_info = self.soup.find_all(class_='maincounter-number') # total, deaths, recovered
self.active_info = self.soup.find(class_='number-table-main') # active cases
self.active_conditions = self.soup.find_all(class_='number-table') # condition of active cases
# get total of cases from main info
def get_cases(self):
cases = self.main_info[0].span.text
cases = self.format_string(cases)
return cases
# get total of recovered from main info
def get_recovered(self):
recovered = self.main_info[2].span.text
recovered = self.format_string(recovered)
return recovered
# get total of deaths from main info
def get_deaths(self):
deaths = self.main_info[1].span.text
deaths = self.format_string(deaths)
return deaths
# get total of active cases from active info
def get_active_cases(self):
active = self.active_info.text
active = self.format_string(active)
return active
# get total of mild conditions
def get_mild_conditions(self):
mild = self.active_conditions[0].text
mild = self.format_string(mild)
return mild
# get total of serious or critical conditions
def get_serious_conditions(self):
serious = self.active_conditions[1].text
serious = self.format_string(serious)
return serious
# format strings
def format_string(self, string):
return string.replace(',', '.') | 31.263158 | 102 | 0.666667 | 227 | 1,782 | 5.0837 | 0.22467 | 0.048527 | 0.051993 | 0.038995 | 0.081456 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004444 | 0.242424 | 1,782 | 57 | 103 | 31.263158 | 0.85037 | 0.168911 | 0 | 0 | 0 | 0 | 0.079538 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.228571 | false | 0 | 0.057143 | 0.028571 | 0.514286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
3e912ff23879be387859ea9f11ef80a93dbe5536 | 346 | py | Python | tests/conftest.py | DewMaple/toolkit | a1f04d1b53420c64e15f684c83acb54276031346 | [
"BSD-3-Clause"
] | null | null | null | tests/conftest.py | DewMaple/toolkit | a1f04d1b53420c64e15f684c83acb54276031346 | [
"BSD-3-Clause"
] | null | null | null | tests/conftest.py | DewMaple/toolkit | a1f04d1b53420c64e15f684c83acb54276031346 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import errno
import pytest
try:
__import__("pytest_xprocess")
from xprocess import ProcessStarter
except ImportError:
@pytest.fixture(scope="session")
def xprocess():
pytest.skip("pytest-xprocess not installed.")
@pytest.fixture
def db_url():
return "mysql://root@localhost:3306/lms_test"
| 18.210526 | 53 | 0.693642 | 41 | 346 | 5.682927 | 0.682927 | 0.103004 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.017544 | 0.176301 | 346 | 18 | 54 | 19.222222 | 0.8 | 0.060694 | 0 | 0 | 0 | 0 | 0.272446 | 0.111455 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | true | 0 | 0.416667 | 0.083333 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
e4257bcebfcfa2201edb018bc1ab4335ee10e023 | 551 | py | Python | osoriweb/website/board/forms.py | HyOsori/Osori-Website | 57a2e62f320e5eac15c73416962b5b6cf049250f | [
"MIT"
] | 15 | 2017-04-01T06:17:56.000Z | 2018-01-13T13:26:01.000Z | osoriweb/website/board/forms.py | HyOsori/Osori-Website | 57a2e62f320e5eac15c73416962b5b6cf049250f | [
"MIT"
] | 7 | 2019-08-22T07:24:30.000Z | 2022-03-11T23:14:38.000Z | osoriweb/website/board/forms.py | HyOsori/Osori-Website | 57a2e62f320e5eac15c73416962b5b6cf049250f | [
"MIT"
] | 3 | 2017-08-25T14:02:28.000Z | 2017-09-01T04:18:52.000Z | from django import forms
from .models import Article
from .models import BoardType
from django_summernote.widgets import SummernoteWidget
# ๊ฒ์๊ธ ํผ
class ArticleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix','')
super(ArticleForm,self).__init__(*args,**kwargs)
class Meta:
model = Article
fields = ('title', 'text',) # ์ ๋ชฉ๊ณผ ๋ด์ฉ์ ์
๋ ฅ ๊ฐ๋ฅํ๋๋ก ์ค์
title = forms.CharField(required=True, label="์ ๋ชฉ")
text = forms.CharField(widget=SummernoteWidget, label="๋ด์ฉ")
| 23.956522 | 63 | 0.689655 | 65 | 551 | 5.692308 | 0.615385 | 0.054054 | 0.086486 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.194192 | 551 | 22 | 64 | 25.045455 | 0.833333 | 0.045372 | 0 | 0 | 0 | 0 | 0.047985 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0.307692 | 0 | 0.692308 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
e42951f67727ccd6e72e3288985c64a860ccc3dd | 8,276 | py | Python | oldp/apps/references/models.py | docsuleman/oldp | 8dcaa8e6e435794c872346b5014945ace885adb4 | [
"MIT"
] | 66 | 2018-05-07T12:34:39.000Z | 2022-02-23T20:14:24.000Z | oldp/apps/references/models.py | Justice-PLP-DHV/oldp | eadf235bb0925453d9a5b81963a0ce53afeb17fd | [
"MIT"
] | 68 | 2018-06-11T16:13:17.000Z | 2022-02-10T08:03:26.000Z | oldp/apps/references/models.py | Justice-PLP-DHV/oldp | eadf235bb0925453d9a5b81963a0ce53afeb17fd | [
"MIT"
] | 15 | 2018-06-23T19:41:13.000Z | 2021-08-18T08:21:49.000Z | import hashlib
import logging
import re
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.urls import reverse
from oldp.apps.cases.models import Case
from oldp.apps.laws.models import Law
from oldp.apps.lib.markers import BaseMarker
from oldp.apps.search.templatetags.search import search_url
logger = logging.getLogger(__name__)
class Reference(models.Model):
"""
A reference connecting two content objects (1:1 relation). The object that is referenced is either "law", "case"
or ... (reference target). The referencing object (the object which text contains the reference) can be derived
via marker.
Depending on the referencing object (its marker) the corresponding implementation is used.
If the referenced object is not defined, the reference is "not assigned" (is_assigned method)
"""
law = models.ForeignKey(Law, null=True, blank=True, on_delete=models.SET_NULL)
case = models.ForeignKey(Case, null=True, blank=True, on_delete=models.SET_NULL)
to = models.CharField(max_length=250) # to as string, if case or law cannot be assigned (ref id)
to_hash = models.CharField(max_length=100, null=True)
count = None
class Meta:
pass
def get_marker(self):
"""Reverse m2m-field look up"""
marker = self.casereferencemarker_set.first()
if marker is None:
marker = self.lawreferencemarker_set.first()
return marker
def get_admin_url(self):
return reverse('admin:references_reference_change', args=(self.pk, ))
def get_absolute_url(self):
"""
Returns Url to law or case item (if exist) otherwise return search Url.
:return:
"""
if self.law is not None:
return self.law.get_absolute_url()
elif self.case is not None:
return self.case.get_absolute_url()
else:
return search_url(self.get_marker().text)
def get_target(self):
if self.has_law_target():
return self.law
elif self.has_case_target():
return self.case
else:
return None
def has_law_target(self):
return self.law is not None
def has_case_target(self):
return self.case is not None
def get_title(self):
# TODO handle unassigned refs
if self.has_law_target():
return self.law.get_title()
elif self.has_case_target():
return self.case.get_title()
else:
return self.to # TODO
# to = json.loads(self.to)
# to['sect'] = str(to['sect'])
#
# if to['type'] == 'law' and 'book' in to and 'sect' in to:
# print(to)
# if to['book'] == 'gg':
# sect_prefix = 'Art.'
# elif 'anlage' in to['sect']:
# sect_prefix = ''
# else:
# sect_prefix = 'ยง'
# to['sect'] = to['sect'].replace('anlage-', 'Anlage ')
# return sect_prefix + ' ' + to['sect'] + ' ' + to['book'].upper()
# else:
# return self.get_marker().text
def is_assigned(self):
return self.has_law_target() or self.has_case_target()
def set_to_hash(self):
"""
Generate a unique hash for this reference (used for grouping)
"""
m = hashlib.md5()
if self.has_law_target():
hash_this = 'law/%i' % self.law_id
elif self.has_case_target():
hash_this = 'case/%i' % self.case_id
else:
hash_this = 'unassigend/' + self.to
m.update(hash_this.encode('utf-8'))
self.to_hash = m.hexdigest()
def __repr__(self):
return self.__str__()
def __str__(self):
if self.count:
return '<Reference(count=%i, to=%s, hash=%s)>' % (self.count, self.to, self.to_hash)
else:
# return self.__dict__
return '<Reference(%s, target=%s)>' % (self.to, self.get_target())
class ReferenceMarker(models.Model, BaseMarker):
"""
Abstract class for reference markers, i.e. the actual reference within a text "ยงยง 12-14 BGB".
Marker has a position (start, end, line), text of the marker as in
the text, list of references (can be law, case, ...). Implementations of abstract class (LawReferenceMarker, ...)
have the corresponding source object (LawReferenceMarker: referenced_by = a law object).
"""
text = models.CharField(
max_length=250,
help_text='Text that represents the marker (e.g. ยง 123 ABC)'
)
# uuid = models.CharField(max_length=36) # Deprecated
start = models.IntegerField(
default=0,
help_text='Position of marker'
)
end = models.IntegerField(
default=0,
help_text='Position of marker',
)
line_number = models.IntegerField(
default=0,
help_text='Number of line, i.e. paragraph, in which marker occurs (0=not set)'
)
referenced_by = None
referenced_by_type = None
references = None
class Meta:
abstract = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO Handle ids with signals?
def get_referenced_by(self):
raise NotImplementedError()
def get_start_position(self):
return self.start
def get_end_position(self):
return self.end
def get_marker_open_format(self):
return '<a href="#refs" onclick="clickRefMarker(this);" data-marker-id="{id}" class="ref">'
def get_marker_close_format(self):
return '</a>'
def __repr__(self):
return self.__str__()
def __str__(self):
return 'RefMarker(ids=%s, line=%s, pos=%i-%i, by=%s)' % ('self.ids', self.line, self.start, self.end, self.referenced_by)
@staticmethod
def remove_markers(value):
return re.sub(r'\[ref=([-a-z0-9]+)\](.*?)\[\/ref\]', r'\2', value)
@staticmethod
def make_markers_clickable(value):
"""
TODO Replace ref marker number with db id
"""
return re.sub(r'\[ref=([-a-z0-9]+)\](.*?)\[\/ref\]', r'<a href="#refs" onclick="clickRefMarker(this);" data-marker-id="\1" class="ref">\2</a>', value)
class LawReferenceMarker(ReferenceMarker):
"""
A reference marker in a law content object.
"""
referenced_by_type = Law
referenced_by = models.ForeignKey(Law, on_delete=models.CASCADE)
references = models.ManyToManyField(Reference, through='ReferenceFromLaw')
def get_referenced_by(self) -> Law:
return self.referenced_by
class CaseReferenceMarker(ReferenceMarker):
"""
A reference marker in a case content object.
"""
referenced_by_type = Case
referenced_by = models.ForeignKey(Case, on_delete=models.CASCADE)
references = models.ManyToManyField(Reference, through='ReferenceFromCase')
def get_referenced_by(self) -> Case:
return self.referenced_by
@receiver(pre_delete, sender=LawReferenceMarker)
@receiver(pre_delete, sender=CaseReferenceMarker)
def pre_delete_reference_marker(sender, instance: ReferenceMarker, *args, **kwargs):
# Delete all corresponding references
Reference.objects.filter(pk__in=instance.references.all()).delete()
class ReferenceFromContent(models.Model):
"""
Helper class for using `select_related` on ManyToManyField
Table exist already from ManyToManyField, run migration with:
./manage.py migrate --fake references 0007_fake_helper_tables_for_m2m
"""
reference = models.ForeignKey(Reference, on_delete=models.CASCADE)
marker = None
class Meta:
abstract = True
class ReferenceFromCase(ReferenceFromContent):
marker = models.ForeignKey(CaseReferenceMarker, on_delete=models.CASCADE, db_column='casereferencemarker_id')
class Meta:
db_table = 'references_casereferencemarker_references'
class ReferenceFromLaw(ReferenceFromContent):
marker = models.ForeignKey(LawReferenceMarker, on_delete=models.CASCADE, db_column='lawreferencemarker_id')
class Meta:
db_table = 'references_lawreferencemarker_references'
| 30.996255 | 158 | 0.637869 | 1,026 | 8,276 | 4.980507 | 0.229045 | 0.035225 | 0.019178 | 0.020548 | 0.24638 | 0.169472 | 0.127202 | 0.127202 | 0.10137 | 0.009002 | 0 | 0.006281 | 0.249758 | 8,276 | 266 | 159 | 31.112782 | 0.816073 | 0.236709 | 0 | 0.215278 | 0 | 0.013889 | 0.119153 | 0.05055 | 0 | 0 | 0 | 0.011278 | 0 | 1 | 0.166667 | false | 0.006944 | 0.076389 | 0.097222 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
e42ff4dbd6eb75d3772ea6d8052f7d8d05171cc0 | 573 | py | Python | fv3config/config/__init__.py | VulcanClimateModeling/fv3config | 544eaf1bc6f1c4617cd8ee6bd3298136ed180f4c | [
"BSD-2-Clause"
] | 2 | 2019-11-12T21:05:09.000Z | 2019-11-17T18:08:34.000Z | fv3config/config/__init__.py | VulcanClimateModeling/fv3config | 544eaf1bc6f1c4617cd8ee6bd3298136ed180f4c | [
"BSD-2-Clause"
] | 77 | 2019-11-12T21:15:38.000Z | 2021-05-07T22:39:36.000Z | fv3config/config/__init__.py | VulcanClimateModeling/fv3config | 544eaf1bc6f1c4617cd8ee6bd3298136ed180f4c | [
"BSD-2-Clause"
] | null | null | null | from .namelist import (
config_to_namelist,
config_from_namelist,
)
from .rundir import write_run_directory
from .alter import enable_restart, set_run_duration
from .derive import get_n_processes, get_run_duration, get_timestep
from .nudging import get_nudging_assets, enable_nudging
from .diag_table import (
DiagFileConfig,
DiagFieldConfig,
DiagTable,
Packing,
FileFormat,
)
from ._serialization import load, dump
def get_default_config():
"""Removed, do not use."""
raise NotImplementedError("get_default_config has been removed")
| 24.913043 | 68 | 0.773124 | 72 | 573 | 5.833333 | 0.569444 | 0.057143 | 0.07619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.160558 | 573 | 22 | 69 | 26.045455 | 0.873181 | 0.034904 | 0 | 0 | 0 | 0 | 0.063985 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.055556 | true | 0 | 0.388889 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
e44b77a3dd8929f05dd5ecc7851517a261576224 | 2,311 | py | Python | spi.py | hurasum/esp32_python | 59302ea48c3e1e0190fed09f78bb18d5f49b9c71 | [
"Unlicense"
] | null | null | null | spi.py | hurasum/esp32_python | 59302ea48c3e1e0190fed09f78bb18d5f49b9c71 | [
"Unlicense"
] | 1 | 2021-12-14T09:34:25.000Z | 2021-12-20T13:41:03.000Z | spi.py | hurasum/esp32_python | 59302ea48c3e1e0190fed09f78bb18d5f49b9c71 | [
"Unlicense"
] | null | null | null | """
SPI typing class
This class includes full support for using ESP32 SPI peripheral in master mode
Only SPI master mode is supported for now.
Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode).
If the requested spihost is VSPI and the psRAM is used at 80 MHz, the exception will be raised.
The exception will be raised if SPI cannot be configured for given configurations.
"""
class SPI:
def deinit(self):
"""
Deinitialize the SPI object, free all used resources.
"""
pass
def read(self, len, val):
"""
Read len bytes from SPI device.
Returns the string of read bytes.
If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used).
"""
pass
def readinto(self, buf, val):
"""
Read bytes from SPI device into buffer object buf. Length of buf bytes are read.
If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used).
"""
pass
def readfrom_mem(self, address, length, addrlen):
"""
Writes address to the spi device and reads length bytes.
The number of the address bytes to write is determined from the address value (1 byte for 0-255, 2 bytes for 256-65535, ...).
The number of address bytes to be written can also be set by the optional argument addrlen (1-4).
Returns the string of read bytes.
"""
pass
def write(self, buf):
"""
Write bytes from buffer object buf to the SPI device.
Returns True on success, False ion error
"""
pass
def write_readinto(self, wr_buf, rd_buf):
"""
Write bytes from buffer object wr_buf to the SPI device and reads from SPI device into buffer object rd_buf.
The lenghts of wr_buf and rd_buf can be different.
In fullduplex mode write and read are simultaneous. In halfduplex mode the data are first written to the device, then read from it.
Returns True on success, False ion error
"""
pass
def select(self):
"""
Activates the CS pin if it was configured when the spi object was created.
"""
pass
| 31.657534 | 139 | 0.645608 | 344 | 2,311 | 4.313953 | 0.351744 | 0.028302 | 0.02628 | 0.028302 | 0.390836 | 0.314016 | 0.169811 | 0.169811 | 0.169811 | 0.115903 | 0 | 0.012361 | 0.29987 | 2,311 | 72 | 140 | 32.097222 | 0.904821 | 0.712678 | 0 | 0.466667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.466667 | false | 0.466667 | 0 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
e4646c76defe0292be4e4ba737853a6d93aaffda | 17,829 | py | Python | advbench/hparams_registry.py | constrainedlearning/advbench | 68f9f6d77268aad45517ca84d383b996724cc976 | [
"MIT"
] | null | null | null | advbench/hparams_registry.py | constrainedlearning/advbench | 68f9f6d77268aad45517ca84d383b996724cc976 | [
"MIT"
] | null | null | null | advbench/hparams_registry.py | constrainedlearning/advbench | 68f9f6d77268aad45517ca84d383b996724cc976 | [
"MIT"
] | null | null | null | import numpy as np
from advbench.lib import misc
from advbench import datasets
def default_hparams(algorithm, perturbation, dataset):
return {a: b for a, (b, c) in _hparams(algorithm, perturbation, dataset, 0).items()}
def random_hparams(algorithm, perturbation, dataset, seed):
return {a: c for a, (b, c) in _hparams(algorithm, perturbation, dataset, seed).items()}
def _hparams(algorithm: str, perturbation:str, dataset: str, random_seed: int):
"""Global registry of hyperparams. Each entry is a (default, random) tuple.
New algorithms / networks / etc. should add entries here.
"""
hparams = {}
def _hparam(name, default_val, random_val_fn):
"""Define a hyperparameter. random_val_fn takes a RandomState and
returns a random hyperparameter value."""
assert(name not in hparams)
random_state = np.random.RandomState(misc.seed_hash(random_seed, name))
hparams[name] = (default_val, random_val_fn(random_state))
# Unconditional hparam definitions.
if dataset == 'IMNET':
_hparam('batch_size', 64, lambda r: int(2 ** r.uniform(3, 8)))
elif dataset == 'modelnet40':
_hparam('batch_size', 32, lambda r: int(2 ** r.uniform(3, 6)))
else:
_hparam('batch_size', 128, lambda r: int(2 ** r.uniform(3, 8)))
_hparam('augmentation_prob', 0.5, lambda r: 0.5)
_hparam('perturbation_batch_size', 10, lambda r: 10)
_hparam('mh_dale_scale', 0.05, lambda r: 0.05)
_hparam('mh_proposal', 'Laplace', lambda r: 'Laplace')
_hparam('gaussian_attack_std', 1, lambda r: 1 )
_hparam('laplacian_attack_std', 1, lambda r: 1 )
_hparam('adv_penalty', 1, lambda r: 1)
if dataset == 'IMNET':
_hparam('label_smoothing', 0.1, lambda r: 0.1 )
else:
_hparam('label_smoothing', 0.0, lambda r: 0.0)
# optimization
if dataset == 'MNIST':
_hparam('learning_rate', 0.01, lambda r: 10 ** r.uniform(-1.5, -0.5))
_hparam('lr_decay_start', 15, lambda r: 15)
_hparam('lr_decay_factor', 0.8, lambda r: r.uniform(0.1, 0.3))
_hparam('lr_decay_epoch', 1, lambda r: 1)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('learning_rate', 0.1, lambda r: 10 ** r.uniform(-2, -1))
if dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('lr_decay_start', 0, lambda r: 0)
_hparam('lr_decay_factor', 0.2, lambda r: r.uniform(0.1, 0.3))
_hparam('lr_decay_epoch', 60, lambda r: 60)
if dataset == 'IMNET':
_hparam('learning_rate', 0.01, lambda r: 10 ** r.uniform(-1.5, -0.5))
_hparam('lr_decay_start', 0, lambda r: 0)
_hparam('lr_decay_factor', 0.8, lambda r: r.uniform(0.1, 0.3))
_hparam('lr_decay_epoch', 1, lambda r: 1)
if dataset == 'modelnet40':
_hparam('learning_rate', 0.1, lambda r: 10 ** r.uniform(-1.5, -0.5))
_hparam('weight_decay', 1e-4, lambda r: 10 ** r.uniform(-4, -3))
else:
_hparam('weight_decay', 5e-4, lambda r: 10 ** r.uniform(-6, -3))
_hparam('sgd_momentum', 0.9, lambda r: r.uniform(0.8, 0.95))
# Wether to batch parrallelizable attacks, bigger mem footprint but faster
if dataset == 'STL10':
_hparam('batched', 0, lambda r: 0)
else:
_hparam('batched', 1, lambda r: 1)
if perturbation == 'Linf':
if dataset == 'MNIST':
_hparam('epsilon', 0.3, lambda r: 0.3)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('epsilon', 0.031, lambda r: 0.031)
elif perturbation == 'Rotation':
if dataset == 'MNIST':
_hparam('epsilon', 30, lambda r: 30)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('epsilon', 30, lambda r: 30)
# Perturbation Specific
elif perturbation == 'Rotation':
##### PGD #####
if dataset == 'MNIST':
_hparam('pgd_n_steps', 20, lambda r: 20)
_hparam('pgd_step_size', 1, lambda r: 1)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('pgd_n_steps', 20, lambda r: 20)
_hparam('pgd_step_size', 10, lambda r: 10)
# DALE (Laplacian-HMC)
if dataset == 'MNIST':
_hparam('l_dale_n_steps', 15, lambda r: 15)
_hparam('l_dale_step_size', 2, lambda r: 2)
_hparam('l_dale_noise_coeff', 1, lambda r: 10 ** r.uniform(-1.0, -1.0))
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('l_dale_n_steps', 10, lambda r: 10)
_hparam('l_dale_step_size', 0.007, lambda r: 0.007)
_hparam('l_dale_noise_coeff', 1e-2, lambda r: 1e-2)
_hparam('l_dale_nu', 0.1, lambda r: 0.1)
_hparam('l_dale_eta', 0.1, lambda r: 0.1)
# Discrete Dale
if dataset == 'MNIST':
_hparam('l_dale_n_steps', 15, lambda r: 15)
_hparam('l_dale_step_size', 2, lambda r: 2)
_hparam('l_dale_noise_coeff', 1, lambda r: 10 ** r.uniform(-1.0, -1.0))
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('l_dale_n_steps', 10, lambda r: 10)
_hparam('l_dale_step_size', 0.007, lambda r: 0.007)
_hparam('l_dale_noise_coeff', 1e-2, lambda r: 1e-2)
# DALE-PD (Gaussian-HMC)
_hparam('g_dale_pd_step_size', 2, lambda r: 2)
_hparam('g_dale_pd_eta', 0.01, lambda r: 0.01)
_hparam('g_dale_pd_margin', 1.45, lambda r: 1.45)
# DALE-PD-INV (Gaussian-HMC)
_hparam('g_dale_pd_inv_step_size', 2, lambda r: 2)
_hparam('g_dale_pd_inv_eta', 0.01, lambda r: 0.01)
_hparam('g_dale_pd_inv_margin', 0.147, lambda r: 0.147)
# Worst of K
_hparam('worst_of_k_steps', 10, lambda r: 10)
# Grid Search
_hparam('grid_size', 10, lambda r: 10)
elif perturbation=='SE':
##### Worst of K ######
_hparam('worst_of_k_steps', 30, lambda r:30)
_hparam('fo_sgd_step_size', 100, lambda r:100)
_hparam('fo_sgd_momentum', 0.1, lambda r:0.1)
_hparam('fo_adam_step_size', 0.1, lambda r:0.1)
_hparam('fo_n_steps', 30, lambda r:20)
_hparam('fo_restarts', 1, lambda r:1)
_hparam('pgd_n_steps', 30, lambda r: 30)
_hparam('pgd_step_size', 0.1, lambda r: 0.1)
# MH DALE
_hparam('mh_dale_n_steps', 30, lambda r:30)
_hparam('epsilon_rot', 30, lambda r:30)
if dataset == 'STL10':
_hparam('epsilon_tx', 10, lambda r:10)
_hparam('epsilon_ty', 10, lambda r:10)
else:
_hparam('epsilon_tx', 3, lambda r:3)
_hparam('epsilon_ty', 3, lambda r:3)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 30, lambda r: 30)
_hparam('l_dale_step_size', 0.05, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('l_dale_noise_coeff', 0.01,lambda r: 10 ** r.uniform(-3.0, -1.5))
_hparam('l_dale_nu', 0.1, lambda r: 0.1)
_hparam('l_dale_eta', 0.001, lambda r: 0.001)
# DALE-PD (Gaussian-HMC)
_hparam('g_dale_pd_step_size', 2, lambda r: 2)
_hparam('g_dale_pd_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_margin', 0.16, lambda r: 0.16)
# DALE-PD-INV (Gaussian-HMC)
_hparam('g_dale_pd_inv_step_size', 0.1, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('g_dale_pd_inv_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_inv_margin', 0.2, lambda r: 0.2)
# DALE-PD-INV (Laplacian-HMC)
if dataset == 'MNIST':
_hparam('l_dale_pd_inv_step_size', 0.05, lambda r: 0.05)
_hparam('l_dale_pd_inv_eta', 0.0008, lambda r: 0.0008)
_hparam('l_dale_pd_inv_margin', 0.07, lambda r: 0.07)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('l_dale_pd_inv_step_size', 1, lambda r: 1)
_hparam('l_dale_pd_inv_eta', 0.0001, lambda r: 0.0001)
_hparam('l_dale_pd_inv_margin', 0.3, lambda r: 0.3)
# Discrete DALE-PD-INV
_hparam('d_num_translations', 3, lambda r: 3)
_hparam('d_num_rotations', 20, lambda r: 20)
if dataset == 'MNIST':
_hparam('d_dale_pd_inv_step_size', 0.05, lambda r: 0.05)
_hparam('d_dale_pd_inv_eta', 0.0008, lambda r: 0.0008)
_hparam('d_dale_pd_inv_margin', 0.14, lambda r: 0.14)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('d_dale_pd_inv_step_size', 1, lambda r: 1)
_hparam('d_dale_pd_inv_eta', 0.00005, lambda r: 0.00005)
_hparam('d_dale_pd_inv_margin', 0.15, lambda r: 0.15)
# Grid Search
_hparam('grid_size', 120, lambda r: 120)
elif perturbation=='Translation':
##### Worst of K ######
_hparam('worst_of_k_steps', 10, lambda r:10)
if dataset == 'STL10':
_hparam('epsilon_tx', 10, lambda r:10)
_hparam('epsilon_ty', 10, lambda r:10)
else:
_hparam('epsilon_tx', 3, lambda r:3)
_hparam('epsilon_ty', 3, lambda r:3)
##### PGD #####
_hparam('pgd_n_steps', 20, lambda r: 20)
_hparam('pgd_step_size', 0.1, lambda r: 0.1)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 10, lambda r: 10)
_hparam('l_dale_step_size', 0.4, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('l_dale_noise_coeff', 0.02,lambda r: 10 ** r.uniform(-3.0, -1.5))
_hparam('l_dale_nu', 0.1, lambda r: 0.1)
_hparam('l_dale_eta', 0.001, lambda r: 0.001)
# DALE-PD (Gaussian-HMC)
_hparam('g_dale_pd_step_size', 2, lambda r: 2)
_hparam('g_dale_pd_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_margin', 0.16, lambda r: 0.16)
# DALE-PD-INV (Gaussian-HMC)
_hparam('g_dale_pd_inv_step_size', 0.4, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('g_dale_pd_inv_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_inv_margin', 0.2, lambda r: 0.2)
# DALE-PD-INV (Laplacian-HMC)
if dataset == 'MNIST':
_hparam('l_dale_pd_inv_step_size', 0.4, lambda r: 0.4)
_hparam('l_dale_pd_inv_eta', 0.0008, lambda r: 0.0008)
_hparam('l_dale_pd_inv_margin', 0.03, lambda r: 0.03)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('l_dale_pd_inv_step_size', 0.1, lambda r: 0.1)
_hparam('l_dale_pd_inv_eta', 0.00005, lambda r: 0.00005)
_hparam('l_dale_pd_inv_margin', 0.08, lambda r: 0.08)
# Discrete DALE-PD-INV
_hparam('d_num_translations', 3, lambda r: 3)
_hparam('d_num_rotations', 20, lambda r: 20)
if dataset == 'MNIST':
_hparam('d_dale_pd_inv_step_size', 0.05, lambda r: 0.05)
_hparam('d_dale_pd_inv_eta', 0.0008, lambda r: 0.0008)
_hparam('d_dale_pd_inv_margin', 0.14, lambda r: 0.14)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('d_dale_pd_inv_step_size', 0.2, lambda r: 0.2)
_hparam('d_dale_pd_inv_eta', 0.00005, lambda r: 0.00005)
_hparam('d_dale_pd_inv_margin', 0.08, lambda r: 0.08)
# Grid Search
_hparam('grid_size', 120, lambda r: 120)
elif dataset=='modelnet40':
_hparam('fo_sgd_momentum', 0.1, lambda r:0.1)
_hparam('fo_adam_step_size', 0.1, lambda r:0.1)
_hparam('fo_n_steps', 10, lambda r:10)
_hparam('fo_restarts', 1, lambda r:1)
_hparam('pgd_n_steps', 10, lambda r: 10)
_hparam('pgd_step_size', 0.1, lambda r: 0.1)
_hparam('worst_of_k_steps', 10, lambda r:10)
if perturbation == "PointcloudTranslation":
_hparam('epsilon_tx', 0.25, lambda r:0.25)
_hparam('epsilon_ty', 0.2, lambda r:0.2)
elif perturbation == "PointcloudJitter":
_hparam('epsilon', 0.05, lambda r:0.05)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 10, lambda r: 10)
_hparam('l_dale_step_size', 0.4, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('l_dale_noise_coeff', 0.02,lambda r: 10 ** r.uniform(-3.0, -1.5))
_hparam('l_dale_nu', 0.1, lambda r: 0.1)
_hparam('l_dale_eta', 0.001, lambda r: 0.001)
# DALE-PD (Gaussian-HMC)
_hparam('g_dale_pd_step_size', 2, lambda r: 2)
_hparam('g_dale_pd_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_margin', 0.16, lambda r: 0.16)
# DALE-PD-INV (Gaussian-HMC)
_hparam('g_dale_pd_inv_step_size', 0.4, lambda r: 10 ** r.uniform(-2.0, -0.5))
_hparam('g_dale_pd_inv_eta', 0.0001, lambda r: 0.0001)
_hparam('g_dale_pd_inv_margin', 0.2, lambda r: 0.2)
# DALE-PD-INV (Laplacian-HMC)
if perturbation == "PointcloudTranslation":
_hparam('l_dale_pd_inv_step_size', 0.1, lambda r: 0.1)
_hparam('l_dale_pd_inv_eta', 0.0002, lambda r: 0.0002)
_hparam('l_dale_pd_inv_margin', 0.35, lambda r: 0.35)
elif perturbation == "PointcloudJitter":
_hparam('l_dale_pd_inv_step_size', 0.4, lambda r: 0.4)
_hparam('l_dale_pd_inv_eta', 0.000025, lambda r: 0.000025)
_hparam('l_dale_pd_inv_margin', 1.4, lambda r: 1.4)
# Grid Search
_hparam('grid_size', 120, lambda r: 120)
else:
raise NotImplementedError
return hparams
def test_hparams(algorithm: str, perturbation:str, dataset: str):
hparams = {}
def _hparam(name, default_val):
"""Define a hyperparameter for test adversaries."""
assert(name not in hparams)
hparams[name] = default_val
_hparam('perturbation_batch_size', 10)
_hparam('gaussian_attack_std', 0.5)
_hparam('laplacian_attack_std', 0.5)
_hparam('fo_sgd_step_size', 10e2)
_hparam('fo_sgd_momentum', 0.5)
_hparam('fo_n_steps', 30)
_hparam('fo_restarts', 10)
_hparam('fo_adam_step_size', 0.1)
_hparam('grid_size', 100)
_hparam('worst_of_k_steps', 120)
_hparam('batched', 1)
if perturbation=='Rotation':
if dataset == 'MNIST':
_hparam('epsilon', 30)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('epsilon', 20)
##### PGD #####
if dataset == 'MNIST':
_hparam('pgd_n_steps', 10)
_hparam('pgd_step_size', 2)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('pgd_n_steps', 10)
_hparam('pgd_step_size', 2)
elif perturbation=='Translation':
_hparam('epsilon_tx', 4)
_hparam('epsilon_ty', 4)
###### MH ###########
_hparam('mh_dale_scale', 0.2)
_hparam('mh_dale_n_steps', 30)
_hparam('mh_proposal', 'Laplace')
##### PGD #####
if dataset == 'MNIST':
_hparam('pgd_n_steps', 30)
_hparam('pgd_step_size', 0.5)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('pgd_n_steps', 20)
_hparam('pgd_step_size', 0.2)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 20)
_hparam('l_dale_step_size', 0.2)
_hparam('l_dale_noise_coeff', 0.2)
_hparam('l_dale_nu', 0.1)
elif perturbation=='SE':
##### Worst of K ######
_hparam('epsilon_rot', 30)
if dataset == 'STL10':
_hparam('epsilon_tx', 10)
_hparam('epsilon_ty', 10)
else:
_hparam('epsilon_tx', 3)
_hparam('epsilon_ty', 3)
###### MH ###########
_hparam('mh_dale_scale', 0.5)
_hparam('mh_dale_n_steps', 40)
_hparam('mh_proposal', 'Laplace')
##### PGD #####
if dataset == 'MNIST':
_hparam('pgd_n_steps', 30)
_hparam('pgd_step_size', 0.3)
elif dataset == 'CIFAR10' or dataset == 'CIFAR100' or dataset == 'STL10':
_hparam('pgd_n_steps', 10)
_hparam('pgd_step_size', 0.5)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 40)
_hparam('l_dale_step_size', 0.5)
_hparam('l_dale_noise_coeff', 0.05)
_hparam('l_dale_nu', 0.1)
elif dataset=='modelnet40':
##### Worst of K ######
if perturbation == "PointcloudTranslation":
_hparam('epsilon_tx', 0.25)
_hparam('epsilon_ty', 0.2)
else:
_hparam('epsilon', 0.02)
###### MCMC ###########
if perturbation == "PointcloudTranslation":
_hparam('mcmc_dale_scale', 0.2)
else:
_hparam('mcmc_dale_scale', 0.002)
_hparam('mcmc_dale_n_steps', 10)
_hparam('mcmc_proposal', 'Laplace')
##### PGD #####
_hparam('pgd_n_steps', 20)
if perturbation == "PointcloudTranslation":
_hparam('pgd_step_size', 0.02)
else:
_hparam('pgd_step_size', 0.01)
# DALE (Laplacian-HMC)
_hparam('l_dale_n_steps', 20)
if perturbation == "PointcloudTranslation":
_hparam('l_dale_step_size', 0.1)
else:
_hparam('l_dale_step_size', 0.001)
_hparam('l_dale_pd_inv_margin', 0.35)
if perturbation == "PointcloudTranslation":
_hparam('l_dale_noise_coeff', 0.2)
else:
_hparam('l_dale_noise_coeff', 0.0002)
_hparam('l_dale_pd_inv_eta', 0.0002)
_hparam('l_dale_nu', 0.1)
else:
raise NotImplementedError
return hparams
| 41.656542 | 91 | 0.581356 | 2,603 | 17,829 | 3.676911 | 0.075682 | 0.117752 | 0.059346 | 0.032598 | 0.823111 | 0.758437 | 0.691882 | 0.636506 | 0.577474 | 0.557204 | 0 | 0.084465 | 0.268888 | 17,829 | 427 | 92 | 41.754098 | 0.649789 | 0.059902 | 0 | 0.603774 | 0 | 0 | 0.239376 | 0.031131 | 0 | 0 | 0 | 0 | 0.006289 | 1 | 0.018868 | false | 0 | 0.009434 | 0.006289 | 0.040881 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e491555fb0a883454759d0883bddf99b641508f9 | 314 | py | Python | src/cek_if_else.py | nart4hire/TBFO_Tubes | 305a4b693de6ce1ff3c0d406d4609686776e22ba | [
"CC0-1.0"
] | null | null | null | src/cek_if_else.py | nart4hire/TBFO_Tubes | 305a4b693de6ce1ff3c0d406d4609686776e22ba | [
"CC0-1.0"
] | null | null | null | src/cek_if_else.py | nart4hire/TBFO_Tubes | 305a4b693de6ce1ff3c0d406d4609686776e22ba | [
"CC0-1.0"
] | null | null | null | nama = "azmi"
umur_5_tahun_lalu = 23
print ("nama saya")
print(nama)
print("sedangkan umur saat ini adalah")
print(umur_5_tahun_lalu + 5)
if (nama == "nathan") :
print("selamat datang Nathan!")
elif (nama == "azmi") :
print("selamat datang Azmi!")
else :
print("Selamat datang pak")
print(nama)
| 19.625 | 39 | 0.659236 | 45 | 314 | 4.466667 | 0.444444 | 0.134328 | 0.268657 | 0.139303 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.019608 | 0.187898 | 314 | 15 | 40 | 20.933333 | 0.768627 | 0 | 0 | 0.153846 | 0 | 0 | 0.361022 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.615385 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
e4983d49c5a9d2cf42ec303f6334eb6ea6dbc267 | 245 | py | Python | open_analyse/settings/production.py | Jaspreet-singh-1032/open_analyse_backend | a03778898543c0fc985a95e30c8fa836ea418f75 | [
"MIT"
] | null | null | null | open_analyse/settings/production.py | Jaspreet-singh-1032/open_analyse_backend | a03778898543c0fc985a95e30c8fa836ea418f75 | [
"MIT"
] | 2 | 2022-03-19T14:08:20.000Z | 2022-03-20T13:08:55.000Z | open_analyse/settings/production.py | Jaspreet-singh-1032/open_analyse_backend | a03778898543c0fc985a95e30c8fa836ea418f75 | [
"MIT"
] | null | null | null | from .base import * # noqa
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'openanalyse.herokuapp.com']
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
CORS_ALLOWED_ORIGINS = [
'https://openanalyse.netlify.app'
]
| 27.222222 | 77 | 0.75102 | 29 | 245 | 6.206897 | 0.827586 | 0.2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.027523 | 0.110204 | 245 | 8 | 78 | 30.625 | 0.798165 | 0.016327 | 0 | 0 | 0 | 0 | 0.493724 | 0.32636 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.142857 | 0 | 0.142857 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e4bf062944f119e8e6959c4fac73cdf925be2caf | 737 | py | Python | OnlineStudy/generic/handlers/homework.py | NanRenTeam-9/MongoMicroCourse | 59053c88faf76de3592b5aa02b1425b126fe2f2d | [
"MIT"
] | 132 | 2019-07-11T01:17:09.000Z | 2022-03-28T02:49:21.000Z | OnlineStudy/generic/handlers/homework.py | liuqiao1995/onlinestudy | b8abfc7b4f2466e595be801bd9a19a509e03534e | [
"MIT"
] | 10 | 2019-07-18T06:50:45.000Z | 2022-01-29T08:31:31.000Z | OnlineStudy/generic/handlers/homework.py | liuqiao1995/onlinestudy | b8abfc7b4f2466e595be801bd9a19a509e03534e | [
"MIT"
] | 49 | 2019-07-11T00:31:26.000Z | 2022-03-05T19:25:35.000Z | from startX.serivce.v1 import StartXHandler, get_m2m_display
from django.urls import reverse
from django.utils.safestring import mark_safe
from .base_promission import PermissionHandler
class HomeworkHandler(PermissionHandler, StartXHandler):
def display_outline(self, model=None, is_header=None, *args, **kwargs):
if is_header:
return 'ไฝไธ่ฏฆๆ
'
record_url = reverse('startX:generic_homeworkdetail_list', kwargs={'homework_id': model.pk})
return mark_safe('<a target="_blank" href="%s">ไฝไธ่ฏฆๆ
</a>' % record_url)
list_display = [get_m2m_display('่ฏพ็จ', 'courses'), 'title', get_m2m_display('็ซ ่', 'chapter'), 'content',
display_outline]
search_list = ['courses__contains']
| 38.789474 | 107 | 0.710991 | 90 | 737 | 5.566667 | 0.6 | 0.035928 | 0.077844 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006547 | 0.170963 | 737 | 18 | 108 | 40.944444 | 0.813421 | 0 | 0 | 0 | 0 | 0 | 0.180461 | 0.046133 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0.307692 | 0 | 0.769231 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
e4c4bab73ca415fde49880f8099967125d7ef340 | 1,713 | py | Python | voyager/resources/exoplanet/tce.py | marwynnsomridhivej/voyager | acce4645f60bb735595e63742f8597b6cfebd99b | [
"MIT"
] | 1 | 2020-11-04T03:40:09.000Z | 2020-11-04T03:40:09.000Z | voyager/resources/exoplanet/tce.py | marwynnsomridhivej/voyager | acce4645f60bb735595e63742f8597b6cfebd99b | [
"MIT"
] | null | null | null | voyager/resources/exoplanet/tce.py | marwynnsomridhivej/voyager | acce4645f60bb735595e63742f8597b6cfebd99b | [
"MIT"
] | null | null | null | from typing import Union
_ATTRS = {
"kepid": Union[int, None],
"tce_plnt_num": Union[int, None],
"tce_rogue_flag": Union[int, None],
"tce_period": Union[float, None],
"tce_period_err": Union[float, None],
"tce_time0bk": Union[float, None],
"tce_time0bk_err": Union[float, None],
"tce_impact": Union[float, None],
"tce_impact_err": Union[float, None],
"tce_duration": Union[float, None],
"tce_duration_err": Union[float, None],
"tce_depth": Union[float, None],
"tce_depth_err": Union[float, None],
"tce_model_snr": Union[float, None],
"tce_prad": Union[float, None],
"tce_prad_err": Union[float, None],
"tce_eqt": Union[float, None],
"tce_eqt_err": Union[float, None],
"tce_insol": Union[float, None],
"tce_insol_err": Union[float, None],
"tce_steff": Union[float, None],
"tce_steff_err": Union[float, None],
"tce_slogg": Union[float, None],
"tce_slogg_err": Union[float, None],
"tce_sradius": Union[float, None],
"tce_sradius_err": Union[float, None],
}
class ThresholdCrossingEvent(object):
__slots__ = [
'_data',
]
def __init__(self, data: dict) -> None:
self._data = data
@property
def to_dict(self) -> dict:
return self._data
@classmethod
def from_dict(cls, data: dict) -> "ThresholdCrossingEvent":
return cls(data)
def _add_func(name: str):
@property
def fn(self) -> _ATTRS.get(name):
return self._data.get(name)
setattr(ThresholdCrossingEvent, name, fn)
for attr in _ATTRS:
_add_func(attr)
| 28.55 | 63 | 0.591944 | 210 | 1,713 | 4.542857 | 0.247619 | 0.183438 | 0.337526 | 0.392034 | 0.520964 | 0 | 0 | 0 | 0 | 0 | 0 | 0.001587 | 0.264448 | 1,713 | 59 | 64 | 29.033898 | 0.755556 | 0 | 0 | 0.041667 | 0 | 0 | 0.189726 | 0.012843 | 0 | 0 | 0 | 0 | 0 | 1 | 0.104167 | false | 0 | 0.020833 | 0.0625 | 0.229167 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e4cc0da74c591b67e478392b71505adc2a627735 | 438 | py | Python | StartPython/75/metaclass1.py | t2y/python-study | 52a132ea600d4696164e540d8a8f8f5fc58e097a | [
"Apache-2.0"
] | 18 | 2016-08-15T00:24:44.000Z | 2020-11-30T15:11:52.000Z | StartPython/75/metaclass1.py | t2y/python-study | 52a132ea600d4696164e540d8a8f8f5fc58e097a | [
"Apache-2.0"
] | null | null | null | StartPython/75/metaclass1.py | t2y/python-study | 52a132ea600d4696164e540d8a8f8f5fc58e097a | [
"Apache-2.0"
] | 6 | 2016-09-28T10:47:03.000Z | 2020-10-14T10:20:06.000Z |
class MyMeta(type):
def __new__(mcs, name, bases, namespace, **kwargs):
print(f'{mcs}, called __new__')
return super().__new__(mcs, name, bases, namespace)
@classmethod
def __prepare__(mcs, name, bases, **kwargs):
print(f'{mcs}, called __prepare__')
return {'๐๐๐': 'ใใ'}
class MyClass(metaclass=MyMeta):
pass
def test():
print(vars(MyClass))
if __name__ == '__main__':
test()
| 20.857143 | 59 | 0.607306 | 51 | 438 | 4.72549 | 0.509804 | 0.087137 | 0.149378 | 0.124481 | 0.373444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.230594 | 438 | 20 | 60 | 21.9 | 0.706231 | 0 | 0 | 0 | 0 | 0 | 0.135011 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.214286 | false | 0.071429 | 0 | 0 | 0.5 | 0.214286 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.